blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
412104dd50bab7a3adf7bb8cc889be227f162ed4
destinysam/Python
/map function.py
530
4.09375
4
# CODED BY SAM@SAMEER # EMAIL:[email protected] # DATE:11/09/2019 # PROGRAM: CONVERTING OF LIST NUMBERS INTO NEGATIVE NUMBERS def negative(numbers, rang): return_list = [] temp = 0 counter = 0 for j in range(rang): counter = int(numbers[j]) temp = counter * -1 return_list.append(temp) return return_list number = [] size = int(input("ENTER THE SIZE OF LIST :")) for i in range(size): num = input("ENTER THE NUMBERS OF THE LIST ") number.append(num) print(negative(number, size))
aa1193d1f11a0c3ed765ceebb0075cfbc1ed3b0c
destinysam/Python
/assignment operators.py
310
4.03125
4
# CODED BY SAM@SAMEER # EMAIL: [email protected] # DATE: 17/08/2019 # PROGRAM: USING OF ASSIGNMENT OPERATORS IN PYTHON name = "sameer" print(name + "ahmad") name += "ahmad" print(name) age = 8 print(age) age += 2 # age = 8+2 =10 print(age) age *= 2 # age = 10*2 = 20 print(age) age -= 3 # age = 20-3 = 17 print(age)
5090e0dc9b0b2af20e1c98a8faefecc9f6e98fe3
destinysam/Python
/if_statement.py
217
4.03125
4
# CODED BY SAM@SAMEER # EMAIL: [email protected] # DATE: 18/08/2019 # PROGRAM: USING OF IF STATEMENT IN PYTHON age = int(input('ENTER THE AGE')) if age >= 21: print("U ARE SELECTED") else: print("YOUR AGE IS BELOW 21")
d9f27a2de72ad70490a106541336da7e12b3658d
venkatadri123/Python_Programs
/100_Basic_Programs/program_83.py
127
3.75
4
# 83.Please write a program to shuffle and print the list [3,6,7,8]. import random li = [3,6,7,8] random.shuffle(li) print(li)
1e1c08f44e704162f524bcf16e864410fbb81936
venkatadri123/Python_Programs
/core_python_programs/prog24.py
146
4.4375
4
# To accept a string from the keyboard and display individual letters of the string. str=input('enter string values:') for i in str: print(i)
6709221f53da07b735c97eb6701ac100d1c04a0a
venkatadri123/Python_Programs
/Sample_programs/31sum.py
114
3.6875
4
#To display sum of a list. l=[10,20,45] sum=0 i=0 while i<len(l): sum=sum+l[i] i=i+1 print("result=",sum)
76d555e119434b9b681e12c24d766a378a46e335
venkatadri123/Python_Programs
/Sample_programs/7incr.py
116
4.0625
4
#to increase a number by 1. ch=int(input()) x = ch+ 1 print ("The incremented character value is : ",x ) print (x)
6e279577678929165b7e5157ae4fffbdaaec1ccd
venkatadri123/Python_Programs
/core_python_programs/prog72.py
187
3.953125
4
# Write a lambda expression for sum of two number. def sum(a,b): return a+b x=sum(10,20) print('sum=',x) # Converting into lambda expression. f=lambda a,b:a+b print('sum=',f(10,20))
44c554dfeae7565f4d281bd31418a6f95a8beee4
venkatadri123/Python_Programs
/Advanced_python_programs/prog7.py
540
3.796875
4
# Wrte employee class with accessor and mulator methods. class emp: def setid(self,id): self.id=id def getid(self): return self.id def setname(self,name): self.name=name def getname(self): return self.name def setsal(self,sal): self.sal=sal def getsal(self): return self.sal e=emp() e.setid(int(input('enter id no:'))) e.setname(input('enter name')) e.setsal(float(input('enter salory:'))) print('id=',e.getid()) print('name=',e.getname()) print('salory=',e.getsal())
0f0ac9cde7b60c38b2b507f099116c2dfa215ede
venkatadri123/Python_Programs
/Sample_programs/6addsub.py
121
3.8125
4
#To find subtraction and addition. x=int(input()) y=int(input()) z=x+y print('addition z=',x+y) z=x-y print('sub z=',x-y)
593d588380891054c09dbdae3303399a2460999a
venkatadri123/Python_Programs
/Advanced_python_programs/student.py
538
3.6875
4
# Import some code from teacher class using Inheritance. from teacher import* class student(teacher): def setmarks(self,marks): self.marks=marks def getmarks(self): return self.marks s=student() s.setid(14) s.setname('venkatadri') s.setage('25 Years') s.setheight('5.11 Inch') s.setaddress('vindur,gudur,nellore,andrapradesh') s.setmarks(965) print('id no=',s.getid()) print('name=',s.getname()) print('age=',s.getage()) print('height=',s.getheight()) print('address=',s.getaddress()) print('marks=',s.getmarks())
2e3e733022370fd080b83b15db16340d75acc2b0
venkatadri123/Python_Programs
/HackerRank_programs/hourglassSum.py
1,200
3.890625
4
"""Given a 2D Array, : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation: a b c d e f g There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum. For example, given the 2D array:""" import math import os import random import re import sys # Complete the hourglassSum function below. def hourglassSum(arr): total = 0 max_total = -1073741824 for i in range(len(arr)): for j in range(len(arr[i])): if (j+2 < 6) and (i+2 < 6): total = arr[i][j] + arr[i][j+1] + arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2] if max_total < total: max_total = total return max_total if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) result = hourglassSum(arr) fptr.write(str(result) + '\n') fptr.close()
1e6200636339b88fdfab99dd685b6f6cc11cbc5a
venkatadri123/Python_Programs
/100_Basic_Programs/program_11.py
532
3.953125
4
# 11.Write a program which accepts a sequence of comma separated 4 digit binary numbers as its # input and then check whether they are divisible by 5 or not. The numbers that are divisible # by 5 are to be printed in a comma separated sequence. l=[] x=input() items=x.split(',') for p in items: q=int(p) if q%5==0: l.append(p) print(','.join(l)) # value = [] # items=[x for x in input().split(',')] # for p in items: # intp = int(p, 2) # if intp%5!=0: # value.append(p) # # print(','.join(value))
d0be8e43586ecf7ccb00bb5bb2c1680e1e3cd6f6
venkatadri123/Python_Programs
/HackerRank_programs/repeatedString.py
978
3.890625
4
"""Lilah has a string, , of lowercase English letters that she repeated infinitely many times. Given an integer, , find and print the number of letter a's in the first letters of Lilah's infinite string. For example, if the string and , the substring we consider is , the first characters of her infinite string. There are occurrences of a in the substring.""" import math import os import random import re import sys # Complete the repeatedString function below. def repeatedString(s, n): len_str=len(s) num_strs=n//len_str remainder=n%len_str count1=0 count2=0 for i in range(len_str): if s[i]=='a': count1+=1 if s[i]=='a' and i<remainder: count2+=1 total=count1*num_strs+count2 return total if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() n = int(input()) result = repeatedString(s, n) fptr.write(str(result) + '\n') fptr.close()
c156d757509443dfe18982519d44481ad0484f3b
venkatadri123/Python_Programs
/Advanced_python_programs/prog21.py
395
3.859375
4
# Creating our own Exception. class MyException(Exception): def __init__(self,str): self.str=str def check(dict): for k,v in dict.items(): print('%-15s %.2f' %(k,v)) if v<2000.00: raise MyException('balence amount is less') bank={'raju':35600,'venkey':25641,'hari':1230,'suri':2564} try: check(bank) except MyException as m: print(m)
b5edf92d6ac5a62efe88d987bfaf0e080e9b7b2e
venkatadri123/Python_Programs
/core_python_programs/prog7.py
247
4.0625
4
#To display employee Id no,Name,Salory from the keyboard & display them. id_no=int(input('enter id:')) name=input('enter name:') sal=float(input('enter sal:')) print('employee details are:') print('id_no=%d,\nname=%s,\nsal=%f' %(id_no,name,sal))
039a88bcde8a8045d66b502bf2d12c14363c54f9
venkatadri123/Python_Programs
/Advanced_python_programs/prog2.py
473
3.96875
4
# Create a student class with roll number,name,marks in three subjects and total marks. class student: def __init__(self,r,n,m): self.rno=r self.name=n self.marks=m def display(self): print('rno=',self.rno) print('name=',self.name) print('marks=',self.marks) print('total marks=',sum(self.marks)) print('average marks=',sum(self.marks)/len(self.marks)) s1=student(10,'venkey',[45,55,78]) s1.display()
0eaf2afa9cc1c3f161504fc2c9254b92fb3f4262
venkatadri123/Python_Programs
/100_Basic_Programs/program_43.py
280
4.53125
5
# 43. Write a program which accepts a string as input to print "Yes" # if the string is "yes" or "YES" or "Yes", otherwise print "No". def strlogical(): s=input() if s =="Yes" or s=="yes" or s=="YES": return "Yes" else: return "No" print(strlogical())
04fad98db209c75d4ec38471b36a7584fa8d2532
venkatadri123/Python_Programs
/Sample_programs/4prod.py
154
4.34375
4
#To find product of given two numbers. x=int(input('enter first no:')) y=int(input('enter second no:')) product=x*y print("product of two no is:",product)
15f676a5c2184115148f89723a2912283baed3c2
venkatadri123/Python_Programs
/core_python_programs/prog37.py
277
3.96875
4
# To display a given string is found or not and display position no also. lst=['hari','venkey','suri','hello'] n=input('enter a string:') a=len(n) l=len(lst) for i in lst: if i==n: print('found') break else: print('not found') print(a) print('end')
9c5ca3f0af3e22d8ed74c58d8bcf0ef5dee9ade6
venkatadri123/Python_Programs
/Codesignal_programs/1add.py
120
3.71875
4
#. Write a function that returns the sum of two numbers. def add(param1, param2): c = param1+param2 return(c)
d3604b7b41e62c1cca3c162d7cbbb5810449f075
venkatadri123/Python_Programs
/100_Basic_Programs/program_41.py
392
3.96875
4
# 41. With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the # first half values in one line and the last half values in one line. def halfval(): fl=[] sl=[] tup=(1,2,3,4,5,6,7,8,9,10) l=len(tup)/2 for i in range(1,int((l)+1)): fl.append(i) for j in range(int(l+1),int(len(tup)+1)): sl.append(j) print(fl) print(sl) halfval()
01158919c0c3b66a38f8094fe99d22d9d3f53bed
venkatadri123/Python_Programs
/100_Basic_Programs/program_35.py
322
4.15625
4
# 35. Define a function which can generate a dictionary where the keys are numbers between 1 and 20 # (both included) and the values are square of keys. The function should just print the keys only. def sqrkeys(): d=dict() for i in range(1,21): d[i]=i**2 for k in d: print(k) sqrkeys()
b73338136080e4dda8026e64309e34b67926b464
venkatadri123/Python_Programs
/core_python_programs/prog21.py
120
4.0625
4
# Read the elements from the tuple and display them using for loop. mytpl=(13,20,30,40,50) for i in mytpl: print(i)
22599e6316b2e1eeade05e5d1fca3dac7916fe15
venkatadri123/Python_Programs
/100_Basic_Programs/program_76.py
241
3.90625
4
# 76.Please write a program to output a random number, which is divisible by # 5 and 7, between 0 and 200 inclusive using random module and list comprehension. import random print(random.choice([i for i in range(201) if i%5==0 and i%7==0]))
8ed9e0ff208ad57a5c44d0461bc7f9d4f5ce907a
venkatadri123/Python_Programs
/100_Basic_Programs/program_85.py
157
3.875
4
# 85. Please write a program to print the list after removing even numbers in [5,6,77,45,22,12,24]. li=[5,6,77,45,22,12,24] print([x for x in li if x%2!=0])
34eaa7eb343803aed8077aa0082256046230dcfb
venkatadri123/Python_Programs
/100_Basic_Programs/program_91.py
256
3.75
4
# 91. With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], # write a program to make a list whose elements are intersection of the above given lists. l1=set([1,3,6,78,35,55]) l2=set([12,24,35,24,88,120,155]) l1 &= l2 li = list(l1) print(li)
bc5117081a9d25c3662a71716194f57b5a46771e
venkatadri123/Python_Programs
/core_python_programs/prog2.py
190
3.921875
4
# To display result of add,sub,mul,div. a=float(input('enter value:')) b=float(input('enter value:')) c=a+b print('sum=',c) c=a-b print('sub=',c) c=a*b print('mul=',c) c=a/b print('div=',c)
b1adffe626fa1a1585012689ec2b1c01925c181c
venkatadri123/Python_Programs
/core_python_programs/prog78.py
334
4.15625
4
# Write a python program to accept values from keyboard and display its transpose. from numpy import* r,c=[int(i) for i in input('enter rows,columns:').split()] arr=zeros((r,c),dtype=int) print('enter the matrix:') for i in range(r): arr[i]=[int(x) for x in input().split()] m=matrix(arr) print('transpose:') print(m.transpose())
3625b577e1d82afc31436473149cc7ff1e3ce96c
venkatadri123/Python_Programs
/100_Basic_Programs/program_39.py
318
4.1875
4
# 39. Define a function which can generate a list where the values are square of numbers # between 1 and 20 (both included). Then the function needs to print all values # except the first 5 elements in the list. def sqrlis(): l=[] for i in range(1,20): l.append(i**2) return l[5:] print(sqrlis())
fa7b092a720e7ce46b2007341f4e70de60f8e6ca
venkatadri123/Python_Programs
/100_Basic_Programs/program_69.py
375
4.15625
4
# 69. Please write assert statements to verify that every number in the list [2,4,6,8] is even. l=[2,4,6,8] for i in l: assert i%2==0 # Assertions are simply boolean expressions that checks if the conditions return true or not. # If it is true, the program does nothing and move to the next line of code. # However, if it's false, the program stops and throws an error.
7a26e4bc77d34fd19cf4350c78f4764492d32064
venkatadri123/Python_Programs
/core_python_programs/prog83.py
250
4.25
4
# Retrive only the first letter of each word in a list. words=['hyder','secunder','pune','goa','vellore','jammu'] lst=[] for ch in words: lst.append(ch[0]) print(lst) # To convert into List Comprehension. lst=[ch[0] for ch in words] print(lst)
710af7c61665471765e13c9e73316fb5a16580c5
OrkMartin/Labs-need-work
/lab1/lab2.py
161
3.5
4
x=input() l=list(x) i2=1 mx=max(l) for i in l: if(int(i)!=int(mx)): if (int(i)>int(i2)): mx2=int(i) else: mx2=int(i2) i2=int(i) print(mx2) print()
dc1edd50a486386b3ab7464bef328be9b2a4e67e
imzhangliang/LearningToys
/python/decorator/4.arguDecorator.py
512
3.734375
4
# 参考:https://www.thecodeship.com/patterns/guide-to-python-function-decorators/ # 带参数的修饰器 def tags(tag_name): def tags_decorator(func): def func_wrapper(name): return "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags("p") def get_text(name): return "Hello "+name @tags("div") def get_text2(name): return "Hello "+name if __name__ == '__main__': print(get_text("John")) print(get_text2("John"))
82e13a62f99e125e104dc8e2d2dc13f4741e6c44
Teaching-projects/SOE-ProgAlap1-HF-2020-Fmiri08
/008/main.py
312
3.90625
4
x=0.0 y=0.0 ir=input() while ir!="stop": if ir=="forward": y=y+float(input()) if ir=="backward": y=y-float(input()) if ir=="right": x=x+float(input()) if ir=="left": x=x-float(input()) ir=input() print(round(x,2)) print(round(y,2)) origo=((x**2)+(y**2))**(1/2) print(round(origo,2))
14e530c84fedbaaa64eeae87f24fa46549b9a7da
toggame/Python_learn
/第四章/num_to_rmb.py
5,224
3.78125
4
han_list = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'] # 数值转换文本列表 unit_list = ['拾', '佰', '仟'] # 数值单位列表 # 把一个浮点数分解成整数部分和小数部分字符串 # num是需要被分解的浮点数(float) # 返回分解出来的整数部分和小数部分(str) # 第一数组元素是整数部分,第二个数组元素是小数部分 def divide(num): # 将一个浮点数强制类型转换为int类型,即可得到它的整数部分 integer_num = int(num) # 浮点减去整数部分,得到小数部分,小数部分乘以100后再取整,得到2位小数,因num参与了计算,num必须为int或float # fraction = int(round(num - integer, 2) * 100) fraction_num = round((num - integer_num) * 100) # round默认返回int,如给了小数位数,则返回值与原数据格式一致 return str(integer_num), str(fraction_num) # 把1个4位的数字字符串变成汉字字符串 # num_str是需要被转换的4位数字字符串(str) # 返回4位数字字符串被转换成汉字字符串(str) def four_to_han_str(num_str): result = '' num_len = len(num_str) # 依次遍历数字字符串的每一位数字 for i in range(num_len): num = int(num_str[i]) # 最后一位为0时,不输出 if i == num_len - 1 and num == 0: continue # 当不是最后一位且不为0时,带单位输出 elif i != num_len - 1 and num != 0: result += han_list[num] + unit_list[-(4 - num_len + i) - 1] # 当连续2个0时,推后输出 elif i < num_len - 1 and num_str[i] == num_str[i + 1] == '0': continue # 最后一位或非最后一位0时,仅输出汉字,不添加单位 else: result += han_list[num] return result # 把整数部分数字字符串变成汉字字符串 # num_str是需要被转换的数字字符串(str) # 返回数字字符串被转换成汉字字符串(str) def integer_to_str(num_str): str_len = len(num_str) n8 = (str_len - 1) // 8 + 1 result = '' for i in range(1, n8 + 1): # 5位数以下不添加'万',直接输出后四位+'圆' if str_len < 5: result += four_to_han_str(num_str[-4:]) + '圆' # 如果是最后一次遍历,不需要添加'亿' elif i == n8: # 如果-8:-4不为空,添加'万' if four_to_han_str(num_str[-8:-4]) != '': # 当为4个0时,添加零 if four_to_han_str(num_str[-8:-4]) == '0000': result += '零' + four_to_han_str(num_str[-4:]) + '圆' # 当不为'0000'时,添加'万' else: result += four_to_han_str(num_str[-8:-4]) + '万' + four_to_han_str(num_str[-4:]) + '圆' # 如果-8到-4位是空,不输出'万' else: result += four_to_han_str(num_str[-4:]) + '圆' # 其他时候遍历,当小于5位时直接添加'亿' elif str_len - 8 * (n8 - i) < 5: result += four_to_han_str(num_str[-8 * (n8 + 1 - i) + 4:-8 * (n8 + 1 - i) + 8]) + '亿' # 如果前4为不为空,输出'万' elif four_to_han_str(num_str[-8 * (n8 + 1 - i):-8 * (n8 + 1 - i) + 4]) != '': # 当为4个0时,添加'零' if four_to_han_str(num_str[-8 * (n8 + 1 - i):-8 * (n8 + 1 - i) + 4]) == '0000': result += '零' + four_to_han_str(num_str[-8 * (n8 + 1 - i) + 4:-8 * (n8 + 1 - i) + 8]) + '亿' # 当不为'0000'时,添加'万' else: result += four_to_han_str(num_str[-8 * (n8 + 1 - i):-8 * (n8 + 1 - i) + 4]) + '万' + \ four_to_han_str(num_str[-8 * (n8 + 1 - i) + 4:-8 * (n8 + 1 - i) + 8]) + '亿' # 如果前4位为空,不输出'万' else: result += four_to_han_str(num_str[-8 * (n8 + 1 - i) + 4:-8 * (n8 + 1 - i) + 8]) + '亿' # 其他遍历,位数小于5时直接添加'亿' # 当以壹拾开头时,删掉第一个'壹' if result[0:2] == '壹拾': result = result[1:] return result # 把小数部分数字字符串变成汉字字符串 # num_str是需要被转换的数字字符串(str) # 返回数字字符串被转换成汉字字符串(str) def fraction_to_str(num_str): num_len = len(num_str) # 当长度为1时(对应0.00~0.09) if num_len == 1: # 为0时,不输出小数位 if num_str == '0': return '' # 不为0时,输出零几分 else: return '零' + han_list[int(num_str[0])] + '分' # 当对应0.10、0.20、0.30…… elif num_str[1] == '0': return han_list[int(num_str[0])] + '角' else: return han_list[int(num_str[0])] + '角' + han_list[int(num_str[1])] + '分' input_num = float(input('请输入一个浮点数:')) # input_num = 10210201001.65 # 测试 integer, fraction = divide(input_num) print('转换后的结果为:%s%s' % (integer_to_str(integer), fraction_to_str(fraction))) # 当浮点数超过双浮点范围时,会自动采用科学计数,导致结果不准确
e8f50c141e2c193134af053d04e88d63ae175a8d
toggame/Python_learn
/第二章/compare_operator_test.py
908
3.625
4
import time print("5是否大于4:", 5 > 4) # True print('3的4次方是否大于或等于90:', 3 ** 4 >= 90) # False print('20是否大于或等于20.0:', 20 >= 20.0) # True print('5和5.0是否相等:', 5 == 5.0) # True print('5.2%4.1与1.1是否相等:', 5.2 % 4.1 == 1.1) # False 浮点精度将会影响值的对比 print('1和True是否相等:', 1 == True) # True 可以用数值1和True/0和False做对比,但是不建议,使用条件或bool与之对比 print('0和False是否相等:', 0 == False) # True print(True + False == True) # True 进行运算后会变成整数 print(type(True + False)) # int a = time.gmtime() b = time.localtime() c = time.gmtime() print(a) print(a.tm_zone) print(b.tm_zone) print(a == b) print(a == c) print(a is c) # 值相同,但ID不同 print(id(a), id(c)) # 通过ID判断是否相同 # > # >= # < # <= # == # != # is # is not
a25f6d70039117398ad94e101c189100393d748e
toggame/Python_learn
/第二章/bit_operator_test.py
842
3.9375
4
print(5 & 9) # 1 0b0101 & 0b1001 = 0b0001,Python默认4字节 print(bin(5 & 9)) print(5 | 9) # 13 0b0101 | 0b1001 = 0b1101 print(bin(5 | 9)) a = -5 print(a & 0xff) # 251 print(bin(a)) print(~a) # 4 负数的补码规则:反码(原码除符号位取反)加1 print(bin(~a)) # 0b100 print(~-a) # -6 5→0b0101 取反0b1010 -1→0b1001 原码0b1110 5→0b00000101 取反0b11111010 -1→0b11111001 原码0b10000110 print(bin(~-a)) # -0b110 print(5 ^ 9) # 12 0b0101 ^ 0b1001 = 0b1100 print(~0xfe) # -255 11111110 取反 00000001 -1→00000000 print("%X" % ~0xfe) # -FF print(~0xfe & 0xff) # 1 print(5 << 2) # 20 0b00000101→0b00010100,5*2^2 print(5 << 2 & 0xf) # 4 print(-5 << 2) # -20 0b10000101取反0b11111010 +1 补码0b11111011 左移2位0b11101100 -1→0b11101011 取反原码0b10010100 print(-5 >> 2) # -2,-5/4
34da97ea1abde74ef4f13ffe4216a23742ea14c9
Simsaris/COM404
/1-basics/week-3-repetition/1-while-loop/5-sum-100/bot.py
179
3.96875
4
print("calculate the sum of the first 100 numbers") count = 1 total = 0 while count <= 100: total+=count #total=total+count# count+=1 print("the total is " + str(total))
bf69b97a50aae1366ad4884ad8fa364320c29458
Simsaris/COM404
/1-basics/week-3-repetition/1-while-loop/3-ascii/bot.py
263
4.0625
4
print("how many bars shoud be charged") ChargeNeeded = int(input()) ChargedBars = 0 while (ChargedBars < ChargeNeeded): ChargedBars+=1 print("charging: " + " █ " * ChargedBars) if (ChargedBars == ChargeNeeded): print("battery is fully charged")
665de3ee810564d1001f10b23e7108f856a4a8eb
sacktock/network_summative
/client.py
10,168
3.609375
4
import socket import sys import json # Client functions def GET_BOARDS(): # construct json message message = '{"request" : "GET_BOARDS"}' while True: # make server request response = server_request(message) if response: # parse json response try: response = json.loads(response.decode()) except: # server doesn't respond with a json message print('server responded badly ... ') print('exiting ... ') sys.exit() if response['valid'] == 1: # valid response received return response elif response['valid'] == 0: # server side error print(response['error']+' error ... ') retry =input('Try again : [Y/N] ') print('exiting ... ') sys.exit() else: # server responded with unexpected json print('server responded badly no valid bit ... ') print('exiting ... ') sys.exit() else: # server didn't respond with anything print('nothing received from the server ... ') print('exiting ... ') sys.exit() def GET_MESSAGES(board_num): # construct json message message = '{"request" : "GET_MESSAGES", "board_num" : '+ str(board_num) +'}' while True: # make server request response = server_request(message) if response: try: # parse json response response = json.loads(response.decode()) except: # server doesn't respond with a json message print('server responded badly ... ') print('returning to message boards ... ') break if response['valid'] == 1: # valid response received # extract data and display messages board_title = response['board'] messages = response['messages'] print() print('Message Board :') print() print('==== '+ board_title+ ' ====') print() if messages == []: print() print('no messages ... ') print() else: for message in messages: print('----------'+'-'*(len(board_title))) print() print(parse_title(message['title'])) print() print(message['content']) print() print('----------'+'-'*(len(board_title))) print() print('=========='+'='*(len(board_title))) print() while True: # wait for user input action = input('Return to message boards : R + [Enter] , Exit : QUIT + [Enter] ') if action == 'R': print('returning to message boards ... ') break elif action == 'QUIT': print('exiting ... ') sys.exit() break elif response['valid'] == 0: # server side error print(response['error']+' error ... ') print('returning to message boards ... ') break else: # server responded with unexpected json print('server responded badly ... ') print('returning to message boards ... ') break else: # server didn't respond with anything print('nothing received from the server ... ') print('returning to message boards ... ') break return def POST_MESSAGE(board_num, msg_title, msg_content): # construct json message message = '{"request" : "POST_MESSAGE", "board_num" : '+ str(board_num) +' , "title" : "'+msg_title+'", "content" : "'+ msg_content+'"}' while True: # make server request response = server_request(message) if response: try: # parse json response response = json.loads(response.decode()) except: # server doesn't respond with a json message print('server responded badly ... ') print('returning to message boards ... ') break if response['valid'] == 1: # valid response received print('message successfully posted ... ') break elif response['valid'] == 0: # server side error print(response['error']+' error ... ') print('returning to message boards ... ') break else: # server responded with unexpected json print('server responded badly ... ') print('returning to message boards ... ') break else: # server didn't respond with anything print('nothing received from the server ... ') print('returning to message boards ... ') break return def server_request(raw_json): # create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(10) #cConnect the socket to the port where the server is listening server_address = (server_name, port) print('connecting to {} port {}'.format(*server_address)) try: sock.connect(server_address) except socket.timeout: # server timeout sock.close() print('server timeout ... ') print('exiting ... ') sys.exit() return b'' except ConnectionRefusedError: # server is unavailable sock.close() print('server is unavailable ... ') print('exiting ... ') sys.exit() return b'' response = b'' try: # send message message = str.encode(raw_json) print('sending {!r}'.format(message)) sock.sendall(message) # look for the response while True: data = sock.recv(1024) print('received {!r}'.format(data)) # construct the server response if data: response += data else: print('no more data from', server_address) break finally: # close the connection print('closing socket') sock.close() # return the server response return response def parse_title(title): # converts the given filename to a displayable title try: year = title[:4] month = str(int(title[4:6])) day = str(int(title[6:8])) hour = str(int(title[9:11])) mins = title[11:13] time = '' if int(hour) < 12: time = hour + '.'+mins+'am' else: time = str(int(hour)-12)+'.'+mins+'pm' text = title[16:] text = text.replace('_', ' ') return '"'+text+'" posted at '+time+' on '+day+' '+ get_month(int(month)) + ' '+year except: return '' def get_month(month): switcher = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December', } return switcher.get(month, '') # Main code server_name = 'localhost' port = 12000 args = sys.argv[1:] # evaluate the commandline arguments if (len(args) != 2): print ('client.py usage: python client.py <serverip> <port>') sys.exit(2) else: server_name = str(args[0]) port = int(args[1]) # call GET_BOARDS to get the boards from the server boards = GET_BOARDS()['boards'] while True: # display the message boards print() print('==== Message Boards ====') print() if boards == []: print() print('no boards ... ') print() else: i = 0 for board in boards: i += 1 print(str(i)+'. '+board) print() print('========================') print() # wait for user input user_input = input('View message board : [number] + [Enter], Post a message : POST + [Enter], Exit : QUIT + [Enter] ') if user_input == 'POST': # start the POST_MESSAGE procedure print('Posting a message requires : [board_number] [message_title] [message_content]') # get user input post_board = input('Enter [board_number] ... ') msg_title = input('Enter [message_title] ... ') msg_content = input('Enter [message_content] ... ') # try parse the board number try: board_num = int(post_board)-1 response = POST_MESSAGE(board_num, msg_title, msg_content) except ValueError: # user input is not a number print('invalid boards number ... ') print('returning to message boards ... ') elif user_input == 'QUIT': print('exiting ... ') sys.exit() else: # try parse the board number try: board_num = int(user_input) -1 GET_MESSAGES(board_num) except ValueError: # user input is not a number print('invalid board number ... ') print('returning to message boards ... ')
eb19e8d85ac5e4bf75f173c1984483d440eca8bf
ITLTVPo/SimplePython
/SimplePython/Test-Bai25.py
3,065
3.625
4
def DocSoThanhChu(): a = ["một","hai","ba","bốn","năm","sáu","bảy","tám","chín"] b = ["mốt","hai","ba","tư","lăm","sáu","bảy","tám","chín"] SoAm=False number = int(input("Nhập số bạn muốn chuyển đổi: ")) if (number <0): number = 0-number SoAm =True if (number==0): print("Không") if (number>0): if (number>0 and number<10): s=str(a[number-1]) elif (number==10): s="Mười" elif (number>10 and number<20): if (number==15): s = "Mười lăm" else: s = "Mười " + a[number%10-1] elif (number>=20): if (number%10==0): s = a[number//10-1] + " mươi " else: s = a[number//10-1] + " mươi "+ b[number%10-1] if SoAm == True: s = "Âm "+s s = s.capitalize() print("{0} đọc là: {1}".format(str(number),str(s))) def TimNgayTiepTheo(): ngay = int(input("Ngày hiện tại: ")) thang = int(input("Tháng hiện tại: ")) nam = int(input("Năm hiện tại: ")) if ((nam%400 == 0 or (nam%4 == 0 and nam//100 != 0)) and thang==2 and ngay==29): print("Ngày mai là: ngày 1 tháng 3 năm ",nam) elif (thang==2 and ngay==28): print("Ngày mai là: ngày 1 tháng 3 năm ",nam) elif (str(thang) in ("1","3","5","7","8","10","12") and ngay==31): print("Ngày mai là: ngày 1 tháng {0} năm {1}".format(thang+1, nam)) elif (str(thang) in ("4","6","11","9") and ngay==30): print("Ngày mai là: ngày 1 tháng {0} năm {1}".format(thang+1, nam)) else: print("Ngày mai là: ngày {0} tháng {1} năm {2}".format(ngay+1, thang, nam)) def PhepTinhDonGian(): print("Nhập vào hai số a và b") a = int(input("a = ")) b = int(input("b = ")) PhepToan = input("Nhập vào phép toán cộng bạn muốn sử dụng (+), trừ (-), nhân (*), chia (/) ") if PhepToan=="+": print("{} + {} = {}".format(a,b,a+b)) elif PhepToan=="-": print("{} - {} = {}".format(a,b,a-b)) elif PhepToan=="*": print("{} * {} = {}".format(a,b,a*b)) elif PhepToan=="/": if b==0: print("b phải khác 0!") else: print("{} / {} = {}".format(a,b,a/b)) while (True): x = input("""Chọn một option: 1. Chuyển đổi số sang chữ (2 chữ số) 2. Nhập vào ngày tháng năm, tìm ngày kế tiếp 3. Nhập vào a và b, chọn + - * / 4. Nhập vào một tháng, xuất ra tháng thuộc quí mấy \n""") if (x=='1'): DocSoThanhChu() elif (x=='2'): TimNgayTiepTheo() elif (x=='3'): PhepTinhDonGian() elif (x=='4'): month = int(input("Nhập vào tháng bạn muốn kiếm tra: ")) print("Tháng {0} thuộc quí: {1}".format(str(month),month//3+1)) else: print("Bạn đã nhập sai giá trị, chương trình tự động thoát...") break
770a5461e82cc2e3fda4b42a7224f8badfd20c13
ITLTVPo/SimplePython
/SimplePython/SoNgayTrongThang.py
706
3.6875
4
print("Đếm số ngày trong tháng") def KiemTraNamNhuan(month, NamNhuan): if month in (1,3,5,7,8,10,12): return 31 elif month in (4,6,9,11): return 30 elif NamNhuan==True: return 29 elif NamNhuan==False: return 28 try: while (True): print("-"*30) month = int(input("Nhập tháng bạn muốn kiểm tra: ")) year = int(input("Tháng đó nằm trong năm: ")) if (year%400==0 or (year%4==0 and year%100!=0)): print("Tháng đó có: ", KiemTraNamNhuan(month,True)) else: print("Tháng đó có: ", KiemTraNamNhuan(month,False)) except: print("Oops, something has gone wrong...")
a4c2e16bfc899de39d68175be19dba4b33d395ce
ITLTVPo/SimplePython
/SimplePython/VeChuN.py
605
3.8125
4
print("Chương trình vẽ chữ N bằng dấu * với độ cao h") while True: h = int(input("Nhập độ cao h: ")) for i in range(h): for j in range(h): if j==0 or j==i or j==h-1: print("*",end="") else: print(" ",end="") print("",end="\n") print("-"*13) i=0 j=0 while i<=h-1: while j<=h-1: if j==0 or j==i or j==h-1: print("*",end="") else: print(" ",end="") j+=1 j=0 i+=1 print("") print("-"*13)
3022a1b5402c126eac6d93f065472c21efc23a3a
dhrunlauwers/advent_2020
/day01.py
905
3.78125
4
from typing import List def parse(inputs: List[int]) -> int: """ Checks to find two elements that add up to 2020, and the returns their product. """ deltas = {2020 - i for i in inputs} for i in inputs: if i in deltas: return i * (2020-i) def parse2(inputs: List[int]): """ Checks to find three elements that add up to 2020, and the returns their product. """ deltas = {(i, j) for i in inputs for j in inputs if i != j} for x in inputs: for (i, j) in deltas: if i + j + x == 2020: return (i*j*x) EXPENSES = [ 1721, 979, 366, 299, 675, 1456 ] assert parse(EXPENSES) == 514579 assert parse2(EXPENSES) == 241861950 with open("data/day01.txt") as f: inputs = [int(line.strip()) for line in f] print("Part 1: ", parse(inputs)) print("Part 2: ", parse2(inputs))
516507efc6764f24f12843468fce2919690d2c09
IshitaG-2002IGK/streamlit-jina
/app.py
1,224
3.578125
4
""" pclass = 1|2|3 gender = 'male'=1,'female'=0 age = 1-60 sibsp = 1|0 parch = 1|0 fare = 0-100 embarked = 1|0 """ import business import streamlit as st pclass_list = [1,2,3] gender_list = ['male','female'] gender = 1 pclass = st.selectbox( 'Passenger Class', pclass_list) gender_str = st.selectbox( 'Gender', gender_list) age = st.slider('AGE', 1, 60) y_n = ['yes','no'] sibsp = st.selectbox( "siblings or spouse", y_n ) parch = st.selectbox( "parents or children", y_n ) embarked = st.selectbox( "boarding location ", ["england","new-york"] ) fare = st.slider('Fare', 0, 350) def yes_no(y_n_str): if y_n_str == 'yes': return 1 return 0 if gender_str == 'female': gender = 0 sibsp = yes_no(sibsp) parch = yes_no(parch) embarked = 1 if embarked == 'england' else 0 data = [[ pclass, gender, age, sibsp, parch, fare, embarked ]] predict = st.button("Predict") if predict: pred = business.predict(data) if pred: st.write("Congrats, you have survived!") else: st.write("Oops, you died!") if __name__ == '__main__': print("RUN : streamlit run app.py")
daea1cb549638923f92a0939fc06687b96e74ef9
Vineeth-Agarwal/FileSortingByNumericField-Northwest
/Sort_By_Numeric_Field.py
1,262
3.921875
4
##### Step0: Open input and output files and create empty lists. input=open("InputFile.txt","r") output=open("OutputFile.txt","w") tupples_array = [] sorted_array = [] ##### Step1: Read each line traditionally(as a String) for line in input: ##### Step2: Break each field in the line separated by comma, into individual variables. data=line.strip().split(",") field_one,field_two,field_three=data ##### Step3: Create a tuple of all fields. While adding each field, convert string into numeric field 'int' or 'float' as necessary. tupple=(int(field_one),field_two,field_three) ##### Step4: Add or append the tuple to a list. tupples_array.append(tupple) ##### Step5: Repeat the process until all the lines are read and added to the list. ##### Step6: Write the new sorted function to sort by numeirc field, rather than traditional string sorting. sorted_array=(sorted(tupples_array, key=lambda array_elements: array_elements[0])) ##### Step7: Write the newly sorted list to output file in same format or any desired format. output.write("\n".join('%s, %s, %s' % new_array_elements for new_array_elements in sorted_array)) ##### Step8: Close the input and output files. input.close() output.close()
b1c41d7bfbc80bdd15642bcb0f02291c7867779e
ProgrammingForDiscreteMath/20170830-bodhayan
/code.py
700
4.15625
4
# 1 # Replace if-else with try-except in the the example below: def element_of_list(L,i): """ Return the 4th element of ``L`` if it exists, ``None`` otherwise. """ try: return L[i] except IndexError: return None # 2 # Modify to use try-except to return the sum of all numbers in L, # ignoring other data-types def sum_of_numbers(L): """ Return the sum of all the numbers in L. """ s = 0 for l in L: try: s+= l except TypeError: pass return s # TEST # print sum_of_numbers([3, 1.9, 's']) == 4.9 # L1 = [1,2,3] # L2 = [1,2,3,4] # print fourth_element_of_list(L1) # print fourth_element_of_list(L2)
d442a0ed9a4a4c5d9a6b94b69ea39bb8ead21a3c
andrSHoi/biosim_G07_sebastian_andreas
/src/biosim/island_class.py
6,174
4.25
4
# -*- coding: utf-8 -*- __author__ = "Sebastian Kihle & Andreas Hoeimyr" __email__ = "[email protected] & [email protected]" from .geography import Mountain, Savannah, Jungle, Desert, Ocean, \ OutOfBounds import numpy as np import re class Map: """ The Map class takes a multiline string as input and creates a numpy array of it. The numpy array will contain one letter in each position and is saved as biome_map. The biome_map is then used to create a numpy array of class instances named array_map. This is done with a dictionary. Each position in the biome_map is a single letter string. In the dictionary(biome_dict) the string is a key with a class instance as a value. The class instances in the dictionary are the different classes defined in the geography file. E. g. if a position in the biome_map is 'J' it will be the class Jungle in the array_map. The Map class also checks that the input string fulfills certain criteria. Each row of the multiline string must have the same amount of letters, else a ValueError is raised. The string can only contain the letters which has corresponding classes. This is checked using ``regular expression``. As of now the only legal letters are J, D, S, O and M, corresponding to the biomes Jungle, Desert, Savannah, Ocean and Mountain. If there are different letters in the input string a ValueError is raised. It checks that the string gives a map where all edge cells are ocean, if not a ValueError is raised. See ``Examples`` for an example of an accepted input string. :param: A multiline string with letters J, S, D, O, M """ def __init__(self, island_multiline_sting): self.island_multiline_sting = island_multiline_sting self.x = 0 self.y = 0 self.top = OutOfBounds() self.bottom = OutOfBounds() self.left = OutOfBounds() self.right = OutOfBounds() # Splits the multiline string and converts it into an array. area = self.island_multiline_sting.split() string_map = [[cell for cell in string] for string in area] self.biome_map = np.array(string_map) # Checks that all lines in the multiline string map are as long as # the first line. reference_length = len(self.biome_map[0]) for lines in self.biome_map: if len(lines) != reference_length: raise ValueError('All lines in map must me same length') # Using regular expression to check if all letters in input string # are defined for this island. if re.fullmatch(r"[OMDJS\n]+", island_multiline_sting) is None: raise ValueError('Map contains biome not defined for this island') # Verifies that cells on the edge of the map are ocean biomes. for cell in self.biome_map[0]: if not cell == 'O': raise ValueError('Edge of map must be ocean') for cell in self.biome_map[-1]: if not cell == 'O': raise ValueError('Edge of map must be ocean') for cell in self.biome_map.T[0]: if not cell == 'O': raise ValueError('Edge of map must be ocean') for cell in self.biome_map.T[-1]: if not cell == 'O': raise ValueError('Edge of map must be ocean') # Converts array elements from strings to object instances self.array_map = np.array(string_map, dtype=object) self.biome_dict = {'O': Ocean, 'D': Desert, 'J': Jungle, 'M': Mountain, 'S': Savannah} for row in range(self.array_map.shape[0]): for col in range(self.array_map.shape[1]): self.array_map[row, col] = self.biome_dict[self.array_map[ row, col]]() def map_iterator(self): """ The map_iterator method iterates through each cell in array_map. self.x is used to iterate through columns in array_map, and self.y is used to iterate through the rows in self.array_map(numpy array with class instances in each position). Yields the object in the current cell of the map. The yield allows the code to produce a series of cells over time, rather than computing them at once and sending them back like a list. Each time the map_iterator is called the values of x and y are reset to zero. The iterator then yields each cell until it has yielded each cell in the array_map. The map_iterator saves the surrounding cells around the current cell. If the current cell is on the edge of the map, the neighbouring cell outside the map is set to be OutOfBounds cell. These neighbouring cells are stored and used when animals migrate. :yields: Object in current cell. """ # Starts in top left corner of map. self.x = 0 self.y = 0 # For each cell in the map yields the object. while True: if self.y >= 1: self.top = self.array_map[self.y-1, self.x] else: self.top = OutOfBounds() if self.y < len(self.biome_map.T[0]) - 1: self.bottom = self.array_map[self.y+1, self.x] else: self.bottom = OutOfBounds() if self.x >= 1: self.left = self.array_map[self.y, self.x-1] else: self.left = OutOfBounds() if self.x < len(self.biome_map[0]) - 1: self.right = self.array_map[self.y, self.x+1] else: self.right = OutOfBounds() # Use yield to be able to iterate through the map. yield self.array_map[self.y, self.x] self.x += 1 # When it reaches the end of the row, start at the first column, # second row. if self.x >= len(self.biome_map[0]): self.y += 1 self.x = 0 # Stops when reaching bottom right cell of the map. if self.y >= len(self.biome_map.T[0]): return
350b8d465f906a49e22669171c8eb47fa533383c
zxch3n/Leetcode
/53/main.py
565
3.6875
4
# -*- coding: utf-8 -*- """ @author: Rem @contack: [email protected] @time: 2017/03/14/ 20:58 """ __author__ = "Rem" class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ max_ans = nums[0] t = nums[0] for i in range(1, len(nums)): if t < 0: t = nums[i] else: t = nums[i] + t if t > max_ans: max_ans = t return max_ans s = Solution() print(s.maxSubArray([-1,-2,9,-3,5,6,-1]))
edc611b56aacab9f4b6602b233ce9f3e759bce16
ahdabalhassani/udacity_project2
/starter_code.py
4,817
3.84375
4
import random moves = ['rock', 'paper', 'scissors'] class Player: def __init__(self): self.score = 0 def move(self): return 'rock' def learn(self, their_move): pass def beats(one, two): return ((one == 'rock' and two == 'scissors') or (one == 'scissors' and two == 'paper') or (one == 'paper' and two == 'rock')) class HumanPlayer(Player): def __init__(self): Player.__init__(self) def move(self): human_move = input("What's your move? xx ").lower() while human_move not in moves: human_move = input("What's your move? ").lower() return human_move class RandomPlayer(Player): def __init__(self): Player.__init__(self) def move(self): return random.choice(moves) class ReflectPlayer(Player): def __init__(self): self.index = -1 def learn(self, their_move): self.their_move = their_move def move(self): self.index += 1 if self.index == 0: return random.choice(moves) else: return self.their_move class CyclerPlayer(Player): def __init__(self): Player.__init__(self) self.index = -1 def move(self): self.index += 1 if self.index % 3 == 0: return "rock" elif self.index % 3 == 1: return "paper" else: return "scissors" class Game: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.score1 = 0 self.score2 = 0 def play_round(self): move1 = self.p1.move() move2 = self.p2.move() self.p2.learn(move1) print(f"Player 1: {move1} Player 2: {move2}") if move1 == move2: print(" \n ----- No winner :( -----\n") elif beats(move1, move2): print(" \n ----- Player 1 WINS :) ----- \n") self.score1 += 1 else: print(" \n ----- Player 2 WIN :) -----\n") self.score2 += 1 print(f"plyer 1 score = {self.score1}") print(f"plyer 2 score = {self.score2}") def play_game(self): print(f"\n*........*\nGame start!\n*........*\n") while True: rounds = (input('How many rounds do you want to play? ')) if rounds.isnumeric(): for round in range(int(rounds)): print(f"\n..........\n Round {round}\n..........\n") self.play_round() print(f"\n..........\n Game over!\n..........\n") else: print('PLEASE TYPE AGAIN NUMBER ONLY .') continue if __name__ == '__main__': while True: choice = input("************** " "Welcome to AHDAB Rock-Paper-Scissors based Games " "******************" "\n************************" "***************************" "****************************" "\n* " "OPTIONS " " *" "\n*************************" "*****************************" "*************************" "\n* [1] - Random " " " " *" "\n* [2] - Reflect " " " " *" "\n* [3] - Cycler " " " " *" "\n* [4] - Exit " " " " *" "\n**************************" "******************************" "***********************" "\n Please select an option (1, 2, 3 or 4): ") if choice == "4": print("Goodbye .") quit() elif choice == "1": game = Game(HumanPlayer(), RandomPlayer()) game.play_game() break elif choice == "2": game = Game(HumanPlayer(), ReflectPlayer()) game.play_game() break elif choice == "3": game = Game(HumanPlayer(), CyclerPlayer()) game.play_game() break else: print("WRONG INPUT!!!! PLEASE WRITE AGAIN") choice = input("What's your option? --")
650217c072d3380afd569106d224da0527f4799c
khc-data/advent-of-code-2020
/2020/max/day2/solve.py
1,711
3.921875
4
from collections import namedtuple import re PasswordPolicy = namedtuple('PasswordPolicy', 'lower upper char') PasswordWithPolicy = namedtuple('PasswordWithPolicy', 'password password_policy') def read(): passwords_with_policies = [] with open('input') as input: for line in input: (lower, upper, char, password) = re.findall('(\d+)-(\d+) ([a-z]): ([a-z]+)', line)[0] password_policy = PasswordPolicy( int(lower), int(upper), char ) passwords_with_policies.append( PasswordWithPolicy( password, password_policy ) ) return passwords_with_policies def process(passwords_with_policies, is_valid_password): valid_passwords = 0 for password_with_policy in passwords_with_policies: if is_valid_password(password_with_policy.password, password_with_policy.password_policy): valid_passwords += 1 return valid_passwords def is_valid_password_part1(password, password_policy): matches = re.findall(password_policy.char, password) return len(matches) >= password_policy.lower and len(matches) <= password_policy.upper def is_valid_password_part2(password, password_policy): return (password[password_policy.lower - 1] == password_policy.char) ^ (password[password_policy.upper -1] == password_policy.char) def main(is_valid_password): input_list = read() return process(input_list, is_valid_password) if __name__ == '__main__': print(f'Part 1: {main(is_valid_password_part1)}') print(f'Part 2: {main(is_valid_password_part2)}')
6de74047e9f7509207bea000f4dd00268077f239
khc-data/advent-of-code-2020
/2020/max/day12/ferry.py
1,394
3.9375
4
class Ferry: def __init__(self): self.dir = 'E' self.x = 0 self.y = 0 def manhattan(self): return abs(self.x) + abs(self.y) def handle_instruction(self, instruction): self.handle_action(instruction[0], instruction[1]) def handle_action(self, action, dist): # Action N means to move north by the given value. # Action S means to move south by the given value. # Action E means to move east by the given value. # Action W means to move west by the given value. # Action L means to turn left the given number of degrees. # Action R means to turn right the given number of degrees. # Action F means to move forward by the given value in the direction the ship is currently facing. if action == 'N': self.y += dist elif action == 'S': self.y -= dist elif action == 'E': self.x += dist elif action == 'W': self.x -= dist elif action == 'L': self.turn(-1 * dist) elif action == 'R': self.turn(dist) elif action == 'F': self.handle_action(self.dir, dist) def turn(self, angle): steps = int((angle % 360) / 90) dirs = ['N', 'E', 'S', 'W'] self.dir = dirs[ ( dirs.index(self.dir) + steps ) % 4 ]
030214bcbe1123ef751976731feacbd614eca0b2
planetblix/learnpythonthehardway
/ex17a.py
1,230
3.9375
4
#!/bin/python #http://blog.amir.rachum.com/blog/2013/10/10/python-importing/ #using os.path as an example import os import os.path from os.path import exists from os.path import exists, dirname from os.path import * from os.path import exists as here from .os import exists os.path = __import__("os.path") reload(foo) #import os #-loads os module into memory #-to view the directories that get searched for modules #import sys #print sys.path #import os.path #-imports the object os.path only, other objects are not accessible directly. #from foo import bar #-Here bar is an object, an object could be: #function definition #class #submodule #from foo import bar, baz #bar and baz can be different types #from foo import * #bad practice - contiminates the global namespace #from foo import bar as fizz #this makes a nice namespace when objects are similiarly spelt #when importing from different modules #Also useful to rename object names, to maybe more meaingful ones #from .foo import bar #doesn't check PYTHONPATH if you've got a local copy of the module #can also do ..foo import bar #also ...foo import bar #foo = __import__("foo") #import a module dynamically, must be assigned to a variable #to be accessible
b6834d2bf0af216c26a7a2b92880ab566685caea
planetblix/learnpythonthehardway
/ex16.py
1,436
4.40625
4
#/bin/python from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Open the file..." #rw doesn't mean read and write, it just means read! #You could open the file twice, but not particularly safe, #As you could overwrite the file. target = open(filename, 'r+') #Other file modes: #'r' - open for read only #'r+' - open for read and write, cannot truncate #'rb - reading binary #'rb+ - reading or writing a binary file #'w' - open for write only #'w+' - open fo read and write, can truncate #'a' - open for append only #'a+' - open for reading and writing. #'U' - opens file for input with Universal newline input. #Based on C fopen(): http://www.manpagez.com/man/3/fopen/ #Nice examples here: http://www.tutorialspoint.com/python/python_files_io.htm print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1:") line2 = raw_input("line 2:") line3 = raw_input("line 3:") print "I'm going to write these to the file." #target.write(line1) #target.write("\n") #target.write(line2) #target.write("\n") #target.write(line3) #target.write("\n") target.write("%s\n" % line1) target.write("%s\n" % line2) target.write("%s\n" % line3) print target.read() print "And finally, we close it." target.close()
606294b3e5cf05889729aab4670e9c04c208b98b
wardm5/Data-Structures-and-Algorithms
/Python/Data_Structures/LinkedList/LinkedList.py
1,699
3.875
4
from Data_Structures.Node.Node import * class LinkedList(): # initalize with no value def __init__(self): self.head = None self.count = 0 # initalize with first value def __init__(self, value): self.head = Node(value) self.count = 1 def add(self, value): if (self.head == None): self.head = Node(value) else: prior = self.head while (prior.next != None): prior = prior.next prior.next = Node(value) self.count = self.count + 1 return True def remove(self, value): prior = None curr = self.head if (curr != None): if (curr.val == value): self.head = curr.next self.count = self.count - 1 return while(curr != None): if (curr.val == value): prev.next = curr.next return True self.count = self.count - 1 return prev = curr curr = curr.next return False def contains(self, value): prior = self.head while (prior != None): if (prior.val == value): return True prior = prior.next return False def clear(self): self.head = None self.count = 0 return True def print(self): if (self.head == None): print("Warning, nothing in list.") return else: prior = self.head while (prior != None): print(prior.val, "", end="") prior = prior.next print("")
37808545149f98fdff61b285857b2e63a42fad97
matthewgplace/Projects
/ex5p19MP.py
4,498
3.859375
4
""" Author: Matthew Place Date: December 6, 2017 (Although actually coded sometime in September, I think) Exercise 5.19 part a through part e i. I never got around to e ii. This program simulates light going through a transmission diffraction grating, going through a converging lens, and then hitting a screen. It creates a density plot of the resulting interference pattern by using computational integration techniques. """ from __future__ import division from pylab import show, imshow, hot from numpy import sin, pi, sqrt, empty from cmath import exp """ Part a) Here, we need to understand that u is the distance from the central axis, and if we let u = d = the slit spacing the find when sin(ad) = 0 note, a is alpha here. sin(ad) = 0 when au = n*pi. n can be any integer, we will let it be 1 here for simplicity. So a = pi/d So our transmission function becomes sin^2(u*pi/d) with d being the slit spacing and u is our position from the center axis. """ xwidth = 0.1 #The screen is 10 cm by 10 cm, so this xwidth will represent that. dx = 0.0001 #This is our step size as we move from left to right and making #our density plot of the screen. points = xwidth/dx #This gives us the total number of grid points along any #of the sides of the screen. d = 2e-5 #slit separation in meters (20 micrometers) slits = 10 #total number of slits on the diffraction grating w = slits*d #total width of the diffraction grating wave = 500e-9 #wavelength of the incoming light, in meters. focus = 1 #focal length of the converging lens xdplot = empty([points, points], float) #an empty array which serves as our #eventual density plot n = 100 #slices for Simpson's integration later, making this number too low #actually has quite drastic effects on the density plot. Try making it 30. #Part c) I chose 100 since making it much higher has negligible effects on the #density plot, but making it lower you can start to see the differences. Also, #100 is a nice round number. I chose Simpson's Method at the time of #programming this because it is what I knew, primarily. It is also nice and fast. def transmissionfunc1(u): func = sin((pi*u)/d)**2 return func #this is the function for part b def transmissionfunc2(u): func = sin((pi*u)/d)**2*sin((pi*u)/(2*d))**2 return func #this is the function for part e i. def intensityfunc(u): func = sqrt(transmissionfunc1(u))*exp((1j*2*pi*x*u)/(wave*focus)) return func #This is the integrand from the intensity function given in the problem. #Now we have a function for taking an integration via Simpson's method. #This method is a technique from chapter 5. def integrate(f, a, b, N): h = (b-a)/N k = 0 s = a+h for i in range(1, int(N/2+1)): k += 4*f(s) s += 2*h s = a+2*h for i in range(1, int(N/2)): k += 2*f(s) s += 2*h return (h/3)*(f(a)+f(b)+k) x = -xwidth/2 #Now we will be checking each horizontal point from the left #edge of our screen, located at a position of -xwidth/2, all the way to #the other edge, located at a position of xwidth/2. We have centered the screen #so that our density plot has the center of the image being where the origin #is located. #Note: Since the pattern only varies along the horizontal, once we have our #intensity at an x-position here, we can then just set that same intensity all #along that vertical line in the density plot. Our interference pattern will be #vertical lines. while x <= xwidth/2: #First, we calculate the intensity at this given x point, given our integration #limits of -w/2 to w/2, making sure to square the absolute value of it, as shown #in the problem. We use 100 slices, as that is enough here. #Note, change intensityfunc to intensityfunc2 in order to see part e i. I = abs(integrate(intensityfunc, -w/2, w/2, n))**2 #Now that we have the intensity at this point, we will set every other value #along the vertical (array column) to this same intensity value. Remembering #that our interference pattern has vertical lines for p in range(int(points-1)): xdplot[p, int((x+xwidth/2)*(1/dx))] = I x+=dx #Now we plot our density plot, making sure to set its extent so that the screen #is centered at the origin. imshow(xdplot, origin="lower", extent=[-xwidth/2, xwidth/2, -xwidth/2, xwidth/2]) hot() show()
caa1c6539841f07e7acaf8dfc0e5d9d17a972ff7
matthewgplace/Projects
/ex7p1mp.py
1,887
4.0625
4
""" Author: Matthew Place Date: November 7, 2017 Exercise 7.1 This program is designed to calculate the coefficients in the discrete Fourier transforms of a few functions and make a plot of these values """ from __future__ import division from numpy import zeros from cmath import exp, pi, sin from pylab import plot, show, xlim, title n = 1000 #number of points sampled square = [] #these three lists are for holding our different shaped functions saw = [] #where the functions are going to be just collections of points modsine = [] def dft(y): #the discrete fourier transform function from the book page 296 N = len(y) c = zeros(N//2+1,complex) for k in range(N//2+1): for n in range(N): c[k] += y[n]*exp(-2j*pi*k*n/N) return c #Now, we must create our three different waveforms which will be used for #calculating the dft of. for i in range(0, n-1): #The next if statement creates a square wave with amplitude 1 if i < 500: square.append(1) else: square.append(-1) saw.append(i) #The book says it wants a sawtooth wave with y[n]=n, so this #saw list will do just that, creating a diagonal line of points. modsine.append(sin((pi*i)/n)*sin((20*pi*i)/n)) #this creates our #modulated sine wave. #Now, we next perform our discrete fourier transform using whichever waveform #we want. In this case, I have chosen the square one since it is the most #interesting of the three. u = dft(square) plot(abs(u)) #we plot the absolute value of the dft since many of the coefficients #are complex. xlim(0, 20) #Here, we set our xlim to just go to 20 so we can see what the dft #actually looks like up close, in this case. title("Discrete Fourier Transform of a Square Wave") show()
bd225d8181acc7cecb070f5c91a778475d5117d9
ninjafrostpn/PythonProjects
/Writer.py
1,319
3.59375
4
__author__ = 'Charlie' from random import randint as rand text = "" while True: textin = input("Input text for imitation (or @ when done)\n>> ") if textin != "@": text += textin text += " " else: break words = text.split(" ") links = dict() tuples = dict() sanity = int(input("Input sanity level of mimicry\n>> ")) for i in range(len(words)): # i2 = (i+1) % len(words) # link = links.get(words[i], []) # if len(link) == 0: # links[words[i]] = [words[i2]] # else: # links[words[i]].append(words[i2]) key = tuple([words[j % len(words)] for j in range(i, i + sanity)]) tup = tuples.get(key, ()) if len(tup) == 0: tuples[key] = [words[(i + sanity) % len(words)]] print(key) else: tuples[key].append(words[(i + sanity) % len(words)]) print(links) print(tuples) while True: no = int(input("How many words?\n>> ")) - 1 wordtup = list(list(tuples.keys())[rand(0, len(tuples))]) gen = " ".join(list(wordtup)) + " " for i in range(sanity, no): choices = tuples[tuple(wordtup)] word = choices[rand(0, len(choices) - 1)] gen += word if i % 10 == 0: gen += "\n" else: gen += " " wordtup.append(word) wordtup.pop(0) print(gen)
eb60fc70191ca84f28abc5349263bfbc0702a556
ninjafrostpn/PythonProjects
/BehaviouralEcology/Shoal/CouzinShoal3D.py
10,920
3.6875
4
# Based on Couzin et al. (2002), but as a 2D simulation import pygame from pygame.locals import * import numpy as np from time import sleep debug = False # If True, shows zones of detection and allows their alteration with mouse position # Interface initialisation pygame.init() w = 200 screen = pygame.display.set_mode((w * 2, w * 2)) panel_xy = pygame.Surface((w, w)) panel_zy = pygame.Surface((w, w)) panel_xz = pygame.Surface((w, w)) keys = set() # For keypress detection font = pygame.font.Font(None, 30) # Set simulation parameters N = 100 # Number of fish s = 10 # Speed of fish (px per time unit) T = 0.1 # Timestep (time units per cycle) alpha = 270 # Visual range of fish (degrees, centred on front of fish) theta = 40 # Turning speed of fish (degrees per time unit) r_r = 2 # Outer radius of Zone of Repulsion r_o = 6 # Outer radius of Zone of Orientation r_a = 34 # Outer radius of Zone of Attraction # The position vectors, c, and unit direction vectors, v, of the fish c = (0.5 + np.random.random_sample((N, 3))) * w / 2 # Initialise positions in middle 1/8 of volume v = np.float32([np.sin([ang + np.pi/2, ang, ang - np.pi/2]) for ang in (np.random.random_sample(N) * (np.pi * 2))]) v = (v.T / np.linalg.norm(v, axis=1)).T # Normalisation. There's a lot of this in this program. # A pair of arrays, covering every possible non-self interaction combination # - pairs[0] are used as the fish doing the detecting, generally called fish i # - pairs[1] are used as the fish being detected, generally called fish j pairs = np.nonzero(np.tri(N, dtype="bool") ^ ~np.tri(N, k=-1, dtype="bool")) while True: if debug: mpos = np.int32(pygame.mouse.get_pos()) # The widths of the Zones of Orientation and Attraction are set by mouse x and y r_o = r_r + (mpos[0] / 10) r_a = r_o + (mpos[1] / 10) # CODE FOR DEBUGGING ANGLE CHECKING ETC (NB, always check your units!) d1 = np.float32([[1, 0, 0], ]) # The vector being turned d2 = np.float32([[*mpos, 0], ]) / np.linalg.norm(mpos) # The vector being turned towards ang_turn = np.arctan2(np.linalg.norm(np.cross(d1, d2), axis=1), np.einsum('ij, ij->i', d2, d1)) mask_close = np.abs(ang_turn * (180 / np.pi)) < theta * T d1[mask_close] = d2[mask_close] d_perp = np.cross((np.cross(d1[~mask_close], d2[~mask_close])), d1[~mask_close]) d_perp = (d_perp.T / np.linalg.norm(d_perp, axis=1)).T v_new = (np.cos(theta * T * (np.pi / 180)) * d1[~mask_close]) + (np.sin(theta * T * (np.pi / 180)) * d_perp) d1[~mask_close] = v_new # The vector pointing from each fish i to each fish j r_ij = c[pairs[1]] - c[pairs[0]] # Full vector r_ij_abs = np.linalg.norm(r_ij, axis=1) # Distance r_ij_norm = (r_ij.T / r_ij_abs).T # Normalised vector # The angle between the direction of travel for fish i and the line of sight from i to j ang_vis = np.arctan2(np.linalg.norm(np.cross(r_ij_norm, v[pairs[0]]).reshape(r_ij.shape[0], -1), axis=1), np.einsum('ij, ij->i', r_ij_norm, v[pairs[0]])) # Mask (for the pair arrays) that singles out the pairings where fish i can see fish j # (einsum here takes the dot product of each pair of corresponding vectors very quickly) mask_visible = alpha / 2 > np.abs(ang_vis * (180 / np.pi)) # Mask (for the pair arrays) that singles out the pairings where fish j is in fish i's zone of repulsion mask_zor = mask_visible & (r_ij_abs < r_r) # Generating the mask (for the pair arrays) that singles out fish i which have either: # - a tank wall in their repulsion zone (this is not in the model as per the paper) # - any fish in their repulsion zone mask_mode_r = np.zeros(r_ij_abs.shape, dtype="bool") # Masks (for the list of all fish i) that single out: mask_toplft = np.any(c < r_r, axis=1) # those close to the top or left walls mask_btmrgt = np.any(c > w - r_r, axis=1) # those close to the bottom or right walls # Fills in mask_mode_r with all the fish satisfying any of these conditions for i in set(pairs[0][mask_zor]): mask_mode_r |= (pairs[0] == i) | mask_toplft[pairs[0]] | mask_btmrgt[pairs[0]] # Masks (for the pair arrays) that single out pairings where fish j is in fish i's mask_zoo = mask_visible & ~mask_mode_r & (r_ij_abs < r_o) # Zone of Orientation mask_zoa = mask_visible & ~mask_mode_r & ~mask_zoo & (r_ij_abs < r_a) # Zone of Attraction # Generating the unit direction vectors representing the direction fish i would like to go d_i = np.zeros((N, 3)) # Generating unit direction vectors for repulsion d_r = np.zeros((N, 3)) d_r[pairs[0][mask_zor]] -= r_ij_norm[mask_zor] # (These must be redone separately to mask_topleft etc, else the fish move on a certain diagonal away from walls) d_r[c < r_r] += 1 d_r[c > w - r_r] -= 1 d_r[pairs[0][mask_zor]] = (d_r[pairs[0][mask_zor]].T / np.linalg.norm(d_r[pairs[0][mask_zor]], axis=1)).T d_i += d_r # Generating unit direction vectors for orientation d_o = np.zeros((N, 3)) d_o[pairs[0][mask_zoo]] += v[pairs[1][mask_zoo]] d_o[pairs[0][mask_zoo]] = (d_o[pairs[0][mask_zoo]].T / np.linalg.norm(d_o[pairs[0][mask_zoo]], axis=1)).T d_i += d_o # Generating unit direction vectors for orientation d_a = np.zeros((N, 3)) d_a[pairs[0][mask_zoa]] += r_ij_norm[mask_zoa] d_a[pairs[0][mask_zoa]] = (d_a[pairs[0][mask_zoa]].T / np.linalg.norm(d_a[pairs[0][mask_zoa]], axis=1)).T d_i += d_a # Mask (for the list of all fish i) that singles out all the fish i with zero vectors as their intended direction mask_zeroes = np.all(d_i == 0, axis=1) # Setting zero vectors to be the same direction the fish is currently going d_i[mask_zeroes] = v[mask_zeroes] # Ensure normalisation of all of the intended direction vectors # (Takes care of fish i with fish in both their Zones of Orientation and Attraction) d_i = (d_i.T / np.linalg.norm(d_i, axis=1)).T # The angle between each fish i's current and intended directions ang_turn = np.arctan2(np.linalg.norm(np.cross(v, d_i), axis=1), np.einsum('ij, ij->i', v, d_i)) # Mask (for the list of all fish i) that singles out fish i who can cover their intended turn in one timestep mask_close = np.abs(ang_turn * (180/np.pi)) < theta * T # Turns said fish (but doesn't bother with fish who aren't turning at all) v[mask_close & ~mask_zeroes] = d_i[mask_close & ~mask_zeroes] # Current and new cardinal direction angle for fish i which can't cover their intended turn in one timestep d_perp = np.cross((np.cross(v[~mask_close & ~mask_zeroes], d_i[~mask_close & ~mask_zeroes])), v[~mask_close & ~mask_zeroes]) mask_antiparallel = np.all(d_perp == 0, axis=1) if np.any(mask_antiparallel): u1 = np.float32([v[~mask_close & ~mask_zeroes][mask_antiparallel][:, 1], -v[~mask_close & ~mask_zeroes][mask_antiparallel][:, 0], np.zeros(np.sum(mask_antiparallel))]).T mask_fail = np.all(u1 == 0, axis=1) u1[mask_fail] = np.float32([v[~mask_close & ~mask_zeroes][mask_antiparallel][mask_fail][:, 2], np.zeros(np.sum(mask_fail)), -v[~mask_close & ~mask_zeroes][mask_antiparallel][mask_fail][:, 0]]).T u2 = np.cross(v[~mask_close & ~mask_zeroes][mask_antiparallel], u1) ang_rand = np.pi * 2 * np.random.random_sample(np.sum(mask_antiparallel)) d_perp[mask_antiparallel] = ((np.cos(ang_rand) * u1.T) + (np.sin(ang_rand) * u2.T)).T d_perp = (d_perp.T / np.linalg.norm(d_perp, axis=1)).T v_new = (np.cos(theta * T * (np.pi / 180)) * v[~mask_close & ~mask_zeroes]) + \ (np.sin(theta * T * (np.pi / 180)) * d_perp) # Turns these fish v[~mask_close & ~mask_zeroes] = v_new c += v * s * T # Movement of all fish i in the direction of v at speed s over one timestep, T c = np.minimum(np.maximum(c, 0), w) # But stop them at the screen edge # Drawing things screen.fill(0) panel_xy.fill(0) panel_zy.fill(0) panel_xz.fill(0) colours = (255 / w) * c colours = [np.int32([255 - colours[:, i], np.zeros(N), colours[:, i]]).T for i in range(3)] for i in range(N): # Draw the fish, approximated as pink circles pygame.draw.circle(panel_xy, colours[2][i], np.int32(c[i, :2]), int((w - c[i, 2]) / 100) + 2) pygame.draw.circle(panel_zy, colours[2][i], np.int32(c[i, 2:0:-1]), int(c[i, 0] / 100) + 2) pygame.draw.circle(panel_xz, colours[2][i], np.int32(c[i, ::2]), int(c[i, 1] / 100) + 2) # Draw the direction the fish is going (white) and wants to go (turquoise) pygame.draw.line(panel_xy, (255, 255, 255), c[i, :2], c[i, :2] + (v[i, :2] * 10)) pygame.draw.line(panel_xy, (0, 255, 255), c[i, :2], c[i, :2] + (d_i[i, :2] * 10)) pygame.draw.line(panel_zy, (255, 255, 255), c[i, 2:0:-1], c[i, 2:0:-1] + (v[i, 2:0:-1] * 10)) pygame.draw.line(panel_zy, (0, 255, 255), c[i, 2:0:-1], c[i, 2:0:-1] + (d_i[i, 2:0:-1] * 10)) pygame.draw.line(panel_xz, (255, 255, 255), c[i, ::2], c[i, ::2] + (v[i, ::2] * 10)) pygame.draw.line(panel_xz, (0, 255, 255), c[i, ::2], c[i, ::2] + (d_i[i, ::2] * 10)) # Display the panels representing each side of the tank screen.blit(panel_xy, (0, 0)) screen.blit(panel_zy, (w, 0)) screen.blit(panel_xz, (0, w)) # Draw lines between panels pygame.draw.line(screen, (255, 255, 255), (0, w), (w * 2, w), 3) pygame.draw.line(screen, (255, 255, 255), (w, 0), (w, w * 2), 3) # Display the parameters used in the model textlines = ["N = {}".format(N), "α = {}° θ = {}°".format(alpha, theta), "T = {} s = {}".format(T, s), "----------------", "Δr_r = {}".format(r_r), "Δr_o = {}".format(r_o - r_r), "Δr_a = {}".format(r_a - r_o)] for i, textline in enumerate(textlines): text = font.render(textline, True, (255, 255, 255)) screen.blit(text, (w + 10, w + 10 + i * 26)) if debug: # For angle calculation checking pygame.draw.line(screen, (255, 0, 0), (0, 0), np.int32(d2[0, :2] * 100), 3) pygame.draw.line(screen, 255, (0, 0), np.int32(d1[0, :2] * 100), 3) pygame.display.flip() # Event handling for e in pygame.event.get(): if e.type == QUIT: quit() elif e.type == KEYDOWN: keys.add(e.key) if e.key == K_ESCAPE: quit() elif e.type == KEYUP: keys.discard(e.key)
89a4cab84879c77e5ded99c23667abc5daf6154b
ninjafrostpn/PythonProjects
/Neural-Nets/Neural-Net-Tutorial.py
1,578
4
4
# Based on https://iamtrask.github.io/2015/07/12/basic-python-network/ import numpy as np # sigmoid function def sigmoid(x, deriv=False): if deriv: # The derivative of the sigmoid function, for calculating direction/intensity of errors # Here, x is the output of the sigmoid function of the original x return x * (1 - x) # The sigmoid function returns higher values as closer to 1, lower as closer to 0 # 1/(1+e^(-x)) return 1 / (1 + np.exp(-x)) # input dataset. Each row is a training example giving values for each of the 3 inputs inputdata = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) # output dataset. Each row is a training example giving a value for each of the 1 (...) outputs outputdata = np.array([[0], [0], [1], [1]]) # seed random numbers to make calculation # deterministic (just a good practice) np.random.seed(1) # initialize weights randomly with mean 0 syn0 = 2 * np.random.random((3, 1)) - 1 for iter in range(10000): # forward propagation layer0 = inputdata layer1 = sigmoid(np.dot(layer0, syn0)) print(layer1) # how much did we miss? layer1_error = outputdata - layer1 # multiply how much we missed by the # slope of the sigmoid at the values in l1 layer1_delta = layer1_error * sigmoid(layer1, True) # update weights syn0 += np.dot(layer0.T, layer1_delta) print("Output After Training:") print(layer1)
32b18218321e2250d8f2dbddea7995fabf35d2f9
datnt55/ktpm2013
/Triangle.py
1,109
4.03125
4
def check(a,b,c): if (a < 0) | (b < 0) | (c < 0): print 'Error' else: print 'OK' x = float(raw_input("Please enter an integer: ")) y = float(raw_input("Please enter an integer: ")) z = float(raw_input("Please enter an integer: ")) e = pow(10,-9) while (x < 0)|(y<0)|(z<0): print 'Please enter again' x = float(raw_input("Please enter an integer: ")) y = float(raw_input("Please enter an integer: ")) z = float(raw_input("Please enter an integer: ")) check(x,y,z) def checkTriangle(a,b,c): if (a>=b+c)|(b>=c+a)|(c>=b+a): print 'it is not a Triangle' else: if a==b==c: print 'It is a equilateral triangle' return if (a==b)|(b==c)|(c==a): if (a*a-b*b-c*c<=e)|(b*b-c*c-a*a<e)|(c*c-b*b-a*a<e): print 'It is a angled isosceles triangle' else: print 'It is a isosceles triangle' if (a*a-b*b-c*c<e)|(b*b-c*c-a*a<e)|(c*c-b*b-a*a<e): if (a!=b)&(b!=c)&(c!=a): print 'It is a angled triangle' checkTriangle(x,y,z)
95248b64e89e979c7298ea02ad28f462e602daaa
shanmugapriya98/shanmu
/alphabet_or_not.py
94
3.734375
4
ch = input() if(ch.isalpha() == True) print("Alphabet") else: print("Not an alphabet")
e948cb19f7b3d4c898271cfd956ce3db8a43ba39
shanmugapriya98/shanmu
/hcf_of_two_numbers.py
117
3.84375
4
num1 = int(input()) num2 = int(input()) while(num2 != 0): rem = num1 % num2 num1 = num2 num2 = rem print(num1)
a29a2a9d86f2bb27637275ebe3df713444b0d4d2
rayraysheng/python-challenge
/PyPoll/main.py
4,008
4.03125
4
import os import csv # I've set up a raw data folder and a results folder # The raw data folder will hold the input .csv files # The program will create a summary with each input file # The summary .txt files will be written to the results folder # Work on each file in the input_files folder for filename in os.listdir("raw data"): csv_path = os.path.join("raw data", filename) with open(csv_path, newline="") as csv_file: # Turn the .csv file into a csv reader file_reader = csv.reader(csv_file, delimiter=",") # Skip header row next(file_reader) # I haven't found a way to work with index of rows in a csv reader # So I will convert the csv reader to a list of lists to work on it # Each row in the csv reader represents a single ballot ballot_box = list(file_reader) # Keep candidate names and respective votes in lists, keyed on index candidate_names = [] candidate_votes = [] # Check each ballot for ballot in ballot_box: # If the candidate is not on the scoreboard yet # Add the candidate's name to the scoreboard # Give the candidate his or her first vote # If the candidate is already on the scoreboard # Find the index of his/her name in the name list # Find the corresponding index in the vote count list # Add one more vote to that corresponding vote count if ballot[2] not in candidate_names: candidate_names.append(ballot[2]) candidate_votes.append(1) else: candidate_votes[candidate_names.index(ballot[2])] += 1 # Total votes is just the count of all ballots in ballot_box # i.e. length of the outer list # which also equals the sum of all the votes tot_votes = len(ballot_box) # We can make the scoreboard a list of dictionaries for organization scoreboard = [] for i in range(1, 1 + len(candidate_names)): scoreboard.append({ "name": candidate_names[i - 1], "vote count": candidate_votes[i - 1], "percentage": str(round(float(candidate_votes[i - 1]) / tot_votes * 100, 2)) + "%" }) # Find the winner winner = candidate_names[candidate_votes.index(max(candidate_votes))] # Now print it out print("Election Results from ") print(filename) print("---------------------------") print("Total Votes: " + str(tot_votes)) print("---------------------------") for candidate in scoreboard: print(candidate["name"] + ": " + candidate["percentage"] + " (" + str(candidate["vote count"]) + ")" ) print("---------------------------") print("Winner: " + winner) print("---------------------------") print("") print("") # Write the output .txt file for each input file output_file_name = filename + "_results.txt" output_path = os.path.join("results", output_file_name) summary_file = open(output_path, "w") summary_file.write( "Election Results from " + "\n" + filename + "\n" + "---------------------------" + "\n" + "Total Votes: " + str(tot_votes) + "\n" + "---------------------------" + "\n" ) for candidate in scoreboard: summary_file.write(candidate["name"] + ": " + candidate["percentage"] + " (" + str(candidate["vote count"]) + ")" + "\n" ) summary_file.write( "---------------------------" + "\n" + "Winner: " + winner + "\n" + "---------------------------" + "\n" ) summary_file.close()
ad04b7264ba1c3cf3486d792afc3c0b1931b5479
geewynn/python_restaurant_simulator
/Menu.py
1,012
3.546875
4
import csv from MenuItem import MenuItem class Menu(object): MENU_ITEM_TYPES = ["Drink", "Appetizer", "Entree", "Dessert"] def __init__(self, filename): self.__menuItemDictionary = {} for t in self.MENU_ITEM_TYPES: self.__menuItemDictionary[t] = [] with open(filename) as f: reader = list(csv.reader(f)) for row in reader: menuItem = MenuItem(row[0], row[1], row[2], row[3]) self.__menuItemDictionary[menuItem.types].append(menuItem) def getMenuItem(self, types, index): for key in self.__menuItemDictionary: if key == types: myMenuItem = self.__menuItemDictionary[key][index] return myMenuItem def printMenuItemsByType(self, types): print(types, ':') for i, v in enumerate(self.__menuItemDictionary[types]): print("#", i + 1, v) def getNumMenuItemsByType(self, types): return len(self.__menuItemDictionary[types])
978f9bb97e638066dd2540b6c439c5ffdf880efc
yunusaltuntas/MachineLearning
/K Nearest Neighbors/knn.py
2,672
3.671875
4
# K-Nearest Neighbors (K-NN) # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('airbnb_warsaw.csv',sep=';') X = dataset.iloc[:, [7, 9]].values y = dataset.iloc[:, 4].values def PrepareForPrediction(X, y): global X_train, X_test, y_train, y_test from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) return X_train, X_test, y_train, y_test # Splitting the dataset into the Training set and Test set & Feature Scaling PrepareForPrediction(X, y) # Fitting K-NN to the Training set from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2) classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # apparently, the K-NN method did slightly worse predicting the results # than the logistic regression. The ratio of well-predicted outcomes in # Logistic Regression was 1,58 : 1, while in K-NN it was only 1,43 : 1. # What's interesting is the fact that this prediction (with the result of # arount 1,4) was still much better then the one, where the dataset excluded # outliers - 2k PLN places with 0 bedrooms and zero reviews. There the # prediction ratio was at around 1,2 : 1). def visualizeResults(X_set, y_set): from matplotlib.colors import ListedColormap X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('K-NN') plt.xlabel('number of bedrooms') plt.ylabel('price in PLN') plt.legend() plt.show() # Visualising the Training set results visualizeResults(X_train, y_train) # Visualising the Test set results visualizeResults(X_test, y_test)
b44a6b18c2fb9239c4d2be5ea07bc287b004f1b2
Sher-V/cups
/main.py
3,010
3.578125
4
# время мытья - 10 мин # время тусовки - 5 мин # периодичность захода - 5 мин # количество людей 5-9 # время работы 180 минут # количество чашек в сервизе 40 # Нарисовать график времени работы от количества моющихся чашек, количество чистых чашек, количество грязных чашек import matplotlib.pyplot as plt import random from constants import NUMBER_OF_PEOPLE_MIN, NUMBER_OF_PEOPLE_MAX, TIME_FOR_WASH, NUMBER_OF_CUPS, WORK_TIME, \ INTERVAL_MIN, INTERVAL_MAX, TEXTS_FOR_GRAPH def main(): res_array_number_of_washing_cups = [0] res_array_number_of_clear_cups = [NUMBER_OF_CUPS] res_array_time = [0] array_of_washing_cups_time = [] number_of_clear_cups = NUMBER_OF_CUPS number_of_washing_cups = 0 time = 0 while number_of_clear_cups > 0 and time <= WORK_TIME: number_of_people_rand = random.randrange(NUMBER_OF_PEOPLE_MIN, NUMBER_OF_PEOPLE_MAX) res_arr = [] for k in range(len(array_of_washing_cups_time)): if time - array_of_washing_cups_time[k].get('time') > TIME_FOR_WASH: number_of_clear_cups += array_of_washing_cups_time[k].get('number') number_of_washing_cups -= array_of_washing_cups_time[k].get('number') else: res_arr.append(array_of_washing_cups_time[k]) array_of_washing_cups_time = res_arr res_array_number_of_clear_cups.append(number_of_clear_cups) res_array_number_of_washing_cups.append(number_of_washing_cups) number_of_clear_cups -= number_of_people_rand number_of_washing_cups += number_of_people_rand time += random.randrange(INTERVAL_MIN, INTERVAL_MAX) res_array_time.append(time) array_of_washing_cups_time.append({'time': time, 'number': number_of_people_rand}) print_graph(res_array_time, res_array_number_of_clear_cups, res_array_number_of_washing_cups) def print_graph(res_array_time, number_of_clear_cups, number_of_washing_cups): fig, ax = plt.subplots(1, 1, figsize=(15, 5), dpi=200) ax.grid() # логирование каждого момента времени log(number_of_clear_cups, res_array_time, number_of_washing_cups) plt.plot(res_array_time, number_of_clear_cups, color="green") plt.plot(res_array_time, number_of_washing_cups, color="blue") ax.legend(TEXTS_FOR_GRAPH, loc='best') ax.set_xlabel('Время (мин)') ax.set_ylabel('Количество чашек') plt.show() def log(number_of_clear_cups, res_array_time, number_of_washing_cups): for i in range(len(number_of_clear_cups)): print(res_array_time[i]) print("Чистые {}".format(number_of_clear_cups[i])) print("Моющиеся {}\n".format(number_of_washing_cups[i])) if __name__ == '__main__': main()
9522b6a465c1644ff8399a838eb3a7fb3b9cbcec
seriouspig/homework_week_01_day_01
/precourse_recap.py
566
4.15625
4
print("Guess the number I'm thinking from 1 to 10, What do you think it is?") guessing = True number_list = [1,2,3,4,5,6,7,8,9,10] import random selected_number = random.choice(number_list) while guessing == True: answer = int(input('Pick a number from 1 to 10: ')) if answer == selected_number: print("Great, you must be a psychic!") guessing = False break elif answer < selected_number: print("No, my number is higher, try again") elif answer > selected_number: print("No, my number is lower, try again")
276f4099bdc847b7c5a92ae909838f063d513a8f
rickhaffey/supply-chain-python
/demand.py
641
3.546875
4
from validation import Validate class Demand: """ Captures all demand-related values. Parameters ---------- quantity : int The amount of demand, in units time_unit : {{'Y', 'M', 'W', 'D'}}, default 'Y' A time unit specifier, representing the period of time over which the `quantity` applies """ def __init__(self, quantity, time_unit='Y'): Validate.required(quantity, "quantity") Validate.non_negative(quantity, "quantity") self.quantity = quantity Validate.one_of_allowable(time_unit, ['Y', 'M', 'W', 'D'], "time_unit") self.time_unit = time_unit
0fa21bbbb6afa66cd3efe096350b53d2f44670fb
ValS-Itescia/Webtarget
/Liste.py
1,422
3.59375
4
import Read_Write import os # Creation de ma liste et l'affiche liste = ["[email protected]","[email protected]","[email protected]","[email protected]"] print(liste) # fonction qui supprime les doublons de ma liste def delete_duplicate(liste): liste = list(set(liste)) return liste # Affichage de ma liste sans doublons liste_propre = delete_duplicate(liste) print(liste_propre) # ----------------------------------------- # Verification si email valide def checkmail(mail): if "@" in mail and (mail[-4:] == ".com" or mail[-3:] == ".fr"): print("L'adresse mail est valide") else: print("L'adresse mail est invalide") mail = "[email protected]" checkmail(mail) # ----------------------------------------- # Supprimer d'un mail mail = "[email protected]" def delete_mail(mail,liste): if mail in liste: liste.remove(mail) return liste delete_mail(mail,liste) print(liste) # ----------------------------------------- # Ping une adresse mail mail = "[email protected]" def pingDomaineEmail(mail): ping = False domain = mail[mail.find("@"):] domaine = domain.replace("@","") reponse = os.system("ping -c 1 " + domaine) if reponse == 0: print(domaine," est accessible") ping = True else: print(domaine," est innacessible") ping = False return ping pingDomaineEmail(mail) # -----------------------------------------
29800604f0b000f1ed4906d51875ab95370a3885
CMPundhir/PandasTutorial
/Ex5.py
448
3.5625
4
import pandas as pd import matplotlib.pyplot as plt # changing index #create a dictionary webDic = {'Day': [1, 2, 3, 4, 5, 6], 'Visitors': [1000, 2000, 200, 400, 10000, 300], 'Bounce_Rate': [20, 20, 23, 15, 10, 43]} #create dataframe df = pd.DataFrame(webDic) print(df) #changing index df2 = df.set_index('Day') print(df2) #inplace: Makes the changes in the dataframe if True. df.set_index('Day', inplace=True) print(df) df.plot() plt.show()
a25e94e6f477c54dc1763353db8ffed044016a5e
szhelyabovskiy/tenki
/direction.py
2,683
3.5625
4
import smbus import time import math import RPi.GPIO as GPIO from time import sleep GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT, initial=GPIO.LOW) #This module receives and converts data from the HMC5883L magnetic sensor that reads off the #direction of the weather vane. #Principle of operation: #A magnet attached to the vane overpowers Earth's magnetic field next to the sensor. Using the #direction of this magnetic field, wind direction can be determined. #1) At plug in, getDeclination() is called. # The user has about 20 seconds to turn the arrow towards true north. # This is indicated by a flashing LED with accelerating flash frequency. #2) After that, getDirection() calculates the direction of the vane relative to the original # declination. The LED stays on, to show that the device is calibrated. time.sleep(6) bus = smbus.SMBus(1) addrR = 0x1E pi = 3.14159265359 output = 0 def getDeclination(): #This function returns the initial orientation of the device, later used as reference. bus.write_byte_data(addrR, 0x00, 0x70) bus.write_byte_data(addrR, 0x01, 0xA0) bus.write_byte_data(addrR, 0x02, 0x00) #Flashing of the LED indicates that calibration is in progress. #Accelerated flashing indicates that time is running out. i = 0; while (i < 5): time.sleep(1) GPIO.output(11, GPIO.HIGH) time.sleep(1) GPIO.output(11, GPIO.LOW) i = i + 1 while (i < 11): time.sleep(0.5) GPIO.output(11, GPIO.HIGH) time.sleep(0.5) GPIO.output(11, GPIO.LOW) i = i + 1 GPIO.output(11, GPIO.HIGH) return getDirection(0) def getVal(adr): #This function reads and merges two bytes into a single value. msb = bus.read_byte_data(addrR, adr) lsb = bus.read_byte_data(addrR, adr + 1) return (msb << 8)+lsb def getDirection(declination): #This function collects and returns vane orientation data in degrees from 0 to 360. #Raw data is stored in a list. Only x and y axes are used. output = [0,0,0] output[0] = getVal(3) #x output[1] = getVal(7) #z output[2] = getVal(5) #y #The module's raw coordinates are not perfect. Using experimentation, these #compensation values have been found to correct this offset. coef = [180, 280, 0] #Sign and offset correction for j in range (3): if (output[j] > 32768): output[j] = output[j] - 65536 output[j] = output[j] + coef[j] #Find the angle from the two coordinates using arctan heading = math.atan2(output[1], output[0]) if (heading < 0): heading = heading + 2*pi #Compare the resultant angle to the reference heading_angle = int(heading*180/pi) - declination if (heading_angle < 0): heading_angle = heading_angle + 360 return heading_angle
0bcfdb2184da61297f36591fc3f05da63e573ecb
raghukrishnamoorthy/python-tricks
/cleaner python/underscores_and_dunders.py
846
3.734375
4
# Single _variable means it is private class Testy: def __init__(self): self.foo = 11 self._bar = 12 # Single variable_ can be used if name is a reserved keyword def make_object(item, class_): pass # Double __variable causes name mangling class Test: def __init__(self): self.foo = 11 self._bar = 23 self.__baz = 42 t = Test() class ExtendedTest(Test): def __init__(self): super().__init__() self.foo = 'overridden' self._bar = 'overridden' self.__baz = 'overridden' class Mangler(): def __init__(self): self.__mia = 5 def get_mia(self): return self.__mia # __var__ is magic python methods and variables. dont use them. # single _ is throwaway/placeholder variable car = ('suzuki', 'red', 1995, 12) make, _, _, mileage = car
5dfdc7a42d5ee842c648979694a4852c791da6cd
dheaangelina/UG9_A_71210693
/1_A_71210693.py
128
3.640625
4
d = int(input("Masukkan diameter : ")) Keliling = 3.14*d print("Keliling lingkaran adalah : ", str(round((Keliling),2)))
961b6639cb292351bff3d4ded8c366ab0d860ed8
IshaqNiloy/Any-or-All
/main (1).py
980
4.25
4
def is_palindromic_integer(my_list): #Checking if all the integers are positive or not and initializing the variable is_all_positive = all(item >= 0 for item in my_list) #Initializing the variable is_palindrome = False if is_all_positive == True: for item in my_list: #Converting the integer into a string and reversing it item_str = str(item)[::-1] #Checking weather the string is a palindrome or not if str(item) == item_str: is_palindrome = True #Printing the result if is_all_positive == True and is_palindrome == True: print('True') else: print('False') if __name__ == '__main__': #Defining an empty list my_list = [] #taking input for the number of integers number_of_integers = input() #taking input for the list my_list = list(map(int, input().split())) #Calling the function is_palindromic_integer(my_list)
5729f4ab552107394ea3066e69e5b23a19b61d4d
Andrey-Dubas/inclusion_analysis
/inclusion_analysis/graph.py
8,605
4.15625
4
class Graph(object): """This class describes directed graph vertices represented by plain numbers directed edges are start with vertex which is index of __vertices vertex the edge goes to is a value within list so, __vertices is "list < list <int> >" vertex is __vertices[*vertex_from*] = list of vertices of adjacent vertices """ def __init__(self): self.__vertices = {} def connect(self, from_vertex, to_vertex): """ sets a one-direction relation (directed edge) between vertices. from_vertex -> to_vertex :param from_vertex: index of vertex that edge goes from :param to_vertex: index of vertex that edge goes to :type from_vertex: int :type to_vertex: int :return: None """ if not self.__vertices.has_key(from_vertex): self.add_vertex(from_vertex) if not self.__vertices.has_key(to_vertex): self.add_vertex(to_vertex) self.__vertices[from_vertex].append(to_vertex) def is_adjacent(self, from_vertex, to_vertex): """ checks if there is an edge between vertices """ return to_vertex in self.__vertices[from_vertex] def get_connected(self, from_vertex): """ get all vertices that are connected directly to the particular one :param from_vertex: particular vertex :rtype: list<int> """ if isinstance(from_vertex, int): return self.__vertices[from_vertex] def add_vertex(self, index): """ add a informational vertex to the graph with :param data: an information contained by vertex :return: None """ self.__vertices[index] = [] def __len__(self): return len(self.__vertices) def has_vertex(self, index): """ checks if graph contains a vertex with particular information :param name: an info we're looking for :return: Boolean """ return self.__vertices.has_key(index) def dfs_impl(graph, cur_vertex, path_marked, marked, cycles, cur_path): """ plain depth first search implementation function. :param cur_vertex: currently processed vertex :param path_marked: list of booleans that defines whether a vertex is a part of path that connects current vertex and vertex dfs algo started with :param marked: visited vertices :param cycles: cycles detected :param cur_path: path to particular vertex from starting point :rtype cur_vertex: int :rtype path_marked: list<int> :rtype marked: list<int> :rtype cycles: list<list<int> > :rtype cur_path: list <int> :returns: if cur_vertex is a part of cycle :rtype: boolean """ result = False cur_path.append(cur_vertex) for next_vertex in graph.get_connected(cur_vertex): if (path_marked[next_vertex]): # path detected, the first index in list cycles.append(([next_vertex],[])) path_marked[next_vertex] = False result = True if not marked[next_vertex]: path_marked[next_vertex] = True marked[next_vertex] = True if dfs_impl(graph, next_vertex, path_marked, marked, cycles, cur_path): # the function is within cycle right now! cycle = cycles[-1][0] if cycle[0] != next_vertex: # append it! path_marked[next_vertex] = False cycle.append(next_vertex) result = True break else: # cucle[0] == next_vertex cycles[-1][1].extend(cur_path) path_marked[next_vertex] = False cur_path.pop() # for path in cycles: # path.append(cur_vertex) return result def cycle_detect(graph, root_vertex): """ cycle detection function :param graph: processed graph :param root_vertex: a vertex to start processing with :type graph: graph :type root_vertex: root_vertex :return: a list of pairs that combine a cycle detected and a path to a vertex cycle starts with :rtype: list<(list, list)> """ path_marked = [False] * len(graph) marked = [False] * len(graph) cycles = [] dfs_impl(graph, root_vertex, path_marked, marked, cycles, []) return cycles class FileGraph(object): """Class that reprecent file inclusion each vertex is a file, each edge describes one header that is included by another """ def __init__(self): """ __graph is a graph of indexes, each index represents file __name_to_index if a dict which key is filename and its value is index __index_name if a dict which key is index and its value is filename """ self.__graph = Graph() self.__name_to_index = {} self.__index_name = {} def get_name_by_index(self, index): """ returns filename by its index """ return self.__index_name[index] def get_index_by_name(self, name): """ returns file's index by its name """ return self.__name_to_index[name] def connect(self, from_vertex, to_vertex): """ sets a one-direction relation between vertices. from_vertex -> to_vertex :param from_vertex: filename that contains inclusion :param to_vertex: included filename :type from_vertex: str :type to_vertex: str :return: None """ if isinstance(from_vertex, str): if not self.__name_to_index.has_key(from_vertex): self.add_vertex(from_vertex) from_vertex_index = self.__name_to_index[from_vertex] else: raise ValueError("vertices must be names of files") if isinstance(to_vertex, str): if not self.__name_to_index.has_key(to_vertex): self.add_vertex(to_vertex) to_vertex_index = self.__name_to_index[to_vertex] else: raise ValueError("vertices must be names of files") self.__graph.connect(from_vertex_index, to_vertex_index) def is_adjacent(self, from_vertex, to_vertex): """ returns whether to_vertex is adjacent to from_vertex """ from_vertex = self.get_index_by_name(from_vertex) to_vertex = self.get_index_by_name(to_vertex) return self.__graph.is_adjacent(from_vertex, to_vertex) def get_connected(self, from_vertex): """ get all vertices that are connected directly to the particular one :param from_vertex: particular vertex :type from_vertex: str :returns: all adjacent vertices :rtype: list <int> """ if isinstance(from_vertex, int): return self.__vertices[from_vertex] def add_vertex(self, data): """ add a informational vertex to the graph with :param data: an information contained by vertex :type data: str :rtype: None """ self.__name_to_index[data] = len(self) self.__index_name[len(self)] = data self.__graph.add_vertex(len(self)) def __len__(self): return len(self.__graph) def has_vertex(self, name): """ checks if graph contains a vertex with particular information :param name: an info we are looking for :rtype name: str :return: if the graph contains particular filename :rtype: Boolean """ return self.__vertices.has_key(name) def cycle_detect(self, root_vertex): """ detects all cycles of the graph :param root_vertex: the vertex it start graph traverse :rtype root_vertex: str :return: a list of pairs that combine a cycle detected and a path to a vertex cycle starts with """ root_vertex = self.get_index_by_name(root_vertex) cycles = cycle_detect(self.__graph, root_vertex) named_cycles = [] for cycle in cycles: named_cycles.append( ([self.get_name_by_index(index) for index in cycle[0]] , [self.get_name_by_index(index) for index in cycle[1]]) ) return named_cycles def __str__(self): result = '' for index, filename in self.__index_name.iteritems(): result += filename + ': ' for include in self.__graph.get_connected(index): result += self.get_name_by_index(include) + ', ' result += "\n" return result
bbd8f07902ff5a1ddc8ca56c3903b096c1a63624
CoderMaik/PokerZen
/src/gamemodes/setups/AmericanSetup.py
1,705
3.671875
4
""" File contains objects used in the dem: Card, deck and player to add modularity access to the attributes is not restricted, they are all public """ class Card(object): def __init__(self, val, suit): self.val = val self.suit = suit def __repr__(self): # This could be done with pattern matching from python 3.10 values = { 0: "2", 1: "3", 2: "4", 3: "5", 4: "6", 5: "7", 6: "8", 7: "9", 8: "10", 9: "J", 10: "Q", 11: "K", 12: "A" } suits = { 0: "\u2663", # Clubs 1: "\u2666", # Diamonds 2: "\u2665", # Hearts 3: "\u2660" # Spades } return values[self.val] + suits[self.suit] def __gt__(self, other): # Overriding this method allows for instant comparison between cards if self.val == other.val: return self.suit > other.suit return self.val > other.val class Deck(set): # Using a set helps us avoid the shuffle action, since you can only pop elements randomly def __init__(self): super().__init__() [[self.add(Card(i, j)) for j in list(range(4))] for i in list(range(13))] def deal(self, target, number=1): for i in range(number): target.cards.append(self.pop()) class Player(object): def __init__(self, name=None): self.name = name self.cards = [] def __repr__(self): return self.name def show_hand(self): # Pythonic way of printing the hand print(*self.cards, sep=", ")
da6ad33803ebefe4086699cab7216ab2f16fb677
Ang-Li615/leetcode
/mergeSortedArray.py
843
3.6875
4
class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ if m == 0 and n == 0: return None if m == 0 and n != 0: i = 0 for e in nums2: nums1[i] = e i += 1 if m != 0 and n == 0: return None i = 0 j = 0 while j < n and i < m + j: if nums1[i] < nums2[j]: i += 1 else: nums1.insert(i, nums2[j]) nums1.pop() j += 1 i += 1 while j < n: nums1[i] = nums2[j] j += 1 i += 1
14c52991b7a7a5891a7d2e0d5d2af3512d977c33
Ang-Li615/leetcode
/Number0fSegmentsInAString.py
605
3.65625
4
class Solution: def countSegments(self, s): """ :type s: str :rtype: int """ if len(s) == 0: return 0 while True: if len(s.strip(' ')) < len(s): s = s.strip(' ') continue if len(s.strip(',')) < len(s): s = s.strip(',') continue break if len(s) == 0: return 0 s1 = s.replace(',', '') s2 = s1.replace(' ', '') if s2 == '': return 0 else: return len(s1) - len(s2) + 1
c9b0181161248354a1b1640e84e312bb9a76f9e9
Ang-Li615/leetcode
/validParenthese.py
424
3.65625
4
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ while True: s1 = s.replace('[]', '') s2 = s1.replace('{}', '') s3 = s2.replace('()', '') if s3 == s: return False else: if s3 == '': return True else: s = s3
a252dc283a07445f1250dd55dc4018e4e0c94321
Ang-Li615/leetcode
/letterCasePermutation.py
422
3.578125
4
class Solution: def letterCasePermutation(self, S): L = [''] for char in S: LL = [] if char.isalpha(): for s in L: LL.append(s + char.lower()) LL.append(s + char.upper()) L = LL else: for s in L: LL.append(s + char) L = LL return L
c494273bb1e1bbf5889a81b2eeab8f27e3182a3d
Ang-Li615/leetcode
/convertBST2GT.py
1,530
3.71875
4
# # Definition for a binary tree node. # # class TreeNode: # # def __init__(self, x): # # self.val = x # # self.left = None # # self.right = None # # class Solution: # def convertBST(self, root): # if root == None: # return root # # self.L = [root] # self.appendNode([root]) # LL = [] # for e in self.L: # LL.append(e.val) # LLL = sorted(LL) # for node in self.L: # valindex = len(LLL) - 1 - LLL[::-1].index(node.val) # while valindex < len(LLL): # node.val += LLL[valindex] # valindex += 1 # return root # # def appendNode(self,l): # L = [] # for node in l: # if node.left != None: # self.L.append(node.left) # L.append(node.left) # if node.right != None: # self.L.append(node.right) # L.append(node.right) # # if L != []: # L1 = L # return self.appendNode(L1) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.total = 0 def convertBST(self, root): if root != None: self.convertBST(root.right) self.total += root.val root.val = self.val self.convertBST(root.left) return root
84014b5e5aeb46694ced4cd3b4b95c0e31257433
Ang-Li615/leetcode
/binaryTreeTilt.py
2,076
3.78125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTilt(self, root): if root == None: return 0 self.diff = 0 self.subtreeSum(root) return self.diff def subtreeSum(self,root): if root.left != None and root.right == None: self.subtreeSum(root.left) root.val = root.val + root.left.val self.diff += abs(root.left.val) elif root.left == None and root.right != None: self.subtreeSum(root.right) root.val = root.val + root.right.val self.diff += abs(root.right.val) elif root.left == None and root.right == None: root.val = root.val self.diff += 0 else: self.subtreeSum(root.left) self.subtreeSum(root.right) root.val = root.val + root.left.val + root.right.val self.diff += abs(root.left.val - root.right.val) return root # if root.left != None: # self.findTilt(root.left) # ld = root.left.val # else: # ld = 0 # # if root.right != None: # self.findTilt(root.right) # else: # rd = 0 # # self.sum += abs(ld - rd) # sum = root.val + ld + rd # root.val = sum # self.sum = 0 # self.findLevel([root]) # return self.sum # # def findLevel(self,L): # l = [] # for i in L: # if i.left != None: # ld = i.left.val # l.append(i.left) # else: # ld = 0 # # if i.right != None: # rd = i.right.val # l.append(i.right) # else: # rd = 0 # self.sum += abs(ld - rd) # # if l != []: # return self.findLevel(l)
46be376db7886d6ef3d8bde07178182fb09b4878
Ang-Li615/leetcode
/constructRectangle.py
792
3.90625
4
from math import sqrt class Solution: def constructRectangle(self, area): n = int(sqrt(area)) for i in range(n,area): if area % i == 0: return [i, area//i] # # # # # # # if self.is_prime(area): # return [area,1] # # i = int(sqrt(area)) # if i * i == area: # return [i, i] # else: # i = i + 1 # while area % i != 0: # i = i + 1 # return [i, area // i] # # def is_prime(self,x): # if x > 1: # n = x // 2 # for i in range(2, n + 1): # if x % i == 0: # return False # return True # else: # return False
78ef89950a7376242b9d4897dbd092a6cdfc66b4
Ang-Li615/leetcode
/canPlaceFlowers.py
1,167
3.625
4
class Solution: def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ l = len(flowerbed) if l == 0: return n <= l if l == 1: if flowerbed[0] == 1: return n <= 0 else: return n <= l if l == 2: if flowerbed == [0, 0]: return n <= 1 else: return n <= 0 sum = 0 i = 0 while i < l: if i == 0: if flowerbed[i:i + 2] == [0, 0]: sum += 1 flowerbed[i:i + 2] = [1, 0] i += 1 continue if i == l - 1: if flowerbed[i - 1:i + 1] == [0, 0]: sum += 1 flowerbed[i - 1:i + 1] = [0, 1] i += 1 continue if flowerbed[i - 1:i + 2] == [0, 0, 0]: sum += 1 flowerbed[i - 1:i + 2] = [0, 1, 0] i += 1 print(flowerbed) return n <= sum
05079f16b25dcad0a9dc4f8bce823972c0c62ae3
dan-klasson/tic-tac-toe
/views.py
1,157
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class GameView: def intro(self): return '\nTic Tac Toe\n' def newlines(self, amount=1): return '\n' * amount def number_of_players(self): return 'Enter number of players (1-2): ' def number_of_players_error(self): return '\nPlease enter 1 or 2' def board(self, board): return ''' ╔═══╦═══╦═══╗ ║ {0} ║ {1} ║ {2} ║ ╠═══╬═══╬═══╣ ║ {3} ║ {4} ║ {5} ║ ╠═══╬═══╬═══╣ ║ {6} ║ {7} ║ {8} ║ ╚═══╩═══╩═══╝ '''.format(*[x or (i + 1) for i, x in enumerate(board)]) def win_player(self, player): return 'Player {} won!'.format(player) def draw(self): return '\nGame ended in draw.' @property def play_again(self): return '\nPlay again? (Y/n): ' def next_move(self, player, move=''): return 'Player {}: {}'.format(player, move) @property def move_not_valid(self): return 'Not a valid move'
de3f02e8416760c40ab208ff7ee372313040fcd1
bishal-ghosh900/Python-Practice
/Practice 1/main30.py
992
4.1875
4
# Sieve of Eratosthenes import math; n = int(input()) def findPrimes(n): arr = [1 for i in range(n+1)] arr[0] = 0 arr[1] = 0 for i in range(2, int(math.sqrt(n)) + 1, 1): if arr[i] == 1: j = 2 while j * i <= n: arr[j*i] = 0 j += 1 for index, value in enumerate(arr): # enumerate will give tuples for every iteration which will contain index and value of that particular iteration coming from the list . And in this particular list the tuple is being unpacked in the index and the value variable # Its something like --> index, value = ("0", 1) # index, value = ("1", 2) and so on # "0", "1", "2" etc are the indexs of the list, and the next argument is the value of that particular index from the list in which we are performing enumerate() operation. if value == 1: print(index, sep=" ") else: continue findPrimes(n)
2b72be0a06d4a19932b256628b2b2f8b6703cb25
bishal-ghosh900/Python-Practice
/Practice 1/main3.py
262
3.625
4
#String name = "My name is Bishal Ghosh" print(name[0]) # M print(name[-2]) # h print(name[0:5])# My na print(name[1:]) # y name is Bishal Ghosh print(name[:len(name) - 1]) # My name is Bishal Ghos print(name[:]) # My name is Bishal Ghosh print(name[1:-1]) # y name is Bishal Ghos
eaadca4eda12fc7af10c3a6f70437a760c14358f
bishal-ghosh900/Python-Practice
/Practice 1/main9.py
595
4.6875
5
# Logical operator true = True false = False if true and true: print("It is true") # and -> && else: print("It is false") # and -> && # Output --> It is true if true or false: print("It is true") # and -> || else: print("It is false") # and -> || # Output --> It is true if true and not true: print("It is true") # and -> && # not -> ! else: print("It is false") # and -> && # Output --> It is false if true or not true: print("It is true") # and -> && # not -> ! else: print("It is false") # and -> && # Output --> It is true
460ea4d25a2f8d69e8e009b70cdec588b8ca7b20
bishal-ghosh900/Python-Practice
/Practice 1/main42.py
782
4.28125
4
# set nums = [1, 2, 3, 4, 5] num_set1 = set(nums) print(num_set1) num_set2 = {4, 5, 6, 7, 8} # in set there is not any indexing , so we can't use expression like num_set1[0]. # # Basically set is used to do mathematics set operations #union print(num_set1 | num_set2) # {1, 2, 3, 4, 5, 6, 7, 8} # intersection print(num_set1 & num_set2) # {4, 5} # A - B --> Every element of A but not of B print(num_set1 - num_set2) # {1, 2, 3} # B - A --> Every element of B but not of A print(num_set2 - num_set1) # {8, 6, 7} # symmetric difference --> (A - B) U (B - A) --> Every thing present in A and B but not in both print(num_set1 ^ num_set2) # {1, 2, 3, 6, 7, 8} # like list we can also create set comprehension nums = { i * 2 for i in range(5)} print(nums) # {0, 2, 4, 6, 8}
8a72ba35bf514fd7ff13479017fa3615eb4766cc
bishal-ghosh900/Python-Practice
/Practice 1/main39.py
301
3.96875
4
# queue from collections import deque list1 = deque([1, 2, 3, 4, 5]); list1.appendleft(10) print(list1) # deque([10, 1, 2, 3, 4, 5]) list1.popleft() print(list1) # deque([1, 2, 3, 4, 5]) list1.append(6) print(list1) # deque([1, 2, 3, 4, 5, 6]) list1.pop() print(list1) # deque([1, 2, 3, 4, 5])
789e675cb561a9c730b86b944a0a80d6c423f475
bishal-ghosh900/Python-Practice
/Practice 1/main50.py
804
4.75
5
# private members # In python there we can prefix any data member with __ (dunder sign) , then it will be private. In reality it don't get private, if we declare any data member with __ , that data member actually get a differet name from python , which is like => _classname__fieldname. So in the below implementation if we change "eyes" field member to "__eyes" , then python will change it to "_Animal__eyes" . We can't access "eyes" by using "a.eyes" (here think "a" is Animal object) as eyes is changed to "_Animal__eyes" , so if we want to access "eyes", then we have to access it by using "a._Animal__eyes" class Animal: def run(self): print("I can run") __eyes = 2 a = Animal() # print(a.eyes) => error -> Animal object has no attribute eyes print(a._Animal__eyes) # 2 a.run()
ff52754b77c4caeac1d1bcb6d4def097b2f6d0c8
bishal-ghosh900/Python-Practice
/Practice 1/main53.py
416
4.09375
4
# closure # A closure is a function that remembers its outer variables and can access them def multiplier(x): def multiply(y): return x * y return multiply m = multiplier(10)(2) print(m) # 20 # defected way of closure print # def doThis(): # arr = [] # for x in range(1, 4): # arr.append(lambda y: y * x) # return arr # q1, q2,q3 = doThis() # print(q1(10), q2(10), q3(10))
c2c1d70b70f5829bc69f221aaff4f1a79a682ddf
MStevenTowns/Python-1
/Statistics.py
2,060
3.625
4
##M. Steven Towns ##4/29/204 ##Assignment 14 import math def minimum(aList): guess=aList[0] for num in aList: if num<guess: guess=num return guess def maximum(aList): guess=aList[0] for num in aList: if num>guess: guess=num return guess def sumNum(aList): total=0 for num in aList: total+=num return total def avg(aList): return sumNum(aList)/len(aList) def median(aList): x=len(aList) y=x/2 if x%2==1: return aList[y] else: return (aList[y-1]+aList[y])/2 def notThere(elem, aList): out=True for thing in aList: if elem==thing: out=False return out def mode(aList): high=0 nums=[] out="" for elem in aList: if high<aList.count(elem): high=aList.count(elem) for x in aList: if (aList.count(x)==high and nums.count(x)<1): nums+=[x] for a in range(len(nums)): out+=str(nums[a])+" " return out def standDev(aList): xBar=avg(aList) sumThis=0 for i in aList: sumThis+=((i-xBar)**2) return math.sqrt(sumThis/(len(aList)-1)) nameFileIn=raw_input('What is the name of the input file? (Enter for default): ') if (nameFileIn==""): nameFileIn="Input" if not nameFileIn.endswith(".txt"): nameFileIn+=".txt" nameFileOut=raw_input('What is the name of the output file? (Enter for default): ') if (nameFileOut==""): nameFileOut="Output" if not nameFileOut.endswith(".txt"): nameFileOut+=".txt" inFile=file(nameFileIn,"r") outFile=file(nameFileOut,"w") m=[] for line in inFile: m+=[float(line)] sendout="" sendout+=("Count: "+str(len(m))+"\nSum: "+str(sumNum(m))+"\nMode(s): "+str(mode(m))+"\nAverage: "+str(avg(m))+"\nMinimum: "+str(minimum(m))+"\nMaximum: "+str(maximum(m))+"\nMedian: "+str(median(m))+"\nStandard Deviation: "+str(standDev(m))) outFile.write(sendout) print "\n"+sendout outFile.close() inFile.close()
a533862c6545a575a7d932aa33b99aacb4f6bf0b
MStevenTowns/Python-1
/TurtleWalk.py
2,145
3.9375
4
#M. Steven Towns #Assignment 5 #1/20/2014 import turtle, random anne=turtle.Turtle() anne.speed(0) anne.up() anne.setpos(-325,-275) anne.down() anne.forward(650) anne.left(90) anne.forward(275*2) anne.left(90) anne.forward(650) anne.left(90) anne.forward(275*2) anne.up() anne.setpos(5000,5000) fred=turtle.Turtle() fred.shape("turtle") fred.speed(0) fred.resizemode("auto") fred.color("black","green") fred.pensize() print "This is the Turtle Hulk, he gets bigger when he hits the top and right,\nbut he gets smaller when he hits the bottom or left." while True: fred.forward(5) fred.right(random.randint(-15,15)) #Right if (fred.xcor()>325): fred.right(90) fred.pensize(fred.pensize()+1) fred.pencolor(random.random(),random.random(),random.random()) if (fred.pensize()>20): fred.pensize(20) print "Roar!!" if (fred.xcor()>350): fred.up() fred.setpos(0,0) fred.down() #Top if (fred.ycor()>275): fred.right(90) fred.pensize(fred.pensize()+1) fred.pencolor(random.random(),random.random(),random.random()) if (fred.pensize()>20): fred.pensize(20) print "Roar!!" if (fred.ycor()>300): fred.up() fred.setpos(0,0) fred.down() #Left if (fred.xcor()<-325): fred.right(90) fred.pensize(fred.pensize()-1) fred.pencolor(random.random(),random.random(),random.random()) if (fred.pensize()<1): fred.pensize(1) print "Ouch!" if (fred.xcor()<-350): fred.up() fred.setpos(0,0) fred.down() #Bottom if (fred.ycor()<-275): fred.right(90) fred.pensize(fred.pensize()-1) fred.pencolor(random.random(),random.random(),random.random()) if (fred.pensize()<1): fred.pensize(1) print "Ouch!" if (fred.ycor()<-300): fred.up() fred.setpos(0,0) fred.down()
f2b42f7fdbd15e8c9d5343bbd3ff7aca8a8d4099
MStevenTowns/Python-1
/SecretMessage.py
1,508
3.96875
4
# M. Steven Towns #Assignment 8 #2/4/2014 encoder=True while encoder: msg=raw_input('What do you want to encode?: ') shift=int(raw_input('what do you want to shift it by?: '))%26 secret_msg="" for i in range(len(msg)): letter=msg[i] if letter.isalpha(): if letter.isupper(): if ord(letter)+shift>90: new_letter=chr(ord(letter)+shift-26) elif ord(letter)+shift<65: new_letter=chr(ord(letter)+shift+26) else: new_letter=chr(ord(letter)+shift) secret_msg+=new_letter else: if ord(letter)+shift>122: new_letter=chr(ord(letter)+shift-26) elif ord(letter)+shift<97: new_letter=chr(ord(letter)+shift+26) else: new_letter=chr(ord(letter)+shift) secret_msg+=new_letter else: secret_msg+=letter print secret_msg again=True while again: prompt=(raw_input("Do you want to encode another message?: ")).lower() if prompt=="no": encoder=False print "Good luck agent!" again=False elif prompt=="yes": print "Security protocol engaged!\nSecuring network." again=False else: again=True print "Try that again, I couldn't understand that."
a9bcd41772d6493b67724fc42a519cadd748020d
MStevenTowns/Python-1
/File Fun.py
1,085
3.78125
4
##M. Steven Towns ##Assignment 13 File Fun ##4/1/14 myList=[] name=(raw_input('What is the name of unsorted input file? (Enter for default): ')).strip() if (name==""): name="InputSort" if not name.endswith(".txt"): name+=".txt" f=file(name) for line in f: myList+=[line.strip()] myList.sort() for elem in myList: print elem name=(raw_input('\nWhat is the name of the numeric input file? (Enter for default): ')).strip() if (name==""): name="InputNum" if not name.endswith(".txt"): name+=".txt" f=file(name) myList=[] for line in f: line=float(line.strip()) myList+=[line] myList.sort() print "Min:",myList[0] print "Max:",myList[-1] print "Average:",sum(myList)/len(myList) name=(raw_input('\nWhat is the name of the encoded input file? (Enter for default): ')).strip() if (name==""): name="InputCode" if not name.endswith(".txt"): name+=".txt" f=file(name) sentence="" for line in f: hold=line.split() word=hold[0] num=int(hold[1]) sentence+=word[num] print "The secret word is:",sentence
0cad154951e8b14a01edb5a9a2ba9d7bb81e469e
MStevenTowns/Python-1
/List.py
318
4.03125
4
x=[5,23,5,2,32,53] print len(x) print x[1:2:3] #[start:stop:step] step is to get every x values x[3]=234 #can change value in list, not str #listception to call value in the list in list multidimensional array call x[][] print x.sort() #wont work x.sort() #do not use x=x.sort() it kills list print x
53e8b7c26985bf98e7ed93563f0a0e866b353f01
kenshimota/Learning-Python
/learning Class/class_people.py
415
3.890625
4
class People(): name = "" # obtiene el nombre de la persona def getName(self): return self.name # funcion que agrega el nombre de la persona def setName(self, str = ""): if str != "": self.name = str # fabrica el input para obtene el nombre def inputName(self): name_tmp = input("Ingrese su nombre: ") self.setName(name_tmp) people1 = People() people1.inputName() print( people1.getName() )