blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
2c449fb5a086b32711f6ad4d74c23549191222e6
LQR471814/Curve-Tortoise
/renderer.py
460
3.75
4
import turtle from bezier import * from common.types import * def draw(t: turtle.Turtle, scale: int, bezier_points: List[Line], steps: int = 20, closed: bool = False): # ? Go to starting position t.penup() t.goto(bezier_points[0].p1.x * scale, bezier_points[0].p1.y * scale) t.pendown() points = bezier_interpolation(bezier_points, steps, closed) for point in points: t.goto(point.x * scale, point.y * scale) t.penup()
42f37b58b8e3b4583208ea054d30bef34040a6ed
inshaal/cbse_cs-ch2
/lastquest_funcoverload_Q18_ncert.py
1,152
4.1875
4
"""FUNCTION OVERLOADING IS NOT POSSIBLE IN PYTHON""" """However, if it was possible, the following code would work.""" def volume(a): #For volume of cube vol=a**3 print vol, "is volume of cube" def volume(a,b,c): #volume of cuboid |b-height vol=a*b*c print vol, "is volume of cuboid" def volume(a,b): #volume of cylinder |a-radius|b-height from math import pi vol= pi*(a**2)*b print vol, "is volume of cylinder" a=raw_input("Enter dimension1: ") b=raw_input("Enter dimension2: ") c=raw_input("Enter dimension3: ") volume(a,b,c) ''' Notice Python takes the latest definition of that function. So if all three values are provided for a,b & c Python will give an error stating it takes only 2 arguments but 3 given. ''' ''' EXTRA PART FOR - (Not Required) ta=bool(a) tb=bool(b) tc=bool(c) if ta: a=float(a) if not (tb and tc): volume(a) elif tb and (not tc): b=float(b) volume(a,b) elif (tb and tc): b=float(b) c=float(c) volume(a,b,c) ''' """It's possible using module/s: https://pypi.python.org/pypi/overload"""
51a882936fb34b9cb740408a72a6d64ce910a796
Leonardo612/leonardo_entra21
/exercicio_01/listar_pessoas.py
654
3.84375
4
""" --- Exercício 3 - Funções --- Escreva uma função para listar pessoas cadastradas: --- a função deve retornar todas as pessoas cadastradas na função do ex1 --- Escreva uma função para exibi uma pessoa específica: a função deve retornar uma pessoa cadastrada na função do ex1 filtrando por id """ from cadastrando_pessoas import pessoas def listar_pessoas_cadastradas(pessoas): print(f'Quanditade de pessoas cadastradas: {len(pessoas)}') return pessoas listar_pessoas_cadastradas(pessoas) def escolha(id_pessoa): for pessoa in pessoas: if pessoa['i_d'] == id_pessoa: print(pessoa)
6335c93ef76e37891cee92c97be29814aa91eb21
Leonardo612/leonardo_entra21
/exercicio_01/cadastrando_pessoas.py
992
4.125
4
""" --- Exercício 1 - Funções --- Escreva uma função para cadastro de pessoa: --- a função deve receber três parâmetros, nome, sobrenome e idade --- a função deve salvar os dados da pessoa em uma lista com escopo global --- a função deve permitir o cadastro apenas de pessoas com idade igual ou superior a 18 anos --- a função deve retornar uma mensagem caso a idade informada seja menor que 18 --- caso a pessoa tenha sido cadastrada com sucesso deve ser retornado um id --- A função deve ser salva em um arquivo diferente do arquivo principal onde será chamada """ #=== escopo global pessoas = [] def cadastrar_pessoas(nome, sobrenome, idade): if idade < 18: print("Idade não permitida!") else: pessoa = {'nome': nome,'sobrenome': sobrenome,'idade': idade} pessoa['i_d'] = len(pessoas) + 1 pessoas.append(pessoa) print("Pessoa cadrastrada!") return pessoas
4208552adfa03bd0d8486192ed9d3206162d64e2
David-Roy-JCU/prac_04
/lists_warmup.py
434
3.6875
4
""" prac 04 - Lists """ numbers = [3, 1, 4, 1, 5, 9, 2] # 3 / # 2 / # 1 / # ? x slices the last value off and returns the list # ? x andswer is 1. it defines a range? look this up! # True / # False / # False / # [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] / numbers[0] numbers[-1] numbers[3] numbers[:-1] numbers[3:4] 5 in numbers 7 in numbers "3" in numbers numbers + [6, 5, 3] numbers[0] = "ten" numbers[-1] = 1 numbers[2:] 9 in numbers
32ca4261b3d5c5e48e802957f0a6931b3d9d60d0
luodonghua/PythonProgrammingLanguage
/6.2_reader.py
1,207
3.765625
4
# reader.py import csv def read_csv(filename, types, *, errors='warn'): ''' Read the CSV with type conversion into a list of dictionary ''' if errors not in {'warn', 'silent', 'raise'}: raise ValueError("errors must be in one of 'warn', 'silent', 'raise'") records = [] # list of records with open(filename,'r') as f: rows = csv.reader(f) headers = next(rows) # Skill a single line input for rowno, row in enumerate(rows, start=1): try: row = [ func(val) for func, val in zip(types, row)] except ValueError as err: # Exception is the top level exception to catch all (dangerous) if errors == 'warn': print('Row:', rowno, 'Bad row:', row) print('Row:', rowno, 'Reason:', err) elif errors == 'raise': raise # Re-raise the last exception else: pass continue # skip to the next line record = dict(zip(headers, row)) records.append(record) return records
569cbdc1106f4f881cd492749f3d3b8042d3782d
tgtiweird/KTaNE-TASer
/Python/Sorting.py
38,040
3.9375
4
sort=input("what sort (use full caps)\n") if sort!="BOGO": first,second,third,fourth,fifth=int(input("what number in pos 1 (either 1/2 digits) \n")),int(input("what number in pos 2\n")),int(input("what number in pos 3\n")),int(input("what number in pos 4\n")),int(input("what number in pos 5\n")) tens1,tens2,tens3,tens4,tens5=int(str(first).zfill(2)[0]),int(str(second).zfill(2)[0]),int(str(third).zfill(2)[0]),int(str(fourth).zfill(2)[0]),int(str(fifth).zfill(2)[0]) if tens1>tens2 or tens2>tens3 or tens3>tens4 or tens4>tens5: while tens1 > tens2 or tens2 > tens3 or tens3 > tens4 or tens4 > tens5: if tens1 > tens2: temp1 = tens1 tens1 = tens2 tens2 = temp1 temp1 = 0 if tens3 > tens4: temp1 = tens3 tens3 = tens4 tens4 = temp1 temp1 = 0 if tens2 > tens3: temp1 = tens2 tens2 = tens3 tens3 = temp1 temp1 = 0 if tens4 > tens5: temp1 = tens4 tens4 = tens5 tens5 = temp1 temp1 = 0 units1,units2,units3,units4,units5=int(str(first).zfill(2)[1]),int(str(second).zfill(2)[1]),int(str(third).zfill(2)[1]),int(str(fourth).zfill(2)[1]),int(str(fifth).zfill(2)[1]) if units1>units2 or units2>units3 or units3>units4 or units4>units5: while units1 > units2 or units2 > units3 or units3 > units4 or units4 > units5: if units1 > units2: temp1 = units1 units1 = units2 units2 = temp1 temp1 = 0 if units3 > units4: temp1 = units3 units3 = units4 units4 = temp1 temp1 = 0 if units2 > units3: temp1 = units2 units2 = units3 units3 = temp1 temp1 = 0 if units4 > units5: temp1 = units4 units4 = units5 units5 = temp1 temp1 = 0 tensor1,tensor2,tensor3,tensor4,tensor5,unitsor1,unitsor2,unitsor3,unitsor4,unitsor5=tens1,tens2,tens3,tens4,tens5,units1,units2,units3,units4,units5 tens1,tens2,tens3,tens4,tens5=int(str(first).zfill(2)[0]),int(str(second).zfill(2)[0]),int(str(third).zfill(2)[0]),int(str(fourth).zfill(2)[0]),int(str(fifth).zfill(2)[0]) units1,units2,units3,units4,units5=int(str(first).zfill(2)[1]),int(str(second).zfill(2)[1]),int(str(third).zfill(2)[1]),int(str(fourth).zfill(2)[1]),int(str(fifth).zfill(2)[1]) if sort=="MERGE": e=int(input("last digit of serial number:")) sor1,sor2,sor3,sor4,sor5=max(first,0),max(second,0),max(third,0),max(fourth,0),max(fifth,0) while sor1 > sor2 or sor2 > sor3 or sor3 > sor4 or sor4 > sor5: if sor1 > sor2: temp10 = sor1 sor1 = sor2 sor2 = temp10 temp10 = 0 if sor2 > sor3: temp10 = sor2 sor2 = sor3 sor3 = temp10 temp10 = 0 if sor3 > sor4: temp10 = sor3 sor3 = sor4 sor4 = temp10 temp10 = 0 if sor4 > sor5: temp10 = sor4 sor4 = sor5 sor5 = temp10 temp10 = 0 if sor3 > sor4: temp10 = sor3 sor3 = sor4 sor4 = temp10 temp10 = 0 if sor2 > sor3: temp10 = sor2 sor2 = sor3 sor3 = temp10 temp10 = 0 if sort=="BUBBLE": while first>second or second>third or third>fourth or fourth>fifth: if first>second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if second>third: temp1=second second=third third=temp1 temp1=0 print("swap 2 3") if third>fourth: temp1=third third=fourth fourth=temp1 temp1=0 print("swap 3 4") if fourth>fifth: temp1=fourth fourth=fifth fifth=temp1 temp1=0 print("swap 4 5") elif sort=="COCKTAIL": while first > second or second > third or third > fourth or fourth > fifth: if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") elif sort=="ODDEVEN": while first > second or second > third or third > fourth or fourth > fifth: if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") elif sort=="INSERTION": i=0 while first > second or second > third or third > fourth or fourth > fifth: i+=1 if i>=4: if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") if i>=3: if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if i>=2: if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if i>=1: if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") elif sort=="CYCLE": e=0 while first > second or second > third or third > fourth or fourth > fifth: if first!=sor1: while e==0: if first == sor2: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") elif first == sor3: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") elif first == sor4: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") elif first == sor5: temp1 = first first = fifth fifth = temp1 temp1 = 0 print("swap 1 5") if first==sor1: e=1 e=0 elif second!=sor2: while e==0: if second==sor3: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") elif second==sor4: temp1 = second second = fourth fourth = temp1 temp1 = 0 print("swap 2 4") elif second==sor5: temp1 = second second = fifth fifth = temp1 temp1 = 0 print("swap 2 5") if second==sor2: e=1 elif third!=sor3: while e==0: if third==sor4: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") elif third==sor5: temp1 = third third = fifth fifth = temp1 temp1 = 0 print("swap 3 5") if third==sor3: e=1 if fourth>fifth: temp1 = fourth fourth = fifth fifth = temp1 print("swap 4 5") elif sort=="HEAP": if second<fourth: temp1=second second=fourth fourth=temp1 temp1=0 print("swap 2 4") if second<fifth: temp1=second second=fifth fifth=temp1 temp1=0 print("swap 2 5") if first<second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if first<third: temp1=first first=third third=temp1 temp1=0 print("swap 1 3") if second<fourth: temp1=second second=fourth fourth=temp1 temp1=0 print("swap 2 4") if second<fifth: temp1=second second=fifth fifth=temp1 temp1=0 print("swap 2 5") if sor5 != fifth: temp1 = first first = fifth fifth = temp1 temp1 = 0 print("swap 1 5") elif sor4 != fourth: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") elif sor3 != third: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") elif sor2 != second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if second<fourth: temp1=second second=fourth fourth=temp1 temp1=0 print("swap 2 4") if first<second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if first<third: temp1=first first=third third=temp1 temp1=0 print("swap 1 3") if second<fourth: temp1=second second=fourth fourth=temp1 temp1=0 print("swap 2 4") if sor4 != fourth: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") elif sor3 != third: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") elif sor2 != second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if first<second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if first<third: temp1=first first=third third=temp1 temp1=0 print("swap 1 3") if sor3 != third: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") elif sor2 != second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if first<second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if sor2 != second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") elif sort=="MERGE": if first>second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if fourth>fifth: temp1=fourth fourth=fifth fifth=temp1 temp1=0 print("swap 4 5") if e%2==1: if first<second and first<third: asdasdasd="as" elif second<first and second<third: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") else: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") else: if fifth>fourth and fifth>third: esij=12302173128312 elif fourth>fifth and fourth>third: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") else: temp1 = third third = fifth fifth = temp1 temp1 = 0 print("swap 3 5") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if sor1 == first: qq8 = 2 elif sor1 == second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") elif sor1 == third: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") elif sor1 == fourth: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") else: temp1 = first first = fifth fifth = temp1 temp1 = 0 print("swap 1 5") if sor2 == second: eue989we7r79283721312 = 1 elif sor2 == third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") elif sor2 == fourth: temp1 = second second = fourth fourth = temp1 temp1 = 0 print("swap 2 4") else: temp1 = second second = fifth fifth = temp1 temp1 = 0 print("swap 2 5") if sor3 == third: sa = "/rihadastroke" elif sor3 == fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") else: temp1 = third third = fifth fifth = temp1 temp1 = 0 print("swap 3 5") if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") elif sort=="SELECTION": if sor1==first: qq8=2 elif sor1==second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") elif sor1==third: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") elif sor1==fourth: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") else: temp1 = first first = fifth fifth = temp1 temp1 = 0 print("swap 1 5") if sor2==second: eue989we7r79283721312=1 elif sor2==third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") elif sor2==fourth: temp1 = second second = fourth fourth = temp1 temp1 = 0 print("swap 2 4") else: temp1 = second second = fifth fifth = temp1 temp1 = 0 print("swap 2 5") if sor3==third: sa="/rihadastroke" elif sor3==fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") else: temp1 = third third = fifth fifth = temp1 temp1 = 0 print("swap 3 5") if fourth>fifth: temp1=fourth fourth=fifth fifth=temp1 temp1=0 print("swap 4 5") elif sort=="COMB": if first>fourth: temp1=first first=fourth fourth=temp1 temp1=0 print("swap 1 4") if second>fifth: temp1=second second=fifth fifth=temp1 temp1=0 print("swap 2 5") if first>third: temp1=first first=third third=temp1 temp1=0 print("swap 1 3") if second>fourth: temp1=second second=fourth fourth=temp1 temp1=0 print("swap 2 4") if third>fifth: temp1=third third=fifth fifth=temp1 temp1=0 print("swap 3 5") if first>second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if second>third: temp1=second second=third third=temp1 temp1=0 print("swap 2 3") if third>fourth: temp1=third third=fourth fourth=temp1 temp1=0 print("swap 3 4") if fourth>fifth: temp1=fourth fourth=fifth fifth=temp1 temp1=0 print("swap 4 5") elif sort=="QUICK": pivot,current=1,5 while first > second or second > third or third > fourth or fourth > fifth: if pivot<current: if pivot==1: if current==2: if first > second: temp1 = first first = second second = temp1 temp1 = 0 pivot, current = 2, 1 print("swap 1 2") elif current==3: if first > third: temp1 = first first = third third = temp1 temp1 = 0 pivot, current = 3, 1 print("swap 1 3") elif current==4: if first > fourth: temp1 = first first = fourth fourth = temp1 temp1 = 0 pivot, current = 4, 1 print("swap 1 4") elif current==5: if first > fifth: temp1 = first first = fifth fifth = temp1 temp1 = 0 pivot, current = 5,1 print("swap 1 5") elif pivot==2: if current==3: if second > third: temp1 = second second = third third = temp1 temp1 = 0 pivot, current = 3, 2 print("swap 2 3") elif current==4: if second > fourth: temp1 = second second = fourth fourth = temp1 temp1 = 0 pivot, current = 4, 2 print("swap 2 4") elif current==5: if second > fifth: temp1 = second second = fifth fifth = temp1 temp1 = 0 pivot, current = 5, 2 print("swap 2 5") elif pivot==3: if current==4: if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 pivot, current = 4, 3 print("swap 3 4") elif current==5: if third > fifth: temp1 = third third = fifth fifth = temp1 temp1 = 0 pivot, current = 5, 3 print("swap 3 5") elif pivot==4: if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 pivot, current = 5, 4 print("swap 4 5") elif current<pivot: if current == 1: if pivot == 2: if first > second: temp1 = first first = second second = temp1 temp1 = 0 current, pivot = 2, 1 print("swap 1 2") elif pivot == 3: if first > third: temp1 = first first = third third = temp1 temp1 = 0 current, pivot = 3, 1 print("swap 1 3") elif pivot == 4: if first > fourth: temp1 = first first = fourth fourth = temp1 temp1 = 0 current, pivot = 4, 1 print("swap 1 4") elif pivot == 5: if first > fifth: temp1 = first first = fifth fifth = temp1 temp1 = 0 current, pivot = 5, 1 print("swap 1 5") elif current == 2: if pivot == 3: if second > third: temp1 = second second = third third = temp1 temp1 = 0 current, pivot = 3, 2 print("swap 2 3") elif pivot == 4: if second > fourth: temp1 = second second = fourth fourth = temp1 temp1 = 0 current, pivot = 4, 2 print("swap 2 4") elif pivot == 5: if second > fifth: temp1 = second second = fifth fifth = temp1 temp1 = 0 current, pivot = 5, 2 print("swap 2 5") elif current == 3: if pivot == 4: if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 current, pivot = 4, 3 print("swap 3 4") elif pivot == 5: if third > fifth: temp1 = third third = fifth fifth = temp1 temp1 = 0 current, pivot = 5, 3 print("swap 3 5") elif current == 4: if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 current, pivot = 5, 4 print("swap 4 5") else: if sor1==first: pivot=1 elif sor2!=second: pivot=2 elif sor3!=third: pivot=3 elif sor4!=fourth: pivot=4 if sor5!=fifth: current=5 elif sor4!=fourth: current=4 elif sor3!=third: current=3 elif sor2!=second: current=2 if pivot>current: current+=1 else: current-=1 elif sort=="BOGO": print("Try your best to sort them until it solves\nGood luck") print("EEEEEEEEEEEEE") elif sort == "RADIX": if unitsor1 == units1: isd09fsd0f0suf = 2 elif unitsor1 == units2 and units1 != units2: temp1 = first first = second second = temp1 temp1 = 0 temp2 = units1 units1 = units2 units2 = temp2 temp2 = 0 temp2 = tens1 tens1 = tens2 tens2 = temp2 temp2 = 0 print("swap 1 2") elif unitsor1 == units3 and units1 != units3: temp1 = first first = third third = temp1 temp1 = 0 temp2 = units1 units1 = units3 units3 = temp2 temp2 = 0 temp2 = tens1 tens1 = tens3 tens3 = temp2 temp2 = 0 print("swap 1 3") elif unitsor1 == units4 and units1 != units4: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") temp2 = units1 units1 = units4 units4 = temp2 temp2 = 0 temp2 = tens1 tens1 = tens4 tens4 = temp2 temp2 = 0 elif unitsor1 == units5 and units1 != units5: temp1 = first first = fifth fifth = temp1 temp1 = 0 temp2 = units1 units1 = units5 units5 = temp2 temp2 = 0 temp2 = tens1 tens1 = tens5 tens5 = temp2 temp2 = 0 print("swap 1 5") if unitsor2 == units2: isfu983 = 2 elif unitsor2 == units3 and units2 != units3: temp1 = second second = third third = temp1 temp1 = 0 temp2 = units2 units2 = units3 units3 = temp2 temp2 = tens2 tens2 = tens3 tens3 = temp2 temp2 = 0 temp2 = 0 print("swap 2 3") elif unitsor2 == units4 and units2 != units4: temp1 = second second = fourth fourth = temp1 temp1 = 0 temp2 = units2 units2 = units4 units4 = temp2 temp2 = 0 temp2 = tens2 tens2 = tens4 tens4 = temp2 temp2 = 0 print("swap 2 4") elif unitsor2 == units5 and units2 != units5: temp1 = second second = fifth fifth = temp1 temp1 = 0 temp2 = units2 units2 = units5 units5 = temp2 print("swap 2 5") temp2 = tens2 tens2 = tens5 tens5 = temp2 temp2 = 0 if unitsor3 == units3: elkavojovika078234 = 1 elif unitsor3 == units4 and units3 != units4: temp1 = third third = fourth fourth = temp1 temp1 = 0 temp2 = units3 units3 = units4 units4 = temp2 temp2 = 0 temp2 = tens3 tens3 = tens4 tens4 = temp2 temp2 = 0 print("swap 3 4") elif unitsor3 == units5 and units3 != units5: temp1 = third third = fifth fifth = temp1 temp1 = 0 temp2 = units3 units3 = units5 units5 = temp2 temp2 = 0 temp2 = tens3 tens3 = tens5 tens5 = temp2 temp2 = 0 print("swap 3 5") if unitsor4 == units5 and units4 != units5: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 temp2 = units4 units4 = units5 units5 = temp2 temp2 = 0 temp2 = tens4 tens4 = tens5 tens5 = temp2 temp2 = 0 print("swap 4 5") if tensor1==tens1: isd09fsd0f0suf=2 elif tensor1==tens2 and tens1!=tens2: temp1 = first first = second second = temp1 temp1 = 0 temp2 = tens1 tens1 = tens2 tens2 = temp2 temp2 = 0 print("swap 1 2") elif tensor1==tens3 and tens1!=tens3: temp1 = first first = third third = temp1 temp1 = 0 temp2 = tens1 tens1 = tens3 tens3 = temp2 temp2 = 0 print("swap 1 3") elif tensor1==tens4 and tens1!=tens4: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") temp2 = tens1 tens1 = tens4 tens4 = temp2 temp2 = 0 elif tensor1==tens5 and tens1!=tens5: temp1 = first first = fifth fifth = temp1 temp1 = 0 temp2 = tens1 tens1 = tens5 tens5 = temp2 temp2 = 0 print("swap 1 5") if tensor2==tens2: isfu983=2 elif tensor2==tens3 and tens2!=tens3: temp1 = second second = third third = temp1 temp1 = 0 temp2 = tens2 tens2 = tens3 tens3 = temp2 temp2 = 0 print("swap 2 3") elif tensor2==tens4 and tens2!=tens4: temp1 = second second = fourth fourth = temp1 temp1 = 0 temp2 = tens2 tens2 = tens4 tens4 = temp2 temp2 = 0 print("swap 2 4") elif tensor2==tens5 and tens2!=tens5: temp1 = second second = fifth fifth = temp1 temp1 = 0 temp2=tens2 tens2 = tens5 tens5 = temp2 print("swap 2 5") if tensor3==tens3: elkavojovika078234=1 elif tensor3==tens4 and tens3!=tens4: temp1 = third third = fourth fourth = temp1 temp1 = 0 temp2 = tens3 tens3 = tens4 tens4 = temp2 temp2 = 0 print("swap 3 4") elif tensor3==tens5 and tens3!=tens5: temp1 = third third = fifth fifth = temp1 temp1 = 0 temp2 = tens3 tens3 = tens5 tens5 = temp2 temp2 = 0 print("swap 3 5") if tensor4==tens5 and tens4!=tens5: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 temp2 = tens4 tens4 = tens5 tens5 = temp2 temp2 = 0 print("swap 4 5") elif sort=="FIVE": if sor3==first: temp1 = first first = third third = temp1 temp1 = 0 print("swap 1 3") if sor3==second: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if sor3==fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if sor3==fifth: temp1 = third third = fifth fifth = temp1 temp1 = 0 print("swap 3 5") if first>sor3: if fourth<first and fourth<third: temp1 = first first = fourth fourth = temp1 temp1 = 0 print("swap 1 4") elif fifth<first and fifth<third: temp1 = first first = fifth fifth = temp1 temp1 = 0 print("swap 1 5") if second>sor3: if fourth<second and fourth<third: temp1 = second second = fourth fourth = temp1 temp1 = 0 print("swap 2 4") elif fifth<second and fifth<third: temp1 = second second = fifth fifth = temp1 temp1 = 0 print("swap 2 5") if first>second: temp1=first first=second second=temp1 temp1=0 print("swap 1 2") if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") elif sort=="STOOGE": for i in range(3): if i%2==0: for ia in range(3): if ia==1: if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") else: if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") else: for ib in range(3): if ib == 1: if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") else: if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") elif sort=="SLOW": while first > second or second > third or third > fourth or fourth > fifth: if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") if third > fifth: temp1 = third third = fifth fifth = temp1 temp1 = 0 print("swap 3 5") if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if second > fourth: temp1 = second second = fourth fourth = temp1 temp1 = 0 print("swap 2 4") elif sort=="SHELL": if first>third: temp1=first first=third third=temp1 temp1=0 print("swap 1 3") if second>fourth: temp1=second second=fourth fourth=temp1 temp1=0 print("swap 2 4") if third>fifth: temp1=third third=fifth fifth=temp1 temp1=0 print("swap 3 5") if first>third: temp1=first first=third third=temp1 temp1=0 print("swap 1 3") while first > second or second > third or third > fourth or fourth > fifth: if first > second: temp1 = first first = second second = temp1 temp1 = 0 print("swap 1 2") if second > third: temp1 = second second = third third = temp1 temp1 = 0 print("swap 2 3") if third > fourth: temp1 = third third = fourth fourth = temp1 temp1 = 0 print("swap 3 4") if fourth > fifth: temp1 = fourth fourth = fifth fifth = temp1 temp1 = 0 print("swap 4 5") print("-------------------------------------") if sort!="BOGO": print(first,second,third,fourth,fifth) print("done ye")
3b9e9d2cf8d4818b101268e4c3953e72d2cc1030
gabrielfrimodig/Python-2--Add-view
/dictionaries.py
714
3.765625
4
# -*- coding: utf-8 -*- """ @author: gabriel """ users = {"nisse":"apa", "bosse":"ko", "stina":"t-rex"} data = {"nisse":["luva", "vante"], "bosse":["spik", "skruv", "hammare"], "stina":["tidsmaskin"]} print("Användare:") for (x, y) in users.items(): print(x) print("\nAnvändare och Lösenord:") for (x, y) in users.items(): print(f"{x}) {y}") print("\nAnvändare och dess data:") for (x, y) in users.items(): print(f"{x}) {data[x]}") g = input("Användare: ") for (x, y) in data.items(): if g in data: print(f"Data lagrat för {g}: {data[g]}") break elif g not in data: print(f"{g} finns inte med") break
b497a67b0a0a3a0e145d12a40fe35bbd3fb05e62
megrao/DP-1
/HouseRobber.py
1,797
3.671875
4
""" Problem2 (https://leetcode.com/problems/house-robber/) You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. Executed in leetcode: Yes Time complexity: O(n) Space complexity: O(1) Comments: Initially, I tried a complicated logic with odd and even indices. Thereafter, used this simple method to do the same. I iterated over the array with the money in each house. Using two variables, the value at a house plus the non-adjacent value is compared with current collection we have so far. The maximum is chosen. """ class Solution: def rob(self, nums: List[int]) -> int: # Sanity check if not nums: return 0 # Suppose there is only 1-2 house(s), we find the maximum elif len(nums)<=2: return max(nums) previous = 0 current = 0 for i in nums: temp = current current = max(previous + i, current) previous = temp return current
4cdf3ebc7fec6a40476b2ca90e5a94c35965c398
ALTI-PRO/Tic-Tac-Toe
/Tic_Tac_Toe.py
4,872
4
4
#Combining Everything from IPython.display import clear_output import random def display_board(board): ''' Display the board ''' clear_output() print(' | |') print(board[7]+' | '+board[8]+' | '+board[9]) print(' | |') print ('----------') print(' | |') print(board[4]+' | '+board[5]+' | '+board[6]) print(' | |') print ('----------') print(' | |') print(board[1]+' | '+board[2]+' | '+board[3]) print(' | |') def player_input(): ''' Output = (Player 1 marker, Player 2 marker) ''' marker= '' while marker != 'X' and marker!= 'O' : marker = input ('Player 1: Choose X or O: ').upper() if marker == 'X': return ('X', 'O') else: return ('O', 'X') def place_maker(board, marker, position): board[position] = marker def win_check(board, mark): #WIN TIC TAC TOE return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle (board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom (board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle (board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle (board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal def choose_first(): #Randomly choose which player will go first flip = random.randint(0,1) if flip == 0: return 'Player 1' else: return 'Player 2' def space_check(board, position): #Check if specified position is empty on the board return board[position] == ' ' def full_board_check(board): #Check if the board is full for i in range (1, 10): if space_check(board, i): return False return True def player_choice(board): #Take input of position from the player position = 0 while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position): position = int(input('Choose a position: (1-9)')) return position def replay(): #Check if players want to play the game again choice = input ("Play again ? Enter Yes or No") return choice == 'Yes' #WHILE LOOP TO KEEP RUNNING THE GAME while True: #Play the game ##SET (BOARD, WHOS 1st, CHOOSE MARKER X, O) the_board = [' ']*10 player1_marker, player2_marker = player_input() turn = choose_first() print(turn + " will go first") play_game = input ('Are you ready to Play Y or N') if play_game == 'y': game_on = True else: game_on = False ##GAME PLAY while game_on: if turn == 'Player 1': print ("Player 1teru") #show the board display_board(the_board) #choose a porition position = player_choice(the_board) #Place the market on the position place_maker(the_board, player1_marker, position) #Check if they won if win_check(the_board, player1_marker): display_board(the_board) print('Player 1 has WON') game_on = False else: if full_board_check(the_board): #Or check if there is a tie display_board(the_board) print ("The Game is a TIE") game_on = False else: turn = 'Player 2' #No tie and no win? Then next player's turn ###PLAYER ONE TURN else: print ("Player 2 turnweh ") #show the board display_board(the_board) #choose a porition position = player_choice(the_board) #Place the market on the position place_maker(the_board, player2_marker, position) #Check if they won if win_check(the_board, player2_marker): display_board(the_board) print('Player 2 has WON') game_on = False else: if full_board_check(the_board): display_board(the_board) print ("The Game is a TIE") game_on = False else: turn = 'Player 1' if not replay(): break
2e93a17e1a4dd98601a86e43c69478b15ad3a15a
vijiang/507_collab_test
/prog.py
142
3.5625
4
import random def num_vowels(s): vowels=0 for letter in s: if letter in [a,e,i,o,u]: vowels+=1 print(vowels)
0d6c7873bebb2346661f55584ee6d735e34b4f82
eunnah/fizzbuzz
/fizzbuzz.py
513
3.890625
4
import sys try: n = sys.argv[1] except IndexError: n = input("Enter something, yo! ") while type(n) != int: try: n = int(n) except ValueError: n = input("Enter something, yo! ") print("Fizz buzz counting up to " + str(n)) counter = 0 for counter in range(1,n+1): if counter % 3 == 0 and counter % 5 == 0: print("fizz buzz") elif counter % 3 == 0: print("fizz") elif counter % 5 == 0: print("buzz") else: print(counter)
ac82eae64050ab1efbac63f893a9744502851967
GanMan78/MachineLearning
/Matplotlib/Students Data/Matplot.py
1,552
3.96875
4
import pandas as pd import matplotlib.pyplot as plt def main(): Line="*"*60 excel='StudentData.xlsx' data=pd.read_excel(excel) print(Line) print("Size of the data is: ",data.shape) print("All data of excel sheet") print(Line) print(data) print(Line) print("First 5 rows from file") print(data.head()) print(Line) print("Last 3 rows of file") print(data.tail(3)) print(Line) sorted_data=data.sort_values(["Name"],ascending=False) print("Data after sorting according to reverse alphabetical order") print(sorted_data) #Plot 1 data["Age"].plot(kind="hist") plt.xlabel("Age Band") plt.ylabel("No of Students") plt.title("Student-Age relationship using Histogram") plt.show() #Plot 2 data["Age"].plot(kind="barh",color="m") plt.xlabel("Age of student") plt.ylabel("Students in order") plt.title("Student-Age relationship using horizontal Bar graph") plt.show() #Plot 3 plt.plot(data["Name"],data["Age"], "g--", label='Default') plt.xlabel("Students") plt.ylabel("Age") plt.title("Student-Age relationship using Line plot") plt.legend(loc="best") plt.show() #Plot 4 data["Age"].plot(kind="bar",color="c",alpha=0.7) plt.xlabel("Index wise Students") plt.ylabel("Age of student") plt.title("Student-Age relationship using vertical Bar graph") plt.show() if __name__=="__main__": main()
b3cfb72146e76d321d5cbe2c90dd6367eb3b2c76
AfSIS-at-CIESIN/RemoteSensing
/meters-degrees-conversion/meters-degree.py
251
4.0625
4
##meters-degree.py ##written by Kimberly Peng ##date: 2015 ##this script converts meters to decimal degrees met=input("What is the meter resolution? Enter>>") meters=float(met) sec=meters*(1/30.87) deg=sec/3600 print("Approximate decimal degrees is", deg)
198c9bb65c0464de64709d56dd2ca14e837c0ca7
captainamerica23/6.00.1x
/w4.ps.q9.py
986
3.84375
4
hand_choice = '' hand = '' while True: hand_choice = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') if hand_choice == 'e': break elif hand_choice != 'n' and hand_choice != 'r': print "Invalid command." continue if hand_choice == 'n': hand = dealHand(HAND_SIZE) elif hand_choice == 'r': if hand == '': print "You have not played a hand yet. Please play a new hand first!"+'\n' continue while True: player = raw_input('Enter u to have yourself play, c to have the computer play: ') if player != 'u' and player != 'c': print "Invalid command." continue if player == 'u': playHand(hand, wordList, HAND_SIZE) elif player == 'c': compPlayHand(hand, wordList, HAND_SIZE) break
c2242fd5c052f01c624059e87c5dd795b935e6d0
Palash144/60-LED-Build-Light-Board
/showBuild.py
2,702
3.609375
4
# NeoPixel build board control # Author Ben Janos ([email protected]) # # Uses the rpi_ws281x library to control the LEDs # Get it here - https://github.com/jgarff/rpi_ws281x # # This program assumes you have a file (status.txt) that contains # the color of each pixel row by row. 6 colors in each row with # 10 rows total. Acceptable colors are red, green, yellow, blue and off # # Example status.txt file: # green green green green green green # green green green green green green # green green green green green green # green green green green green green # red red red red red red # green green green green green green # green green green green green green # off off red red green green # green green green green green green # yellow yellow yellow yellow yellow yellow import time import sys from neopixel import * # LED strip configuration LED_COUNT = 60 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 5 # DMA channel to use for generating signal (try 5) LED_BRIGHTNESS = 30 # Set to 0 for darkest and 255 for brightest^M LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) # Looks like the rpi_ws281x library have RED and GREEN switched?!? RED = Color(0, 255, 0) GREEN = Color(255, 0, 0) YELLOW = Color(255, 255, 0); BLUE = Color(0, 0, 255); OFF = Color(0, 0, 0); def setPixel(color, pixel): if color == 'red': strip.setPixelColor(pixel, RED) elif color == 'green': strip.setPixelColor(pixel, GREEN) elif color == 'yellow': strip.setPixelColor(pixel, YELLOW) elif color == 'blue': strip.setPixelColor(pixel, BLUE) elif color == 'off': strip.setPixelColor(pixel, OFF) strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) strip.begin() i = 0; with open('/home/pi/BuildLight/status.txt') as f: for line in f: print line lineStatus = line.split() print len(lineStatus) if i != 0: i += 1 if 0 < len(lineStatus): setPixel(lineStatus[0], i) i += 1 else: setPixel('off', i) if 1 < len(lineStatus): setPixel(lineStatus[1], i) i += 1 else: setPixel('off', i) if 2 < len(lineStatus): setPixel(lineStatus[2], i) i += 1 else: setPixel('off', i) if 3 < len(lineStatus): setPixel(lineStatus[3], i) i += 1 else: setPixel('off', i) if 4 < len(lineStatus): setPixel(lineStatus[4], i) i += 1 else: setPixel('off', i) if 5 < len(lineStatus): setPixel(lineStatus[5], i) # After setting all 60 LED pixels show the entire strip. strip.show()
a51dbfde20535bf25df91451cbb7d02731c865c7
gibson20g/faculdade_exercicios
/moda_2.py
190
3.546875
4
import statistics amostra = [] while True: n = int(input('Digite Valores de 0 a 10 varias vezes: ')) amostra += [n] if n == 0: break moda = statistics.mode(amostra) print('Moda', moda)
e4e48753c17246d173832d2d5f5bb352cb901301
gibson20g/faculdade_exercicios
/venda_de_combustivel_ex03.py
1,482
4
4
print('''Escolha o Tipo de Combustivel\nD - Diesel\nE - Etanol\nG - Gasolina''') combustivel = str(input('Escolha: ')) litros = float(input('Quantos Litros: ')) diesel = 4.486 etanol = 4.719 gasolina = 5.793 if combustivel == 'D' and 20 >= litros: tot = diesel * litros desc = tot - (tot * 0.02) print('O total de conta foi R${:.2f} você recebeu um desconto e pagará somente R${:.2f}'.format(tot, desc)) elif combustivel == 'E' and 20 >= litros: tot = etanol * litros desc = tot - (tot * 3/100) print('O total de conta foi R${:.2f} você recebeu um desconto e pagará somente R${:.2f}'.format(tot, desc)) elif combustivel == 'G' and 20 >= litros: tot = gasolina * litros desc = tot - (tot * 4/100) print('O total de conta foi R${:.2f} você recebeu um desconto e pagará somente R${:.2f}'.format(tot, desc)) elif combustivel == 'D' and litros >= 20: tot = diesel * litros desc = tot - (tot * 0.04) print('O total de conta foi R${:.2f} você recebeu um desconto e pagará somente R${:.2f}'.format(tot, desc)) elif combustivel == 'E' and litros >= 20: tot = etanol * litros desc = tot - (tot * 5/100) print('O total de conta foi R${:.2f} você recebeu um desconto e pagará somente R${:.2f}'.format(tot, desc)) elif combustivel == 'G' and litros >= 20: tot = gasolina * litros desc = tot - (tot * 6/100) print('O total de conta foi R${:.2f} você recebeu um desconto e pagará somente R${:.2f}'.format(tot, desc)) else: print('Opção Invalida\nTente Novamente')
7a7c57df27e9ebe41ca43971eb19227ff9cec091
gibson20g/faculdade_exercicios
/NotasBimestrais.py
310
3.921875
4
print("Você devera fornecer suas notas"), nota1b = float(input("Insira nota do 1 Bimestre: ")) nota2b = float(input("Insira nota do 2 Bimestre: ")) nota3b = float(input("Insira nota do 3 Bimestre: ")) media = nota1b + nota2b + nota3b / 3 print("Sua média é: {} Aprovado".format(media)), print("Nota: {} ")
6fbc27a3112849fca46676213facbd3d6edaff29
ejrach/my-python-utilities
/ResistorConverter/resistor-converter.py
6,426
3.75
4
# This script will allow you to: # 1. Choose by 4 color bands (tell me a value) # 2. Choose by value (tell me colors) # TODO: # make it easier to read the ohm value. for example: # 300000000 --> 300,000,000 ohms. # or 300000000 --> 300M ohms # currently the value is printed as: 300000000.0 from os import system import re # value entered: color_mapping = { "0": "Black", "1": "Brown", "2": "Red", "3": "Orange", "4": "Yellow", "5": "Green", "6": "Blue", "7": "Violet", "8": "Grey", "9": "White", "a": "Gold", "b": "Silver" } ohm_multiplier_mapping = { "Black": 1, "Brown": 10, "Red": 100, "Orange": 1000, "Yellow": 10000, "Green": 100000, "Blue": 1000000, "Violet": 10000000, "Grey": 100000000, "White": 10000000000, "Gold": .1, "Silver": .01 } tolerance_mapping = { "Brown": "+/- 1%", "Red": "+/- 2%", "Green": "+/- 0.5%", "Blue": "+/- 0.25%", "Violet": "+/- 0.1%", "Grey": "+/- 0.05%", "Gold": "+/- 5%", "Silver": "+/- 10%" } multiplier_list = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, .1, .01 ] def clear(): _ = system('clear') def colors_to_value(user_input): # This function expects a string value. # for example: "564J" # first band is the first digit of the resistor value # look up the key value corresponding to the color value band1_color = color_mapping.get(user_input[0]) band1_key = list(color_mapping.keys())[ list(color_mapping.values()).index(band1_color)] # second band is the second digit of the resistor value # look up the key value corresponding to the color value band2_color = color_mapping.get(user_input[1:2]) band2_key = list(color_mapping.keys())[ list(color_mapping.values()).index(band2_color)] # third band is the multiplier of the resistor value band3_color = color_mapping.get(user_input[2:3]) band3_multiplier = ohm_multiplier_mapping.get(band3_color) # fourth band is the tolerance of the resistor value band4_color = color_mapping.get(user_input[-1]) band4_tolerance = tolerance_mapping.get(band4_color) # Build the value using the multipler resistor_value = float(band1_key + band2_key) * band3_multiplier # return the resistor value along with the tolerance return f"{str(resistor_value)} ohms {band4_tolerance}" # This function displays the menu for selection, validates the user input, calls # the colors_to_value function and displays the result def color_band_selection(): # Print out the color selection menu for the user to select. for key, value in color_mapping.items(): print(f'{key}) {value}') print("r) Return to main menu") # a color code is entered here user_input = input("Enter your selection: ") user_input = user_input.lower() # TODO more error checking if 'r' in user_input: # return to calling function return elif len(user_input) is not 4: print("You must enter exactly 4 characters") input("Press any key to return to main menu...") else: # return a string that identifies the value msg = colors_to_value(user_input) clear() print(f"Your resistor value is: {msg}") print("") input("Press enter to continue...") def value_to_colors(first_digit, second_digit, multiplier_list_index): band1_color = color_mapping.get(first_digit) band2_color = color_mapping.get(second_digit) multiplier_value = multiplier_list[multiplier_list_index] band3_color = list(ohm_multiplier_mapping.keys())[ list(ohm_multiplier_mapping.values()).index(multiplier_value)] value = float(first_digit + second_digit) * multiplier_value print("") print("*" * 50) print( f'Your resistor color coding is: {band1_color} {band2_color} {band3_color}: {value} ohms') print("*" * 50) print("") print("Select the 4th band color for specific tolerance:") for key, value in tolerance_mapping.items(): print(f'{key}: {value}') input("Press enter to continue...") def validate_character(user_input): validated = True if (len(user_input) > 1): print("input error --> Too many characters. Try again.") return not validated if not re.match("^[0-9]*$", user_input): print("input error --> Use only number values 0-9. Try again.") return not validated return validated while(True): clear() print("=== 4 Band Resistor selection ===") print("1. Choose by color bands (tell me the value)") print("2. Choose by value (tell me the color bands)") print("3. Quit") try: choice = int(input("> ")) if choice is 1: # Choose by color bands clear() print("Select the color by entering the corresponding number value.") print(" e.g. for a color band of green, blue, yellow, gold --> enter 564a") color_band_selection() elif choice is 2: # Choose by value clear() valid_value = False while(not valid_value): first_digit = input( "Enter the FIRST digit of the value of the resistor (e.g. 5 for 56000): ") valid_value = validate_character(first_digit) valid_value = False while(not valid_value): second_digit = input( "Enter the SECOND digit of the value of the resistor (e.g. 6 for 56000): ") valid_value = validate_character(second_digit) for i, item in enumerate(multiplier_list): print(f'{i}) {item}') while (True): multiplier_list_index = int(input( "Select the multiplier value of the resistor (e.g. 4 for 10000, or think 4 zeros): ")) if multiplier_list_index in range(0, len(multiplier_list) + 1): break else: input( "input error --> Incorrect selection. Press enter to try again.") value_to_colors(first_digit, second_digit, multiplier_list_index) else: clear() break except ValueError: continue
4b276fb67a33eeb3940e9dc510fb7ac004b3d0e0
SaimonFury/lesson1
/numbers.py
83
3.5
4
v = int(input('Введите число от 1 до 10: ')) x = 10 + v print(x)
054305fbabef5221e1ad0f1a3139941c748e6945
boopalanjayaraman/DataStructures_Algorithms
/Big O Analysis - Project 01/Task2.py
1,549
4.09375
4
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv 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 2: Which telephone number spent the longest time on the phone during the period? Don't forget that time spent answering a call is also time spent on the phone. Print a message: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". """ from collections import defaultdict if __name__ == '__main__': #The whole data of calls are actually for September 2016, #And hence it does not need to be filtered for time period. Process the whole file. #Get a mapping between number and their time caller_col_index = 0 receiver_col_index = 1 time_col_index = 3 phone_usage = defaultdict(int) #key: phone_number, val: time for call_record in calls: phone_usage[call_record[caller_col_index]] += int(call_record[time_col_index]) phone_usage[call_record[receiver_col_index]] += int(call_record[time_col_index]) longest_time_duration = 0 high_usage_number = '' for key, val in phone_usage.items(): if val > longest_time_duration: longest_time_duration = val high_usage_number = key print('{0} spent the longest time, {1} seconds, on the phone during September 2016.'.format(high_usage_number, longest_time_duration))
794ec7622144b5ae53726ece289440cb4ff9599a
boopalanjayaraman/DataStructures_Algorithms
/Data Structure Scenarios/LRUCache.py
2,425
4
4
# ordered dictionary preserves the order of items in which they were inserted # To know the least accessed item, we can remove the item and re-add it whenever it is accessed # In that way, even unaccessed items will be ordered in the least-used fashion from collections import OrderedDict class LRU_cache(object): def __init__(self, capacity = 10): self.cache = OrderedDict() self.capacity = capacity def get(self, key): if key in self.cache.keys(): #update the existing order since the item is accessed self.update_existing_order(key) return self.cache[key] else: return -1 def set(self, key, value): if key in self.cache.keys(): #update the existing order since the item is accessed self.cache.pop(key) self.cache[key] = value else: #check if the dictionary has reached its limit, and if yes, remove the last accessed (first added) item if len(self.cache) == self.capacity: self.cache.popitem(last=False) self.cache[key] = value def update_existing_order(self, key): # since the item already exists, we need to re-insert the item into the cache # a redundant step to achieve LRU functionality value = self.cache.pop(key, -1) if (value != -1): self.cache[key] = value def __str__(self): return str(self.cache) if __name__ == '__main__': # test cases our_cache = LRU_cache(5) our_cache.set(1, 1) our_cache.set(2, 2) our_cache.set(3, 3) our_cache.set(4, 4) print(our_cache) #prints whole cache print(our_cache.get(1)) # returns 1 print(our_cache.get(2)) # returns 2 print(our_cache.get(9)) # returns -1 because 9 is not present in the cache our_cache.set(5, 5) our_cache.set(6, 6) print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry print(our_cache) #prints whole cache, without 3 #additional test cases our_cache.get(2) our_cache.get(2) our_cache.get(2) our_cache.get(2) our_cache.get(2) our_cache.get(2) #does not remove any item and cache is intact, except the order. Item 2 has been shifted to the last (latest) in order print(our_cache)
50c9f9833fa4cc542158bc31e1fef57033cbeb30
samhaug/Linux_class
/pandas_intro/pandas_demo.py
3,138
3.65625
4
#!/home/samhaug/anaconda2/bin/python ''' ============================================================================== File Name : pandas_demo.py Purpose : Introduce some basic pandas functionalities Creation Date : 14-02-2018 Last Modified : Wed 14 Feb 2018 01:00:08 PM EST Created By : Samuel M. Haugland ============================================================================== ''' import numpy as np from matplotlib import pyplot as plt import pandas as pd # Read excel file to DataFrame object df = pd.read_excel('appendixB.xlsx',skiprows=2) df_3 = pd.read_excel('appendixB.xlsx',skiprows=3) # Dataframe objects are just concatenated series objects, a series is a single # column s = df[df.columns[0]] s = df['Study'] # Find unique studies u = df['Study'].unique() #return first ten rows first_ten = df.head(10) #return last ten rows last_ten = df.tail(10) #return dataframe without column df_drop = df.drop('Study',axis=1) #return dataframe with columns renamed #rename = df.rename(columns={'oldname':'newname', # 'oldname':'newname'}) rename = df.rename(columns={'Study':'STUDY', 'sample #':'Sample_no'}) # return dataframe of only study and sample column study_sample = df[['Study','sample #']] # Boolean indexing of dataframe object takahashi = df.loc[df['Study']=='Takahashi, 1978'] # & means 'and', | means 'or' # Index all studies by takahashi,1978 that also have xtal phases 'gl+ol' takahashi = df.loc[(df['Study']=='Takahashi, 1978') & (df['xtal phases']=='gl+ol')] # Index all studies by takahashi,1978 or studies that have gl+ol+sp as xtal phase takahashi_or_glolsp = df.loc[(df['Study']=='Takahashi, 1978') | (df['xtal phases']=='gl+ol+sp')] # Index all studies not by takahashi,1978 or studies that have gl+ol+sp # as xtal phase not_takahashi = df.loc[(df['Study']!='Takahashi, 1978') | (df['xtal phases']=='gl+ol+sp')] # Find all studies with NaN in the 'melt CoO' position no_coo = df_3.loc[df_3['melt CoO'].isnull()] # Crosstabulate to get a quick overview of the data in a sheet cross = pd.crosstab(df['Study'],df['xtal phases'],margins=True) # You can sum the elements in a series by column # Total number of studies cross['All'].sum() # Total number of studies with xtal phases gl+ol+sp cross['gl+ol+sp'].sum() # Sort dataframe alphabetically by Study sort_df = df.sort_values(['Study']) # Sort dataframe first by study then by sample # sort_df = df.sort_values(['Study','sample #']) # Sort Study ascending, sample decending # ascending list is boolean sort_df = df.sort_values(['Study','sample #'],ascending=[1,0]) #Get values from series as numpy linspace t_k = df['T(K)'].values #Merge these two into one dataset #USE SKIPROWS, NOT HEADER df = df[df.columns[0:9]] d_3 = df_3[df_3.columns[9::]] df = df.drop([0]) df_merge = pd.concat([df,df_3],axis=1) #Save multiple dataframes to different sheets in excel file writer = pd.ExcelWriter('output.xlsx') df_merge.to_excel(writer,'Sheet1') df.to_excel(writer,'Sheet2') df_3.to_excel(writer,'Sheet3') writer.save()
109d7adc06ec9c8d52fde5743dbea7ffb262ab33
edenizk/python_ex
/dict.py
1,321
4.21875
4
def main(): elements = {"hydrogen": 1, "helium": 2, "carbon": 6} print("print the value mapped to 'helium'",elements["helium"]) # print the value mapped to "helium" elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary print("elements = ",elements) print("is there carbon = ", "carbon" in elements) print("get dilithum = ",elements.get("dilithium")) print("get hydrogen = ",elements.get('hydrogen')) print("there is no dilithium ? ", elements.get("dilithium") is None) n = elements.get("dilithium") print("there is no dilithium ? ", n is None) print("there is no dilithium ? ", n is not None) print("type of elements = ", type(elements)) animals = {'dogs': [20, 10, 15, 8, 32, 15], 'cats': [3,4,2,8,2,4], 'rabbits': [2, 3, 3], 'fish': [0.3, 0.5, 0.8, 0.3, 1]} print(sorted(animals)) elements2 = {"hydrogen": {"number": 1, "weight": 1.00794, "symbol": "H"}, "helium": {"number": 2, "weight": 4.002602, "symbol": "He"}} print("hydrogen weight = ",elements2['hydrogen']['weight']) a = [1, 2, 3] b = a c = [1, 2, 3] print(a == b) print(a is b) print(a == c) print(a is c) main()
2d534e5720d00c8c0f3e80d308844c65f2f5c15c
edenizk/python_ex
/gandalf exercises/4.1 guessing game.py
463
3.90625
4
import random def game(): i=0 n=int(input('n=')) rand=random.randrange(1,n) while True: a=int(input('guess the num: ')) if a==rand: print('number was:',rand ,'\nYou guess correctly in ',i,'times') break; elif a>rand: print('guess again it was too high') i+=1 elif a<rand: print('too low guess again') i+=1 def main(): game() main()
579a2fbc1f237e1207be37752963d17f2011b629
edenizk/python_ex
/ifstatement.py
866
4.15625
4
def main(): phone_balance = 10 bank_balance = 50 if phone_balance < 10: phone_balance += 10 bank_balance -= 10 print(phone_balance) print(bank_balance) number = 145 if number % 2 == 0: print("Number " + str(number) + " is even.") else: print("Number " + str(number) + " is odd.") age = 35 free_up_to_age = 4 child_up_to_age = 18 senior_from_age = 65 concession_ticket = 1.25 adult_ticket = 2.50 if age <= free_up_to_age: ticket_price = 0 elif age <= child_up_to_age: ticket_price = concession_ticket elif age >= senior_from_age: ticket_price = concession_ticket else: ticket_price = adult_ticket message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price) print(message)
ddfe6ed0932774f70f31c50121a5334d6e8f16bb
edenizk/python_ex
/hackerrank exercises/Nested Lists.py
702
3.515625
4
students = [] for _ in range(int(input())): name = input() score = float(input()) students.append([name,score]) #studets.sort() #print(students[0][1]) tmp1 = students[0][1] #tmp2 = students[0][0] for i in range(1, len(students)): if tmp1 > students[i][1]: tmp1 = students[i][1] #tmp2 = students[i][0] tmp4 = [["", 101.0]] print("asd",tmp4[0][1]) for i in range(1, len(students)): if tmp4[0][1] == students[i][1]: tmp4.append([students[i][0], students[i][1]]) if tmp1 < students[i][1] and float(tmp4[0][1]) > students[i][1]: tmp4 = [students[i][0], students[i][1]] tmp4.sort() for i in range(0, len(tmp4)): print(tmp4[i][0])
44c7a70129b725ee4e9d18cf3d4b46e510d32360
edenizk/python_ex
/gandalf exercises/3.5.1 - 3.5.2 - 3.5.3 dictionary database with zip.py
691
3.625
4
def zipdic(sentence,a,b,c,d,e): print(sentence['what'][a%2],sentence['who'][b%3], sentence['how'][c%2],sentence['do'][d%2], sentence['where'][e%3]) def main(): sentence=dict(zip(['what','who','how','do','where'],[ ['What what','Stray'], ['Doctor','Cat','Dog'], ['ludly','happily'], ['cry','laugh'], ['in the street','in the home','under the dome']])) a = int(input("a= ")) b = int(input("b= ")) c = int(input("c= ")) d = int(input("d= ")) e = int(input("e= ")) zipdic(sentence,a,b,c,d,e) main()
85e4355c82cb4f32f161d66b0222c379629f84cb
edenizk/python_ex
/gandalf exercises/4.3 random matrix generetor2.py
257
3.875
4
import random Matrix = lambda r,c,k: [[ random.randrange(1,k) for x in range(c)] for y in range(r)] def main(): c=int(input('choose columns= ')) r=int(input('choose rows= ')) k=int(input('range of k= ')) print(Matrix(r, c, k)) main()
020ce80ddb7b5e8a2d8df3bb3550202502b9ba53
vani33/PycharmProjects
/DuckTyping.py
1,495
3.515625
4
# class Duck: # def quack(self): # print('Quack, Quack....') # # # class Monkey: # def talk(self): # print('monkey talking like a duck: Quack,Quack...') # # # def invoke_quack(object): # #Non-Pythonic code # if hasattr(object,'quack'): # if callable(object.quack()): # object.quack() # # #Pythonic code:EAFP # try: # object.quack() # except AttributeError as e: # print(e) # # d = Duck() # m = Monkey() # invoke_quack(d) # invoke_quack(m) #student = {'name':'Vani','marks':98,'rollno':101} student = {'name':'Vani','rollno':101} #Non-Pythonic code(LBYL-Look Before You Leave) #This code is lengthy and there will be a performance issue if 'name' in student and 'marks' in student and 'rollno' in student: print('Hello I am {name}, My Rollno: {rollno}, My Marks:{marks}'.format(**student)) else: print('Missing Some keys') #Pythonic(EAFP) try: print('Hello I am {name}, My Rollno: {rollno}, My Marks:{marks}'.format(**student)) except KeyError as e: print('Missing {} key'.format(e)) #This is Non-pythonic code because it checks everytime def print4th_index_element(list): if len(list)>=5: print(list[4]) else: print('There is no such element') #This is pythonic code def print4th_index_element(list): try: print(list[4]) except IndexError: print('There is no such element')
711a105d564748f35250b9a02b4e8dae71c45f82
MaiadeOlive/Curso-Python3
/desafios-1mundo-01-35/D004 ANALISE VARIAVEL.py
500
3.671875
4
t = input('\033[;31mDigite algo: \033[m') print('\033[0;34mO tipo primitivo deste valor é \033[m', type(t)) print('\033[32mSó tem espaços?\033[m', t.isspace()) print('\033[33mÉ numérico? \033[m', t.isnumeric()) print('\033[35mÉ Alphabético? \033[m', t.isalpha()) print('\033[36mÉ Alphanumérico? \033[m', t.isalnum()) print('\033[37mEstá em maiúsculas? \033[m', t.isupper()) print('\033[31mEstá em minúsculas?\033[m', t.islower()) print('\033[34mEstá capitalizado? \033[m', t.istitle())
5f73caf286d67b1b6f2085ab7a74769cf22ce6b4
MaiadeOlive/Curso-Python3
/desafios-2mundo-36-71/D058 ADIVINHANDO WHILE.py
329
3.8125
4
import random cont = 0 print('---JOGO DA ADIVINHAÇÃO---') num = int(input('Digite seu palpite de 1 a 10: ')) a = (1, 11) l = random.choice(a) while a != l: cont = cont + 1 a = int(input('Tente novamente: ')) print('Bingo" \nO número {} que você escolheu esta correto!\nVocê levou {} tentativas!'.format(a,cont))
2b4684ed6de37e89afacdac8c2c4061b57061706
MaiadeOlive/Curso-Python3
/desafios-1mundo-01-35/D008 CONVERSÃO METROS EM CM,MM.py
176
3.65625
4
a = int(input('\033[1;4;34mQuantos metros tem sua rua? \033[m')) a1 = a a2 = a print('\033[1;4;35mSua rua tem {} metros, são {:.3f} cm e {:.4f} mm\033[m'.format(a, a1, a2))
627141b086b05f0738ad0821f1c7765ed47c5953
MaiadeOlive/Curso-Python3
/desafios-2mundo-36-71/D056 NOME, IDADE E SEXO.py
1,132
3.65625
4
somaidade = 0 mediaidade = 0 nomehomem = 0 idadehomem = 0 mulhermenos20 = 0 for c in range(1, 5): print('-----{}° PESSOA -----'.format(c)) nome = str(input('Digite seu nome: ').strip()) idade = int(input('Digite sua idade: ')) generosex = str(input('Digite seu sexo [M/F]: ').strip()) somaidade += idade mediaidade = somaidade / 4 if c == 1 and generosex in 'Mm': idadehomem = idade nomehomem = nome if generosex in "Mm" and idade > idadehomem: idadehomem = idade nomehomem = nome if idade < 20 and generosex in "Ff": mulhermenos20 += 1 print('A média de idade do grupo é de {} anos.'.format(mediaidade)) print('O nome do Homem mais velho é {} e ele tem {} anos'.format(nomehomem, idadehomem)) print('Existem {} mulheres menos de 20 anos'.format(mulhermenos20)) #if idade < 20 and se == 'f': #cont2 += 1 #if se == 'm' and idade > c: #print('A média de idade do grupo é de {}'.format(med)) #print('O nome do homem mais velho é {}'.format(nome)) #print('{} mulheres tem menos de 20 anos.'.format(cont2))
9f7254b1bfca544762ff533cc4f2bc179b2aa65a
MaiadeOlive/Curso-Python3
/desafios-1mundo-01-35/D028 ADIVINHANDO NUMEROS.py
191
3.671875
4
import random a = (0,1,2,3,4,5) l = random.choice(a) m = int(input("De 0 a 5 qual seria sua aposta? ")) if l == m: print("Caramba acertou!!!") else: print('Não foi dessa vez!')
39737ae12d5bdc8fc518727dd45b25f207bb49c9
katherinelamb/data
/scripts/us_cdc/environmental_health_toxicology/parse_precipitation_index.py
3,427
3.6875
4
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Author: Padma Gundapaneni @padma-g Date: 7/28/21 Description: This script cleans up a csv file on county level precipitation data downloaded from the CDC. URL: https://data.cdc.gov/browse?category=Environmental+Health+%26+Toxicology @input_file filepath to the original csv that needs to be cleaned @output_file filepath to the csv to which the cleaned data is written python3 parse_precipitation_index.py input_file output_file ''' import sys import pandas as pd def main(): """Main function to generate the cleaned csv file.""" file_path = sys.argv[1] output_file = sys.argv[2] clean_precipitation_data(file_path, output_file) def clean_precipitation_data(file_path, output_file): """ Args: file_path: path to a comma-separated CDC precipitation index data file output_file: path for the cleaned csv to be stored Returns: a cleaned csv file """ print("Cleaning file...") data = pd.DataFrame(pd.read_csv(file_path)) data["month"] = data["month"].map("{:02}".format) data["date"] = data["year"].astype(str) + "-" + data["month"].astype(str) if "Evapotranspiration" in file_path: data.rename(columns={ "spei": "StandardizedPrecipitation" + "EvapotranspirationIndex" }, inplace=True) data["fips"] = "0" + data["fips"].astype(str) data = pd.melt( data, id_vars=['state', 'county', 'fips', 'year', 'month', 'date'], value_vars=[ "StandardizedPrecipitation" + "EvapotranspirationIndex" ], var_name='StatisticalVariable', value_name='Value') data["dcid"] = "geoId/" + data["fips"].astype(str) elif "Palmer" in file_path: data.rename(columns={"pdsi": "PalmerDroughtSeverityIndex"}, inplace=True) data["countyfips"] = "0" + data["countyfips"].astype(str) data = pd.melt( data, id_vars=['year', 'month', 'date', 'statefips', 'countyfips'], value_vars=["PalmerDroughtSeverityIndex"], var_name='StatisticalVariable', value_name='Value') data["dcid"] = "geoId/" + data["countyfips"].astype(str) else: data.rename(columns={"spi": "StandardizedPrecipitationIndex"}, inplace=True) data["countyfips"] = "0" + data["countyfips"].astype(str) data = pd.melt( data, id_vars=['year', 'month', 'date', 'statefips', 'countyfips'], value_vars=["StandardizedPrecipitationIndex"], var_name='StatisticalVariable', value_name='Value') data["dcid"] = "geoId/" + data["countyfips"].astype(str) data.to_csv(output_file, index=False) print("Finished cleaning file!") if __name__ == "__main__": main()
6e192fdced74582346095cf118bf5a33f3bea869
davidnuna/Manga-Reminder
/domain.py
1,040
3.671875
4
class Manga(object): def __init__(self, name, chapter, website): self.name = name self.chapter = int(chapter) self.website = website def __str__(self): return str(self.name + ", " + str(self.chapter) + ", " + self.website + "\n") @staticmethod def read_from_file(line): manga_fields = line.split(",") return Manga(manga_fields[0], manga_fields[1], manga_fields[2]) @staticmethod def write_to_file(manga): return str(manga.name + "," + str(manga.chapter) + "," + manga.website + "\n") def read_file(): mangas = [] with open("mangas.txt", "r") as file: lines_in_file = file.readlines() for line in lines_in_file: line = line.strip() if line != "": mangas.append(Manga.read_from_file(line)) return mangas def update_file(mangas): with open("mangas.txt", "w") as file: for manga in mangas: new_line = Manga.write_to_file(manga) file.write(new_line)
ef951139419318682deb52d24fdfd10979eb1fe9
Conorrific/DC-python-3
/assignments/Fizz.py
273
4
4
num = int(input("Enter a number: ")) def game(): if num % 3 == 0 and num % 5 == 0: print("Fizz Buzz") elif num % 3 == 0: print(f"Fizz") elif num % 5 == 0: print(f"Buzz") else: print("Invalid number, sorry!") game()
df91ffbf1bb904cdfeb319a9c104f3f243affd27
arvindsaripalli/regret-coin
/regret-coin.py
2,592
3.546875
4
import requests import json import datetime import sys def get_current_rate(): current_price = 'https://api.coindesk.com/v1/bpi/currentprice.json' response = requests.get(current_price) data = json.loads(response.content) # Clean returned rate of comma rate = data['bpi']['USD']['rate'].split(",") if(len(rate) > 1): rate = rate[0] + rate[1] else: rate = rate[0] return float(rate) def get_historical_rate(year, month, day): time = str(year) + "-" + str(month) + "-" + str(day) historical_price = 'https://api.coindesk.com/v1/bpi/historical/close.json?start=' + time + '&end=' + time response = requests.get(historical_price) data = json.loads(response.content) # Historical price is returned as a float instead of string by # the api for some reason (inconsistent with above) rate = data['bpi'][time] return float(rate) def main(): while(True): now = datetime.datetime.now() now_year = now.year now_month = now.month now_day = now.day year_cap = 2010 month_cap = 07 day_cap = 17 invested = float(raw_input("If I had invested: \n")) print("USD into bitcoin on: \n") year = int(raw_input("year: ")) month = int(raw_input("month: ")) day = int(raw_input("day: ")) # Check if supplied dates preceed bitcoin if(year < year_cap): print("Error. Date supplied preceeds bitcoin. \n") continue elif(year == year_cap and month < month_cap): print("Error. Date supplied preceeds bitcoin. \n") continue elif(year == year_cap and month == month_cap and day < day_cap): print("Error. Date supplied preceeds bitcoin. \n") continue # Check if supplied dates are greater than present time if(year > now_year): print("Error. Future date supplied. \n") continue elif(year == now_year and month > now_month): print("Error. Future date supplied. \n") continue elif(year == now_year and month == now_month and day > now_day): print("Error. Future date supplied. \n") continue # Check if supplied dates are valid dates if(day < 1): print("Error. Invalid date supplied. \n") continue elif(month < 1): print("Error. Invalid date supplied. \n") continue # Add leading 0s to supplied month and day if single digit if(month / 10 == 0): month = "0" + str(month) if(day / 10 == 0): day = "0" + str(day) # Get current and historical bitcoin rates current_rate = get_current_rate() historical_rate = get_historical_rate(year, month, day) print("\nI would currently have: \n") print(str(current_rate * (invested / historical_rate)) + " USD") sys.exit() main()
af6678ae4824f149d21d7f3aa3e2ff2abc581102
jimmahoney/umber
/src/model.py
72,913
3.578125
4
""" model.py The data class definitons and methods, built on the pewee ORM with a sqlite3 database. The following tests assumes that the database has been created and that populate_database() has been run; see ../database/init_db. The script ../bin/umber_test runs these and other tests. # Find the people and their role in a course given its name. >>> democourse = Course.get(Course.name == 'Demo Course') >>> for (uname, rname) in sorted(democourse.username_to_rolename.items()): ... user = Person.by_username(uname) ... print("{} is {} in {}.".format(user.name, rname, democourse.name)) ... Jane Q. Doe is student in Demo Course. Johnny Smith is student in Demo Course. Tammy Tutor is tutor in Demo Course. Ted Teacher is faculty in Demo Course. # Find a person from their username. >>> john = Person.get(username='johnsmith') >>> print(john.name) Johnny Smith # test last, first >>> john.get_last_first() 'Smith, Johnny' # Change their name. >>> john.name = 'John Z. Smith' >>> rows_changed = john.save() # See the change. >>> newjohn = Person.get(username='johnsmith') >>> print(newjohn.name) John Z. Smith # Change it back. >>> john.name = 'Johnny Smith' >>> rows_changed = john.save() Another example: all registrations for democourse : >>> rs = list(Registration.select().where(Registration.course==democourse)) >>> len(rs) # (jane, john, ted, tammy) in demo course 4 See docs/model_notes.txt for more about the database model. Jim Mahoney | [email protected] | MIT License """ import os, yaml, re, mimetypes, shutil, random from functools import reduce from flask import url_for from werkzeug.security import generate_password_hash, check_password_hash from peewee import ( SqliteDatabase, Model, TextField, IntegerField, PrimaryKeyField, ForeignKeyField ) from bs4 import BeautifulSoup from utilities import ( markdown2html, link_translate, static_url, md5, Time, ext_to_filetype, filetype_to_icon, size_in_bytes, stringify_access, print_debug, clean_access_dict ) from settings import ( os_db, umber_url, protocol, hostname, umber_mime_types, os_root, os_courses, photos_url, url_base, os_default_course, site_course_path, site_home, due_grace_hours ) import gitlocal db = SqliteDatabase(os_db) class BaseModel(Model): class Meta: database = db # (peewee requires this 'database' name) def __repr__(self): # e.g. fields = ', '.join(["{}={}".format(x[0],repr(x[1])) for x in list(self.__dict__['_data'].items())]) return '<{}({}) at 0x{:X}>'.format(self.__class__.__name__, fields, id(self)) @classmethod def first(cls): return cls.select().first() @classmethod def all(cls): return list(cls.select().execute()) class Person(BaseModel): class Meta: db_table = 'Person' person_id = PrimaryKeyField(db_column='person_id') username = TextField(unique=True) password = TextField() name = TextField() email = TextField() notes = TextField() _by_username = {} # cache _admins = None @staticmethod def from_comma_string(comma_string): """ Return people list from a string of usernames e.g. "john,mary" """ return list(map(Person.by_username, comma_string.split(','))) @staticmethod def searchname(partialname, maxresults=32): """ search for a name or username - returning up to a given number """ people = Person.select().where( \ Person.name.contains(partialname) | \ Person.username.contains(partialname)) \ .order_by(Person.username).limit(maxresults) return [p.username for p in people] @staticmethod def create_person(username, name, email, password='', is_admin=False): # TODO : restrict legal usernames ... # * prohibit leading '_' (reserved for system) # * lowercase_only? underbar? numbers? # * enforce uniqueness with db.atomic(): (user, created) = Person.get_or_create(username=username) if created: user.name = name user.email = email if not password: password = str(random.getrandbits(32)) user.set_password(password) user.save() # enroll_site has in it db.atomic() too ... # the docs say its OK to nest them. Course.enroll_site(user, is_admin=is_admin) return user @staticmethod def edit_person(username, name, email, password): try: with db.atomic(): user = Person.by_username(username) user.name = name user.email = email if password != '': user.set_password(password) user.save() except: print_debug('OOPS : Person.edit_user(username="{}") failed' \ .format(username)) def course_data(self): """ return courses that this person is registered in as a dict with keys role,course,url,semester """ registrations = list(Registration.select() .where(Registration.person == self)) registrations.sort(key=lambda r: r.course.name) registrations.sort(key=lambda r: r.course.start_date, reverse=True) return [{'role':r.role.name, 'course':r.course.name, 'url':r.course.url, 'semester':Time(r.course.start_date).semester()} for r in registrations if not r.course.name == 'Umber'] def get_username(self, username): return Person.by_username(username) def make_admin(self): """ Turn this person into a site admin """ with db.atomic(): umber = Course.get_site() site_registration = Registration.get(course=umber, person=self) site_registration.role = Role.by_name('admin') site_registration.save() def works(self, course): query = (Work.select() .where( Work.person == self, Work.course == course )) return list(query.execute()) def _save(self): """ save to database and invalidate caches """ try: del Person._by_username[self.username] except KeyError: pass Person._admins = None self.save() def set_password(self, passwordtext): with db.atomic(): self.password = generate_password_hash(passwordtext) self._save() def check_password(self, passwordtext): return check_password_hash(self.password, passwordtext) def get_role(self, course): """ Return role of this person in that course """ if self.username in course.username_to_role: return course.username_to_role[self] else: return Role.by_name('visitor') def get_last_first(self): names = self.name.split(' ') return names[-1] + ', ' + names[0] # -- Flask-Login methods & tools -- @staticmethod def get_anonymous(): """ Create and return an anonymous Person """ # Not saved to database (i.e. save() not called). # Not logged in. anon = Person(name='anonymous', username='') anon.anonymous = True return anon def is_authenticated(self): return not self.is_anonymous() def is_active(self): return not self.is_anonymous() def is_anonymous(self): try: return self.anonymous except: return False def is_admin(self): """ return True if this user is an admin, false otherwise """ return self.username in Person.admins() def get_id(self): if self.username == None: return str('') else: return str(self.username) def get_photo_url(self): return photos_url + '/' + self.username + '.jpg' @staticmethod def generic_photo_url(): return photos_url + '/generic_student.png' @staticmethod def by_username(username): """ Returns anonymous person if not found """ if username not in Person._by_username: try: person = Person.get(username = username) #person = Person.select() \ # .where(Person.username==username).first() except: return Person.get_anonymous() Person._by_username[username] = person return Person._by_username[username] @staticmethod def by_rolename(rolename): """ Return list of users who have a given type of registration """ # ... in any registration record i.e. any course return list(Person.select() .join(Registration) .where(Registration.role == Role.by_name(rolename)) .execute()) @staticmethod def admins(): """ Return list of administrators """ if not Person._admins: Person._admins = {p.username : True for p in Person.by_rolename('admin')} return Person._admins class Course(BaseModel): class Meta: db_table = 'Course' course_id = PrimaryKeyField(db_column='course_id') active = IntegerField() assignments_md5 = TextField() credits = IntegerField() end_date = TextField() name = TextField() name_as_title = TextField() notes = TextField() path = TextField(unique=True) start_date = TextField() _site_course = None # course for site data def prepared(self): """ setup this instance after it's attributes are set """ # This method is essentially __init__ for these database objects. self._set_users() self.assignments = self._get_assignments() if not self.start_date: self.semester = '' else: self.semester = Time(self.start_date).semester() # url without request though that info is also in request self.url = umber_url + '/' + self.path self.abspath = os.path.join(os_courses, self.path) def __getattr__(self, key): # Define some attributes (.url, .abspath, .students, ...) # when they're needed. # # June 2019 : there is no "prepared" in python3's peewee; # see https://github.com/coleifer/peewee/issues/1479 # So I need another way to call this after instantiating a Course. # See docs.python.org/3/reference/expressions.html#attribute-references; # ... I can override __getattr__ to fill 'em in when first accessed. if not 'abspath' in self.__dir__(): self.prepared() return self.__getattribute__(key) def _set_users(self): """ define self.students, .faculty, .guests, .username_to_role """ # .students includes tutors; # username_to_rolename lists their role as 'tutor' registrations = list(Registration.select() .where((Registration.course == self) & (Registration.status != 'drop'))) self.students = [reg.person for reg in registrations if reg.role == Role.by_name('student')] self.faculty = [reg.person for reg in registrations if reg.role == Role.by_name('faculty')] self.guests = [reg.person for reg in registrations if reg.role == Role.by_name('guest')] self.students.sort(key=lambda s: s.name) self.faculty.sort(key=lambda s: s.name) self.username_to_role = {reg.person.username : reg.role for reg in registrations} self.username_to_rolename = {reg.person.username : reg.rolename() for reg in registrations} @staticmethod def get_all(): """ Return all but the 'Umber' course, sorted by semester & name """ result = [c for c in Course.all() if not c.name == 'Umber'] result.sort(key=lambda c: c.name) result.sort(key=lambda c: c.start_date, reverse=True) return result @staticmethod def create_course(name, path, start='', name_as_title='', copyfrom=os_default_course, user=None): if name_as_title == '': name_as_title = name if start == '': now = str(Time()) now_year = now[:4] now_month = now[5:7] if now_month < '06': start = now_year + '-' + '01-01' # spring elif now_month < '09': start = now_year + '-' + '06-01' # summer else: start = now_year + '-' + '09-01' # fall with db.atomic(): (course, created) = Course.get_or_create( name = name, path = path, start_date = start, name_as_title = name_as_title ) # Create a disk folder for a course by copying # files from some other course. # (If 'copyfrom' isn't defined, then those course files # had better already exist ... which is the case # for defaultcourse and democourse.) if copyfrom: abspath = os.path.join(os_courses, path) abscopyfrom = os.path.join(os_courses, copyfrom) shutil.copytree(abscopyfrom, abspath) # remove the old copied .git folder shutil.rmtree(os.path.join(abspath, '.git'), ignore_errors=True) gitlocal.init_add_commit(course, user) # initalize its .git folder return course @staticmethod def get_site(): """ return site admin course 'Umber' """ if not Course._site_course: Course._site_course = Course.get(name='Umber') return Course._site_course @staticmethod def create_site(): """ create site couse 'Umber' """ # for site resoruces i.e. help files, user id photos etc. with db.atomic(): (sitecourse, created) = Course.get_or_create( name = 'Umber', name_as_title = 'Umber<div>a course<br>managment<br>system</div>', path = site_course_path, start_date = '2018-01-01') return sitecourse def get_shortname(self): """ used in html title ; see Page.html_title """ # TODO : ... something shorter ? return self.name def is_site(self): """ true if this is the site course """ return self.path == site_course_path def person_to_role(self, person): """ Return role of person in course, or visitor """ return self.username_to_role.get(person.username, Role.by_name('visitor')) def username_is_member(self, username): return username in self.username_to_role def _get_assignments(self): return list(Assignment.select() \ .where(Assignment.course == self) \ .order_by(Assignment.nth)) def drop(self, user): """ Drop user (Person or username) from this course """ # (Students who are registered may have submitted work. # Rather than delete their files and database records, # I'm just changing their status to 'drop', and ignoring # those people in _set_users try: person = user name = person.name # Is this a Person object? except AttributeError: person = Person.by_username(user) # No - treat it as a username. name = person.name if name == 'anonymous' or name == '': return "error in drop with user '{}'".format(str(user)) with db.atomic(): registration = Registration.get(person=person, course=self) registration.status = 'drop' registration.date = str(Time()) registration.save() # refresh course data self._set_users() return "OK, dropped {}.".format(name) def get_profile_url(self): # site course ends with / ; others don't ... slightly different behavior. if self.url[-1] == '/': return self.url + 'sys/user' else: return self.url + '/sys/user' def get_home_url(self): """ return url for course home page """ if self.is_site(): # special case : Umber course home is docs/home, # so that all public stuff can be in docs/* home_path = site_home else: home_path = 'home' return os.path.join(self.url, home_path) def get_registered(self, rolename=None): registrations = list(Registration.select() .where((Registration.course == self) & (Registration.status != 'drop'))) if rolename == 'tutor': people = [reg.person for reg in registrations if reg.grade == 'tutor'] elif not rolename: people = [reg.person for reg in registrations] elif rolename == 'student': people = [reg.person for reg in registrations if (reg.role.name == rolename and reg.grade != 'tutor')] else: people = [reg.person for reg in registrations if reg.role.name==rolename] people.sort(key=lambda p: p.get_last_first()) return people def email_everyone_html(self): return "mailto:" + ','.join([p.email for p in self.get_registered()]) def has_username(self, username): return username in self.username_to_role def get_faculty_data(self): """ return {'email', 'name'} of faculty """ return [{'email':person.email, 'name':person.name} for person in self.faculty] def grade_data_list(self, student): """ return student's view grade list for templates/grades.html """ # See the description below for the faculty grid. result = list(self.get_assignments_with_extras()) for ass in result: # Hmmm - not sure why this needs .person_id here, but errors without. # Maybe something about how the jinja2 template treats variables? # Or because the assignment has had its fields modified?? ass.work = ass.get_work(student.person_id) (grade, css_grade) = ass.work.get_grade_css(faculty_view=True) ass.work_grade = grade ass.work_css_grade = "grade-{}".format(css_grade) ass.duedate = Time(ass.due).assigndate() return result def grade_data_grid(self): """ return faculty's grade grid for templates/grades.html """ # Returned data is list of dicts, one per student. # Each student dict includes list of student works, one per assignment. # The grade will be shown as # '…' if not submitted and not yet due # 'overdue' if not submitted and past due date # 'ungraded' if submitted and not graded # work.grade if submitted and graded # # The grade css class is "grade-*" # where * is one of (green,darkgreen,darkred,red,black) # for faculty viewing the color is : # red overdue : due > today and not submitted # brown faculty modified date > student seen date # darkgreen student modified date > faculty seen date # green ungraded : student has submitted; faculty hasn't graded # black none of above # for student viewing the color is : # brown ungraded : student has submitted; faculty hasn't graded # brown student modified; faculty hasn't seen # dark green faculty modified; student hasn't seen # green overdue : due > today and not submitted # black none of above # # The basic idea of the colors is that # green-ish means the viewer should respond (i.e. "go") # red-ish means that the other person should do something # (i.e. a problem) # result = [] for stud in self.students: # skip grade line for student if they are a tutor if self.username_to_rolename[stud.username] == 'tutor': continue works = [] for ass in self.assignments: work = ass.get_work(stud) (grade, css_grade) = work.get_grade_css(faculty_view=True) works.append({'url': work.get_url(), 'css_grade': 'grade-{}'.format(css_grade), 'grade': grade, 'id': work.work_id }) result.append({'email': stud.email, 'name' : stud.name, 'works': works }) return result def get_assignment_by_nth(self, nth): """ Return nth assignment in this course """ try: return Assignment.select() \ .where(Assignment.course == self, \ Assignment.nth == nth) \ .first() except: return None def update_assignments(self, assignments_data): """ Update course assignments from a dict of assignments_data[nth][name, due, blurb] """ # Note: passed argument is *not* made up of Assignment objects. # Note: this is designed to update *all* assignments. db_assignments = {a.nth : a for a in self._get_assignments()} with db.atomic(): for nth in assignments_data: if nth not in db_assignments: (db_assignments[nth], status) = Assignment.get_or_create( course=self, nth=nth) db_assignments[nth].name = assignments_data[nth]['name'] duedate = assignments_data[nth]['due'] db_assignments[nth].due = str(Time.parse(duedate)) new_blurb = assignments_data[nth]['blurb'] old_blurb = db_assignments[nth].blurb #print_debug(f" debug update_assignments : '{duedate}'") #print_debug(f" md5(new_blurb) = '{md5(new_blurb)}'") #print_debug(f" new_blurb = '{new_blurb}' ") #print_debug(f" ass.blurb_hash = '{db_assignments[nth].blurb_hash}'") #print_debug(f" ass.blurb = '{old_blurb}' ") #print_debug(f" new == old ? {new_blurb == old_blurb}") if md5(new_blurb) != db_assignments[nth].blurb_hash: # is this changed? db_assignments[nth].blurb = new_blurb # yes: update it db_assignments[nth].blurb_hash = md5(new_blurb) db_assignments[nth].blurb_html = markdown2html( link_translate(self, new_blurb)) #print_debug(" updating cache ") #else: #print_debug(" NOT updating cache ") db_assignments[nth].save() self.assignments = self._get_assignments() def get_assignments_with_extras(self): """ Return list of assignments in this course with extra info """ # ... i.e. prepare the data for html display now = Time() # print(" now = " + str(now)) if len(self.assignments) == 0: self.assignment_nth_plus1 = 1 else: self.assignment_nth_plus1 = self.assignments[-1].nth + 1 for ass in self.assignments: duedate = Time(ass.due) if duedate < now: #print(" PAST : duedate = " + str(duedate)) ass.dateclass = 'assign-date-past' else: #print(" FUTURE : duedate = " + str(duedate)) ass.dateclass = 'assign-date' ass.date = duedate.assigndate() # for assignment list display ass.ISOdate = duedate.assignISOdate() # ditto return self.assignments def nav_page(self, user): """ return course's navigation page """ # TODO: put this in a "try" and do something reasonable if it fails. # (otherwise, pages in courses without sys/navigation.md will crash.) # TODO: should this be cached to self._nav_page ? # (Need it for both displaying and editing course's navigation page.) return Page.get_from_path(os.path.join(self.path, 'sys', 'navigation.md'), user=user) def nav_html(self, user, page): """ Return html for course's navigation menu for a given user & a given page """ return self.nav_page(user).nav_content_as_html(page) @staticmethod def enroll_site(person, datestring=None, is_admin=False): """ enroll a person in the site course """ # All users should be in this course. if not datestring: datestring = str(Time()) site_course = Course.get_site() if is_admin: site_role = Role.by_name('admin') else: site_role = Role.by_name('member') with db.atomic(): (reg, created) = Registration.get_or_create( person = person, course = site_course) if created or is_admin: # update role & date reg.role = site_role reg.date = datestring reg.status = '' reg.save() site_course._set_users() def make_student_work_folders(self): for person in self.students: student_abspath = os.path.join(self.abspath, 'students', person.username) if not os.path.exists(student_abspath): Page.new_folder(student_abspath, user=person, accessdict= {'read':person.username, 'write':person.username}) work_abspath = os.path.join(student_abspath, 'work') if not os.path.exists(work_abspath): Page.new_folder(work_abspath, user=person) def enroll(self, person, rolename, datestring=None, create_work=False): """ Enroll a person in this course with this role. """ # If there is an existing registration for the course&person, modify it. # Also enroll this person in the site couse if they aren't already # and if this isn't the site course itself. # Optionally create their work folder (if it doesn't already exist) # # add tutors by using student role with registration.grade='tutor' is_tutor = rolename=='tutor' if rolename == 'tutor': rolename = 'student' if not datestring: datestring = str(Time()) with db.atomic(): (reg, created) = Registration.get_or_create( person = person, course = self) reg.role = Role.by_name(rolename) reg.grade = 'tutor' if is_tutor else '' reg.status = '' # if re-enrolling would have been 'drop' reg.date = datestring reg.save() if not self.name == 'Umber': Course.enroll_site(person, datestring=datestring) if create_work: # Create folder for student work within the course folder. # The absolute path for their student work folder is # e.g. course/students/johnsmith/ with its .access.yaml # & course/students/johnsmith/work/ student_abspath = os.path.join(self.abspath, 'students', person.username) Page.new_folder(student_abspath, user=person, accessdict= {'read':person.username, 'write':person.username}) work_abspath = os.path.join(student_abspath, 'work') Page.new_folder(work_abspath, user=person) # refresh students self._set_users() class Page(BaseModel): # --- path, filename, url definitions --- # With settings on my laptop development machine as # os_courses /Users/mahoney/academics/umber/courses # then for the 'notes/week1' file within a course at 'fall/math' , # the parts are # url: http://127.0.0.1:5000/ umber / fall/math / notes/week1 # protocol hostname url_base path................... # file: /Users/mahoney/academics/umber/courses / fall/math / notes/week1 # os_courses path................... # Following python's os.path phrasing, other terms used here are # basename last word in address (same as os.path.basename) # abspath e.g. /Users/mahoney/.../fall/math/notes/week1 # dirname e.g. /Users/mahoney/.../fall/math/notes # This url would have in its flask request object the attributes # request.url_root 'http://localhost:8090/' # request.path '/umber/fall/math/notes/week1' # # Note that Page.path (e.g. fall/math/notes/week1) # does not have a leading slash or contain the url_base, # while request.path (e.g. /umber/fall/math/notes/week1) does. # # The Page object will also contain various extra data # that isn't stored in the sql database but is instead # pulled from the filesystem. class Meta: db_table = 'Page' # Each course has some sys/* pages which get special treatment. # Also here are site/sys/* pages for editing users and courses, # which are only accessible within the 'site' course. system_pages = ('assignments', 'navigation', 'error', 'folder', 'grades', 'roster', 'user', 'users', 'course', 'courses', 'registration', 'newuser', 'newcourse') editable_system_pages = ('assignments', 'navigation', 'grades', 'user', 'course') page_id = PrimaryKeyField(db_column='page_id') html = TextField() html_lastmodified = TextField() notes = TextField() path = TextField(unique=True) course = ForeignKeyField(model=Course, db_column='course_id', to_field='course_id') _mime_types = None @staticmethod def new_folder(abspath, accessdict=None, user=None): """ Create a new folder with the given abspath. Add it into the github repo. Optionally create its .access.yaml file. """ if os.path.exists(abspath): # bail without doing anything of this already exists # print_debug(' new_folder {} already exists '.format(abspath)) return None try: os.makedirs(abspath) # makes intermediate folders if need be. except: # bail with error message if the OS system won't do it. print_debug(' os.makdir("{}") failed '.format(abspath)) return None # Add an empty .keep file in this new folder, # as a workaround to force git to include this new folder. # (Git pays attention to files, not folders.) open(os.path.join(abspath, '.keep'), 'w').close() # unix 'touch' # Create the new folder object. path = os.path.relpath(abspath, os_courses) folder = Page.get_from_path(path, user=user) if accessdict: # don't do a git commit here - wait to do whole folder folder.write_access_file(accessdict, do_git=False) gitlocal.add_commit(folder) return folder @classmethod def get_from_path(cls, path, revision=None, action=None, user=None): """ Get or create a Page and set up all its internal data i.e. course, file info, user permissions, etc """ (page, iscreated) = Page.get_or_create(path=path) if user == None: user = Person.get_anonymous() page.user = user page.action = action page.revision = revision page._setup_file_properties() # sets page.is_file etc page.gitpath = os.path.join(os_courses, page.path_with_ext) page.login_google_url = url_for('login_google', pagepath=path) page.course = page.get_course() try: if page.course.page_error: ### Unexpected (to me anyway) behavior here : ### page.course = None ### if page.course: # This throws an error! ### ... ### Apparently the peewee database code has put hooks into ### the Page object to do tricky stuff for "page.course", ### seems to drop into peewee and complain. ### I'm avoiding this by returning the Umber site course ### but with a .page_error attribute set. ### In umber.py this will turn the request into 404 not found. return page except AttributeError: # .page_error field not set; keep going. pass page.relpath = page._get_relpath() page._setup_sys() # do this before .get_access() page.access = page.get_access() # gets .access.yaml property. page._setup_user_permissions() # sets page.can['read'] etc if revision or action=='history': page._setup_revision_data() # sets page.history etc page._setup_attachments() # sets .has_attachments page._setup_work() # page.html_title = page.get_html_title() return page def get_html_title(self): """ Return string for the <title></title> html tag. """ try: return self.course.get_shortname() + ' : ' + self.relpath except: return self.path def get_gitpath(self, abspath=None): """ Return file path of page (or abspath file) relative to course path, including file extension if any """ # This abspath option is used in gitlocal.py and umber.py:ajax_upload ; # for attachments the page is not the upload file. _abspath = self.abspath if abspath==None else abspath return os.path.relpath(_abspath, self.course.abspath) def _get_relpath(self): """ Return path of page relative to course path, e.g. notes/home for path=demo/notes/home in course 'demo' """ # self.course must be already set. return os.path.relpath(self.path, self.course.path) def attachments_folder(self): return self.abspath.replace(self.ext, '.attachments') def _setup_attachments(self): if self.is_file and self.ext == '.md': attach_dir = self.attachments_folder() if os.path.exists(attach_dir) and os.path.isdir(attach_dir): self.attachments = self.children(abspath=attach_dir) else: self.attachments = [] self.has_attachments = len(self.attachments) > 0 else: self.attachments = [] self.has_attachments = False def _setup_work(self): """ see if this is a students/<name>/work/<number> student work page; define .is_work and .work, set up .work for html display, update """ # print(' _setup_work : relpath = {}'.format(self.relpath)) m = re.match(r'students/(\w+)/work/(\d+)(\?.*)?', self.relpath) if m: now = Time() self.is_work = True (work_username, work_nth, ignore) = m.groups() work_nth = int(work_nth) self.work_person = Person.by_username(work_username) self.work_assignment = self.course.get_assignment_by_nth(work_nth) self.work = self.work_assignment.get_work(self.work_person) duedate = Time(self.work_assignment.due) self.work_due = duedate.assigndatedetail() # ... but give students a extra grace period of a few hours # before marking things as "late"; # this let's me get "end of day" to something reasonable, # without changing server timezone duedate.arrow = duedate.arrow.shift(hours=due_grace_hours) if self.work.submitted: submitdate = Time(self.work.submitted) self.work_submitted = submitdate.assigndate() self.work_is_late = submitdate > duedate else: self.work_submitted = '' self.work_is_late = now > duedate self.work_grade = self.work.grade # update *_seen fields in the database # TODO : think about whether there's a better # transactional way to update the database here. if self.user_role.name == 'faculty': self.work.faculty_seen = str(now) self.work.save() if self.user.username == work_username: self.work.student_seen = str(now) self.work.save() else: self.is_work = False #self.work = None #self.work_assignment = None #self.work_person = None #self.work_due = '' #self.work_submitted = '' #self.work_is_late = False #self.work_grade = '' def _setup_sys(self): """ define .is_sys. if it is, also define .sys_template, ./sys_edit_template """ # If relpath is 'sys/assignments', then is_sys will be true, # the template will be 'umber/sys/assignments.html' # and the edit template will be 'umber/sys/edit_assignments.html', # (and the access permissions will be in the first line of the template.) self.is_sys = self.relpath[:4] == 'sys/' # -- default values for sys templates for all pages -- if self.is_sys: which = self.relpath[4:] if which == '': which = 'folder' if which not in Page.system_pages: which = 'error' self.sys_template = 'sys/' + which + '.html' if which in Page.editable_system_pages: self.sys_edit_template = 'sys/edit_' + which + '.html' else: self.sys_edit_template = 'sys/editerror.html' def get_course(self): """ return this page's course """ # And if there is no course for this page, # return the site course but also set an error within it. # # extract path pieces e.g. ['demo', 'home'] path_parts = self.path.split('/') # build partial paths e.g. ['demo', 'demo/home'] # (stackoverflow.com/questions/13221896/python-partial-sum-of-numbers) paths = reduce(lambda x,y: x + [x[-1]+'/'+y], path_parts[1:], path_parts[0:1]) # build peewee's "where condition" to find matching courses. condition = Course.path for c in paths: condition = condition | Course.path % c # Get list of matching courses from database. # Choose the one with the longest path, # if more than on was found ... # which would only happen for courses directories # embedded within another course, which shouldn't happen. # TODO: make sure to test for that issue during new course creation query = Course.select().where(condition) courses = list(query.execute()) # if courses: return max(courses, key=lambda c: len(c.path)) else: # Couldn't find a course for that page, so return # the default course with a flag indicating the error. umber = Course.get_site() umber.page_error = True return umber def write_access_file(self, accessdict, do_git=True): """ Given an access dict from user input e.g. {'read':'students', 'write':['faculty','bob']} , write it to a .access.yaml file, and return its abspath. """ assert self.is_dir # this page should be a folder accesspath = os.path.join(self.abspath, '.access.yaml') accessfile = open(accesspath, 'w') # open or create # replace yaml permissions # (yaml.dump turns u'string' into ugly stuff so I convert to str(). accessfile.write(yaml.dump(clean_access_dict(accessdict))) accessfile.close() if do_git: # I've left an option to avoid this to handle # the case of a new folder efficiently, since # we can in that case commit the whole folder in one go # after this .access.yaml is created. gitlocal.add_commit(self) return accesspath def get_access(self): """ Return .access dict from .access.yaml in an enclosing folder or from the first line of a sys_template """ # e.g. {'read': ['janedoe', 'johnsmith'], 'write': 'faculty'} # default if we don't find it. #access_dict = {'read':'all', 'write':'faculty'} if self.is_sys: ## navigation is a special case : since it's a faculty editable file, ## I'll fill it it manually and not require that it have ## the {# #} first line. if self.relpath == 'sys/navigation' or \ self.relpath == 'sys/navigation.md': access_dict = {'read':'member', 'write':'faculty'} else: ## all other system files have an access spec as their first line ## e.g. {# {'read':'all', 'write':'faculty' #} template = os.path.join(os_root, 'templates', self.sys_template) firstline = open(template).readline() try: access_dict = eval(firstline.replace('{#','').replace('#}','')) except: # something fairly safe as a fall-back access_dict = {'read':'faculty', 'write':'faculty'} else: if self.is_dir: abspath = self.abspath else: abspath = os.path.dirname(self.abspath) while len(abspath) >= len(os_courses): accesspath = os.path.join(abspath, '.access.yaml') if os.path.exists(accesspath): accessfile = open(accesspath) # see https://msg.pyyaml.org/load access_dict = yaml.full_load(accessfile) accessfile.close() if type(access_dict) == type({}): # OK, we found an access dict, so stop here. break abspath = os.path.dirname(abspath) # i.e. "cd .." if 'read' not in access_dict: access_dict['read'] = '' if 'write' not in access_dict: access_dict['write'] = '' # clean up for display : self.read_access = stringify_access(access_dict['read']) self.write_access = stringify_access(access_dict['write']) return access_dict def _setup_user_permissions(self): """ Set page.can['read'], page.can['write'], page.user_role, page.user_rank from page.user, page.access, and page.course """ # Note that admins who are faculty in a given course # will have a displayed role of 'faculty' in that course # but will have admin access to nav menus etc. assert self.course != None # call self.set_course() first. assert self.access != None # call self.set_access() first. assert self.user != None self.user_role = self.course.person_to_role(self.user) # this includes 'tutor' even though there is no 'tutor' role; # and so I'm using this one in the displayed login role try: self.user_rolename = self.course.username_to_rolename[ self.user.username] except: self.user_rolename = 'visitor' self.user_rank = self.user_role.rank if self.user_role.name in ('faculty', 'admin') and not self.is_sys: # faculty & admin can read or write anything # ... but not system pages - I don't want 'edit' tab on all pages. self.can = {'read': True, 'write': True} return if self.user.is_admin(): # Let site admins do what they want in any course. # Change their display name to 'admin' if it isn't 'faculty'. # i.e. leave 'faculty' or 'student' display names as is. self.user_rank = Role.by_name('admin').rank if self.user_role.name != 'faculty': self.user_role = Role.by_name('admin') self.can = {'read':False, 'write':False} # default is deny access for permission in ('read', 'write'): yaml_rights = self.access[permission] access_needed = 10 # i.e. more than anyone has by default # can be list e.g. ['faculty', 'bob'] or string 'students' if type(yaml_rights) == type(''): yaml_rights = [ yaml_rights ] for name_or_role in yaml_rights: if name_or_role == self.user.username: self.can[permission] = True break elif name_or_role in Role.name_alias: access_needed = min(access_needed, \ Role.by_name(name_or_role).rank) if self.user_rank >= access_needed: self.can[permission] = True def get_mimetype(self): """ Return e.g. 'image/jpeg' for '.jpg' file """ if not Page._mime_types: mimetypes.init() Page._mime_types = mimetypes.types_map.copy() for key in umber_mime_types: Page._mime_types[key] = umber_mime_types[key] if self.ext == '': return 'text/plain' return Page._mime_types.get(self.ext, 'application/octet-stream') def children(self, abspath=''): """ return page for each file or folder below this folder """ result = [] if abspath == '': abspath = self.abspath try: path = os.path.relpath(abspath, os_courses) for name in sorted(os.listdir(abspath)): if name[0] == '.': # skip invisible files e.g. .access.yaml continue result.append(Page.get_from_path(os.path.join(path, name), user=self.user)) except OSError: # i.e. if abspath isn't a directory. pass return result def icon_url(self): """ return url for icon for this file type """ return static_url(filetype_to_icon[self.filetype]) def _setup_revision_data(self): """ read and store within page the git file revision data """ # The log is a list of tuples [(revision, date, author), ...] log = gitlocal.get_history(self) if len(log) == 0: link = self.url date = self.lastmodified.daydatetimesec() author = '' self.githashes = tuple() self.history = ([link, 'current', date, author], ) self.revision_date = date self.revision_commit = '' self.revision_prev_url = '' self.revision_next_url = '' self.revision_count = 1 self.revision = None # No git revision stored. else: self.githashes = tuple((githash for (githash, date, author) in log)) self.history = [None] * len(log) for i in range(len(log)): # say len(log) == 4 # nth => (new) current 3 2 1 (old) # i => 0 1 2 3 (old) if i == 0: nth = 'current' url = self.url else: nth = len(log) - i url = self.url + '?revision={}'.format(nth) # history => 0:url 1:nth 2:date 3:author self.history[i] = tuple((url, nth, log[i][1], log[i][2])) self.revision_count = len(log) self.revision_date = self.history[0][2] if self.revision: self.revision = int(self.revision) index = self.revision_count - self.revision self.revision_date = self.history[index][2] self.revision_commit = self.githashes[index] self.revision_next_url = self.url + '?revision={}'.format( min(self.revision + 1, len(log))) self.revision_prev_url = self.url + '?revision={}'.format( max(self.revision - 1, 1)) def _setup_file_properties(self): """ given self.path, set a bunch of information about the file including self.absfilename, self.exists, self.is_file, self.is_dir, self.lastmodified, self.breadcrumbs """ self.abspath = os.path.join(os_courses, self.path) self.path_with_ext = self.path # default, unless modified below if not os.path.exists(self.abspath): for ext in ['.md', '.html']: if ext == '.md' and os.path.exists(self.abspath + ext): self.abspath = self.abspath + ext self.path_with_ext = self.path + ext (ignore, self.ext) = os.path.splitext(self.abspath) self.exists = os.path.exists(self.abspath) #print_debug(f'debug _setup_file_properties : path={self.path} exists={self.exists} ') if not self.exists and self.ext == '': # creating a new file, so make it a .md markdown file self.ext = '.md' self.abspath += '.md' self.name_with_ext = os.path.split(self.abspath)[-1] if self.ext == '': self.name = self.name_with_ext else: self.name = self.name_with_ext[: - len(self.ext) ] # self.name_underlined = self.name + '\n' + '='*len(self.name) self.path_no_name = self.path[: - len(self.name) ] self.is_file = os.path.isfile(self.abspath) self.is_dir = os.path.isdir(self.abspath) if self.exists: stat = os.stat(self.abspath) #print_debug(f'debug _setup_file_properties : stat={str(stat)}') self.lastmodified = Time(stat.st_mtime) if self.is_dir: self.size = None self.filetype = 'directory' self.name_with_ext += '/' elif self.is_file: self.size = stat.st_size self.filetype = ext_to_filetype.get(self.ext, 'unknown') else: self.size = None self.filetype = 'unknown' else: self.lastmodified = None self.size = None # -- build url links for page breadcrumbs -- url_list = [url_base] + self.path.split('/') urlsofar = protocol + hostname self.breadcrumbs = '<a href="{}">{}</a>'.format(urlsofar, urlsofar) while url_list: pathpart = '/' + url_list.pop(0) urlsofar += pathpart self.breadcrumbs += '&nbsp;' + '<a href="{}">{}</a>'.format( urlsofar, pathpart) self.url = umber_url + '/' + self.path self.url_for_print_version = self.url + '?print=1' self.bytesize = size_in_bytes(self.size) def revision_content_as_html(self): content = gitlocal.get_revision(self) content_with_links = link_translate(self.course, content) return markdown2html(content_with_links) def content(self): """ Return file or github (revision) data for a page """ # python3 gotchas: # for text, I convert to a python3 string (utf8) # but for other (i.e. binary) data, I leave as python3 bytes if self.exists and self.is_file: if self.revision: text = gitlocal.get_revision(self) else: with open(self.abspath, 'rb') as _file: text_bytes = _file.read() try: text = text_bytes.decode('utf8') except: text = text_bytes # e.g. *.png files else: text = '' #print_debug(" page.content : page.action = '{}'".format(page.action)) return text def write_content(self, new_content): """ Write new data to page's file; return number of bytes written """ if self.can['write']: # shouldn't get here without this anyway with open(self.abspath, 'wb') as _file: # open as binary ... need to write bytes. try: new_bytes = new_content.encode('utf8') except: new_bytes = new_content bytes_written = _file.write(new_bytes) return bytes_written def content_as_html(self): """ Return file contents as html. """ # This also handles revisions since self.content() does. if not self.exists: return '' elif self.ext == '.md': # I'm caching the html version of .md pages in the sql database # (for the current version) # checking to see if the cache is stale with # the file's lastmodified and a sql db html_lastmodified fields. #print_debug(f" debug content_as_html cache") #print_debug(f" lastmodified='{self.lastmodified}' ; " + \ # f"html_lastmodified='{self.html_lastmodified}'") if self.revision: content = self.content() # pull from git repo content_with_links = link_translate(self.course, content) self.html = markdown2html(content_with_links) self.html_lastmodified = str(self.lastmodified) elif str(self.lastmodified) != self.html_lastmodified: #print_debug(f" updating {self.path}") with db.atomic(): content = self.content() # pull from file content_with_links = link_translate(self.course, content) self.html = markdown2html(content_with_links) self.html_lastmodified = str(self.lastmodified) self.save() #else: #print_debug(f" using cache {self.path}") # cache : just use .html already read from sql html = self.html else: # Not markdown, so send the file (txt, html, ...) as is. html = self.content() # from file or git repo return html def action_query(self): """ Return empty string or '&action=edit' if editing """ if self.action == 'edit': return '&action=edit' else: return '' def nav_content_as_html(self, page): """ Return authorized parts of html & markdown at html . """ # Here self is the navigation.md page. # TODO: unlinkify current page # TODO: This implementation is pretty ugly. # Perhaps just do this explicitly without BeautifulSoup? # And make some tests ... # Each course has a menu navigation page which is a mixture of html # and markdown, including access tags that look like this : # <div access='student'> # ... # </div> # This method converts the content of that file to html, # keeping only the parts that this user is allowed to see. # # And do the link_translate first, before any markdown stuff, # so that it can see the context. content = self.content() content = link_translate(self.course, content) # parser = BeautifulSoup(content, 'html.parser') for role in list(Role.name_rank.keys()): divs = parser.find_all('div', access=role) if self.user_rank < Role.by_name(role).rank: for div in divs: div.extract() # remove this div from its parent parser insides = [] marker = '.~*#!#*~.' # something that won't be in the html. for divm in parser.find_all('div', markdown=1): contents = ''.join(divm.stripped_strings) mstring = markdown2html(contents) insides.append(mstring) divm.string = marker html = str(parser) # convert beautiful soup object to formatted unicode while insides: inside = insides.pop(0) html = html.replace(marker, inside, 1) # If the current page is one of the links in the nav menu, # that link should be unlinkified ... which I'm doing # with another (ugh) pass through BeautifulSoup, # now that markdown has run. # ------------- # TODO do the right thing for file.md, file.html, # and folder ; currently only "file" and "folder/" will work # in the nav markdown; the other non-canonical with redirectrs won't. # (So check other options in a loop, eh?) parser = BeautifulSoup(html, 'html.parser') anchor = parser.find('a', href=page.url) if anchor: span = parser.new_tag('span') span['class'] = 'thispage' span.string = anchor.string parser.find('a', href=page.url).replace_with(span) html = str(parser) return html class Assignment(BaseModel): class Meta: db_table = 'Assignment' assignment_id = PrimaryKeyField(db_column='assignment_id') nth = IntegerField(null=False, unique=True) active = IntegerField() blurb = TextField() blurb_hash = TextField() blurb_html = TextField() due = TextField(null=True) name = TextField() notes = TextField() course = ForeignKeyField(model=Course, db_column='course_id', to_field='course_id') def get_url(self): return '{}/sys/assignments#{}'.format(self.course.url, self.nth) def name_smaller(self): """ return html version of assignment name with <br> instead of spaces """ return self.name.replace(' ', '<br>') def get_work(self, person): """ Return Work for this assignment by given student """ # i.e. work = assignment.get_work(student) with db.atomic(): (work, created) = Work.get_or_create(assignment = self, person = person) if created: work.grade = '' # | I would have expected this to be work.notes = '' # | created with the sql defaults ... work.submitted = '' # | but apparently not. work.student_modified = '' work.faculty_modified = '' work.student_seen = '' work.faculty_seen = '' work.page = 0 work.save() return work class Role(BaseModel): class Meta: db_table = 'Role' role_id = PrimaryKeyField(db_column='role_id') name = TextField() rank = IntegerField() name_rank = {'admin': 5, 'faculty': 4, 'student': 3, 'member': 2, 'visitor': 1 } name_alias = {'admin': 'admin', 'administrator': 'admin', 'faculty': 'faculty', 'student': 'student', 'students': 'student', 'tutor': 'student', 'class': 'student', 'guests': 'member', 'guest': 'member', 'member': 'member', 'all': 'visitor', 'any': 'visitor', 'visitor': 'visitor' } _cache = {} @staticmethod def by_name(name): if not name in Role.name_rank: if name in Role.name_alias: name = Role.name_alias[name] else: name = 'visitor' if not name in Role._cache: Role._cache[name] = Role.get(name=name) return Role._cache[name] @staticmethod def unalias(alias): """ Convert alias to its standard role name. """ return Role.name_alias[alias] @staticmethod def create_defaults(): with db.atomic(): for (name, rank) in list(Role.name_rank.items()): Role.get_or_create(name=name, rank=rank) class Registration(BaseModel): class Meta: db_table = 'Registration' registration_id = PrimaryKeyField(db_column='registration_id') credits = IntegerField() date = TextField(null=True) grade = TextField() midterm = TextField() status = TextField() course = ForeignKeyField(model=Course, db_column='course_id', to_field='course_id') person = ForeignKeyField(model=Person, db_column='person_id', to_field='person_id') role = ForeignKeyField(model=Role, db_column='role_id', to_field='role_id') def rolename(self): """ return rolname for this registration, including 'tutor' """ return 'tutor' if self.grade=='tutor' else self.role.name class Work(BaseModel): class Meta: db_table = 'Work' work_id = PrimaryKeyField(db_column='work_id') grade = TextField() notes = TextField() submitted = TextField() student_modified = TextField(db_column='student_modified') student_seen = TextField(db_column='student_seen') faculty_modified = TextField(db_column='faculty_modified') faculty_seen = TextField(db_column='faculty_seen') assignment = ForeignKeyField(model=Assignment, db_column='assignment_id', to_field='assignment_id') person = ForeignKeyField(model=Person, db_column='person_id', to_field='person_id') page = ForeignKeyField(model=Page, db_column='page_id', to_field='page_id') @staticmethod def edit_grades(id_grade_dict): """ id_grade_dict is web form with some {'work_<id>':new_grade} extract id's & change grades """ # the dict also has other keys i.e. 'submit_work'; ignore them. try: with db.atomic(): for key in id_grade_dict: if key[:5] == 'work_': id = int(key[5:]) work = Work.get(work_id=id) # See get_grade_css for special grades ..., # The special grades "...", "overdue', 'ungraded' # are created when the actual grade is not set yet. grade = id_grade_dict[key] if grade in ('…', '...', 'overdue', 'ungraded'): grade = '' work.grade = grade work.save() except: print_debug('OOPS : Work.edit_grades(id_grade_dict="{}") failed' \ .format(id_grade_dict)) def get_url(self): # Also see templates/assignments.html return '{}/students/{}/work/{}.md'.format(self.assignment.course.url, self.person.username, self.assignment.nth) def get_grade_css(self, faculty_view): css_class = 'black' # the default # duedate = Time(self.assignment.due) duedate.arrow = duedate.arrow.shift(hours=due_grace_hours) now = Time() before_due_date = now < duedate # # Set blank times to '1901' to avoid errors. faculty_modified = self.faculty_modified or '1901' faculty_seen = self.faculty_seen or '1901' student_modified = self.student_modified or '1901' student_seen = self.student_seen or '1901' #print_debug(" faculty_modified = '{}'".format(faculty_modified)) #print_debug(" faculty_seen = '{}'".format(faculty_seen)) #print_debug(" student_modified = '{}'".format(student_modified)) #print_debug(" student_seen = '{}'".format(student_seen)) if faculty_view: if Time(faculty_modified) > Time(student_seen): css_class = 'brown' if Time(student_modified) > Time(faculty_seen): css_class = 'darkgreen' if not self.submitted: if before_due_date: grade = '…' else: grade = 'overdue' css_class = 'red' else: if not self.grade: grade = 'ungraded' css_class = 'green' else: grade = self.grade else: if Time(student_modified) > Time(faculty_seen): css_class = 'brown' if Time(faculty_modified) > Time(student_seen): css_class = 'darkgreen' if not self.submitted: if before_due_date: grade = '…' else: grade = 'l͟a͟t͟e͟' # l͟a͟t͟e͟ css_class = 'green' else: if not self.grade: grade = 'ungraded' css_class = 'brown' else: grade = self.grade if self.grade: # If a grade has been assigned, show it. Period. grade = self.grade return (grade, css_class) def init_db(): """ Create base database objects """ # i.e. roles & site course. # The Roles data must be in place for the login system to work. # And the Umber course must exist for user photos and site docs # and admin user role. # The sql database must already exist; see bin/init_db . # All these are "get_or_create", so running 'em multiple times won't hurt. Role.create_defaults() Course.create_site() def populate_production_db(interactive=False): """ create initial objects for production database """ # see umber/bin/init_db from utilities import toggle_debug toggle_debug() make_admin = False if interactive: make_admin = input(' Create admin? (y/n) ').lower()[0] == 'y' if admin: admin_username = input(' Admin username? ') admin_name = input(' Admin full name? ') admin_passwd = input(' Admin password? ') admin_email = input(' Admin email? ') with db.atomic(): defaultcourse = Course.create_course( name = 'Default Course', name_as_title = 'Default<br>Course', path = 'default_course', start = '2018-01-01', copyfrom = False ) if make_admin: (admin, created) = Person.get_or_create(username = admin_username) if created: admin.name = admin_name admin.email = admin_email password = admin_passwd else: if interactive: print(f' username "{admin_username}" already exists') print(' ... setting their is_admin=True') print(' ... leaving their name & email unchanged.') admin.is_admin = True admin.save() toggle_debug() def populate_db(): """ Create test & example development objects """ # i.e. democourse, jane, ted, john, adam; examples and tests. #print("Populating development database.") from utilities import toggle_debug toggle_debug() with db.atomic(): student = Role.by_name('student') faculty = Role.by_name('faculty') democourse = Course.create_course( name = 'Demo Course', name_as_title = 'Demo<br>Course', path = 'demo', start = '2018-01-01', copyfrom = False ) defaultcourse = Course.create_course( name = 'Default Course', name_as_title = 'Default<br>Course', path = 'default_course', start = '2018-01-01', copyfrom = False ) jane = Person.create_person( username = 'janedoe', name = 'Jane Q. Doe', email = '[email protected]', password = 'test' ) john = Person.create_person( username = 'johnsmith', name = 'Johnny Smith', email = '[email protected]', password = 'test' ) ted = Person.create_person( username = 'tedteacher', name = 'Ted Teacher', email = '[email protected]', password = 'test' ) tammy = Person.create_person( username = 'tammytutor', name = 'Tammy Tutor', email = '[email protected]', password = 'test' ) adam = Person.create_person( username = 'adamadmin', name = 'Adam Administrator', email = '[email protected]', password = 'test', is_admin = True ) default_date = '2018-01-02' democourse.enroll(john, 'student', default_date, create_work=False) democourse.enroll(jane, 'student', default_date, create_work=False) democourse.enroll(tammy, 'tutor', default_date, create_work=False) democourse.enroll(ted, 'faculty', default_date, create_work=False) # Assignments are set with a dict {nth: {name, due, blurb}. assignments_data = { 1: {'name': 'week 1', 'due': '2018-01-23', 'blurb': 'Do chap 1 exercises 1 to 10.'}, 2: {'name': 'week 2', 'due': 'Jan 28 2018 5pm', 'blurb': 'Write a four part fugue.'} } democourse.update_assignments(assignments_data) assign1 = democourse.get_assignment_by_nth(1) johns_work = assign1.get_work(john) johns_work.grade = 'B' johns_work.submitted = '2018-01-22T18:20:23-05:00' # on time johns_work.student_seen = johns_work.submitted johns_work.student_modified = johns_work.submitted johns_work.faculty_seen = '2018-01-28T16:00:00-05:00' johns_work.faculty_modified = johns_work.faculty_seen johns_work.save() janes_work = assign1.get_work(jane) janes_work.submitted = '2018-02-04T22:23:24-05:00', # past due # janes_work.grade = '' # not graded yet janes_work.student_seen = janes_work.submitted janes_work.student_modified = janes_work.submitted janes_work.save() toggle_debug() if __name__ == '__main__': import doctest doctest.testmod()
955eaaa6b0dbfe5c45a89a75963e50124e75d634
MrrRaph/BMP-Processing
/processors/printers/printHistogram.py
1,286
3.75
4
from matplotlib import pyplot as plt import numpy as np def printHistogram(bmp): """ Print the histogram of colors of the bmp file using Matplotlib Parameters ---------- bmp: BMP """ flattenedImage = bmp.imageData[:, :, :].flatten() blueFlattened = bmp.imageData[:, :, 0].flatten() greenFlattened = bmp.imageData[:, :, 1].flatten() redFlattened = bmp.imageData[:, :, 2].flatten() figure, axes = plt.subplots() axes.hist(flattenedImage, bins=256, color='cyan', alpha=0.3) if not (blueFlattened.all() == greenFlattened.all() == redFlattened.all()): axes.hist(blueFlattened, bins=256, color='blue', alpha=0.5) axes.hist(greenFlattened, bins=256, color='green', alpha=0.5) axes.hist(redFlattened, bins=256, color='red', alpha=0.5) axes.set_title(f'Color channel Histogram for given image {bmp.filename}') plt.legend(['Total of Channels', 'Blue Channel', 'Green Channel', 'Red Channel']) else: axes.hist(redFlattened, bins=256, color='gray', alpha=0.5) axes.set_title(f'Histogram of the grayscale image {bmp.filename}') plt.legend(['Total of Channels', 'Grayscale']) axes.set_xlabel('Value') axes.set_ylabel('Pixels Frequency') plt.show()
503c4e19158dde13eb6294e781fa4d63e5799ee1
MrrRaph/BMP-Processing
/processors/transformers/imageScale.py
629
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from utils import helpers as hp import numpy as np def scale(image, nR, nC): nR0 = len(image) nC0 = len(image[0]) return [ [ image[int(nR0 * r / nR)][int(nC0 * c / nC)] for c in range(nC) ] for r in range(nR) ] def imageScale(bmp, nR, nC): """ Scaling/Shriking the image by specifying rows and cols Parameters ---------- bmp: BMP nR: int nC: int Returns ------- np.ndarray((h, w, 3)) """ return np.array(scale(bmp.imageData, nR, nC)).astype(float)
c38d238de26c17699a4c27e7ae0458e5f9accb89
vatsaashwin/Trees-3
/symmetricTree.py
1,469
4
4
# // Time Complexity : O(n), n = number of elements # // Space Complexity : O(maxdepth) # // Did this code successfully run on Leetcode : Yes # // Any problem you faced while coding this : No # // Your code here along with comments explaining your approach # 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 isSymmetric(self, root: TreeNode) -> bool: #if root is null, return true if root == None: return True return self.recur(root.left, root.right) def recur(self, leftP1: TreeNode, rightP2: TreeNode) -> bool : #check if both of roots is null, return true if leftP1==None and rightP2==None: return True #check if any of the branch value doesn't match #or if one side is null and another isn't, return false if leftP1 == None or rightP2 == None or leftP1.val != rightP2.val: return False # now return True only if both side of the tree recursively gives same values for: #left tree's left child == right tree's right child and #left tree's right child == right tree's left child return self.recur(leftP1.left, rightP2.right) and self.recur(leftP1.right, rightP2.left)
7e232ffae79030cc86662e4ca6b5b8fc40d494d2
uni4/research
/shading2.py
590
3.6875
4
#画像にガウシアンフィルターを適用させるプログラム #https://algorithm.joho.info/programming/python/opencv-gaussian-filter-py/ import cv2 import numpy as np #def main(): # 入力画像を読み込み img = cv2.imread("org.jpg") # グレースケール変換 gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # 方法3 dst3 = cv2.GaussianBlur(gray, ksize=(3,3), sigmaX=1.3) #画像を表示 cv2.imshow("GaussianBlue", dst3) # 結果を出力 cv2.imwrite("output3.jpg", dst3) cv2.waitKey(0) cv2.destroyAllWindows() #if __name__ == "__main__": # main()
2f58dc3a9b0dbb2f2d8a5ad63fe3aef2ce421e12
Safe-Shammout/Python_Assesment
/main.py
15,445
3.515625
4
#Story line game #Safe Shammout 2021 from tkinter import * # for GUI and widgets from PIL import ImageTk, Image # for Images from tkinter import messagebox # for error messages (diagnose and recover) # variables names_list = [] # list to store names for leader board # Componenet 1 (Game Starter Window object) will be constructed through following class class GameStarter: def __init__(self, parent): # constructor, The __init__() function is called automatically every time the class is being used to create a new object. background_color = 'dark blue' # to set it as background color for all the label widgets # entry box self.entry_box = Entry(parent) self.entry_box.place(x=350, y=400) # continue button self.continue_button = Button(parent, text='Continue', font=('Helvetica', '13', 'bold'), bg='lawn green', command=self.name_collection) self.continue_button.place(x=550, y=550) # cancel button self.cancel_button = Button(parent, text='Cancel', font=('Helvetica', '13', 'bold'), bg='red', command=self.cancel) self.cancel_button.place(x=50, y=550) # method in class to collect the name entered by user, destry widgets and create a StoryWindow object def name_collection(self): name = self.entry_box.get() if name == '': messagebox.showerror('Name is required!', 'Please enter your name') elif len(name) > 15: # toi make sure user inputs between 1-15 characters messagebox.showerror('limit error', 'please enter a name between 1 and 15 characters' ) elif name.isnumeric(): messagebox.showerror('Name error', 'Name can only consist of letters' ) elif not name.isalpha(): messagebox.showerror('test', 'name cant consist of symbols') else: names_list.append(name) # add name to names list declared at the beginning self.entry_box.destroy() self.continue_button.destroy() self.cancel_button.destroy() StoryWindow(root) # cancel method def cancel(self): root.destroy() # Componenet 2 (Story wimdow object) will be constructed through following class class StoryWindow: def __init__(self, parent): # component 4: Dictionary collection of scenarios and options self.scenario_options = { 's1': 'You went on a trip overseas with your friends and you have decided to go by ship. Everything was going well until the welcoming cheerful sun slowly faded away. The sky turned pitch black, the only light source other than the torch you and your friends now share is the flashes of the lightning. The waves start to play around with your ship. It seems the sea has rejected you and any moment the ship will top over. The compass stopped working and it seems that there is no way of communicating with the outside world.there is no reception. The ship has drifted off course and no one, not even the captain knows where you are. You are stuck in the middle of nowhere with no help from the outside world. Everyone is panicking and the captain is nowhere to be seen.....', 's1_opt1': 'Stay on the ship.', 's1_opt2': """Use one of the lifeboats\n and abandon the ship.""", 's2': 'Now you and your friends have set off in the life boat, but it seems the situation has gotten worse, you have drifted too far off. You are in the middle of the sea with limited food and drinking water. The fierce sea does not seem to be calming down and everyone is just hoping that things can get better. All of a sudden an island has been spotted.', 's2_opt1': 'Go to the island.', 's2_opt2': '''The island looks too sketchy you think that there isnt a safe place to set shore, So wait.''', 's3': "With the waves tossing you around randomly you hit the jackpot and land on an island. You have no idea how you got here but you're thankful. After setting ashore you are greeted by a creature that you have never seen before..It is so hairy that you can't tell the front of its head from the back, and it speaks human language, English. You are really shocked, amazed and mostly petrified by what you're seeing, doubting your own consciousness, have you lost it? \n The creature tells you that it can help you out.", 's3_opt1': 'Trust the creature', 's3_opt2': '''This creature is freaky as hell and this is so suspicious, go back to the ship and sail away immediately''', 's4_end': "The waves get more violent than ever, fortunately you land on an island, but this island is not the one you've seen before. Its a whole different island. Much smaller than the one you have seen before. You set up a camp until you realise this is your new home, with no contact to the outside world, with no idea as to where you are. You are the only habitants to this island. You have lived here for about 4 years, as long as you remember but you are not really sure, as days passed and you lost track\n you lose, GAME OVER", 's5_end': 'After setting sail and running away from that creature you are now lost in the ocean, back to square 1. Luckily out of nowhere the storm suddenly ends. The rescue team that has been sent out has finally found you', 's6_end': 'The creature explains to you the situation, gives you food supplies and also gives you a whole new ship. It turned out to be a really friendly creature. It helped you set sail and you arrive safely to your original destination', } # Background image on Frame self.bg_img = Image.open('storm1y.png') # update my image file image = ImageTk.PhotoImage(self.bg_img) # update PhotoImage image_label.configure(image=image) # upadate the label image_label.image = image # keep a reference! self.story_label = Message( parent, bg='MediumPurple4', text=self.scenario_options['s1'], bd=6, fg='white', font=('Helvetica', '13', 'bold'), ) self.story_label.place(x=100, y=20, width=570, height=400) # option 1 Button self.option1_button = Button( parent, text=self.scenario_options['s1_opt1'], font=('Helvetica', '13', 'bold'), bg='white', activebackground='RoyalBlue3', wraplength=0, command=self.option1, ) self.option1_button.place(x=30, y=500, width=320, height=100) # option 2 Button self.option2_button = Button( parent, text=self.scenario_options['s1_opt2'], font=('Helvetica', '13', 'bold'), bg='white', activebackground='RoyalBlue3', command=self.option2, ) self.option2_button.place(x=415, y=500, width=320, height=100) # exit button to take to LeaderboardWindow self.leader_board_button = Button(parent, text='Exit', font=('Helvetica', '13', 'bold'), bg='red', command=self.leaderboard_collection) self.leader_board_button.place(x=355, y=620) # index to keep track where the player is in the story self.index = 1 # points was coming with error in leaderboard method that its referenced without assignment # adding it here in the constructor solved the issue self.points = 0 def option1(self): # using or operator is more efficient than repeating conditions if self.index == 1 or self.index == 2: self.story_label.config(text=self.scenario_options['s3']) self.option1_button.config(text=self.scenario_options['s3_opt1']) self.option2_button.config(text=self.scenario_options['s3_opt2']) if self.index == 1: self.points += 400 else: self.points += 75 self.index = 3 else: self.points += 150 self.story_label.config(text=self.scenario_options['s6_end']) print (self.points) self.option1_button.destroy() self.option2_button.destroy() # self.leader_board_button = Button(parent, text="Leader Board", command=self.leaderboard_collection) # elif index ==2 : # self.story_label.config(text=scenario_options["s3"]) # self.option1_button.config(text=scenario_options["s3_opt1"]) # self.option2_button.config(text=scenario_options["s3_opt2"]) # index=3 # option 2 button method def option2(self): if self.index == 1: self.points += 250 self.story_label.config(text=self.scenario_options['s2']) self.option1_button.config(text=self.scenario_options['s2_opt1']) self.option2_button.config(text=self.scenario_options['s2_opt2']) self.index = 2 elif self.index == 2: self.points += -250 self.story_label.config(text=self.scenario_options['s4_end']) self.option1_button.destroy() self.option2_button.destroy() else: # self.leader_board_button = Button(parent, text="Leader Board", command=self.leaderboard_collection) self.points += 100 self.story_label.config(text=self.scenario_options['s5_end']) self.option1_button.destroy() self.option2_button.destroy() # self.leader_board_button = Button(parent, text="Leader Board", command=self.leaderboard_collection) def leaderboard_collection(self): self.option1_button.destroy() self.option2_button.destroy() self.story_label.destroy() self.leader_board_button.destroy() # save information to a file name = names_list[0] file = open('leader_board.txt', 'a') # open file or create if its first time in append mode if name == 'safe_erase': file = open('leader_board.txt', 'w') # this clears the data in file else: file.write(str(self.points)) # turn into string as will be displayed as text in a label file.write(' - ') file.write(name + '\n') file.close() # To dispolay name and score in seperate labels leaders = LeaderboardWindow(root) # create an instance of LeaderboardWindow so we can edit its labels input_file = open('leader_board.txt', 'r') # open in read mode line_list = input_file.readlines() # read the lines in text file line_list.sort() # sort them score is first so according to score print(line_list) # test sorting working top = [] # list to store only top 5 leader_list = line_list[-5:] # take last 5 index in list (as want highest) print(leader_list) # testing the last 5 is working for line in leader_list: points = line.split(' - ') top.append((int(points[0]), points[1])) # this is a list containing tuples (top) file.close() top.sort() top.reverse() print(top) # for testing (list is sorted after testing so good) for i in range(len(top)): leaders.name_lbl.config(text=top[0][1]) # leaders is the object from leaderboardWindow class leaders.score_lbl.config(text=top[0][0]) leaders.name2_lbl.config(text=top[1][1]) leaders.score2_lbl.config(text=top[1][0]) leaders.name3_lbl.config(text=top[2][1]) leaders.score3_lbl.config(text=top[2][0]) leaders.name4_lbl.config(text=top[3][1]) leaders.score4_lbl.config(text=top[3][0]) leaders.name5_lbl.config(text=top[4][1]) leaders.score5_lbl.config(text=top[4][0]) # component 3: leader board class LeaderboardWindow: def __init__(self, parent): # Background image on Frame parent.geometry('550x650') self.bg_img = Image.open('Lb4.png') # update my image file self.bg_img = self.bg_img.resize((550, 650), Image.ANTIALIAS) image = ImageTk.PhotoImage(self.bg_img) # update PhotoImage image_label.configure(image=image) # upadate the label image_label.image = image # keep a reference! self.name_lbl = Label(parent, text='name', font=('Helvetica', '13', 'bold'), height=3, width=15) self.name_lbl.place(x=50, y=100) # option 2 Button self.score_lbl = Label(parent, text='score', font=('Helvetica', '13', 'bold'), height=3, width=15) self.score_lbl.place(x=300, y=100) self.name2_lbl = Label(parent, text='name2', font=('Helvetica', '13', 'bold'), height=3, width=15) self.name2_lbl.place(x=50, y=200) # option 2 Button self.score2_lbl = Label(parent, text='score2', font=('Helvetica' , '13', 'bold'), height=3, width=15) self.score2_lbl.place(x=300, y=200) self.name3_lbl = Label(parent, text='name3', font=('Helvetica', '13', 'bold'), height=3, width=15) self.name3_lbl.place(x=50, y=300) # option 2 Button self.score3_lbl = Label(parent, text='score3', font=('Helvetica' , '13', 'bold'), height=3, width=15) self.score3_lbl.place(x=300, y=300) self.name4_lbl = Label(parent, text='name4', font=('Helvetica', '13', 'bold'), height=3, width=15) self.name4_lbl.place(x=50, y=400) # option 2 Button self.score4_lbl = Label(parent, text='score4', font=('Helvetica' , '13', 'bold'), height=3, width=15) self.score4_lbl.place(x=300, y=400) self.name5_lbl = Label(parent, text='name5', font=('Helvetica', '13', 'bold'), height=3, width=15) self.name5_lbl.place(x=50, y=400) # option 2 Button self.score5_lbl = Label(parent, text='score5', font=('Helvetica' , '13', 'bold'), height=3, width=15) self.score5_lbl.place(x=300, y=400) # Program runs below if __name__ == '__main__': root = Tk() root.title('Lost in Time') root.geometry('750x650') bg_image = Image.open('game10.png') # need to use Image if need to resize bg_image = bg_image.resize((750, 650), Image.ANTIALIAS) bg_image = ImageTk.PhotoImage(bg_image) # image label below image_label = Label(root, image=bg_image) image_label.place(x=0, y=0, relwidth=1, relheight=1) # make label l to fit the fram game_starter_window = GameStarter(root) # instantiation, making an instance (object) of the class root.mainloop() # so the window doesnt dissapear
b404e386aa86f7e7a8abfdbbfb1a7e678920e420
sn-lvpthe/CirquePy
/02-loops/fizzbuzz.py
680
4.15625
4
print ("Dit is het FIZZBUZZ spel!") end = input("""\nWe gaan even na of een getal deelbaar is door 3 OF 5 .\nOf door 3 EN 5.\n Geef een geheel getal in tussen 1 en 100: """) # try-except statement: # if the code inside try fails, the program automatically goes to the except part. try: end = int(end) # convert string into number for num in range(1, end+1): if num % 3 == 0 and num % 5 == 0: print ("FIZZBUZZ-3-5") elif num % 3 == 0: print ("\tfizz-3") elif num % 5 == 0: print ("\t\tbuzz-5") else: print(num) except Exception as e: print("Sorry. Ik lust alleen HELE getallen!")
1fb7b06f3ed69f53268c4b1f6fc0a39702f8274c
mishra-atul5001/Python-Exercises
/Search.py
574
4.15625
4
Stringy = ''' Suyash: Why are you wearing your pajamas? Atul: [chuckles] These aren't pajamas! It's a warm-up suit. Suyash: What are you warming up for Bro..!!? Atul: Stuff. Suyash: What sort of stuff? Atul: Super-cool stuff you wouldn't understand. Suyash: Like sleeping? Atul: THEY ARE NOT PAJAMAS! ''' print(Stringy) def countWord(word,st): st = st.lower() count = st.count(word) return print(word + ' repeats ' + str(count) + ' times') print('What word do you want to search for?') userWord = input() countWord(userWord,Stringy) #Atul Mishra #SRM Univ.
4271d1c657889264d3238286f3cbaa2a128eedef
laxminagln/Neural-Networks-and-Deep-Learning
/Logistic Regression with a Neural Network mindset.py
24,127
4.34375
4
Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning. Instructions: Do not use loops (for/while) in your code, unless the instructions explicitly ask you to do so. You will learn to: Build the general architecture of a learning algorithm, including: Initializing parameters Calculating the cost function and its gradient Using an optimization algorithm (gradient descent) Gather all three functions above into a main model function, in the right order. Updates This notebook has been updated over the past few months. The prior version was named "v5", and the current versionis now named '6a' If you were working on a previous version: You can find your prior work by looking in the file directory for the older files (named by version name). To view the file directory, click on the "Coursera" icon in the top left corner of this notebook. Please copy your work from the older versions to the new version, in order to submit your work for grading. List of Updates Forward propagation formula, indexing now starts at 1 instead of 0. Optimization function comment now says "print cost every 100 training iterations" instead of "examples". Fixed grammar in the comments. Y_prediction_test variable name is used consistently. Plot's axis label now says "iterations (hundred)" instead of "iterations". When testing the model, the test image is normalized by dividing by 255. 1 - Packages First, let's run the cell below to import all the packages that you will need during this assignment. numpy is the fundamental package for scientific computing with Python. h5py is a common package to interact with a dataset that is stored on an H5 file. matplotlib is a famous library to plot graphs in Python. PIL and scipy are used here to test your model with your own picture at the end. import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset ​ %matplotlib inline 2 - Overview of the Problem set Problem Statement: You are given a dataset ("data.h5") containing: - a training set of m_train images labeled as cat (y=1) or non-cat (y=0) - a test set of m_test images labeled as cat or non-cat - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB). Thus, each image is square (height = num_px) and (width = num_px). You will build a simple image-recognition algorithm that can correctly classify pictures as cat or non-cat. Let's get more familiar with the dataset. Load the data by running the following code. # Loading the data (cat/non-cat) train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() We added "_orig" at the end of image datasets (train and test) because we are going to preprocess them. After preprocessing, we will end up with train_set_x and test_set_x (the labels train_set_y and test_set_y don't need any preprocessing). Each line of your train_set_x_orig and test_set_x_orig is an array representing an image. You can visualize an example by running the following code. Feel free also to change the index value and re-run to see other images. # Example of a picture index = 25 plt.imshow(train_set_x_orig[index]) print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.") y = [1], it's a 'cat' picture. Many software bugs in deep learning come from having matrix/vector dimensions that don't fit. If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating many bugs. Exercise: Find the values for: - m_train (number of training examples) - m_test (number of test examples) - num_px (= height = width of a training image) Remember that train_set_x_orig is a numpy-array of shape (m_train, num_px, num_px, 3). For instance, you can access m_train by writing train_set_x_orig.shape[0]. ### START CODE HERE ### (≈ 3 lines of code) m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] ### END CODE HERE ### ​ print ("Number of training examples: m_train = " + str(m_train)) print ("Number of testing examples: m_test = " + str(m_test)) print ("Height/Width of each image: num_px = " + str(num_px)) print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)") print ("train_set_x shape: " + str(train_set_x_orig.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x shape: " + str(test_set_x_orig.shape)) print ("test_set_y shape: " + str(test_set_y.shape)) Number of training examples: m_train = 209 Number of testing examples: m_test = 50 Height/Width of each image: num_px = 64 Each image is of size: (64, 64, 3) train_set_x shape: (209, 64, 64, 3) train_set_y shape: (1, 209) test_set_x shape: (50, 64, 64, 3) test_set_y shape: (1, 50) Expected Output for m_train, m_test and num_px: m_train 209 m_test 50 num_px 64 For convenience, you should now reshape images of shape (num_px, num_px, 3) in a numpy-array of shape (num_px ∗∗ num_px ∗∗ 3, 1). After this, our training (and test) dataset is a numpy-array where each column represents a flattened image. There should be m_train (respectively m_test) columns. Exercise: Reshape the training and test data sets so that images of size (num_px, num_px, 3) are flattened into single vectors of shape (num_px ∗∗ num_px ∗∗ 3, 1). A trick when you want to flatten a matrix X of shape (a,b,c,d) to a matrix X_flatten of shape (b∗∗c∗∗d, a) is to use: X_flatten = X.reshape(X.shape[0], -1).T # X.T is the transpose of X # Reshape the training and test examples ​ ### START CODE HERE ### (≈ 2 lines of code) train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T ### END CODE HERE ### ​ print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape)) print ("test_set_y shape: " + str(test_set_y.shape)) print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0])) train_set_x_flatten shape: (12288, 209) train_set_y shape: (1, 209) test_set_x_flatten shape: (12288, 50) test_set_y shape: (1, 50) sanity check after reshaping: [17 31 56 22 33] ​ Expected Output: train_set_x_flatten shape (12288, 209) train_set_y shape (1, 209) test_set_x_flatten shape (12288, 50) test_set_y shape (1, 50) sanity check after reshaping [17 31 56 22 33] To represent color images, the red, green and blue channels (RGB) must be specified for each pixel, and so the pixel value is actually a vector of three numbers ranging from 0 to 255. One common preprocessing step in machine learning is to center and standardize your dataset, meaning that you substract the mean of the whole numpy array from each example, and then divide each example by the standard deviation of the whole numpy array. But for picture datasets, it is simpler and more convenient and works almost as well to just divide every row of the dataset by 255 (the maximum value of a pixel channel). Let's standardize our dataset. train_set_x = train_set_x_flatten/255. test_set_x = test_set_x_flatten/255. What you need to remember: Common steps for pre-processing a new dataset are: Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...) Reshape the datasets such that each example is now a vector of size (num_px * num_px * 3, 1) "Standardize" the data 3 - General Architecture of the learning algorithm It's time to design a simple algorithm to distinguish cat images from non-cat images. You will build a Logistic Regression, using a Neural Network mindset. The following Figure explains why Logistic Regression is actually a very simple Neural Network! Mathematical expression of the algorithm: For one example x(i)x(i): z(i)=wTx(i)+b(1) z(i)=wTx(i)+b ŷ (i)=a(i)=sigmoid(z(i))(2) y^(i)=a(i)=sigmoid(z(i)) (a(i),y(i))=−y(i)log(a(i))−(1−y(i))log(1−a(i))(3) L(a(i),y(i))=−y(i)log⁡(a(i))−(1−y(i))log⁡(1−a(i)) The cost is then computed by summing over all training examples: J=1m∑i=1m(a(i),y(i))(6) J=1m∑i=1mL(a(i),y(i)) Key steps: In this exercise, you will carry out the following steps: - Initialize the parameters of the model - Learn the parameters for the model by minimizing the cost - Use the learned parameters to make predictions (on the test set) - Analyse the results and conclude 4 - Building the parts of our algorithm The main steps for building a Neural Network are: Define the model structure (such as number of input features) Initialize the model's parameters Loop: Calculate current loss (forward propagation) Calculate current gradient (backward propagation) Update parameters (gradient descent) You often build 1-3 separately and integrate them into one function we call model(). 4.1 - Helper functions Exercise: Using your code from "Python Basics", implement sigmoid(). As you've seen in the figure above, you need to compute sigmoid(wTx+b)=11+e−(wTx+b)sigmoid(wTx+b)=11+e−(wTx+b) to make predictions. Use np.exp(). # GRADED FUNCTION: sigmoid ​ def sigmoid(z): s = 1/(1+np.exp(-z)) return s print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2])))) sigmoid([0, 2]) = [ 0.5 0.88079708] Expected Output: sigmoid([0, 2]) [ 0.5 0.88079708] 4.2 - Initializing parameters Exercise: Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documentation. def initialize_with_zeros(dim): w = np.zeros(shape=(dim,1)) b = 0 assert(w.shape == (dim,1)) assert(isinstance(b, float) or isinstance(b, int)) return w, b dim = 2 w, b = initialize_with_zeros(dim) print ("w = " + str(w)) print ("b = " + str(b)) w = [[ 0.] [ 0.]] b = 0 Expected Output: w [[ 0.] [ 0.]] b 0 For image inputs, w will be of shape (num_px ×× num_px ×× 3, 1). 4.3 - Forward and Backward propagation Now that your parameters are initialized, you can do the "forward" and "backward" propagation steps for learning the parameters. Exercise: Implement a function propagate() that computes the cost function and its gradient. Hints: Forward Propagation: You get X You compute A=σ(wTX+b)=(a(1),a(2),...,a(m−1),a(m))A=σ(wTX+b)=(a(1),a(2),...,a(m−1),a(m)) You calculate the cost function: J=−1m∑mi=1y(i)log(a(i))+(1−y(i))log(1−a(i))J=−1m∑i=1my(i)log⁡(a(i))+(1−y(i))log⁡(1−a(i)) Here are the two formulas you will be using: ∂J∂w=1mX(A−Y)T(7) ∂J∂w=1mX(A−Y)T ∂J∂b=1m∑i=1m(a(i)−y(i))(8) ∂J∂b=1m∑i=1m(a(i)−y(i)) # GRADED FUNCTION: propagate ​ def propagate(w, b, X, Y): m = X.shape[1] A = sigmoid(np.dot(w.T,X)+b) cost = (-1/m)*np.sum(np.dot(Y,np.log(A).T)+np.dot((1-Y),np.log(1-A).T)) dw = (1/m)*np.dot(X,(A-Y).T) db = (1/m)*np.sum(A-Y) assert(dw.shape == w.shape) assert(db.dtype == float) cost = np.squeeze(cost) assert(cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost w, b, X, Y = np.array([[1.],[2.]]), 2., np.array([[1.,2.,-1.],[3.,4.,-3.2]]), np.array([[1,0,1]]) grads, cost = propagate(w, b, X, Y) print ("dw = " + str(grads["dw"])) print ("db = " + str(grads["db"])) print ("cost = " + str(cost)) dw = [[ 0.99845601] [ 2.39507239]] db = 0.00145557813678 cost = 5.80154531939 Expected Output: dw [[ 0.99845601] [ 2.39507239]] db 0.00145557813678 cost 5.801545319394553 4.4 - Optimization You have initialized your parameters. You are also able to compute a cost function and its gradient. Now, you want to update the parameters using gradient descent. Exercise: Write down the optimization function. The goal is to learn ww and bb by minimizing the cost function JJ. For a parameter θθ, the update rule is θ=θ−α dθθ=θ−α dθ, where αα is the learning rate. # GRADED FUNCTION: optimize ​ def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] for i in range(num_iterations): grads, cost = propagate(w,b,X,Y) dw = grads["dw"] db = grads["db"] w = w-(learning_rate*dw) b = b-(learning_rate*db) ### END CODE HERE ### # Record the costs if i % 100 == 0: costs.append(cost) # Print the cost every 100 training iterations if print_cost and i % 100 == 0: print ("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False) ​ print ("w = " + str(params["w"])) print ("b = " + str(params["b"])) print ("dw = " + str(grads["dw"])) print ("db = " + str(grads["db"])) w = [[ 0.19033591] [ 0.12259159]] b = 1.92535983008 dw = [[ 0.67752042] [ 1.41625495]] db = 0.219194504541 Expected Output: w [[ 0.19033591] [ 0.12259159]] b 1.92535983008 dw [[ 0.67752042] [ 1.41625495]] db 0.219194504541 Exercise: The previous function will output the learned w and b. We are able to use w and b to predict the labels for a dataset X. Implement the predict() function. There are two steps to computing predictions: Calculate Ŷ =A=σ(wTX+b)Y^=A=σ(wTX+b) Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5), stores the predictions in a vector Y_prediction. If you wish, you can use an if/else statement in a for loop (though there is also a way to vectorize this). # GRADED FUNCTION: predict ​ def predict(w, b, X): m = X.shape[1] Y_prediction = np.zeros((1,m)) w = w.reshape(X.shape[0], 1) A = sigmoid(np.dot(w.T,X)+b) for i in range(A.shape[1]): Y_prediction[0][i] = 0 if A[0][i]<=0.5 else 1 assert(Y_prediction.shape == (1, m)) return Y_prediction w = np.array([[0.1124579],[0.23106775]]) b = -0.3 X = np.array([[1.,-1.1,-3.2],[1.2,2.,0.1]]) print ("predictions = " + str(predict(w, b, X))) predictions = [[ 1. 1. 0.]] Expected Output: predictions [[ 1. 1. 0.]] What to remember: You've implemented several functions that: Initialize (w,b) Optimize the loss iteratively to learn parameters (w,b): computing the cost and its gradient updating the parameters using gradient descent Use the learned (w,b) to predict the labels for a given set of examples 5 - Merge all functions into a model You will now see how the overall model is structured by putting together all the building blocks (functions implemented in the previous parts) together, in the right order. Exercise: Implement the model function. Use the following notation: - Y_prediction_test for your predictions on the test set - Y_prediction_train for your predictions on the train set - w, costs, grads for the outputs of optimize() # GRADED FUNCTION: model ​ def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): w, b = np.zeros(shape=((X_train.shape[0], 1))), 0 parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations=num_iterations, learning_rate=learning_rate, print_cost=print_cost) w = parameters["w"] b = parameters["b"] Y_prediction_test = predict(w,b,X_test) Y_prediction_train = predict(w,b,X_train) print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train" : Y_prediction_train, "w" : w, "b" : b, "learning_rate" : learning_rate, "num_iterations": num_iterations} return d Run the following cell to train your model. d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True) Cost after iteration 0: 0.693147 Cost after iteration 100: 0.584508 Cost after iteration 200: 0.466949 Cost after iteration 300: 0.376007 Cost after iteration 400: 0.331463 Cost after iteration 500: 0.303273 Cost after iteration 600: 0.279880 Cost after iteration 700: 0.260042 Cost after iteration 800: 0.242941 Cost after iteration 900: 0.228004 Cost after iteration 1000: 0.214820 Cost after iteration 1100: 0.203078 Cost after iteration 1200: 0.192544 Cost after iteration 1300: 0.183033 Cost after iteration 1400: 0.174399 Cost after iteration 1500: 0.166521 Cost after iteration 1600: 0.159305 Cost after iteration 1700: 0.152667 Cost after iteration 1800: 0.146542 Cost after iteration 1900: 0.140872 train accuracy: 99.04306220095694 % test accuracy: 70.0 % Expected Output: Cost after iteration 0 0.693147 ⋮⋮ ⋮⋮ Train Accuracy 99.04306220095694 % Test Accuracy 70.0 % Comment: Training accuracy is close to 100%. This is a good sanity check: your model is working and has high enough capacity to fit the training data. Test accuracy is 68%. It is actually not bad for this simple model, given the small dataset we used and that logistic regression is a linear classifier. But no worries, you'll build an even better classifier next week! Also, you see that the model is clearly overfitting the training data. Later in this specialization you will learn how to reduce overfitting, for example by using regularization. Using the code below (and changing the index variable) you can look at predictions on pictures of the test set. # Example of a picture that was wrongly classified. index = 1 plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3))) print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") + "\" picture.") y = 1, you predicted that it is a "cat" picture. Let's also plot the cost function and the gradients. # Plot learning curve (with costs) costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d["learning_rate"])) plt.show() Interpretation: You can see the cost decreasing. It shows that the parameters are being learned. However, you see that you could train the model even more on the training set. Try to increase the number of iterations in the cell above and rerun the cells. You might see that the training set accuracy goes up, but the test set accuracy goes down. This is called overfitting. 6 - Further analysis (optional/ungraded exercise) Congratulations on building your first image classification model. Let's analyze it further, and examine possible choices for the learning rate αα. Choice of learning rate Reminder: In order for Gradient Descent to work you must choose the learning rate wisely. The learning rate αα determines how rapidly we update the parameters. If the learning rate is too large we may "overshoot" the optimal value. Similarly, if it is too small we will need too many iterations to converge to the best values. That's why it is crucial to use a well-tuned learning rate. Let's compare the learning curve of our model with several choices of learning rates. Run the cell below. This should take about 1 minute. Feel free also to try different values than the three we have initialized the learning_rates variable to contain, and see what happens. learning_rates = [0.01, 0.001, 0.0001] models = {} for i in learning_rates: print ("learning rate is: " + str(i)) models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False) print ('\n' + "-------------------------------------------------------" + '\n') ​ for i in learning_rates: plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"])) ​ plt.ylabel('cost') plt.xlabel('iterations (hundreds)') ​ legend = plt.legend(loc='upper center', shadow=True) frame = legend.get_frame() frame.set_facecolor('0.90') plt.show() learning rate is: 0.01 train accuracy: 99.52153110047847 % test accuracy: 68.0 % ------------------------------------------------------- learning rate is: 0.001 train accuracy: 88.99521531100478 % test accuracy: 64.0 % ------------------------------------------------------- learning rate is: 0.0001 train accuracy: 68.42105263157895 % test accuracy: 36.0 % ------------------------------------------------------- Interpretation: Different learning rates give different costs and thus different predictions results. If the learning rate is too large (0.01), the cost may oscillate up and down. It may even diverge (though in this example, using 0.01 still eventually ends up at a good value for the cost). A lower cost doesn't mean a better model. You have to check if there is possibly overfitting. It happens when the training accuracy is a lot higher than the test accuracy. In deep learning, we usually recommend that you: Choose the learning rate that better minimizes the cost function. If your model overfits, use other techniques to reduce overfitting. (We'll talk about this in later videos.) 7 - Test with your own image (optional/ungraded exercise) Congratulations on finishing this assignment. You can use your own image and see the output of your model. To do that: 1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub. 2. Add your image to this Jupyter Notebook's directory, in the "images" folder 3. Change your image's name in the following code 4. Run the code and check if the algorithm is right (1 = cat, 0 = non-cat)! ## START CODE HERE ## (PUT YOUR IMAGE NAME) my_image = "my_image.jpg" # change this to the name of your image file ## END CODE HERE ## ​ # We preprocess the image to fit your algorithm. fname = "images/" + my_image image = np.array(ndimage.imread(fname, flatten=False)) image = image/255. my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T my_predicted_image = predict(d["w"], d["b"], my_image) ​ plt.imshow(image) print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.") y = 0.0, your algorithm predicts a "non-cat" picture. What to remember from this assignment: Preprocessing the dataset is important. You implemented each function separately: initialize(), propagate(), optimize(). Then you built a model(). Tuning the learning rate (which is an example of a "hyperparameter") can make a big difference to the algorithm. You will see more examples of this later in this course! Finally, if you'd like, we invite you to try different things on this Notebook. Make sure you submit before trying anything. Once you submit, things you can play with include: - Play with the learning rate and the number of iterations - Try different initialization methods and compare the results - Test other preprocessings (center the data, or divide each row by its standard deviation) Bibliography: http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/ https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c
91512810a131c61f9d4013e6915ca8acb84591aa
thorsteinn17/Assignment-5
/assigment5-2.py
379
3.96875
4
n = int(input("Enter the length of the sequence: ")) # Do not change this line number_1 = 1 number_2 = 2 number_3 = 3 next_number = 0 n=n-2 print(number_1) print(number_2) print(number_3) for i in range(1,n): next_number = number_1+number_2+number_3 print (next_number) number_1 = number_2 number_2 = number_3 number_3 = next_number
3e1ea1e71e55e5c1f8b7b5e5b338c07773ae4b2e
vnegs14/CS104-02
/ForLoop.py
310
3.90625
4
x = 1 print("The program will start counting up from 0 and finish at 9.") print("You will recieve a nice message after the program has ended.") response=(input("Are you ready to proceed? ")) for x in range(0,10): print ("total= ",x) print("Program has ended folks! Take care and Stay Frosty - Vinnie")
cc8e5d5db27730063c43f01ef610dcea40ec77df
lacra-oloeriu/learn-python
/ex15.py
552
4.125
4
from sys import argv# That is a pakege from argv script, filename = argv#This is define the pakege txt= open(filename)#that line told at computer ...open the file print(f"Here's your file {filename}:")#print the text...and in {the name of file to open in extension txt} print ( txt.read()) print("Type the filename again:")#print the text.."Type the fil....again" file_again = input ( " > ")# the name of file txt_again = open ( file_again)#open file again print (txt_again.read())#printeaza continutul fisierului ...prin the cont of file again
cb5a49c4bbe6781796a6f7450910653aedc649fd
FranFer03/Practica
/Nate/list_2.py
410
3.890625
4
number_usuary = [] number_of_usuary = "" while len(number_usuary) < 6: while not number_of_usuary.isdigit(): number_of_usuary = input("Dime un numero : ") number_usuary.append(int(number_of_usuary)) number_of_usuary = "" print("Numero añadido!!") lower = number_usuary[0] for number in number_usuary: if number < lower: lower = number print("El menor numero es ",lower)
1efd2759844f0c7de6a216896ba32ac44577c62a
FranFer03/Practica
/Nate/list_1.py
415
3.890625
4
number_usuary = [] number_of_usuary = "" while len(number_usuary) < 10: while not number_of_usuary.isdigit(): number_of_usuary = input("Dime un numero : ") number_usuary.append(int(number_of_usuary)) number_of_usuary = "" print("Numero añadido!!") higher = number_usuary[0] for number in number_usuary: if number > higher: higher = number print("El mayor numero es ",higher)
4bdfc19951f63f544becb5bc083dc08817208005
FranFer03/Practica
/Curso/Class_2/practice_class_2.8.py
415
3.921875
4
day = input("Ingrese el dia de la semana : ").title() if day == "Lunes": print("Con la profesora Bety") elif day == "Viernes": print("Hoy la Motok") elif day == "Sabado": print("A salir de peda") elif day == "Domingo": print("Sale asaduki") elif day == "Martes" or day == "Miercoles" or day == "Jueves": print("Feriado") else: print("Usted no aprende los dias me parece o no sabe escribir")
a4ff8ec5d15ecc726f96046dd90c73cdeb3b06bf
FranFer03/Practica
/Curso/Class_2/practice_class_2.1.py
244
3.890625
4
radio = float(input("Ingrese la radio : ")) height = float(input("ingrese la altura : ")) volumen = float(radio * radio * 3.14 * height) if (volumen >300): print("Su volumen es mayor a 300 ") else: print("El volumen es menor a 300")
a108262b02134c6029de3a1ffa6ea0d68120b475
FranFer03/Practica
/Curso/Class_3/practice_class_3.1.py
430
3.59375
4
import random def age(): mayor, menor = 0, 0 for i in range(0, 50): edad = random.randrange(1, 75) print("", edad ,end="") if edad > 21: mayor += 1 elif edad < 21: menor += 1 print("\nMayores a 21 : ", end="") for i in range(mayor): print("*", end="") print("\nMenor a 21 : ", end="") for i in range(menor): print("*", end="") age()
51829ff07ed19d9d2f6bda8bc2208046c6d0b0d4
FranFer03/Practica
/Nate/multi_2.py
270
4
4
input_numero = int(input("¿Que numero quieres introducir en la tabla? ")) numeros = [] for numero in range(1, 11): numeros.append(numero) revnumeros = reversed(numeros) for num in revnumeros: print("{} x {} = {}".format(input_numero, num, input_numero * num))
f90d8cb6734aa2489ee0a039d47005896f16bff0
josh231101/RGBColorPicker
/ProjectCalc.py
3,717
3.5625
4
import PySimpleGUI as sg def calcularConversion(magnitud, u1, u2, entrada): if magnitud == "LONGITUD": # In case we convert Meters to Yd we use the formula, else means it's inverted so we use the inverted formula return entrada * 0.914 if u1 == "Metros" and u2 == "Yardas" else entrada / 0.914 elif magnitud == "MASA": return entrada * 453.6 if u1 == "Libras" and u2 == "Gramos" else entrada / 463.6 elif magnitud == "VOLUMEN": return entrada / 3.785 if u1 == "Litros" and u2 == "Galón" else entrada * 3.785 def cleanAndUpdateMagnitude(window, magnitude): # This method cleans the input and combo box to the correct units window["_ENTRADA_"].update("") # Clean the input and combos window["_UNIT1_"].Update("") window["_UNIT2_"].update("") window["_UNIT1_"].Update(values=magnitude) # Update the units to the according magnitude window["_UNIT2_"].update(values=magnitude) def validateInput(entrada, combo_1, combo_2): if entrada != "" and combo_1 != "" and combo_2 != "": # Both units and input are filled try: # If user sends letters and invalid characters we send the user to the exception entrada = float(entrada) if combo_1 != combo_2: # User must choose different units # The number must be positive return True if entrada > 0 else "Ingresa por favor un número positivo mayor a cero" else: return "Ingresaste las mismas unidades" except ValueError: return "Ingresa un número entero" else: return "Ingresa todos los campos!" # Create info for the combos CALC_INFO = { "LONGITUD": ("Metros", "Yardas"), "MASA": ("Libras", "Gramos"), "VOLUMEN": ("Galón", "Litros") } def main(): sg.theme("Topanga") # Create layout layout = [ [sg.Text("MAGNITUD A CALCULAR: ")], [sg.Combo(("LONGITUD", "MASA", "VOLUMEN"), default_value="LONGITUD", size=(20, 4), key="_MAGNITUD_"), sg.Button("CAMBIAR")], [sg.T("Cantidad a convertir: ")], [sg.Input(key="_ENTRADA_")], [sg.Combo(CALC_INFO["LONGITUD"], key="_UNIT1_"), sg.T("a"), sg.Combo(CALC_INFO["LONGITUD"], key="_UNIT2_")], [sg.Button("CALCULAR")] ] window = sg.Window("CALCULADORA DE CONVERSIONES", layout) while True: event, values = window.read() # Read the window if event == sg.WIN_CLOSED: # User clicked X btn break elif event == "CAMBIAR": # User wants to change magnitude # Get the user magnitude to calculate magnitude_units = CALC_INFO[values["_MAGNITUD_"]] # Clean the screen and update combobox info to the corresponding magnitude units cleanAndUpdateMagnitude(window, magnitude_units) elif event == "CALCULAR": entrada = values["_ENTRADA_"] unit_1 = values["_UNIT1_"] # The first unit (from) unit_2 = values["_UNIT2_"] # The second unit(to) # VALIDATE USER INPUT if validateInput(entrada, unit_1, unit_2) == True: # Validate the user form current_magnitude = values["_MAGNITUD_"] entrada = float(entrada) # Convert to float the input to calculate the conversion resultado = calcularConversion(current_magnitude, unit_1, unit_2,entrada) salida = f"Al convertir {entrada}, de {unit_1} a {unit_2} obtenemos {resultado}" else: salida = validateInput(entrada, unit_1, unit_2) # Function returns the msg of the error sg.popup_ok(salida) #Print the result in the popup window.close() main()
77ea1796467ad100aaa69be0453c61242a6f55d8
Etoakor/love
/scr/create_sample.py
1,018
3.703125
4
import pandas as pd import random from configuration import MAN_NUM,WOMAN_NUM def create_sample(): man_num = MAN_NUM women_num = WOMAN_NUM #设置男女生喜好样本 print('==============================生成样本数据==============================') man = pd.DataFrame( [['w'+str(i) for i in random.sample(range(1,women_num+1),women_num)] \ for i in range(man_num)], index = ['m'+str(i) for i in range(1,man_num+1)], columns = ['level'+str(i) for i in range(1,women_num+1)] ) women = pd.DataFrame( [['m'+str(i) for i in random.sample(range(1,man_num+1),man_num)] \ for i in range(women_num)], index = ['w'+str(i) for i in range(1,women_num+1)], columns = ['level'+str(i) for i in range(1,man_num+1)] ) return (man,women) if __name__ == '__main__': create_sample(man,women)
2310553f84b88bd7512ab59201c991de11e1a7bc
Echo226/LeetCode
/229_majorityElementII.py
1,437
3.765625
4
''' Method1: Brute Force Method2: Boyer-Moore Algorithm Author: Xinting Date : 2019-11-04 ''' # Brute Force class Solution: def majorityElement(self, nums: List[int]) -> List[int]: res = [] for num1 in nums: if num1 not in res and sum(1 for num2 in nums if num2 == num1) > len(nums)//3: res.append(num1) return res # Boyer-Moore Algorithm # Time Complexity: O(N) # Space Complexity: O(1) class Solution: def majorityElement(self, nums: List[int]) -> List[int]: res = [] cnt1, cnt2 = 0, 0 candidate1, candidate2 = 0, 0 for num in nums: if num == candidate1: cnt1 += 1 elif num == candidate2: cnt2 += 1 elif cnt1 == 0: candidate1 = num cnt1 = 1 elif cnt2 == 0: candidate2 = num cnt2 = 1 else: cnt1 -= 1 cnt2 -= 1 # check two potential candidates if sum(1 for num in nums if num == candidate1) > len(nums)//3: res.append(candidate1) # for [0,0,0] candidate1=candidate2=0 so that need to make sure candidate2 not in res if candidate2 not in res and sum(1 for num in nums if num == candidate2) > len(nums)//3: res.append(candidate2) return res
e07d650b50884b7955478b2cbd4c704e56c3e56e
ssupasanya/Coursework
/Mary_hw1.py
6,439
4.125
4
# File: hw1.py # Authors: [give the names of all Homework 1 team members here] # Date: [submission date] # Part 0 # Define your mean_of_3 function here def mean_of_3(i, j, k): return (i + j + k) / 3 #'''Comment this and the following triple-quoted line to test your function print('mean_of_3(1, 2, 3):', mean_of_3(1, 2, 3)) #''' # Part 1 # Define your Fibonacci number function (Fib) here def Fib(n): ''' Input: non-negative integer n Output: the nth Fibonacci integer ''' if type(n) != int or n < 0: print(n, 'must be integer >= 0') return None if n == 0 or n == 1: return n else: n0 = 0 n1 = 1 i = 1 #counter while i < n: i += 1 n2 = n0 + n1 n0 = n1 n1 = n2 return n2 #'''Comment this and the following triple-quoted line to test your function print('\n---- Part 1 ----\n') n = 0 while n <= 10: print('n: ', n, 'Fib(n): ', Fib(n)) n += 1 n = 2000 print('n: ', n, 'Fib(n): ', Fib(n)) n = 'hello' print('n: ', n, 'Fib(n): ', Fib(n)) n = 3.4 print('n: ', n, 'Fib(n): ', Fib(n)) n = -7 print('n: ', n, 'Fib(n): ', Fib(n)) #''' # Part 2 # Define your is_even, is_odd, is_div_by_n, and neg_of functions here def is_even(n): ''' Input: an integer n Output: True if that int is even, otherwise False ''' if type(n) != int: print(n, "must be integer.") #negative integers are also considered for even and odd return False # supposed return False if n % 2 == 0: return True else: return False def is_odd(n): ''' Input: an integer n Output: True if that int is odd, otherwise False ''' if type(n) != int: print(n, "must be integer.") return False if n % 2 == 0: return False else: return True def is_div_by_n(m, n): ''' Input: two int arguments (call them m and n) Output: returns True if m is evenly divisible by n, otherwise False. ''' if type(m) != int: print(m, "must be integers.") return False if type(n) != int or n == 0: print(n, "must be non-zero integers.") return False if m % n == 0: return True return False def neg_of(n): ''' Input: a numeric argument (an int or float) Output: returns the negative of that argument. ''' if type(n) != int and type(n) != float: print(n, "must be integer or float.") return False return -n #'''Comment this and the following triple-quoted line to test your function print('\n---- Part 2 ----\n') n = 0 while n <= 10: print('n:', n, ' is_even(n):', is_even(n), ' is_odd(n):', is_odd(n)) print(' neg_of(n):', neg_of(n), '\n') n += 1 n = 'hello' print('n:', n, ' is_even(n):', is_even(n), ' is_odd(n):', is_odd(n)) print(' neg_of(n):', neg_of(n), '\n') n = 3.4 print('n:', n, ' is_even(n):', is_even(n), ' is_odd(n):', is_odd(n)) print(' neg_of(n):', neg_of(n), '\n') n = -7 print('n:', n, ' is_even(n):', is_even(n), ' is_odd(n):', is_odd(n)) print(' neg_of(n):', neg_of(n), '\n') print('is_div_by_n(15, 5): ', is_div_by_n(15, 5)) print('is_div_by_n(15, 4): ', is_div_by_n(15, 4)) #''' # Part 3 # Define your sum_of_n and sum_of_n_sqr functions here def sum_of_n(n): ''' Input: a non-negative integer n Output: returns the value of the sum 0 + 1 + … + n. ''' if type(n) != int or n < 0: print(n, "must be a non-negative integer.") return None return int((1+n)*n / 2) def sum_of_n_sqr(n): ''' Input: a non-negative integer n Output: returns the value of the sum 0 + 1 + 4 + 9 + … + n2. ''' if type(n) != int or n < 0: print(n, "must be a non-negative integer.") return None return int(n*(n+1)*(2*n+1)/6) #'''Comment this and the following triple-quoted line to test your function print('\n---- Part 3 ----\n') n = 0 while n <= 1000: print('n:', n, ' sum_of_n(n):', sum_of_n(n), ' sum_of_n_sqr(n):', sum_of_n_sqr(n)) n += 25 n = 100000 print('n:', n, ' sum_of_n(n):', sum_of_n(n), ' sum_of_n_sqr(n):', sum_of_n_sqr(n)) n = 10000000 print('n:', n, ' sum_of_n(n):', sum_of_n(n), ' sum_of_n_sqr(n):', sum_of_n_sqr(n)) #''' # Part 4 # Predict the output of each print function call #'''Comment this and the following triple-quoted line to test your predictions print('\n---- Part 4 ----\n') print('int(True):', int(True)) print('int(False):', int(False)) print('int("9876"):', int("9876")) #print('int("five"):', int("five")) print('int(0.123):', int(0.123)) print('int(1230):', int(1230)) #print('int(None):', int(None)) print('\n') print('float(True):', float(True)) print('float(False):', float(False)) print('float("9876"):', float("9876")) #print('float("five"):', float("five")) print('float(0.123):', float(0.123)) print('float(1230):', float(1230)) #print('float(None):', float(None)) print('\n') print('str(True):', str(True)) print('str(False):', str(False)) print('str("9876"):', str("9876")) print('str("five"):', str("five")) print('str(0.123):', str(0.123)) print('str(1230):', str(1230)) print('str(None):', str(None)) print('\n') print('bool(True):', bool(True)) print('bool(False):', bool(False)) print('bool("9876"):', bool("9876")) print('bool("five"):', bool("five")) print('bool(0.123):', bool(0.123)) print('bool(1230):', bool(1230)) print('bool(None):', bool(None)) print('bool(""):', bool("")) print('bool(" "):', bool(" ")) print('bool(0):', bool(0)) print('bool(0.0):', bool(0.0)) #''' # Part 5 ''' Mary's Preference Among the IDLE, Spyder, and Pycharm, I like Spyder the most, especially its variable explorer debug feature. Though IDLE is easy and light-weight to use, it is not robust enought for larger projects and data analysis. While PyCharm offers more features on user interface, I think Spyder is more suitable for big data and machine learning related work. '''
ce02e4503266e12a185c6f7e1e7f4a5690e55193
karthik-dasari/Guessing-Number-in-Tkinter
/Guessing Number(SYSTEM).py
1,652
4.0625
4
from tkinter import * from random import * from tkinter.font import * root=Tk() root.title('Guessing Number by System') def start(): correct="n" a,b=1,100 counter=1 while correct!="y": my_guess=(a+b)//2 label_result1=Label(root,text="My guess is ") label_result1.grid(row=2,column=0,sticky=S+W) label_result2=Label(root,text=my_guess) label_result2.grid(row=2,column=1) label_result3=Label(root,text="Is your number matchs my guess?(y/n)") label_result3.grid(row=3,column=0) entry=Entry(root) entry.grid(row=3,column=1) #button_next=Button(root,text="Next",command=Next) #button_next.grid(row=3,column=2,columnspan=3) #correct=entry.get() #if correct=="n": #label_result3=Label(root,text="Is your number is small or large than my guess(s/l):") #entry.delete(0,END) #acc=entry.get() #if acc=="s": # b=my_guess #elif acc=="l": # a=my_guess #counter+=1 #print("I got it! After " + str(counter) + " trails") def Next(): pass label_start=Label(root,text="You Guess a Number and i will find that number!\nAre you ready??\nLEt's get started...\nNow it's time for You to Guess a number between 1 and 100\nAfter you Guess the Number Press the below 'Start' button",font=Font(size=11)) label_start.grid(row=0,column=0) button_start=Button(root,text="Start",padx=35,pady=3,borderwidth=5,font=Font(size=15),command=start) button_start.grid(row=1,column=0,columnspan=2) root.mainloop()
af1191998cf3f8d5916e22b8b55da7766bead003
huynhirene/ICTPRG-Python
/q1.py
241
4.28125
4
# Write a program that counts from 0 to 25, outputting each number on a new line. num = 0 while num <= 26: print(num) num = num + 1 if num == 26: break # OR for numbers in range(0,26): print(numbers)
2beabe313feafd85369975df2289d0fb4787e6d3
Sarthak-Rijal/Pong
/pong/ball.py
1,548
3.90625
4
import pygame import math pygame.init() #screen window WIDTH = 1000 HEIGHT = 600 class Ball(object): def __init__(self, velocityX, velocityY, size, angle, speed, color): self._posX = WIDTH/2 - size/2 self._posY = HEIGHT/2 - size/2 self._velocityX = velocityX self._velocityY = velocityY self._angle = angle self._speed = speed self._size = size self._color = color self._rect = pygame.Rect((self._posX, self._posY),(self._size, self._size)) def _update(self, surface): print (self._posX, self._posY, self._velocityX) self._collide() self._posX += self._velocityX self._posY += self._velocityY pygame.draw.rect(surface, self._color, [self._posX, self._posY, self._size, self._size]) def _collide(self): if (self._posX + self._size > WIDTH or self._posX < 0): self._velocityX = -self._velocityX print ("Collide") if (self._posY + self._size > HEIGHT or self._posY < 0): self._velocityY = -self._velocityY print ("Collide") #bounce function will tell how the ball will bounce # def bounce(self): # collide function will handle how the ball handel collisions # 3 different cases: # 1 - Ball bounces on the upper or lower ceiling # 2 - Ball bounces on the paddle # 3 - Ball bounces on the left or right end of the scree. # def collide(self): # def update(self)
5eb56b2325519c91a5a55ceba4bf0f4a4efe8c37
AlexDanvers18/isklucheniya
/2_zad
3,257
3.671875
4
documents = [ {"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"}, {"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"}, {"type": "insurance", "number": "10006", "name": "Аристарх Павлов"} ] directories = { '1': ['2207 876234', '11-2', '5455 028765'], '2': ['10006'], '3': [] } def second_name_people(): print('Введите номер документа человека, имя которого Вы хотите узнать: ') number_doc = 'Ничего не найдено' number_doc = input() for document in documents: if document['number'] == number_doc: res = document['name'] print(res) break else: print('sdgsdg', number_doc) def all_list(): for document in documents: print('Документ:\n{} {} {}'.format(document['type'], document['number'], document['name'])) def number_shelf(): print('Введите номер документа и Вы узнаете номер полки, на которой он располагается ') num_doc = 'Ничего не найдено' num_doc = input() for key_directories in directories: for values_directories in directories[key_directories]: if num_doc == values_directories: num_doc = print(f'Полка №:', key_directories) return num_doc # break # else: # print("Возможно, Вы неправильно ввели номер документа") # num_doc = input() # continue def add_dok(): add_doc = input('Type (passport, invoice, insurance):') add_number = input('number:') add_name = input('name:') information = {'type': add_doc, 'number': add_number, 'name': add_name} add_key = input('directory:') for key_directories in directories: if add_key == key_directories: print('Все хорошо, такая полка есть') break else: print("Возможно, Вы неправильно ввели номер полки. Попробуйте еще раз") add_key = input('directory:') continue directories[add_key].append(add_number) documents.append(information) def new_doc_list(): for document in documents: print('{} {} {}'.format(document['type'], document ['number'], document ['name'])) #Задача по исключениям - KeyError def print_all_name(documents): for item in documents: try: print(item['name']) except KeyError as e: print(e) def all_func(): print ("Что Вы хотите сделать? \np - узнать фамилию человека по номеру документа. \nl - увидеть список всех документов. \ns - узнать номер полки, на которой хранится документ. \na - добавить документ. \nk - вывести все имена. \nВведите команду:") user_input = input() if user_input == 'p': second_name_people() elif user_input == 'l': all_list() elif user_input == 's': number_shelf() elif user_input == 'a': add_dok() new_doc_list() elif user_input == 'k': print_all_name(documents) else: print ("Возможно, Вы неправильно ввели номер команды") while True: all_func()
8f2acf8371583b570c717a97047d0a44df46ee01
TingliangZhang/VR_Robot
/Python/Pythonpa/ch08/prime.py
384
3.875
4
def is_prime(n): if n < 2: return False #如果n小于2,返回False i = 2 while i*i <= n: #一旦n能够被2~ 中的任意整数整除,n就不是素数,返回False if n % i == 0: return False i += 1 return True #测试代码 for i in range(100): #判断并输出1~99中的素数,以空格分隔 if is_prime(i):print(i, end=' ')
94ca45cec436db0dea3679ebce948e6649768a4b
TingliangZhang/VR_Robot
/Python/Pythonpa/ch12/MyDialog.py
1,655
3.6875
4
import tkinter as tk #导入tkinter模块 class MyDialog: #自定义对话框 def __init__(self, master): #构造函数 self.top = tk.Toplevel(master) #生成Toplevel组件 self.label1 = tk.Label(self.top, text='版权所有') #创建标签组件 self.label1.pack() self.label2 = tk.Label(self.top, text='V 1.0.0') #创建标签组件 self.label2.pack() self.buttonOK = tk.Button(self.top, text='OK', command=self.funcOk) #创建按钮 self.buttonOK.pack() def funcOk(self): self.top.destroy() #销毁对话框 class Application(tk.Frame): #定义GUI应用程序类,派生于Frame类 def __init__(self, master=None): #构造函数,master为父窗口 tk.Frame.__init__(self, master) #调用父类的构造函数 self.pack() #调用组件的pack方法,调整其显示位置和大小 self.createWidgets() #调用对象方法,创建子组件 def createWidgets(self): #对象方法:创建子组件 self.btnAbout = tk.Button(self, text="About", command=self.funcAbout) self.btnAbout.pack() #调用组件的pack方法,调整其显示位置和大小 def funcAbout(self): #定义事件处理程序 d = MyDialog(self) #创建对话框 root = tk.Tk() #创建1个Tk根窗口组件root root['width']=400; root['height'] = 50 #设置窗口宽、高 app = Application(master=root) #创建Application的对象实例 app.mainloop() #调用组件的mainloop方法,进入事件循环
87e56a662466fdd7ee4b279597d2da0e716bea3b
TingliangZhang/VR_Robot
/Python/Pythonpa/ch12/text.py
349
3.6875
4
from tkinter import * #导入tkinter模块所有内容 root = Tk(); root.title("Text") #窗口标题 w = Text(root, width=20, height=5) #创建文本框,宽20,高5 w.pack() w.insert(1.0, '生,还是死,这是一个问题!\n ') w.get(1.0) #'生' w.get(1.0, END) #'生,还是死,这是一个问题!\n' root.mainloop()
ad191ab445912a17fd5c8070dc001e7d4face132
TingliangZhang/VR_Robot
/Python/Pythonpa/ch06/io_test2.py
253
3.984375
4
import datetime sName = input("请输入您的姓名:") birthyear = int(input("请输入您的出生年份:"))#把输入值通过int转换为整型 age = datetime.date.today().year - birthyear print("您好!{0}。您{1}岁。".format(sName, age))
3111014da165081bdfa4becfc96879e497b2d013
TingliangZhang/VR_Robot
/Python/Pythonpa/ch03/continue_div3.py
318
3.625
4
#chapter03\continue_div3.py j = 0 #控制一行显示的数字个数 print('100~200之间不能被3整除的数为:') for i in range(100, 200 + 1): if (i % 3 == 0): continue #跳过被3整除的数 print(str.format("{0:<5}",i), end="") j += 1 if (j % 10 == 0): print() #一行显示10个数后换行
74d5902adfc195a9d2132f61862ceae39f65a640
TingliangZhang/VR_Robot
/Python/Pythonpa/ch12/event.py
240
3.6875
4
from tkinter import * #导入tkinter模块所有内容 root = Tk() def printEvent(event): #事件处理函数 print('当前坐标位置:',event.x, event.y) root.bind('<Button-1>',printEvent) #单击鼠标左键 root.mainloop()
d3ad476b63a77a71c9a2a80ebf4b316031dbf68b
TingliangZhang/VR_Robot
/Python/Practice/leapyear2.py
191
3.8125
4
y=int(input("请输入")) if(y%400==0):print("Y") else: if(y%4==0): if(y%100==0): print("N") else: print("Y") else: print("N") input()
bbab62d4f28b4123f293a82ae0174bd543c7ec82
TingliangZhang/VR_Robot
/Python/Pythonpa/ch13/polygon.py
450
3.9375
4
import turtle def draw_polygon(sides, side_len): #绘制指定边长度的多边行 for i in range(sides): turtle.forward(side_len) #绘制边长 turtle.left(360.0/sides) #旋转角度 def main(): for i in range(3,11): #绘制三角形、正方形、正五边形、……、正十边形 step = 50 #边长(海龟步长)为50 draw_polygon(i, step) #绘制多边形 if __name__ == '__main__': main()
0fe4c04ad7c282d076b2bef426f0ef99cc188286
TingliangZhang/VR_Robot
/Python/Pythonpa/ch13/sin.py
899
3.859375
4
from tkinter import * import math WIDTH = 510; HEIGHT = 210 #画布宽度、高度 ORIGIN_X = 2; ORIGIN_Y = HEIGHT / 2 #原点(X=2、Y=窗体左边中心) SCALE_X = 40; SCALE_Y = 100 #X轴、Y轴的缩放倍数 END_ARC = 360 * 2 #函数图形画多长 ox = 0; oy = 0; x = 0; y = 0 #坐标初始值 arc = 0 #弧度 root = Tk() c = Canvas(root,bg = 'white', width=WIDTH, height=HEIGHT);c.pack()#创建并显示Canvas c.create_text(200, 20, text='y=sin(x)') #绘制文字 c.create_line(0, ORIGIN_Y, WIDTH, ORIGIN_Y) #绘制Y纵轴 c.create_line(ORIGIN_X, 0, ORIGIN_X, HEIGHT)#绘制X横轴 for i in range(0, END_ARC+1, 10): #绘制函数图形 arc = math.pi * i * 2 / 360 x = ORIGIN_X + arc * SCALE_X y = ORIGIN_Y - math.sin(arc) * SCALE_Y c.create_line(ox, oy, x, y) ox = x; oy = y
bb39f54d87ab1524753d465b1e1a1aae090ce949
TingliangZhang/VR_Robot
/Python/Pythonpa/ch12/grid2.py
748
4.03125
4
from tkinter import * #导入tkinter模块所有内容 root = Tk();root.title("登录") #窗口标题 root['width']=200; root['height']=80 #窗口宽度、高度 Label(root, text="用户名", width=6).place(x=1, y=1) #用户名标签,绝对坐标(1,1) Entry(root, width=20).place(x=45, y=1) #用户名文本框,绝对坐标(45,1) Label(root, text="密 码",width=6).place(x=1, y=20) #密码标签,绝对坐标(1,20) Entry(root, width=20,show="*").place(x=45, y=20) #密码文本框,绝对坐标(45,20) Button(root, text="登录", width=8).place(x=40, y=40) #登录按钮,绝对坐标(40,40) Button(root, text="取消", width=8).place(x=110, y=40)#取消按钮,绝对坐标(110,40) root.mainloop()
9514adfe728160abecf0fe6730c780eae12e6f63
TingliangZhang/VR_Robot
/Python/Pythonpa/ch03/if_coordinate.py
416
3.8125
4
#chapter03\ifMul_test.py x = int(input("请输入x坐标:")) y = int(input("请输入y坐标:")) if (x == 0 and y == 0): print("位于原点") elif (x == 0): print("位于y轴") elif (y == 0): print("位于x轴") elif (x > 0 and y > 0): print("位于第一象限") elif (x < 0 and y > 0): print("位于第二象限") elif (x < 0 and y < 0): print("位于第三象限") else: print("位于第四象限") input()
0bf64907b4c9e2a4cc7a3260605db42f2ab5ca79
TingliangZhang/VR_Robot
/Python/Pythonpa/ch03/for_sum1_100.py
316
3.765625
4
#chapter03\for_sum1_100.py sum_odd = 0; sum_even = 0 for i in range(1, 101): if i % 2 != 0: #奇数 sum_odd += i #奇数和 else: #偶数 sum_even += i #偶数和 print("1~100中所有奇数的和:", sum_odd) print("1~100中所有偶数的和:", sum_even) input()
113cddca4472e40432caf9672fdc4ce22f25fb86
fjctp/find_prime_numbers
/python/libs/mylib.py
542
4.15625
4
def is_prime(value, know_primes=[]): ''' Given a list of prime numbers, check if a number is a prime number ''' if (max(know_primes)**2) > value: for prime in know_primes: if (value % prime) == 0: return False return True else: raise ValueError('List of known primes is too short for the given value') def find_all_primes(ceil): ''' find all prime numbers in a range, from 2 to "ceil" ''' known_primes = [2, ] for i in range(3, ceil+1): if is_prime(i, known_primes): known_primes.append(i) return known_primes
907b14b99728a643a050cdb1c258ea022074834a
maribeltg/shogi
/pieces/lance.py
708
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from .piece import Piece # This class represent a Lance class Lance(Piece): piece_type = "L" """ Object constructor """ def __init__(self, color): super().__init__(color) """ A lance (L) moves one or more squares straight forward. It cannot moves backwards or to the side. """ def correct_move(self, from_x, from_y, to_x, to_y): if (self.color == "v"): if (from_x < to_x) and (from_y == to_y): return True else: return False else: if (from_x > to_x) and (from_y == to_y): return True else: return False
7d13afaa76e2de5ffb17f9df6cec33014f14a781
cs-c92/python-fundamentals
/magic_answers.py
930
3.875
4
import random name = "" question = "Will it rain?" answer = "" random_number = random.randint(1, 10) if random_number == 1: answer = "Oh yeah, for sure." elif random_number == 2: answer = "If I told you, I'd have to kill you." elif random_number == 3: answer = "Signs point to groovy." elif random_number == 4: answer = "I see many clouds." elif random_number == 5: answer = "That is the big question!" elif random_number == 6: answer = "No chance in hell." elif random_number == 7: answer = "Don't count on it." elif random_number == 8: answer = "Ow have mercy!" elif random_number == 9: answer = "It doesn't matter." elif random_number == 10: answer = "Ask again in klingon" else: answer = "Error" if name == "": print("Question: " + question) else: print(name + " asks " + question) if question == "": print("You gotta ask a question, man!") else: print(" answer: " + answer)
7e7a821d20fd2a94807b18a6bea4795d0d094bfa
Nick12321/udemy
/lesson2-set.py
292
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 12 10:46:34 2021 @author: nick """ #lists contain duplicates, sets do not hold duplicates list_1 = [222, 333, 444, 333] list_1 = set(list_1) print(list_1) print('\n') s_1= {1,2,3,4,4,5,5,6,6} print(type(s_1)) print(s_1)
77f47d8da94d71e0e7337cf8dc9e4f3faa65c31a
orozcosomozamarcela/Paradigmas_de_Programacion
/recursividad.py
1,132
4.125
4
# 5! = 5 * 4! = 120 # 4! = 4 * 3! = 24 # 3! = 3 * 2! = 6 # 2! = 2 * 1! = 2 # 1! = 1 * 0! = 1 # 0! = 1 = 1 #% * 4 * 3 * 2 * 1 def factorial (numero): if numero == 0 : return 1 else: print ( f "soy el { numero } " ) #recur = factorial(numero -1) #da = recur * numero #return da # LOS PRINTS SON UTILIUZADOS EN ESTE CAS PARA MOSTRAR COMO ES LA RECURSIIDAD, CON UN PRINT ESTARIA BIEN. LA RECURSIVIDAD SE DA DE ARRIBA PARA ABAJO Y CUANDO HAY UN RETURN VUELVE DE ABAJO PARA ARRIBA. # DESDE recur hasta return se puede achicar a solo una linea y va a hacer lo mismo, quedaria asi: return factorial ( numero - 1 ) * numero print(factorial(5)) # OTRO EJEMPLO MAS: EJEMPLO DE FIBONACCI, es una doble recursion basicamente. #fibonacci(0) = 1 #fibonacci(1) = 1 #fibonacci(n) = fibonacci(n-1)+fobonacci(n-2): #TRADUCIDO EN PYTHON LUCE ASI: def sacarFibonacci ( numero ): if numero == 0 or numero == 1 : return 1 else: return sacarFibonacci ( numero - 1 ) + sacarFibonacci ( numero - 2 ) print(sacarFibonacci ( 10 ))
5d7ce72a6c6f1131ad65147d0f2b61c5ef978f72
orozcosomozamarcela/Paradigmas_de_Programacion
/ejercicio9.py
1,213
3.59375
4
import csv def prestamos_dnis__prestamo(archivo_prestamos): """ Recorre un archivo csv, con la información almacenada en el formato: dni,año,_prestamo,venta """ # Inicialización prestamos = open(archivo_prestamos) prestamos_csv = csv.reader(prestamos) # Saltea los encabezados next(prestamos_csv) item = next(prestamos_csv, None) total = 0 while item: # Inicialización para el bucle de dni dni = item[0] total_dni = 0 print("dni {}".format(dni)) prestacion = item[1] total_prestacion = 0 while item and item[0] == dni and item[1] == prestacion: _prestamo, saldo = item[1], float(item[2]) print("\t\tTotal del prestamo {}: {:.2f}".format(_prestamo, saldo)) total_prestacion += saldo # Siguiente registro item = next(prestamos_csv, None) # Final del bucle de dni print("Total para el dni {}: {:.2f}\n".format(dni, total_dni)) total += total_dni # Final del bucle principal print("Total general: {:.2f}".format(total)) # Cierre del archivo prestamos.close() prestamos_dnis__prestamo("prestaciones.csv")
a3c2ac4234daefa2a07898aa9cce8890ca177500
orozcosomozamarcela/Paradigmas_de_Programacion
/quick_sort.py
1,025
4.15625
4
def quick_sort ( lista ): """Ordena la lista de forma recursiva. Pre: los elementos de la lista deben ser comparables. Devuelve: una nueva lista con los elementos ordenados. """ print ( "entra una clasificación rápida" ) if len ( lista ) < 2 : print ( "devuelve lista con 1 elemento" ) return lista menores , medio , mayores = _partition ( lista ) print ( "concatena" ) return quick_sort ( menores ) + medio + quick_sort ( mayores ) def _partition ( lista ): """Pre: lista no vacía. Devuelve: tres listas: menores, medio y mayores. """ pivote = lista [ 0 ] menores = [] mayores = [] for x in range ( 1 , len ( lista )): print ( f" pivote: { pivote } , valor: { lista [ x ] } " ) if lista [ x ] < pivote: menores.append ( lista [ x ]) else: mayores.append ( lista [ x ]) return menores , [ pivote ], mayores print( quick_sort ([ 7 , 5 , 3 , 12 , 9 , 2 , 10 , 4 , 15 , 8 ]))
818aa68874d794f6da6fc14bad58ef545a11258a
wangyiyao2016/Mypystudy
/tool_modules/Functional_Programming/collection.py
281
3.71875
4
#!/usr/bin/env python # encoding: utf-8 ''' Created on Sep 5, 2017 @author: Jack ''' from collections import namedtuple Point = namedtuple('Point', ['x', 'y', 'x'], rename=True) p = Point(11, 1, 22) print(p) if __name__ == '__main__': for i in p: print(i) pass
2b9317cf91e059122957a18ce201020e80bb9334
wangyiyao2016/Mypystudy
/tool_modules/thread/main.py
2,278
3.828125
4
''' Created on Nov 13, 2017 @copied_by: Jack ''' import threading from time import sleep import time import _thread def function(i): sleep(3) print ("function called by thread %i\n" % i) return def main(): threads = [] for i in range(5): t = threading.Thread(target=function, args=(i, )) threads.append(t) t.start() for i in threads: i.join() def first_function(): print(threading.currentThread().getName() + str(' is Starting ')) time.sleep(2) print (threading.currentThread().getName() + str(' is Exiting ')) return def second_function(): # print(threading.currentThread().name) # print(threading.currentThread().getName()) print(threading.currentThread().getName() + str(' is Starting ')) time.sleep(2) print (threading.currentThread().getName() + str(' is Exiting ')) return def third_function(): print(threading.currentThread().getName() + str(' is Starting ')) time.sleep(3) print(threading.currentThread().getName() + str(' is Exiting ')) return exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting " + self.name) print_time(self.name, self.counter, 5) print("Exiting " + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: # 译者注:原书中使用的thread,但是Python3中已经不能使用thread,以_thread取代,因此应该 # import _thread # _thread.exit() _thread.exit() time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 if __name__ == "__main__": # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # 以下两行为译者添加,如果要获得和图片相同的结果, # 下面两行是必须的。疑似原作者的疏漏 thread1.join() thread2.join() print("Exiting Main Thread")
58915af3377ddd9b81f75413b261755ce1d28b2f
yaoshengzhe/project-euler
/problems/python/069.py
1,259
3.671875
4
#! /usr/bin/python from util.prime import is_prime # phi(p_0^q0p_1^q_1...) = phi(p_0^q0) * phi(p_1^q_1) * ... # here p_n is prime number, q_n is positive integer # so, for given number n, factorize n and we get n = p_0^q_0 * p_1^q_1 * .. # therefore n / phi(n) = p_0^q_0 * p_1^q_1 / (phi(p0^q0) * phi(p1^q1) * ...) # we know phi(p^q) = p^q * (1 - 1/p) # thus n/phi(n) = 1 / ((1-1/p0) * (1-1/p1) * ...) = p0*p1*... / ((p0-1)*(p1-1) * ...) # notice pn is prime number. therefore, the more prime factors number n has, the larger the ratio n / phi(n) # function f(x) = x / (x-1) is a decrease function for all positive x, which means f(x1) < f(x2) if x1 > x2. # Here we come up an algorithm, start from prime number 2, find all continuous prime number and make sure their prod is less than upper bound. Exit util we find a next prime number but it causes prod larger than given upper bound. # Also see on wiki: http://en.wikipedia.org/wiki/Euler%27s_totient_function def main(): cache = {} max_ratio = 1 n_max = 1000000 max_val = 1 for n in ( i for i in xrange(2, n_max+1) if is_prime(i) ): if max_val * n <= n_max: max_val *= n else: break print max_val if __name__ == '__main__': main()
1cc95b9ca1081ff06891fc3ed7c6eddd1d618bbf
yaoshengzhe/project-euler
/problems/python/083.py
1,341
3.703125
4
#! /usr/bin/python import sys import heapq def is_in_matrix(matrix, i, j): return i > -1 and j > -1 and i < len(matrix) and j < len(matrix[0]) def add_node_if_exist(search_tree, matrix, i, j, score, used_node_set): if is_in_matrix(matrix, i, j) and not (i, j) in used_node_set: heapq.heappush(search_tree, (score+matrix[i][j], (i, j))) def search(search_tree, matrix): used_node_set = set([]) score, pos = heapq.heappop(search_tree) while pos != (len(matrix)-1, len(matrix[-1])-1): used_node_set.add(pos) i, j = pos # left add_node_if_exist(search_tree, matrix, i-1, j, score, used_node_set) # right add_node_if_exist(search_tree, matrix, i+1, j, score, used_node_set) # up add_node_if_exist(search_tree, matrix, i, j-1, score, used_node_set) # down add_node_if_exist(search_tree, matrix, i, j+1, score, used_node_set) score, pos = heapq.heappop(search_tree) return score def main(): matrix = [ [int(num) for num in line.split(',')] for line in sys.stdin.readlines() ] #score_matrix = [ [0 for v in range(len(matrix[0]))] for i in range(len(matrix)) ] search_tree = [] heapq.heappush(search_tree, (matrix[0][0], (0, 0))) print search(search_tree, matrix) if __name__ == '__main__': main()
bc33fa88880906f8870fc38b0eff49b3d11151a8
yaoshengzhe/project-euler
/problems/python/065.py
564
3.90625
4
#! /usr/bin/python from util.prime import is_prime import itertools import fractions import math def get_convergent_at(n): if n % 3 == 1: return 2 * (n / 3 + 1) else: return 1 def foo(): val = -1 n = 100 for n in reversed(range(n-1)): if val == -1: val = fractions.Fraction(get_convergent_at(n)) else: val = 1/val + get_convergent_at(n) val = 2 + 1/val return sum([ int(ch) for ch in str(val.numerator)]) def main(): print foo() if __name__ == '__main__': main()
661818fc3e4e76a44fd431728f7d716c5c2714bf
yaoshengzhe/project-euler
/problems/python/030.py
398
3.828125
4
#! /usr/bin/python import math def sum_of_digit(num, base): return sum([ int(i)**base for i in str(num)]) def find_upper_bound(): n = 1 while True: if 10**n > 9**5*n: return 9**5*n n += 1 def foo(): return sum([i for i in range(2, find_upper_bound()+1) if sum_of_digit(i, 5) == i]) def main(): print foo() if __name__ == '__main__': main()
7c81c0e3533219ecee73a35e427036fb264929a9
yaoshengzhe/project-euler
/problems/python/009.py
384
3.9375
4
#! /usr/bin/python def is_pythagorean(a, b, c): arr = sorted([a, b, c]) return arr[0]**2 + arr[1] **2 == arr[2]**2 def foo(): for a in range(1, int(1000/3)): for b in range(a, int(1000-a)/2): c = 1000 - a -b if is_pythagorean(a, b, c): return a * b * c def main(): print foo() if __name__ == '__main__': main()
75a44928da5a4fc39a18b771fd201135d51abe82
yaoshengzhe/project-euler
/problems/python/038.py
1,215
3.5
4
#! /usr/bin/python import itertools def is_pandigital(s): return len(s) == 9 and ''.join(sorted(s)) == '123456789' def test_n(num, n_upper_bound): candidate = [] length = 0 n_val = 0 for n in range(1, n_upper_bound+1): if length >= 9: break val = str(num * n) length += len(val) candidate.append(val) n_val = n pandigital_num = ''.join(candidate) if is_pandigital(pandigital_num): return (pandigital_num, num, n_val) return () def max_pandigital_num(a, b): if len(a) == 0: return b if len(b) == 0: return a if a[0] > b[0]: return a else: return b def produce_num(digit): for p in itertools.permutations('12345678', digit-1): yield int('9'+''.join(p)) def foo(): result = () # only two-digit, three-digit and four-digit numbers are possible to be candidate # and n should <= 9 for num in itertools.chain(produce_num(2), produce_num(3), produce_num(4)): r = test_n(num, 9) if len(r) > 0: result = max_pandigital_num(result, r) return result def main(): print foo() if __name__ == '__main__': main()
6451dcca1b269108e48e2f855658fda4f082b275
yaoshengzhe/project-euler
/problems/python/045.py
942
3.625
4
#! /usr/bin/python import math def h(x): return x*(2*x-1) # Suppose we have x(x+1)/2 = y(3y-1)/2 = z(2z-1) # Then we can search solution by let z from 1 to inf # Let C = z(2z-1) # then x = (-1 sqrt(1+8C)) / 2 # and y = (1 + sqrt(1+24C)) / 6 # find the solution that let x and y be positive integer # the one after (285, 165, 143) is our solution def foo(): z = 1 epsilon = 1e-6 solution = [] while True: c = h(z) for_x = math.sqrt(1+8*c) - 1 for_y = math.sqrt(1+24*c) + 1 if (for_x - int(for_x)) < epsilon and (for_y - int(for_y)) < epsilon: for_x, for_y = int(for_x), int(for_y) if for_x % 2 == 0 and for_y % 6 == 0: solution.append((for_x/2, for_y/6, z)) if len(solution) > 1 and solution[-2] == (285, 165, 143): return h(z) z += 1 def main(): print foo() if __name__ == '__main__': main()
20ea54b9807e934eb863f057c180d63a534f51ee
MicheleMorelli/inverted_index_test
/inv_index.py
770
3.6875
4
def retrieve(d): print_d(d) print("INVERTED INDEX:") b = inv_index(d) print_inv_d(b) def inv_index(d): idx = {} for k,v in d.items(): for element in v: idx[element] = idx.get(element, []) + [k] return idx def intersect(d): pass def print_d(d): for k,v in d.items(): print("%s contains %s." % (k,v)) def print_inv_d(d): for k,v in d.items(): print("%s is in pages %s." % (k,v)) def main(): the_internet = { 'a' : [1,2], 'b': [1,2,7,9,7,8,7,7,56,567], 'c' : [1,2,625,8,4,3,27,7,56,567], 'd' : [1,2,625,8,4,3,567], 'e' : [25,53,7,9,567], 'f' : [56], 'g' : [53,56,567], 'h' : [6,567], } retrieve(the_internet) if (__name__=='__main__'): main()
83875eff99de925da3f4ecc87671753a32656067
janhavik/my_projects
/Course 1/week2_inversions.py
2,193
3.8125
4
import os import time inversions = 0 def sort_array(ip1, ip2): sort_ip = list() len_ip1 = len(ip1) len_ip2 = len(ip2) i = 0 j = 0 inversions = 0 while (i < len_ip1 and j < len_ip2): if ip1[i] <= ip2[j]: sort_ip.append(ip1[i]) i = i + 1 else: sort_ip.append(ip2[j]) j = j + 1 # both arrays are sorted, the minute there is one item greater, it is going to reflect over all the small elements inversions = inversions + (len_ip1 - i) # inversions = inversions + 1 sort_ip.extend(ip1[i:]) sort_ip.extend(ip2[j:]) # print ip1, ip2, len(ip1), len(ip2), "i=", i, "j=", j, inversions, inversions + i * len_ip1 print sort_ip return (inversions, sort_ip) def mergeSort(a): global inversions b = a[:] # avoid aliasing len_b = len(b) if len_b <= 1: return (inversions, b) left_half = b[:len_b / 2] right_half = b[len_b / 2:] left_half = mergeSort(left_half)[1] right_half = mergeSort(right_half)[1] # print "Prinitng from merge sort", left_half, right_half, sort_array(left_half, right_half) invs, sorted_array = sort_array(left_half, right_half) inversions = inversions + invs return (inversions, sorted_array) print mergeSort([5, 3, 8, 9, 1, 7, 0, 2, 6, 4]) # pathdir = "F:\\Learning\\coursera\\Algorithms Exercises\\stanford-algs\\testCases\\course1\\assignment2Inversions" # resultdir = open(os.path.join(pathdir, "Results.txt"), "w") # for everyele in os.listdir(pathdir): # if "input" in everyele: # with open(os.path.join(pathdir, everyele)) as fp: # numbers = [int(f.strip()) for f in fp.readlines()] # with open(os.path.join(pathdir, everyele.replace("input", "output"))) as fp1: # result_required = int(fp1.read().strip()) # res = mergeSort(numbers) # print res[0] # resultdir.write("Result=%s, Filename=%s, Inversions=%s, SortedNumbers=%s" % # (result_required == res[0], everyele, res[0], res[1])) # inversions = 0 # resultdir.write("\n") # resultdir.close()
e3096ed5aaed8dce71cb125440dd586fefce02f9
janhavik/my_projects
/Course 1/fastpower.py
246
3.71875
4
def fastpower(a, b): print a, b if b == 1: return a else: c = a * a ans = fastpower(c, b / 2) if b % 2 == 1: return a * ans else: return ans a, b = 5, 9 print fastpower(a, b), a**b
0deba5438d954e637a71ef6c9f62dc067f58d664
taroukuma/w18
/mnist_cnn.py
2,650
3.65625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist=input_data.read_data_sets("MNIST_data/",one_hot=True) #helper functions #initialize weights def init_weights(shape): init_random_dist=tf.truncated_normal(shape,stddev=0.1) return tf.Variable(init_random_dist) #initialize biases def init_bias(shape): init_bias_vals=tf.constant(0.1,shape=shape) return tf.Variable(init_bias_vals) #conv2d def conv2d(x,W): #x --> [batch,H,W,Channels] #W --> [filter H,filter W,Channels IN,Channels OUT] return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME') #pooling def max_pool_2by2(x): #x --> [batch,H,W,Channels] return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') #CONVOLUTIONAL LAYER def convolutional_layer(input_x,shape): W=init_weights(shape) b=init_bias([shape[3]]) return tf.nn.relu(conv2d(input_x,W)+b) #FULLY CONNECTED LAYER def normal_full_layer(input_layer,size): input_size=int(input_layer.get_shape()[1]) W=init_weights([input_size,size]) b=init_bias([size]) return tf.matmul(input_layer,W)+b #Now, we create the network #placeholders x=tf.placeholder(tf.float32,shape=[None,784]) y_true=tf.placeholder(tf.float32,shape=[None,10]) #Layers x_image=tf.reshape(x,[-1,28,28,1]) convo_1=convolutional_layer(x_image,shape=[5,5,1,32]) convo_1_pooling=max_pool_2by2(convo_1) convo_2=convolutional_layer(convo_1_pooling,shape=[5,5,32,64]) convo_2_pooling=max_pool_2by2(convo_2) convo_2_flat=tf.reshape(convo_2_pooling,[-1,7*7*64]) full_layer_one=tf.nn.relu(normal_full_layer(convo_2_flat,1024)) #Dropout hold_prob=tf.placeholder(tf.float32) full_one_dropout=tf.nn.dropout(full_layer_one,keep_prob=hold_prob) y_pred=normal_full_layer(full_one_dropout,10) #Loss function cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_pred)) #optimizer optimizer=tf.train.AdamOptimizer(learning_rate=0.001) train=optimizer.minimize(cross_entropy) init=tf.global_variables_initializer() #session steps=5000 with tf.Session() as sess: sess.run(init) for i in range(steps): batch_x,batch_y=mnist.train.next_batch(50) sess.run(train,feed_dict={x:batch_x,y_true:batch_y,hold_prob:0.5}) if (i%100)==0: print("On step: {}".format(i)) print("ACCURACY: ") matches=tf.equal(tf.argmax(y_pred,1),tf.argmax(y_true,1)) acc=tf.reduce_mean(tf.cast(matches,tf.float32)) print(sess.run(acc,feed_dict={x:mnist.test.images,y_true:mnist.test.labels,hold_prob:1.0})) print('\n')
2b8c15c7cd57ee9dcdb90d0c9ab2aa545f8d0052
Bynaryman/SR_GAMES
/src/player.py
1,069
3.546875
4
import pygame from common.common import * class Player: """ """ def __init__(self, x, y, name, conn, world_ref): self.name = name self.score = 0 self.conn = conn self.pict = pict_player self.case_x = x self.case_y = y self.world = world_ref ''' Renvoie la position du joueur sur la grille ''' def get_pos(self): return self.case_x, self.case_y ''' Renvoie le score du joueur ''' def get_score(self): return self.score ''' Modifie le score du joueur ''' def set_score(self, score): self.score = score ''' Renvoie le nom du joueur ''' def get_name(self): return self.name ''' Renvoie la connection avec le joueur ''' def get_conn(self): return self.conn ''' Permet de print un joueur ''' def __repr__(self): return "Player : " + self.name + ", Coords : (" + str(self.case_x) + "," + str(self.case_y) + "), Score : " \ + str(self.score)
4f6047d91e8b99e652508a7ec7537c681e40bb66
Ktsunezawa/Python-practice
/complete/practice/trapezoid.py
157
3.515625
4
def get_trapezoid(upper=10, lower=10, height=10): return (upper + lower) * height / 2 print('台形の面積は', get_trapezoid(upper=2, height=3))