blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
5f522fb8221a2bdc5251290858bda16fcceca60e
murayama333/python2020
/01_basic/tr/src/08/set_tr4.py
133
3.796875
4
names = set() while True: name = input("Name: ") if name == "": break names.add(name) print("Names:", names)
516f66fb7ae9c1c08dd40d01cde39a00fd5dffe9
soy-sauce/cs1134
/lab9/q4b.py
893
3.609375
4
#change last and first from DoublyLinkedList import* def reverse_list_change_elements_order(lnk_lst): while not lnk_lst == None: first=lnk_lst.first_node() last=lnk_lst.last_node() first, last = lnk_lst.last_node(),lnk_lst.first_node() lnk_lst.delete_first() lnk_lst.delete_last() lnk_lst.add_last(last) lnk_lst.add_first(first) return lnk_lst lnk_lst=DoublyLinkedList() lnk_lst.add_last(1) lnk_lst.add_last(2) lnk_lst.add_last(3) lnk_lst.add_last(4) print(reverse_list_change_elements_order(lnk_lst)) #---answer def reverse(lst): firstNode=lst.header.next cursor=firstNode lst.header.next=lst.trailer.prev while cursor.data is not None: cursor.next, cursor.prev=cursor.prev, cursor.next cursor=cursor.prev firstNode.next=cursor cursor.prev=firstNode
e104f2b0289e8cfdcd672768efa680336a32afb1
SSravanthi/Python-Deep-Learning
/ICP2/Source/wordcount.py
767
3.84375
4
FILE_NAME = 'task3.txt' wordCounter = {} with open(FILE_NAME,'r') as fh: for line in fh: # Replacing punctuation characters. Making the string to lower. # The split will spit the line into a list. word_list = line.replace(',','').replace('\'','').replace('.','').lower().split() for word in word_list: # Adding the word into the wordCounter dictionary. if word not in wordCounter: wordCounter[word] = 1 else: # if the word is already in the dictionary update its count. wordCounter[word] = wordCounter[word] + 1 print('{:15}{:3}'.format('Word','Count')) print('-' * 18) # printing the words and its occurrence. for (word,occurance) in wordCounter.items(): print('{:15}{:3}'.format(word,occurance))
762d67ca2fbe6dd4181c8b8a6028436424ea0f6e
nelvinpoulose999/Pythonfiles
/LanguageFundamentals/flowcontrols/looping/reversinganumber.py
132
4.0625
4
num=int(input("enter a number")) result=" " while num!=0: digit=num%10 result+=str(digit) num=num//10 print(result)
d6c7996905f0a35a122b26f703061f9e5cf11624
tanmaymudholkar/project_euler
/1-49/twenty_seven.py
807
3.78125
4
#!/usr/bin/env python from __future__ import division, print_function from peModules.primality import is_prime def quadratic_form(a,b,n): return (n**2 + a*n + b) def get_number_of_consecutive_primes(a,b): n = 0 while (is_prime(quadratic_form(a,b,n))): n += 1 return n if __name__ == "__main__": maximum_number_of_primes = 0 product_at_maximum = 1 for a in range(-999,1000): for b in range(-999,1000): number_of_consecutive_primes = get_number_of_consecutive_primes(a,b) if (number_of_consecutive_primes > maximum_number_of_primes): maximum_number_of_primes = number_of_consecutive_primes product_at_maximum = a*b print ("Product at maximum number of consecutive primes is %i"%(product_at_maximum))
d1689df87ee4b20b1e2e0331b47e93ec6c4ac71d
bahareh-farhadi/Python-Projects
/Robots/main.py
2,015
4.34375
4
#!/bin/python3 from turtle import * from random import choice screen = Screen() screen.bgcolor('White') turtle = Turtle() turtle.penup() turtle.hideturtle() # opens the file, 'r' means 'read only' file = open('cards.txt', 'r') robots = {} #read the file's lines separately for i in file.read().splitlines(): #split the names and store them as string variables name, battery, intelligence, image = i.split(', ') #add to the dictionary robots[name] = [battery, intelligence, image] #add the shape to the screen screen.addshape(image) file.close() print('Robots: rainbow, space, bird, jet, twoheads, dog, round, brains, tv, hair, shades, yellow (or random)') #infinite loop while True: x = input('Choose a robot: ') #users can choose robots from a given list, or just let the program choose randomly if x in robots or x == 'random': if x == 'random': #randomly chooses from all the keys in the dictionary x = choice(list(robots.keys())) #print the info of the chosen robot from dictionary(print values) print(robots[x]) style = ('Verdana', 14, 'bold') turtle.clear() turtle.hideturtle() turtle.goto(0, 100) #the 3rd value in the dictionary is the robot's image turtle.shape(robots[x][2]) turtle.setheading(90) turtle.stamp() turtle.setheading(-90) turtle.forward(70) # text='Name: '+x+'\nBattery Life: '+robots[name][0]+'\nIntelligence: '+robots[name][1] text = 'Name: ' + x turtle.write(text, font=style, align='center') turtle.forward(25) text = 'Battery Life: ' + robots[x][0] turtle.write(text, font=style, align='center') turtle.forward(25) text = 'Intelligence: ' + robots[x][1] turtle.write(text, font=style, align='center') turtle.forward(25) else: print("The robot chosen does not exist")
cf46824dd7b067a02718419c4cbc4dec7c6c9f00
kongli23/Seo_spider
/5 循环语句/loop_while.py
563
3.71875
4
# -*- coding: utf-8 -*- # 循环语句 sum = 1 while sum <= 10: print('第{}遍'.format(sum)) sum +=1 # 等同于 sum = sum+1,每循环一次+1,不然会一直条件不满足死循环 # 使用 while 生成0-10的url page = 0 while True: if page >=10: break print(f'http://www.baidu.com/seo/{page}.html') page +=1 # 使用while打印 99 乘法表,正序 x = 1 while x <= 9: y = 1 while y <= x: print(f'{y}x{x}={y*x}',end='\t') y += 1 print() x += 1 # 使用while打印 99 乘法表,倒序
f7dafe1fb0816d92b685b36a8d357a66672a6a1f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/domdivakaruni/Lesson03/slicing_lab.py
1,438
4.375
4
#!/usr/bin/env python3 # Dom Divakaruni # Lesson03- slicing def exchange_first_last(input): #take in a string, touple or list and return one with the first and last items exchanged. return input[-1:] + input[1:-1] + input[:1] def every_other_item(input): #with every other item removed. return input[::2] def drop_eight_lose_half(input): #with the first 4 and the last 4 items removed, and then every other item in the remaining sequence. return input[4:-4:2] def reverse_slice(input): #with the elements reversed (just with slicing). return input[::-1] def new_order(input): third = len(input)//3 #with the last third, then first third, then the middle third in the new order. return input[-third:]+input[:third]+input[third:-third] if __name__ == "__main__": #testing the code above s = "this is a string" t = (2, 54, 13, 12, 5, 32) #assert statements assert exchange_first_last(s) == 'ghis is a strint' assert exchange_first_last(t) == (32, 54, 13, 12, 5, 2) assert every_other_item(s) == 'ti sasrn' assert every_other_item(t) == (2, 13, 5) assert drop_eight_lose_half(s) == ' sas' assert drop_eight_lose_half(t) == () assert reverse_slice(s) == 'gnirts a si siht' assert reverse_slice(t) == (32, 5, 12, 13, 54, 2) assert new_order(s) == 'tringthis is a s' assert new_order(t) == (5, 32, 2, 54, 13, 12) print("all tests passed")
2c0872c5987842a3f9ae8aab74dc70ef7bd8189a
teksasha/ChemPython
/grams:moles.py
252
3.84375
4
print "Gram to Mole conversion" print "-------------------------" givenM=raw_input("Given mass: ") atomicM=raw_input("Atomic/Molar mass: ") wanted=float(givenM)*(1/float(atomicM)) print "-------------------------" print "Result:" print wanted print " "
5458b4ef88f8628054dd979f0fd66371e0723ced
sendurr/spring-grading
/submission - lab2/set2/DUSTIN S MULLINS_3737_assignsubmission_file_Lab 2/lab2/Lab 2.py
505
3.515625
4
#1 jimmhy = (98,35,56) jones = (89,88,98) lucy = (99,90,98) print jones[2] #2 M1 = [[1,1,1],[1,1,1],[1,1,9]] M2 = [[2,2,2],[2,8,2],[2,2,2]] M3 = [M1,M2] print M3[0][2][2] print M3[1][1][1] #3 scores = {"physics":58,"math":98,"english":98} for subject in scores: print subject,scores[subject] #4 cityT = {"columbia":65,"florence":66,"beaufort":76,"bluffton":78,"hilton head":67,"greenville":58,"augusta":65,"charlotte":76,"clemson":52,"myrtle beach":58} for temps in cityT: print temps,cityT[temps]
68e7f665a224b1018ca11c6b16446c638774a722
kartikeya-shandilya/project-euler
/python/51_2.py
716
3.625
4
from math import sqrt def isPrime (n): for i in xrange(2,int(sqrt(n))+1): if not n%i: return 0 return 1 """ for i in xrange(10**5,2*10**5-1): if isPrime(i): prSum = 0 for j in xrange(10): prSum += isPrime(int(`i`.replace('1',`j`))) if prSum >= 7: print i,prSum """ for num in [141619 ,121313 ,111857]: prSum = 0 numArr = [] for j in xrange(10): numArr.append(int(`num`.replace('1',`j`))) prSum += isPrime(int(`num`.replace('1',`j`))) print num, numArr[-1], prSum print
d328a004b80bceb77180e6f81923c64849f887e8
bosontreinamentos/python-jogos
/Jogo - Interação Textual.py
1,712
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 16:04:57 2021 @author: Fábio dos Reis """ import random import time def mostraIntro(): print('''Duas cavernas, uma à esquerda e uma à direita. Ambas possuem tesouros guardados por duendes. Escolha uma caverna para explorar''') print() def escolherCaverna(): caverna = 0 escolha = '' while escolha != 'E' and escolha != 'D': print('Escolha a caverna: E ou D') escolha = input() if (escolha == 'E'): caverna = 1 if (escolha == 'D'): caverna == 0 return caverna def verificaCaverna(caverna): print('Você está na entrada da caverna...') time.sleep(3) print('A caverna é escura e assustadora...') time.sleep(3) print('De repente, um duende surge da escuridão bem em frente a você!') print() time.sleep(2) duendeAmistoso = random.randint(0, 1) if caverna == duendeAmistoso: print('Seja bem-vindo e vamos compartilhar o tesouro!') else: print('Diga adeus invasor, vou te matar agora!') time.sleep(5) combateOuFuga() print(duendeAmistoso) def combateOuFuga(): print('Você precisa decidir o que irá fazer. Irá fugir?') print('Ou irá enfrentar o duende para tentar obter seu tesouro?\n') time.sleep(4) print('Digite F se for covarde ou L se for valente e decidir lutar!') decisao = input() if decisao == 'F': print('Fuja covarde!') if decisao == 'L': print('Saque sua espada imediatamente!') mostraIntro() caverna = escolherCaverna() verificaCaverna(caverna) print('')
c7685b365661d548b12290777489b6a4e1ee3315
Niloy28/Python-programming-exercises
/Solutions/Q76.py
292
3.96875
4
# Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. import random def generator(start=100, end=200): for i in range(start, end+1): if i % 2 == 0: yield i print(random.sample(list(generator()), k=5))
2f282295827d7a049c520db9a8b94cd484507843
Leumash/UVaOnlineJudge
/113/113.py
1,370
4.21875
4
#!/usr/bin/python ''' Power of Cryptography Background Current work in cryptography involves (among other things) large prime numbers and computing powers of numbers modulo functions of these primes. Work in this area has resulted in the practical use of results from number theory and other branches of mathematics once considered to be of only theoretical interest. This problem involves the efficient computation of integer roots of numbers. The Problem Given an integer n >= 1 and an integer p >= 1 you are to write a program that determines p ^ (1/n) , the positive nth root of p. In this problem, given such integers n and p, p will always be of the form k^n for an integer k (this integer is what your program must find). The Input The input consists of a sequence of integer pairs n and p with each integer on a line by itself. For all such pairs 1 <= n <= 200 , 1 <= p < 10^101 and there exists an integer k, 1 <= k <= 10^9 such that k^n = p . The Output For each integer pair n and p the value p^(1/n) should be printed, i.e., the number k such that k^n = p. Sample Input 2 16 3 27 7 4357186184021382204544 Sample Output 4 3 1234 ''' import sys import math def GetK(n,p): return (round(pow(p, 1/n))) try: while True: n = int(input()) p = int(input()) print (GetK(n,p)) except: pass
f46aa872c4b2e948466bd8706ce3543401a202e2
dalaAM/month-01
/day19_all/day19/exercise03.py
528
3.78125
4
""" 使用装饰器,增加打印函数执行时间的功能. """ import time def print_execute_time(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) stop_time = time.time() print("执行时间是", stop_time - start_time) return result return wrapper @print_execute_time def func01(n): sum_value = 0 for number in range(n): sum_value += number return sum_value print(func01(10)) print(func01(10000000))
bd885cd21a02386f9b270fac365734d356b5e509
anden3/Python
/dailyprogrammer/#198 - Words with Enemies.py
317
3.796875
4
def word_diff(a, b): for c in a + b: if c in a and c in b: a.remove(c) b.remove(c) return "A: " + ''.join(a) + "\nB: " + ''.join(b) + '\n' + ("Tie!" if len(a) == len(b) else ("Left Wins!" if len(a) > len(b) else "Right Wins!")) print(word_diff(list("hello"), list("below")))
54918ade2aa30ce88de8e067e12fe61634292528
sumitpatra6/leetcode_daily_challenges
/august/decode_ways.py
639
3.640625
4
def numDecodings(s): if not s or s == '0': return 0 memory = {} def util(string): if not string: return 1 if string[0] == '0': return 0 if string in memory: return memory[string] left = util(string[1:]) right = 0 if len(string) >= 2 and int(string[:2]) <= 26: right = util(string[2:]) memory[string] = right + left return left + right return util(s) """ 123 """ result = numDecodings('111111111111111111111111111111111111111111111') # result = numDecodings('12') print(result)
c69e73e5fa5c97d1b8175bae68f8385ea6ef826f
Monikabandal/My-Python-codes
/Find the minimum distance between two numbers.py
604
3.90625
4
""" set={3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3} """ z=[] def minimum_distance(z,x,y): distance=999999 for i in range(0,len(z)): if(z[i]==x or z[i]==y): prev=i break for j in range(prev,len(z)): if(z[j]== x or z[j]==y): if(z[j]== z[prev]): prev=j else: if(abs(prev-j)<distance): distance=abs(prev-j) prev=j return distance for i in range(0,input()): z.append(input()) x=input() y=input() print minimum_distance(z,x,y)
ffff39f3b254d358a1a92f9c5cff6de4f0e9f840
darkvoid32/CTF-writeups
/ångstromCTF 2020/Reasonably Strong Algorithm/rsa_qpe.py
3,214
3.546875
4
import fractions from binascii import unhexlify # https://www.alpertron.com.ar/ECM.HTM def getModInverse(a, m): if fractions.gcd(a, m) != 1: return None u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = ( u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 return u1 % m def long_to_bytes (val, endianness='big'): """ Use :ref:`string formatting` and :func:`~binascii.unhexlify` to convert ``val``, a :func:`long`, to a byte :func:`str`. :param long val: The value to pack :param str endianness: The endianness of the result. ``'big'`` for big-endian, ``'little'`` for little-endian. If you want byte- and word-ordering to differ, you're on your own. Using :ref:`string formatting` lets us use Python's C innards. """ # one (1) hex digit per four (4) bits width = val.bit_length() # unhexlify wants an even multiple of eight (8) bits, but we don't # want more digits than we need (hence the ternary-ish 'or') width += 8 - ((width % 8) or 8) # format width specifier: four (4) bits per hex digit fmt = '%%0%dx' % (width // 4) # prepend zero (0) to the width, to zero-pad the output s = unhexlify(fmt % val) if endianness == 'little': # see http://stackoverflow.com/a/931095/309233 s = s[::-1] return s def main(): p = "13 536574 980062 068373".replace(" ", "") q = "9 336949 138571 181619".replace(" ", "") e = 65537 ct = 13612260682947644362892911986815626931 p = int(p) q = int(q) # compute n n = p * q # Compute phi(n) phi = (p - 1) * (q - 1) # Compute modular inverse of e d = getModInverse(e, phi) print("n: " + str(d)) # Decrypt ciphertext pt = pow(ct, d, n) print("pt: " + str(pt)) print('pt_byte: ' + str(long_to_bytes(pt))) #172070576318285777902351017014850513943749891499547486454156569029770767741 if __name__ == "__main__": main() #!/usr/bin/python ## RSA - Given p,q and e.. recover and use private key w/ Extended Euclidean Algorithm - crypto150-what_is_this_encryption @ alexctf 2017 # @author intrd - http://dann.com.br/ (original script here: http://crypto.stackexchange.com/questions/19444/rsa-given-q-p-and-e) # @license Creative Commons Attribution-ShareAlike 4.0 International License - http://creativecommons.org/licenses/by-sa/4.0/ ##import binascii, base64 ## ##p = 13536574980062068373 ##q = 9336949138571181619 ##e = 65537 ##ct = 13612260682947644362892911986815626931 ## ##def egcd(a, b): ## x,y, u,v = 0,1, 1,0 ## while a != 0: ## q, r = b//a, b%a ## m, n = x-u*q, y-v*q ## b,a, x,y, u,v = a,r, u,v, m,n ## gcd = b ## return gcd, x, y ## ##n = p*q #product of primes ##phi = (p-1)*(q-1) #modular multiplicative inverse ##gcd, a, b = egcd(e, phi) #calling extended euclidean algorithm ##d = a #a is decryption key ## ##out = hex(d) ##print("d_hex: " + str(out)); ##print("n_dec: " + str(d)); ## ##pt = pow(ct, d, n) ##print("pt_dec: " + str(pt)) ## ##out = hex(pt) ####out = str(out[2:-1]) ##print("flag") ##print(bytes.fromhex(out).decode('utf-8'))
35ac2d8ff8548ac5899910bda94f718af65c82fb
sreekarachanta/py-programs
/calc.py
602
4.09375
4
def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def divide(a,b): return a/b print("What operation do you want to Perform - \n" "1. add\n" \ "2. sub\n" \ "3. multiply\n" \ "4. Divide\n") select = input("Select operations from 1, 2, 3, 4 :") num1 = int(input("Enter 1st number :")) num2 = int(input("Enter 2nd number :")) if (select == '1'): print(add(num1,num2)) elif (select == '2'): print(sub(num1,num2)) elif (select == '3'): print(mul(num1,num2)) elif (select == '4'): print(divide(num1,num2)) else: print("Invalid operation")
05b13efaa3731c3e675c4b8df6e89609fcf4f89a
t-walker-21/gameAI
/tic_tac_toe/game.py
353
3.96875
4
""" Script to play tic tac toe game """ import sys from board import board b = board.Board() while True: b.display_board() move = int(raw_input("Enter your move\n")) b.place_piece(move) if b.check_win(1): print "Player 0 won!" b.display_board(True) exit() elif b.check_win(-1): print "Player 1 won!" b.display_board(True) exit()
b17dbb8a8126323fe53ca7738f6f19d93d0d7b23
narsingojuhemanth/pythonlab
/largestof3.py
302
4.21875
4
# Write a python program to find largest of three numbers. a=int(input("enter a=")) b=int(input("enter b=")) c=int(input("enter c=")) largest=0 if (a>b) and (a>c): largest=a elif (b>c) and (b>a): largest=b else: largest=c print("largest of ",a,b,"and",c,"=",largest)
cf2a471fba237137ec68f03f446c05c1c7dab937
taehoon95/python-study
/예외처리/trycatchelse.py
642
3.78125
4
try: number_input_a = int(input("정수 입력")) except: print("정수를 입력 하지 않았습니다.") else: print("원의 반지름 : " ,number_input_a) print("원의 둘레 : " , 2*3.14*number_input_a) print("원의 넓이 : " ,3.14*number_input_a*number_input_a) try: number_input_a = int(input("정수 입력")) print("원의 반지름 : ", number_input_a) print("원의 둘레 : ", 2 * 3.14 * number_input_a) print("원의 넓이 : ", 3.14 * number_input_a * number_input_a) except: print("정수입력부탁") else: print("예외 발생 X") finally: print("프로그램 종료")
7dbf0c315399a19749fdcaf288b7da5fd6b0cc49
SwiftPanda10/fib
/fib.py
155
4.21875
4
fib=int(input("Enter a number of the desired fibonacci: ")) a1=0 a2=1 print(a1) print(a2) for i in range(1,fib): a3=a1+a2 print(a3) a1,a2=a2,a3
32eb0904eaccd01b783944803b87fa3211ef4506
Cprocc/Python-Study
/foundmently/foundmentlyKnow.py
4,862
3.765625
4
'''map function & for ''' def fib(n): if n == 0 or n==1: return 1 else: return fib(n-1) + fib(n-2) for i in map(fib, [2,6,4]): print (i) L1 = [1,4] L2 = [2,3] for i in map(min, L1,L2): print (i) '''lambda no-name function''' L = [] for i in map (lambda x,y: x**y, [1,2,3,4], [3,2,1,0]): L.append(i) print (L) '''There rae many function in Py to do on Str such as count(s1) find(s1) rfind(s1) index(s1) rindex(s1) lower() replace(old,new) rstrip() split(d)''' '''tuple as the key of dictiontry dict:key-value dict 中的项目是无序的,monthNumbers[1]指的是1月的key-value key()是一个方法:返回一个dict_keys类型的对象 所有python的内置不可变对象都是可散列的,所有python内置的可变对象都是不可散列的 dict function: len(d):返回d中项目的数量 d.keys():返回d中所有键的view d.values() k in d: d[k]:返回key为k的value d.get(k,v): 如果K在d中,则返回d[k],否则返回v del d[k]: 从d中删除key k for k in d: 遍历d中的key''' monthNumbers = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May'} print ('the third month is ' + monthNumbers[3]) dist = monthNumbers['Apr'] - monthNumbers['Jan'] print ('Apr and Jan are', dist, 'months apart') keys = [] for e in monthNumbers: keys.append(str(e)) print (keys) keys.sort() print (keys) months = monthNumbers.keys() list1 = list(months) print (list1) '''Error finding''' def isPal(x): temp = x temp.reverse if temp == x: return True else: return False def silly(n): for i in range(n): result = [] elem = input('Enter element: ') result.append(elem) if isPal(result): print('yes') else: print('no') # 异常控制 '''Error try Except''' numSuccess = 1 numFail = 0 try: successFail = numSuccess/numFail print('this result is work') except ZeroDivisionError: print('this result wont work ') print('now here') while True: val = input('Enter an integer: ') try: val = int(val) print('The square of the number you entered is ', val**2) break except ValueError: print(val ,'is not an integer') '''define readInt function to slove the input of integer''' def readInt(): while True: val = input('Enter an integer1: ') try: return(int(val)) except ValueError: print(val ,'is not an integer') '''define readVal function to slove the input of any type''' def readVal(valType,requestMsg,errorMsg): while True: val = input(requestMsg + ' ') try: return(valType(val)) except ValueError: print(val ,errorMsg) readVal(int ,'Enter an integer2:' ,'is not a integer') val = readVal(int ,'Enter an integer3: ','is not an integer') def getRatios(vect1, vect2): '''假设vect1和vect2是长度相同的数值型列表,返回一个包含vect[i]和vect2[i]中有意义的值的列表''' ratios = [] for index in range(len(vect1)): try: ratios.append(vect1[index]/vect2[index]) except ZeroDivisionError: ratios.append(float('nan')) #nan not a number except: raise ValueError('getRatios called with bad arguments') #raise expectionName(arguements) return ratios try: print(getRatios([1.0,2.0,7.0,6.0],[1.0,2.0,0.0,3.0])) print(getRatios([],[])) print(getRatios([1.0,2.0],[3.0])) except ValueError as msg: print(msg) def getGrades(fname): try: gradesFile = open(fname , 'r') #open file for reading except IOError: raise ValueError('getGrades could not open ' + fname) grades = [] for line in gradesFile: try: grades.append(float(line)) except: raise ValueError('Unable to convert line to float') return grades try: grades = getGrades('quiz1grades.txt') grades.sort() median = grades[len(grades)//2] print('Median grade is ', median) except ValueError as errorMsg: print('Whoops.',errorMsg) '''assert Boolean expression assert Boolean expression, argument''' class IntSet(object): """docstring for IntSet""" def __init__(self): self.vals = [] def insert(self,e): if e not in self.vals: self.vals.append(e) def member(self,e): return e in self.vals def remove(self,e): try: self.vals.remove(e) except: raise ValueError(str(e) + 'not found') def getMembers(self): return self.vals[:] def __str__(self): '''返回一个表示self的字符串''' self.vals.sort() result = '' for e in self.vals: result = result + str(e) + ',' return '{' + result[:-1] + '}' #-1可以忽略最后的逗号 print(type(IntSet),type(IntSet.insert)) s = IntSet() s.insert(3) print(s.member(3)) s = IntSet() s.insert(4) s.insert(3) print(s)
7d5db8b89c83154deef7c87278a50cbe8848360f
claudiodantas/labfmcc2
/labfmcc2.py
4,236
3.5
4
import csv #arquivo = open(r'C:\Python27\data\raw', 'r') #linhas = csv.reader(arquivo) #UFCG - Campina Grande #Autor: Franciclaudio Dantas da Silva #Matricula: 118210343 #Disciplina: Fundamentos Matematicos para Ciencia da Computacao II #Professor: Thiago Emmanuel #----------------SETUP------------------- dict1 = {1: [-1,1,1], 2: [1,0,1], 3: [1,1,1], 4:[1,0,1], 5:[-1,-1,-1]} dict2 = {1: [1, 1, 1], 2: [1,1,1]} dict3 = {1: [0,-1,0], 2: [0,0,0]} dict4 = {1: [-1,-1,-1], 2: [1,1,1]} #Se o produto interno for igual a 1 = concordam #Se for igual a -1 = discordam #Se for igual a 0 = abstencao #Soma positiva indica que eles concordam e uma negativa discordam #---------------PROBLEMA 1--------------- def compare(congress_id1, congress_id2, votos_dict): array1 = [] array2 = [] for e in votos_dict: if e == congress_id1: array1 = votos_dict[e]; if e == congress_id2: array2 = votos_dict[e]; result = 0; for i in range(len(array1)): if (array1[i] == 0 and array2[i] == 0): result += 1 else: result += array1[i] * array2[i] return result print(compare(2, 4, dict1)) print(compare(2, 5, dict1)) print(compare(1, 2, dict2)) print(compare(1, 2, dict3)) print(compare(1, 2, dict4)) #---------------PROBLEMA 2--------------- def most_similar(congress_id, votos_dict): idMaisSimilar = 0 similaridade = 0 primeiro = True for x in votos_dict: if (x == congress_id): continue elif primeiro: similaridade = compare(congress_id, x, votos_dict) idMaisSimilar = x primeiro = False elif compare(congress_id, x, votos_dict) >= similaridade: similaridade = compare(congress_id, x, votos_dict) idMaisSimilar = x return idMaisSimilar print(most_similar(1, dict1)) #---------------PROBLEMA 3--------------- def least_similar(congress_id, votos_dict): idMenosSimilar = 0 similaridade = 0 primeiro = True for x in votos_dict: if (x == congress_id): continue if primeiro: similaridade = compare(congress_id, 1, votos_dict) idMenosSimilar = x primeiro = False if compare(congress_id, x, votos_dict) <= similaridade: idMenosSimilar = x similaridade = compare(congress_id, x, votos_dict) return idMenosSimilar print(least_similar(2, dict1)) #---------------PROBLEMA 4--------------- #---------------PROBLEMA 5--------------- def average_similarity(congress_id, congress_set, votos_dict): media = 0.0 soma = 0.0 for x in congress_set: soma += compare(congress_id, x, votos_dict) media = soma/len(congress_set) return "%.2f" %media print (average_similarity(1, {2, 3, 4}, dict1)) def least_similar_partido(congress_set, votos_dict): similaridade = 0.0 diferentao = 0 primeiro = True for x in congress_set: if primeiro: similaridade = average_similarity(x, congress_set, votos_dict) diferentao = x primeiro = False else: if average_similarity(x, congress_set, votos_dict) < similaridade: similaridade = average_similarity(x, congress_set, votos_dict) diferentao = x return diferentao print (least_similar_partido({2,3,4},dict1)) #---------------PROBLEMA 6--------------- def pair_seem(votos_dict): parecidos = {} ids = "" for x in votos_dict: parecidos[x] = most_similar(x, votos_dict) similaridade = 0 primeiro = True for y in parecidos: if primeiro: similaridade = compare(y, parecidos[y], votos_dict) ids = "%d e %d" %(y, parecidos[y]) primeiro = False else: if compare(y, parecidos[y], votos_dict) >= similaridade: similaridade = compare(y, parecidos[y], votos_dict) ids = "%d e %d" %(y, parecidos[y]) return ids print(pair_seem(dict1)) #---------------PROBLEMA 7--------------- def pair_different(votos_dict): diferentes = {} ids = "" for x in votos_dict: diferentes[x] = least_similar(x, votos_dict) similaridade = 0 primeiro = True for y in diferentes: if primeiro: similaridade = compare(y, diferentes[y], votos_dict) ids = "%d e %d" %(y, diferentes[y]) primeiro = False else: if compare(y, diferentes[y], votos_dict) <= similaridade: similaridade = compare(y, diferentes[y], votos_dict) ids = "%d e %d" %(y, diferentes[y]) return ids print(pair_different(dict1)) #---------------PROBLEMA 8--------------- #---------------PROBLEMA 9---------------
fc40272b31101efdbece1a66cc0d6048e0ecccac
dyutibhardwaj/Memory-Allocator
/compare.py
2,034
3.53125
4
''' @anirudha 12:26:55 17-11-2020 ''' choose=input("Original [press 0] or New [press 1]?") if(choose==1): filename1 = input("input file: ") filename2 = input("Output file: ") else: filename1 = "output2.txt" filename2 = "out_A2_20.txt" file1 = open(filename1).readlines() file1_line = [] for lines in file1: lines= lines[:lines.find('\\')] file1_line.append(lines[:lines.find('\\')]) file2 = open(filename2).readlines() file2_line = [] for lines in file2: file2_line.append(lines[:lines.find('\\')]) print(file1_line[0:10]); print(file2_line[0:10]) flag=True count=0 n = 0 if len(file1) > len(file2): print("Length Of File is ",filename1,"is greater than",filename2,len(file1),">",len(file2)) for line in file2_line: if line == file1_line[n]: '''print("Match:","Line :",n + 1,filename1,":",line,"|",filename2,":",file2_line[n])''' n += 1 else: flag=False; count+=1 print(line, file2_line[n]) n += 1 print("Length Of File is ",filename1,"Equals",filename2,len(file1),"==",len(file2)) elif len(file1) < len(file2): n = 0 print("Length Of File is ",filename1,"is less than",filename2,len(file1),"<",len(file2)) for line in file1_line: if line == file2_line[n]: '''print("Match:","Line :",n + 1,filename1,":",line,"|",filename2,":",file2_line[n])''' n += 1 else: flag=False; count+=1 print(line, file1_line[n]) n += 1 print("Length Of File is ",filename1,"Equals",filename2,len(file1),"==",len(file2)) else: print("Length Of File is ",filename1,"Equals",filename2,len(file1),"==",len(file2)) n = 0 for line in file1_line: if line == file2_line[n]: '''print("Match:","Line :",n + 1,filename1,":",line,"|",filename2,":",file2_line[n])''' n += 1 else: flag=False; count+=1 print(line, file2_line[n]) n += 1 print(count) print("Length Of File is ",filename1,"Equals",filename2,len(file1),"==",len(file2)) if flag: print('match')
1c10da1e772df6147613f3fd8edf63e5171078d4
dhaipuleanurag/CourseWork
/BigData/hw2_solution/task2-e/reduce.py
1,121
3.5
4
#!/usr/bin/python import sys current_num_days = None current_medallion = None current_date = None current_num_trips = 0 current_num_days = 0 #input comes from STDIN (stream data that goes to the program) for line in sys.stdin: medallion, date = line.strip().split("\t", 1) if medallion == current_medallion and date == current_date: current_num_trips += 1 elif medallion == current_medallion and date != current_date: current_num_trips += 1 current_num_days += 1 else: if current_medallion != None: # output goes to STDOUT (stream data that the program writes) print "%s\t%d,%s" %( current_medallion, current_num_trips, '{0:.2f}'.format(1.*current_num_trips/current_num_days)) current_date = date current_medallion = medallion current_num_trips = 1 current_num_days = 1 print "%s\t%d,%s" %( current_medallion, current_num_trips, '{0:.2f}'.format(1.*current_num_trips/current_num_days))
a5292ad1e0c43b9210ed79fb54523ca751555fbf
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/pllnev006/question4.py
690
4.15625
4
# Program to print out palindromic primes # Nevarr Pillay - PLLNEV006 # 8 March 2014 def pal(num): newnum = str(num) reverse = newnum[::-1] if(newnum == reverse): return True return False def prime(num): for i in range(2,num): if (num%i==0): return False return True def main(): start = eval(input("Enter the starting point N:\n")) + 1 end = eval(input("Enter the ending point M:\n")) print("The palindromic primes are:") for i in range(start,end): if pal(i) == False: continue if(prime(i) == False): continue print(i) main()
7af0a8a0c82fe9587b9278049e1a36700b039bda
hoonest/PythonStudy
/src/chap08/01_baseInheritance.py
440
3.59375
4
class Base: def __init__(self): print(self) self.messge='Hello, World.' def print_message(self): print(self.messge) class Derived(Base): pass # Derived 클래스가 스스로 구현한 메서드는 없지만, Base로 부터 물려받은 print_messages()는 갖고 있음 if __name__ == '__main__': base = Base() base.print_message() dv = Derived() dv.print_message()
b2cfb1f6f99493738fa21cb57501942ef42357c8
keithdowd/newsgroups-classifier
/train-classifier.py
1,318
3.59375
4
# -*- coding: utf-8 -*- """ Demonstrates how to use NewsGroupsClassifier to fit a model to text data to classify newsgroup articles. This example comes from an example provided in the [Scikit-Learn documentation](http:// scikit-learn.org/stable/auto_examples/model_selection/ grid_search_text_feature_extraction.html). While the Scikit-Learn example implements this example using a procedural approach, this implementation demonstrate a object-oriented programmming (OOP) approach. Examples: Train the classifier and output a summary report: $ python train-classifier.py Run in interactive mode (to play around with objects and methods): $ python -i train-classifier.py """ from sklearn.datasets import fetch_20newsgroups from NewsGroupsClassifier import NewsGroupsClassifier if __name__ == "__main__": # Specify news groups categories categories = ["alt.atheism", "talk.religion.misc",] # Extract train data for news groups categories data = fetch_20newsgroups(subset="train", categories=categories) # Training examples train_examples = data.data # Training labels train_labels = data.target # Instantiate classifier clf = NewsGroupsClassifier() # Fit data clf.fit(train_examples, train_labels) # Report summary clf.summary
e0ce2ebd915f72d145306e71953b59a85ae4a1f3
cybelewang/leetcode-python
/code137SingleNumberII.py
1,010
3.5625
4
""" 137 Single Number II Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ # count bit at the same position, and module by 3 # python solution not accepted because python uses long type int. better to do this with java or C++ class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ count = [0]*32 # count of corresponding bit '1's in 32-bit integers for num in nums: for i in range(32): if (num & (1<<i)) != 0: count[i] += 1 res = 0 for i in range(32): if count[i]%3 !=0: res |= (1 << i) return res test_case = [1,1,1,2,2,2,3] obj = Solution() print(obj.singleNumber(test_case))
52b1d9178a2ef36dae25e9e30c39fbaab66f0aa6
drubiom/python
/Otros Ejercicios/numero_magico.py
967
3.84375
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: david.rubio # # Created: 10/01/2018 # Copyright: (c) david.rubio 2018 # Licence: <your licence> #------------------------------------------------------------------------------- import random def main(): pass if __name__ == '__main__': main() vidas = 7 cont = 0 con_a = 0 con_f = 0 while (vidas > 0): sol = random.randint(1,10) entrada = int(input ("Introduce número:")) if entrada != sol: vidas -= 1 con_f += 1 print("Vaya, no has adivinado el número. Te quedan %i vidas"%(vidas)) else: vidas += 1 con_a += 1 print("Bien! sumas una vida! Te quedan %i vidas"%(vidas)) cont +=1 if vidas == 0: print("Vaya, te has quedado sin intentos! Has hecho un total de %i intentos de los cuales has fallado %i y has acertado %i" %(cont, con_f, con_a))
58857b7bb7eaa63a364cf66d15450c409ed88369
Jayesh97/programmming
/design/588_DesignInmemoryFs.py
2,015
3.609375
4
from collections import defaultdict #my solution class TrieNode(): def __init__(self): self.children = defaultdict(TrieNode) class FileSystem(): def __init__(self): self.root = TrieNode() self.fileinfo = defaultdict(str) def ls(self, path): cur = self.root for token in path.split("/"): if token and cur: cur = cur[token] return sorted(cur.children.keys()) if cur else [] def mkdir(self, path): cur = self.root for token in path.split("/"): if token: cur = cur.children[token] #a/b/c/d - "hello". Create a file d and make its fileinfo hello def addcontenttofile(self,path,content): self.mkdir(path) self.fileinfo[path]=self.fileinfo[path]+content def readcontentfromfile(self,path): return self.fileinfo[path] #standard answer class TrieNode(object): def __init__(self): self.children = {} def setdefault(self,token): return self.children.setdefault(token,TrieNode()) def get(self,token): return self.children.get(token,None) class FileSystem(object): def __init__(self): self.root = TrieNode() self.fileinfo = defaultdict(str) def ls(self, path): cur = self.root for token in path.split("/"): if token and cur: cur = cur.get(token) return sorted(cur.children.keys()) if cur else [] def mkdir(self, path): cur = self.root for token in path.split("/"): if token: cur = cur.setdefault(token) #a/b/c/d - "hello". Create a file d and make its fileinfo hello def addcontenttofile(self,path,content): self.mkdir(path) self.fileinfo[path]=self.fileinfo[path]+content def readcontentfromfile(self,path): return self.fileinfo[path] obj = FileSystem() obj.mkdir("a/b/c") print(obj.ls("/")) obj.mkdir("fdf") print(obj.ls("/"))
fa396ab3d8496d509228265822fe6d674436cbe3
RahulYamgar/Predict-whether-income-based-on-census-data-using-Python
/LogisticReggresstion_AdultDataset.py
3,824
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 5 23:20:30 2018 @author: User """ # Importing Library import pandas as pd import numpy as np # Reading the File adult_df = pd.read_csv('adult_data.csv',header = None, delimiter=' *, *',engine='python') # delimiter=Seperation adult_df.head() # Top 5 Values adult_df.shape # Dimensions # header is not avaliable so we create header adult_df.columns = ['age', 'workclass', 'fnlwgt', 'education', 'education_num', 'marital_status', 'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss', 'hours_per_week', 'native_country', 'income'] # Numerical missing Values are shown as 'NAN' # categorical missing Values are shown as '?' adult_df.head() adult_df.isnull().sum() # For counting missig values adult_df.info() # Data types # only for categorical data for value in ['workclass','education','marital_status','occupation', 'relationship','race','sex','native_country','income']: print(value, sum(adult_df[value] == "?")) # craete a copy of the dataframe adult_df_rev = pd.DataFrame.copy(adult_df) # To see all columns adult_df_rev.describe(include= 'all') pd.set_option('display.max_columns',None) # Missing Values replace by Mode(Catagorical) for value in ['workclass','occupation','native_country']: adult_df_rev[value].replace(['?'], adult_df_rev[value].mode()[0], inplace=True) # inplace = replace in original # check the missing values for value in ['workclass','education','marital_status','occupation', 'relationship','race','sex','native_country','income']: print(value, sum(adult_df_rev[value] == "?")) # To find Levels in the categories veriable adult_df_rev.education.value_counts() # For preprocessing the data couverting the Catagocical data into Numerical(Lebal Encoding) colname = ['workclass','education','marital_status','occupation', 'relationship','race','sex','native_country','income'] from sklearn import preprocessing le={} type(le) for x in colname: le[x]=preprocessing.LabelEncoder() for x in colname: adult_df_rev[x]=le[x].fit_transform(adult_df_rev.__getattr__(x)) adult_df_rev.head() # Creating to Y and X variable Y = adult_df_rev.values[:,-1] Y X = adult_df_rev.values[:,:-1] X # standardizing the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(X) X = scaler.transform(X) # precautionary step Y=Y.astype(int) # Spliting data into Train & Test data from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=10) # Logistic Regression Model from sklearn.linear_model import LogisticRegression classifer=(LogisticRegression()) classifer.fit(X_train, Y_train) # Predicting values Y_pred=classifer.predict(X_test) print(list(zip(Y_test,Y_pred))) # Evaluating the model from sklearn.metrics import confusion_matrix, accuracy_score, \ classification_report # Confuion MAtrix cfm=confusion_matrix(Y_test,Y_pred) print(cfm) print("Classification report: ") print(classification_report(Y_test,Y_pred)) # Accuracy of Model = 82.27 acc=accuracy_score(Y_test,Y_pred) print("Accuracy of model: ",acc) # Using kfold_cross_validation classifier=(LogisticRegression()) from sklearn import cross_validation kfold_cv=cross_validation.KFold(n=len(X_train),n_folds=10) print(kfold_cv) # Run the model using scoring metric as accuracy kfold_cv_result=cross_validation.cross_val_score(estimator=classifier,X=X_train, y=Y_train, cv=kfold_cv) print(kfold_cv_result) #finding the mean Acc = 82.43 print(kfold_cv_result.mean())
bee06b90dd29b1a1b0dc3b8f50be5832a07c545f
Darfunfun/Revisions
/2.4.4 - Anagrammes.py
553
3.625
4
ch1 = "items" ch2 = "attention" compteur = 0 for i, lettre in enumerate(ch1) : # print(i, "-> ", end='') # print(lettre, "-> ", end='') for j, lettre2 in enumerate(ch2): if lettre == lettre2: # print("True") compteur += 1 # print(f"Compteur = {compteur}") else : pass # print("False") # print(f"Compteur = {compteur}") if compteur == len(ch2): print("Ce sont des anagrammes") else: print("Ce sont PAS des anagrammes")
b6682bc9360c3ee2622cf32ffb9e2c697df66ba3
alejo8591/dmk-django
/lab2/lab2_1.py
732
3.703125
4
# -*- coding: utf-8 -*- """ Program: lab2_1.py Author: Alejandro Romero Calcuar la tasa de impuesto de un alimento 1. Declaracion de variables: tax tasa de impuesto tax_one tasa de impuesto adicional 2. Entradas: valor del alimento numero de alimentos 3. Computacion: tasa de entrada = suma de numero de alimentos + tax + tax_one 4. Salida: El calculo de los elementos comprados """ # Declaracion de Constantes TAX = 0.16 TAX_ONE = 0.03 # Entrada(s) del teclado food = int(input('Ingrese el valor del Alimento: ')) ammount_food = int(input('Ingrese la cantidad de Alimentos: ')) # Computaciones total = (food * ammount_food) * (TAX + TAX_ONE) print("El total de los alimentos es:", total)
89ff89e5fc410acdc9dd06855169b421fdf5a3bc
PanamaP/pythonDump
/BikeRent.py
1,443
3.59375
4
# Elfar Snær Arnarson # 27 Febrúar 2020 # Skilaverkefni 4 class BikeRent: def __init__(self, inventory=15): self.inventory = inventory def displayinv(self): with open("bike_inventory.txt", "r") as f: fjoldi = f.read().replace('\n', '') self.inventory = int(fjoldi) print(f"Currently there are {self.inventory} bikes available to rent.") return self.inventory class Customer: def __init__(self): pass def bike_request(self): bikes = int(input("How many bikes would you like to rent? : ")) self.bikes = bikes with open("bike_inventory.txt", "r") as f: fjoldi = f.read().replace('\n', '') fjoldi = int(fjoldi) - int(bikes) inventory = str(fjoldi) with open("bike_inventory.txt", "w") as f: f.write(inventory) print(self.bikes) def bike_return(self): days = int(input('How many days did you rent? : ')) bike_return = int(input('How many bikes? : ')) with open("bike_inventory.txt", "r") as f: fjoldi = f.read().replace('\n', '') fjoldi = int(fjoldi) + int(bike_return) inventory = str(fjoldi) bill = days * bike_return * 20 print(f"Thanks for the return, the bill is ${bill}") with open("bike_inventory.txt", "w") as f: f.write(inventory)
d4c5782aae6bbf877843a9f4ce52f7267ab3f486
frclasso/turma1_Python_Modulo2_2019
/Cap02_Classes/revisao.py
987
4.03125
4
#!/usr/bin/env python3 # revisao # declaracao da classe class Pessoa_Fisica: idade = 40 # variaveis de classe def __init__(self, nome, sobrenome, salario): # construtor de classe, inicializa as var self.nome = nome self.sobrenome = sobrenome self.salario = salario def nome_completo(self): # metodo de classe return '{} {}'.format(self.nome, self.sobrenome) class Desenvolvedor(Pessoa_Fisica): # herança def __init__(self, nome, sobrenome, salario, linguagem): super().__init__(nome, sobrenome,salario) # construtor da classe Pai self.linguagem = linguagem # instancia de classe fabio = Pessoa_Fisica('Fabio', 'Classo', 5000) homem_aranha = Pessoa_Fisica('Peter', 'Parker', 20000) kevin = Desenvolvedor('Kevin', 'Mitnick', 1000000, 'Python') print(fabio.idade) print(fabio.nome) print(fabio.sobrenome) print(fabio.salario) print(f'{fabio.nome_completo()} tem {fabio.idade} anos') print(kevin.nome_completo())
71f2b14710792195eb42943def005504c8333713
jeffyjkang/Algorithms
/making_change/making_change.py
1,196
3.734375
4
#!/usr/bin/python # penies = 1 , nickles = 5 , dimes = 10 , quarters = 25 , half-dollars = 50 # input = amount of cents # denominations = array of coin denominations # total number of ways in which change can be made for input # create denominations array # start with largest denomination # if largest denom is divisible by amount, use it until you cant # import sys def making_change(amount, denominations): table = [0 for k in range(amount+1)] table[0] = 1 for i in range(0, len(denominations)): for j in range(denominations[i], amount+1): table[j] += table[j-denominations[i]] return table[amount] denom = [50, 25, 10, 5, 1] a = 100 variations = making_change(a, denom) print(variations) if __name__ == "__main__": # Test our your implementation from the command line # with `python making_change.py [amount]` with different amounts if len(sys.argv) > 1: denominations = [1, 5, 10, 25, 50] amount = int(sys.argv[1]) print("There are {ways} ways to make {amount} cents.".format( ways=making_change(amount, denominations), amount=amount)) else: print("Usage: making_change.py [amount]")
5fb1e37c271f9aa0bc2e08332b3dc08eecc823ef
ramaisgod/My-Python-Practice
/prog54_Raise_Errors.py
673
4.25
4
# Raise In Python # search Built in exceptions #----- Example-1 ------- # name = input("Enter Name : ") # if name.isnumeric(): # raise Exception("Numbers not allowed") # print(f"Welcome {name}") #----- Example-2 ------- # a = int(input("Enter 1st Number: ")) # b = int(input("Enter 2nd Number: ")) # if b==0: # raise ZeroDivisionError("Cant not devide by zero !!!") # result = a/b # print(result) #----- Example-3 ------- country = input("Enter Country: ") try: print(age) except Exception as e: if country == "pakistan": raise ValueError("pakistan is blocked !!!") print("Invalid Input")
3969d5bb0f1944b5a0d35ee923d174798afa7071
grimmessor/example
/main.py
1,720
3.765625
4
from deflist import read_file, balance, expenses while True: print('1 - Show current funds') print('2 - Expenses per month') print('3 - Exit') print('') a = input('Choose an option: ') if a not in ['1', '2', '3']: print('Ops, something went wrong, please try again') else: messages = read_file() if a == '1': balance = balance(messages) for key in balance: print(f'{key} {balance[key]} EUR') if a == '2': cards = [] for sms in messages: if sms[3] not in cards: cards.append(sms[3]) i = 1 for card in cards: print(f'{i} - {card}') i += 1 try: a = int(input('Choose a card: ')) if a < 0 or a > i + 1: print('Oops, something went wrong, please try again') except ValueError: print('Ooops, something went wrong, please try again') continue card = cards[a - 1] period = str(input('Enter date in format YYYY-MM: ')) if len(period) == 7: if period[4:5] == '-': try: int(period[:4]) int(period[5:]) except ValueError: print('Oooops, something went wrong, please try again') if int(period[5:]) > 12 or int(period[5:]) <= 0: print('There only 12 month in year :^)') continue e = expenses(messages, period, card) else: print('Ooooops, something went wrong, please try again') else: pass
0c63defa16af478b09c7059a9895aac271dfc1d5
qeedquan/misc_utilities
/math/bernstein-polynomial.py
757
3.828125
4
""" https://en.wikipedia.org/wiki/Bernstein_polynomial """ from sympy import * from sympy.abc import * import sys import os def bernstein(v, n): return expand(binomial(n, v) * x**v * (1-x)**(n-v)) def bernstein_derivative(v, n): return n*(bernstein(v-1, n-1) - bernstein(v, n-1)) def bernstein_integral(v, n): s = 0 for j in range(v+1, n+2): s += bernstein(j, n+1) return s/(n+1) if len(sys.argv) < 3: print("usage: v n") sys.exit() v = int(sys.argv[1]) n = int(sys.argv[2]) print("Bernstein(v={}, n={})".format(v, n)) print(bernstein(v, n)) print() print("Derivative(v={}, n={})".format(v, n)) print(bernstein_derivative(v, n)) print() print("Integral(v={}, n={})".format(v, n)) print(bernstein_integral(v, n))
2fd243a844a8cba06ab9941a6b3251ecbf420482
LimaEchoAlpha/cluedetective_python_class_project
/clue_detective_module/detective.py
12,857
4.15625
4
from board import * class Note(): """This is class represents the types of notes stored in a notebook. Attributes: - type = what type of information the note contains Subclasses: - Yes: marks the cards that are known to be in another player’s hand - No: marks the cards that are known to be absent from another player’s hand - Maybe: marks the unknown cards that a player secretly revealed in a turn - Mine: marks the cards that are in the user’s hand """ def __init__(self): pass def __eq__(self, other): return self.type == other.type class Yes(Note): def __init__(self): self.type = 'yes' def __repr__(self): return '\u2713' class No(Note): def __init__(self): self.type = 'no' def __repr__(self): return 'X' class Maybe(Note): def __init__(self): self.type = 'maybe' self.notes = [] def __repr__(self): if len(self.notes) == 0: return ' ' elif len(self.notes) == 1: return '?' elif len(self.notes) > 1: return '!' class Mine(Note): def __init__(self): self.type = 'mine' def __repr__(self): return '\u2731' class Notebook(): """This is a container class used to store all the notes taken by the detective during the current game of Clue being played by the user. Attributes: - board: current instance of Board - contents: dictionary that stores all the notes indexed by card and player Functions: - mark_mine(): Marks the appropriate notes for all the cards in the user’s hand. - mark_no(): Marks a card as absent in a player’s hand. - mark_yes(): Marks the card as present in a player’s hand and absent in everyone else’s. - mark_maybe(): Marks the unknown cards that a player secretly revealed that turn. - rows(): Takes in a card type as argument and returns all the rows in the notebook containing cards of that type. - printout(): Prints out the current contents of the notebook. """ def __init__(self, board): self.board = board self.contents = {(card.type, card.name, player.name): Maybe() for card in board.cards for player in board.players} self.mark_mine() def mark_mine(self): # mark all the cards in the user's hand keys = [(card.type, card.name, self.board.me.name) for card in self.board.me.hand] for key in keys: self.contents[key] = Mine() # cross out all cards in the user's column that is absent from their hand x_keys = [key for key in self.contents.keys() if key[2] == self.board.me.name and self.contents[key] != Mine()] for key in x_keys: self.mark_no(key) # cross out the cards in the user's hand for all the other players my_hand = [card.name for card in self.board.me.hand] x_keys2 = [key for key in self.contents if key[2] != self.board.me.name and key[1] in my_hand] for key in x_keys2: self.mark_no(key) def mark_no(self, key): # only proceed if card is orginally marked as maybe not_maybe = ['yes', 'no', 'mine'] if self.contents[key].type in not_maybe: return else: self.contents[key] = No() def mark_yes(self, key): # only proceed if card is orginally marked as maybe not_maybe = ['yes', 'no', 'mine'] if self.contents[key].type in not_maybe: print("Warning: something is wrong with the entry; not recorded.") return # if card was marked as a maybe for a turn # remove those maybe marks for other cards that remain # this is needed for a deduction step later if len(self.contents[key].notes) > 0: player_maybe = [new_key for new_key in self.contents if new_key[2] == key[2] and self.contents[new_key].type == 'maybe'] for new_key in player_maybe: if len(self.contents[new_key].notes) > 0: for i in self.contents[new_key].notes: if i in self.contents[key].notes: self.contents[new_key].notes.remove(i) # mark the card with check self.contents[key] = Yes() # cross out the card for all the other players x_keys = [x_key for x_key in self.contents if x_key[2] != key[2] and x_key[1] == key[1]] for x in x_keys: self.mark_no(x) def mark_maybe(self, turn): i = self.board.history.index(turn) for card in turn.suggestion: key = (card.type, card.name, turn.disprover.name) if self.contents[key].type == 'maybe': self.contents[key].notes.append(i) def rows(self, card_type): rows = {} for key in self.contents: if key[0] == card_type: if key[1] not in rows: rows[key[1]] = [] rows[key[1]].append(self.contents[key]) return rows def printout(self): border = '-'*(16 + 4*self.board.num_players) print(f"{' ':17s}", end = ' ') for player in self.board.players: if player.name == 'Rose': print('RS', end=" ") elif player.name == 'Peach': print('PH', end=" ") elif player.name == 'Gray': print('GY', end=" ") else: print(f"{player.name[:2].upper():^3s}", end=" ") print('\n' + border) card_types = ['Suspect', 'Weapon', 'Room'] for t in card_types: cards = self.rows(t) print(t.upper() + ":" ) for card in cards.keys(): print(f"{card:13s}", '-|-', end = ' ') for player in self.board.players: symbol = str(self.contents[(t, card, player.name)]) print(f"{symbol:^3s}", end = ' ') print() print('\n', border) print() class Detective(): """This is class takes notes on information learned in each turn and deduced new information from previous notes. Attributes: - board: current instance of Board - notebook = current instance of Notebook Functions: - take notes(): Takes in a turn as argument. If there is no disprover, crosses out the cards suggested for all the players except the suggester. If there is a disprover and a card is revealed, checks off the card. If there is a disprover, but the card is revealed secretly, marks all the maybes. - deduce_count(): Check to see if all the player’s cards are known. If they are, cross off all the other cards for that player. - deduce_maybe(): Check a player’s column for any cards from previous turns that are now known to be in that player’s hand by process of elimination. - deduce_solution(): Takes a card type as an argument, checks for a solution for that type, and returns the solution, if found. - find_solution(): Uses the deduce_solution function to find any solutions and stores it in the current instance of Solution. """ def __init__(self, board, notebook): self.board = board self.notebook = notebook def take_notes(self, turn): suggestion = turn.suggestion revealed = turn.revealed disprover = turn.disprover suggester = turn.suggester if not disprover: x_keys = [(card.type, card.name, player.name) for card in suggestion for player in self.board.players if player != suggester] for key in x_keys: self.notebook.mark_no(key) elif disprover != self.board.me: # check off the revealed card if any # or else mark secretly revealed unknown cards as maybe if revealed: key = (revealed.type, revealed.name, disprover.name) self.notebook.mark_yes(key) x_keys = [key for key in self.notebook.contents if key[1] == revealed.name and key[2] != disprover.name and key[2] != self.board.me.name] for key in x_keys: self.notebook.mark_no(key) else: self.notebook.mark_maybe(turn) # if players could not disprove before the disprover # mark the cards suggested as absent in all those players' hands x_players = [] next_player = self.board.next_player(suggester) while next_player.name != disprover.name: x_players.append(next_player) current_player = next_player next_player = self.board.next_player(current_player) x_keys = [(card.type, card.name, player.name) for card in suggestion for player in x_players if player != self.board.me] for key in x_keys: self.notebook.mark_no(key) self.deduce_count() self.deduce_maybe() self.deduce_count() self.deduce_maybe() self.deduce_count() self.find_solution() def deduce_count(self): dictionary = self.notebook.contents for player in self.board.players: cards = [key for key in dictionary if key[2] == player.name and key[2] != self.board.me.name and dictionary[key] != Yes()] yes_cards = 21 - len(cards) if player.num_cards == yes_cards: for key in cards: self.notebook.mark_no(key) def deduce_maybe(self): dictionary = self.notebook.contents for player in self.board.players: maybe_cards = [key for key in dictionary if key[2] == player.name and dictionary[key].type == 'maybe'] if len(maybe_cards) > 0: maybe_short = maybe_cards.copy() values = [] # look if the player has any maybes marked from previous turns for key in maybe_cards: if len(dictionary[key].notes) == 0: maybe_short.remove(key) if len(dictionary[key].notes) > 0: values.extend(dictionary[key].notes) # look to see if any maybes from previous turns have been isolated # if so, we know by process of elimination # that the player definitely has that card # only works if the safeguard in mark_yes() in notebook works if len(values) > 0: value_count = [x for x in set(values) if values.count(x) == 1] if len(value_count) > 0: for key in maybe_short: for i in dictionary[key].notes: if i in value_count: self.notebook.mark_yes(key) def deduce_solution(self, card_type): check = [key for key in self.notebook.rows(card_type)] for key, row in self.notebook.rows(card_type).items(): count = 0 # checks for the solution by row for entry in row: if entry == No(): count += 1 # checks for the solution by column elif entry == Yes() or entry == Mine(): check.remove(key) if count == self.board.num_players: return key if len(check) == 1: return check[0] def find_solution(self): solution = self.board.solution if solution.suspect == None: solution.suspect = self.deduce_solution('Suspect') if solution.weapon == None: solution.weapon = self.deduce_solution('Weapon') if solution.room == None: solution.room = self.deduce_solution('Room')
85677d11942a377ef05aff3c880d4d919e60c5c2
YvesHarrison/Python-programming-exercises-forked-from-zhiweihu
/53.py
308
3.625
4
class shape: def __init__(self): pass def area(self): return 0 class square(shape): def __init__(self,l): shape.__init__(self) self.length=l def cal(self): return self.length**2 def Question53(): a=square(3) print(a.cal()) Question53()
23dd47cf6e5688e6bb07fba8ddae7d9f9466eedf
pradeepsinngh/A-Problem-A-Day
/random/022-kth_largest_element_array.py
448
3.75
4
# Prob: Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, # not the kth distinct element. # Sol 1: # --------------------------------- class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ sortedNums = sorted(nums) return sortedNums[-k]
8a6c015d009ba2fa86907d54fc822d3b16c2af18
cpingor/leetcode
/654.最大二叉树.py
677
3.546875
4
# # @lc app=leetcode.cn id=654 lang=python3 # # [654] 最大二叉树 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: if len(nums) == 0: return None max = 0 for i in range(len(nums)): if nums[i] > nums[max]: max = i return TreeNode(nums[max], self.constructMaximumBinaryTree(nums[:max]), self.constructMaximumBinaryTree(nums[max + 1:])) # @lc code=end
3b74abb365ba0d492987165616b4a72e8c38de9e
KoliosterNikolayIliev/Softuni_education
/Fundamentals2020/Final exam Prep/Battle Manager.py
1,390
3.671875
4
people = {} while True: command = input() if command == "Results": break command = command.split(":") cmd = command[0] if cmd == "Add": personName = command[1] health = int(command[2]) energy = int(command[3]) if personName not in people.keys(): people[personName] = [health, energy] else: people[personName][0] += health # people[personName][1] += energy elif cmd == "Attack": attacker = command[1] defender = command[2] damage = int(command[3]) if attacker in people.keys() and defender in people.keys(): people[defender][0] -= damage people[attacker][1] -= 1 if people[defender][0] <= 0: del people[defender] print(f"{defender} was disqualified!") if people[attacker][1] <= 0: del people[attacker] print(f"{attacker} was disqualified!") elif cmd == "Delete": username = command[1] if username == "All": people.clear() else: if username in people.keys(): del people[username] count = len(people) people = dict(sorted(people.items(), key=lambda x: (-(x[1][0]), x[0]))) print(f"People count: {count}") for k, v in people.items(): print(f"{k} - {v[0]} - {v[1]}")
21e9870cce1df1472bae46dde01096ea092c644a
tsaihuangsd/Data-Structures
/linked_list/linked_list.py
1,563
3.765625
4
""" Class that represents a single linked list node that holds a single value and a reference to the next node in the list """ class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None self.tail = None def add_to_tail(self, value): if self.head == None: self.head = Node(value) self.tail = self.head else: new_tail = Node(value) self.tail.set_next(new_tail) self.tail = new_tail def remove_head(self): if self.head == None: return None else: if self.head == self.tail: self.tail = None old_head = self.head self.head = self.head.get_next() return old_head.get_value() def contains(self, value): current_node = self.head if self.head == None: return False while not current_node == None: print(current_node.get_value()) if value == current_node.get_value(): return True current_node = current_node.get_next() return False def get_max(self): current_max = 0 current_node = self.head if self.head == None: return None while not current_node == None: if current_node.get_value() > current_max: current_max = current_node.get_value() current_node = current_node.get_next() return current_max
7d7bcc3ea22df74a71dd5bc953678f62058c8605
chinitacode/Python_Learning
/Tencent_50/03_kth-largest-element-in-an-array.py
1,807
3.65625
4
# 215. Kth Largest Element in an Array # Method 1: quick sort + random seed, O(n), the best solution import random def findKthLargest(self, nums, k): x = random.randint(0, len(nums) - 1) nums[0], nums[x] = nums[x], nums[0] r = [num for num in nums[1:] if num > nums[0]] if len(r) == k - 1: return nums[0] if len(r) > k - 1: return self.findKthLargest(r, k) l = [num for num in nums[1:] if num <= nums[0]] return self.findKthLargest(l, k - len(r) - 1) # Method 2 (quick_sort, random seed, divide and conquer) def partition(nums, l, r): # random seed is the most crucial step x = random.randint(l, r) nums[l], nums[x] = nums[x], nums[l] pivot_idx = l for i in range(l+1, r+1): if nums[i] >= nums[l]: pivot_idx += 1 nums[i], nums[pivot_idx] = nums[pivot_idx], nums[i] nums[l], nums[pivot_idx] = nums[pivot_idx], nums[l] return pivot_idx #Or use while loop(slower) def partition2(nums, l, r): # choose the right-most element as pivot pivot_idx = l while l < r: if nums[l] >= nums[r]: # put the element no smaller than pivot to the start of nums nums[l], nums[pivot_idx] = nums[pivot_idx], nums[l] pivot_idx += 1 l += 1 nums[r], nums[pivot_idx] = nums[pivot_idx], nums[r] return pivot_idx def findKthLargest(nums, k): pivot_idx = self.partition(nums, 0, len(nums)-1) if pivot_idx + 1 == k: return nums[pivot_idx] if pivot_idx + 1 > k: return self.findKthLargest(nums[:pivot_idx], k) else: return self.findKthLargest(nums[pivot_idx + 1:], k - pivot_idx - 1) # Vice Versa: def findKthSmallest(nums, k): return findKthLargest(nums, len(nums) + 1 - k)
d68ccd24394df9742be117ea664a0b3a0e7c36f1
estraviz/codewars
/7_kyu/The Poet And The Pendulum/pendulum.py
271
3.5625
4
from collections import deque def pendulum(values): output = deque(maxlen=len(values)) for i, value in enumerate(sorted(values)): if i % 2 == 0: output.appendleft(value) else: output.append(value) return list(output)
c2375e02dc89b88ffa4f3a75d79791bb1e583bc8
ficklel/HankerRank-Algorithms
/8.py
605
3.53125
4
#!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): sumi=sum(arr) mini=arr[0] maxi=arr[0] t=1 n=len(arr) while t<n: if arr[t]<=mini: mini=arr[t] if arr[t]>=maxi: maxi=arr[t] t+=1 print(sumi-maxi,end=" ") print(sumi-mini) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
4c6bd47164e8ec7febea991bf74db245d31b148a
dorjeedamdul/python-basics
/basics.py
3,557
4.34375
4
#### --- STRINGS IN PYTHON --- #### # Strings can be indexed word = 'Python' word[0] # character in position 0 --> 'P' word[5] # character in position 5--> 'n' # Indices may also be negative numbers, to start counting from the right: word[-1] # last character --> 'n' word[-2] # second-last character -> 'o' word[-6] # selects first character --> 'P' # In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring: word[0:2] # characters from position 0 (included) to 2 (excluded) --> 'Py' word[2:5] # characters from position 2 (included) to 5 (excluded) --> 'tho' # Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced. word[:2] # character from the beginning to position 2 (excluded) --> 'Py' word[4:] # characters from position 4 (included) to the end --> 'on' word[-2:] # characters from the second-last (included) to the end --> 'on' #### --- DICTIONARIES IN PYTHON --- #### person = {'name':'Dorje', 'age': 28, 'city':'Richmond', 'state':'California'} print(person) name_is = person['name'] print(name_is) print(person['age']) print(person['city']) # Getting all the keys or values from a dictionary print(person.keys()) print(person.values()) # Getting both the keys and the value together print(person.items()) # dictionary with list as a value car = {'model': 'T3', 'color':['red', 'yellow', 'green'], 'year':2020} print(car['model']) print(car['color'][1]) alpha = {'letters': ['a','b','c']} print(alpha['letters'][1].upper()) numbs = {'a': 100, 'b':200, 'c':300} numbs['d'] = 400 # adds 'd':400 to the numbs dictionary print(numbs) numbs['new_value'] = 'yep' print(numbs) # Getting all the keys or values from a dictionary print(numbs.keys()) print(numbs.values()) # Getting both the keys and the value together print(numbs.items()) #### --- TUPLES IN PYTHON --- #### # Tuples are very similar to Lists. However, they have one difference - tuples are IMMUTABLE ( can't be changed ). It basically means once an element is assigned to an index position inside a tuple, you can't grab that element and reassigned another value. # Tuples looks like Lists, except it uses ( ) t = ('one', 2, 'three', 4.5) print(t[1]) print(t[-1]) # prints 4.5 because we are getting the element at last index by using the -1 # 2 built-in methods for Tuple - index() and count() methods # Count(): name = ('dorje', 'dorje', 'damdul', 1, 3, 3, 5, 3) print(name.count('dorje')) print(name.count(3)) #### --- SETS IN PYTHON --- #### # Sets are unordered collection of unique elements - meaning there can only be one representative of the same object myset = set() myset.add(1) myset.add(2) print(myset) myset.add(2) print(myset) # this will not add another 2 to the set, because set only can contain unique element - meaning can't have same value twice #### --- BOOLEANS IN PYTHON --- #### # Booleans are operators that allow you to convey True or False statements. In python its 'True' and 'False' print(1 == 1) print(100 < 50) b = None print(type(b)) # I/O Basics of Files in Python # muffle.read() --> outputs a giant string of everything in the file # # .readlines() --> outputs each sentence as a list # Opening a file living somewhere on your computer, just pass in the file path # .open('...file - path..') # should use forward slash '/' in the file path # Always make sure to close the file once done with it by .close()
befaf447b804416f94809a4ea5aeefd135451f25
buzycoderscamp/ML-Workshop-Samlpes-Day2-
/Visualization/Plot.py
467
3.546875
4
from matplotlib import pyplot import math def sine(xvals) : y = [] for i in xvals : y.append(math.sin(i * math.pi / 180)) pyplot.plot(xvals, y) pyplot.show() def plotLine(x, m, c) : y = [(i*m) + c for i in x] pyplot.xlabel("X axis") pyplot.ylabel("Y axis, y = mx+c") pyplot.xlim([0, 30]) pyplot.ylim([0, 60]) pyplot.plot(x, y) pyplot.show() #plotLine([0, 1, 2, 3, 4, 5, 6], 2, 1) sine([i for i in range(0, 360, 15)])
479af0cce4d2f110cad924e34862b214a775d328
prajwal60/ListQuestions
/learning/BasicQuestions/Qsn8.py
162
4.125
4
# Write a Python program to display the first and last colors from the following list. list1 = ["Red","Green","White" ,"Black"] print(list1[0]) print(list1[-1])
b981529d1f6d5df5680f9b5a8284f5d7d75eb159
panosadamop/pythonCourses
/scrap.py
737
3.734375
4
import copy di1={1:[1,2,3], 2:{1:'A', 2:'B'}} di2 = copy.copy(di1) di2[2][1] = 'X' di3 = copy.deepcopy(di1) di3[1][0] = 'Y' print(di1) print(di3) print("---------------------------------------------") print("---------------------------------------------") adict = {1:'A', 20:'B', 50:'C'} print(sum([max(adict), min(adict)])) print(sorted([max(adict), len(adict), sum(adict), min(adict)])) print(len([max(adict), len(adict), min(adict)])) bdict = [max(adict) if i%2 else min(adict) for i in range(4)] print(bdict) print("---------------------------------------------") di1 = {1:10, 2:20, 3:30} di2={} for it in di1.items(): di2[it[0]] = it[1] + 100 print(di2) print(di2.get('1','Δεν υπάρχει το κλειδί'))
a628f2937aba932584fef752a175ee98c207ca05
RubinaSali/rock_paper_scissors
/game3.py
1,364
4.28125
4
import random print("...rock...\n...paper...\n...scissors...") player_wins = 0 computer_wins = 0 winning_score = 2 while player_wins < winning_score and computer_wins < winning_score: print(f"player = {player_wins} computer = {computer_wins}") rand_number= random.randint(0,2) player=input("Make your move: ") if player == "quit" or player== "q": break if rand_number==0: computer="rock" elif rand_number==1: computer="paper" else: computer="scissors" print("computer plays: " + computer) if player==computer: print("draw") elif player=="rock": if computer=="scissors": print("player wins!!") player_wins +=1 elif computer=="paper": print("computer wins!!") computer_wins +=1 elif player=="paper": if computer=="rock": print("player wins!!") player_wins +=1 elif computer == "scissors": print("computer wins!!") computer_wins +=1 elif player=="scissors": if computer=="rock": print("computer wins!!") computer_wins +=1 elif computer=="paper": print("player wins") player_wins +=1 else: print("something went wrong") print(f"FINAL SCORES...player = {player_wins} computer = {computer_wins}") if player_wins > computer_wins: print("CONGRATS") elif player_wins==computer_wins: print("it's a tie!") else: print("SORRY YOU LOST")
d44968811cb1d91e1bfab31910f85ec3de2f9916
felipeonf/Exercises_Python
/exercícios_fixação/049.py
383
3.9375
4
''' Crie um programa que leia 6 números inteiros e no final mostre quantos deles são pares e quantos são ímpares.''' par = 0 impar = 0 for num in range(1,7): numero = int(input(f'{num}° numero: ')) if numero % 2 == 0: par +=1 else: impar += 1 print(f'A quantidade números pares digitados é {par}, já de números ímpares são {impar}')
84411a0f519a6846b68195c011ea1edb044e8d6a
LoutreStarery/ift6759_project1
/models/CNN2D.py
1,927
3.703125
4
""" Basic model example using a 2D CNN with images as inputs and metadata """ import tensorflow as tf class CNN2D(tf.keras.Model): """ Simple 2D CNN """ def __init__(self): """ Define model layers """ super(CNN2D, self).__init__() self.conv_1 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu') self.pool_1 = tf.keras.layers.MaxPooling2D((2, 2)) self.conv_2 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu') self.pool_2 = tf.keras.layers.MaxPooling2D((2, 2)) self.conv_3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu') self.flatten = tf.keras.layers.Flatten() self.FC1 = tf.keras.layers.Dense(128, activation='relu') self.FC2 = tf.keras.layers.Dense(64, activation='relu') self.t0 = tf.keras.layers.Dense(4, name='t0') def call(self, inputs): """ Perform forward on inputs and returns predicted GHI at the desired times :param inputs: input images and metadata :return: a list of four floats for GHI at each desired time """ img, past_metadata, future_metadata = inputs # split images and metadatas # Remove timesteps dimensions from sequences of size 1 patch_size = img.shape[-2] n_channels = img.shape[-1] img = tf.reshape(img, (-1, patch_size, patch_size, n_channels)) past_metadata = tf.reshape(past_metadata, (-1, past_metadata.shape[-1])) x = self.conv_1(img) x = self.pool_1(x) x = self.conv_2(x) x = self.pool_2(x) x = self.conv_3(x) x = self.flatten(x) # concatenate encoded image and metadata x = tf.keras.layers.concatenate([x, past_metadata, future_metadata], 1) x = self.FC1(x) x = self.FC2(x) # Create 4 outputs for t0, t0+1, t0+3 and t0+6 t0 = self.t0(x) return t0
2b438c288ce8569b0517a6c6e2a156f9ec4e46bc
jazzy1331/cseGradingScripts
/CSE2421/unzipSubmissions.py
819
4.03125
4
#Author: Thomas Sullivan #unzips .zip files in current directory and puts content in a file named after the student and late status. #places processed files in a folder named "unzipped" #Expected file format: studentname_<late>_####_####.zip #<late> is optional and ### are numbers #usage: python unzipSubmissions.py & import os names = os.listdir(".") if (not os.path.isdir("unzipped")): os.mkdir("unzipped") for fileName in names: if (os.path.isfile(fileName) and fileName.endswith(".zip")): splitName = fileName.split("_") directoryName = splitName[0] if (splitName[1] == "late"): directoryName = splitName[0] + "_" + splitName[1] print("Unzipping " + fileName + " into " + directoryName) os.system("unzip " + fileName + " -d " + directoryName) os.system("mv " + fileName + " unzipped")
15c5ea2d0e66890f39325a6b9bb7c93472371a21
banana-galaxy/challenges
/challenge4(zipcode)/vaterz.py
1,156
4.09375
4
def validate(x): """ Validates a integer based zip code. Requirements: 11xxx # two or more same digits in a row, not valid 1x1xx # two or more neighboring digits, not valid 1xx1x # no neighboring or next to each other digits, valid Parameters: x (int): the zipcode to validate. Returns: Boolean: True or False based on the requirements for valid Zip Code. """ numbers = "1234567890" x = str(x) s = len(x) z = 0 # Checking size of Zip submitted if s == 5: for i in range(s): z = i + 1 # Assuring that it's numbers being validated and that z is not throwing an index error if x[i] in numbers and z < s: # Checking for repetition if x[i] == x[z]: return False # Making sure z does cause an index error if z + 1 < s: # Checking for Neighboring numbers if x[i] == x[z + 1]: return False else: return False else: return False return True
b6c50034f278ccbf64133f511cbc49a1dc364c66
bdliyq/algorithm
/lintcode/word-ladder.py
1,043
3.6875
4
#!/usr/bin/env python # encoding: utf-8 # Question: http://www.lintcode.com/en/problem/word-ladder/ import string class Solution: # @param start, a string # @param end, a string # @param dict, a set of string # @return an integer def ladderLength(self, start, end, dict): # write your code here alphabet = string.ascii_lowercase dict.add(end) queue = [] queue.append((start, 1)) while len(queue) > 0: word, dist = queue.pop(0) if word == end: return dist for j in alphabet: for i in xrange(len(word)): if j != word[i]: new_word = word[:i] + j + word[i+1:] if new_word in dict: dict.remove(new_word) queue.append((new_word, dist + 1)) return 0 if __name__ == '__main__': s = Solution() print s.ladderLength('hit', 'cog', set(["hot","dot","dog","lot","log"]))
7d6efd78eab99429705058902f3c8a7a1a00f47d
Jessica8729/DeepLearningStartUp
/ex_dpl.py
1,211
3.625
4
# -*- coding:utf-8 -*- # 该程序使用python 2,因此,一般用以下4,5,6三行代码解决中文编码错误问题,一劳永逸 # 但貌似因为Python2选择了 ASCII,而python 3默认Unicode,所以,有声音不建议这种用法。 import sys reload(sys) sys.setdefaultencoding("utf-8") import re from collections import Counter from zhon.hanzi import punctuation initial_input=open("happiness_seg.txt", "r").read().decode("utf-8") # 读取文件,将str转换为unicode string = re.sub(ur"[%s]+" %punctuation, "", initial_input.decode("utf-8")) # 调用zhon包去除中文标点 initial_list=string.split(" ") # 将文章生成初始列表,空格划分各个元素 # print (string) # print (initial_list) standard_list=[] # 初始化最终的列表 for i in range(0, len(initial_list)-1): if(len(initial_list[i])>=2 and len(initial_list[i+1])>=2): # 判断相邻两元素长度均不小于2 doublewords=initial_list[i]+initial_list[i+1] standard_list.append(doublewords) counter=Counter(standard_list).most_common(10) # Counter的内置函数挑选出频次最高的10个 for element in counter: # 打印 for word_count in element: print (word_count)
cb83fe4bf92aa21c219ff985af0e7b9cf6a9ca77
kruthik23/Python
/assignment 1/q4.py
215
4.46875
4
my_str = input("Enter string : ") str = '' for i in my_str: str = i + str print("\nThe Original String is: ", my_str) print("The Reversed String is: ", str) print("Reverse of the string: "+my_str[::-1])
de052ee82161fff6946b7d43247713fa746949f7
OuroborosD/estudospython
/12_validador_cpf.py
4,058
3.90625
4
#TODO cria v2 identificar numeros repetidos, e quantidade de caracteres. def verifica_repetido(valor,resultado = 0): """verifica se só tem numeros repetidos no cpf. modifiquei para uma igualdade, entre os valores multiplicados de valor X ele mesmo e o resultado pois pode dar um falso negativo. como o exemplo: o valor da 55, e 55 é divisivel por 11 com resto 0, ai dava erro. valor = 55 % 11 == 0 >> TRUE Args: valor string: os numeros do cpf resultado int: inicializa o resultado. Returns: bollean: verdedeiro ou falso dependendo se só tiver numeros repetidos """ for i in range(len(valor)): resultado += int(valor[i]) if resultado != (len(valor)*int(valor[0])): return True else: return False def valida_cpf_v1(cpf): """função para validar cpf, irá verificar os ulitmos dois digitos. para saber se estão corretos Args: cpf (string): numeros do cpf Returns: bolean : se é valido ou não """ verifica_cpf = cpf multiplicador = 10 controle = 0 digitos_verificadores = [] while controle != 2: valor = 0 # valor do incremento. for i in range((9+controle)): valor += int(verifica_cpf[i])*(multiplicador-i) resultado = valor*10%11 if resultado == 10: #caso seja 10 o resto no cpf é 0 o digito resultado = 0 controle += 1 #incrementa para na proxima sair do loop multiplicador += 1 #incrementa para pegar o primeiro digito verificador na multiplicação. digitos_verificadores.append(resultado) if int(cpf[-2]) == digitos_verificadores[0] and int(cpf[-1]) == digitos_verificadores[1]:#foi transformado os para interiros return True #pois estava dando erro comparando como string else: return False def valida_cpf_v2(cpf): """valida cpf, consegue verificar os digitos, e se são numeros repetido Args: cpf (string): o valor do cpf Returns: dict: {'status': bolean, 'mensagem':'o por que do status'} retorna o booleano True ou False como o status, e uma mensagem mostrando o por que o status. """ verifica_cpf,multiplicador,controle,digitos_verificadores, = cpf, 10, 0, [] mensagens = ['quantidade de digitos invalida','cpf invalido','todos os numeros não podem ser iguais','valido'] retorno = {'valido':False, 'mensagem':mensagens[0]}# numeros_repetidos = verifica_repetido(verifica_cpf) if len(cpf) == 11 and numeros_repetidos == True : while controle != 2: valor = 0 # valor do incremento. for i in range((9+controle)): valor += int(verifica_cpf[i])*(multiplicador-i) resultado = valor*10%11 if resultado == 10: #caso seja 10 o resto no cpf é 0 o digito resultado = 0 controle += 1 #incrementa para na proxima sair do loop multiplicador += 1 #incrementa para pegar o primeiro digito verificador na multiplicação. digitos_verificadores.append(resultado) if int(cpf[-2]) == digitos_verificadores[0] and int(cpf[-1]) == digitos_verificadores[1]:#foi transformado o cpf para interiro #pois estava dando erro comparando como string retorno['mensagem'] = mensagens[3] retorno['valido'] = True return retorno else: retorno['mensagem'] = mensagens[1] return retorno elif numeros_repetidos:#caso não seja numero repetido entra aqui. return retorno else: retorno['mensagem'] = mensagens[2] return retorno #23569741052 validos #a3 = verifica_repetido('23569741052') a4 = valida_cpf_v2('16951785805') print(a4)
5c13b41c9ce3e5daf06af2946139119822e4e8e8
mdinos/coding-problems
/codewars/python/kyu/4/catch_car_milage_numbers.py
1,381
3.84375
4
# https://www.codewars.com/kata/52c4dd683bfd3b434c000292 def is_interesting(number, awesome_phrases): if number == 98 or number == 99: return 1 elif number < 100: return 0 next_three = [number, number + 1, number + 2] xs = [] xs.append([check_followed_by_zeros(i) for i in next_three]) xs.append([check_all_numbers_same(i) for i in next_three]) xs.append([check_if_palindrome(i) for i in next_three]) xs.append([check_awesome_phrases(i, awesome_phrases) for i in next_three]) xs.append([check_ascending_digits(i) for i in next_three]) xs.append([check_decending_digits(i) for i in next_three]) for x in xs: if x[0]: return 2 for x in xs: if x[1] or x[2]: return 1 return 0 def check_followed_by_zeros(number): return (len(str(number)) - 1) * "0" == str(number)[1:len(str(number))] def check_all_numbers_same(number): return str(number)[0] * len(str(number)) == str(number) def check_if_palindrome(number): return str(number) == str(number)[::-1] def check_awesome_phrases(number, awesome_phrases): return number in awesome_phrases def check_ascending_digits(number): return str(number) in '1234567890' def check_decending_digits(number): return str(number) in '9876543210'
1b3133fa49a9489e93e2b38a40cea366646cb1b0
BIGStrawberry/ALDS
/Week_4/4.1.py
2,605
3.578125
4
""" Student Naam: Wouter Dijkstra Student Nr. : 1700101 Klas : ?? Docent : [email protected] """ import random class HashTable: def __init__(self): self.data = [None for _ in range(11)] self.num_elements = 0 def __repr__(self): s = '' for i in range(len(self.data)): sets = self.data[i] s += str(i) + ": \n" if sets is not None: # and sets != set() for value in sets: s += " " + str(value) s += '\n' return s def search(self, e): hashed = hash(e) % self.num_elements return self.data[hashed] is not None and e in self.data[hashed] def insert(self, e): self.num_elements += 1 if len(self.data) > 0 and self.num_elements / len(self.data) > 0.75: self.rehash(len(self.data) * 2) hashed = hash(e) % self.num_elements if self.data[hashed] is not None: self.data[hashed].add(e) else: self.data[hashed] = {e} def delete(self, e): hashed = hash(e) % self.num_elements if self.data[hashed] is not None and e in self.data[hashed]: self.data[hashed].remove(e) if self.data[hashed] == set(): self.data[hashed] = None def rehash(self, new_size): print("Rehashed, from: ", len(self.data), " to: ", new_size) tmp = self.data[:] tmp_count = self.num_elements self.data = [None for _ in range(new_size)] for sets in tmp: if sets is not None: for value in sets: self.num_elements -= 1 # Num_elements - 1 because insert adds one self.insert(value) self.num_elements = tmp_count print(self) hashTable = HashTable() for i in range(200): hashTable.insert(random.random()) for i in range(100): hashTable.delete(random.random()) print("----------INSERTING-------------------") print("Can I find 0.1890327678114233? " + str(hashTable.search(0.1890327678114233))) print("Inserting 0.1890327678114233.. ") hashTable.insert(0.1890327678114233) print("Can I find 0.1890327678114233? " + str(hashTable.search(0.1890327678114233))) print("----------DELETING--------------------") print("Can I find 0.1890327678114233? -> " + str(hashTable.search(0.1890327678114233))) print("Deleting 0.1890327678114233..") hashTable.delete(0.1890327678114233) print("Can I find 0.1890327678114233? ->" + str(hashTable.search(0.1890327678114233))) print("--------------------------------------")
c5e9ebc16d2bb7fb00e48198c888e8c501502f71
Uttam1982/PythonTutorial
/08-Python-DataTypes/String-Format/07-formating-class.py
177
4.21875
4
# Example : Formatting class members using format() #define a class class Student: name = 'Sara' age = 21 print("Name = {s.name} and Age = {s.age}".format(s= Student()))
4b668844a8b443abbbb922624b94e06558664a41
Avaddov/DevInstitute
/Week4/Day3 - Dictionaries/XP1.py
2,448
4.21875
4
## Convert the two following lists, into dictionaries. # keys = ['Ten', 'Twenty', 'Thirty'] # values = [10, 20, 30] # # Hint: Use the zip method # results = zip(keys, values) # print(dict(results)) # Exercise 2 : Cinemax #2 # “Continuation of Exercise Cinemax of Week4Day2 XP” # A movie theater charges different ticket prices depending on a person’s age. # if a person is under the age of 3, the ticket is free # if they are between 3 and 12, the ticket is $10; # and if they are over age 12, the ticket is $15 . # age # price = {<3 = 0, >2 & <13 = 10, >13 = 15} family = {"rick": 64, 'beth': 33, 'morty': 5, 'summer': 8} total = 0 # Using a for loop, the dictionary above, and the instructions, print out how much each family member will need to pay alongside their name for name, age in family.items(): if age < 3: price=0 elif age < 13: price=10 else: price=15 print(name, age, price) # After the loop print out the family’s total cost for the movies total = total + price print(total) # Bonus: let the user input the names and ages instead of using the provided family variable # (Hint: ask the user for names and ages and add them into a family dictionary that is initially empty) # name: Zara # creation_date: 1975 # creator_name: Amancio Ortega Gaona # type_of_clothes: men, women, children, home # international_competitors: Gap, H&M, Benetton # number_stores: 7000 # major_color: France -> blue, Spain -> red, US -> pink, green brand = { 'name': 'Zara', 'creation_date': 1975, 'creator_name': 'Amancio Ortega Gaona', 'type_of_clothes': ['men', ' women', ' children', ' home'], 'international_competitors': ['Gap', 'H&M', 'Benetton'], 'number_stores': 7000, 'major_color': { 'France':'blue', 'Spain':'red', 'US' : ['pink', 'green'] } } # Change the number of stores to 2. brand['number_stores'] = 2 # Print a sentence that explains who the clients of Zara are. print('Our customers are:', '',''.join(brand['type_of_clothes'][:3])), # Add a key called country_creation with a value of Spain to brand brand["country_creation"] = 'Spain' if 'international_competitors' in brand: brand["international_competitors"].append('Desingual') else: brand['international_competitors'] = ['Desingual'] users = [ "Mickey", "Minnie", "Donald","Ariel","Pluto"] for name in users: if "i" in name and name[0] in ['M', 'P']: print(name)
c1161d513e39679c51f2e4fcfc55cf8828302101
mitchell-johnstone/PythonWork
/PE/P069.py
2,021
3.765625
4
# Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine # the number of numbers less than n which are relatively prime to n. # For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6. # # n Relatively Prime φ(n) n/φ(n) # 2 1 1 2 # 3 1,2 2 1.5 # 4 1,3 2 2 # 5 1,2,3,4 4 1.25 # 6 1,5 2 3 # 7 1,2,3,4,5,6 6 1.1666... # 8 1,3,5,7 4 2 # 9 1,2,4,5,7,8 6 1.5 # 10 1,3,7,9 4 2.5 # It can be seen that n=6 produces a maximum n/φ(n) for n ≤ 10. # # Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum. from UsefulFunctions import * import numpy from decorators import * def bruteForce(): max = 0 for i in range(2, 100000001): phi = i - 1 for j in range(phi, 1, -1): if gcd(i, j) > 1: phi -= 1 result = i / phi max = i if result > max else max print(max) spf = smallest_factors(1000001) print(spf) # The general formula to compute φ(n) is the following: # If the prime factorisation of n is given by n =p1^e1*...*pn^en, then φ(n) = n *(1 - 1/p1)* ... (1 - 1/pn). def phi(n): if spf[n] == n: return n - 1 factors = [] nt = n while nt != 1: factors += [spf[int(nt)]] nt //= spf[nt] factors = list(dict.fromkeys(factors)) # print(factors) for factor in factors: n *= (1 - (1 / factor)) return int(n + .5) def v1(): vals = [n / phi(n) for n in range(2, 1000001)] return vals.index(max(vals)) + 2 def v2(): maximum_result = 0 maximum_n = 0 for n in range(2, 1000001): result = n / phi(n) if result > maximum_result: maximum_result = result maximum_n = n return maximum_n @timer def main(): # print(phi(2)) # print(phi(3)) # print(phi(4)) # print(phi(5)) # print(phi(6)) # print(phi(7)) # print(phi(8)) # print(phi(9)) # print(phi(10)) print(v1()) if __name__ == '__main__': main()
6151aa62eda1ba641d891d6a2d130f681bf892d8
stuartses/AirBnB_clone
/models/amenity.py
340
3.734375
4
#!/usr/bin/python3 """Module: amenity This module define Amenity class Atributes: name (str): name of amenity """ from models.base_model import BaseModel class Amenity(BaseModel): """Class Amenity Inherits from BaseModel create class Amenity Atributes: name (str): name of amenity """ name = ""
dcff7c64de0769865aa4be9031857ae3864a87ea
Amarnath9962/Breakfast_Hotel_Bill-
/Tiffen_hotel_bill_Generation.py
3,695
3.5
4
from tkinter import * root = Tk() root.geometry('500x500') root.title('Billing Table') # Functions def Calculate(): Cust_name = Name_1.get() Idly_Qty = int(Idly_1.get())*5 Dosa_Qty = int(Dosa_1.get())*15 Upma_Qty = int(Upma_1.get())*25 Spl_Dosa_Qty = int(Spl_Dosa_1.get())*30 Tea_Qty = int(Tea_1.get())*7 Cofee_Qty = int(Cofee_1.get())*10 global Total Total=Idly_Qty+Dosa_Qty+Upma_Qty+Spl_Dosa_Qty+Tea_Qty+Cofee_Qty print('The Total Bill Amount is :',Total) def Generate_bill(): Cust_name = Name_1.get() Idly_Qty = int(Idly_1.get())*5 Dosa_Qty = int(Dosa_1.get())*15 Upma_Qty = int(Upma_1.get())*25 Spl_Dosa_Qty = int(Spl_Dosa_1.get())*30 Tea_Qty = int(Tea_1.get())*7 Cofee_Qty = int(Cofee_1.get())*10 print() print('The Customer Name is :',Cust_name) print('The Idly price is :',Idly_Qty) print('The Dosa Price is :',Dosa_Qty) print('The Upma Price is :',Upma_Qty) print('The Spl_Dosa price is :',Spl_Dosa_Qty) print('The Tea Price is :',Tea_Qty) print('The Cofee price is :',Cofee_Qty) print() print('The Total Bill Amount is :',Total) # Name Label Head = Label(root,text = "Billing Table",relief = 'solid',width = 25,bg = 'gray',font = ('arial',18,'italic')).place(x = 45,y = 15) Name = Label(root,text = "Customer Name :",font = ('arial',14,'italic')).place(x = 45,y = 65) Number_1 = Label(root,text = "1 . Idly ",font = ('arial',12,'italic')).place(x =45, y = 120) Number_2 = Label(root,text = "2 . Dosa ",font = ('arial',12,'italic')).place(x = 45, y = 160) Number_3 = Label(root,text = "3 . Upma ",font = ('arial',12,'italic')).place(x = 45,y = 200) Number_4 = Label(root,text = "4 . Spl Dosa " ,font = ('arial',12,'italic')).place(x = 45, y = 240) Number_5 = Label(root,text= "5 . Tea ",font = ('arial',12,'italic')).place(x = 45, y = 280) Number_6 = Label(root,text = "6 . Cofee ",font = ('arial',12,'italic')).place(x = 45,y = 320) va = StringVar() Terms = Label(root,text = "Terms and Conditions :",font = ('arial',12,'italic')).place(x = 45,y = 360) Check = Checkbutton(root,text = "I agree the terms and conditions",variable = va).place(x = 65, y = 400) Button_1 = Button(root,text = "Calculate Bill ",padx = 5,pady = 5,font = ('arial',12,'italic'),command = Calculate).place(x = 45,y = 440) Bill = Button(root,text = "Generate Bill",padx = 5,pady = 5,font = ('arial',12,'italic'),command = Generate_bill).place(x = 220,y = 440) New = StringVar() # Entry Label Name_1 = Entry(root,textvar = New,width = 25,borderwidth = 5) Name_1.place(x = 220,y = 70) Idly_1 = Entry(root,width = 5) Idly_1.place(x = 180,y = 120) Dosa_1 = Entry(root,width = 5) Dosa_1.place(x = 180,y = 160) Upma_1 = Entry(root,width = 5) Upma_1.place(x = 180,y = 200) Spl_Dosa_1 = Entry(root,width = 5) Spl_Dosa_1.place(x = 180,y = 240) Tea_1 = Entry(root,width = 5) Tea_1.place(x = 180,y = 280) Cofee_1 = Entry(root,width = 5) Cofee_1.place(x = 180,y = 320) #Price Idly_2 = Label(root,text = "Each Idly Rs = 5/-",font= ('arial',10,'italic')).place(x = 250,y = 120) Dosa_2 = Label(root,text = "Each Dosa Rs = 15/-",font= ('arial',10,'italic')).place(x = 250,y = 160) Upma_2 = Label(root,text = "One upma Rs = 25/-",font= ('arial',10,'italic')).place(x = 250,y = 200) Spl_Dosa_2 = Label(root,text = "Each SPl Dosa Rs = 30/-",font= ('arial',10,'italic')).place(x = 250,y = 240) Tea_2 = Label(root,text = "Each Tea Rs = 7/-",font= ('arial',10,'italic')).place(x = 250,y = 280) Cofee_2 = Label(root,text = "Each Cofee Rs = 10/-",font= ('arial',10,'italic')).place(x = 250,y = 320) root.mainloop()
013774f0fa13db3af7f995c1809eafa8d5ecb6b3
ameyyadav09/ML-Assignments
/custom utils/cat_conv.py
2,420
3.75
4
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer """ Given a Series object CountVectorizer is used to obtain a csr matrix and then it is converted as a pandas DataFrame and returned input: ser:Pandas Series output: Pandas DataFrame obtained after vectorizing """ def _vectorize(ser): column = ser.name # initializing countVectorizer vectorizer = CountVectorizer() # transforming the required feature vector into csr_matrix vectorizer.fit(ser) cdf = vectorizer.transform(ser) #create a dictionary to change the column names vals = {val: column+"_"+ val for val in np.unique(ser)} # replacing the column names into more redable format vals = [column+"_"+val for val in vectorizer.get_feature_names()] #converting csr_matrix to pandas DataFrame return pd.DataFrame(cdf.todense(), columns=vals) """ Given a Pandas DataFrame categorical features are identified and dummy encoding is performed on each individual feature and resultant DataFrame is returned input: df: Pandas DataFrame output: Pandas DataFrame after performing Dummy encoding """ def dummy_encoding(df): if not isinstance(df, pd.DataFrame): df = pd.DataFrame(df) num_df = df.select_dtypes(include=["object"]) df.drop(num_df.columns, axis = 1, inplace = True) for column in num_df.columns: temp_df = _vectorize(num_df[column]) num_df = pd.concat([num_df, temp_df], axis = 1) num_df.drop(column, axis = 1, inplace = True) df = pd.concat([df, num_df], axis = 1) return df """ input: Given a Pandas Dataframe categorical columns are identified and label encoding is applied on each individual column and resultant dataframe is returned df:Pandas DataFrame output: Pandas DataFrame after performing """ def cat_encoding(df): if not isinstance(df, pd.DataFrame): df = pd.DataFrame(df) cat_df = df.select_dtypes(include=["object"]) df.drop(cat_df.columns, axis = 1, inplace = True) res_df = pd.DataFrame() for column in cat_df.columns: uniq_dict = {i:val for val,i in enumerate(np.unique(cat_df[column]))} cat_df[column] = cat_df[column].map(uniq_dict) df = pd.concat([df, cat_df], axis = 1) return df # Test Script # df = pd.DataFrame({"a":["sss","bam","lam"],"b":[2,4,3],"c":[1,5,6],"d":["44a","asd","56asf7567"]}) # print(df) # print(cat_encoding(df))
a3bebc702725a87b56f55474aea8809a8db1726e
uvkrishnasai/algorithms-datastructures-python
/interviewcake/BalancedBinaryTree.py
2,095
4.125
4
class BinaryTreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right def is_balanced_recursion(root): heights = [] get_height(root, 0, heights) max_height = max(heights) min_height = min(heights) return True if max_height - min_height <= 1 else False def get_height(node, dept, heights): if not node.left and not node.right: heights.append(dept) return if node.left: get_height(node.left, dept+1, heights) if node.right: get_height(node.right, dept+1, heights) def is_balanced(root): if not root: return True nodes = [(root, 1)] min_, max_ = float("Inf"), float("-Inf") while nodes: node, dept = nodes.pop() if not node.left and not node.right: min_ = min_ if dept > min_ else dept max_ = max_ if dept < max_ else dept #print(node.value, min_, max_, dept) if node.left: nodes.append((node.left, dept+1)) if node.right: nodes.append((node.right, dept+1)) return True if max_-min_ <= 1 else False tree = BinaryTreeNode(5) left = tree.insert_left(8) right = tree.insert_right(6) left.insert_left(1) left.insert_right(2) right.insert_left(3) right.insert_right(4) result = is_balanced(tree) print(result) tree = BinaryTreeNode(3) left = tree.insert_left(4) right = tree.insert_right(2) left.insert_left(1) right.insert_right(9) result = is_balanced(tree) print(result) tree = BinaryTreeNode(6) left = tree.insert_left(1) right = tree.insert_right(0) right_right = right.insert_right(7) right_right.insert_right(8) result = is_balanced(tree) print(result) tree = BinaryTreeNode(1) right = tree.insert_right(2) right_right = right.insert_right(3) right_right.insert_right(4) result = is_balanced(tree) print(result)
88d6d52120fdeff0551067ccc0b5e72521b35137
neilsjlee/AlarmSystem
/ControlHub/priority_queue.py
1,600
3.875
4
# Implementing Priority Queue using List data type import threading class MyPriorityQueue: def __init__(self): self.queue_list = [] self.queue_size = 0 self.lock = threading.Lock() def put(self, task_type, priority, timestamp, address, data): self.p() i = 0 found_the_right_place = False current_queue_size = len(self.queue_list) if current_queue_size > 0: while (not found_the_right_place) and i < current_queue_size: if self.queue_list[i].priority > priority: found_the_right_place = True else: i = i + 1 self.queue_list.insert(i, QueueTask(task_type, priority, timestamp, address, data)) else: self.queue_list.append(QueueTask(task_type, priority, timestamp, address, data)) self.queue_size = self.queue_size + 1 self.v() def get(self): self.p() if len(self.queue_list) > 0: first_item = self.queue_list[0] self.queue_list.pop(0) self.queue_size = self.queue_size - 1 self.v() return first_item self.v() def length(self): return self.queue_size def p(self): self.lock.acquire() def v(self): self.lock.release() class QueueTask: def __init__(self, task_type, priority, timestamp, address, data): self.task_type = task_type self.priority = priority self.timestamp = timestamp self.address = address self.data = data
032deea49c29c887b574f27763c8a70716657231
sudbasnet/Leetcode-Practice
/splitArrayLargestSum.py
2,472
3.640625
4
class Solution: def splitArray(self, nums: [int], m: int) -> int: """ One of the solutions that I can think of is by considering multiple options but here, the branches could be too large. For example, I cant just consider every possibility, that would be absurd. how about we sum up everything and save the running sum first [7,2,5,10,8] runningSums = [7, 9, 14, 24, 32] say we take 7 then remaining woul be 32 - 7 = 25 say we take 9 so we got left 23 say we take 14, so we got left with 18 ??? not sure how to do it!!! might need to look at the hints """ """ one way would be to try every way the arrays could be split but that would be too time consuming after looking at the hints, i saw that we need to use binary search somehow so the idea has become, you find the max sum you can have, and the min sum you could have and basically do binary search to find the least point(maxsum) where the array can be broken into m pieces """ # maximum the array could sum up to largestPossible = 0 # the least value, max of the nums in the array lowestPossible = 0 for i in range(len(nums)): lowestPossible = max(lowestPossible, nums[i]) largestPossible += nums[i] while lowestPossible < largestPossible: mid = (largestPossible + lowestPossible)//2 if self.splitIntoPieces(nums, mid) > m: lowestPossible = mid + 1 else: '''there might be multiple ways to break the string into m parts but with larger sums, so we still recurse and not return mid, but instead we rescurse until we find the minimum sum one.''' largestPossible = mid return lowestPossible # or can return largestPossible, they are same at this point def splitIntoPieces(self, nums, maxSum): runningSum = 0 numberOfSplits = 1 # least is one, what we got as input for i in range(len(nums)): if runningSum + nums[i] > maxSum: numberOfSplits += 1 runningSum = nums[i] else: runningSum += nums[i] return numberOfSplits
f960aade75f2731a957fd78bedbe9cf4f9e3b19d
kumarnalinaksh21/Python-Practice
/Arrays/Palindrome problem.py
647
4.34375
4
################ Question ###################################### # "A palindrome is a string that reads the same forward and backward" # For example: radar or madam # Our task is to design an optimal algorithm for checking whether # a given string is palindrome or not! ################################################################ def check_palindrome_method(var_string): if var_string.casefold() == var_string[::-1].casefold(): print("True! The string is a palindrome") else: print("False The string is not a palindrome") if __name__ == "__main__": var_string = "Madam" check_palindrome_method(var_string)
d14b9b174ae386ba9ff36e36b08410c22f2d95f7
ErickBritoN/Aprendizados
/Python/Atividade1.py
364
3.6875
4
preco_pass = float(input("Preço da passagem: ")) num_pass = int(input("Numero de Passageiros: ")) especiais = int(input("NUmero de Passageiros especiais: ")) faturamento = float(preco_pass*num_pass) faturamento_espec = float((preco_pass*especiais)/2) faturamento_total = faturamento + faturamento_espec print("O faturamento da viagem foi %.2f"% faturamento_total)
6134378797364b29d35b133d70edbb7f7f3af9ad
Oyagoddess/PDX-Code-Guild
/learnpyex/ex35.py
4,241
4.28125
4
from sys import exit # importing the exit feature from system def gold_room(): # defines the function for the gold room print "This room is full of gold. How much do you take?" # ask for user input next = raw_input("> ") # collects user inputs if "0" in next or "1" in next: # creates conditions for user inputs to run if.. how_much = int(next) # collects a integer or number else: dead("Man, learn to type a number.") # this prints if user does not put in 0 or 1 number if how_much < 50: # creates condition for user inputs for how much if it is less than 50 print "Nice, you're not greedy, you win!" exit(0) # this exits the loop and stops else: # if users how much is more than 50 it prints dead("You greedy bastard!") def bear_room(): # defines a function for bear_room print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How are you going to move the bear?" # need more clarity on the relevance of the bear_moved expression bear_moved = False # set bear_moved false creates boolean test while True: # creates while loop for users input how they are moving the bear creates an infinite loop for this #until it reaches a false. or when they enter a correct option. next = raw_input("> ") # collects user input if next == "take honey": # creates condition to move bear dead("The bear looks at you then slaps your face off") # prints and calls dead function (Good Job!) elif next == "taunt bear" and not bear_moved: # creates condition if taunt bear and true (not false) print ("The bears has moved from the door. You can go through it now") bear_moved = True # reassigns bear_moved to True elif next == "taunt bear" and bear_moved: # if you taunt bear and bear moved true then dead("The bear gets pissed off and chews your leg off.") elif next == "open door" and bear_moved: # if user opens door and bear moves then they start gold_room gold_room() else: # if none of the user input applies then type print " I got no idea what that means" def cthulhu_room(): # defines a new function for cthulhu to run when called print "Here you see the great evil Cthulhu." print "He, it, whatever stares at you and you go insane" print "Do you flee for your life or eat your head?" next = raw_input("> ") if "flee" in next: # if user is flee then it goes to start function start() elif "head" in next: # if user inputs is head it prints dead value and well that ... dead("Well that was tasty!") else: # if user chooses neither then it calls cthulhu function to run again cthulhu_room() # not sure of the relevance of this function def dead(why): # creates a function to be called print why, "Good Job!" # it prints good job exit(0) # and it exits. def start(): # this is the start function to start and run the program print "You are in a dark room." print "There is a door to your right and left." print "Which one do you take?" next = raw_input("> ") # takes user input if next == "left": # conditions for user input bear_room() # if they choose left it will loop to the bear_room function elif next == "right": # if they choose right it loops to cthulhu_room function cthulhu_room() else: # if they choose neither and something else then it runs dead and ends. dead("You stumble around the room until you starve.") start() # this calls the whole game to run from start and runs through functions and loops """ study drill 1. map of the game start - begins the game and ask for options which door through room: bear room or cthulu room or gold rooms with what happens. 2. fixed mistakes 3. written comments two items i don't quite understand is the necessity for the dead function, and the bear_moved expression 4. 5. the bugs in typing a number with 0 or 1 in the gold room are that if you do numbers without it will keep saying it doesn't understand what that means. """
14fa85dc6110b79590cf0ebde52eb0660d29e63a
Quarant/pythong
/homework/lotto/lotto.py
1,475
3.59375
4
import random def num_len(num_list): if(len(num_list)<6): raise Exception(1,"fall to reach limit") elif(len(num_list)>6): raise Exception(2,"list exceeded limit") def dublicate_number(num_list): for i in num_list: if(num_list.count(i) > 1): raise Exception(3,"dublicate numbers") def range_of_number(num_list): for i in num_list: if(not(i>=1 and i<=49)): raise Exception(4,"number exceeded range") def get_numbers(): temp_list = [] for i in input("podaj liczby\n").strip().split(" "): if(len(i)>0): temp_list.append(int(i)) return temp_list def calculate_error(num_list): num_len(num_list) dublicate_number(num_list) range_of_number(num_list) def calculate_winners(num_list): temp_list = [] while len(temp_list) < 6: r=random.randint(1,49) if(not(temp_list.count(r)>0)): temp_list.append(r) hits=0 for i in num_list: for j in temp_list: if(i==j): hits+=1 return hits,temp_list def main(): nr = get_numbers() try: calculate_error(nr) except Exception as e: code,reason = e.args print("an error was cought \n{}".format(reason)) exit(code) hits,num = calculate_winners(nr) print("""Your Numbers was {} \nLucky Numbers Was {}\nAnd you hit {} times!""".format(nr,num,hits)) if __name__=="__main__": main()
f1811d48129a36d55f8442de3ad719184e720901
nightwolfer1/NUMA01-Numerical-analysis-with-python
/Task_Lecture_10.py
2,121
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 8 10:50:46 2020 @author: nightwolfer """ import numpy as np import matplotlib.pyplot as plt #Task 1 x_val=np.linspace(-10,10,100) #make a list of resulting values of the polynomial x**3+x y=list(map(lambda x:x**3+x , x_val)) #derivateive of pol 3x**2+1 dydx=list(map(lambda x:3*x**2+1,x_val)) fig,ax = plt.subplots() ax.plot(x_val,y,'red') ax.plot(x_val,dydx,'green') ax.set_title('Task 1') #Task 2 #insection point is when the function changes sign going from negative to positive. (cureve goes from concave to convex) #this happens at x= 0 so lets plot between -2 and 2 fig,ax2 = plt.subplots() ax2.plot(x_val,y,'red') ax2.plot(x_val,np.linspace(-0.2,0.2,100),ls='-.',lw=0.5, color='black')#Tankent ax2.set_xlim([-2,2]) ax2.set_ylim([-20,20]) ax2.set_title('Task 2') #Task 3,4,5,6,7,8 Doing the same for extreme values, chaging polynomial to contain extreme values x_val2=np.linspace(-2,2,100) #make a list of resulting values of the polynomial x**3-2x y2=list(map(lambda x:x**3-2*x, x_val2)) #derivateive of pol 3x**2-2 dydx2=list(map(lambda x:3*x**2-2,x_val2)) fig,ax3 = plt.subplots() ax3.plot(x_val2,y2,'red') ax3.plot(x_val2,dydx2,'black',lw=4) ax3.plot(x_val2[20:45],np.linspace(y2[29],y2[29],25),ls='-.',lw=0.5, color='black') ax3.plot(x_val2[60:85],np.linspace(y2[70],y2[70],25),ls='-.',lw=0.5, color='black') ax3.set_title('Task 3-8') ax3.set_xticks([x_val2[29],0,x_val2[70]]) ax3.set_xticklabels([str(x_val2[29]),str(0),str(x_val2[70])]) ax3.annotate('local max',xy=(x_val2[29],y2[29]),xytext=(x_val2[29]+1,y2[29]+1),arrowprops=dict(facecolor='black',shrink=0.05)) ax3.annotate('local min',xy=(x_val2[70],y2[70]),xytext=(x_val2[70]+1,y2[70]+1),arrowprops=dict(facecolor='black',shrink=0.05)) #From regular plots we can se that one extreme value is around x=-0.7 and the other around x=0.7 #search the local max at around -1,5 to 0 max_l_pos=np.array(y2[25:50]).argmax()+25 print(max_l_pos)# 29 min_r_pos=np.array(y2[55:80]).argmin()+55 print(min_r_pos)# 70 #Task 9 plt.savefig('Task_save.png')
84ec03686f4c9ba9c54f5f92c3ef3ddb029a5294
wsjung/2017Challenges
/challenge_3/python/wjung/src/challenge_3.py
213
3.625
4
array = [2,2,3,7,5,7,7,7,4,7,2,7,4,5,6,7,7,8,6,7,7,8,10,12,29,30,19,10,7,7,7,7,7,7,7,7,7] def findMajority(array=[]): for n in array: if array.count(n) >= len(array)/2: print n break findMajority(array)
9049dcc8b9cb24fbe3a6feed1365701be17ff544
grock2015/python
/separarTuplas.py
447
4.1875
4
# -*- coding: utf-8 -*- # Definindo as variaveis minha_tupla = (1,0.3,"vasco") # Funcao que checa o tipo do elemento e o adiciona a lista correta # que é convertida em tupla ao final def separarTuplas(tupla): tupla_string = [] tupla_outros = [] for item in tupla: if type(item) == str: tupla_string.append(item) else: tupla_outros.append(item) return tuple(tupla_outros), tuple(tupla_string) print separarTuplas(minha_tupla)
22f180585c535a04ce138c3afddda52463479d28
Rostyk1404/Codewars
/What time is it?.py
1,188
4.21875
4
""" Kata source : https://www.codewars.com/kata/converting-12-hour-time-to-24-hour-time/train/python Given a time in AM/PM format as a string, convert it to military (24-hour) time as a string. Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock Sample Input: 07:05:45PM Sample Output: 19:05:45 Try not to use built in DateTime libraries. For more information on military time, check the wiki https://en.wikipedia.org/wiki/24-hour_clock#Military_time Sample Tests: Test.assert_equals(get_military_time('12:00:01AM'), '00:00:01') Test.assert_equals(get_military_time('11:46:47PM'), '23:46:47') """ from datetime import datetime def get_military_time(time): return datetime.strptime(time, "%I:%M:%S%p").strftime("%H:%M:%S") def get_military_time2(time): if time[:2] == "12" and time[-2:] == "AM": return "00" + time[2:-2] elif time[-2:] == "AM": return time[:-2] elif time[:2] == "12" and time[-2:] == "PM": return time[:-2] else: return str(int(time[2:]) + 12) + time[2:8]
e6feabccacae15ed66205deb0bf4724d79b0b10f
hytim/SegDL
/Viz/demo05.py
459
3.671875
4
#语义分割之图片和 mask 的可视化 #https://www.aiuai.cn/aifarm276.html import cv2 import matplotlib.pyplot as plt imgfile = 'image.jpg' pngfile = 'mask.png' img = cv2.imread(imgfile, 1) mask = cv2.imread(pngfile, 0) contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(img, contours, -1, (0, 0, 255), 1) img = img[:, :, ::-1] img[..., 2] = np.where(mask == 1, 255, img[..., 2]) plt.imshow(img) plt.show()
0e15002cb2966234e7aecd129f6921f10c4742db
wilsonify/euler
/src/euler_python_package/euler_python/easiest/p035.py
1,186
4.03125
4
""" The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ from euler_python.utils import eulerlib def count_circular_primes(upper_bound=999999): """ The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ is_prime = eulerlib.list_primality(upper_bound) def is_circular_prime(input_n): n_string = str(input_n) return all( is_prime[int(n_string[i:] + n_string[:i])] for i in range(len(n_string)) ) ans = sum(1 for i in range(len(is_prime)) if is_circular_prime(i)) return ans def problem035(): """ :return: """ return count_circular_primes(upper_bound=999999) if __name__ == "__main__": print(problem035())
095eacb0f416f38570e083badc5a2f8d257f252f
katelevshova/py-algos-datastruc
/Course1/p5_set_possible_telemarketers.py
7,784
3.9375
4
""" Read file into texts and calls. """ import csv from enum import Enum with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 5: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ class TelTypes(Enum): not_valid = 0 fixed_line = 1 mobile = 2 telemarketer = 3 possible_telemarketers_set = set() verification_set = set() ''' Checks all items in calls list. For each item checks the type of the number called. If the caller number does not exists in the verification_set we add it to the possible_telemarketers_set. We verify the answered number and add it to verification_set. If answered number exists in possible_telemarketers_set we discard it because the telemarketer number cannot answer the calls. ''' def check_calls_data(calls_list): possible_telemarketers_set.clear() verification_set.clear() for item in calls_list: # add the caller tel number as possible telemarketer if item[0] not in verification_set: possible_telemarketers_set.add(item[0]) # check the answering tel_number verify_tel_number(item[1]) ''' Checks all items in texts list. For each item checks the type of the number sent message and received. If it is a telemarketer format, we remove the number from possible_telemarketers_set because telemarketers only call but never send or receive text messages. ARGS: texts_list (list) - list of lists. Example: [["78130 00821", "90365 06212", "1/9/2016 6:46:56 AM"], ["78130 00821", "90365 06212", "1/9/2016 6:46:56 AM"]] ''' def check_texts_data(texts_list): if len(possible_telemarketers_set) == 0: raise Exception("->check_texts_data: you need to call check_texts_data() " "after check_calls_data() to fill in the possible_telemarketers_set") for item in texts_list: verify_tel_number(item[0]) # checking the sending texts tel_number verify_tel_number(item[1]) # checking the receiving texts tel_number ''' Takes the telephone number, adds it into verification_set and if such telephone number exists in possible_telemarketers_set deletes it. ARGS: tel_number (string) ''' def verify_tel_number(tel_number): # telemarketers never send and receive texts so if the number is found and it exists # in the possible_telemarketers_set we need to delete it because it is not considered a telemarketer verification_set.add(tel_number) possible_telemarketers_set.discard(tel_number) ''' Creates possible_telemarketers_set based on the data from 2 files - calls.csv and texts.csv ''' def create_telemarketers_set(): check_calls_data(calls) check_texts_data(texts) def print_sorted_telemarketers_new_line(): # print("length of possible_telemarketers_set = {}".format(len(possible_telemarketers_set))) print("These numbers could be telemarketers: ") print(*sorted(possible_telemarketers_set), sep='\n') # in lexicographic order with no duplicates def main(): create_telemarketers_set() print_sorted_telemarketers_new_line() # TEST CASES---------------------------------------------- def test_check_calls_data(): print("---------------------------------------------") print("->test_check_calls_data:start") test_calls_list = [["7777 77777", "99999 99999", "1/9/2016 6:46:56 AM", "165"], ["44444 4444", "55555 55555", "1/9/2016 6:46:56 AM", "165"], ["66666 6666", "7777 77777", "1/9/2016 6:46:56 AM", "165"], ["1403333333", "(080)111111", "1/9/2016 7:31", "15"]] check_calls_data(test_calls_list) print("verification_set=" + str(verification_set)) assert len(verification_set) == 4 assert ("99999 99999" in verification_set) assert ("55555 55555" in verification_set) assert ("7777 77777" in verification_set) assert ("(080)111111" in verification_set) print("possible_telemarketers_set=" + str(possible_telemarketers_set)) assert len(possible_telemarketers_set) == 3 assert ("44444 4444" in possible_telemarketers_set) assert ("66666 6666" in possible_telemarketers_set) assert ("1403333333" in possible_telemarketers_set) assert ("7777 77777" not in possible_telemarketers_set) print("->test_check_calls_data: is finished") def test_check_check_texts_data(): print("---------------------------------------------") print("->test_check_check_texts_data:start") test_texts_list = [["1401111111", "90365 06212", "1/9/2016 6:03:22 AM"], ["(04456)69245029", "(080)787878", "1/9/2016 7:31"], ["44444 4444", "0000 00000", "1/9/2016 6:46:56 AM", "165"], ["78130 00821", "66666 6666", "1/9/2016 7:31"]] print("possible_telemarketers_set=" + str(possible_telemarketers_set)) check_texts_data(test_texts_list) print("verification_set=" + str(verification_set)) assert len(verification_set) == 12 # we add sending and receiving msg to verification list assert ("1401111111" in verification_set) assert ("0000 00000" in verification_set) assert ("44444 4444" in verification_set) # 44444 4444 and 66666 6666 not must be removed from possible_telemarketers_set print("after removing numbers from TEXTS file, possible_telemarketers_set=" + str(possible_telemarketers_set)) assert len(possible_telemarketers_set) == 1 assert ("44444 4444" not in possible_telemarketers_set) # should be deleted assert ("66666 6666" not in possible_telemarketers_set) # should be deleted assert ("1403333333" in possible_telemarketers_set) print("->test_check_check_texts_data: is finished") def test_verify_tel_number(): print("---------------------------------------------") print("->test_verify_tel_number:start") test_calls_list = [["7777 77777", "99999 99999", "1/9/2016 6:46:56 AM", "165"], ["44444 4444", "55555 55555", "1/9/2016 6:46:56 AM", "165"], ["66666 6666", "7777 77777", "1/9/2016 6:46:56 AM", "165"], ["1403333333", "(080)111111", "1/9/2016 7:31", "15"]] check_calls_data(test_calls_list) print("possible_telemarketers_set=" + str(possible_telemarketers_set)) # case1 - check any not existed number verify_tel_number("1408888888") assert ("1408888888" not in possible_telemarketers_set) # must be deleted assert ("1408888888" in verification_set) # must be added for verification assert len(possible_telemarketers_set) == 3 print("case1: possible_telemarketers_set=" + str(possible_telemarketers_set)) # case2 - check existed number among callers verify_tel_number("66666 6666") assert ("66666 6666" in verification_set) assert ("66666 6666" not in possible_telemarketers_set) assert len(possible_telemarketers_set) == 2 print("case2: possible_telemarketers_set=" + str(possible_telemarketers_set)) print("->test_check_check_texts_data: is finished") def test(): print("START ALL TESTS....") test_check_calls_data() test_check_check_texts_data() test_verify_tel_number() print("ALL TESTS FINISHED....") # ---------------------------------------------------------- # test() main()
99ca8f843e217582f1df12212a811272f59c7574
emirot/algo-loco.blog
/algorithms/sorting/quick_sort.py
434
4
4
def quick_sort(arr): if len(arr) < 2: return arr z = (len(arr)-1) // 2 pivot = arr[z] left = [i for i in arr if i < pivot] right = [i for i in arr if i > pivot] return quick_sort(left) + [pivot] + quick_sort(right) if __name__ == '__main__': arr = [-4, 3, 2, 1, 10, 9] z = quick_sort(arr) arr = [100, -4,20, 3, -30, 2, 8, 1, 10, 9] z = quick_sort(arr) print("z:", z)
65343486561d6145d17de698787500a2749d7fb1
RicardoAugusto-RCD/exercicios_python
/exercicios/ex004.py
962
4.1875
4
# Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possiveis # sobre ele. print('-'*20) leia = input('Escreva algo: ') print('-'*20) print('O tipo primitivo do valor {} é'.format(leia), type(leia)) print('-'*20) print('{}, é um múmero?'.format(leia), leia.isnumeric()) print('-'*20) print('{}, é um digito?'.format(leia), leia.isdigit()) print('-'*20) print('{}, é alfabético?'.format(leia), leia.isalpha()) print('-'*20) print('{}, é alfanumérico?'.format(leia), leia.isalnum()) print('-'*20) print('{}, está em maiúsculas?'.format(leia), leia.isupper()) print('-'*20) print('{}, está em minúsculas?'.format(leia), leia.islower()) print('-'*20) print('{}, só tem espaços?'.format(leia), leia.isspace()) print('-'*20) print('{}, está capitalizada?'.format(leia), leia.istitle()) print('-'*20) print('{}, é imprimível?'.format(leia), leia.isprintable()) print('-'*20)
78ef753e2d7a894eb3268bab611755d0c0df53a2
RennanFelipe7/algoritmos20192
/Lista 3/lista03ex08.py
525
4.0625
4
print("Digite dois numeros, lembrando que o primeiro numero tem que ser menor que o segundo, a diferença entre os dois numeros tem que ser maior que 1, e esses dois numeros também não pode ser iguais.") MenorNumero = int(input("Qual o menor numero do intervalo? ")) MaiorNumero = int(input("Qual o maior numero do intervalo? ")) MaiorNumero = MaiorNumero - 1 while MenorNumero < MaiorNumero: MenorNumero = MenorNumero + 1 if MenorNumero // 1 == MenorNumero: Intervalo = MenorNumero print(Intervalo)
aab1f0ec1331b59ed783eb966f28244945756d12
kate2797/password-manager
/delete_by_website.py
715
4.25
4
import sqlite3 import os def delete(): # connect to db connect_to_db = sqlite3.connect('database.db') c = connect_to_db.cursor() user_input = input("Password for which website you want to delete? ") print(">> WARNING <<") confirm = input("Whole database entry will be deleted, not just the password.\nDo you still want to continue? (y/n): ") if confirm == "y": c.execute("""DELETE FROM passwords WHERE website = ? """, (user_input,)) connect_to_db.commit() connect_to_db.close() print("Your password was successfully deleted \n") input("Press Enter to Exit") else: input("Press Enter to Exit") return
e45d70bdf8936a3c80da80a653654581821883b0
abbindustrigymnasium/Python-kompendium_Vicfag
/5_If_satser.py
1,725
3.65625
4
# print('Vilket kön har du?') # kön=input() # print('Vilken hårfärg har du?') # hårfärg=input() # print('Vilken ögonfärg har du?') # ögonfärg=input() # daniel_radcliff=['man','brun','brun','Daniel Radcliff'] # rupert_grint=['man','röd','blå','Rupert Grint'] # emma_watson=['kvinna','brun','brun','Emma Watson'] # selena_gomez=['kvinna','brun','brun','Selena Gomez'] # kändis=[daniel_radcliff,rupert_grint,emma_watson,selena_gomez] # for personer in kändis: #kollar om din information är lika som någon av personerna # if kön == personer[0]: # if hårfärg == personer[1]: # if ögonfärg == personer[2]: # print('Du är lik:', personer[3]) # #5.2 # namn = input('Ange ditt namn:') # ålder = int(input('Ange ditt ålder:')) # behov=[14,13,12,11.5,11,11,10.5,10,10,10,9.5,9,9,9,8.5,8] # if ålder < 17: # om åldern är under 17 går den efter listan,annars 8h # h=behov[ålder-1] #tar åldern man skriver in -1 för att få rätt plats i listan # else: # h=8 # print('Hej',namn,', du borde sova', h ,'timmar') # 5.3 # land=input('Skriv ett land:') # land=land.capitalize() # för att få första bokstäven stor # norden=['Danmark','Finland','Island','Norge','Sverige'] # stor=['England','Nordirland','Skottland','Wales'] # if land in norden: #om landet man skriver in ligger i listan norden säger den det # print('Ditt land ligger i Norden!') # elif land in stor: #om landet man skriver in ligger i listan stor säger den det # print('Ditt land ligger i Storbrittanien!') # else: # print('Ditt land ligger varken i Norden eller Storbrittanien') #om det man skriver in inte finns i någon av listorna säger den att landet ligger i varken eller
1db49111f14dc7429d1dabb12d233301f4042572
Sbenaventebravo/AdhGestionFichas
/Clases/DTO.py
21,875
3.59375
4
# -*- coding: cp1252 -*- from datetime import datetime, date import re def formatoAtributoInforme(cadena,largo): listaCandena= list(cadena) for i in range(largo - len(cadena)): listaCandena.append(" ") return "".join(listaCandena) class Caracteristica(object): "Clase que representa una Caracteristica de una etiqueta" def __init__(self,proveedor): "Constructor de la clase Caracteristica" self.__proveedor = str(str(proveedor)).upper() def getProveedor(self): return self.__proveedor pass def setProveedor(self,proveedor): if len(proveedor) is 0: raise Exception('El proveedor no puede estar vacio') else: self.__proveedor = str(proveedor).upper() class Categoria: def __init__(self,nombre =" "): self.__idCategoria = -1 self.__nombre = nombre def getIdCategoria(self): return self.__idCategoria def setIdCategoria(self, idCategoria): self.__idCategoria = idCategoria def getNombre(self): return self.__nombre def setNombre(self, nombre): if(len(nombre) is 0): raise Exception("El nombre no puede estar vacio") else: self.__nombre = str(nombre).upper() def __str__(self): res = "Informacion de Categoria\n=================\nNombre:{0}".format(self.getNombre()) return res class Cliente: def __init__(self, rut = " ", nombre = " "): self.__idCliente = -1 self.__rut = rut self.__nombre = nombre def getIdCliente(self): return self.__idCliente def setIdCliente(self,idCliente): self.__idCliente = idCliente def getRut(self): return self.__rut def setRut(self,rut): rut = str(rut).upper() if len(rut) is 0: raise Exception("El rut no puede estar vacio") resultado = re.match("^([0-9]+-[0-9K])",rut) if not bool(resultado): raise Exception("El rut es invalido, intente nuevamente") else: self.__rut = rut def getNombre(self): return self.__nombre def setNombre(self,nombre): if(len(nombre) is 0): raise Exception("El nombre nos puede estar vacio") else: self.__nombre = str(nombre).upper() def __str__(self): res = "Datos Cliente\n"+"=======================\nRut:{0}\nNombre:{1}".format( str(self.getRut()), str(self.getNombre()) ) return res; class AdhesivoColdFoil(Caracteristica): "Clase que representa un tipo de Caracteristica de una etiqueta, Caracteristica Adhesivo Cold Foil" def __init__(self,proveedor="",anilox="", hotstamping = False): "Constructor de la clase AdhesivoColdFoil" Caracteristica.__init__(self, proveedor) self.__idAdhCoFo = -1 self.__anilox = str(anilox) pass "Encapsulamiento de atributos" def getIdAdhCoFo(self): return self.__idAdhCoFo def setIdAdhCoFo(self, value): self.__idAdhCoFo = value def getAnilox(self): return self.__anilox pass def setAnilox(self, anilox): self.__anilox = str(anilox).upper() def __str__(self): res = "{0}\t{1}\n\n".format( str(formatoAtributoInforme(self.getProveedor(), 30)), str(formatoAtributoInforme(str(self.getAnilox()), 8))) return res def listaAdhCoFo(self): lista = list() lista.append(self.getProveedor()) lista.append(str(self.getAnilox())) return lista class AdhesivoLaminacion(Caracteristica): "Clase que representa un tipo de Caracteristica de una etiqueta, Caracteristica Adhesivo Laminacion" def __init__(self,proveedor = "",anilox = ""): "Constructor Clase Adhesivo Laminacion" Caracteristica.__init__(self,proveedor) self.__idAdhLam = -1 self.__anilox = anilox "Encapsulamiento de atributos" def getIdAdhLam(self): return self.__idAdhLam def setIdAdhLam(self, value): self.__idAdhLam = value def getAnilox(self): return self.__anilox pass def setAnilox(self, anilox): if len(anilox) is 0: raise Exception('El anilox no puede estar vacio') else: self.__anilox = str(anilox).upper() def getAdhLam(self): return self.__idAdhLam def setAdhLam(self, value): self.__idAdhLam = value pass def __str__(self): res = "{0}\t{1}\n\n".format( str(formatoAtributoInforme(self.getProveedor(), 30)), str(formatoAtributoInforme(self.getAnilox(), 20))) return res pass def listaAdhLam(self): lista = list() lista.append(self.getProveedor()) lista.append(self.getAnilox()) return lista class ColdFoil(Caracteristica): "Clase que representa un tipo de Caracteristica de una etiqueta, Caracteristica Cold Foil" def __init__(self,proveedor = "",ancho = -.1, tipo = False ): "Constructor de la clase Cold Foil" Caracteristica.__init__(self, proveedor) self.__idColdFoil = -1 self.__ancho = float(ancho) self.__tipo = tipo "Encapsulamiento de atributos" def getIdColdFoil(self): return self.__idColdFoil pass def setIdColdFoil(self, value): self.__idColdFoil = value pass def getAncho(self): return self.__ancho def setAncho(self, ancho): if ancho <= 0: raise Exception('El ancho debe ser mayor a 0') else: self.__ancho = float(ancho) def getTipo(self): return self.__tipo def setTipo(self, tipo): self.__tipo = bool(tipo) def __str__(self): res = "{0}\t{1}\n\n".format( str(formatoAtributoInforme(self.getProveedor(), 30)), str(formatoAtributoInforme(str(self.getAncho()), 8)), str(formatoAtributoInforme(str(self.getTipo(), 8)))) return res pass def listaColdFoil(self): lista = list() lista.append(self.getProveedor()) lista.append(str(self.getAncho())) return lista class FilmMicronaje(Caracteristica): "Clase que representa un tipo de Caracteristica de una etiqueta, Caracteristica Film Micronaje" def __init__(self,proveedor = "", ancho = -.1): Caracteristica.__init__(self, proveedor) self.__idFilmMi = -1 self.__ancho = float(ancho) pass "Encapsulamiento de atributos" def getIdFilmMi(self): return self.__idFilmMi pass def setIdFilmMi(self, value): self.__idFilmMi = value pass def getAncho(self): return self.__ancho pass def setAncho(self, ancho): if ancho <= 0: raise Exception('El ancho debe ser mayor a 0') else: self.__ancho = float(ancho) def __str__(self): res = "{0}\t{1}\n\n".format( str(formatoAtributoInforme(self.getProveedor(), 30)), str(formatoAtributoInforme(str(self.getAncho()), 8))) return res pass def listaFilmMi(self): lista = list() lista.append(self.getProveedor()) lista.append(str(self.getAncho())) return lista class Malla: "Clase que representa la malla de un etiqueta" def __init__(self, tipo = "", interno = False): "Constructor de la clase Malla" self.__idMalla = -1 self.__tipo = tipo self.__interno = interno "Encapsulamiento tipo" def getIdMalla(self): return self.__idMalla pass def setIdMalla(self, value): self.__idMalla = value pass def getTipo(self): return self.__tipo def setTipo(self, tipo): if len(tipo) is 0: raise Exception('El tipo no puede estar vacio') else: self.__tipo = str(tipo).upper() "Encapsulamiento interno" def getInterno(self): return self.__interno def setInterno(self, interno): self.__interno = interno def __str__(self): res = "{0}\t{1}\n\n".format( str(formatoAtributoInforme(self.getTipo(), 20)), str(formatoAtributoInforme(self.getInterno(), 20)), ) return res def listaMalla(self): lista = list() lista.append(self.getTipo()) interno = "Externo" if self.getInterno() == True: interno = "Interno" lista.append(interno) return lista class Material: "Clase que representa un material dentro de una etiqueta" def __init__(self,codigo = " ",nombre = "",proveedor = " " ,ancho = -1,TC = False): "Constructor dentro de la clase material" self.__idMaterial = -1 self.__codigo = codigo self.__nombre = nombre self.__proveedor = proveedor self.__ancho = float(ancho) self.__TC = TC #Encapsulamiento para codigo def getIdMaterial(self): return self.__idMaterial def setIdMaterial(self,value): self.__idMaterial = value pass def getCodigo(self): return self.__codigo def setCodigo(self,codigo): if len(codigo) is 0: raise Exception('El Codigo no puede estar vacio') else: self.__codigo = str(codigo).upper() def getNombre(self): return self.__nombre def setNombre(self, nombre): if len(nombre) is 0: raise Exception('El Nombre no puede estar vacio') else: self.__nombre = str(nombre).upper() #Encapsulamiento para proveedor def getProveedor(self): return self.__proveedor def setProveedor(self,proveedor): if len(proveedor) is 0: raise Exception('El Proveedor no puede estar vacio') else: self.__proveedor = str(proveedor).upper() #Encapsulamiento para ancho def getAncho(self): return self.__ancho def setAncho(self,ancho): if(ancho <= 0): raise Exception('El ancho debe ser mayor a 0') else: self.__ancho = float(ancho) #Encapsulamiento TC def getTC(self): return self.__TC def setTC(self,TC): self.__TC = TC def __str__(self): res = "{0}\t{1}\t{2}\t{3}\t{4}\n".format( str(formatoAtributoInforme(str(self.getCodigo()), 20)), str(formatoAtributoInforme(str(self.getNombre()), 20)), str(formatoAtributoInforme(str(self.getProveedor()), 30)), str(formatoAtributoInforme(str(self.getAncho()), 8)), str(formatoAtributoInforme(str(self.getTC()), 6))) return res pass def listaMaterial(self): lista = list() lista.append(self.getCodigo()) lista.append(self.getNombre()) lista.append(self.getProveedor()) lista.append(str(self.getAncho())) tc = "NO" if self.getTC() == True: tc = "SI" lista.append(tc) return lista class Maquina: "Clase que representa a la maquina que hace la etiqueta" def __init__(self,codigo= " ", velocidad = " "): self.__idMaquina = -1 self.__codigo = codigo def getIdMaquina(self): return self.__idMaquina pass def setIdMaquina(self, idMaquina): self.__idMaquina = idMaquina def getCodigo(self): return self.__codigo def setCodigo(self,codigo): if len(codigo) is 0: raise Exception("El codigo no puede estar vacio") else: self.__codigo = str(codigo).upper() def __str__(self): return "Informacion Maquina\n====================\nCodigo:{0}\n".format(str(self.getCodigo())) class Tinta: "Clase que representa una tinta para la elaboracion de una etiqueta" def __init__(self,color = "", tipo = "",anilox = "",proveedor1 = "",proveedor2 = "NO" ,proveedor3 = "NO"): "Constructor de la clases tinta" self.__idTinta = -1 self.__color = color self.__tipo = tipo self.__anilox = anilox self.__proveedor1 = proveedor1 self.__proveedor2 = proveedor2 self.__proveedor3 = proveedor3 "Encapsulamiento de atributos" def getIdTinta(self): return self.__idTinta def setIdTinta(self, value): self.__idTinta = value def getColor(self): return self.__color; def setColor(self,color): if len(color) is 0: raise Exception('El Color no puede estar vacio') else: self.__color = str(color).upper() def getTipo(self): return self.__tipo def setTipo(self,tipo): if len(tipo) is 0: raise Exception('El tipo no puede estar vacio') else: self.__tipo = str(tipo).upper() def getAnilox(self): return self.__anilox def setAnilox(self,anilox): if len(anilox) is 0: raise Exception('El anilox no puede esta vacio') else: self.__anilox = str(anilox).upper() def getProveedor1(self): return self.__proveedor1 def setProveedor1(self, proveedor1): if len(proveedor1) is 0: raise Exception('El Proveedor 1 no puede estar vacio') else: self.__proveedor1 = str(proveedor1).upper() def getProveedor2(self): return self.__proveedor2 def setProveedor2(self, proveedor2): self.__proveedor2 = str(proveedor2).upper() def getProveedor3(self): return self.__proveedor3 def setProveedor3(self, proveedor3): self.__proveedor3 = str(proveedor3).upper() def __str__(self): res = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\n\n".format( str(formatoAtributoInforme(str(self.getColor()), 20)), str(formatoAtributoInforme(str(self.getTipo()), 20)), str(formatoAtributoInforme(str(self.getAnilox()), 20)), str(formatoAtributoInforme(str(self.getProveedor1()), 30)), str(formatoAtributoInforme(str(self.getProveedor2()), 30)), str(formatoAtributoInforme(str(self.getProveedor3()), 30)) ) return res def listaTinta(self): lista = list() lista.append(self.getColor()) lista.append(self.getTipo()) lista.append(self.getAnilox()) lista.append(self.getProveedor1()) lista.append(self.getProveedor2()) lista.append(self.getProveedor3()) return lista class TipoBarniz(Caracteristica): "Clase que representa un tipo de Caracteristica de una etiqueta, Caracteristica Tipo Barniz" def __init__(self, tipo = "",proveedor = "",anilox = ""): "Constructor de la clase Tipo Barniz", Caracteristica.__init__(self, proveedor) self.__idTBarniz = -1 self.__tipo = tipo self.__anilox = anilox pass "Encapsulamiento de atributos" def getIdTBarniz(self): return self.__idTBarniz def setIdTBarniz(self, value): self.__idTBarniz = value def getTipo(self): return self.__tipo pass def setTipo(self, tipo): if len(tipo) is 0: raise Exception('El Tipo no puede estar vacio') else: self.__tipo = str(tipo).upper() def getAnilox(self): return self.__anilox pass def setAnilox(self, anilox): if len(anilox) is 0: raise Exception('El anilox no puede estar vacio') else: self.__anilox = str(anilox).upper() def __str__(self): res = "{0}\t{1}\t{2}\n\n".format( str(formatoAtributoInforme(self.getProveedor(), 30)), str(formatoAtributoInforme(self.getTipo(), 8)), str(formatoAtributoInforme(self.getAnilox(), 20))) return res pass def listaTBarniz(self): lista = list() lista.append(self.getProveedor()) lista.append(str(self.getTipo())) lista.append(str(self.getAnilox())) return lista class Troquel(Caracteristica): "Clase que representa un tipo de Caracteristica de una etiqueta, Caracteristica Troquel" def __init__(self,proveedor = "",observacion = ""): "Constructor de la clase Troquel" Caracteristica.__init__(self, proveedor) self.__idTroquel = -1 self.__observacion = observacion pass "Encapsulamiento de atributos" def getIdTroquel(self): return self.__idTroquel def setIdTroquel(self, value): self.__idTroquel = value def getTroquel(self): return self.__idTroquel pass def setTroquel(self, value): self.__idTroquel = value pass def getObservacion(self): return self.__observacion pass def setObservacion(self, value): self.__observacion = str(value).upper() pass def __str__(self): res = "{0} {1}\n\n".format( str(formatoAtributoInforme(self.getProveedor(), 30)) , str(formatoAtributoInforme(self.getObservacion(), 120)) ) return res pass def listaTroquel(self): lista = list() lista.append(str(self.getProveedor())) lista.append(str(self.getObservacion())) return lista class FichaTecnica: "Clase que representa un ficha tecnica de una etiqueta" def __init__(self, pedido="", etiqueta=" ", fecha=date.today(), clisse=False, velocidad=-1): "Contructor de la clase ficha tecnica" self.__idFicha = -1 self.__pedido = pedido self.__etiqueta = etiqueta self.__fecha = fecha self.__clisse = clisse self.__velocidad = velocidad self.__idCategoria = -1 self.__idCliente = -1 self.__idMaquina = -1 "Encapsulamiento atributos" def getIdFicha(self): return self.__idFicha pass def setIdFicha(self, value): self.__idFicha = value pass def getPedido(self): return self.__pedido def setPedido(self, pedido): if len(pedido) is 0: raise Exception("El pedido no puede estar vacio") else: self.__pedido = str(pedido).upper() def getEtiqueta(self): return self.__etiqueta def setEtiqueta(self, etiqueta): if len(etiqueta) is 0: raise Exception("La etiqueta no puede estar vacia") else: self.__etiqueta = str(etiqueta).upper() def getFecha(self): return self.__fecha def setFecha(self, fecha): fechaf = datetime.strptime(fecha, "%d/%m/%Y").date() self.__fecha = fechaf def getClisse(self): return self.__clisse def setClisse(self, value): self.__clisse = value def getVelocidad(self): return self.__velocidad def setVelocidad(self, velocidad): if velocidad <= 0.0: raise Exception("la velocidad debe ser mayor a 0") else: self.__velocidad = velocidad def getIdCategoria(self): return self.__idCategoria pass def setIdCategoria(self, value): self.__idCategoria = value pass def getIdCliente(self): return self.__idCliente pass def setIdCliente(self,value): self.__idCliente = value pass def getIdMaquina(self): return self.__idMaquina pass def setIdMaquina(self, value): self.__idMaquina = value pass def __str__(self): res = "Pedido:{0}\tEtiqueta:'{1}'\tFecha:{2}\tVelocidad Maquina:{3}(m/m)\n".format( str(self.getPedido()), str(self.getEtiqueta()), str(self.getFecha()), str(self.getVelocidad())) return res
6053f8cc30a7377d6545da6da8bd3878b9cfeadc
cyberchaud/automateBoring
/vid16/vid16.py
1,731
4.40625
4
# Dictionaries are a collection of key value pairs # Python gets the value by indexing the name of the dictionary with the key value in [] # key values in a dictionary are unordered # the is no order to the keys - ie: no first and last value myCat = {'size': 'fat', 'colour': 'grey', 'disposition': 'loud'} print(myCat['colour']) #dictionaries can also use integers as keys myNumbers = { 1: 'yes', 2: 'no', 3: 'maybe' } print(myNumbers[3]) # Trying to access a key that isn't in a dictionary will result in a KeyError try: print(myNumbers[99]) except KeyError: print("This key is not in the dictionary") myNumbers.keys() myNumbers.values() # Dictionary methods can be called and they return listlike lists print(list(myNumbers.keys())) # Dictionary method .items() will print a list of tupples for all the key value pairs print(myNumbers.items()) # The IN and NOT IN operators can be used to verify if the key exists in a dictionary print('fat' in myCat.values()) print('skinny' in myCat.values()) print('skinny' not in myCat.values()) # To avoid KeyError the .get method on a dictionary can return a default value # if it doesn't exist in the dictionary print(myCat.get('parent', 0)) # If a key is in the dictionary but no value is assigned to it # the setdefault method can be used to give a default value # It will take the correct value if one is given myList = {1:'a', 2:'b', 3:'c'} print(myList) myList.setdefault(0, '') print(myList) myList = {1:'a', 2:'b', 3:'c', 0:'d'} print(myList) # the module pprint (pretty print) can be used to display dictionary key value pairs in a # cleaner format import pprint pprint.pprint(myList) pprint.pprint((pprint.pformat(myList)))
710f58225a8f62da34b6e9efa4081e7b7151f1d4
vishrutkmr7/DailyPracticeProblemsDIP
/2019/10 October/dp10082019.py
3,332
3.796875
4
# This problem was recently asked by Facebook: # Two words can be 'chained' if the last character of the first word is the same as the first character of the second word. # Given a list of words, determine if there is a way to 'chain' all the words in a circle. # Input: ['eggs', 'karat', 'apple', 'snack', 'tuna'] # Output: True # Explanation: # The words in the order of ['apple', 'eggs', 'snack', 'karat', 'tuna'] creates a circle of chained words. from collections import defaultdict CHARS = 26 # Eulerian Graph problem class Graph(object): def __init__(self, V): self.V = V # No. of vertices self.adj = [[] for _ in range(V)] self.inp = [0] * V # function to add an edge to graph def addEdge(self, v, w): self.adj[v].append(w) self.inp[w] += 1 # Method to check if this graph is Eulerian or not def isSC(self): # Mark all the vertices as not visited (For first DFS) visited = [False] * self.V # Find the first vertex with non-zero degree n = 0 for n in range(self.V): if len(self.adj[n]) > 0: break # Do DFS traversal starting from first non zero degree vertex. self.DFSUtil(n, visited) # If DFS traversal doesn't visit all vertices, then return false. for i in range(self.V): if len(self.adj[i]) > 0 and visited[i] == False: return False # Create a reversed graph gr = self.getTranspose() # Mark all the vertices as not visited (For second DFS) for i in range(self.V): visited[i] = False # Do DFS for reversed graph starting from first vertex. # Staring Vertex must be same starting point of first DFS gr.DFSUtil(n, visited) return not any( len(self.adj[i]) > 0 and visited[i] == False for i in range(self.V) ) # This function returns true if the directed graph has an eulerian # cycle, otherwise returns false def isEulerianCycle(self): # Check if all non-zero degree vertices are connected if self.isSC() == False: return False return all(len(self.adj[i]) == self.inp[i] for i in range(self.V)) # A recursive function to do DFS starting from v def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited[v] = True # Recur for all the vertices adjacent to this vertex for i in range(len(self.adj[v])): if not visited[self.adj[v][i]]: self.DFSUtil(self.adj[v][i], visited) # Function that returns reverse (or transpose) of this graph # This function is needed in isSC() def getTranspose(self): g = Graph(self.V) for v in range(self.V): # Recur for all the vertices adjacent to this vertex for i in range(len(self.adj[v])): g.adj[self.adj[v][i]].append(v) g.inp[v] += 1 return g def chainedWords(words): # Fill this in. n = len(words) g = Graph(CHARS) for i in range(n): s = words[i] g.addEdge(ord(s[0]) - ord("a"), ord(s[len(s) - 1]) - ord("a")) return g.isEulerianCycle() print(chainedWords(["apple", "eggs", "snack", "karat", "tuna"])) # True
f356960886a2ce737f291544154888b22c1783b4
ChidinmaKO/Chobe-Py-Challenges
/bites/bite140.py
1,299
3.546875
4
import pandas as pd import collections data = "https://bites-data.s3.us-east-2.amazonaws.com/summer.csv" def athletes_most_medals(data=data): # read data pd_data = pd.read_csv(data, index_col=0) # ==> one way # male_most_medals = dict(pd_data[pd_data["Gender"] == "Men"]["Athlete"].value_counts().head(1)) # female_most_medals = dict(pd_data["Athlete"][pd_data["Gender"] == "Women"].value_counts().head(1)) # merge dicts # return {**male_most_medals, **female_most_medals} # ==> another way f_medals = dict(collections.Counter(pd_data["Athlete"][pd_data["Gender"] == 'Women']).most_common(1)) m_medals = dict(collections.Counter(pd_data["Athlete"][pd_data["Gender"] == 'Men']).most_common(1)) most_medals = {**f_medals, **m_medals} return most_medals # tests from medals import data, athletes_most_medals def test_athletes_most_medals_default_csv(): ret = athletes_most_medals() assert len(ret) == 2 assert ret["LATYNINA, Larisa"] == 18 assert ret["PHELPS, Michael"] == 22 def test_smaller_csv_and_guarantee_checking_male_and_female(): ret = athletes_most_medals( data.replace('summer', 'summer_2008-2012') ) assert len(ret) == 2 assert ret["PHELPS, Michael"] == 14 assert ret["COUGHLIN, Natalie"] == 7 # not LOCHTE, Ryan
7ac67028bb4174be1d7088e3854e4b0ef215f945
MaxIakovliev/algorithms
/old/Session002/DepthFirstSearch/SearchinBinarySearchTree.py
736
3.8125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: """ https://leetcode.com/problems/search-in-a-binary-search-tree/description/ """ def searchBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ return self.search(root,val) def search(self,node, val): if node is None: return None if node.val==val: return node elif node.val>val: return self.search(node.left, val) else: return self.search(node.right, val)
2830989eed91875e04f40aedf2459f1ef2aadb3a
conradylx/Python_Course
/24.03.2021/Excercise8/exc8.py
886
3.65625
4
# Utwórz generator dowolnego typu np. generator zdań, tweetów czy konferencji. # Dane wejściowe pobierz z pliku csv (plik csv możesz traktować jako plik txt ze znanym znakiem podziału), # który będzie przechowywał dane potrzebne do generowania. import csv import random def read_file() -> dict: reader_dict = dict() with open('quotes.csv', mode='r') as csv_file: reader = csv.reader(csv_file, delimiter=';') iterator = 0 for line in reader: value, key = line[0], line[1] reader_dict[key] = f'"{value}"' iterator += 1 return reader_dict def get_random_quote(quotes: dict): random_quote = random.choice(list(quotes.values())) for author, quote in quotes.items(): if quote == random_quote: print(random_quote, author) reader_dict = read_file() get_random_quote(reader_dict)
9eb153d1270f0c8cd1a6835f6d8d522268850c3f
MEng-Alejandro-Nieto/Python-3-Udemy-Course
/6 Print formatting with strings.py
1,285
4.4375
4
# 1 METHOD --- .format() print("his name is {}".format("Alejandro")) # It will print "his name is Alejandro" print("the next 3 words are {} {} {}".format('fox','brown','quick')) # It will print "the next 3 words are fox brown quick" print("the next 3 words are {2} {1} {0}".format('fox','brown','quick')) # It will print "the next 3 words are quick brown fox" print("the next 3 words are {c} {a} {b}".format(a='fox',b='brown',c='quick')) # It will print "the next 3 words are quick brown fox" a=1; b=2; c=a+b; print("the sum of {} + {} is equal to {}".format(a,b,c) ) # it will print "the sum of 1 + 2 is equal to 3" print("the result of {2} - {1} is equal to {0}".format(a,b,c)) # it will print "the result of 3 - 2 is equal to 1" # float formatting result=100/777 print("the result is {}".format(result)) print("the result is {r:10.3f}".format(r=result)) # It will print with a precision of 3 decimals and 10 spaces # 2 METHOD --- f-strings name = "Alejandro" c=100 d=777 e=c/d print(f"his name is {name}") # It will print "his name is Alejandro" print(f"the sum of {a}+{b}={c}") # it will print "the sum of 1 + 2 is equal to 3" print(f"the resul of {c}/{d} ={e:10.5f}") # It will print with a precision of 3 decimals and 10 spaces
a4ee6d78fba7e778d7ab1bf993c6df2406f5a0a4
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/tfbanks/Lesson03/List_Lab.py
4,657
4.40625
4
# List Lab Exercise by tfbanks #!/usr/bin/env python3 # Series 1 fruits = ["Apples", "Pears", "Oranges", "Peaches"] # Original List of Fruits # Welcome to series 1 and tells how many fruits are in the list print("Welcome to Series 1\nThis list has the following", len(fruits), "fruits: ", fruits, "\n") new_fruit = input("What one fruit would you like to add to this list? ") # Asks the user what fruit they want to add fruits.append(new_fruit.title()) # Appends what the user inputs print(new_fruit, "was added; The list now has the following", len(fruits), "fruits: ", fruits, "\n") # Tells how many fruits are in the list num_value = int(input("Please enter a number between 1 and " + str(len(fruits)) + ": ")) # Asks for a number between 1 and the number of fruit on the list select_num = int(num_value - 1) # Corrects the number to Python "number" print(fruits[select_num], "is number", num_value, "in the list of fruits\n") # Tells what fruit and what number it is on the list new_fruit2 = input("Name one more fruit to add to the list ") # Asks for another fruit to add to the list fruits = [new_fruit2.title()] + fruits print(new_fruit2, "was added; The list now has the following", len(fruits), "fruits: ", fruits, "\n") # Tells how many fruits are in the list new_fruit3 = input("Name one last fruit to add to the list ") # Asks for one more fruit to add to the list fruits.insert(0, new_fruit3.title()) print(new_fruit3, "was added; The list now has the following", len(fruits), "fruits: ", fruits, "\n") # Tells how many fruits are on the list p_start_fruits = [] for fruit in fruits: if fruit[0] == 'P': p_start_fruits.append(fruit) print("FYI: all the fruits that start with P are: ", p_start_fruits, "\n") s1_fruits = fruits[:] # Transition between Series 1 and Series 2 Exercises continue_s2 = input("This ends Series 1, Would you like to continue to Series 2? Please enter Y/N ") if continue_s2.title() == "Y": pass else: print("Thank You, Have a nice day") exit() # Series 2 print("\n") # Adds some space before the next block s2_fruits = s1_fruits[:] # Copies the last iteration of Series 1 fruits to Series 2 list print("Welcome to Series 2\nThe fruit list currently has the following", len(s2_fruits), "fruits: ", fruits, "\n") # Tells how many fruits are on the list last_fruit = s2_fruits[-1] # Selects the last fruit on the list s2_fruits.remove(last_fruit) # Removed the last fruit on the list print(last_fruit, "Was removed; The fruit list now has the following", len(s2_fruits), "fruits: ", s2_fruits, "\n") # Tells how many fruits are on the list del_fruit = input("What other fruit would you like to remove from the list above? ") # Asks what fruit to delete s2_fruits.remove(del_fruit.title()) # Deletes the fruit that the user inputs print(del_fruit, "Was removed; The fruit list now has the following", len(s2_fruits), "fruits: ", s2_fruits, "\n") # Tells how many fruits are on the list # Transition between Series 2 and Series 3 Exercises continue_s3 = input("This ends Series 2, Would you like to continue to Series 3? Please enter Y/N ") if continue_s3.title() == "Y": pass else: print("Thank You, Have a nice day") exit() # Series 3 print("\n") # Adds some space before the next block s3_fruits = s1_fruits[:] # Copies the list of fruits from above print("Welcome to Series 3\n") no_no_fruit = [] for fruit in s3_fruits: answer = input(f"Do you like {fruit.lower()}? Please enter Yes/No ") while answer.lower() != "yes" and answer.lower() != "no": answer = input(f"Do you like {fruit.lower()}? Please enter Yes/No ") if answer.lower() == "no": no_no_fruit = no_no_fruit + [fruit.title()] for fruits in no_no_fruit: s3_fruits.remove(fruits) print("You like the following fruits: ", s3_fruits) # Series 4 print("\n") # Adds some space before the next block s4_fruits = s1_fruits[:] # Copies the last iteration of Series 1 fruits to Series 4 list print("Welcome to Series 4\n") fruit_backwards = [] # creates an empty list for writing fruit backwards for fruit in s4_fruits: ind_backward_fruit = fruit[::-1] # writes each fruit backwards fruit_backwards = fruit_backwards + [ind_backward_fruit] # combines each fruit in the new list del fruit_backwards[-1:] # removes the last fruit from the list print("The original fruit list at the end of Series 1 contained: ", s4_fruits, "\n") # prints the original fruit print("Here is the list with all fruit written backwards and the last item removed: ", fruit_backwards, "\n") # prints new list close_statement = input("Press Any key to exit")