blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2b9c010fcbc0c77d42919128b13fe285a4fa94e2 | irfan-ansari-au28/Python-Pre | /Interview/RandomQuestions/matrix_prob.py | 1,105 | 3.796875 | 4 |
"""
# A = [
# ['#', '#', '#'],
# ['#', '', '#'],
# ['#', '#', '#'],
# ]
for 3 X 3 gap = 1 idx =[ (1,)]
for 4 X 4 gap = 2**2 idx = [(1,1),(1,2),(2,1),(2,2)]
for 5 X 5 gap = 3**3 idx = [((1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3))]
"""
ip= int(input('Enter row or column of a square matrix greater than 3 : '))
A = [[0 for i in range(ip)] for j in range(ip)]
# print(A)
rows = len(A)
cols = len(A[0])
list_of_non_border_ele = []
def findIdxOfGap(rows,cols):
for row in range(1, rows-1):
for col in range(1, cols-1):
# print(row,col)
list_of_non_border_ele.append((row,col))
findIdxOfGap(rows,cols)
# print(list_of_non_border_ele)
def printBorderElements(rows,cols):
for row in range(rows):
for col in range(cols):
if (row,col) in list_of_non_border_ele:
A[row][col] = ' '
print(A[row][col], end=' ')
else:
A[row][col] = '#'
print(A[row][col], end=' ')
print()
printBorderElements(rows,cols)
# print(A)
|
02b826027ec3d85ddc982ee11df3966527eb041f | irfan-ansari-au28/Python-Pre | /Doubt/week08_day01.py | 311 | 3.84375 | 4 | #Q-1) Next Greater Element
#Answer:-
def find_next_ele(A):
for i in range(len(A)):
next_ele = -1
for j in range(i+1,len(A)):
if A[j]>A[i]:
next_ele = A[j]
break
print(next_ele,end =" ")
if __name__ == "__main__":
A= [2,6,4,7,8,3,5,9] # 0 1 2 3 4 5 6 7 8
find_next_ele(A)
# t(n) : O(n**2)
|
fb745ae55b2759660a882d00b345ae0db70e60d2 | irfan-ansari-au28/Python-Pre | /Interview/DI _ALGO_CONCEPT/stack.py | 542 | 4.28125 | 4 | """
It's a list when it's follow stacks convention it becomes a stack.
"""
stack = list()
#stack = bottom[8,5,6,3,9]top
def isEmpty():
return len(stack) == 0
def peek():
if isEmpty():
return None
return stack[-1]
def push(x):
return stack.append(x)
def pop():
if isEmpty():
return None
else:
return stack.pop()
if __name__ == '__main__':
push(8)
push(5)
push(6)
push(3)
push(9)
print(isEmpty())
print(peek())
x = pop()
print(x,'pop')
print(stack) |
bcca7baa2d01e320b8a0c2257cbb1c9b2a0db405 | irfan-ansari-au28/Python-Pre | /ClassPractice/W4D3/main.py | 324 | 3.796875 | 4 | from student import Student
if __name__ == '__main__':
name = input('Enter the name of the student')
age = int(input('Enter the age of the student'))
birth = int(input('Enter the birth date of the student'))
pradeep = Student(name,age,birth)
print(pradeep.name)
print(pradeep.age)
pradeep.read() |
4cebce3d1fd394fb85db8ad4bee95f51b1e50dda | irfan-ansari-au28/Python-Pre | /Lectures/lecture4/nested_loop.py | 96 | 3.546875 | 4 |
for i in range(3):
for j in range(3):
for k in range(3):
print(i,j,k) |
d74a82478b26a11505f547aefe6dcdea9efebce0 | TSG405/Simple-Games | /main/Rock Paper Scissor/rock_paper_scissor_2_players.py | 1,568 | 3.84375 | 4 | s1=0
s2=0
# LOGICAL FUNCTION
def winner(p1, p2):
global s1
global s2
if (p1 == p2):
s1+=1
s2+=1
return "It's a tie!"
elif (p1 == 'r'):
if (p2 == 's)':
s1+=1
return "First Player wins!"
else:
s2+=1
return "Second Player wins!"
elif (p1 == 's'):
if (p2 == 'p'):
s1+=1
return "First Player wins!"
else:
s2+=1
return"Second Player wins!"
elif (p1 == 'p'):
if (p2 == 'r'):
s1+=1
return "First Player wins!"
else:
s2+=1
return "Second Player wins!"
else:
return "Invalid Input!"
print(" --- ** --- !WELCOME TO THE R.P.S GAME! --- ** --- ")
try:
c=int(input("\nHow many rounds will you like to play? Enter that number:"))
except:
print("INVALID INPUT! Try again, next time!")
exit()
if c<=0:
print("Negative number not allowed! Redirecting to 1 round only!")
c=1
# DRIVER CODE...
while(c>0):
print("\nRounds left -->",c)
player1 = input("\nFirst player: rock [enter 'r'], paper [enter 'p'] or scissors [enter 's']: ").lower()
player2 = input("Second Player: rock [enter 'r'], paper [enter 'p'] or scissors [enter 's']: ").lower()
print(winner(player1, player2))
c-=1
# RESULTS
if s1>s2:
print("\nUltimate Winner ---> First Player")
elif s1<s2:
print("\nUltimate Winner ---> Second Player")
else:
print("\nTie GAME!")
@ CODED BY TSG405, 2020
|
c6d3d321cbe9cc790a109506c8b80f9d11397462 | mattblk/Study | /Python/level1/level1_이상한문자만들기.py | 397 | 3.578125 | 4 | def solution(s):
_list = s.split(" ")
answer = ''
def sub(string):
k=0
sub_ans=''
for i in string:
if i==' ' : sub_ans+=' '
elif k%2 == 0 : sub_ans+=i.upper()
else : sub_ans+=i.lower()
k=k+1
return sub_ans
for i in _list :
answer+=sub(i)+" "
return answer[:-1]
#score 12
|
e6ae535a8661e08d94cbb21e812a1f2580f29f09 | mattblk/Study | /Python/level2/level2_가장큰수.py | 929 | 3.59375 | 4 | # a=[1,3,4,56,4,2,23,12,89,9,888,999,331,1000]
a=[3, 30, 34, 5, 9]
def solution(arr):
def str_arr(arr):
str_arr=""
for i in range(0, len(arr)):
str_arr= str_arr + str(arr[i])
return str_arr
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot=arr[len(arr)//2]
lesser_arr, equal_arr, greater_arr = [],[],[]
for num in arr:
if int(str(num)+str(pivot)) > int(str(pivot)+str(num)) :
lesser_arr.append(num)
elif int(str(num)+str(pivot)) < int(str(pivot)+str(num)) :
greater_arr.append(num)
else :
equal_arr.append(num)
return quick_sort(lesser_arr) + equal_arr + quick_sort(greater_arr)
if str_arr(quick_sort(arr))[0] == 0 :
return "0"
else:
return str_arr(quick_sort(arr))
print(solution(a))
|
785495eea588f1ac26f5bb49457648c072e3346b | mattblk/Study | /Python/level1/level1_두개뽑아서더하기.py | 545 | 3.765625 | 4 | numbers = [0,0]
def solution(numbers):
# 두개의 수 합 array
arr_sum=[]
# 두개의 수 합을 구하는 함수 추가
def add_sum(nums):
# 배열 backward
num_foward = nums[0]
arr_backward=nums[1:len(nums)]
for i in arr_backward :
arr_sum.append(num_foward + i)
if len(arr_backward) >= 2 :
add_sum(arr_backward)
add_sum(numbers)
answer = list(set(arr_sum))
answer.sort()
return answer
print(solution(numbers))
|
672038829fa89be5aeb711cff4d9b26289028f5c | Vanderson10/Codigos-Python-UFCG | /mtp4/FuncionarioMes/funcionariomes.py | 842 | 3.890625 | 4 | #Receber a quantidade de chinelos produzidos por cada funcionario nos vários turnos dele.
#Saida: descobrir quem vendeu mais chinelos.
#obs:. não haberá empates
#1)receber cada usuario e realizar a soma do quanto eles venderam
#2)colocar cada soma numa lista
#3)colocar o nome numas lista
#4) analisar quem vendeu mais na lista
nomes = []
soma = 0
somas = []
while True:
nome = input()
if nome=="fim":break
else:nomes.append(nome)
while True:
n = input()
if n=="-": break
else: soma+=int(n)
somas.append(soma)
soma = 0
#analisar qual soma é maior
i = 1
maior = somas[0]
nom = nomes[0]
while i<len(somas):
if maior>=somas[i]:
maior = maior
nom = nom
else:
maior = somas[i]
nom = nomes[i]
i+=1
print(f'Funcionário do mês: {nom}')
|
88ea10bba74dc895a0cddb587de8f81f808e19ea | Vanderson10/Codigos-Python-UFCG | /4simulado/ar.py | 155 | 3.671875 | 4 | x = int(input())
y = int(input())
if x>y:
print("---")
exit()
menos = y-x
for i in range(0,menos+1):
atu = x+i
print(f'{atu} {atu*atu}')
|
8259b3a8301dac20fd5cf5d83f0a1dbb93aa0fda | Vanderson10/Codigos-Python-UFCG | /uni4/melhordesempenho/melhordesempenho.py | 568 | 3.5625 | 4 | #calcular qual aluno teve mais "." no miniteste
#se tiver empate coloca o primeiro
#se n acertar nenhuma questão é pra imprimir -1
quant = int(input())
#encontrar qual teve mais "."
maior = 0
lista = []
for i in range(quant):
exercicio = input()
soma = 0
for t in range(0,len(exercicio)):
if exercicio[t] == ".":
soma +=1
lista.append(soma)
if maior<soma:
maior = soma
if maior == 0:
print(-1)
exit()
for v in range(0,len(lista)):
if lista[v]==maior:
print(v+1)
break
|
7fedccbfa707a0a01b76ab3b65d91683abb1967e | Vanderson10/Codigos-Python-UFCG | /uni3/natalina/natalina.py | 1,699 | 3.703125 | 4 | #gratificação de natal
#dados: 235 dias, G = (235 - número de dias que faltou) * valor-da-gratificação-por-dia-trabalhado
#caso ele não tenha faltado nenhum dia tem a gratificação também
#entrada: codigo do cargo, dias que faltou
cod = int(input())
#caso1
if cod == 1:
print('Deverá receber em dezembro R$ 25000.00.')
elif cod ==2:
print('Deverá receber em dezembro R$ 15000.00.')
elif cod ==3:
diasfaltou = int(input())
gratificacao = (235-diasfaltou)*2
if diasfaltou ==0:
gt = 500
sala = 8000+gt
print(f"Valor da gratificação R$ {gt:.2f}.")
print(f"Deverá receber em dezembro R$ {sala:.2f}.")
else:
sala = 8000+gratificacao
print(f"Valor da gratificação R$ {gratificacao:.2f}.")
print(f"Deverá receber em dezembro R$ {sala:.2f}.")
elif cod ==4:
diasfaltou = int(input())
gratificacao = (235-diasfaltou)*1
if diasfaltou ==0:
gt = 300
sala = 5000+gt
print(f"Valor da gratificação R$ {gt:.2f}.")
print(f"Deverá receber em dezembro R$ {sala:.2f}.")
else:
sala = 5000+gratificacao
print(f"Valor da gratificação R$ {gratificacao:.2f}.")
print(f"Deverá receber em dezembro R$ {sala:.2f}.")
elif cod ==5:
diasfaltou = int(input())
gratificacao = (235-diasfaltou)*0.7
if diasfaltou ==0:
gt = 200
sala = 2800+gt
print(f"Valor da gratificação R$ {gt:.2f}.")
print(f"Deverá receber em dezembro R$ {sala:.2f}.")
else:
sala = 2800+gratificacao
print(f"Valor da gratificação R$ {gratificacao:.2f}.")
print(f"Deverá receber em dezembro R$ {sala:.2f}.")
|
511b43f80a63e424aa9403ac3a9d21529eca3082 | Vanderson10/Codigos-Python-UFCG | /4simulado/tabelaquadrados/Chavesegura/chavesegura.py | 1,009 | 4.125 | 4 | #analisar se a chave é segura
#se não tiver mais que cinco vogais na chave
#não tem tre caracteres consecultivos iguais
#quando detectar que a chave não é segura é para o programa parar e avisar ao usuario
#criar um while e analisar se tem tres letras igual em sequencia
#analisar se tem mais que cinco vogais, analisar com uma lista cada letra.
#entrada
chave = input()
pri = chave[0]
seg = chave[1]
i = 2
soma = 0
vogais = ['A','E','I','O','U','a','e','i','o','u']
e = 0
while True:
if pri == seg and pri == chave[i]:
print("Chave insegura. 3 caracteres consecutivos iguais.")
break
else:
pri = seg
seg = chave[i]
i=i+1
for v in vogais:
if v==chave[e]:
soma = soma+1
break
e=e+1
if soma>5:
print("Chave insegura. 6 vogais.")
break
if i==len(chave):
print("Chave segura!")
break
if e>len(chave):
print("Chave segura!")
|
c1f33cd31e1dd2237b7b4ad92268858864ed9f7f | Vanderson10/Codigos-Python-UFCG | /uni4/SOMAIMPARES/somai.py | 798 | 3.734375 | 4 | #recebe uma sequencia e calcula a soma dos ultimos impares até atingir o valor limite
#obs. o valor limite não entra na soma
#ex. 3,1,6,4,7 com limite 9, soma = 8 (1+7) obs. de tras pra frente
#1-entrada: quantos itens, limite, nuns da sequencia
quant = int(input())
limite = int(input())
#nuns dentro do for
#colocar os elementos dentro de uma lista
lista = []
for i in range(0,quant):
n = int(input())
lista.append(n)
#criar um for e colocar a lista de tras pra frente pra facilitar
listai = []
for i in range(0,quant):
listai.append(lista[(quant-1)-i])
#somar os elementos impares até chegar no valor limite (<=)
soma = 0
for n in listai:
if n%2!=0:
soma=soma+n
if soma>=limite:
soma= soma-n
break
#imprimir a soma
print(soma)
|
5e91680b3e38d6d2798d93a6c327cf64c5b8af8f | FloVnst/Python-Challenge-2020 | /solutions/road_trip.py | 2,499 | 3.796875 | 4 | # Processing
def road_trip(distance, speed, departure):
durationMinutes = int((distance / speed) * 60)
durationHours = durationMinutes // 60
durationMinutes -= durationHours * 60
# Generate the text for the departure time
if departure[1] < 10:
departureResult = "Départ à {}h0{}".format(departure[0], departure[1])
else:
departureResult = "Départ à {}h{}".format(departure[0], departure[1])
# Generate the text for the duration of the travel
durationResult = "Trajet de "
if durationHours > 0:
durationResult += "{} heure".format(durationHours)
if durationHours > 1:
durationResult += 's'
durationResult += " et "
durationResult += "{} minute".format(durationMinutes)
if durationMinutes != 1:
durationResult += 's'
arrival = [0, 0] # [hours, minutes]
arrival[1] = (departure[1] + durationMinutes) % 60
arrival[0] = (departure[0] + durationHours + (departure[1] + durationMinutes) // 60) % 24
# Generate the text for the arrival time
if arrival[1] < 10:
arrivalResult = "Arrivée prévue à {}h0{}".format(arrival[0], arrival[1])
else:
arrivalResult = "Arrivée prévue à {}h{}".format(arrival[0], arrival[1])
return departureResult + '\n' + durationResult + '\n' + arrivalResult
# Unit Tests API Input
# print(road_trip(lines[0], lines[1], lines[2]))
# Tests
print(road_trip(45, 95, [7, 10])) # Must return "Départ à 7h10\nTrajet de 28 minutes\nArrivée prévue à 7h38"
print(road_trip(600, 115, [23, 10])) # Must return "Départ à 23h10\nTrajet de 5 heures et 13 minutes\nArrivée prévue à 4h23"
print(road_trip(200, 75, [23, 55])) # Must return "Départ à 23h55\nTrajet de 2 heures et 40 minutes\nArrivée prévue à 2h35"
print(road_trip(15, 45, [15, 3])) # Must return "Départ à 15h03\nTrajet de 20 minutes\nArrivée prévue à 15h23"
print(road_trip(0.1, 6, [15, 3])) # Must return "Départ à 15h03\nTrajet de 1 minute\nArrivée prévue à 15h04"
print(road_trip(1, 0.97, [15, 3])) # Must return "Départ à 15h03\nTrajet de 1 heure et 1 minute\nArrivée prévue à 16h04"
print(road_trip(1, 0.99, [15, 3])) # Must return "Départ à 15h03\nTrajet de 1 heure et 0 minutes\nArrivée prévue à 16h03"
print(road_trip(143, 140, [18, 30])) # Must return "Départ à 18h30\nTrajet de 1 heure et 1 minute\nArrivée prévue à 19h31"
|
d43a0da77a1fa9164087b0a4dbc9b3be38c33d82 | venkataniharbillakurthi/python-lab | /ex-2.py | 263 | 4.0625 | 4 | a=int(input('Enter the number:'))
b=int(input('Enter the number:'))
c=int(input('Enter the number:'))
sum=a+b+c
average=(a+b+c)/3
print('sum = ',sum,'\naverage = ',average)
Enter the number:23
Enter the number:45
Enter the number:67
sum = 135
average = 45.0
|
b0f286afb0b68bc79aa25c4808abf5ad406cd582 | KAPILSGNR/KapilSgnrMath | /KapilSgnrMath/MyRectangle.py | 239 | 3.625 | 4 | class Rectangle:
def __init__(self,length, width):
self.length=length
self.width=width
def getArea(self):
area= self.length*self.width
print("Area of the Rectangle is: ", area)
return area |
6a34496d114bc6e67187e4bc12c8ff874d575de0 | BrightAdeGodson/submissions | /CS1101/bool.py | 1,767 | 4.28125 | 4 | #!/usr/bin/python3
'''
Simple compare script
'''
def validate(number: str) -> bool:
'''Validate entered number string is valid number'''
if number == '':
print('Error: number is empty')
return False
try:
int(number)
except ValueError as exp:
print('Error: ', exp)
return False
return True
def read_number(prefix: str) -> int:
'''Read number from the prompt'''
while True:
prompt = 'Enter ' + prefix + ' > '
resp = input(prompt)
if not validate(resp):
continue
number = int(resp)
break
return number
def compare(a, b: int) -> (str, int):
'''
Compare two numbers
It returns 1 if a > b,
returns 0 if a == b,
returns -1 if a < b,
returns 255 if unknown error
'''
if a > b:
return '>', 1
elif a == b:
return '==', 0
elif a < b:
return '<', -1
return 'Unknown error', 255
def introduction():
'''Display introduction with example'''
_, example1 = compare(5, 2)
_, example2 = compare(2, 5)
_, example3 = compare(3, 3)
print('''
Please input two numbers. They will be compared and return a number.
Example:
a > b is {}
a < b is {}
a == b is {}
'''.format(example1, example2, example3))
def main():
'''Read numbers from user input, then compare them, and return result'''
introduction()
first = read_number('a')
second = read_number('b')
result_str, result_int = compare(first, second)
if result_int == 255:
print(result_str)
return
print('Result: {} {} {} is {}'.format(first, result_str, second,
result_int))
if __name__ == "__main__":
main()
|
0b3c1743acf1b4f3ad68757fe8699ee10fc8f67e | abhi-accubits/caffinated | /src/filegen.py | 676 | 3.671875 | 4 | import os
"""
File Generator
Author Danwand NS github.com/DanBrown47
verify if the buffer file is present, if not generates one
as temp storage of the file
"""
class FileGen:
"""
Checks if the file is present if not generate
"""
def __init__(self, path) -> None:
self.path = path
pass
def generate(self) -> None:
os.mkdir("godown")
os.chdir("godown")
f = open("buff.txt","x")
def isFile(self) -> None:
presence = os.path.isfile(self.path)
if not presence:
FileGen.generate(self)
else:
# Can Add banner here
print("File Exists")
pass
|
009b1d64116333f801b6b7947d336be76686f082 | BowieSmith/project_euler | /python/p_001.py | 133 | 4.0625 | 4 | # Find the sum of all the multiples of 3 or 5 below 1000.
ans = sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)
print(ans)
|
49b854f0322357dd2ff9f588fc8fb9c6f62fd360 | BowieSmith/project_euler | /python/p_004.py | 352 | 4.125 | 4 | # Find the largest palindrome made from the product of two 3-digit numbers.
def is_palindrome(n):
s = str(n)
for i in range(len(s) // 2):
if s[i] != s[-i - 1]:
return False
return True
if __name__ == "__main__":
ans = max(a*b for a in range(100,1000) for b in range(100,1000) if is_palindrome(a*b))
print(ans)
|
81c2f882685c1222115f2700ae39aeb77da3749a | BowieSmith/project_euler | /python/p_019.py | 1,550 | 4.03125 | 4 | # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
# Assume 1 Jan 1900 was a Monday
def is_leap_year(n):
if n % 4 != 0: # leap years on years divisible by 4
return False
if n % 400 == 0: # also on years divisible by 400
return True
if n % 100 == 0: # but not other centuries
return False
return True
# 1 2 3 4 5 6 7 8 9 10 11 12
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 0 1 2 3 4 5 6
weekdays = ["sun", "mon", "tues", "wed", "thurs", "fri", "sat"]
def cal_gen(y, m, d, wkdy):
year = y
month = m
day = d
wkday = wkdy
while True:
yield (year, month, day, wkday)
if ((day < 31 and month in (1, 3, 5, 7, 8, 10, 12)) or
(day < 30 and month in (4, 6, 9, 11)) or
(day < 28 and month == 2) or
(day < 29 and month == 2 and is_leap_year(year))):
day += 1
elif month < 12:
month += 1
day = 1
else:
year += 1
month = 1
day = 1
wkday = (wkday + 1) % 7
if __name__ == "__main__":
first_of_month_sunday = 0
cal = cal_gen(1900, 1, 1, 1)
date = next(cal)
while date[0] < 2001:
if (date[0] > 1900 and
date[2] == 1 and
date[3] == 0):
first_of_month_sunday += 1
date = next(cal)
print(first_of_month_sunday)
|
48d4eaad07fc9dcfa1f4c8b4a1f364bc02bbbd7f | Dron2200/My-first-steps-in-Python | /HW3_4.py | 554 | 4.0625 | 4 | print("This program is more interesting that previous", '\n',
"So, using this program you can resolve following formula", '\n',
"ax^2 + bx + c = 0 ")
a = float(input("Please, write a :"))
b = float(input("Please, write b :"))
c = float(input("Please, write c :"))
d = (b**2 - 4*a*c)
x = -(b/2*a)
x1 = None
x2 = None
if d < 0:
print("you have no results D<0")
elif d == 0:
print("You have one result x =", x)
elif d > 0:
x1 = (-b + d ** 0.5) / 2 * a
x2 = (-b - d ** 0.5) / 2 * a
print("x1=", x1, "x2=", x2) |
1def7f563fa6c611e1806b07e94c84e8af0cbb0d | Dron2200/My-first-steps-in-Python | /lesson2_3.py | 362 | 4.03125 | 4 | print("Homework-2 Task-3")
print("This program is more interesting that previous", '\n',
"So, using this program you can resolve following formula", '\n',
"ax^2 + bx + c = 0 ")
a = float(input("Please, write a :"))
b = float(input("Please, write b :"))
c = float(input("Please, write c :"))
x = (-b + (b**2 - 4*a*c)**0.5) / (2*a)
print(x) |
ccb6c8bd7bd657668691cad6c3fa7c5bd699c766 | tameravci/FeedForwardNNet | /AvciNeuralNet.py | 7,606 | 4.09375 | 4 |
# coding: utf-8
# # Simple feedforward neural network with Stochastic Gradient Descent learning algorithm
#
# Tamer Avci, June 2016
#
# Motivation: To get better insights into Neural nets by implementing them only using NumPy.
# Task: To classify MNIST handwritten digits: http://yann.lecun.com/exdb/mnist/
#
# Accuracy:~95%
#
# Deficiencies:
# No optimization of the code
# No cross-validation split.
#
# 1) Define a network class. Instance variables will be:
# -num of layers e.g. [2,3,1]
# -size of our network [2, 3, 1] = 3
# -bias vectors
# -weight matrices
#
# 2) Write the instance methods:
# -feedforward: used to pass the input forward once and evaluate
# -train: take batches of the data and call SGD to minimize the cost function
# -SGD: for every single input in the batch, call backprop to find the derivatives with respect to
# weights and bias, and then update those in the descent direction
# -backprop: find the derivatives using chain rule (watch the video for more help)
# -evaluate: run feedforward after training and compare it against target value
# -cost_derivative: as simple as (y(target) - x(input))
# -sigmoid: sigmoid function (1 / 1 - exp(-z))
# -sigmoid delta: derivative of the sigmoid function
# In[ ]:
#import dependencies
import random
import numpy as np
# In[46]:
class Network(object):
def __init__(self, layer):
# layer: input layer array
# Example usage >>> net = Network([2,3,1])
# For instance [2,3,1] would imply 2 input neurons, 3 hidden neurons and 1 output neuron
self.num_layers = len(layer)
self.sizes = layer
# Create random bias vectors for respective layers using uniform distribution
self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]
# Create weight matrices for respective layers, note the swap x,y
self.weights = [np.random.randn(y, x) for x, y in zip(self.sizes[:-1], self.sizes[1:])]
def feedforward(self, a):
""" For each layer take the bias and the weight, and apply sigmoid function
Return the output of the network if "a" is input. Used after training when evaluating"""
for b, w in zip(self.biases, self.weights):
#One complete forward pass
a = sigmoid(np.dot(w, a)+b)
return a
def train(self, training_data, epochs, mini_batch_size, eta, test_data=test_data):
""" Train the neural network taking batches from the data hence stochastic SGD """
#provide training data, number of epochs to train, batch size, the learning rate and the test_data
#learning rate: how fast do you want the SGD to proceed
n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
random.shuffle(training_data) #shuffle the data
mini_batches = [training_data[k:k+mini_batch_size]
for k in xrange(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.SGD(mini_batch, eta)
#uncomment this if you want intermediate results
#print "Batch: {0} / {1}".format(self.evaluate(test_data), n_test)
#otherwise epoch results:
print "Epoch {0}: {1} / {2}".format(j, self.evaluate(test_data), n_test)
def SGD(self, mini_batch, eta):
"""Update the network's weights and biases by applying
gradient descent using backpropagation (derivatives) to a single mini batch."""
#provide the mini_batch and the learning rate
#create empty derivative array of vectors for each layer
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
#call backprop for this particular input
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
#update the derivative
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
#update the weight and biases in the negative descent direction aka negative derivative
self.weights = [w-(eta/len(mini_batch))*nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b-(eta/len(mini_batch))*nb
for b, nb in zip(self.biases, nabla_b)]
def backprop(self, x, y):
"""For in-depth computation of the derivatives watch my video!"""
delta_nabla_b = [np.zeros(b.shape) for b in self.biases]
delta_nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass <<<--- output layer
delta = self.cost_derivative(activations[-1], y) * sigmoid_prime(zs[-1])
#delta is simply cost_derivate times the sigmoid function of the last activation aka output which
#is the derivative of the bias for output layer
delta_nabla_b[-1] = delta
#derivative of the weights:
#delta * output of the previous layer which is the previous activation before the output
delta_nabla_w[-1] = np.dot(delta, activations[-2].transpose())
#backward pass <<<--- hidden layers
#using negative indices: starting from the first hidden layer and backwards
for l in xrange(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
delta_nabla_b[-l] = delta
delta_nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (delta_nabla_b, delta_nabla_w)
def evaluate(self, test_data):
"""Return the number of test inputs for which the neural
network outputs the correct result. Note that the neural
network's output is assumed to be the index of whichever
neuron in the final layer has the highest activation."""
test_results = [(np.argmax(self.feedforward(x)), y) for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
def cost_derivative(self, output_activations, y):
return (output_activations-y)
def sigmoid(z):
""" Classic sigmoid function: lot smoother than step function
that MLP uses because we want small changes in parameters lead to
small changes in the output """
return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))
# Sources:
# Neural networks and deep learning, Michael Nielsen (great book!)
# http://neuralnetworksanddeeplearning.com/chap2.html
# Neural network, backpropagation algorithm, Ryan Harris
# https://www.youtube.com/watch?v=zpykfC4VnpM
# MNIST database
#
# Code:
# mnist_loader is completely Nielsen's work
# Network code is also majorly inspired by him. I have made modifications to make it simpler.
|
b1ce06dcf2fffe8543d67751f712166d20000bf7 | ysw900524/Python_Multicampus | /Day4_10_27/s606_인스턴스변수_인스턴스간공유안됨.py | 556 | 3.5 | 4 | # 인스턴스 변수
class Cat:
def __init__(self, name):
self.name = name
self.tricks = [] # 인스턴스 변수 선언
def add_trick(self, trick):
self.tricks.append(trick) #인스턴스 변수에 값 추가
cat1 =Cat('하늘이')
cat2 = Cat('야옹이')
cat1.add_trick('구르기')
cat2.add_trick('두발로 서기')
cat2.add_trick('죽은척 하기')
print(cat1.name, ":", cat1.tricks)
print(cat2.name, ':', cat2.tricks)
# 하늘이 : ['구르기']
# 야옹이 : ['두발로 서기', '죽은척 하기'] |
daa15a806aa377a9261d0d4cb94a4d3676904b86 | ysw900524/Python_Multicampus | /Day4_10_27/Day4_미션1_로또번호생성.py | 1,121 | 4.03125 | 4 | # 미션 1
# 로또 번호를 자동으로 생성해서 출력
# 주문한 개수만큼 N개의 로또 번호 출력
# Hint : 랜덤 숫자 생성
# import random
# random.randint(num1, num2) # num1~num2까지의 정수 생성
#
# Ex. dice.py
# import random
#
# dice_num = random.randint(1, 6)
# print('주사위:'. doce_num)
import random
# class Lotto:
# nums = set()
#
# def select(self, num):
# while len(num) <= 7:
# num.add(random.randint(1,45))
# print(num)
#
# class Lotto:
# nums = set()
#
# def __init__(self, num):
# while len(num) <= 7:
# self.nums.add(random.randint(1,45))
#
# def select(self):
#
#
# mylotto = Lotto()
# my_lotto = mylotto.select()
# print(my_lotto)
class Lotto:
final = list()
def select(self, n):
for i in range(n):
nums = set()
while len(nums) <= 6:
num = random.randint(1, 45)
nums.add(num)
self.final.append(nums)
return self.final
try1 = Lotto()
x = try1.select(4)
print(x)
|
c8e8670b016510be47f75896a82fecaadef0aa77 | ysw900524/Python_Multicampus | /Day2_10_25/Day2_과제_도형그리기.py | 865 | 4 | 4 | import turtle
import math
import time
width = 100
height = 100
slide = math.sqrt(width**2 + height**2)
input('엔터를 치면 거북이가 도형을 그립니다.')
turtle.shape('turtle')
turtle.pensize(5)
turtle.color('blue')
print('거북이 달리기 시작합니다.')
#time.sleep(1)
turtle.forward(width)
#time.sleep(1)
turtle.right(135)
turtle.forward(slide)
#time.sleep(1)
turtle.left(135)
turtle.forward(width)
#time.sleep(1)
turtle.left(135)
turtle.forward(slide)
#time.sleep(1)
turtle.left(135)
turtle.forward(height)
#time.sleep(1)
turtle.left(90)
turtle.forward(width)
#time.sleep(1)
turtle.left(90)
turtle.forward(width)
#time.sleep(1)
turtle.left(45)
turtle.forward(slide/2)
#time.sleep(1)
turtle.left(90)
turtle.forward(slide/2)
turtle.done()
# time.sleep(1)
# turtle.right(90)
# turtle.forward(width)
#
# time.sleep(1)
# turtle.
|
a9e29aa8ec9548ea7928a9d83598ddcdec7e4ba7 | ysw900524/Python_Multicampus | /Day1_10_24/s105_comment.py | 626 | 3.65625 | 4 | # 한줄 주석 : 샵기호(#)로 시작하는 줄
# 블럭 주석 : 큰따옴표 3개로 감사는 줄
# 이 줄은 라인 코멘트입니다.
print("Hello World!")
print("Hello World!") # 이것도 라인 코멘트입니다.
print("Hello World!") # 이것도 라인 코멘트입니다.
# First comment
a = 15 # Second comment
# a값을 출력해 보세요!
print(a)
b = '파이썬의 주석은 샾기호(#)로 시작합니다.'
print(b)
# 마지막 라인입니다.
# 한줄 주석과 블럭 주석
"""
블럭주석,
즉 멀티라인의 주석문은 따옴표(''' ''') 3개
"""
# 한줄 주석문은 샾기호(#)
|
00cf2f1c84d610e15e65b70d4a643caea0a01c4c | JordenHai/workSpace | /oldboyDaysDir/day1/passwd.py | 360 | 3.625 | 4 | # -*- coding:utf-8 -*-
# Author: Jorden Hai
#秘文输入
import getpass
#新的包
_username = 'jh'
_password = '123456'
username = input("username:")
password = input("password:")
if username == _username and _password == password:
print("Success Login!")
print('''Wellcome user {_name} login...'''.format(_name = username))
else:
print("Fail")
|
44c8ac49899f2174a56812c8e62d229ea7b0c3a3 | JordenHai/workSpace | /oldboyDaysDir/day6/MulIheri.py | 695 | 3.984375 | 4 | # -*- coding:utf-8 -*-
# Author: Jorden Hai
class A():
def __init__(self):
print("init in A")
class B(A):
def __init__(self):
A.__init__(self)
print("init in B")
class C(A):
def __init__(self):
A.__init__(self)
print("init in C")
class D(B,A): #找到第一个就停下来
pass
#
# A
# | \
# B C
# D
#继承策略
#继承方向 从D --> B --> C --> A 广度优先查找
#
#从python3中经典类新式类按照广度优先
#从python2中经典类中深度优先来继承 新式类按照广度优先来继承
#
#继承方向 从D --> B --> A --> C 深度优先查找
a = D() |
5be234e49a9106b7bdef8a1cea9def37cc97a72b | JordenHai/workSpace | /oldboyDaysDir/day1/集合.py | 1,073 | 3.859375 | 4 |
list_1 = [1,4,5,6,9,7,3,1,2]
list_1 = set(list_1)
print(list_1)
list_2 = set([2,6,0,66,22,8,4])
print(list_2)
#交集
list_3 = list_1.intersection(list_2)
print(list_3)
#并集
list_3 = list_1.union(list_2)
print(list_3)
#差集
list_3 = list_1.difference(list_2)
print(list_3)
list_3 = list_2.difference(list_1)
print(list_3)
#子集
#判断是不是子集
print(list_1.issubset(list_2))
print(list_1.issuperset(list_2))
list_3 = set([1,3,7])
print(list_3.issubset(list_1))
print(list_1.issuperset(list_3))
#反向的差集
#对称差集
list_3 = list_1.symmetric_difference(list_2)
#去掉大家都有的
print(list_3)
L = []
for value in list_3:
L.append(value)
print(L)
#disjoint
list_3 = [22,44,55]
print(list_1.isdisjoint(list_3))
#用运算符来计算交并
print(list_1&list_2)#交集
print(list_1|list_2)#并集
print(list_1-list_2)#差集
print(list_1^list_2)#对称差集
#subset and upperset
#没有专门符号
print(list_1)
list_1.add(99)
print(list_1)
list_1.update([88,99,66,33])
print(list_1)
list_1.remove(1)
print(list_1)
|
a60a933c68c6210b3c407f3bdfcae0352cd575c6 | MarkHershey/PythonWorkshop2020 | /Session_01/py101/10_classes.py | 418 | 3.984375 | 4 | class People:
def __init__(self, name, birthYear):
self.name = name
self.birthYear = birthYear
self.age = 2020 - birthYear
self.height = None
self.pillar = None
p1 = People("Maria", 1999)
print(p1.name)
print(p1.birthYear)
print(p1.age)
p1.pillar = "Architecture and Sustainable Design (ASD)"
print(f"{p1.name} is {p1.age} years old, and she is majored in {p1.pillar}")
|
552b2a950f718a75b11dcba8ee93fbb41ad4438c | zhengshaobing/PythonSpider | /BK_全局锁机制_生产者与消费者模式.py | 1,899 | 3.625 | 4 | import threading, random, time
Qmoney = 1000
# Value_data = 0
gLock = threading.Lock()
gTotal_times = 10
gtimes = 0
#
#
# class CountThread(threading.Thread):
# def run(self):
# global Value_data
# # 锁主要用于:修改全局变量的地方
# gLock.acquire()
# for x in range(1000000):
# Value_data += 1
# gLock.release()
# print(Value_data)
#
#
# def main():
# for x in range(2):
# t = CountThread()
# t.start()
'''
这种方法十分占用cpu资源,
不推荐使用
'''
# class Producer(threading.Thread):
# def run(self):
# global Qmoney
# global gtimes
# global gTotal_times
# while 1:
# money = random.randint(100, 1000)
# gLock.acquire()
# if gtimes >= gTotal_times:
# gLock.release()
# break
# Qmoney += money
# gtimes += 1
# gLock.release()
# print('生产了%d元,剩余了%d元'%(money, Qmoney))
# time.sleep(0.5)
#
#
# class Consumer(threading.Thread):
# def run(self):
# global Qmoney
# global gTotal_times
# global gtimes
# while 1:
# money = random.randint(100, 1000)
# gLock.acquire()
# if Qmoney >= money:
# Qmoney -= money
# gLock.release()
# print('消费了%d元,剩余了%d元' % (money, Qmoney))
# else:
# #if gtimes > gTotal_times:
# gLock.release()
# break
#
# time.sleep(0.5)
#
#
# def main():
#
# for x in range(1):
# t = Producer(name='生产者%d'%x)
# t.start()
# for x in range(3):
# t = Consumer(name='消费者%d'%x)
# t.start()
#
#
# if __name__ == '__main__':
# main()
|
5822eb6433daf2b6421c7a0f318729b043eb84fb | avelikev/Exercises | /data_structures/dictionaries_and_arrays/2.Reverse_Array /Solutions/solution.py | 196 | 4.0625 | 4 | from array import *
array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])
reverse_array = array('i')
for i in range(len(array_num)-1,-1,-1):
reverse_array.append(array_num[i])
print(reverse_array)
|
ae5fd33d822cacc8617bf5db2f8b4633f9860f1a | avelikev/Exercises | /introduction_to_python/functions/1_return_hello/Solution/solution.py | 128 | 3.671875 | 4 | # Code your solution here
def hello(name):
data="Hello "+name
return data
name=input()
result=hello(name)
print(result) |
73857ec7f281166378fecff5c1ab4f1ff3011d44 | avelikev/Exercises | /data_structures/stacks_and_queues/1_create_queue/Solution/solution.py | 369 | 3.703125 | 4 | # Code your solution here
def queue():
import queue
queue_a = queue.Queue(maxsize=5) # Queue is created as an object 'queue_a'
queue_a.put(9)
queue_a.put(6)
queue_a.put(7) # Data is inserted in 'queue_a' at the end using put()
queue_a.put(4)
queue_a.put(1)
return queue_a
data=queue()
result=list(data.queue)
print(result) |
7cddd25f93030f10c2c9a4e6eb71bb1445f7fc9c | avelikev/Exercises | /introduction_to_python/functions/3_total/Solution/solution.py | 160 | 3.5 | 4 | # Code your solution here
def summ(l):
total = 0
for x in l:
total=total+x
return total
l=[10,20,30,40,50,60]
result=summ(l)
print(result) |
1bd7f0daf5019e00dc508429182bd7016956bf33 | avelikev/Exercises | /data_structures/stacks_and_queues/2_stack_insert/Solution/solution.py | 237 | 3.515625 | 4 | # Code your solution here
def insert(stack_planets):
stack_planets.insert(2,'Earth')
return stack_planets
stack_planets=['Mercury','Venus','Mars','Jupiter','Saturn','Uranus','Neptune']
result=insert(stack_planets)
print(result) |
cbe50f30732a080bf558b0a77e29942ed2c04f7a | avelikev/Exercises | /data_structures/binary_trees/3_normal BST to Balanced BST/Solution/solution.py | 1,810 | 3.953125 | 4 | import sys
import math
# A binary tree node has data, pointer to left child
# and a pointer to right child
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
# This function traverse the skewed binary tree and
# stores its nodes pointers in vector nodes[]
def storeBSTNodes(root,nodes):
# Base case
if not root:
return
# Store nodes in Inorder (which is sorted
# order for BST)
storeBSTNodes(root.left,nodes)
nodes.append(root)
storeBSTNodes(root.right,nodes)
# Recursive function to construct binary tree
def buildTreeUtil(nodes,start,end):
# base case
if start>end:
return None
# Get the middle element and make it root
mid=(start+end)//2
node=nodes[mid]
# Using index in Inorder traversal, construct
# left and right subtress
node.left=buildTreeUtil(nodes,start,mid-1)
node.right=buildTreeUtil(nodes,mid+1,end)
return node
# This functions converts an unbalanced BST to
# a balanced BST
def buildTree(root):
# Store nodes of given BST in sorted order
nodes=[]
storeBSTNodes(root,nodes)
# Constucts BST from nodes[]
n=len(nodes)
return buildTreeUtil(nodes,0,n-1)
# Function to do preorder traversal of tree
def preOrder(root):
if not root:
return
return root.data
preOrder(root.left)
preOrder(root.right)
if __name__=='__main__':
root = Node(10)
root.left = Node(8)
root.left.left = Node(7)
root.left.left.left = Node(6)
root.left.left.left.left = Node(5)
root = buildTree(root)
# print("Preorder traversal of balanced BST is :")
result=preOrder(root)
print(result) |
eed8d54cb38af8b0bb62927b9dadfdf0aa69d378 | debargham14/bcse-lab | /Sem 4/Adv OOP/python_assignments_set1/sol10.py | 444 | 4.125 | 4 | import math
def check_square (x) :
"Function to check if the number is a odd square"
y = int (math.sqrt(x))
return y * y == x
# input the list of numbers
print ("Enter list of numbers: ", end = " ")
nums = list (map (int, input().split()))
# filter out the odd numbers
odd_nums = filter (lambda x: x%2 == 1, nums)
# filter out the odd squares
odd_squares = list (filter (check_square, odd_nums))
print ("Odd squares are: ", odd_squares) |
6b2736e3ef5bd2b374367750d21d8af3e9ca2e0a | debargham14/bcse-lab | /Sem 4/Adv OOP/python_assignments_set1/sol11.py | 434 | 4.28125 | 4 | print ("Pythagorean Triplets with smaller side upto 10 -->")
# form : (m^2 - n^2, 2*m*n, m^2 + n^2)
# generate all (m, n) pairs such that m^2 - n^2 <= 10
# if we take (m > n), for m >= 6, m^2 - n^2 will always be greater than 10
# so m ranges from 1 to 5 and n ranges from 1 to m-1
pythTriplets = [(m*m - n*n, 2*m*n, m*m + n*n) for (m,n) in [(x, y) for x in range (1, 6) for y in range (1, x)] if m*m - n*n <= 10]
print (pythTriplets) |
2f266658a68658cc904391e4fea493d8581025c8 | JasianJ/Python | /Fibonacci Sequence/Fibonacci.py | 1,195 | 4.09375 | 4 | from IPython.display import clear_output
def findnum(n):
out = []
a, b = 0, 1
for i in range(n):
out.append(a)
a, b = b, a+b
return out
def nth(n):
a, b = 0, 1
for i in range(n):
a, b = b, a+b
return a
on = True
print 'Enther a number to generate Fibonacci sequence to that number.'
while on == True:
print 'Option 1 for display sequence\nOption 2 for display Nth number'
op = int(raw_input('Press 1 or 2: '))
if op == 1:
n = int(raw_input('Display Fibonacci sequence, starts from 0, upto '))
if n > 20:
print 'Sorry your sequence is too long. Please use option 2.'
else:
print findnum(n)
elif op == 2:
n = int(raw_input('Display Nth number of Fibonacci sequence starts from 0. N = '))
print nth(n-1)
again = str(raw_input('Again? Y/N: ')).upper()
if again == 'Y':
clear_output()
pass
elif again == 'N':
clear_output()
on = False
break
else:
again = str(raw_input('Y or N only. Again? Y/N: ')).upper()
clear_output()
|
2c0d624ee886d24c10a979e922c1e7fbab74d7ed | AlterFritz88/flask_practice | /task_3_14_6.py | 758 | 3.546875 | 4 | class PiggyBank:
def __init__(self, dollars, cents):
self.dollars = dollars
self.cents = cents
def add_money(self, deposit_dollars, deposit_cents):
self.dollars += deposit_dollars
self.cents += deposit_cents
if self.cents > 99:
self.dollars += self.cents // 100
self.cents = self.cents % 100
# if deposit_cents + self.cents > 99:
# print('here')
# print((deposit_cents + self.cents) % 100)
# self.dollars += (deposit_cents + self.cents) // 100
# self.cents += (deposit_cents + self.cents) % 100
# else:
# self.cents += deposit_cents
pig = PiggyBank(10, 20)
pig.add_money(0, 90)
print(pig.dollars, pig.cents) |
bbe6083817412b75edfb6985b3718f08a6740faa | ThallesVale/calculadoraAnuncios | /calculadora.py | 849 | 3.765625 | 4 | #CALCULADORA - ALCANCE DE ANÚNCIO ONLINE:
investimento = input('Digite o valor a ser investido: ')
investimento = float(investimento)
#Visualizações atreladas ao valor investido:
visualizacao = investimento*30
#Cliques gerados por volume de visualizações:
cliques = int(visualizacao*.12)
#Compartilhamentos por volume de cliques:
compartilham = int(cliques*.15)
#Manipulação de compartilhamentos considerando restrições:
#Sequência de compartilhamentos
controle_compart = compartilham//5
resto = compartilham%5
controle_compart *= 4
controle_compart += resto
#Visualizações atreladas aos compartilhamentos:
visualiz_extra = controle_compart * 40
#Total de visualizações:
visualizacao += visualiz_extra
visualizacao = int(visualizacao)
print(f'O alcance do seu anúncio é de aproximadamente {visualizacao} visualizações. ') |
84e3e7e273206db5ddb0576f42fbec467164f1c5 | shaunmulligan/resin-neopixel | /app/leds.py | 1,530 | 3.53125 | 4 | from time import sleep
from neopixel import Adafruit_NeoPixel, Color
# LED strip configuration:
LED_COUNT = 64 # 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 = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
ROW_WIDTH = 8
def setRowColor(strip, row_number, color):
start = 0 + row_number*ROW_WIDTH
end = start + ROW_WIDTH
for i in range(start, end):
strip.setPixelColor(i, color)
strip.show()
def fill_up_to(strip, row, color):
for i in range(row + 1):
setRowColor(strip,i,color)
def empty_array(strip):
for i in range(256):
strip.setPixelColorRGB(i,0,0,0)
strip.show()
# Main program logic follows:
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
led_array = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
# Intialize the library (must be called once before other functions).
led_array.begin()
while True:
color = Color(0, 0, 60)
# setRowColor(led_array,1,color)
# fill_up_to(led_array,0,color)
# sleep(0.1)
fill_up_to(led_array,7,color)
sleep(5)
empty_array(led_array)
sleep(3)
|
669f4bbca09f2d6062be01a30fdfd0f7a0367394 | mckinleyfox/cmpt120fox | /pi.py | 487 | 4.15625 | 4 | #this program is used to approximate the value of pi
import math
def main():
print("n is the number of terms in the pi approximation.")
n = int(input("Enter a value of n: "))
approx = 0.0
signchange = 1.0
for i in range(1, n+1, 2):
approx = approx + signchange * 4.0/i # JA
signchange = -signchange
print("The aprroximate value of pi is: ", approx)
print("The difference between the approximation and real pi is: ", math.pi - approx)
main()
|
5c1a951d38aeeec9b7329a011b8d634cb9137f52 | jorgeromeromg2/Python | /mundo2/ex92.py | 580 | 3.703125 | 4 | from datetime import datetime
relacao = dict()
relacao["Nome"] = str(input('Nome: ')).capitalize()
idade = int(input('Ano de nascimento: '))
relacao["Idade"] = datetime.now().year - idade
relacao["CTPS"] = int(input('Carteira de Trabalho (0 não tem): '))
if relacao["CTPS"] != 0:
relacao["Contratação"] = int(input('Ano de Contratação: '))
relacao["Salário"] = float(input('Salário: '))
relacao["Aposentadora"] = relacao["Idade"] + ((relacao["Contratação"] + 35) - datetime.now().year)
for k, v in relacao.items():
print(f'{"-":>5} {k} tem o valor {v}')
|
f6c98f4637a5dbf25fd4d76119aa0cb93c819e77 | jorgeromeromg2/Python | /mundo2/ex85.py | 670 | 3.84375 | 4 | '''valores = []
par = []
impar = []
for v in range(1, 8):
valores.append(int(input(f'Digite o {v}º valor: ')))
if valores[0] % 2 == 0:
par.append(valores[:])
elif valores[0] % 2 != 0:
impar.append(valores[:])
valores.clear()
print(sorted(par))
print(sorted(impar))'''
numeros = [[], []]
valor = 0
for v in range(1, 8):
valor = int(input(f'Digite o {v}º valor: '))
if valor % 2 == 0:
numeros[0].append(valor)
else:
numeros[1].append(valor)
numeros[0].sort()
numeros[1].sort()
print('==='*30)
print(f'Os números pares digitados são: {numeros[0]}')
print(f'Os números ímpares digitados são: {numeros[1]}') |
6d8ca4a28dfdc8a6a703c8dc8d8652981fe10238 | jorgeromeromg2/Python | /mundo1/ex033.py | 350 | 3.890625 | 4 | reta1 = float(input('Digite a primeira reta: '))
reta2 = float(input('Digite a segunda reta: '))
reta3 = float(input('Digite a terceira reta: '))
if (reta1 + reta2 > reta3) and (reta2 + reta3 > reta1) and (reta1 + reta3 > reta2):
print('Possui condição para ser um triângulo.')
else:
print('Não possui condição para ser um triângulo.') |
4c538d0eccedfa427845be1ca803cdb6cc2ef867 | jorgeromeromg2/Python | /mundo2/ex008_D41.py | 787 | 4.25 | 4 | #--------CATEGORIA NATAÇÃO--------#
print(10 * '--=--')
print('CADASTRO PARA CONFEDERAÇÃO NACIONAL DE NATAÇÃO')
print(10 * '--=--')
nome = str(input('Qual é o seu nome: ')).capitalize()
idade = int(input('Qual é a sua idade: '))
if idade <= 9:
print('{}, você tem {} anos e está cadastrado na categoria MIRIM.'.format(nome, idade))
elif idade <= 14:
print('{}, você tem {} anos e está cadastrado na categoria INFANTIL.'.format(nome, idade))
elif idade <= 19:
print('{}, você tem {} anos e está cadastrado na categoria JUNIOR.'.format(nome, idade))
elif idade <= 20:
print('{}, você tem {} anos e está cadastrado na categoria SENIOR.'.format(nome, idade))
else:
print('{}, você tem {} anos e está cadastrado na categoria MASTER.'.format(nome, idade)) |
fd614fdd36b34645dd4afc125153dc09493841c2 | jorgeromeromg2/Python | /mundo1/ex005.py | 648 | 4.15625 | 4 | #--------SOMA ENTRE NÚMEROS------
#n1 = int(input('Digite o primeiro número: '))
#n2 = int(input('Digite o segundo número: '))
#soma = n1 + n2
#print('A soma entre {} e {} é igual a {}!'.format(n1, n2, soma))
#--------SUCESSOR E ANTECESSOR-----
n = int(input('Digite um número e verifique o sucessor e antecessor:'))
a = n-1
s = n+1
print('Analisando o valor {} podemos perceber que o antecessor é {} e o sucessor é {}.'.format(n, a, s))
#-----OU-----
n = int(input('Digite um número e verifique o sucessor e antecessor:'))
print('Analisando o valor {} podemos perceber que o antecessor é {} e o sucessor é {}.'.format(n, (n-1), (n+1))) |
f26dc0e78afb7d4ca9e79764ee4914b8f523f9b8 | jorgeromeromg2/Python | /mundo2/ex013_D51.py | 437 | 4.0625 | 4 | #-----PROGRESSÃO ARITMÉTICA------
'''num1 = int(input('Digite o primeiro termo da P.A: '))
num3 = int(input('Digite a razão da P.A: '))
for n in range(num1, 10*num3, num3):
print('O termos da P.A são {} '.format(n))'''
primeiro = int(input('Primerio termo: '))
razao = int(input('Razão: '))
decimo = primeiro + (10 - 1) * razao
for c in range(primeiro, decimo + razao, razao):
print('{}'.format(c), end=' » ')
print('FIM') |
457ee2cf1dbd934cab7bf67f8600c895ec9229a0 | jorgeromeromg2/Python | /mundo2/ex88.py | 458 | 3.6875 | 4 | from random import randint
from time import sleep
jogo = []
jogo1 = []
jogadas = int(input('Quantos jogos você quer que eu sorteie? '))
print(3*'-=', f'SORTEANDO {jogadas} NÚMEROS', 3*'-=')
for j in range(1, jogadas+1):
jogo.clear()
jogo1 = [randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60)]
jogo.append(jogo1[:])
jogo1.clear()
print(f'Jogo {j:^1}: {jogo}')
sleep(1)
print('Boa sorte')
|
c53134cddbc37e350cd80a9b8a334a0f1299382e | jorgeromeromg2/Python | /mundo2/ex013_D48.py | 655 | 4.0625 | 4 | #------NUMEROS IMPARES DIVISIVEIS POR 3--------
'''primeiro = int(input('Digite o primeiro número da sequência: '))
ultimo = int(input('Digite o último número da sequência: '))
for c in range(primeiro, ultimo):
if c % 3 == 0 and c % 2 != 0:
print(c)
print('Na contagem de {} à {} os números em tela são impares múltiplos de 3'.format(primeiro, ultimo))'''
soma = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0:
cont += 1 #QUANTIDAE DE VALORES SELECIONADOS
soma += c #SOMATORIO DOS VALORES SELECIONADOS
#print(c, end=' ')
print('A soma de todos os {} valores solicitados é {}'.format(cont, soma)) |
d11deb0a802075340ada466cb8a9af86f764b71d | jorgeromeromg2/Python | /mundo2/ex014_D64.py | 558 | 3.78125 | 4 | cont = n = total = 0
while total < 999:
total = int(input('Digite um número [999 para parar]: '))
if total != 999:
n += total
cont += 1
print('Você digitou {} números e a soma entre eles foi {}'.format(cont, n))
'''
n = cont = soma = 0
n = int(input('Digite um número [999 para parar]: ))
while n != 999:
soma += n
cont += 1
n = int(input('Digite um número [999 para parar]: )) #O FLAG ESTANDO NA ULTIMA LINHA FAZ ELE SAIR DO WHILE
print('Você digitou {} números e a soma entre eles foi {}.'.format(cont, soma))''' |
225121d559a01c2380908f55d70d53357972b619 | jorgeromeromg2/Python | /mundo2/ex014_D60.py | 687 | 4.0625 | 4 | #----FATORIAL-----
'''from math import factorial
fat = int(input('Digite o número e descubra seu fatorial: '))
num1 = factorial(fat)
print('O fatorial de {} é {}'.format(fat, num1))'''
'''n1 = int(input('Digite um número para calcular o fatorial: '))
f = 1
print('Calculando {}! = '.format(n1), end='')
while n1 > 0:
print('{}'.format(n1), end='')
print(' x ' if n1 > 1 else ' = ', end='')
f *= n1
n1 -= 1
print('{}'.format(f))'''
fat = int(input('Digite um número: '))
c = 1
print('Calculando {}! = '.format(fat), end='')
for n in range(fat, 0, -1):
print('{}'.format(n), end='')
print(' x ' if n > 1 else ' = ', end='')
c *= n
print(' {} '.format(c))
|
8bd089a620d46edb2e29106eeecbbcc94c4a46ab | jorgeromeromg2/Python | /mundo1/ex004a.py | 204 | 3.765625 | 4 | n1 = input('Digite algo: ')
print('O que foi digitado é um número? ', n1.isalnum())
print('O que foi digitado é uma string? ', n1.isalpha())
print('O que foi digitado é alfanumérico? ', n1.isalnum()) |
c5eb72c84282a18019f9d280449ffcdbcf0948d1 | Zoooka/Rock-Paper-Scissors- | /rock paper.py | 1,228 | 4.03125 | 4 | import sys
import getpass
# Creates two users, and for users to enter their names
User1 = input("Player one, what is your name? ")
User2 = input("Player two, What is your name? ")
# Counts users wins
User1_wincount = 0
User2_wincount = 0
# Prompts users to enter rock paper scissors etc...
User1_answer = input("%s, do you want to choose rock, paper or scissors? " % User1)
User2_answer = input("%s, do you want to choose rock, paper or scissors? " % User2)
# Compares user ones and user twos inputs and calculates winner
def compare(u1, u2):
if u1 == u2:
return("It's a tie!")
elif u1 == 'rock':
if u2 == 'scissors':
return("Rock wins!")
User1_wincount + 1
else:
return('Paper wins!')
elif u1 == 'scissors':
if u2 == 'paper':
return("Scissors wins!")
else:
return("Rock wins!")
elif u1 == 'paper':
if u2 == 'rock':
return("Paper wins!")
else:
return("Scissors wins!")
else:
return("Invalid input. Don't try and get fancy.")
sys.exit()
# Prints who won to console
print(compare(User1_answer, User2_answer))
# print(User1_wincount, User2_wincount) |
ec7e9176ef54a88a6c1d25b89c599f8d9e419c89 | irische/Intro-to-CS_Python | /HW_3/HW_3_part_1/hw3_part1_files/hw3_part1.py | 3,744 | 3.921875 | 4 | # Qianqian Che (cheq@rpi.edu)
# Purpose: output the table about top 250 ranked female and male names on demand.
# read and access the names and counts
import read_names
import sys
# function to find if a value is in the list and the index and return required values
def table(name,list_name,list_counts):
position=list_name.index(name)
count='%5d'%int(list_counts[position])
percent_top='%7.3f'%(100.*int(count)/list_counts[0])
percent_sum='%7.3f'%(100.*int(count)/sum(list_counts))
rank='%3d'%int(position+1)
name=name.ljust(11)
return '%s %s %s %s %s'%(rank,name,count,percent_top,percent_sum)
# function to print out required table of rank, name, count, and percentage information
def table_(name,list_name,list_counts):
if name in list_name:
position=list_name.index(name)
if position==0:
name_1=name
name_2=list_name[position+1]
name_3=list_name[position+2]
print table(name_1,list_name,list_counts)
print table(name_2,list_name,list_counts)
print table(name_3,list_name,list_counts)
elif position==1:
name_1=name
name_2=list_name[position+1]
name_3=list_name[position+2]
name_4=list_name[position-1]
print table(name_4,list_names,list_counts)
print table(name_1,list_names,list_counts)
print table(name_2,list_names,list_counts)
print table(name_3,list_names,list_counts)
elif position==249:
name_1=name
name_2=list_name[position-1]
name_3=list_name[position-2]
print table(name_3,list_name,list_counts)
print table(name_2,list_name,list_counts)
print table(name_1,list_name,list_counts)
elif position==248:
name_1=name
name_2=list_name[position+1]
name_3=list_name[position-1]
name_4=list_name[position-2]
print table(name_4,list_name,list_counts)
print table(name_3,list_name,list_counts)
print table(name_1,list_name,list_counts)
print table(name_2,list_name,list_counts)
else:
name_1=list_name[position-2]
name_2=list_name[position-1]
name_3=list_name[position]
name_4=list_name[position+1]
name_5=list_name[position+2]
print table(name_1,list_name,list_counts)
print table(name_2,list_name,list_counts)
print table(name_3,list_name,list_counts)
print table(name_4,list_name,list_counts)
print table(name_5,list_name,list_counts)
else:
print '%s is not in top 250.'%name
# read in year and names from the user and call the functions above to output the table required.
read_names.read_from_file('top_names_1880_to_2014.txt')
year=raw_input('Enter the year to check => ')
print year
if int(year)<1880 or int(year)>2014:
print 'Year must be at least 1880 and at most 2014'
sys.exit()
print
female_name=raw_input('Enter a female name => ')
print female_name
print 'Data about female names'
(female_names,female_counts)=read_names.top_in_year(int(year), 'f')
print 'Top ranked name %s'%female_names[0]
print '250th ranked name %s'%female_names[249]
list_250_female=female_names[0:250]
female=table_(female_name,female_names,female_counts)
print
male_name=raw_input('Enter a male name => ')
print male_name
print 'Data about male names'
(male_names,male_counts)=read_names.top_in_year(int(year), 'M')
print 'Top ranked name %s'%male_names[0]
print '250th ranked name %s'%male_names[249]
list_250_male=male_names[0:250]
male=table_(male_name,male_names,male_counts)
|
d4fd84f9634db9e9db97e347360b5da2bab01b09 | irische/Intro-to-CS_Python | /HW_8/hw9_part1.py | 1,898 | 3.84375 | 4 | """Author: <Boliang Yang and yangb5@rpi.edu>
Purpose: This program reads a yelp file about the businesses, counts all
categories that co-occur with the given category and prints those
categories with counts greater than the given cutoff in sorted order.
"""
## all imports
import json
## main body of the program
if __name__ == "__main__":
category_name=raw_input('Enter a category ==> ')
print category_name
cutoff=int(raw_input('Cutoff for displaying categories => '))
print cutoff
business_list=[]
category_all=set()
for line in open('businesses.json'):
business = json.loads(line)
business_list.append(business)
for category in business['categories']:
category_all.add(category)
categories_dictionary={}
for business_name in business_list:
if category_name in business_name['categories']:
for category in business_name['categories']:
if category_name!=category:
if category not in categories_dictionary.keys():
categories_dictionary[category]=0
categories_dictionary[category]+=1
output_list=[]
for category in categories_dictionary.keys():
if categories_dictionary[category]>=cutoff:
output_list.append((category,categories_dictionary[category]))
if category_name not in category_all:
print 'Searched category is not found'
elif len(output_list)==0:
print 'None above the cutoff'
else:
print 'Categories co-occurring with %s:' %category_name
output_list.sort()
for output in output_list:
string='%s: %d' %(output[0],output[1])
space=' '*(30-len(output[0]))
string=space+string
print string
|
5bad1293e9456a4baf7c4b63c1edac3662d1f18d | irische/Intro-to-CS_Python | /HW_4/hw4_part3.py | 1,473 | 3.640625 | 4 | '''This program reads in the death statistics for areas of NYS from 2003 to 2013
and ouput the trend in a single line.
'''
import hw4_util
## function definition to output the trend of death statistics.
def read_deaths(county,data):
data_=data[:]
sum=0
for r in range(len(data_)):
sum+=data_[r]
average=sum/11
high=average*105/100
low=average*95/100
data__=''
for d in range(len(data_)):
if float(data_[d])>=high:
data_[d]='+'
data__+=data_[d]
elif float(data_[d])<=low:
data_[d]='-'
data__+=data_[d]
else:
data_[d]='='
data__+=data_[d]
print county.ljust(15)+data__
## main body of program
if __name__=="__main__":
county_1=raw_input('First county => ')
print county_1
data_1 = hw4_util.read_deaths(county_1)
county_2=raw_input('Second county => ')
print county_2
data_2= hw4_util.read_deaths(county_2)
print
## conditional statements for different cases
if data_1!=[] and data_2!=[]:
print ' '*15+'2013'+' '*3+'2003'
read_deaths(county_1,data_1)
read_deaths(county_2,data_2)
elif data_1!=[] and data_2==[]:
print 'I could not find county %s'%county_2
elif data_1==[] and data_2!=[]:
print 'I could not find county %s'%county_1
else:
print 'I could not find county %s'%county_1
print 'I could not find county %s'%county_2 |
7354794ac710eeb677d5c2d163c2c74f60e78d22 | nindanindra/meerkpy | /chapter2.py | 1,715 | 4.0625 | 4 | users={"Anna":{ "bbm":2.0, "doraemon":4.325}, "Joe":{"ff7":4.125, "doraemon":3.275}, "Smith":{"ff7":1.25, "bbm":2.450, }}
def manhattan(rating1,rating2):
distance=0
for key in rating1:
if key in rating2:
distance+=abs(rating1[key] - rating2[key])
return distance
def minkowski(rating1, rating2, r):
distance=0
commonRatings=False
# calculate difference
for key in rating1:
if key in rating2:
print 'in the loop'
distance+=pow((abs(rating1[key] - rating2[key])),r)
commonRatings= True
if commonRatings:
print 'true'
return pow(distance, 1/r)
else:
print 'false'
return 0
def computeNearestNeighbour(username,users):
distances=[]
for user in users:
if user != username:
distance = minkowski(users[user],users[username],2)
distances.append((distance, user))
distances.sort()
return distances
def recommend(username, users):
# get the name of the nearest neighbour
nearestNeighbour = computeNearestNeighbour(username,users)[0][1]
# computeNearestNeighbour return pair of tuple, we would like to pick the first
# one which will return the pair of our username
# if we pick [0], it will return the tuple
# we want the name, which locate in the second index of our tuple [0]
# therefore we increment the index into [1]
recommendations = []
# get the list of their movies
nearestNeighbourMov = users[nearestNeighbour]
userMov = users[username]
# get the recommendations
for film in nearestNeighbourMov:
if not film in userMov:
recommendations.append((film, nearestNeighbourMov[film], nearestNeighbour))
return sorted(recommendations, key=lambda filmTuple: filmTuple[1], reverse = True)
|
3d93e7ba5742d17e856ec95538b1bfaaca906d79 | Madhuparna-Das/Madhuparna_Das | /extension.py | 330 | 3.890625 | 4 | file_name=input("enter the file name").casefold()
b=file_name.split('.')
y=b[1]
if(y=='py'):
print("file extension is python")
elif(y=='java'):
print("file extension is java")
elif(y=='c'):
print("file extension is C")
elif(y=='cpp'):
print("file extension is c++")
else:
print("please enter valid file name")
|
d1efce2817a84b01f03ffd6510e19e70177387f9 | elirud/kattis | /problems/sodasurpler.py | 257 | 3.5625 | 4 | i = dict(zip(['start', 'found', 'needed'], map(int, input().split())))
bottles = i['start'] + i['found']
sodas = 0
while bottles >= i['needed']:
sodas += bottles // i['needed']
bottles = bottles // i['needed'] + bottles % i['needed']
print(sodas)
|
e8ba6c87fc0660ecec74f67dff3ab8a4b92316f8 | jptafe/ictprg434_435_python_ex | /wk4/wk4_input.py | 989 | 3.609375 | 4 | #!/usr/bin/python
# TAKE only 1 parameter from the CLI
# calculate and print the CLI parameter + 5
# NOTE: Attempt this WITHOUT an if statement
# use try: except: block instead
import sys
try:
newnum = int(sys.argv[1]) + 4
if(newnum = 999):
raise Exception('blah')
except ValueError:
print('err')
sys.exit(1)
except IndexError:
newnum = 99
print(newnum)
sys.exit(0)
import sys
try:
newvar = int(sys.argv[1]) + 4
except:
print('err: arg error')
sys.exit(1)
print(newvar)
sys.exit(0)
def GetInput():
return input('give me a number: ')
def EvalAsNum(anum = 'a'):
if anum.isdigit():
return True
else:
return False
numb = str('abca')
#while EvalAsNum(numb) == False:
# numb = GetInput()
try:
if int(numb) > 5:
print('larger than 5')
else:
print('smaller or equal to 5')
except ValueError:
print('I give up!!!')
|
6c3d96d82e199378ef5cb8b5060a52f4ad92da07 | ArjunSubramonian/CrazyEights | /util/card.py | 692 | 3.6875 | 4 | from enum import Enum
class Rank(Enum):
JOKER = 14
KING = 13
QUEEN = 12
JACK = 11
TEN = 10
NINE = 9
EIGHT = 8
SEVEN = 7
SIX = 6
FIVE = 5
FOUR = 4
THREE = 3
DEUCE = 2
ACE = 1
class Suit(Enum):
CLUBS = 1
DIAMONDS = 2
HEARTS = 3
SPADES = 4
class Color(Enum):
BLACK = 1
RED = 2
class Card:
def __init__(self, rank, suit, color, alt_value=None):
self.rank = rank
if alt_value:
self.value = alt_value
else:
self.value = self.rank
self.suit = suit
self.color = color
def __str__(self):
return self.rank.name + ' OF ' + self.suit.name |
0b1c100231c6dbe5d970655a92f4baed0cbe1221 | firoj1705/git_Python | /V2-4.py | 1,745 | 4.3125 | 4 |
'''
1. PRINT FUNCTION IN PYTHON:
print('hello', 'welcome')
print('to', 'python', 'class')
#here by default it will take space between two values and new line between two print function
print('hello', 'welcome', end=' ')
print('to', 'python', 'class')
# here we can change end as per our requirement, by addind end=' '
print('hello', 'welcome', end=' ')
print('to', 'python', 'class', sep=',')
# here you can change sep as per our requirement by writing it. By default sep as SPACE is present.
2. KEYWORDS IN PYTHON: RESERVED WORDS
import keyword
print(keyword.kwlist) #you will get list of keyword in Python
print(len(keyword.kwlist))
print(dir(keyword.kwlist))
print(len(dir(keyword.kwlist)))
3. BASIC CONCEPTS IN PYTHON:
A. INDEXING:
+indexing: strats from 0
-indexing: starts from -1
0 1 2 3 4 5
s= 'P y t h o n'
-6-5-4-3-2-1
B. HASHING:
s='Pyhton'
print(s[0])
print(s[-6])
print(s[4])
print(s[7])
C. SLICING:
s='Python'
print(s[0:4])
print(s[3:])
print(s[:])
print(s[:-3])
print(s[5:4])
D. STRIDING/STEPPING:
s='Python'
print(s[0:5:2])
print(s[0:7:3])
print(s[5:0:-2])
print(s[::-1])
#E. MEMBERSHIP:
s='Python'
print('o' in s)
print('p' in s)
#F. CONCATENATION:
s1='Hi'
s2='Hello'
s3='303'
print(s1+s2)
print(s1+' '+s2)
print(s1+s2+s3)
print(s1+s2+100) # error will occur, As datatype should be same.
#G. REPLICATION:
s1='Firoj'
print(s1*3)
print(s1*s1) # multiplier should be integer
#H. TYPECASTING:
s='100'
print(int(s))
n=200
s1=str(n)
print(s1)
s='Hello'
print(list(s))
#I. CHARACTER TO ASCII NUMBER:
print(ord('a'))
print(ord('D'))
#J. ASCII TO CHARACTER NUMBER:
print(chr(97))
print(chr(22))
'''
|
bf66f636f476c0610625d54d5ebb6ec4c0111b05 | firoj1705/git_Python | /V5.py | 1,003 | 4.0625 | 4 |
'''
1. INPUTS IN PYTHON:
s=input('Enter String: ')
print(s)
n=int(input("Enter Number: "))
print(n)
f=float(input('Enter Floating point number: '))
print(f)
2. LOOPS IN PYTHON:
A. if-elif-else ladder:
Single if statement has multiple elif statements.
n%5=Buzz
n%3=Fizz
n%3,5=FizzBuzz
n=int(input("Enter Number: "))
if n%3==0 and n%5==0:
print('FizzBuzz')
elif n%3==0:
print('Fizz')
elif n%5==0:
print('Buzz')
else:
print('Number is not divisible by 3,5')
B. Range Function in Python:
a. range(10):
b. range(1,10):
c. range(0,10,2):
d. range(10,2,-1):
for i in range(10):
print(i)
for i in range(20,0,-3):
print(i)
C. for loop in Pyhton:
for i in range(1,101):
if i%3==0 and i%5==0:
print('FizzBuzz')
elif i%3==0:
print('Buzz')
elif i%5==0:
print('Fizz')
else:
print(i, 'is not divisible by 3,5')
'''
for i in range(1,6):
print(" "*(5-i)+'*'*i+"*"*(i-1))
|
b18609cde09810784b1c2ce40381ee7ab7ee6d43 | samaro19/Random_Code | /decode_ceaser.py | 717 | 3.859375 | 4 | dict = {
-2: '!',
-1: '?',
0: ' ',
1: 'a',
2: 'b',
3: 'c',
4: 'd',
5: 'e',
6: 'f',
7: 'g',
8: 'h',
9: 'i',
10: 'j',
11: 'k',
12: 'l',
13: 'm',
14: 'n',
15: 'o',
16: 'p',
17: 'q',
18: 'r',
19: 's',
20: 't',
21: 'u',
22: 'v',
23: 'w',
24: 'x',
25: 'y',
26: 'z',
}
message = input("input text to decode: ")
three_back = []
decoded = []
if message != '':
message = message.split(", ")
print(message)
for msg1 in message:
three_back.append(int(msg1) - 3)
print(three_back)
for msg in three_back:
print(dict[int(msg)])
decoded.append(dict[int(msg)])
print(" ")
print(''.join(decoded))
|
54202c7d5234ff5bad17419c664f9d479615cef5 | samaro19/Random_Code | /l_system_hilbert_curve.py | 510 | 3.96875 | 4 | import turtle
turtle.penup()
turtle.sety(00)
turtle.pendown()
turtle.hideturtle()
turtle.tracer(20, 1)
def str_rep(x):
y = ""
for xs in x:
if xs == "A":
y += "BF+AFA+FB-"
elif xs == "B":
y += "AF-BFB-FA+"
else:
y += xs
return y
def iterate(x, t):
for i in range(t):
x = str_rep(x)
return x
g = iterate("A",10)
for gs in g:
if gs == "F":
turtle.forward(1)
elif gs == "-":
turtle.left(90)
elif gs == "+":
turtle.right(90)
print(g)
turtle.exitonclick()
|
38932f838745fff4b086d05c8b7b00802133bd22 | samaro19/Random_Code | /polyalphabetic_cypher 1.0.py | 818 | 3.78125 | 4 | ALPHABET = {
'!': -2,
'?': -1,
' ': 0,
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9,
'j': 10,
'k': 11,
'l': 12,
'm': 13,
'n': 14,
'o': 15,
'p': 16,
'q': 17,
'r': 18,
's': 19,
't': 20,
'u': 21,
'v': 22,
'w': 23,
'x': 24,
'y': 25,
'z': 26,
}
keyinp = input("Key word: ")
leng = len(keyinp)
key = []
for let in keyinp:
lowerCasekey = let.lower()
key.append(ALPHABET[lowerCasekey])
word = input("Word: ")
enc = []
var = 0
if word != '':
word.split()
for msg in word:
lowerCase = msg.lower()
print(ALPHABET[lowerCase])
enc.append(int(ALPHABET[lowerCase]) + int(key[var]))
var = var + 1
if var > leng:
var = 0
enc = str(enc)
print(" ")
print(enc)
|
13ca3b030032cf5763a584614ee169d436145fb9 | TroyeWlb/testProjects | /ifelse.py | 1,207 | 3.8125 | 4 | # price = float(input("价格"))
# weight = float(input("重量"))
# total = price * weight
# print("合计 %.02f元 " % total)
# name = input("name")
# print("我的名字叫 %s,请多多关照" % name)
# student_no = int(input("No."))
# print("我的学号是 %09d" % student_no)
# scale = float(input("age"))
# if scale >= 18:
# print("welcome")
# else:
# print("go away")
# print(1+2)
# age = int(input("age"))
# if age <= 18:
# print("请叫家长")
# if age == 17:
# print("请明年再来")
# elif age == 16:
# print("请后年再来")
# elif age <= 15:
# print("回家去吧")
# else:
# hight = int(input("请输入身高 "))
# if hight > 160:
# print("来吧")
# else:
# print("你太高了,有 %d 公分高" % hight)
is_employee = True
if not is_employee:
print("go away")
else:
nummber = input("No. ")
if len(nummber) == 4:
if nummber[0] == "1":
print("请去一楼")
elif nummber[0] == "2":
print("请去二楼")
elif nummber[0] == "3":
print("请去三楼")
else:
print("go away")
else:
print("go away !")
|
4c7fede5166a8852646ab41c41033e4d40be3c13 | mohanbabu2706/testrepo | /2020/october/1/2-Oct/log2 and log10.py | 255 | 3.609375 | 4 | #importing "math" for mathematical operations
import math
#returnig log2 of 16
print("The value of log2 of 16 is:",end="")
print(math.log2(16))
#returning the log10 of 10000
print("The value of log10 of 10000 is:",end="")
print(math.log10(10000))
|
655468222209a0a6151c576027827d12c1082ad6 | mohanbabu2706/testrepo | /2020/october/1/1-Oct/reverse string.py | 194 | 4.09375 | 4 | def string_reverse(str1):
rstr = ''
index = len(str1)
while index>0:
rstr1 += str1[index-1]
index = index-1
return str1
print(string_reverse('1234abcd'))
|
9d72e56c01ac55832f7caa24afb7d32e39dde8b3 | gc2321/Coursera_PC_1 | /week2_2048_full.py | 6,987 | 3.625 | 4 | """
Clone of 2048 game.
"""
import poc_2048_gui, random
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0), DOWN: (-1, 0), LEFT: (0, 1), RIGHT: (0, -1)}
def slide(line, val):
"""
Function that slide tiles to the front
"""
_original_list = line
_new_list = []
# slide all non-zero value to the front
if val == 1:
for item in _original_list:
if item!=0:
_new_list.append(item)
for item in _original_list:
if item==0:
_new_list.append(item)
else:
for item in _original_list:
if item==0:
_new_list.append(item)
for item in _original_list:
if item!=0:
_new_list.append(item)
# return new list
return _new_list
def combine(line, val):
"""
Function that combine adjust value if they are the same
"""
_original_list = line
_new_list = _original_list
# reverse list val !=1
if val!=1:
_original_list= _original_list[::-1]
# find paired tiles
item = 0
while item <=(len(_original_list)-1):
if item<=(len(_original_list)-2):
if _original_list[item]==_original_list[item+1]:
_new_list[item] = _original_list[item]*2
_new_list[item+1] = 0
item += 2
else:
_new_list[item] = _original_list[item]
item +=1
else:
_new_list[item] = _original_list[item]
item +=1
if val!=1:
_new_list= _new_list[::-1]
return _new_list
def merge(line, val):
"""
Helper function that merges a single row or column in 2048
"""
_original_list = line
_new_list = []
_new_list = slide(_original_list, val)
_new_list = combine(_new_list, val)
_new_list = slide(_new_list, val)
# return new list
return _new_list
class TwentyFortyEight:
"""
Class to run the game logic.
"""
def __init__(self, grid_height, grid_width):
self._grid_height = grid_height
self._grid_width = grid_width
self._grid = [[row + col for col in range(self._grid_width)]
for row in range(self._grid_height)]
# make every cell = 0
for row in range(self._grid_height):
for column in range(self._grid_width):
self._grid[row][column] = 0
def reset(self):
"""
Reset the game so the grid is empty except for two
initial tiles.
"""
for row in range(self._grid_height):
for column in range(self._grid_width):
self._grid[row][column] = 0
fill_cell = 0
while (fill_cell <2):
self.new_tile()
fill_cell +=1
def __str__(self):
"""
Return a string representation of the grid for debugging.
"""
#return str(self._grid)
return str([x for x in self._grid]).replace("],", "]\n")
def get_grid_height(self):
"""
Get the height of the board.
"""
return self._grid_height
def get_grid_width(self):
"""
Get the width of the board.
"""
return self._grid_width
def move(self, direction):
"""
Move all tiles in the given direction and add
a new tile if any tiles moved.
"""
# copy grid before move
_grid_before = [[row + col for col in range(self._grid_width)]
for row in range(self._grid_height)]
for row in range(self._grid_height):
for col in range(self._grid_width):
_grid_before[row][col] = 0
_grid_before[row][col] = self._grid[row][col]
_direction = direction
self._direction = OFFSETS[_direction]
if (self._direction[1]==1 or self._direction[1]==-1):
for row in range(self._grid_height):
_old_list = []
for col in range(self._grid_width):
_old_list.append(self._grid[row][col])
if (self._direction[1]==-1):
_new_list = merge(_old_list, 2)
else:
_new_list = merge(_old_list, 1)
for col in range(self._grid_width):
self._grid[row][col] = _new_list[col]
else:
for col in range(self._grid_width):
_old_list = []
for row in range(self._grid_height):
_old_list.append(self._grid[row][col])
if (self._direction[0]==-1):
_new_list = merge(_old_list, 2)
else:
_new_list = merge(_old_list, 1)
for row in range(self._grid_height):
self._grid[row][col] = _new_list[row]
# compare grid before and after
_move_happen = 0
for row in range(self._grid_height):
for col in range(self._grid_width):
if (_grid_before[row][col] != self._grid[row][col]):
_move_happen +=1
print "Move happen"+str(_move_happen)
# add new tile if there is a empty cell and move happened
_empty = 0
for row in range(self._grid_height):
for col in range(self._grid_width):
if (self._grid[row][col]==0):
_empty += 1
break
if(_empty!=0 and _move_happen!=0):
self.new_tile()
def new_tile(self):
"""
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time.
"""
fill_cell = 0
while (fill_cell <1):
row = random.randrange(self._grid_height)
col = random.randrange(self._grid_width)
if (self._grid[row][col]==0):
val = random.choice([2,2,2,2,2,2,2,2,2,4])
self._grid[row][col] = val
fill_cell +=1
def set_tile(self, row, col, value):
"""
Set the tile at position row, col to have the given value.
"""
self._grid[row][col]=value
def get_tile(self, row, col):
"""
Return the value of the tile at position row, col.
"""
return self._grid[row][col]
poc_2048_gui.run_gui(TwentyFortyEight(4, 5))
|
3303ed1dceb6078ee7f6770b67dcf3fefd24a99b | saedmansour/University-Code | /Artificial Intelligence/final_competition/myGraph.py | 6,492 | 3.734375 | 4 | #################################
## ##
## Graph Search Algorithms ##
## ##
#################################
# This file contains the basic definition of a graph node, and the basic
# generic graph search on which all others are based.
# The classes defined here are:
# - Node
# - GraphSearch
# - Graph Search
# - Breadth-First Graph Search
# - Depth-First Graph Search
# - Iterative Depening Search
from algorithm import SearchAlgorithm
from utils import *
from utils import infinity
import time
##########################
## Graph Definition ##
##########################
# These are used for graphs in which we know there are no two routes to the
# same node.
class Node:
'''
A node in a search tree used by the various graph search algorithms.
Contains a pointer to the parent (the node that this is a successor of) and
to the actual state for this node. Note that if a state is arrived at by
two paths, then there are two nodes with the same state.
Also includes the action that got us to this state, and the total path_cost
(also known as g) to reach the node.
Other functions may add an f and h value; see BestFirstGraphSearch and
AStar for an explanation of how the f and h values are handled.
'''
def __init__(self, state, parent=None, action=None, path_cost=0):
'''
Create a search tree Node, derived from a parent by an action.
'''
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.depth = 0
if parent:
self.depth = parent.depth + 1
def __cmp__(self, other):
'''
The comparison method must be implemented to ensure deterministic results.
@return: Negative if self < other, zero if self == other and strictly
positive if self > other.
'''
return cmp(self.getPathActions(), other.getPathActions())
def __hash__(self):
'''
The hash method must be implemented for states to be inserted into sets
and dictionaries.
@return: The hash value of the state.
'''
return hash(tuple(self.getPathActions()))
def __str__(self):
return "<Node state=%s cost=%s>" % (self.state, self.path_cost)
def __repr__(self):
return str(self)
def getPath(self):
'''
Returns a list of nodes from the root to this node.
'''
node = self
path = []
while node:
path.append(node)
node = node.parent
path.reverse()
return path
def getPathActions(self):
'''
Returns a list of actions
'''
node_path = self.getPath()
actions = [node.action for node in node_path]
return actions[1:] # First node has no action.
def expand(self):
'''
Return a list of nodes reachable from this node.
'''
def path_cost(action):
return self.path_cost + action.cost
successors = self.state.getSuccessors()
return [Node(next, self, act, path_cost(act))
for (act, next) in successors.items()]
#################################
## Graph Search Algorithms ##
#################################
# This is the base implementation of a generic graph search.
class GraphSearch (SearchAlgorithm):
'''
Implementation of a simple generic graph search algorithm for the Problem.
It takes a generator for a container during construction, which controls the
order in which open states are handled (see documentation in __init____).
It may also take a maximum depth at which to stop, if needed.
'''
def __init__(self, container_generator,time_limit=infinity, max_depth=infinity):
'''
Constructs the graph search with a generator for the container to use
for handling the open states (states that are in the open list).
The generator may be a class type, or a function that is expected to
create an empty container.
This may be used to effect the order in which to address the states,
such as a stack for DFS, a queue for BFS, or a priority queue for A*.
Optionally, a maximum depth may be provided at which to stop looking
for the goal state.
'''
self.container_generator = container_generator
self.max_depth = max_depth
self.limit=time_limit
#<new>SAED: timesToRun is for A* with limited steps.</new>
def find(self, problem_state, heuristic=None, timesToRun=infinity):
'''
Performs a full graph search, expanding the nodes on the fringe into
the queue given at construction time, and then goes through those nodes
at the order of the queue.
If a maximal depth was provided at construction, the search will not
pursue nodes that are more than that depth away in distance from the
initial state.
@param problem_state: The initial state to start the search from.
@param heuristic: Ignored.
'''
open_states = self.container_generator()
closed_states = {}
open_states.append(Node(problem_state))
#<new>
safty_time=0.3
if(len(problem_state.robots)==5):
safty_time = 0.7
if(len(problem_state.robots)>5):
safty_time=2.5
i = 0
start=time.clock()
#</new>
while open_states and len(open_states) > 0:
node = open_states.pop()
if(self.limit -(time.clock()-start) <= safty_time ):
return -1
#<new>
if i >= timesToRun:
return (0,node.getPathActions(),node.state) #current state to continue from
i = i + 1
#</new>
if node.depth > self.max_depth:
continue
if node.state.isGoal():
#print node.state
return node.getPathActions()
if (node.state not in closed_states) or (node.path_cost < closed_states[node.state]):
closed_states[node.state] = node.path_cost
open_states.extend(node.expand())
#print node.state
return None
|
288f226242b46fc371d12df7f9dcfb7166f6d46b | whg/DfPaI | /week3/examples/exception-example.py | 108 | 3.640625 | 4 | text = input()
try:
number = int(text)
print(number + 1)
except:
print("that's not a number!")
|
c7eebd9b9319084b280308ea931083fba6a4f222 | chorton2227/dailyprogrammer | /challenge_86/intermediate/program.py | 601 | 3.734375 | 4 | import sys
import math
from datetime import date
if len(sys.argv)==1:
print 'Enter arguments'
exit(0)
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
day = int(sys.argv[1])
month = int(sys.argv[2])
year = sys.argv[3]
T = int(year[2:])
if T & 1:
T += 11
T /= 2
if T & 1:
T += 11
T = 7 - (T % 7)
cent = int(year[:-2]) + 1
anchor = ((5 * cent + ((cent - 1) / 4)) % 7 + 4) % 7
doomsday = (anchor + T) % 7
year = int(year)
search_date = date(year, month, day)
doomsday_date = date(year, 4, 4)
print days[(doomsday + (search_date - doomsday_date).days) % 7] |
675ab06bd6f1512e00daa95ab82697de8d3a6f08 | m-m-adams/ChallengeServer | /Solutions/ChallengeClient.py | 3,125 | 3.5625 | 4 | import socket
import time
import select
###########################################################
# Class declarations
###########################################################
###########################################################
# Challenge Interface
# This class is a wrapper for socket functions to make
# them more friendly to use in this context. Has specific
# functions select_level and submit_answer for this
# challenge, as well as implementing friendlier send and
# receives, reset, and exit for internal use in the class.
class challengeinterface(object):
#setup the socket to connect to the challenge
#This function has default arguments
def __init__(self,address,port):
sock=socket.socket()
self.address=address
self.port=port
self.sock=sock
def start(self):
self.sock.connect((self.address, self.port))
return self.receive()
#accept a level and a challenge socket as
#input, select the level and return its text
def select_level(self,level):
self.transmit(level)
ChallengeText=self.receive()
return ChallengeText
#If it's correct you get a flag
#if it's incorrect you get a new challenge
#in some challenges, on submitting a correct
#answer you immediately get a new challenge,
#which will be stored in result
def submit_answer(self,solution):
self.transmit(solution)
result=''
while result=='':
result=self.receive()
return result
#resets the socket and restarts the connection
#shouldn't be needed but implemented for robustness
def reset(self):
self.exit()
sock=socket.socket()
sock.connect((self.address,self.port))
self.sock=sock
#generic socket encode and send
def transmit(self,submission):
return self.sock.send(str(submission).encode())
# socket receive and decode
# checks that the socket has data on it, and if so reads
# repeats until the socket has no more data
# 0.15 second wait each loop accounts for latency on the
# server side - it's an AWS t2.nano instance......
# default to receiving until it receives 'END MESSAGE\n', as sent by the server's communications.py
def receive(self, terminator='END MESSAGE\n'):
do_read = False
receiveddata=''
while not receiveddata.endswith(terminator):
try:
# select.select will return true if there is data on the socket
# this prevents the recv function from blocking
r, _, _ = select.select([self.sock], [], [],0.15)
do_read = bool(r)
except socket.error:
pass
if do_read:
data = self.sock.recv(1024).decode()
receiveddata+=data
return receiveddata.replace('END MESSAGE\n','')
#generic socket close
def exit(self):
self.sock.close()
#end of challenge interface class
#############################################################
|
6739e2d0bbde7dd5b96001abf6c3e775c765acb2 | BMHArchives/ProjectEuler | /Problem_9/Problem_9.py | 605 | 3.6875 | 4 | import numpy as np
import math
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
def FindAnswer():
sum = 1000
numbers = []
range_a = round_up(sum/3, -2),
range_a = int(range_a[0])
range_b = int(sum/2)
for a in range(1,range_a):
for b in range(1, range_b):
c = sum - a-b
if((a*a) + (b*b) == (c*c)):
numbers.append(a)
numbers.append(b)
numbers.append(c)
return numbers
print("Answer is: {} ".format(np.prod(FindAnswer())))
|
c5db4886b9e216f7da109bcfdd190a2267d7258b | BMHArchives/ProjectEuler | /Problem_1/Problem_1.py | 1,128 | 4.21875 | 4 | # Multiples of 3 and 5
#---------------------
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
numberCount = 1000 # Use this number to find all multiples under the numberCount
total = 0 # summerize the total count of multiples under 1000
# loop between 1 and 1000
for count in range(1,numberCount):
if count != 0: # can't divide by 0
# if the % value is equal to 0 for 3 or 5, then add it to the total.
if (count % 3) == 0 or (count % 5) == 0:
total += count
#def FindAllMultiplesOfTragetNumber(TargetNumber):
# sumTotal = 0
# for a in range(1,numberCount):
# if(a % TargetNumber) == 0:
# sumTotal += a
# return sumTotal
# We're using 3, 5 and 15 here because 15 is the lowest common denominator between 3 and 5, so we will add 3 + 5 to 8 and then subtract from 15 to get the value.
#print(FindAllMultiplesOfTragetNumber(3) + FindAllMultiplesOfTragetNumber(5) - FindAllMultiplesOfTragetNumber(15))
print("Answer: {}".format(total))
|
84fa0e7c67f83e895ab25832db97d086807a4689 | luturol/learning-python | /snake-game/app.py | 5,442 | 3.546875 | 4 | import os
from msvcrt import getch
class SnakeGame(object):
screen = None
def __init__(self, rows_count, column_count):
self.screen = self.initialize_screen(rows_count, column_count)
self.collided = False
def initialize_screen(self, rows_count, column_count):
#creates the 2D list with 0 in all values
screen = [[0 for x in range(column_count)] for y in range(rows_count)]
#get the rows
for row in range(len(screen)):
if row == 0 or row == len(screen) - 1:
screen[row] = self.add_same_value_entire_list(screen[row], 1)
else:
for column in range(len(screen[row])):
if column == 0 or column == len(screen[row]) - 1:
screen[row][column] = 1
return screen
def add_same_value_entire_list(self, list, value):
populatedList = [value for i in range(len(list))]
return populatedList
def print_screen(self):
screen_text = ''
for row in self.screen:
for column in row:
screen_text = screen_text + self.translated_value(column)
screen_text = screen_text + '\n'
return screen_text
def translated_value(self, value):
if value == 1:
return '#'
elif value == 2:
return '*'
elif value == -1: #snake body
return 'O'
elif value == -2: #moving left snake head left <----
return '<'
elif value == -3: #moving right snake head right ---->
return '>'
elif value == -4: #moving down
return 'V'
elif value == -5: #moving up
return '^'
else:
return ' '
def play(self):
player = Player()
key_pressed = 9999
self.add_player_to_screen(player)
while(self.defeated() is not True and key_pressed != 27):
self.clear()
print(self.print_screen())
key_pressed = self.read_key()
player.move(self.translate_key(key_pressed))
self.add_player_to_screen(player)
def read_key(self):
return ord(getch())
def add_player_to_screen(self, player):
print(player.location_x)
print(player.location_y)
if(player.position_cordination == 'E'):
self.screen[player.location_x][player.location_y - 1] = 0
elif (player.position_cordination == 'W'):
self.screen[player.location_x][player.location_y + 1] = 0
elif (player.position_cordination == 'N'):
self.screen[player.location_x + 1][player.location_y] = 0
elif (player.position_cordination == 'S'):
self.screen[player.location_x - 1][player.location_y] = 0
if(self.screen[player.location_x][player.location_y] == 0):
self.screen[player.location_x][player.location_y] = player.body
elif(self.screen[player.location_x][player.location_y] < 0):
self.collided = True
def translate_key(self, key):
print (key)
if (key == 224):
key = ord(getch())
print(key)
if (key == 72):
return 'N'
elif (key == 80):
return 'S'
elif (key == 75):
return 'W'
elif (key == 77):
return 'E'
else:
pass
def defeated(self):
return self.collided
def clear(self):
os.system('cls' if os.name=='nt' else 'clear')
class Player(object):
def __init__(self):
self.nodes_size = 1
self.position_cordination = 'E'
self.last_cordination = 'E'
self.location_x = 4
self.location_y = 4
self.body = -3
def draw(self):
body = ''
for index in range(self.nodes_size):
if(index == 0 and self.position_cordination == 'E'):
body = '>'
elif(index == 0 and self.position_cordination == 'W'):
body = '<'
elif(index == 0 and self.position_cordination == 'N'):
body = '^'
elif(index == 0 and self.position_cordination == 'S'):
body = 'V'
else:
body += '-'
return body
def move(self, cordination):
print("Cordinations x = " + str(self.location_x) + " y = " + str(self.location_y))
if (self.position_cordination != 'S' and cordination == 'N'):
self.location_x -= 1
self.body = -5
elif (self.position_cordination != 'N' and cordination == 'S'):
self.location_x +=1
self.body = -4
elif (self.position_cordination != 'W' and cordination == 'E'):
self.location_y += 1
self.body = -3
elif (self.position_cordination != 'E' and cordination == 'W'):
self.location_y -= 1
self.body = -2
else:
pass
self.position_cordination = cordination
print("Cordinations x = " + str(self.location_x) + " y = " + str(self.location_y))
snake = SnakeGame(32, 32)
snake.play() |
c0d728b393c1b9184357b51442f0f3ee96e0db3d | edvalvitor/projetos | /python/media2.py | 1,215 | 4.15625 | 4 | #Programa para calcular a média e quanto falta para passar
#Centro Universitário Tiradentes
#Edval Vitor
#Versão 1.0.1
while True:
print("Programa para calcular média da UNIT")
print("Se você quer calcular a sua média digite 1")
print("Se quer calcular quanto precisa para passar digite 2")
opcao = int(input("Digite sua opção: "))
#Função para calcular a média final
def func1():
uni1 = float(input("Digite a nota da Primeira unidade: "))
uni2 = float(input("Digite a nota da Segunda unidade: "))
total = ((uni1 * 4) + (uni2 * 6))
if (total >= 60):
print("Você passou, sua nota é igual a: ", (total/10))
elif (total < 60):
print("Você não passou, sua nota é igual a: ", (total/10))
#Função para calcular quanto precisa para passar
def func2():
uni1 = float(input("Digite a nota da primeira unidade: "))
falta =(60 - (uni1*4))
mediaf = falta /6
print("Você precisa de", mediaf, "para passar")
if (opcao == 1):
func1()
elif (opcao == 2):
func2()
else:
print("Opção incorreta, saindo do programa!")
break
|
868fa6af1abc4794475a805bc1aba88de1c468ee | wragon/Fall_Detection_System | /user.py | 868 | 3.78125 | 4 | # About User Info
class UserInfo:
name = ""
number = ""
location = ""
def __init__(self):
self.set_user()
def set_user(self):
self.set_name()
self.set_number()
self.set_location()
def set_name(self):
self.name = input ("사용자 이름: ")
#self.name = "" # todo yourself
def set_number(self):
self.number = input ("보호자 연락처: ")
#self.number = "" # todo yourself
def set_location(self):
self.location = input ("사용자 위치: ")
#self.location = "" # todo yourself
def get_user(self):
print(self.name)
print(self.number)
print(self.location)
def get_name(self):
return self.name
def get_number(self):
return self.number
def get_location(self):
return self.location
|
7a1672a4dcf3a4b717001d7504315692b5209305 | lucasmarcao/slot_pra_python | /slot_para_python/jogodatabuada.py | 1,087 | 3.5 | 4 | import random
cont=0
try:
testandomatriz = random.sample([1,4,2],counts=[5,5,5], k=7)
print(testandomatriz)
except Exception as e:
print("famoso erro")
print("Você precisa de 10 pontos para ganhar")
while(cont<10):
prim = random.randint(1,11)
seg = random.randint(1,11)
print("a conta é : ",prim," X ",seg," = \n" )
vezes = prim * seg
resposta = int(input("O resultado desta conta é -------->"))
if(resposta==vezes):
print("você acertou!!!, o resultado realmente era: ", vezes)
cont = cont + 1
print("sua pontuação é:", cont)
else:
print("Você está errado, a resposta era: ", vezes)
print("sua pontuação é:", cont)
confirm = input("deseja continuar?")
if(confirm=="sim" or confirm=="SIM" or confirm=="s" or confirm=="S" or confirm=="claro"):
prim = 0
seg = 0
vezes = 0
else:
cont = 11
print("até a proxima")
if(cont==10):
print("Você ganhou o jogo")
|
7396455c9f1af991085a0a7954f7a75c55ea7986 | qilin-link/-algorithm015 | /Week_08/merge.py | 1,181 | 3.796875 | 4 | ###############################
# leetcode [56] 合并区间
###############################
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
n = len(intervals)
res = []
left = intervals[0][0]
right = intervals[0][1]
for i in range(1, n):
# 下一区间的左界小于等于当前区间的右界,表示有公共部分
if intervals[i][0] < right:
# intervals[i]右界大于当前区间的右界,表示intervals[i]不包含于当前区间,需要更新当前区间的右界
if intervals[i][1] > right:
right = intervals[i][1]
else:
# 没有交集
res.append([left, right])
# 更新当前区间左界和右界,指向下一区间
left = intervals[i][0]
right = intervals[i][1]
res.append([left, right])
return res
if __name__ == "__main__":
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
s = Solution()
print(s.merge(intervals))
|
f87ddea432ce38f221e1d2bd793f375b7d27a125 | martius-lab/GateL0RD-paper | /src/environments/remote_control_gym.py | 19,880 | 3.65625 | 4 | """
Simple control task where an agent can control a robot after accessing a computer.
The goal is to bring the robot to a goal location
The scenario is implemented in the OpenAi Gym interface (gym.openai.com)
"""
import gym
from gym import spaces, logger
import remote_control_gym_rendering as rendering
import numpy as np
import pyglet
import random
from pyglet.gl import *
from pyglet.image.codecs.png import PNGImageDecoder
import os
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) + '/'
class RemoteControlGym(gym.Env):
"""
Simple gym task for controlling a boy and a robot in a 2D environment
Observation (4 dimensional):
- Position of agent (x, y)
- Position of robot (x, y)
Action (2-dimensional):
- Movement of agent (x, y)
Additional information (may be used as additional observation, 9-dimensional)
- Is the robot controlled?
- Distance to wall for agent (N, E, S, W)
- Distance to wall for agent (N, E, S, W)
Reward is obtained when the robot is moved to the goal position.
The robot can be moved when the agent reaches a computer.
Agent and robot starting positions are randomly sampled for each simulation.
Goal and computer position do not change over simulations.
"""
def __init__(self, r_seed=42):
"""
:param r_seed: random seed
"""
super().__init__()
np.random.seed(r_seed)
self.agent_pos = (np.random.rand(2) - 0.5) * 2
self.robot_pos = (np.random.rand(2) - 0.5) * 2 + np.array([2.0, 0.0], dtype=np.float64)
self.computer_pos = np.array([0.5, 0.5], dtype=np.float64)
self.goal_pos = np.array([2.5, -0.5], dtype=np.float64)
self.r_seed = r_seed
self.agent_pos_upper_limits = np.array([0.95, 0.95], dtype=np.float64)
self.agent_pos_lower_limits = np.array([-0.95, -0.95], dtype=np.float64)
self.robot_pos_upper_limits = np.array([2.95, 0.95], dtype=np.float64)
self.robot_pos_lower_limits = np.array([1.05, -0.95], dtype=np.float64)
self.position_limits = np.array([0.95, 0.95, -0.95, -0.95, 2.95, 0.95, 1.05, -0.95], dtype=np.float64)
action_limits = np.array([1, 1])
obs_limits = np.array([0.95, 0.95, 0.95, 0.95])
self.action_space = spaces.Box(-1 * action_limits, action_limits, dtype=np.float64)
self.observation_space = spaces.Box(-1 * obs_limits, obs_limits, dtype=np.float64)
# VISUALIZATION
self.viewer = None
# all entities are composed of a Geom, a Transform (determining position) and a sprite
self.agent_sprite = None
self.agent_sprite_trans = None
self.robot_sprite = None
self.robot_sprite_trans = None
self.computer_sprite = None
self.computer_sprite_trans = None
self.goal_sprite = None
self.goal_sprite_trans = None
# background image is treated the same way
self.background_sprite = None
self.background_geom = None
self.background_trans = None
# Threshold for reaching the goal
self.goal_threshold = 0.1
# Scaling of action effect
self.action_factor = 0.1
# Range where the distance sensors detect walls
self.distance_range = 0.1
# Flag whether robot is currently controlled
self.robot_controlled = False
self.last_action = np.array([-0.1, 0], dtype=np.float64)
self.wall_contacts = np.zeros(8, dtype=np.float64)
self.t = 0
self.t_render = 0
def seed(self, seed):
self.r_seed = seed
random.seed(seed)
np.random.seed(seed)
# ------------- STEP -------------
def step(self, action):
"""
Performs one step of the simulation
:param action: next action to perform
:return: next information, obtained reward, end of sequence?, additional inf
"""
assert self.action_space.contains(action), "%r (%s) invalid" % (action, type(action))
# Save the action
self.last_action = action * self.action_factor
# Move agent (and robot) based on action
self.agent_pos = self.agent_pos + self.last_action
if self.robot_controlled:
self.robot_pos = self.robot_pos + self.last_action
# check boundaries of agent and patient position
self._clip_positions()
# Infrared sensor like measurement of wall distances
self.wall_contacts = np.zeros(8, dtype=np.float64)
double_pos_agent = np.append(self.agent_pos, self.agent_pos, 0)
double_pos_robot = np.append(self.robot_pos, self.robot_pos, 0)
double_pos = np.append(double_pos_agent, double_pos_robot, 0)
self.wall_contacts = 1.0 - 10* abs(double_pos - self.position_limits)
pos_diff = double_pos - self.position_limits
self.wall_contacts[abs(pos_diff) > self.distance_range] = 0
# Check if agent reached computer
distance_agent_computer = np.linalg.norm(self.computer_pos - self.agent_pos)
if distance_agent_computer < self.goal_threshold:
self.robot_controlled = True
# Check if robot reached goal
distance_robot_goal = np.linalg.norm(self.goal_pos - self.robot_pos)
done = distance_robot_goal < self.goal_threshold
reward = 0.0
if done:
reward = 1.0
# Adjust robot position such that it is in [-1, 1] for the observation
norm_robot_pos = np.copy(self.robot_pos)
norm_robot_pos[0] -= 2.0
# Create additional info vector
robot_controlled_array = np.array([0.0])
if self.robot_controlled:
robot_controlled_array[0] = 1.0
info = np.append(robot_controlled_array, self.wall_contacts)
observation = np.append(self.agent_pos.flat, norm_robot_pos.flat, 0)
return observation, reward, done, info
def _clip_positions(self):
np.clip(self.agent_pos, self.agent_pos_lower_limits, self.agent_pos_upper_limits, self.agent_pos)
np.clip(self.robot_pos, self.robot_pos_lower_limits, self.robot_pos_upper_limits, self.robot_pos)
# ------------- RESET -------------
def reset(self, with_info=False):
"""
Randomly reset the simulation.
:param with_info: include additional info (robot control, wall sensors) in output
:return: first observation, additional info
"""
self.agent_pos = (np.random.rand(2) - 0.5) * 2
self.robot_pos = (np.random.rand(2) - 0.5) * 2 + np.array([2.0, 0.0], dtype=np.float64)
self.computer_pos = np.array([0.5, 0.5], dtype=np.float64)
self.goal_pos = np.array([2.5, -0.5], dtype=np.float64)
self.robot_controlled = False
norm_robot_pos = np.copy(self.robot_pos)
norm_robot_pos[0] -= 2.0
self.wall_contacts = np.zeros(8, dtype=np.float64)
# Infrared sensor like measurement
double_pos_agent = np.append(self.agent_pos, self.agent_pos, 0)
double_pos_robot = np.append(self.robot_pos, self.robot_pos, 0)
double_pos = np.append(double_pos_agent, double_pos_robot, 0)
self.wall_contacts = 1.0 - 10 * abs(double_pos - self.position_limits)
pos_diff = double_pos - self.position_limits
self.wall_contacts[abs(pos_diff) > 0.1] = 0
o_init = np.append(self.agent_pos.flat, norm_robot_pos.flat, 0)
if with_info:
# Create additional info vector
robot_controlled_array = np.array([0.0])
if self.robot_controlled:
robot_controlled_array[0] = 1.0
info_init = np.append(robot_controlled_array, self.wall_contacts)
return o_init, info_init
return o_init
# ------------- RENDERING -------------
def _determine_robot_sprite(self, action, t):
"""
Finds the right sprite for the robot depending on the last actions
:param action: last action
:param t: time
:return: sprite number
"""
if self.robot_controlled:
return t % 4
return 0
def _determine_agent_sprite(self, action, t):
"""
Finds the right sprite for the agent depending on the last actions
:param action: last action
:param t: time
:return: sprite number
"""
if abs(action[1]) > abs(action[0]):
# Left right dimension is stronger than up/down
if action[1] < 0:
# down:
return 0 + t % 2
else:
#up
return 2 + t % 2
else:
if action[0] < 0:
# left:
return 4 + t % 2
else:
#right
return 6 + t % 2
def render(self, store_video=False, video_identifier=1, mode='human'):
"""
Renders the simulation
:param store_video: bool to save screenshots or not
:param video_identifier: number to label video of this simulation
:param mode: inherited from gym, currently not used
"""
# Constant values of window size, sprite sizes, etc...
screen_width = 1200 #pixels
screen_height = 630 #pixels
agent_sprite_width = 70 # pixels of sprite
robot_sprite_width = 70
computer_sprite_width = 70
wall_pixel_width = 12
goal_sprite_width = 16
goal_sprite_height = 16
scale = 300.0 # to compute from positions -> pixels
foreground_sprite_scale = 2 # constant scaling of foreground sprites
background_sprite_scale = 3 # constant scaling of walls, floor, etc...
self.t += 1
if self.t % 2 == 0:
self.t_render += 1
if self.viewer is None:
# we create a new viewer (window)
self.viewer = rendering.Viewer(screen_width, screen_height)
glEnable(GL_TEXTURE_2D)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
# Agents sprite list [d, u, l, r] *[0, 1]
agent_sprite_list = []
robot_sprite_list = []
agent_sprite_names = ["d", "u", "l", "r"]
for i in range(4):
robot_sprite_file = SCRIPT_PATH + "RRC_Sprites/rob" + str(i+1) + ".png"
robot_image = pyglet.image.load(robot_sprite_file, decoder=PNGImageDecoder())
robot_pyglet_sprite = pyglet.sprite.Sprite(img=robot_image)
robot_sprite_list.append(robot_pyglet_sprite)
for j in range(2):
agent_sprite_file = SCRIPT_PATH + "RRC_Sprites/" + agent_sprite_names[i] + str(j+1) + ".png"
agent_image = pyglet.image.load(agent_sprite_file, decoder=PNGImageDecoder())
agent_pyglet_sprite = pyglet.sprite.Sprite(img=agent_image)
agent_sprite_list.append(agent_pyglet_sprite)
self.agent_sprite = rendering.SpriteGeom(agent_sprite_list)
self.agent_sprite_trans = rendering.Transform()
self.agent_sprite.add_attr(self.agent_sprite_trans)
self.viewer.add_geom(self.agent_sprite)
self.robot_sprite = rendering.SpriteGeom(robot_sprite_list)
self.robot_sprite_trans = rendering.Transform()
self.robot_sprite.add_attr(self.robot_sprite_trans)
self.viewer.add_geom(self.robot_sprite)
goal_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/target.png", decoder=PNGImageDecoder())
goal_pyglet_sprite = pyglet.sprite.Sprite(img=goal_image)
goal_sprite_list = [goal_pyglet_sprite]
self.goal_sprite = rendering.SpriteGeom(goal_sprite_list)
self.goal_sprite_trans = rendering.Transform()
self.goal_sprite.add_attr(self.goal_sprite_trans)
self.viewer.add_geom(self.goal_sprite)
computer_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/terminal2.png", decoder=PNGImageDecoder())
computer_pyglet_sprite = pyglet.sprite.Sprite(img=computer_image)
computer_sprite_list = [computer_pyglet_sprite]
self.computer_sprite = rendering.SpriteGeom(computer_sprite_list)
self.computer_sprite_trans = rendering.Transform()
self.computer_sprite.add_attr(self.computer_sprite_trans)
self.viewer.add_geom(self.computer_sprite)
wall_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/long_wall.png", decoder=PNGImageDecoder())
wall_pyglet_sprite = pyglet.sprite.Sprite(img=wall_image)
wall_sprite_list = [wall_pyglet_sprite]
wall_sprite = rendering.SpriteGeom(wall_sprite_list)
wall_sprite_trans = rendering.Transform()
wall_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
wall_sprite_trans.set_translation(screen_width/2.0 - wall_pixel_width/2.0 * background_sprite_scale, 0)
wall_sprite.set_z(3)
wall_sprite.add_attr(wall_sprite_trans)
self.viewer.add_geom(wall_sprite)
wall_2image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/long_wall.png", decoder=PNGImageDecoder())
wall_2pyglet_sprite = pyglet.sprite.Sprite(img=wall_2image)
wall_2sprite_list = [wall_2pyglet_sprite]
wall_2sprite = rendering.SpriteGeom(wall_2sprite_list)
wall_2sprite_trans = rendering.Transform()
wall_2sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
wall_2sprite_trans.set_translation(0 - wall_pixel_width / 2.0 * background_sprite_scale, 0)
wall_2sprite.set_z(3)
wall_2sprite.add_attr(wall_2sprite_trans)
self.viewer.add_geom(wall_2sprite)
wall_3image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/long_wall.png", decoder=PNGImageDecoder()) # "Sprites/wall_longest3.png"
wall_3pyglet_sprite = pyglet.sprite.Sprite(img=wall_3image)
wall_3sprite_list = [wall_3pyglet_sprite]
wall_3sprite = rendering.SpriteGeom(wall_3sprite_list)
wall_3sprite_trans = rendering.Transform()
wall_3sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
wall_3sprite_trans.set_translation(screen_width - wall_pixel_width / 2.0 * background_sprite_scale, 0)
wall_3sprite.set_z(3)
wall_3sprite.add_attr(wall_3sprite_trans)
self.viewer.add_geom(wall_3sprite)
back_wall_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/back_wall.png", decoder=PNGImageDecoder())
back_wall_pyglet_sprite = pyglet.sprite.Sprite(img=back_wall_image)
back_wall_sprite_list = [back_wall_pyglet_sprite]
back_wall_sprite = rendering.SpriteGeom(back_wall_sprite_list)
back_wall_sprite_trans = rendering.Transform()
back_wall_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
back_wall_pixel_height = 20
back_wall_sprite_trans.set_translation(0, screen_height - back_wall_pixel_height)
back_wall_sprite.add_attr(back_wall_sprite_trans)
self.viewer.add_geom(back_wall_sprite)
front_wall_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/grey_line.png", decoder=PNGImageDecoder())
front_wall_pyglet_sprite = pyglet.sprite.Sprite(img=front_wall_image)
front_wall_sprite_list = [front_wall_pyglet_sprite]
front_wall_sprite = rendering.SpriteGeom(front_wall_sprite_list)
front_wall_sprite_trans = rendering.Transform()
front_wall_sprite_trans.set_translation(0, 0)
front_wall_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
front_wall_sprite.add_attr(front_wall_sprite_trans)
self.viewer.add_geom(front_wall_sprite)
background_image = pyglet.image.load(SCRIPT_PATH + "RRC_Sprites/grey_wood_background.png", decoder=PNGImageDecoder())
background_pyglet_sprite = pyglet.sprite.Sprite(img=background_image)
background_sprite_list = [background_pyglet_sprite]
background_sprite = rendering.SpriteGeom(background_sprite_list)
background_sprite_trans = rendering.Transform()
background_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
background_sprite.set_z(-1)
background_sprite.add_attr(background_sprite_trans)
self.viewer.add_geom(background_sprite)
# during video recording images of the simulation are saved
if store_video:
self.viewer.activate_video_mode("Video" + str(video_identifier) + "/")
# determine the sprite position and size for
# 1. ... agent
agent_x = (self.agent_pos[0] + 1) * scale
agent_y = (self.agent_pos[1] + 1) * scale
self.agent_sprite.set_z(1)
self.agent_sprite.alter_sprite_index(self._determine_agent_sprite(self.last_action, self.t_render))
self.agent_sprite_trans.set_scale(foreground_sprite_scale, foreground_sprite_scale)
sprite_center = np.array([foreground_sprite_scale * agent_sprite_width / 2.0, 0.0])
self.agent_sprite_trans.set_translation(agent_x - sprite_center[0], agent_y - sprite_center[1])
# 2. ... the computer
computer_x = (self.computer_pos[0] + 1) * scale
computer_y = (self.computer_pos[1] + 1) * scale
self.computer_sprite_trans.set_scale(foreground_sprite_scale, foreground_sprite_scale)
computer_sprite_center = np.array([foreground_sprite_scale * computer_sprite_width / 2.0, 0])
self.computer_sprite_trans.set_translation(computer_x - computer_sprite_center[0], computer_y - computer_sprite_center[1])
self.computer_sprite.set_z(0)
if agent_y > computer_y + computer_sprite_width / 4.0:
self.computer_sprite.set_z(2)
# 3. ... the goal
goal_x = (self.goal_pos[0] + 1) * scale
goal_y = (self.goal_pos[1] + 1) * scale
self.goal_sprite.set_z(0)
self.goal_sprite_trans.set_scale(background_sprite_scale, background_sprite_scale)
goal_sprite_center = np.array([background_sprite_scale * goal_sprite_width / 2.0, background_sprite_scale * goal_sprite_height / 2.0])
self.goal_sprite_trans.set_translation(goal_x - goal_sprite_center[0], goal_y - goal_sprite_center[1])
# 4. ... the robot
robot_x = (self.robot_pos[0] + 1) * scale
robot_y = (self.robot_pos[1] + 1) * scale
self.robot_sprite.set_z(1)
self.robot_sprite_trans.set_scale(foreground_sprite_scale, foreground_sprite_scale)
robot_sprite_center = np.array([foreground_sprite_scale * robot_sprite_width / 2.0, 0.0])
self.robot_sprite_trans.set_translation(robot_x - robot_sprite_center[0], robot_y - robot_sprite_center[1])
self.robot_sprite.alter_sprite_index(self._determine_robot_sprite(self.last_action, self.t_render))
return self.viewer.render(mode == 'rgb_array')
# ------------- CLOSE -------------
def close(self):
"""
Shut down the gym
"""
if self.viewer:
self.viewer.deactivate_video_mode()
self.viewer.close()
self.viewer = None
|
a0411df383523974ac3d9bfec5c4031066dcfe93 | Serge-Mavuba/Python-List-Comprehensions | /Lists Comprehensions.py | 3,665 | 4.34375 | 4 | # List = [1,2, "collection ", "of", "data", "surronded", "by", "brackets", "and", "the",
# "elements", "are", "separated", "by", "commas"]
# List comprehensions =
# ["is", "also", "surronded", "by", "brackets","but", "instead", "of", "a", "list", "of", "data", "inside"
# "you", "enter", "an", "expression", "followed", "by", "for", "loops", "and", "if", "clauses"]
# Here is the most basic forms for a list comprehension:
# [expr for val in collection]
# expr: the first expression generates the elements in the list
# for val in collection: followed with a for loop over some collection of data (this evaluates every item in the collection)
# [expr for val in collection if <test>]
# if <test>: adding an if clause will only evaluate the expression for certains pieces of data
# Print colored Text
import colorama
from colorama import Fore, Back, Style
colorama.init(autoreset=True)
# Using a List Comprcehension, list all the students with the name that starts with the letter "S"
#------------------------------------------------------------------------------------------------
NAMES = ['Dana Hausman', 'Corrine Haley', 'Huan Xin (Winnie) Cai', 'Greg Willits', 'Michael Lyda', 'Aidana Utepkaliyeva',
'Claudius Taylor', 'Dyian Nikolv', 'Higl Daniel', 'Mary Beth Arroyo', 'Sajini George', 'Natalia Gomez',
'Riad Mesharafa','Shafan Sugarman','Sarah Chang', 'Rashmi Venkatesh', 'Higl Daniel', 'Domineco Sacca', 'Tanzeela Chaudry',
'Nataliia Zdrok','Natnael Argaw','Nosa Okundaye', 'Sibel Gulmez', 'Serge Mavuba', 'Geethalakshmi Prasanna', 'Gwei Balantar',
'Imran Barker', 'Lesley Ndeh', 'Trevor Unaegbu', 'Abraham Musa', 'Roberto Santos']
print(Fore.WHITE + Back.RED + Style.BRIGHT +"Names = " + ", ".join(NAMES))
print(155*"-")
# Without using a List comprehension
#-----------------------------------
# Make an empty list
PerScholas =[]
# Loop over the list of names
for student in NAMES:
# We can use the startswith method to see the student names that start with the letter S
if student.startswith("S"):
# then append the results to a list
PerScholas.append(student)
# print to make sure that it worked
print(Fore.WHITE + Back.RED + Style.BRIGHT + ", ".join(PerScholas))
print(155*"-")
# Using a List Comprehension you can reduce lines of code into a single line
#---------------------------------------------------------------------------
PerScholas2=[student for student in NAMES if student.startswith('S')]
# the expression we want to appear on our list is simply the student; next loop over the names
# but also check that the name starts with the letter S then print
print(Fore.RED + Back.WHITE + Style.BRIGHT + ", ".join(PerScholas2))
print(155*"-")
# Lets get fancier: consider a List of tuples
# -------------------------------------------
NEW = [('Dana Hausman', 1996), ('Corrine Haley', 1998), ('Huan Xin (Winnie) Cai', 1997), ('Greg Willits', 2001), ('Michael Lyda', 1995), ('Aidana Utepkaliyeva', 2000),
('Claudius Taylor', 2001), ('Dyian Nikolv', 2016), ('Higl Daniel', 2009), ('Mary Beth Arroyo', 2010), ('Sajini George', 2006), ('Natalia Gomez', 2007),
('Riad Mesharafa', 1922),('Shafan Sugarman', 1980),('Sarah Chang', 1946), ('Rashmi Venkatesh', 1970), ('Higl Daniel', 1919), ('Domineco Sacca', 2000), ('Tanzeela Chaudry', 2020),
('Nataliia Zdrok', 2121),('Natnael Argaw', 2021),('Nosa Okundaye',2525), ('Sibel Gulmez', 2527), ('Serge Mavuba', 1995), ('Geethalakshmi Prasanna', 2000), ('Gwei Balantar', 3000),
('Imran Barker', 1900), ('Lesley Ndeh', 1999), ('Trevor Unaegbu', 2001), ('Abraham Musa', 2000), ('Roberto Santos', 1890)]
# Using a list comprehension list all the students born before the year 2000
#---------------------------------------------------------------------------
pre2k=[student for (student, year) in NEW if year < 2000]
# we want our list to contain the student name but this time when we write the for-loop; each element is a tuple.
# Next We select the students that were born before 2000 using an if clause
print(Fore.WHITE+ Back.GREEN + Style.BRIGHT + ", ".join(pre2k)) |
b436c92cebb0c6af8e53b211d2b85bb68374ea4b | diagram-ai/vishwakarma | /vishwakarma/pdfplot.py | 4,625 | 3.609375 | 4 | # -*- coding: utf-8 -*-
'''
Build visualizations for continuous distributions
[Uniform, Gaussian, Exponential, Gamma]
Example:
from vishwakarma import pdfplot
pdfplot.gaussian(mu, sigma)
Attributes:
Todo:
'''
import requests
import tempfile
import os
import random
import shutil
import string
import datetime
from IPython.display import Image
class pdfplot:
''' This class generates visualizations for continuous distributions '''
# setup the API endpoint to be called
_url = 'http://api.diagram.ai:5000/vishwakarma/'
_endpoint = 'pdfplot/'
# default width of image to be displayed
_width = 600
@classmethod
def uniform(cls, a, b):
'''
Visualization for a Uniform distribution
Args:
a, b (int): parameters to a Uniform distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if not isinstance(a, int):
raise ValueError('For a Uniform distribution, a should always be an integer.')
if not isinstance(b, int):
raise ValueError('For a Uniform distribution, b should always be an integer.')
if b <= a:
raise ValueError('For a Uniform distribution, b should always be greater than a.')
return cls._call_post(dist='uniform', a=a, b=b)
@classmethod
def gaussian(cls, mu, sigma):
'''
Visualization for a Gaussian distribution
Args:
mu, sigma (float): parameters to a Gaussian distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if sigma <= 0:
raise ValueError('For a Gaussian distribution, sigma should be greater than zero.')
return cls._call_post(dist='gaussian', mu=mu, sigma=sigma)
@classmethod
def exponential(cls, lam, sam):
'''
Visualization for an Exponential distribution
Args:
lam (float): parameter to an Exponential distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if lam <= 0:
raise ValueError('For an Exponential distribution, lambda should be greater than zero.')
return cls._call_post(dist='exponential', lam=lam, sam=sam)
@classmethod
def gamma(cls, alpha, beta):
'''
Visualization for a Gamma distribution
Args:
alpha, beta (float): parameters to a Gamma distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
'''
if alpha <= 0:
raise ValueError('For a Gamma distribution, alpha should be greater than zero.')
if beta <= 0:
raise ValueError('For a Gamma distribution, beta should be greater than zero.')
return cls._call_post(dist='gamma', alpha=alpha, beta=beta)
@classmethod
def _call_post(cls, **kwargs):
'''
Calls the API hosted on www.diagram.ai
Args:
kwargs: Name and parameters of the distribution
Returns:
image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
Note:
Internal function - not to be exposed
'''
tmp_dir_name = ''
try:
# create a temp directory & temp file
tmp_dir_name = tempfile.mkdtemp()
# generate a tmp file name (excluding file extension)
epoch = datetime.datetime.now().strftime('%s')
tmp_file_name = ''.join(
[random.choice(string.ascii_letters + string.digits) for n in range(8)])
tmp_file_name = os.path.join(
tmp_dir_name, tmp_file_name + epoch + '.png')
# make the call ...
resp = requests.post(cls._url + cls._endpoint, json=kwargs)
if(resp.ok):
# get the image file and write it to temp dir
if resp.headers.get('Content-Type') == 'image/png':
open(tmp_file_name, 'wb').write(resp.content)
# now return this image as an Image object displayable in a
# Jupyter notebook
return Image(filename=tmp_file_name, width=cls._width)
else:
raise Exception(resp.raise_for_status())
finally:
# cleanup the temp directory
shutil.rmtree(tmp_dir_name, ignore_errors=True)
|
077c33b4377263224f651ff989fd186d289d71ff | hongweifei/Fly-python | /compiler/ast.py | 2,156 | 3.546875 | 4 |
from .token import *
from enum import Enum,unique,auto
@unique
class TreeType(Enum):
NONE = auto() #
IMPORT = auto() # include,import
RETURN = auto() # return
VAR = auto() # 变量声明
FUNCTION = auto() # 函数声明
UNION = auto() # 定义联合体
STRUCT = auto() # 定义结构体
CLASS = auto() # 定义类
CALL = auto() # 调用
ASSIGN = auto() # 赋值
IF = auto() # 如果
SWITCH = auto() # 判断
WHILE = auto() # while
FOR = auto() # for
class Node(object):
"""
A node in the abstract syntax tree of the program.
"""
def __init__(self,token = None):
super().__init__()
self.token:Token = token;
self.parent = None;
self.children = [];
def add_child(self,node):
if node != None:
self.children.append(node);
node.parent = self;
def get_parent(self):
return self.parent;
def get_children(self):
return self.children;
def get_parent_num(self) -> int:
if self.parent == None:
return 0;
else:
n = 0;
parent:Node = self.parent;
while parent != None:
n += 1;
parent = parent.parent;
return n;
def print(self):
if self.parent == None:
print("--" + self.token.value + " type:" + str(self.token.ttype))
else:
print("--" + "-" * self.get_parent_num() + self.token.value + " type:" + str(self.token.ttype))
if self.parent != None and len(self.children) == 0:
if self is self.parent.children[len(self.parent.children) - 1]:
print("\n")
for child in self.children:
child.print()
class RootNode(Node):
def __init__(self, token = None):
super().__init__(token = token)
self.ttype = TreeType.NONE;
def print(self):
print("Type:" + str(self.ttype));
return super().print();
|
c219b35384dcc23574658cfcbae883f4223f8709 | LRG84/python_assignments | /average7.5.py | 538 | 4.28125 | 4 | # calculate average set of numbers
# Write a small python program that does the following:
# Calculates the average of a set of numbers.
# Ask the user how many numbers they would like to input.
# Display each number and the average of all the numbers as the output.
def calc_average ():
counter = int (input('How many numbers would you like to input?_'))
total = 0
for a in range (0, counter):
total = total + int(input('Enter number_ '))
print('The average of your input is ', total/counter)
calc_average ()
|
cfa1235528a3b32f4c93e015f89ef13b2b8053be | LRG84/python_assignments | /Celsius_5degree_increments.py | 323 | 3.984375 | 4 | #write a program that outputs a table of celsius temperatures from 1-100, in increments of 5
#in addition, the corresponding farenheit temperature should be listed.
#upload to github
for a in range (0,101,5):
cel_temp = a
far_temp = cel_temp * (9/5) + 32
print ('celsius =',cel_temp,'farenheit =',far_temp)
|
0095ae6aada5352dee242b1ec05a027fd695de99 | VishLi777/python-practice | /bonus_practice1/task6_1_1.py | 490 | 3.90625 | 4 | # Реализуйте функцию fast_mul в соответствии с алгоритмом двоичного умножения в столбик.
# Добавьте автоматическое тестирование, как в случае с naive_mul.
def fast_mul(x, y):
if x == 0 or y == 0: # add condition
return 0
r = 0 # r = 1
while y > 0:
if y % 2 == 1:
r += x
x *= 2
y //= 2
return r
|
6cbc3f38656ead6125e3c1cc360d9e0e2a1de979 | ttitus72372/GitHubTesting | /main.py | 597 | 3.546875 | 4 | '''
x = 0
while x <= 10:
x +=1
print(x)
#print(x)
list1 = [1,4,7,9,11,34,65]
for item in list1:
#print(item)
if item <= 20:
print(item)
numb1 = int(input("Please enter a number:\n"))
numb2 = int(input("Please enter another number:\n"))
numb3 = numb1 + numb2
print(numb3)
'''
list2 = []
counter = 0
while counter < 5:
var = int(input("Type a number to be added into the list:\n"))
list2.append(var)
counter +=1
print(sum(list2))
#hi tim
#looks like the Github collaboration works.
#it doesn't seem to highlight who did what changes, directly within repl.it, at this time.
|
66a863f91af4b1fb778e0b8edface323d321f370 | RasmusKnothNielsen/PicoCTF2019 | /General_Skills/whats_the_difference/whats_the_difference_solution.py | 597 | 3.546875 | 4 | # Whats-the-difference
# General skills
# PicoCTF 2019
# Author: Rasmus Knoth Nielsen
# Open the kitters.jpg file and read it into memory
with open('./kitters.jpg', 'rb') as f:
kitters = f.read()
# Open the cattos.jpg file and read it into memory
with open('./cattos.jpg', 'rb') as f:
cattos = f.read()
flag = ''
# For the length of the shortest file, do the following
for i in range(min(len(kitters), len(cattos))):
# If these differ, do the following
if kitters[i] != cattos[i]:
# Save the Decimal as the ASCII value in our flag variable
flag += chr(cattos[i])
print(flag)
|
1420c19f9f80614f5d3b6ba122ed7b1d9f51122f | shihan123a/Daily_-summary | /绘图函数/递归函数.py | 238 | 4.03125 | 4 | import sys
def Factorial(num):
if num == 1 :
return 1
else:
result = num * Factorial(num-1)
return result
if __name__ == '__main__' :
result = Factorial(5)
print('5的阶乘是:{}'.format(result)) |
833bd691452513944dabb2af51272c90c70c8eaf | lucasrwv/python-p-zumbis | /lista III/questao04.py | 273 | 4.125 | 4 | #programa fibonacci
num = int(input("digite um numero "))
anterior = 0
atual = 1
proximo = 1
cont = 0
while cont != num :
seun = proximo
proximo = atual + anterior
anterior = atual
atual = proximo
cont += 1
print("o seu numero fibonacci é %d" %seun)
|
ddfd3b2738cce2d2d41f57cd21687fa488e76f2b | lucasrwv/python-p-zumbis | /lista II/questao02.py | 259 | 3.953125 | 4 | # ano bixesto
ano = int(input("digite o ano: "))
if ano % 4 == 0 and ano % 100 != 0 :
print("o ano é bissexto")
elif ano % 4 == 0 and ano % 100 == 0 and ano % 400 == 0 :
print("o ano é bissexto")
else :
print("o ano nao é bissexto")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.