blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
db171d3ae18ad50b883f7ed7dc8b262ee334247f
Eunbae-kim/python
/basic11.py
1,112
3.6875
4
# 파이썬 # 함수 Fuction와 모듈 module # 함수 : 특정한 입력을 받아서 처리를 한 이후에, 특정한 출력을 해줌 # 함수를 이용하면 반복을 줄일 수 있는 장점 def add(a,b): sum = a + b return sum print("1 + 3 = ", add(1,3)) #return 문이 없는 경우 def add(a,b): print(a + b) add(4,6) # 가변인자 : 함수의 매개변수가 가변적일 수 있을 때 사용 def function(*data): print(data) function(1,2,3) # 전역변수 vs 지역변수 # 전역변수 : 소스코드 전체에서 사용 가능 # 지역변수 : 그 함수 내에서만 사용 가능 # 함수안에서 전역변수 사용하기 위해서는 global을 앞에 붙여 # 파이썬은 독특하게 반환값이 여러개일 수 있음 def function(): a = 5 b = [1, 2, 3] return a,b a, b = function() print(a, type(a)) print(b) # 모듈(library) # 미리 작성된 함수코드, 라이브러리 쉽게 이용 가능 import math print(math.pow(3,5)) print(math.sqrt(4)) print(math.gcd(72,24)) #최대 공약수 #내가 만든 모듈 import lib print(multiply(6,4))
bb78ecd3b33b974d26d1b7fc83f933ef8a660a20
Eunbae-kim/python
/chapter07_01.py
3,391
3.625
4
#Chapter07_01 #예외 개념 및 처리 # SyntaxError, typeError, nameError, indexError # 문법적으로는 예외가 없지만, 코드 실행 프로세스(단계) 발생하는 예외도 있음 # 1. 예외는 반드시 처리해야 한다. # 2. 로그는 반드시 남긴다. # 3. 예외는 던져진다. # 4. 예외 무시할 수 있지만, 좋은 방법은 아니ㅏㄷ. # SyntaxError : 문법 오류 #print('error) #print('error')) #if True # pass #NameError : 참조가 없을 떄 # a = 10 # b = 15 # print(c) #ZeroDivisionErorr #print( 100 / 0 ) # x = [50, 70, 90] # print[x[1]] # print[x[4]] # print(x.pop()) # print(x.pop()) # print(x.pop()) # print(x.pop()) # print(x.pop()) #KeyError # dic = {'name': 'Lee', 'Age': 41, 'City': 'Busan'} # print(dic['hobby']) # print(dic.get('hobby')) # 예외 없는 것을 가정하고 프로그램 작성 # -> 런타임 예외 발생시 예외 처리 권장 (EAFP) # AttributeError : 모듈, 클래스에 있는 잘못된 속성 사용 예외 # import time # print(time.time2()) time에는 time2라는 예외 없음 # ValueErrror # x = [10, 50, 90] # x.remove(50) # print(x) #없는 변수를 꺼내면 안됨. # x.remove(200) #FileNotFoundError # f = open('text.txt') #이런 파일이 존재하지 않음 #TypeError : 자료형에 맞지 않은 연산을 수행할 경우 # x = [1,2] #리스트는 가변형 # y = (1,2) #튜플은 불변형 # z = 'test' # print(x + y) #리스트와 튜플은 합칠 수 없음 # print(z + y) #문자와 숫자도 더할 수 없음 # print(x + z) #예외 처리 기본 # try : 에러가 발생 할 가능성이 있는 코드 실행 # except 에러명1 : dufjro rksmd # except 에러명2 : # else : try 부분에 에러가 없을 경우 실행 # finaly : 항상 실행 name = ['Kim', 'Lee', 'Park'] #예제1 # try: # z = 'Kim' #Cho로 바꾸면 예외 처리되고, 예외 발생하면 else실행 되지 않음. # x = name.index(z) # print('Found it! {} in name'.format(z, x + 1)) # except ValueError: # print('Not found it! - Occured ValueError') # else: # print('Ok! else.') # # print() # print('pass') # 문법적인 에러가 날 것 같은 경우에는 try문으로 감싸 놓는 것이 좋음 #예제2 # try: # z = 'Kim' #Cho로 바꾸면 예외 처리되고, 예외 발생하면 else실행 되지 않음. # x = name.index(z) # print('Found it! {} in name'.format(z, x + 1)) # except Exception: #안써도 되지만, 어떤 예외가 발생했는지 알 수 없음. Exception은 모든 예외의 상위 # print('Not found it! - Occured Error') # else: # print('Ok! else.') # # print() # print('pass') #예제3 # try: # z = 'Oh' # x = name.index(z) # print('Found it! {} in name'.format(z, x + 1)) # except Exception: #안써도 되지만, 어떤 예외가 발생했는지 알 수 없음 # print('Not found it! - Occured Error') # else: # print('Ok! else.') # finally: # print('OK! finally') #finally는 예외가 발생했어도 마지막에 꼭 작업해야하는 경우! # # print() # print('pass') #예제4 #예외 발생 : raise #raise 키워드로 예외 직접 발생 try: a = 'Kim' if a == 'Kim': print('OK! Pass!') else: raise ValueError #일부러 직접 예외를 만들어서 처리하는 것임 except ValueError: print('Occured Exception!') else: print('OK else')
c452668b786727a3438a06c22230e08c3eb01914
Eunbae-kim/python
/basic9.py
850
4.1875
4
# 파이썬 # 튜플 (Tuple) : 리스트(list)와 비슷하지마, 다만 한번 설정되면 변경 불가 # 튜플은 변경 불과 tuple = (1, 2, 3) print(tuple ," : tuple type ", type(tuple)) # 리스트는 하나의 원소로 취급가능하기 때문에 리스트를 튜플의 각 원소로 사용가능 list1 = [1,3,5] list2 = [2,4,6] tuple2 = (list1, list2) print(tuple2) #2개의 리스트가 각각 원소로 들어감 print(tuple2[0][1]) #하지만, 튜플은 변경불가능 하기 떄문에 tuple[0] = 1하면 오류 #cf) tuple2[0][1] = 3는 가능. 이건 리스트를 바꾸는 거니까 # 리스트와 특성이 비슷하기 때문에 # 인덱싱, 슬라이싱 가능 tuple3 = (0,1,2,3,4,5,6,7,8,9) print(tuple3[0:5]) print(tuple3[-1]) print(tuple3[:-1]) print(tuple3[0:-1:2]) print(tuple3[0:3]*2) #[0,3) 까지 2번 반복 출력
046ec8d5a65e6f793e93f57793edd4d7469b188d
Eunbae-kim/python
/basic2.py
794
3.875
4
# 문자열 자료형의 함수 a = "INTERSTING PYTHON" print(a) #특정 문자열을 대체할 떄 : replace b = a.replace("INTERSTING","love") print(b) #문자열에 특정 문자가 몇개 포함되어있는지 알고 싶을 떄 : count print(a.count('N')) print(a.count('n')) #파이썬은 대소문자 구분 #특정한 문자의 위치를 반환 : find print(a.find("PYT")) #시작하는 값을 return해줌 print(a.find("love")) #없는 문자를 찾을 때는 -1을 return #소문자를 모두 대문자or 소문자로 바꿔 :upper lower print(b) print(b.upper()) print(b.lower()) #특정한 단어를 지우고자 할 때 : strip print(b.strip("love ")) #하나의 문자열을 여러개의 문자열 배열로 나눌 떄 : split c = a.split(" ") print(c) #배열로 변환됨
1bcbbf8100ba55c13f4772d23b4956ece040adb0
CrazyPython/99-python-problems
/99-04.py
98
3.6875
4
# Return the length of a list list = [0, 1, 2, 3, 4, 5] def length(list): return len(list)
9d73a041f7b28c140f00aa2d7cf7c8d3f270cb91
Deepthibr28/software-testing
/tutorials/unittests/python/src/grader.py
386
3.9375
4
def calculator(grade): if grade > 90: return 'A' elif 80<grade <= 90 : return 'B' elif 70<grade <= 80 : return 'C' elif 60<grade <= 70 : return 'D' def calculate(grade): if grade > 90: return 'A' elif 80 < grade <= 90: return 'B' elif 70 < grade <= 80: return 'C' else: return 'F'
39de0dd6e5eec91dccfcc49cbaa45d088816a07e
fxbabin/Piscine_python_django
/d01/ex07/periodic_table.py
3,348
3.53125
4
#! /usr/bin/python3 import sys def print_header(file): file.write("<!DOCTYPE html>\n<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"utf-8\"/>\n\t\t<title>periodic table</title>\n\t</head>\n\t<body>\n") def print_end(file): file.write("\t</body>\n</html>") def print_line(out_file, periodic_table, space_1=0, nb_elem_1=0, space_2=0, nb_elem_2=0, space_3=0): out_file.write("\t\t\t<tr>\n") pos = 0 for _ in range(space_1): out_file.write("\t\t\t\t<td></td>\n") for _ in range(nb_elem_1): out_file.write("\t\t\t\t<td style=\"border: 1px solid black; padding: 10px\">\n") out_file.write("\t\t\t\t<h4>{}</h4>\n".format(periodic_table[pos]["element"])) out_file.write("\t\t\t\t\t<ul>\n") out_file.write("\t\t\t\t\t\t<li>{}</li>\n".format(periodic_table[pos]["atom_num"])) out_file.write("\t\t\t\t\t\t<li>{}</li>\n".format(periodic_table[pos]["symbol"])) out_file.write("\t\t\t\t\t\t<li>{}</li>\n".format(periodic_table[pos]["mass"])) out_file.write("\t\t\t\t\t</ul>\n") out_file.write("\t\t\t\t</td>\n") pos += 1 for _ in range(space_2): out_file.write("\t\t\t\t<td></td>\n") for _ in range(nb_elem_2): out_file.write("\t\t\t\t<td style=\"border: 1px solid black; padding: 10px\">\n") out_file.write("\t\t\t\t<h4>{}</h4>\n".format(periodic_table[pos]["element"])) out_file.write("\t\t\t\t\t<ul>\n") out_file.write("\t\t\t\t\t\t<li>{}</li>\n".format(periodic_table[pos]["atom_num"])) out_file.write("\t\t\t\t\t\t<li>{}</li>\n".format(periodic_table[pos]["symbol"])) out_file.write("\t\t\t\t\t\t<li>{}</li>\n".format(periodic_table[pos]["mass"])) out_file.write("\t\t\t\t\t</ul>\n") out_file.write("\t\t\t\t</td>\n") pos += 1 for _ in range(space_3): out_file.write("\t\t\t\t<td></td>\n") out_file.write("\t\t\t</tr>\n") def main(): periodic_table = [] with open('periodic_table.txt', 'r') as in_file: for line in in_file: line_split = line.strip().split(',') element = line_split[0].split('=')[0].strip() atom_num = line_split[1].split(':')[1] symbol = line_split[2].split(':')[1].strip() mass = line_split[3].split(':')[1] tmp = {} #if element not in periodic_table: tmp["element"] = element tmp["atom_num"] = atom_num tmp["symbol"] = symbol tmp["mass"] = mass periodic_table.append(tmp) with open('periodic_table.html', 'w') as out_file: print_header(out_file) out_file.write("\t\t<table>\n") print_line(out_file, periodic_table[0:2], nb_elem_1=1, space_2=15, nb_elem_2=1) print_line(out_file, periodic_table[2:10], nb_elem_1=2, space_2=9, nb_elem_2=6) print_line(out_file, periodic_table[10:19], nb_elem_1=2, space_2=9, nb_elem_2=6) print_line(out_file, periodic_table[19:37], nb_elem_1=17) print_line(out_file, periodic_table[37:54], nb_elem_1=17) print_line(out_file, periodic_table[54:71], nb_elem_1=17) print_line(out_file, periodic_table[71:88], nb_elem_1=17) out_file.write("\t\t</table>\n") print_end(out_file) if __name__ == '__main__': main()
d2417f9b2a06ca9447d554ecc34998fac1f1d59d
yossef21-meet/meet2019y1lab1
/turtleLab1-Yossi.py
1,457
4.5
4
import turtle # Everything that comes after the # is a # comment. # It is a note to the person reading the code. # The computer ignores it. # Write your code below here... turtle.penup() #Pick up the pen so it doesn’t #draw turtle.goto(-200,-100) #Move the turtle to the #position (-200, -100) #on the screen turtle.pendown() #Put the pen down to start #drawing #Draw the M: turtle.goto(-200,-100+200) turtle.goto(-200+50,-100) turtle.goto(-200+100,-100+200) turtle.goto(-200+100,-100) #E turtle.penup() turtle.forward(50) turtle.pendown() turtle.forward(100) turtle.backward(100) turtle.left(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.backward(100) turtle.left(90) turtle.forward(100) turtle.right(90) turtle.forward(100) #Second E turtle.penup() turtle.right(90) turtle.forward(200) turtle.left(90) turtle.forward(50) turtle.pendown() turtle.forward(100) turtle.backward(100) turtle.left(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.backward(100) turtle.left(90) turtle.forward(100) turtle.right(90) turtle.forward(100) #T turtle.penup() turtle.forward(50) turtle.pendown() turtle.forward(150) turtle.backward(75) turtle.right(90) turtle.forward(200) # ...and end it before the next line. turtle.mainloop() # turtle.mainloop() tells the turtle to do all # the turtle commands above it and paint it on the screen. # It always has to be the last line of code!
221fb99b3dcf52ccf43cff5f3d897f448ca3fede
samsonosiomwan/SQL-model-practice
/sqlite/setup.py
645
3.65625
4
from sqlite.interfaces import ToSQLInterface import sqlite3 import pandas class SetUpSQL(ToSQLInterface): '''this class initializies sqlite connection to sqlite3 and creates database if none exists, it has convert_to_sql method which opens csv files and converts it sql''' def __init__(self): self.connection = sqlite3.connect('sqlite/grades.db') self.cursor = self.connection.cursor() def convert_to_sql(self): with open('sqlite/grades.csv','r') as csv_to_sql: csv_data = pandas.read_csv(csv_to_sql) csv_data.to_sql('grades',self.connection, if_exists = 'replace', index=False)
4e841521e03d9b05ab438f2c50bfd20aaf72c99d
vt-dataengineer/leetcode
/leetcode_problems/file4/pivot index.py
670
3.6875
4
# Input: # nums = [1, 7, 3, 6, 5, 6] # Output: 3 # Explanation: # The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. # Also, 3 is the first index where this occurs. # def one(a): # nums = [1, 7, 3, 6, 5, 6] # i = 1 # s = 0 # s1 = 0 # for x in range(0,i): # s+=nums[x] # print(s) # # # for y in range(i,len(nums)): # s1+=nums[y] # print(s1) # # if s == s1: # print('yes') # else: # print('No') # i+=1 # one(i) # # one(1) def one(i): nums = [1, 7, 3, 6, 5, 6] for x in range(i,len(nums)+1):
c680534217d72ebbfe129641a80193f3a1514014
vt-dataengineer/leetcode
/leetcode_problems/file4/missing numbers in array.py
267
3.625
4
# Input: # [4,3,2,7,8,2,3,1] # # Output: # [5,6] l = [1,1] ll = [] s = sorted(l) print(s) for x in s: if x > len(s): break if len(s) == 1: ll.append(s+1) else: for y in range(1,len(s)+1): if y not in s: ll.append(y) print(ll)
0a5d2c164e84ea9d620ea68d1b1f33fb5ba3a119
vt-dataengineer/leetcode
/leetcode_problems/file3/sort colors.py
390
3.828125
4
# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. # # Note: You are not suppose to use the library's sort function for this problem. # # Example: # # Input: [2,0,2,1,1,0] # Output: [0,0,1,1,2,2] l = [2,0,2,1,3,1,0] mini = l.count(min(l)) print(mini) maxi = l.count(max(l)) print(maxi) print(str(min(l))*mini) print(str(max(l))*maxi)
c42e00e3703d52b2603d3480d2d5e1ae984e769b
vt-dataengineer/leetcode
/leetcode_problems/file5/list of multiples.py
178
3.90625
4
# list_of_multiples(7, 5) ➞ [7, 14, 21, 28, 35] ll = [] def list_of_multiples(x,y): for z in range(1,y+1): ll.append(x*z) print(list_of_multiples(7,5)) print(ll)
e148cfa990163d8ca46623ad862ac14e2757fd95
vt-dataengineer/leetcode
/leetcode_problems/file2/test50.py
326
3.71875
4
#1 22 11 2 1 22 """ 1 22 11 2 11 22 ...... #Input: 6 #Output: 3 #Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3. if __name__=='__main__': a = 1 s ='1221121221221121122' one = '' for x in range(0,len(str(a))): one+=s[x] print(one.count('1'))
73a9eb87144825ce39342bdac12f4f9ef793cd6c
vt-dataengineer/leetcode
/leetcode_problems/file3/plus one.py
347
3.96875
4
# Example 1: # # Input: [1,2,3] # Output: [1,2,4] # Explanation: The array represents the integer 123. # Example 2: # # Input: [4,3,2,1] # Output: [4,3,2,2] # Explanation: The array represents the integer 4321. l = [4,3,2,1] z = '' l1 = [] for x in l: z = str(z)+str(x) print(z) add = int(z)+1 for y in str(add): l1.append(y) print(l1)
e17344a483ada87f2a693a04752428f69e1e2e25
vt-dataengineer/leetcode
/leetcode_problems/file2/test47.py
894
3.828125
4
#numbers = "0123456789" #lower_case = "abcdefghijklmnopqrstuvwxyz" #upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #special_characters = "!@#$%^&*()-+" if __name__=='__main__': s = 'aacabdddd23' lower_case = "abcdefghijklmnopqrstuvwxyz" upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" numbers = "0123456789" lo = '' up = '' num = '' move = 0 if len(s)>=6 and len(s)<=20: for x in s: if x in lower_case: lo = lo+x elif x in upper_case: up = up+x elif x in numbers: num = num+x print(lo) print(up) print(num) if len(lo) == 0: print('Enter a lowercase') elif len(up)==0: print('Enter an uppercase') elif len(num)==0: print('Enter one numeric value') else: print('Short length')
2532cce1afad6219915ecec7fb7ab10c4c926cf7
vt-dataengineer/leetcode
/leetcode_problems/file/test29.py
261
3.578125
4
# Input: 13 # Output: 6 # Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. if __name__ == '__main__': a = str(13) c=0 for i in range(1,int(a)+1): if '1' in str(i): c+=1 print(i) print(c)
52dd4ffb2ddb42e58e744b2c8164dbd6a78d4bc7
vt-dataengineer/leetcode
/leetcode_problems/file4/robot return to origin.py
661
3.921875
4
# Input: "UD" #The move sequence is represented by a string, and the character moves[i] represents its ith move. # Valid moves are R (right), L (left), U (up), and D (down). # If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false. # Output: true # Explanation: The robot moves up once, and then down once. # All moves have the same magnitude, so it ended up at the origin where it started. s = 'LRUD' y = 0 z = 0 for x in s: if x == 'U': y+=1 elif x == 'D': y-=1 elif x == 'L': z+=1 elif x == 'R': z-=1 if y == z: print('True') else: print('False')
2544ba5f06724bbab067a818fb3ef49fb1ffd0c4
vt-dataengineer/leetcode
/leetcode_problems/test4.py
341
3.546875
4
if __name__ == "__main__": l = (1,0,1,0,0) z=0 m =0 last_index = -1 while True: try: last_index = l.index(z, last_index + 1) print(last_index) if last_index> l.index(1): m = m +1 print("Max = "+str(m)) except ValueError: break
fb7c0cebce3fac2963591d30175d6d9f35be7cde
dev-ds/PyPractice
/prisoners.py
1,096
3.890625
4
#!/bin/python3 ''' A jail has N prisoners, and each prisoner has a unique id number, S, ranging from 1 to N. There are M sweets that must be distributed to the prisoners. The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending S), and then, starting with some random S, distribute one candy at a time to each sequentially numbered prisoner until all M candies are distributed. For example, if the jailer picks prisoner S = 2, then his distribution order would be (2, 3, 4, ... n-1, n, 1, 2, 3 ...) until all M sweets are distributed. But wait—there's a catch—the very last sweet is poisoned! Can you find and print the ID number of the last prisoner to receive a sweet so he can be warned? ''' import sys def saveThePrisoner(n, m, s): if (m+s-1)%n == 0: return (n) else: return (m+s-1)%n # Complete this function t = int(input().strip()) for a0 in range(t): n, m, s = input().strip().split(' ') n, m, s = [int(n), int(m), int(s)] result = saveThePrisoner(n, m, s) print(result)
26a431a7caa6b98a3f938497b540cfd161382a54
SamEhret/codeChallenge
/python_code_challenge/src/inputFunctions.py
1,009
3.859375
4
import sys import re # Take input or give default input def getInput(): inputString = input('Please enter the string to process') if not inputString: inputString='(id,created,employee(id,firstname,employeeType(id),lastname),location)' return inputString # Check that nesting in "()"" is valid # String will need to start with "(" and end with ")" # String will need same number of "(" and ")" def isValid(inputString): if inputString.count('(') != inputString.count(')'): return False elif inputString[0] != '(' or inputString[-1] != ')': return False else: return True # Process inputString to list # First removes start and end parenthesis # Split string on "(" ")" and "," # Filter out "[,]" and "[]" def processInput(inputString): inputString = re.search(r'\((.+)\)', inputString)[1] inputString = re.split('([(),])', inputString) processedString = filter(lambda s: not (s[:]==',' or s[:]==''), inputString) return processedString
67dafd87e132064d3a492f3e8c9bdde80dae1110
Katy-Scha/programming_practice
/4 week/N6.py
459
3.96875
4
""" was a[i] before?""" a = input() a = a.split() before = set([]) for i in range(len(a)): if set([a[i]]) & before != set([]): print('yes') else: before.add(a[i]) print('no') """print (bool(a[0] == '1')) print(before & '1') a = [1, 2, 3, 1, 2, 3] before = set([]) for i in range(len(a)): if set([a[i]]) & before != set([]): print('yes', before) else: print('no', before) before.add(a[i]) """
81f43aec85cede4c308070be22805fed734bf755
84436/AI-Project-02
/src/map_generator.py
5,173
3.515625
4
#!/bin/env python3 # Map generator (standalone): utility for generating random maps from random import randrange import os # Parameters # No checks will be applied on parameters; please make sure it's sane. map_size = 10 # count_pit = 10 # count_wumpus = 10 # count_gold = 10 count_pit = randrange(0, 10+1) count_wumpus = randrange(1, 10+1) count_gold = randrange(0, 10+1) # Map format: see docs for export_map() gen_format = 'readable' # gen_format = 'compact' #################### # Working directory BASE_DIR = os.path.dirname(os.path.realpath(__file__)) + '/..' MAPS_DIR = BASE_DIR + '/maps' # Storage set_blacklist = set() # exclude me breeze = [] pit = [] stench = [] wumpus = [] gold = [] player = None # Subroutine: Generate a random location random_loc = lambda : (randrange(0, map_size), randrange(0, map_size)) def adjacents(loc): """Get adjacents of a location. """ x, y = loc adjacent_list = [] if (x-1 >= 0) : adjacent_list.append((x-1, y)) if (x+1 <= map_size-1) : adjacent_list.append((x+1, y)) if (y-1 >= 0) : adjacent_list.append((x, y-1)) if (y+1 <= map_size-1) : adjacent_list.append((x, y+1)) return adjacent_list def generate_map(): """Randomly generate location of items on map based on given parameters. """ global count_gold, count_pit, count_wumpus global gold, pit, breeze, wumpus, stench, player # Player player = random_loc() set_blacklist.add(player) for each in adjacents(player): set_blacklist.add(each) # Gold while count_gold > 0: gold_i = random_loc() if gold_i not in set_blacklist: set_blacklist.add(gold_i) gold.append(gold_i) count_gold -= 1 # Pit while count_pit > 0: pit_i = random_loc() if pit_i not in set_blacklist: set_blacklist.add(pit_i) pit.append(pit_i) count_pit -= 1 # Wumpus while count_wumpus > 0: wumpus_i = random_loc() if wumpus_i not in set_blacklist: set_blacklist.add(wumpus_i) wumpus.append(wumpus_i) count_wumpus -= 1 # Pit: surrounding breeze for each_pit in pit: for each_potential_breeze in adjacents(each_pit): set_blacklist.add(each_potential_breeze) breeze.append(each_potential_breeze) # Wumpus: surrounding stench for each_wumpus in wumpus: for each_potential_stench in adjacents(each_wumpus): set_blacklist.add(each_potential_stench) stench.append(each_potential_stench) def export_map(format='readable'): """Serialize the current map (for writing to file) #### Available formats: - `compact`: Conform to the format given in original problem statement. - `readable`: The more human-readable version of `compact`, with even-map_size string per tiles """ global map_size, map_size global gold, pit, breeze, wumpus, stench map_2d_str = '' if format in ['compact', 'readable']: # Empty map map_2d = [['' for _ in range(map_size)] for _ in range(map_size)] # Add player px, py = player map_2d[py][px] = 'A' # Add objects for each in gold: map_2d[each[1]][each[0]] += 'G' for each in pit: map_2d[each[1]][each[0]] += 'P' for each in wumpus: map_2d[each[1]][each[0]] += 'W' for each in breeze: if all([ x not in map_2d[each[1]][each[0]] for x in 'BPW' ]): map_2d[each[1]][each[0]] += 'B' for each in stench: if all([ x not in map_2d[each[1]][each[0]] for x in 'SPW' ]): map_2d[each[1]][each[0]] += 'S' # If `readable` format: pad spaces if format == 'readable': max_tile_map_size = max([ len(tile) for each_row in map_2d for tile in each_row ]) map_2d = [ [tile.rjust(max_tile_map_size, '-') for tile in each_row] for each_row in map_2d ] # Serialize for each_line in map_2d: map_2d_str += '.'.join(each_line) + '\n' return map_2d_str ########## if __name__ == "__main__": # Generate map generate_map() # Some info filename = '{}G-{}P-{}W.txt'.format( len(gold), len(pit), len(wumpus) ) print('Map = {} * {}\nPlayer = {}\nFilename = {}'.format( map_size, map_size, player, filename )) # Write to file with open(MAPS_DIR + '/' + filename, 'w+') as file: file.write('{}\n'.format(map_size)) # map size file.write(export_map(format=gen_format)) print('File written.') # Debug # print('All locations:', set_blacklist) # print('Gold:', gold) # print('Pit:', pit) # print('Wumpus:', wumpus) # print('Breeze:', breeze) # print('Stench:', stench)
8d888e53b71da82ae029c0ffc4563edc84b8283d
EdwardMoseley/HackerRank
/Python/INTRO Find The Second Largest Number.py
661
4.15625
4
#!/bin/python3 import sys """ https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list Find the second largest number in a list """ #Pull the first integer-- we don't need it junk = input() def secondLargest(arg): dat = [] for line in arg: dat.append(line) dat = dat[0].split(' ') i = 0 while i < len(dat): dat[i] = int(dat[i]) i += 1 dat.sort() #Find the first integer that is not the maximum integer while decrementing for j in reversed(range(len(dat))): if dat[j] is not max(dat): return dat[j] print(secondLargest(sys.stdin))
bbe8b6100246aa2f58fca457929827a0897e9be5
arickels11/Module4Topic3
/topic_3_main/main_calc.py
1,637
4.15625
4
"""CIS 189 Author: Alex Rickels Module 4 Topic 3 Assignment""" # You may apply one $5 or $10 cash off per order. # The second is percent discount coupons for 10%, 15%, or 20% off. # If you have cash-off coupons, those must be applied first, then apply the percent discount coupons on the pre-tax # Then you add tax at 6% and shipping according to these guidelines: # # up to $10 dollars, shipping is $5.95 # $10 and up to $30 dollars, shipping is $7.95 # $30 and up to $50 dollars, shipping is $11.95 # Shipping is free for $50 and over def calculate_order(price, cash_coupon, percent_coupon): if price < 10.00: if (price - cash_coupon)*(1 - (percent_coupon / 100)) < 0: return 5.95 # if coupons get price to under zero, customer only pays shipping costs else: return round((((price - cash_coupon)*(1 - (percent_coupon / 100)))*1.06) + 5.95, 2) elif 10.00 <= price < 30.00: return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06) + 7.95, 2) elif 30.00 <= price < 50.00: return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06) + 11.95, 2) elif price >= 50.00: return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06), 2) else: print("Please correct your input") if __name__ == '__main__': initial_price = float(input("What is the price?")) cash = float(input("What is the cash discount, $5 or $10?")) percent = float(input("What is the percent discount, 10%, 15%, or 20%?")) final_price = float(calculate_order(initial_price, cash, percent)) print(final_price)
51eb05addd6e4abb3363eaaf1eb7ad78cc2506af
Jay-Wang-zechong/Wang-s-python-code
/python抽签/抽签.py
171
3.59375
4
import random people_num = 7 number = random.randint(1,people_num) print(number) people_num = 6 number = random.randint(1,people_num) print(number) input("Press <Enter>")
a6e545b4dbff5c1866ee076535d3b637c8e063b7
tehologist/x-venture
/version_new/World/player.py
355
3.515625
4
"""Player class which represents in game character""" class player: """Initialize name attribute""" def __init__(self, name, id): self.name = name self.id = id self.location = "" self.description = "" self.isPlayer = true def do_say(self, args): pass def do_look(self, args): pass
27006f8290968a5d89a8d0d25355538212718075
Manny-Ventura/FFC-Beginner-Python-Projects
/madlibs.py
1,733
4.1875
4
# string concatenation (akka how to put strings together) # # suppose we want to create a string that says "subscribe to ____ " # youtuber = "Manny Ventura" # some string variable # # a few ways... # print("Subscribe to " + youtuber) # print("Subscribe to {}".format(youtuber)) # print(f"subscribe to {youtuber}") adj = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_person = input("Famous Person: ") noun1 = input("Noun: ") noun2 = input("Noun: ") place = input("Make a name for a place: ") number = input("Number : ") madlib = f"My time on earth is absolutely {adj}! All i want to do is {verb1} \n\ and {verb2} because I miss my home planet. Back home in the land of {place}, \n\ we had {noun1}'s running around all the time. Not only that, but some {noun2}'s \n\ even got along with the them! It was a crazy time, and I want to go back... \n\ I just... I miss my kids man. \n\ I wasn't there for them like I should have. Heck, LOOK WHERE I AM NOW. \n\ Its a scary feeling not being sure if I ever will be a good dad man, or ever was. \n\ Its not like wanting to be is enough. And its not fair to try and explain \n\ The hardships I go through to be there for them. There kids you know? \n\ Im supposed to not make it seem so scary, but what's scary is that \n\ They probably learned that life is scary and sometimes those that \n\ want to be there for them wont. Tough as nails, but it breaks my heart, \n\ cause its not fair to them. They should not have to tough BECAUSE of me. \n\ I hope at least they know I do love them, and that I am just a bad father \n\ I owe them at least that. Love all {number} of ya, \n\ \n\ Pops" print(madlib)
0acf51277b792ba4159316f07096297844dbadd0
dashkazaitseva/yandex.traning
/2 июня. Тестирование/B.py
158
3.65625
4
a = [0, 0, 0] a[0] = int(input()) a[1] = int(input()) a[2] = int(input()) a.sort() if (a[2] < a[0] + a[1]): print("YES") else: print("NO")
e1f02b9b444ee75a76e85115bef94eda1c17a59f
chrisbryan88/ProjectEuler
/PE6.py
883
3.703125
4
''' projecteuler.net/problem=6 The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. ''' import time start = time.time() def sumofsquares(num): result = 0 for i in range(1,num+1): result += i**2 return result def squareofsum(num): iter_sum = 0 for i in range(1,num+1): iter_sum += i return iter_sum**2 end = time.time() print(squareofsum(100)-sumofsquares(100)) print(end-start) #FINAL SOLUTION: 25164150 TIME: 1.6689300537109375e-06s
19b1c93472b95b084d5561a79ce1f2c969ebbcdf
Ksenaty/PythonLearning
/Homework/Lesson1/task4.py
333
3.765625
4
user_number = int(input('Введите число>>>')) max_number = 0 while user_number > 0: comparing_number = user_number % 10 if max_number < comparing_number: max_number = comparing_number user_number //= 10 else: user_number //= 10 comparing_number = user_number % 10 print(max_number)
6d429a601525ddbd21a71d6b0cb2ca251464600a
shirdha/ss
/vowel/largest1.py
117
3.53125
4
a,b,c=map(int,input().split()) if a>=b and a>=c: print(a) elif b>=c and b>=-a: print(b) else: print(c)
1b00aac23ad6f8c35ac1e5dd520630abc28ababb
shirdha/ss
/factplay.py
150
3.859375
4
n=int(input("")) fact=1 if(n<=0): print(fact) elif(n==1): print(fact) if(n>1): for i in range(1,n+1): fact=fact*i print(fact)
e6df2e20e5dae1904746a8c676d8d6610f6b74c5
shirdha/ss
/countdigits_play.py
137
3.890625
4
string=input("") count1=0 for i in string: if(i.isdigit()): count1=count1+1 #count is incremented by one print(count1)
658e3113ab34936c6bd1a276170c5d99da8f3231
shirdha/ss
/sum.py
75
3.828125
4
n=int(input("")) sum1=0 for i in range(1,n+1): sum1=sum1+i print(sum1)
89f89f5427df86d1ee3b38d7c38a1e48863d44cd
nclslmx/Inertial_action_recognition
/model/hierarchical_CNN_linear.py
20,499
3.625
4
import torch import torch.nn as nn def weights_init(m): """ Standard module's weight initialization :param m: pytorch module """ if isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight, gain=1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Conv1d): nn.init.xavier_uniform_(m.weight, gain=1) class Model(nn.Module): """ Architecture of the model. It includes the 5 convolution blocks, the parsing strategy in order to learn a specific set of parameters for each action through grouped convolutions and both binary and multiclass classifiers """ def __init__(self, dummy_input, f_1, f_2, f_3, f_4, f_5, nb_class, bin_layer, multi_layer ): """ Initialization of the model :param dummy_input: Dummy input used to automatically initialize the model :param f_1: The number of filters of the first convolution block :param f_2: The number of filters of the second convolution block :param f_3: The number of filters of the third convolution block :param f_4: The number of filters of the forth convolution block :param f_5: The number of filters of the fifth convolution block :param nb_class: The number of class of the data set :param bin_layer: The number of neurons in the fully connected layers of the binary classifier :param multi_layer: The number of neuros in the fully connected layers of the multiclass classifier """ super().__init__() self.__name__ = 'hierarchical CNN' ################################################## Input formating ############################################# print(f'The size of the input is : {dummy_input.size()}') x = dummy_input # Permute the input in order to adopt the following order : # Batch_examples / Signals (acceleration and angular variation rate) / time frames x = x.permute(0,2,1) print(f'After permutation : {x.size()}') ################################################### Block and groups 1 ######################################### # First convolution block class conv_block_1(nn.Module): def __init__(self, ): super(conv_block_1, self).__init__() self.block_1 = nn.Sequential( nn.Conv1d(x.size()[1], f_1, kernel_size=1, bias=False), nn.SELU(), nn.BatchNorm1d(f_1, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.MaxPool1d(2)) def forward(self, x): """ :param x: The previous time series :return: The processed time series by the convolution block's operations """ out = self.block_1(x) return out # First block convolution group (one block for each action) class block_1_groups(nn.Module): def __init__(self, nb_group): super(block_1_groups, self).__init__() # Initialize the first block for each group self.group = nn.ModuleList( [conv_block_1() for _ in range(nb_group)]) def forward(self, x): """ :param x: The concatenated previous time series of all the groups :return: The processed time series for each group and the sampled features """ for i, pose in enumerate(self.group): if i < 1: out = pose(x) else: out = torch.cat((out, pose(x)), dim=1) max_block_1 = torch.max(out,2) min_block_1 = torch.min(out, 2) return [out, max_block_1, min_block_1] # Initialize the first convolution block for all the groups self.block_1_groups = block_1_groups(nb_class) # Apply the first convolution block operations group_conv_1 = self.block_1_groups(x) # The outputted processed time series which is fed to the next block x = group_conv_1[0] # The feature vector's sampled elements of the first time series for each group max_block_1 = group_conv_1[1] min_block_1 = group_conv_1[2] print(f'The output of the first group is of size: {x.size()}') ################################################### Block and groups 2 ############################################# # Second convolution block class conv_block_2(nn.Module): def __init__(self, ): super(conv_block_2, self).__init__() self.create_pose_mixer_conv = nn.Sequential( nn.Conv1d(f_1, f_2, kernel_size=3, bias=False), nn.BatchNorm1d(f_2, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.MaxPool1d(2)) def forward(self, x): out = self.create_pose_mixer_conv(x) return out # Grouped convolution of the second block class block_2_groups(nn.Module): def __init__(self, nb_group, f_1): super(block_2_groups, self).__init__() self.input_group_size = f_1 self.group = nn.ModuleList( [conv_block_2() for _ in range(nb_group)]) def forward(self, x): for i, pose_mixer in enumerate(self.group): if i < 1: out = pose_mixer(x[:,0:self.input_group_size,:]) else: out = torch.cat((out, pose_mixer(x[:,i*self.input_group_size:(i+1)*self.input_group_size,:])), dim=1) # Gives the maximum activation value for each channels in the time series max_block_2 = torch.max(out, 2) min_block_2 = torch.min(out, 2) return [out, max_block_2, min_block_2] # Initialize the second convolution block for all the groups self.block_2_groups = block_2_groups(nb_class, f_1) # Apply the first convolution block operations group_conv_2 = self.block_2_groups(x) # The outputted processed time series which is fed to the next block x = group_conv_2[0] # The feature vector's sampled elements of the second time series for each group max_block_2 = group_conv_2[1] min_block_2 = group_conv_2[2] print(f'The output of the second group is of size: {x.size()}') ################################################### Block and groups 3 ######################################## # Third convolution block class conv_block_3(nn.Module): def __init__(self, ): super(conv_block_3, self).__init__() self.create_motionlet_conv = nn.Sequential( nn.Conv1d(f_2, f_3, kernel_size=5, bias=False), nn.BatchNorm1d(f_3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.MaxPool1d(2)) def forward(self, x): out = self.create_motionlet_conv(x) return out # Grouped convolution of the third block class block_3_groups(nn.Module): def __init__(self, nb_group, f_3): super(block_3_groups, self).__init__() self.nb_group = nb_group self.input_group_size = f_3 self.group = nn.ModuleList([conv_block_3() for _ in range(nb_group)]) def forward(self, x): for i, motionlet in enumerate(self.group): if i < 1: out = motionlet(x[:,0:self.input_group_size,:]) else: out = torch.cat((out, motionlet(x[:,i*self.input_group_size:(i+1)*self.input_group_size,:])), dim=1) # Gives the maximum activation value for each channels in the time serie max_block_3 = torch.max(out, 2) min_block_3 = torch.min(out, 2) return [out, max_block_3, min_block_3] self.block_3_groups = block_3_groups(nb_class, f_3) group_conv_3 = self.block_3_groups(x) x = group_conv_3[0] max_block_3 = group_conv_3[1] min_block_3 = group_conv_3[2] print(f'The output of the third group is of size: {x.size()}') ################################################### Block and groups 4 ######################################### # Forth convolution block class conv_block_4(nn.Module): def __init__(self, ): super(conv_block_4, self).__init__() self.create_actionlet_conv = nn.Sequential( nn.Conv1d(f_3, f_4, kernel_size=7, bias=False), nn.BatchNorm1d(f_4, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.MaxPool1d(2)) def forward(self, x): out = self.create_actionlet_conv(x) return out # Grouped convolution of the forth block class block_4_groups(nn.Module): def __init__(self, nb_group, input_group_size): super(block_4_groups, self).__init__() self.input_group_size = input_group_size self.nb_group = nb_group self.group = nn.ModuleList( [conv_block_4() for _ in range(nb_group)]) def forward(self, x): for i, actionlet in enumerate(self.group): if i < 1: out = actionlet(x[:,0:self.input_group_size,:]) else: out = torch.cat((out, actionlet(x[:,i*self.input_group_size:(i+1)*self.input_group_size,:])), dim=1) # Gives the maximum activation value for each channels in the time series max_block_4 = torch.max(out,2) min_block_4 = torch.min(out,2) return [out, max_block_4, min_block_4] self.block_4_groups = block_4_groups(nb_class, f_4) group_conv_4 = self.block_4_groups(x) x = group_conv_4[0] max_block_4 = group_conv_4[1] min_block_4 = group_conv_4[2] print(f'The output of the forth group is of size: {x.size()}') ################################################### Block and groups 5 ######################################### # Fifth convolution block class conv_block_5(nn.Module): def __init__(self, ): super(conv_block_5, self).__init__() self.create_card_conv = nn.Sequential( nn.Conv1d(f_4, f_5, kernel_size=4, padding=1, bias=False), nn.BatchNorm1d(f_5, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.MaxPool1d(2)) def forward(self, x): out = self.create_card_conv(x) return out # Grouped convolution of the fifth block class block_5_groups(nn.Module): def __init__(self, nb_group, input_group_size): super(block_5_groups, self).__init__() self.input_group_size = input_group_size self.nb_group = nb_group self.group = nn.ModuleList( [conv_block_5() for _ in range(nb_group)]) def forward(self, x): for i, action_card in enumerate(self.group): if i < 1: out = action_card(x[:,0:self.input_group_size,:]) else: out = torch.cat((out, action_card(x[:,i*self.input_group_size:(i+1)*self.input_group_size,:])), dim=1) # Gives the maximum activation value for each channels in the time series max_block_5 = torch.max(out,2) min_block_5 = torch.min(out,2) return [out, max_block_5, min_block_5] self.block_5_groups = block_5_groups(nb_class, f_5) group_conv_5 = self.block_5_groups(x) x = group_conv_5[0] max_block_5 = group_conv_5[1] min_block_5 = group_conv_5[2] print(f'The output of the fifth group is of size: {x.size()}') ########################################### Binary max group ################################################### class binary_groups(nn.Module): def __init__(self, nb_group, f_1, f_2, f_3, f_4, f_5): """ Parse the sampled elements for each group in order to create the feature vector of each binary classifier The element of each feature vector are concatenated together and each feature vector is concatenated one after the other. :param nb_group: :param f_1: Number of dimension of the first time series' time step vector :param f_2: Number of dimension of the second time series' time step vector :param f_3: Number of dimension of the third time series' time step vector :param f_4: Number of dimension of the forth time series' time step vector :param f_5: Number of dimension of the fifth time series' time step vector """ super(binary_groups, self).__init__() self.nb_group = nb_group self.f_1 = f_1 self.f_2 = f_2 self.f_3 = f_3 self.f_4 = f_4 self.f_5 = f_5 def forward(self, max_block_1, max_block_2, max_block_3, max_block_4, max_block_5, min_block_1, min_block_2, min_block_3, min_block_4, min_block_5): for i in range(self.nb_group): if i < 1: out = torch.cat((max_block_1[0][:,0:self.f_1], max_block_2[0][:, 0:self.f_2], max_block_3[0][:,0:self.f_3], max_block_4[0][:,0:self.f_4], max_block_5[0][:, 0:self.f_5], min_block_1[0][:, 0:self.f_1], min_block_2[0][:, 0:self.f_2], min_block_3[0][:, 0:self.f_3], min_block_4[0][:, 0:self.f_4], min_block_5[0][:, 0:self.f_5]), dim=1) else: out_next = torch.cat(( max_block_1[0][:, i * self.f_1:(i + 1) * self.f_1], max_block_2[0][:,i*self.f_2:(i+1)*self.f_2], max_block_3[0][:,i*self.f_3:(i+1)*self.f_3], max_block_4[0][:,i*self.f_4:(i+1)*self.f_4], max_block_5[0][:,i*self.f_5:(i+1)*self.f_5], min_block_1[0][:, i * self.f_1:(i + 1) * self.f_1], min_block_2[0][:, i * self.f_2:(i + 1) * self.f_2], min_block_3[0][:,i * self.f_3:(i + 1) * self.f_3], min_block_4[0][:,i * self.f_4:(i + 1) * self.f_4], min_block_5[0][:,i * self.f_5:(i + 1) * self.f_5]), dim=1) out = torch.cat((out, out_next), dim=1) return out self.binary_groups = binary_groups(nb_class, f_1, f_2, f_3, f_4, f_5) embedding_features = self.binary_groups(max_block_1, max_block_2, max_block_3, max_block_4, max_block_5, min_block_1, min_block_2, min_block_3, min_block_4, min_block_5) print(f'The embedding_features output size is : {embedding_features.size()}') ################################################### Binary classifier ########################################## # Size of the feature vector of one convolution group feature_size = 2*(f_1 + f_2 + f_3 + f_4 + f_5) print(f'The binary features are of size: {feature_size}') # The binary classifiers architecture class bin_classifier_unit(nn.Module): def __init__(self, feature_size): super(bin_classifier_unit, self).__init__() self.bin_classifier = nn.Sequential( nn.BatchNorm1d(feature_size, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.Linear(feature_size, bin_layer), nn.ReLU(), nn.Dropout(), nn.Linear(bin_layer, bin_layer), nn.ReLU(), nn.Dropout(), nn.Linear(bin_layer, 2)) def forward(self, x): out = self.bin_classifier(x) return out # Parse and issue a prediction for each convolution group class bin_classifier_group(nn.Module): def __init__(self, nb_classes, feature_size): super(bin_classifier_group, self).__init__() self.group = nn.ModuleList([bin_classifier_unit(feature_size) for _ in range(nb_classes)]) self.feature_size = feature_size def forward(self, x): for i, bin_classif in enumerate(self.group): if i < 1: out = self.group[i](x[:, i * self.feature_size:(i + 1) * self.feature_size]) else: out_next = self.group[i](x[:, i * self.feature_size:(i + 1) * self.feature_size]) out = torch.cat((out, out_next), dim=1) return out self.bin_classifier_group = bin_classifier_group(nb_class, feature_size) x = self.bin_classifier_group(embedding_features) ################################################### Multiclass classifier ###################################### self.multi_classifier = nn.Sequential( nn.BatchNorm1d(feature_size*nb_class, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.Linear(embedding_features.size()[1],multi_layer ), nn.ReLU(), nn.Dropout(), nn.Linear(multi_layer, multi_layer), nn.ReLU(), nn.Dropout(), nn.Linear(multi_layer, nb_class)) self.apply(weights_init) # Forward pass of the hierarchical CNN def forward(self, x_seq): x = x_seq.permute(0,2,1) # Convolution that creates the different time series conv_block_1 = self.block_1_groups(x) conv_block_2 = self.block_2_groups(conv_block_1[0]) conv_block_3 = self.block_3_groups(conv_block_2[0]) conv_block_4 = self.block_4_groups(conv_block_3[0]) conv_block_5 = self.block_5_groups(conv_block_4[0]) # Sampled elements of each time series max_block_1 = conv_block_1[1] min_block_1 = conv_block_1[2] max_block_2 = conv_block_2[1] min_block_2 = conv_block_2[2] max_block_3 = conv_block_3[1] min_block_3 = conv_block_3[2] max_block_4 = conv_block_4[1] min_block_4 = conv_block_4[2] max_block_5 = conv_block_5[1] min_block_5 = conv_block_5[2] # Create the feature vectors for each group embedding_features = self.binary_groups(max_block_1, max_block_2, max_block_3, max_block_4, max_block_5, min_block_1, min_block_2, min_block_3, min_block_4, min_block_5) # Outputs a binary prediction for each group out_bin = self.bin_classifier_group(embedding_features) # Outputs the multi-class probabilistic prediction vector out = self.multi_classifier(embedding_features.detach()) return [out, out_bin]
65d3041e75c767cd1333a0ab808f13b13b1faa8c
aashurajhassani/OpenCV_basics
/Source_1/08 - Handle Mouse Events in OpenCV.py
1,350
3.5
4
events = [i for i in dir(cv2) if 'EVENT' in i] # dir is inbuilt method which is going to show all clases functions etc in cv2 package print(events) # all the events in cv2 library are shown # first mouse callback function is created which is called when something is done with the mouse def click_event(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: print(x, ', ' ,y) font = cv2.FONT_HERSHEY_SIMPLEX strXY = str(x) + ', ' + str(y) cv2.putText(img, strXY, (x,y), font, 1, (255,0,0), 2) cv2.imshow('image', img) if event == cv2.RBUTTONDOWN: blue = img[y, x, 0] green = img[y, x, 1] red = img[y, x, 2] font = cv2.FONT_HERSHEY_SIMPLEX strBGR = str(blue) + ', ' + str(green) + ', ' + str(red) cv2.putText(img, strBGR, (x,y), font, 1, (255,0,0), 2) cv2.imshow('image', img) img = np.zeros([512,512,3], np.uint8) cv2.imshow('image', img) cv2.setMouseCallback('image', click_event) # to call back the function created above, first parameter is the name of the image or window name and the second ths the name of the function which is to be called cv2.waitKey(0) cv2.destroyAllWindows() # the above will create a black window which tells the coordinates of the place where left mose button is clicked also the bgr value where right button is clicked
0c59e4e602351bc53f8785788263312c77e27233
aashurajhassani/OpenCV_basics
/Source_1/03 - How to Read, Write, Show Images in OpenCV.py
1,703
3.9375
4
pip install opency-python # in the terminal window to install opencv package in pycharm import cv2 # to import the package to the project # copy any image file to be worked on to the prject folder in pycharm cv2.imread('image_name(lena.jpg)', 0) # second argument is a flag that specifies the way to read image files # Flag(can be used instead of integer value)- cv2.IMREAD_COLOR, Integer value- 1, Description- loads a color image # Flag(can be used instead of integer value)- cv2.IMREAD_GRAYSCALE, Integer value- 0, Description- loads image in grayscale mode # Flag(can be used instead of integer value)- cv2.IMREAD_UNCHANGED, Integer value- -1, Description- loads image as such including alpha channel img = cv2.imread('image_name(lena.jpg)', 0) # assign the value read from image to a variable img print(img) # prints an array that contains image information cv2.imshow('window_name_in_which_image_will_be_shown', variable_name_which_contains_image_information) # will show the image for a milisecond if waitkey is not added with this cv2.waitKey(number_of_milisecond_window_should_stay) # stops the window to exit, putting 0 in it will make it wait untill we do not close it cv2.destroyAllWindows() cv2.imwrite('file_name(lena_copy.png)', image_to_be_saved(img)) # writes the image information stored in img variable to lena_copy.png which itself is an image file k = cv2.waitKey(0) # create an output of waitKey, any key pressed will be stored in k variable now if k==27: cv2.destroyAllWindows() elif k== ord('s') cv2.imwrite('lena_copy.png', img) cv2.destroyAllWindows() # k==27 in the value for escspe key, ord is a builtin function that takes the value of keyboard buttons
de25e31fa817bc6347566c021edc50f1868de959
gohjunyi/RegEx
/google_ex.py
1,167
4.125
4
import re string = 'an example word:cat!!' match = re.search(r'word:\w\w\w', string) # If-statement after search() tests if it succeeded if match: print('found', match.group()) # 'found word:cat') else: print('did not find') # i+ = one or more i's, as many as possible. match = re.search(r'pi+', 'piiig') # found, match.group() == "piii" # Finds the first/leftmost solution, and within it drives the + # as far as possible (aka 'leftmost and largest'). # In this example, note that it does not get to the second set of i's. match = re.search(r'i+', 'piigiiii') # found, match.group() == "ii" # \s* = zero or more whitespace chars # Here look for 3 digits, possibly separated by whitespace. match = re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx') # found, match.group() == "1 2 3" match = re.search(r'\d\s*\d\s*\d', 'xx12 3xx') # found, match.group() == "12 3" match = re.search(r'\d\s*\d\s*\d', 'xx123xx') # found, match.group() == "123" # ^ = matches the start of string, so this fails: match = re.search(r'^b\w+', 'foobar') # not found, match == None # but without the ^ it succeeds: match = re.search(r'b\w+', 'foobar') # found, match.group() == "bar"
cd2b1d842bbfdb2bd017da79f87ed0ebf9e49fdd
wasuaje/ondina
/Sistema Deteccion de Somnolencia/Tesis_Ondina/fuzzy/Desfusificador.py
1,958
3.609375
4
# -*- coding: utf-8 *-* """ -Obtener la forma geométrica obtenida de la inferencia -Crear la Clase Mandani y Clase del Japonés -Centroide por cada tipo de clase -Generar valor final """ class Desfusificador: def __init__(self,trapecio): self.trapecio = trapecio self.centroide = 0 self.numerador = 0 self.denominador = 0 self.etiqueta = "" self.calcularCentroide() def calcularCentroide(self): self.etiqueta = "" for trap in self.trapecio: a,b,c,d,altura,etiqueta = trap if a==b: puntoMedio = (d-b)/2 intervalo = d-b base = c-b Base = d-b area = ((Base-base) *altura)/2 elif c==d: puntoMedio = (c-a)/2 intervalo = c-a base = c-b Base = c-a area = ((Base-base) *altura)/2 else: puntoMedio = (d-a)/2 intervalo = d-a Base = d-a area = (Base*altura)-((altura**2)/2) self.numerador = self.numerador + (puntoMedio*area) self.denominador = self.denominador + area self.centroide = self.numerador/self.denominador for trap in self.trapecio: a,b,c,d,altura,etiqueta = trap if a <= self.centroide <=d: self.etiqueta = etiqueta else: pass def obtenerValorDesfusificado(self): return self.centroide def obtenerEtiquetaResultado(self): print self.etiquta return self.etiqueta #a,b,c,d,altura = (333, 530.4071856287426, 802.0, 1000, 0.592814371257485) #puntoMedio = (d-a)/2 #intervalo = d-a #base = c-b #Base = d-a #area = ((Base+base)*altura)/2 #centroide = 0 #print area #centroide = centroide +((puntoMedio*(intervalo*area))/(intervalo*area)) #print centroide
49ead4bb0d12fb53f9cab8a9c974c02a9f9fdebc
haley-harris/belhavencsc
/221/chap8/ex-mcb.pyw
1,257
3.671875
4
# saves and loads pieces of text to clipboard # commands: python3 ex-mcb.pyw save <keyword> - saves clipboard to keyword # python3 ex-mcb.pyw <keyword> - loads keyword to clipboard # python3 ex-mcb.pyw list - loads all keywords to clipboard # python3 ex-mcb.pyw delete <keyword> - deletes a key from clipboard # ptyhon3 ex-mcb.pyw delete list - deletes entire list from clipboard import shelve, pyperclip, sys mcb_shelf = shelve.open('mcb') # save clipboard content if len(sys.argv) == 3 and sys.argv[1].lower() == 'save': mcb_shelf[sys.argv[2]] = pyperclip.paste() elif len(sys.argv) == 2: # list keywords and load content if sys.argv[1].lower() == 'list': pyperclip.copy(str(list(mcb_shelf.keys()))) elif sys.argv[1] in mcb_shelf: pyperclip.copy(mcb_shelf[sys.argv[1]]) # deletes keywords from shelf if len(sys.argv) == 3 and sys.argv[1].lower() == 'delete': for keyword in mcb_shelf: if keyword == sys.argv[2]: del(mcb_shelf[keyword]) # deletes entire list from shelf if sys.argv[1].lower() == 'delete' and sys.argv[2].lower() == 'list': for keyword in mcb_shelf.keys(): del(mcb_shelf[keyword]) mcb_shelf.close()
fa6620b0c37a911279ddc486ea4354d8d439a5b8
wonhyeongseo/python
/exercises/practice/collatz-conjecture/collatz_conjecture_test.py
1,040
3.640625
4
import unittest from collatz_conjecture import ( steps, ) # Tests adapted from `problem-specifications//canonical-data.json` class CollatzConjectureTest(unittest.TestCase): def test_zero_steps_for_one(self): self.assertEqual(steps(1), 0) def test_divide_if_even(self): self.assertEqual(steps(16), 4) def test_even_and_odd_steps(self): self.assertEqual(steps(12), 9) def test_large_number_of_even_and_odd_steps(self): self.assertEqual(steps(1000000), 152) def test_zero_is_an_error(self): with self.assertRaises(ValueError) as err: steps(0) self.assertEqual(type(err.exception), ValueError) self.assertEqual(err.exception.args[0], "Only positive integers are allowed") def test_negative_value_is_an_error(self): with self.assertRaises(ValueError) as err: steps(-15) self.assertEqual(type(err.exception), ValueError) self.assertEqual(err.exception.args[0], "Only positive integers are allowed")
491454a81d8ee0e33fa142d93260c72e23345631
ammalik221/Python-Data-Structures
/Trees/Depth_first_traversal.py
2,866
4.25
4
""" Depth First Search implementation on a binary Tree in Python 3.0 Working - recursion calls associated with printing the tree are in the following order - - print(1, "") |- traversal = "1" |- print(2, "1") | |- traversal = "12" | |- print(4, "12") | | |- traversal = "124" | | |- print(None, "124") | | |- print(None, "124") | |- print(5, "124") | | |- traversal = "1245" | | |- print(None, "1245") | | |- print(None, "1245") |- print(3, "1245") | |- traversal = "12453" | |- print(None, "12453") | |- print(None, "12453") recursion calls associated in searching are in the following order - - search(1, 5) ----------------- True |- search(2,5) ----------------- True | |- search(4, 5) ----------------- False | | |- search(None, 5) ----------------- False | | |- search(None, 5) ----------------- False | |- search(5,5) ----------------- True |- search(3, 5) ----------------- False | |-search(None, 5) ----------------- False | |- search(None, 5) ----------------- False """ class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) def print_binary_tree(self): return self.preorder_print(self.root, "") def preorder_print(self, start, traversal): if start: traversal += str(start.value) traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def search_element(self, element): return self.preorder_search(self.root, element) def preorder_search(self, start, element): if start: if start.value == element: return True else: return self.preorder_search(start.left, element) or self.preorder_search(start.right, element) else: return False if __name__ == "__main__": # test case # add nodes to the tree tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) # 1 # / \ # 2 3 # / \ # 4 5 # output is True print(tree.search(4)) # output is False print(tree.search(6)) # output is 12453 print(tree.print_binary_tree())
f01d7fab6569e318399eee144b7310d39433d061
ammalik221/Python-Data-Structures
/Collections/Queues_using_queue_module.py
411
4.1875
4
""" Queues Implementation in Python 3.0 using deque module. For implementations from scratch, check out the other files in this repository. """ from collections import deque # test cases # make a deque q = deque() # add elements q.append(20) q.append(30) q.append(40) # output is - 10 20 30 40 print(q) # remove elements from queue # output is 10 and 20 respectively print(q.popleft()) print(q.popleft())
58eed8a3f65600fa30df36a73cae9f8ce355ed20
eileenjang/algorithm-study
/src/sunwoo/source_code/week9/네트워크.py
360
3.765625
4
def solution(n, computers): answer = 0 enumerated_link = enumerate(computers) queue = [] current_queue = [enumerated_link.next()] while len(current_queue) > 0: queue += current_queue return answer count = [ solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]), solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]) ] print(count)
1e4d6472c97160fef43a028d04f001c86825d8ed
eileenjang/algorithm-study
/src/programmers/jichang/week1/test_행렬의덧셈.py
799
3.984375
4
def sum_of_array(arr1, arr2): """두 행렬의 덧셈을 구하라. 시간 복잡도: arr1가 M x N 크기의 행렬이라고 할 떄 O(NM) """ return [sum_of_rows_in_arrays(arr1[row], arr2[row]) for row in range(len(arr1))] def sum_of_rows_in_arrays(row1, row2): return [row1[row] + row2[row] for row in range(len(row1))] def test_sum_of_array(): assert sum_of_array([[1, 2], [2, 3]], [[3, 4], [5, 6]]) == [[4, 6], [7, 9]] assert sum_of_array([[1], [2]], [[3], [4]]) == [[4], [6]] def test_sum_of_rows_in_arrays(): assert sum_of_rows_in_arrays([1, 2], [3, 4]) == [4, 6] assert sum_of_rows_in_arrays([1], [3]) == [4]
8cc1a7bed872b55a22a130af76fc56b93879fb7b
eileenjang/algorithm-study
/src/programmers/jichang/week1/test_다트게임.py
3,380
4
4
# 다트게임 https://programmers.co.kr/learn/courses/30/lessons/17682 import re exponents = {'S': 1, 'D': 2, 'T': 3} def dart_game(dart): """다트게임의 문자열이 주어지면 총점수를 반환하라. """ return mathematical_expression_to_score( make_mathematical_expression(game_to_token(split_dart_game(dart)))) def mathematical_expression_to_score(mathematical_expressions): total = 0 for mathematical_expression in mathematical_expressions: total += mathematical_expression[0] ** mathematical_expression[1] * \ mathematical_expression[2] return total def make_mathematical_expression(game_token): result = [] for token in game_token: coefficient = 1 if token[2]: if token[2] == '*': coefficient = 2 if result: old = result.pop() new = (old[0], old[1], old[2]*coefficient) result.append(new) else: coefficient = -1 mathematical_expression = ( int(token[0]), exponents[token[1]], coefficient) result.append(mathematical_expression) return result def game_to_token(splited_dart_game): result = [] for game in splited_dart_game: base = re.findall(r"\d{1,2}", game)[0] exponent = re.findall(r"[A-Z]", game)[0] coefficient = re.findall( r"[#*]", game)[0] if re.findall(r"[#*]", game) else '' game_tuple = (base, exponent, coefficient) result.append(game_tuple) return result def split_dart_game(dart): m = re.findall(r"\d{1,2}\w[#*]*", dart) return m def test_dart_game(): assert dart_game('1S2D*3T') == 37 assert dart_game('1D#2S*3S') == 5 def test_mathematical_expression_to_score(): assert mathematical_expression_to_score([(1, 1, 2), (2, 2, 2), (3, 3, 1)]) == 37 assert mathematical_expression_to_score([(1, 2, -2), (2, 1, 2), (3, 1, 1)]) == 5 def test_make_mathematical_expression(): assert make_mathematical_expression( [('1', 'S', ''), ('2', 'D', '*'), ('3', 'T', '')]) == [(1, 1, 2), (2, 2, 2), (3, 3, 1)] assert make_mathematical_expression( [('1', 'D', '#'), ('2', 'S', '*'), ('3', 'S', '')]) == [(1, 2, -2), (2, 1, 2), (3, 1, 1)] def test_game_to_token(): assert game_to_token(['1S', '2D*', '3T']) == [('1', 'S', ''), ('2', 'D', '*'), ('3', 'T', '')] assert game_to_token(['1D#', '2S*', '3S']) == [('1', 'D', '#'), ('2', 'S', '*'), ('3', 'S', '')] def test_split_dart_game(): assert split_dart_game('1S2D*3T') == ['1S', '2D*', '3T'] assert split_dart_game('1D#2S*3S') == ['1D#', '2S*', '3S'] assert split_dart_game('1S*2T*3S') == ['1S*', '2T*', '3S'] assert split_dart_game('10S*2T*10S#') == ['10S*', '2T*', '10S#']
df75c3a26e33098755df0f48694989f809cb61c4
eileenjang/algorithm-study
/src/programmers/jichang/week2/test_멀쩡한사각형.py
435
3.734375
4
""" 솔루션을 봤음 """ from math import gcd def available_square(W, H): return W * H - W - H + gcd(W, H) def test_available_square(): assert available_square(8, 12) == 80 assert available_square(2, 3) == 2 assert available_square(4, 6) == 16 assert available_square(5, 7) == 24 assert available_square(3, 7) == 12 assert available_square(5, 5) == 20 assert available_square(10, 20) == 200 - 20
73c2bcf27da231afe7d9af4425683c006799e7a9
razzanamani/pythonCalculator
/calculator.py
1,515
4.375
4
#!usr/bin/python #Interpreter: Python3 #Program to create a functioning calculator def welcome(): print('Welcome to the Calculator.') def again(): again_input = input(''' Do you want to calculate again? Press Y for YES and N for NO ''') # if user types Y, run the calculate() function if again_input == 'Y': calculate() #if user types N, say bye elif again_input == 'N': print('Thank You for using Calculator') #if user types another key, run the same funtion again else: again() def calculate(): operation = input(''' Please type the math operation you would like to complete: + for addition - for substraction * for multiplication / for division % for modulo ''') number_1 = int(input('Enter the first number :')) number_2 = int(input('Enter the second number :')) #Addition if operation == '+': print('{} + {} = '.format(number_1,number_2)) print(number_1 + number_2) #Substraction elif operation == '-': print('{} - {} = '.format(number_1,number_2)) print(number_1 - number_2) #Multiplication elif operation == '*': print('{} * {} ='.format(number_1,number_2)) print(number_1 * number_2) #Division elif operation == '/': print('{} / {} = '.format(number_1,number_2)) print(number_1/number_2) #else operation else: print('You have not typed a valid operator,please run the program again.') #calling the again() function to repeat again() #calling the welcome funtion welcome() #calling the calculator function outside the function calculate()
7a484599980c33837ededc64d953b590668bd13f
kdwatt15/simplegames
/Lib/simplegames/chess/game.py
1,834
3.59375
4
from pieces import * class Board: def __init__(self, white_type, black_type): self.white = Player(1, white_type) self.black = Player(-1, black_type) self.board = self.init_board() def __str__(self): board_string = '' for row in self.board: board_string += ' '.join([str(c) for c in row]) board_string += '\n' return board_string def init_board(self): board = [self.black.pieces[:8], self.black.pieces[8:]] for _ in range(4): board.append([Empty() for _ in range(8)]) board.extend([self.white.pieces[:8], self.white.pieces[8:]]) return board class Player: def __init__(self, player_value, player_type): self.value = player_value self.player_type = player_type self.pieces = self.place_pieces() self.score = sum([int(p) for p in self.pieces]) def __repr__(self): return f'{self.value}, {self.score}' def place_pieces(self): pawn_row = [Pawn(self.value, i) for i in range(8)] noble_row = [Rook(self.value, 0), Bishop(self.value, 1), Knight(self.value, 2), Queen(self.value), King(self.value), Knight(self.value, 5), Bishop(self.value, 6), Rook(self.value, 7)] if self.value == 1: pawn_row.extend(noble_row) return pawn_row noble_row.extend(pawn_row) return noble_row class Chess(Board): def __init__(self, white_type='user', black_type='ai'): super().__init__(white_type, black_type) self.current_player = self.white def __iter__(self): self.turn = 0 return self def __next__(self): self.turn += 1 self.current_player = self.change_player() def change_player(self): if self.current_player is self.black: return self.white return self.black def play(self): game = iter(self) while self.turn < 10: # white turn next(game) # black turn return self.turn if __name__ == '__main__': game = Chess()
e0b39bd95a52671b521c943f15327924377d7c4f
RNHodkinson/Scripts
/PongMain.py
3,455
3.53125
4
# Game of pong | . | # Using the turtle module, and os module(works with os). import turtle import os # Inherit from the Screen class. wn = turtle.Screen() # Set Screen Properties wn.title("Pong version ..::HC::..") wn.bgcolor("red") wn.setup(width=1000, height=700) wn.tracer(0) # Score score_a = 0 score_b = 0 # Paddle A # inherit something i need to look up in docs paddle_a = turtle.Turtle() # set moving "paddle" properties paddle_a.speed(0) paddle_a.shape("square") paddle_a.color("black") paddle_a.shapesize(stretch_len=1, stretch_wid=5) paddle_a.penup() paddle_a.goto(-400, 0) # Paddle B # paddle b object inherit something i need to look up in docs paddle_b = turtle.Turtle() # set moving "paddle" properties paddle_b.speed(0) paddle_b.shape("square") paddle_b.color("black") paddle_b.shapesize(stretch_len=1, stretch_wid=5) paddle_b.penup() paddle_b.goto(400, 0) # Ball # ball object inherit something i need to look up in docs ball = turtle.Turtle() # set moving "ball" properties ball.speed(0) ball.shape("square") ball.color("black") ball.penup() ball.goto(0, 0) ball.dx = 0.08 # moves x 2 pix ball.dy = 0.08 # moves y 2 pix # Pen pen = turtle.Turtle() pen.speed(0) # animation speed pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 250) pen.write("Player A: Player B: ", align="center", font=("Courier", 24, "normal")) # ----------- # Function # ----------- def PaddleAUp(): y = paddle_a.ycor() y += 20 paddle_a.sety(y) def PaddleADown(): y = paddle_a.ycor() y -= 20 paddle_a.sety(y) def PaddleBUp(): y = paddle_b.ycor() y += 20 paddle_b.sety(y) def PaddleBDown(): y = paddle_b.ycor() y -= 20 paddle_b.sety(y) # Keyboard bindings wn.listen() wn.onkeypress(PaddleAUp, "w") wn.onkeypress(PaddleADown, "s") wn.onkeypress(PaddleBUp, "Up") wn.onkeypress(PaddleBDown, "Down") # Main Game loop while True: # so ugly <-- wn.update() # ball movement updater ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Border checking # top boarder set if ball.ycor() > 340: ball.sety(340) ball.dy *= -1 os.system("aplay beeww...wav &") # "aplay" allows you to play a sound! "beeww...wav" = soundfile. # bottom boarder check if ball.ycor() < -340: ball.sety(-340) ball.dy *= -1 os.system("aplay beeww...wav &") # "aplay" allows you to play a sound! # Right boarder set if ball.xcor() > 490: ball.setx(0) ball.dx *= -1 score_a += 1 pen.clear() pen.write("Player A: " + str(score_a) + " Player B: " + str(score_b), align="center", font=("Courier", 24, "normal")) # Left boarder check if ball.xcor() < -490: ball.setx(0) ball.dx *= -1 score_b += 1 pen.clear() pen.write("Player A: " + str(score_a) + " Player B: " + str(score_b), align="center", font=("Courier", 24, "normal")) # Ball paddle_b colision if (ball.xcor() > 390 and ball.xcor() < 400) and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40): ball.setx(390) ball.dx *= -1 os.system("aplay beeww...wav &") # Ball paddle_a colision if (ball.xcor() < -390 and ball.xcor() > -400) and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40): ball.setx(-390) ball.dx *= -1 os.system("aplay beeww...wav &")
7e4e3dcbe4378f252c5a79aeec81a93133e14f45
AaronMerlosH/Club_de_algoritmia_UPIITA
/fibonacci.py
630
3.875
4
# -*- coding: utf-8 -*- """ Programa para obtener serie Fibonacci usando recursividad CLUB ALGORITMIA UPIITA Aaron Merlos """ def fibonacci(posicion): if posicion==0: return 0 elif posicion==1: return 1 return fibonacci(posicion-1)+fibonacci(posicion-2) if __name__ == '__main__': print("\t**PROGRAMA SERIE DE FIBONACCI USANDO RECURSIVIDAD***\n\n") pos=input("Introduzca el numero de la posicion que busca obtener de la serie Fibonacci: ") pos=int(pos) print("\n\nEl valor de la serie Fibonacci para la posicion {} es: {}".format(pos, fibonacci(pos)))
2c33f956faac35d8feccc660255bde6236d33a38
ludmilai/storage_model
/mttdl2le.py
4,682
3.8125
4
""" Calculates mean time to data lost estimations for disk and latent block failures given the following parameters: N - total number of disks C - total number of chunks n - data blocks tuple length B - number of disk blocks per disk B=C*n/N Td - time to failure for the particular disk Tb - time to failure for the particular block on the disk Ts - scrabbling time per disk block, so the total scrubbing time is TS = Ts*B All times are with respect to the recovery time (so its assumed to be equal to 1) We are considering (n, n-2) data storage scheme (redundancy 2) """ def nk2_disk_faults(N, C, n, Td): """The rate of the faults due to the disk failures""" return C**2*n*n*(n-1)*(n-1)*(n-1)/(2*N*N*Td*Td*Td) def nk2_block_faults(N, C, n, Tb, Ts): """The rate of the faults due to the block failures""" TS = Ts*C*n/N return C*n*(n-1)*(n-2)*TS*TS/(Tb*Tb*Tb) def nk2_disk_faults1(N, C, n, Td, Tb, Ts): """The rate of data lost on the first disk fault""" TS = Ts*C*n/N return C*n*(n-1)*(n-2)*TS*TS/(Tb*Tb*Td) def nk2_disk_faults2(N, C, n, Td, Tb, Ts): """The rate of data lost on the second disk fault""" TS = Ts*C*n/N return C**2*n*n*(n-1)*(n-1)*(n-2)*TS/(2*N*N*Td*Td*Tb) def total_faults(N, C, n, Td, Tb, Ts): """The total fault rate""" return nk2_disk_faults(N, C, n, Td) + nk2_block_faults(N, C, n, Tb, Ts) \ + nk2_disk_faults1(N, C, n, Td, Tb, Ts) \ + nk2_disk_faults2(N, C, n, Td, Tb, Ts) def relative_fault_rate(N, B, n, Td, Tb, Ts): """The total fault rate relative to the fault rate considering disk faults only""" d = Td*B/Tb return 1 + (n-2)*d*Ts/(n-1) + 2*N*(n-2)*(1+d/B)*d*d*Ts*Ts/(B*(n-1)*(n-1)) if __name__ == '__main__': import numpy as np import matplotlib.pyplot as plt N, C, n = 50, 2500, 5 TB = 1e5 Tb = TB * C * n / N Ts = 1. Td = np.logspace(4, 8) Fd = nk2_disk_faults(N, C, n, Td) Ft = total_faults(N, C, n, Td, Tb, Ts) Fb = nk2_block_faults(N, C, n, Tb*np.ones(len(Td)), Ts) print total_faults(N, C, n, TB, Tb, Ts) / nk2_disk_faults(N, C, n, TB) plt.figure(1) np.savetxt('nk2_disk_faults.dat', np.vstack((Td, 1./Fd)).T) np.savetxt('nk2_block_faults.dat', np.vstack((Td, 1./Fb)).T) np.savetxt('nk2_total_faults.dat', np.vstack((Td, 1./Ft)).T) plt.plot(Td, 1./Fd, '--', label='disk faults') plt.plot(Td, 1./Fb, '--', label='block faults') plt.plot(Td, 1./Ft, label='total faults') plt.xscale('log') plt.yscale('log') plt.title('Mean time to data loss in the presence\nof latent disk block failures') plt.xlabel('disk lifetime / replication time') plt.ylabel('MTTDL / replication time') plt.legend() plt.figure(2) df_fraction = nk2_disk_faults(N, C, n, Td) / Ft bf_fraction = nk2_block_faults(N, C, n, Tb, Ts) / Ft b1_fraction = nk2_disk_faults1(N, C, n, Td, Tb, Ts) / Ft b2_fraction = nk2_disk_faults2(N, C, n, Td, Tb, Ts) / Ft np.savetxt('nk2_df_fraction.dat', np.vstack((Td, df_fraction)).T) np.savetxt('nk2_bf_fraction.dat', np.vstack((Td, bf_fraction)).T) np.savetxt('nk2_b1_fraction.dat', np.vstack((Td, b1_fraction)).T) np.savetxt('nk2_b2_fraction.dat', np.vstack((Td, b2_fraction)).T) plt.plot(Td, df_fraction, label='disk faults') plt.plot(Td, bf_fraction, label='block faults') plt.plot(Td, b1_fraction, label='1st block recovery faults') plt.plot(Td, b2_fraction, label='2nd block recovery faults') plt.xscale('log') plt.title('The fraction of the total faults related\nto the particular data lost mechanism') plt.xlabel('disk lifetime / replication time') plt.ylabel('Total faults fraction') plt.legend() plt.figure(3) plt.title('Data lost vs scrabling rate') for i, k in enumerate((.1, 1., 10.)): Td = 1e5 TB = Td * k Tb = TB * C * n / N Ts = np.logspace(0, 3) r = nk2_disk_faults(N, C, n, Td)/total_faults(N, C, n, Td, Tb, Ts) rt = 1/(1 + .75*Td*Ts/TB) np.savetxt('nk2_relative%d.dat' % i, np.vstack((Ts, r)).T) np.savetxt('nk2_relative%d_.dat' % i, np.vstack((Ts, rt)).T) plt.plot(Ts, r, label='$T_B=%gT_d$' % k) plt.plot(Ts, rt, '--') plt.xlabel('block scrabling time / replication time') plt.ylabel('MTTDL relative to pure disk faults case') plt.xscale('log') plt.yscale('log') plt.legend() plt.figure(4) plt.title('Data lost vs number of disks') for i, B in enumerate((50, 500, 5000)): N = np.arange(2, 100001, 2, dtype=float) C = N * B / n Td = 1e5 TB = Td / 2 Tb = TB * B Ts = 10 r = nk2_disk_faults(N, C, n, Td)/total_faults(N, C, n, Td, Tb, Ts) np.savetxt('nk2_scaling%d.dat' % i, np.vstack((N, r)).T) plt.plot(N, r, label='B=%d' % B) plt.xlabel('N') plt.ylabel('MTTDL relative to pure disk faults case') plt.xscale('log') plt.yscale('log') plt.legend() plt.show()
d0c4efbc254e8cbf5323da5c0758d6a6f0975611
yhlhenry/projecteular
/27_Quadratic_primes.py
691
3.546875
4
a_candi = [x for x in range(-1000, 1000) if x % 2 != 0] b_candi = [x for x in range(-1000, 1000) if x % 2 != 0] def isPrime(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else: return False number_prime_list = [] max_num = 0 for a in a_candi: for b in b_candi: for n in range(80): if not isPrime(n * n + a * n + b): if(n > max_num): max_num = n at = a bt = b number_prime_list.append(n) break print(max(number_prime_list)) print(at, bt)
951ab4d2b011efdfcc4b7eeb376c0c8076fcc95d
anukulu/100DaysOfCode
/Dhumbal (to be made)/main.py
2,805
3.640625
4
import random import itertools class Card: def __init__(self, name, color): self.name = name self.color = color class Deck: def __init__(self): self.newDeck = [] self.colors = ['C', 'D', 'H', 'S'] self.numbers = [i for i in range(1,14)] def MakeNewDeck(self): for color in self.colors: for number in self.numbers: self.newDeck.append(Card(number, color)) def ShuffleDeck(self, deck): random.shuffle(deck) return deck def MakeDeck(self, randomDeck): smallerDeck = self.ShuffleDeck(randomDeck) self.newDeck = smallerDeck def ShowDeck(self): for card in self.newDeck: print(str(card.name) + card.color) class Player: def __init__(self): self.cards = [] self.handProbabilities = { 'Trio': 0.0022, 'PureSequence': 0.0024, } def ReceiveCards(self, card): self.cards.append(card) def PickCard(self, singleCard): pass def Throw(x = None): if(x == None): # For the first player cardsInHand = self.BestArrangement() else: pass # For all other rounds def BestArrangement(self): if (len(self.cards) > 3): allCombinationsOfThree = list(itertools.combinations(cards, 3)) allCombinationsOfTwo = list(itertools.combinations(cards, 2)) allPossibleCombinations = allCombinationsOfThree + allCombinationsOfTwo deckOfCards = Deck() deckOfCards.MakeNewDeck() deckOfCards.ShuffleDeck(deckOfCards.newDeck) players = [] numberOfPLayers = int(input('Enter the number of players : ')) if (numberOfPLayers > 1 and numberOfPLayers < 6): for i in range(numberOfPLayers): newPlayer = Player() players.append(newPlayer) for i in range(5): for player in players: player.ReceiveCards(deckOfCards.newDeck.pop()) # beginning the game show = False playerIndex = 0 cardsOnGround = [] rounds = 0 while(not show): currentPlayer = players[playerIndex] # The player needs to throw a card first and then pick a card if(rounds == 0): # just throw the cards and pick one from deck thrownCards = currentPlayer.Throw() newCard = deckOfCards.newDeck.pop() playerIndex += 1 playerIndex = playerIndex % numberOfPLayers # for player in players: # for card in player.cards: # print(str(card.name) + card.color) # print('\n') else: print('The game is not possible')
19ebb43dcbe1a3195b0b0cbe7202fa5fec0fd037
risooonho/RPG
/enemies/__init__.py
1,664
3.609375
4
#!/usr/bin/python3 """ This is to handle the games enemies """ import pygame class enemies(object): def __init__(self, pos): from config import mobs self.position = (pos[0], pos[1]) self.rect = pygame.Rect(self.position[0], self.position[1], 32, 32) mobs.append(self) self.health = 100 self.alive = True self.defense = 20 def died(self): from config import mobs, killed if self.health == 0: self.alive = False if not self.alive: mobs.remove(self) killed.append(self) def move(self, dx, dy): # Move each axis separately. Note that this checks for collisions both times. if dx != 0: self.move_single_axis(dx, 0) if dy != 0: self.move_single_axis(0, dy) # move to next level def move_single_axis(self, dx, dy): # Move the rect self.rect.x += dx self.rect.y += dy # If you collide with a wall, move out based on velocity from config import walls for wall in walls: if self.rect.colliderect(wall.rect): if dx > 0: # Moving right; Hit the left side of the wall self.rect.right = wall.rect.left if dx < 0: # Moving left; Hit the right side of the wall self.rect.left = wall.rect.right if dy > 0: # Moving down; Hit the top side of the wall self.rect.bottom = wall.rect.top if dy < 0: # Moving up; Hit the bottom side of the wall self.rect.top = wall.rect.bottom
4c97f87224677eb2a20c4e469f74a959764c936a
williamsyb/mycookbook
/algorithms/BAT-algorithms/Array & String/L_ 旋转数组中查找最小值.py
1,254
3.90625
4
# coding:utf-8 """ 一、题目 0124567 --旋转--> 4567012 , 最小值 是 0 二、思路 用索引start, end 分别指向首尾元素,元素不重复。 1、若子数组是普通升序数组,则 Array[start] < Array[end]; eg:Array = [4,5,6] 2、若子数组是循环升序数组,前半段子数组的元素全都大于后半子数组中的元素:Array[start] > Array[end]. eg: Array = [7,0,1,2] 三、步骤: 计算中间位置 mid = (start + end) >> 1 1、显然,Array[start...mid] 和 Array[mid+1....end]必有一个是循环升序数组,有一个是普通升序数组;而最小元素一定在循环升序数组中 2、若,Array[mid] > Array[end],说明子数组Array[mid+1,mid+2,...,end]是循环升序,更新 start = mid + 1 3、若,Array[mid]<Array[end], 说明子数组Array[mid+1,mid+2,...,end]是普通升序, 更新 end = mid """ def find_min(nums): size = len(nums) low = 0 high = size - 1 while low < high: mid = (low + high) >> 1 if nums[mid] < nums[high]: high = mid elif nums[mid] > nums[high]: low = mid + 1 return nums[low] if __name__ == '__main__': array = [4, 5, 6, 7, 0, 1, 2, 3] print(find_min(array))
32948a2bcf2470ffb894d2ad6fc0379c187add89
williamsyb/mycookbook
/algorithms/BAT-algorithms/The beauty of programming/chapter-4/7-蚂蚁爬树.py
816
3.578125
4
def ant_time(locs, wood_len,speed): """ 求所有蚂蚁都离开木杆的最短时间和最长时间 :param locs: 蚂蚁的初始位置 :param wood_len: 木杆的长度 :param speed: 蚂蚁爬行速度,厘米/秒 :return: 最短时间 最长时间 """ min_distance = [] # 存储蚂蚁到木杆 最近 一端的距离 max_distance = [] # 存储蚂蚁到木杆 最远 一端的距离 for loc in locs: min_distance.append(min(loc, wood_len - loc)) max_distance.append(max(loc, wood_len - loc)) min_time = 1.0 * max(min_distance) / speed max_time = 1.0 * max(max_distance) / speed return min_time, max_time if __name__ == '__main__': locs = [3, 7, 20, 50, 66, 77] wood_len = 100 speed = 2 print(ant_time(locs, wood_len, speed))
c08cc0a18eaf2d615fafe3ee3a5b35b938b7ff8c
williamsyb/mycookbook
/pydantic_demo/demo.py
1,317
3.5
4
from pydantic import BaseModel, ValidationError, validator class UserModel(BaseModel): name: str username: str password1: str password2: str @validator('name') def name_must_contain_space(cls, v): print('name_must_contain_space-v:', v) if ' ' not in v: raise ValueError('must contain a space') return v.title() @validator('password2') def passwords_match(cls, v, values, **kwargs): print('passwords_match-v:', v) print('passwords_match-values:', values) if 'password1' in values and v != values['password1']: raise ValueError('passwords do not match') return v @validator('username') def username_alphanumeric2(cls, v): print('username_alphanumeric2-v:', v) assert v.isalpha(), 'must be alphanumeric' return v print(UserModel(name='samuel colvin', username='scolvin', password1='zxcvbn', password2 = 'zxcvbn')) # try: # UserModel(name='samuel', username='scolvin', password1='zxcvbn', # password2='zxcvbn2') # except ValidationError as e: # print(e) # """ # 2 validation errors for UserModel # name # must contain a space (type=value_error) # password2 # passwords do not match (type=value_error) # """
8be14b95e50f530eeaaaf7d9fda8ddc843ba4ded
williamsyb/mycookbook
/algorithms/BAT-algorithms/Tree/分行打印一棵树.py
1,498
3.78125
4
""" 一、题目 分行从上之下打印一颗二叉树 例如有如下一棵树: 5 / \ 3 6 / \ \ 2 4 7 打印结果是 5 3 6 2 4 7 二、思路 在层次遍历的基础加以改进 如何实现逐行打印,必须要知道每一行的开始和结束。如何准确地获得该信息是关键。 核心思想:在每一层开始遍历前,队列中存储的就是该行的全部是数据,用size记录,然后一次性全部遍历。 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def print_from_top_to_bottom(root): if root is None: return [] # 用一个list和一个索引index模拟队列的先进先出 queue = [] index = 0 result = [] queue.append(root) while len(queue) > index: size = len(queue) - index # 新遍历一个层时,队列中存储是该层的全部数据,size记录个数 res = [] for i in range(size): # 遍历size次 temp = queue[index] index += 1 res.append(temp.val) if temp.left is not None: queue.append(temp.left) if temp.right is not None: queue.append(temp.right) result.append(res) return result if __name__ == '__main__': from Tree.tree import construct_tree root = construct_tree() print(print_from_top_to_bottom(root))
af65af7af55c545222130b1b0330eeb4c26b91d0
williamsyb/mycookbook
/algorithms/双指针/leetcode-633-两数平方和.py
711
3.84375
4
# -*- coding UTF-8 -*- # @project : python03 # @Time : 2020/6/3 12:34 # @Author : Yibin Sun # @Email : sunyibin@orientsec.com.cn # @File : leetcode-633-两数平方和.py # @Software: PyCharm import math class Solution: @classmethod def judge_square_sum(cls, target): if target < 0: return False i, j = 0, int(math.sqrt(target)) while i < j: res = i * i + j * j if res == target: print(i, j) return True elif res < target: i += 1 else: j -= 1 return False if __name__ == '__main__': print(Solution.judge_square_sum(math.pow(34, 2) + math.pow(12, 2)))
63c41b9812173e85be95f1181a2104085530f525
williamsyb/mycookbook
/algorithms/bfs_dfs/robots.py
1,823
3.703125
4
""" 问题定义 有如下 8 x 8 格子,机器人需要从开始位置走到结束位置,每次只能朝右或朝下走,粉色格子为障碍物,机器人不能穿过, 问机器人从开始位置走到结束位置最多共有多少种走法? """ from pprint import pprint mat = [ [0] * 8, [0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0] * 8 ] class Node: __slots__ = 'x', 'y' def __init__(self, x, y): self.x = x self.y = y def right_node(self): return Node(self.x + 1, self.y) def down_node(self): return Node(self.x, self.y + 1) def __eq__(self, other): if self.x == other.x and self.y == other.y: return True else: return False def can_visit(self): if self.x > len(mat[0]) - 1 or self.y > len(mat) - 1 or mat[self.y][self.x] == 1: return False else: return True def __repr__(self): return f'{(self.x, self.y)}' def solution(): """深度优先搜索""" stack = [Node(0, 0)] destination = Node(len(mat) - 1, len(mat[0]) - 1) count = 0 res = [] route = [] while len(stack) > 0: cur_node = stack.pop() route.append(cur_node) if destination == cur_node: res.append(route[:]) route = [] count += 1 right_node = cur_node.right_node() down_node = cur_node.down_node() if right_node.can_visit(): stack.append(right_node) if down_node.can_visit(): stack.append(down_node) pprint(res) return f"共{count}种走法" if __name__ == '__main__': pprint(solution())
f19c45f6389c44c162b54b0eb74edb25cfa5da9b
williamsyb/mycookbook
/algorithms/BAT-algorithms/Linklist/删除链表的倒数第 n 个节点.py
1,055
3.5
4
""" 题目: 给定一个链表,删除链表的倒数第 k 个节点,并且返回链表的头结点。 示例: 给定一个链表: 1->2->3->4->5, 和 k = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5. 思路: 第一种:遍历一次,获得链表长度N,则可知 倒数第k个节点 == 顺数第N-k+1个节点,再次遍历,删除即可。 (一共需要两次遍历) 第二种:使用快慢指针遍历,让快指针先走k步,然后快慢指针一起移动,当快指针遍历到末尾,慢指针正好在倒数第k个节点上,删除即可 """ from Linklist.utils import * def remove_k_th_from_end(head, k): fast = head while k > 0: fast = fast.next k -= 1 if fast is None: return head.next slow = head while fast.next is not None: fast = fast.next slow = slow.next slow.next = slow.next.next return head if __name__ == '__main__': head1 = build_l([1, 2, 3, 4, 5]) print_l(remove_k_th_from_end(head1, 2))
510499c97a353ae97df9ef7e3e0eae96dd2f382f
williamsyb/mycookbook
/algorithms/BAT-algorithms/Array & String/L_Two sum - 有序数组.py
993
3.90625
4
""" 题目: 在有序数组中找出两个数,使它们的和为 target。 思路: 双指针 使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。 指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。 遍历过程: * 如果两个指针指向元素的和 sum == target,那么得到要求的结果; * 如果 sum > target,移动较大的元素,使 sum 变小一些; * 如果 sum < target,移动较小的元素,使 sum 变大一些。 """ def two_sum(nums, target): size = len(nums) start = 0 end = size - 1 while start < end: temp = nums[start] + nums[end] if temp == target: return nums[start], nums[end] elif temp < target: start += 1 else: end -= 1 return None if __name__ == '__main__': nums = [2, 7, 11, 15] print(two_sum(nums=nums,target=9))
97e8fbbb1cb7c4751ccd8fc65695ec3e2ac7f9f3
williamsyb/mycookbook
/algorithms/BAT-algorithms/Array & String/L_除自身以外数组的乘积.py
1,121
3.53125
4
""" 题目: 给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output , 其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。 示例: 输入: [1,2,3,4] 输出: [24,12,8,6] 说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 思路: 本题难点在于 不许使用除法。 其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积, 即 output[i] = nums[0] * nums[1] * ... * nums[i-1] * nums[i+1] * ... * nums[size-1], 要想实现连乘,只能采用构造的方法:将数组从左往右遍历,从右往左遍历,不断累加相乘,对每一个output[i]构成出满足条件的乘法因子。 """ def product_except_self(nums): size = len(nums) output = [1] * size left = 1 for i in range(1, size): left *= nums[i - 1] output[i] *= left right = 1 for j in range(size - 2, -1, -1): right *= nums[j + 1] output[j] *= right return output if __name__ == '__main__': print(product_except_self([1, 2, 3, 4]))
6431a97ffaebaccd2552886ade7d1cb3e1f1a1ad
williamsyb/mycookbook
/algorithms/BAT-algorithms/Array & String/L_最小移动次数使数组元素相等.py
2,083
3.984375
4
""" 题目: 给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数, 其中每次移动可将选定的一个元素加1或减1。 您可以假设数组的长度最多为10000。 例如: 输入: [1,2,3] 输出: 2 说明: 只有两个动作是必要的(记得每一步仅可使其中一个元素加1或减1): [1,2,3] => [2,2,3] => [2,2,2] 思路: 要想将数组中所有元素都移动为相同的,而且总移动步数还得最小。必须将所有的数往数组的"中位数"移动. [将所有数往“平均数”移动的想法是错误,平均值容易受到异常点的影响,例如,实操一下数组[1,1,1,1,1,1000],即可明白] 本题的难点就是如何快速找到数组的中位数了,可以联想到“L_找出n个数里最小的k个”一题。中位数就是第(len(nums) >> 1)+1个数了。 在逐个统计每个数与中位数的距离了,累加起来即可 注意: 此代码Python版在LeetCode上超时,Java版的不超时 leetcode-462题 """ def min_moves(nums): k = (len(nums) >> 1) + 1 median = find_min_k_th(nums, k) count = 0 for num in nums: count += abs(num - median) return count def find_min_k_th(nums, k): # 快速排序 def quick_sort(nums, start, end, k): if start >= end: return pivot = nums[start] # 基准值 low = start high = end while low < high: while low < high and nums[high] >= pivot: high -= 1 nums[low] = nums[high] while low < high and nums[low] < pivot: low += 1 nums[high] = nums[low] nums[low] = pivot if low == k - 1: return elif low < k - 1: quick_sort(nums, low + 1, end, k) else: quick_sort(nums, start, low - 1, k) quick_sort(nums, 0, len(nums) - 1, k) return nums[k - 1] if __name__ == '__main__': print(min_moves([1, 2, 3]))
706ad16847e812a429f5c26d941a68454f7311ae
williamsyb/mycookbook
/algorithms/BAT-algorithms/Tree/遍历-层次遍历.py
1,199
3.953125
4
""" 一、题目 按层次的遍历的方法打印一颗树 例如有如下一棵树: 5 / \ 3 6 / \ \ 2 4 7 打印结果是 5 3 6 2 4 7 二、思路 层次遍历的步骤是: 对于不为空的结点,先把该结点加入到队列中 从队中拿出结点,如果该结点的左右结点不为空,就分别把左右结点加入到队列中 重复以上操作直到队列为空 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def hierarchical_traversal(root): if root is None: return [] # 用一个list和一个索引index模拟队列的先进先出 queue = [] index = 0 result = [] queue.append(root) while len(queue) > index: temp = queue[index] index += 1 result.append(temp.val) if temp.left is not None: queue.append(temp.left) if temp.right is not None: queue.append(temp.right) return result if __name__ == '__main__': from Tree.tree import construct_tree root = construct_tree() print(hierarchical_traversal(root))
89ac7d2b6a35ce2b06c093108b54968f5c026bf5
williamsyb/mycookbook
/设计模式/singleton02.py
637
3.578125
4
from threading import Thread, Lock class Singleton(type): def __init__(cls, *args, **kwargs): super().__init__(*args, **kwargs) cls.__instance = None def __call__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance = super().__call__(*args, **kwargs) return cls.__instance class Car(metaclass=Singleton): def __init__(self, name): self.__name = name @property def name(self): return self.__name if __name__ == '__main__': car01 = Car('01') car02 = Car('02') print(car01.name) print(car02.name) print(car01 is car02)
54fc0546510cf9478ab6d933fb1496e886c9d40e
williamsyb/mycookbook
/algorithms/BAT-algorithms/Array & String/S_循环左移.py
300
3.546875
4
""" *例如将abcdef循环左移2位得到 cdefab *思路:转置 (X’Y')' = YX * "abcd"[::-1] = "dcba" """ def left_roatet_str(str1, m): return ((str1[0:m])[::-1] + (str1[m:])[::-1])[::-1] if __name__ == '__main__': str1 = "abcdef" print(left_roatet_str(str1, 2))
b80078fddc12095b80f7f3c9b99c3905ca1926b5
williamsyb/mycookbook
/thread_prac/cond2.py
1,348
3.71875
4
import time from threading import Thread, Condition li = list(range(1, 101)) cond = Condition() class Consumer01(Thread): def __init__(self, name, nums, con): Thread.__init__(self) self.name = name self.nums = nums self.con: Condition = con def consumer(self): self.con.acquire() num = self.nums.pop() print(f'{self.name}: {num}') if num % 2 == 0: self.con.wait() self.con.notify() self.con.release() def run(self): while len(self.nums) > 0: time.sleep(1) self.consumer() class Consumer02(Thread): def __init__(self, name, nums, con): Thread.__init__(self) self.name = name self.nums = nums self.con: Condition = con def consumer(self): self.con.acquire() num = self.nums.pop() print(f'{self.name}: {num}') if num % 2 == 1: self.con.wait() self.con.notify() self.con.release() def run(self): while len(self.nums) > 0: time.sleep(2) self.consumer() if __name__ == '__main__': consumer01 = Consumer01('Thread01', li, cond) consumer02 = Consumer02('Thread02', li, cond) consumer01.start() consumer02.start() consumer01.join() consumer02.join()
5e18167771713cf6b16b8d21f1bd61d8bf33dbb7
williamsyb/mycookbook
/algorithms/BAT-algorithms/Tree/二叉查找树-从有序链表构造平衡的二叉查找树.py
1,886
4
4
""" 一、题目 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 二、思路 递归大法 利用二分查找的思路,二分建树。 二分的中点是根节点(相对而言的,每个子树都有根节点),左边的序列建立左子树,右边的序列建立右子树 三、本题与“从有序数组中构建二叉查找树”的整体思路是一样的 只是单链表无法直接获得中间节点,必须通过顺序遍历才能得到mid位置的节点。 遍历的方法是用“快慢指针”: 快指针每走两步,慢指针只走1步,这样快指针走到重点时,慢指针在中间。 *** “快慢指针”是单链表中的重要方法,很多问题都要用到这个技巧,才能实现最优解 *** 四、同 LeetCode-109 """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # 找到单链表中间节点mid的前驱 def pre_Mid(head): slow = head fast = head.next pre = head while fast is not None and fast.next is not None: pre = slow slow = slow.next fast = fast.next.next return pre def sortedListToBST(head): if head is None: return None if head.next is None: return TreeNode(head.val) preMid = pre_Mid(head) mid = preMid.next preMid.next = None # 断开链表 t = TreeNode(mid.val) t.left = sortedListToBST(head) t.right = sortedListToBST(mid.next) return t
5938614ce9d3181ed59c2e56e4df3adaa17ab91b
williamsyb/mycookbook
/algorithms/BAT-algorithms/Math/判断一个数是否为两个数的平方和.py
735
4.1875
4
""" 题目: 判断一个数是否是两个数的平方和 示例: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 思路: 双指针 本题是要判断一个数是否等于两个数的平方和 <=等价=> 在自然数数组中,是否存在两个数的平方和是否等于一个数。 所以本题的思路与 “/数组/Two sum - 有序数组”基本一致。 """ def judge_square_sum(c): start = 0 end = int(c ** 0.5) while start <= end: temp = start ** 2 + end ** 2 if temp == c: return True elif temp < c: start += 1 else: end -= 1 return False if __name__ == '__main__': print(judge_square_sum(3))
ee1e7bff3095782f4886eeefc0558543c091ddc6
williamsyb/mycookbook
/thread_prac/different_way_kill_thread/de04.py
1,153
4.59375
5
# Python program killing # a thread using multiprocessing # module """ Though the interface of the two modules is similar, the two modules have very different implementations. All the threads share global variables, whereas processes are completely separate from each other. Hence, killing processes is much safer as compared to killing threads. The Process class is provided a method, terminate(), to kill a process. Now, getting back to the initial problem. Suppose in the above code, we want to kill all the processes after 0.03s have passed. This functionality is achieved using the multiprocessing module in the following code. """ import multiprocessing import time def func(number): for i in range(1, 10): time.sleep(0.01) print('Processing ' + str(number) + ': prints ' + str(number * i)) # list of all processes, so that they can be killed afterwards all_processes = [] for i in range(0, 3): process = multiprocessing.Process(target=func, args=(i,)) process.start() all_processes.append(process) # kill all processes after 0.03s time.sleep(0.03) for process in all_processes: process.terminate()
f1a08050859a649f0dd7c647078aa1dbfbc0c8b2
case112/Python_TH
/Beginner/Collections/dungeon_game.py
9,192
3.75
4
# P, but the monster, the door, and the shrine (explained below) are displayed also as M, D, and S respectively. #The player and monster hp are displayed as numbers, and their hp bars are displayed as Xs and Ys respectively which decrease every -20 hp. #If the player makes an invalid move, they lose 5 hp. #If the player encounters the monster, the game will randomly generate 0 or 1. If the number is 0, the player loses 10 hp. If the number is 1, the monster loses 10 hp unless killed. #If the player's hp reaches 0, the player loses. If the monster's hp reaches 0 the monster dies, and the player is prompted to get to the door. #The monster moves 1 tile in a random direction every 5 valid moves unless it has been killed. #The monster heals itself 5 hp every 10 valid moves unless killed or has maximum hp (100). #The player gets healed 5 hp if they move to the shrine unless they have maximum hp (100). If the monster moves to the shrine, the monster does not get healed. #If the monster reaches the door, the player loses automatically. #If the player reaches the door and the monster has not been killed, the player is prompted to kill the monster first. #If the player reaches the door and the monster has been killed, the player wins. import random import os CELLS = [(c%10, c//10) for c in range(10**2)] def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def get_locations(): return random.sample(CELLS, 5) def move_player(player, move): x, y = player if move == "W": x, y = x, y elif move == "L" and x > 0: x -= 1 elif move == "R" and x < 9: x += 1 elif move == "U" and y > 0: y -= 1 elif move == "D" and y < 9: y += 1 else: print("\n ** A wall is blocking your way! ** \n") return x, y def move_monster(monster, num): x, y = monster if num == 0: if x > 0: x -= 1 elif x == 0: x += 1 elif num == 1: if x < 9: x += 1 elif x == 9: x -= 1 elif num == 2: if y > 0: y -= 1 elif y == 0: y += 1 elif num == 3: if y < 9: y += 1 elif y == 9: y -= 1 return x, y def get_moves(player): moves = ["L", "R", "U", "D", "W"] return moves def draw_map(monster, door, player, shrine, difficulty, monster_found, door_found, shrine_found): print(" _" * 10) tile = "|{}" for cell in CELLS: x, y = cell if x < 9: line_end = "" if cell == player: output = tile.format("P") elif cell == monster and (difficulty != "H" or monster_found): output = tile.format("M") elif cell == door and (difficulty != "H" or door_found): output = tile.format("D") elif cell == shrine and (difficulty != "H" or shrine_found): output = tile.format("S") else: output = tile.format("_") else: line_end = "\n" if cell == player: output = tile.format("P|") elif cell == monster and (difficulty != "H" or monster_found): output = tile.format("M|") elif cell == door and (difficulty != "H" or door_found): output = tile.format("D|") elif cell == shrine and (difficulty != "H" or shrine_found): output = tile.format("S|") else: output = tile.format("_|") print(output, end = line_end) def display_player_hp_bar(player_hp): if 80 < player_hp <= 100: print("Player:", "X" * 5, player_hp) elif 60 < player_hp <= 80: print("Player:", "X" * 4, player_hp) elif 40 < player_hp <= 60: print("Player:", "X" * 3, player_hp) elif 20 < player_hp <= 40: print("Player:", "X" * 2, player_hp) elif 0 < player_hp <= 20: print("Player:", "X", player_hp) return player_hp def display_monster_hp_bar(monster_hp): if 80 < monster_hp <= 100: print("Monster:", "Y" * 5, monster_hp) elif 60 < monster_hp <= 80: print("Monster:", "Y" * 4, monster_hp) elif 40 < monster_hp <= 60: print("Monster:", "Y" * 3, monster_hp) elif 20 < monster_hp <= 40: print("Monster:", "Y" * 2, monster_hp) elif 0 < monster_hp <= 20: print("Monster:", "Y", monster_hp) return monster_hp def display_message(player): moves = ["(L)EFT", "(R)IGHT", "(U)P", "(D)OWN"] x, y = player if 0 <= x <= 9 and 0 <= y <= 9: print("You're currently in room {}.".format(player)) if x == 0: moves.remove("(L)EFT") if x == 9: moves.remove("(R)IGHT") if y == 0: moves.remove("(U)P") if y == 9: moves.remove("(D)OWN") print("You can move {}.".format(", ".join(moves)), "or you can (W)AIT.") print("Enter Q to quit. Enter C to clear your screen.") def game_loop(): monster, door, player, shrine, trap = get_locations() num_moves = 0 player_hp = 100 monster_hp = 100 monster_alive = True playing = True shrine_found = False door_found = False monster_found = False difficulty = input("Choose difficulty: (E)asy (N)ormal, or (H)ard. ") while difficulty.upper() != "E" and difficulty.upper() != "N" and difficulty.upper() != "H": print("Invalid input.") difficulty = input("Choose difficulty: (E)asy, (N)ormal, or (H)ard. ") difficulty = difficulty.upper() while playing: draw_map(monster, door, player, shrine, difficulty, monster_found, door_found, shrine_found) valid_moves = get_moves(player) display_message(player) if difficulty != "E": if num_moves > 0 and num_moves % 5 == 0 and monster_alive: num = random.randint(0, 3) print("\n ** The monster has moved! **\n") monster = move_monster(monster, num) monster_found = False if num_moves > 0 and num_moves % 10 == 0: if monster_alive and monster_hp < 100: monster_hp += 5 print("\n ** The monster has healed itself 5 hp! **\n") if monster == door: print("\n ** The monster has escaped! You lose! **\n") playing = False break if display_player_hp_bar(player_hp) <= 0: print("\n ** You're dead! **\n") playing = False break if display_monster_hp_bar(monster_hp) <= 0: print("\n ** You've killed the monster! Now get to the door! **\n") monster_alive = False print("{} moves.".format(num_moves)) move = input("> ") move = move.upper() if move == "Q": print("\n ** See you next time! **\n") break if move == "C": clear_screen() continue if move in valid_moves: player = move_player(player, move) num_moves += 1 if player == monster: monster_found = True number = random.randint(0, 1) if number == 0: player_hp -= 10 print("\n ** You've been damaged by the monster! You've lost 10 hp! **\n") elif number == 1 and monster_alive: monster_hp -= 10 print("\n ** You've damaged the monster! It's lost 10 hp! **\n") elif player == shrine: shrine_found = True if player_hp < 100: player_hp += 5 print("\n ** You've been healed 5 hp! **\n") else: print("\n ** You're already at full hp! **\n") elif player == trap: if difficulty == "E": player_hp -= 5 print("\n ** You've activated a trap! You've lost 5 hp! **\n") elif difficulty == "N": player_hp -= 10 print("\n ** You've activated a trap! You've lost 10 hp! **\n") elif difficulty == "H": player_hp -= 20 print("\n ** You've activated a trap! You've lost 20 hp! **\n") elif player == door: door_found = True if not monster_alive: print("\n ** You've escaped! Congratulations! **\n") playing = False break elif monster_alive: print("\n ** You must kill the monster before you can escape! **\n") else: print("Invalid move.") if playing == False: game_end() def game_end(): play_again = input("Play again? (y/n) ") while play_again.lower() != 'y' and play_again.lower() != 'n': print("Invalid input.") play_again = input("Play again? (y/n) ") if play_again.lower() == 'y': game_loop() clear_screen() print("Welcome to the dungeon!") input("Press return to start!") clear_screen() game_loop()
ef74e743d39e57a7540994194602bc0bacb1bd8f
case112/Python_TH
/Beginner/Object_oriented/instances.py
358
3.84375
4
my_list = ["apple", 5.2, "dog", 8] def combiner(my_list): strlist = "" numlist = 0 for items in my_list: if isinstance(items, str): strlist += items else: numlist += items print(strlist + str(numlist) ) return strlist + str(numlist) combiner(my_list)
c8784ad04cef958ae1284cd4ab5d23100a1bc2e7
case112/Python_TH
/Beginner/Collections/out_of_this_word.py
2,500
4.09375
4
import random import os WORDS = ( "treehouse", "python", "learner") def prompt_for_words(challenge): guesses = set() print("What words can you find in the word '{}'".format(challenge)) print("(Enter Q to Quit)") while True: guess = input("{} words >. ".format(len(guesses))) # Don't allow words of less than 2 chars if len(guess) < 2: if guess.upper() == "Q": break else: print ("Guesses must be at least two letters - try again.") continue if check_valid_word(guess): guesses.add(guess.lower()) else: print("Sorry, '{}' is not in '{}' - try agian.". format(guess, challenge)) continue return guesses def check_valid_word(word): """Check whether the chars exist in the word.""" guess_chars = [] for char in word: guess_chars.append(char.lower()) # 1. make a copy of the challenge_chars list check_list = challenge_chars.copy() # 2. Loop through the copied list and remove any matches for letter in guess_chars: if letter not in check_list: return False else: check_list.remove(letter) return True def output_results(results): for word in results: print("* " + word) def clear_screen(): os.system("cls" if os.name == 'nt' else "clear") # The Game clear_screen() challenge_chars = [] challenge_word = random.choice(WORDS) # Create a list of chars in the challenge word for char in challenge_word: challenge_chars.append(char) player1_name = input("\nPlayer 1, what is your name? ") player1_words = prompt_for_words(challenge_word) player2_name = input("\nPlayer 2, what is your name? ") player2_words = prompt_for_words(challenge_word) # The results clear_screen() print("Results for " + player1_name + ":") player1_unique = player1_words - player2_words print("{} guesses, {} unique".format(len(player1_words), len(player1_unique))) output_results(player1_unique) print("-" * 10 + "\n") print("Results for " + player2_name + ":") player2_unique = player2_words - player1_words print("{} guesses, {} unique".format(len(player2_words), len(player2_unique))) output_results(player2_unique) print("-" * 10 + "\n") print("Shared guesses:") shared_words = player1_words & player2_words output_results(shared_words) print("-" * 10 + "\n")
e0d1a2a1d9c3bed6d3cecff4a4383e3783c6f6ff
PatMulvihill/MachineLearning-FinancialData
/strategy_learner/StrategyLearner.py
9,600
3.578125
4
""" Template for implementing StrategyLearner (c) 2016 Tucker Balch """ """Author: Lu Wang, lwang496, lwang496@gatech.edu""" import datetime as dt import pandas as pd import util as ut import random import numpy as np import QLearner as ql class StrategyLearner(object): # constructor # Author: Lu Wang lwang496 def __init__(self, verbose = False, impact=0.0): self.verbose = verbose self.impact = impact self.qlearner = ql.QLearner(num_states=3000, \ num_actions=3, \ alpha=0.2, \ gamma=0.9, \ rar=0.5, \ radr=0.99, \ dyna=0, \ verbose=False) # this method should create a QLearner, and train it for trading def addEvidence(self, symbol = "IBM", \ sd=dt.datetime(2008,1,1), \ ed=dt.datetime(2009,1,1), \ sv = 10000): # add your code to do learning here # example usage of the old backward compatible util function syms = [symbol] dates = pd.date_range(sd, ed) prices_all = ut.get_data(syms, dates) # automatically adds SPY prices = prices_all[syms] # only portfolio symbols prices_SPY = prices_all['SPY'] # only SPY, for comparison later if self.verbose: print prices # example use with new colname volume_all = ut.get_data(syms, dates, colname="Volume") # automatically adds SPY volume = volume_all[syms] # only portfolio symbols volume_SPY = volume_all['SPY'] # only SPY, for comparison later if self.verbose: print volume train_SMA = prices.rolling(window=14, min_periods=14).mean() train_SMA.fillna(method='ffill', inplace=True) train_SMA.fillna(method='bfill', inplace=True) train_std = prices.rolling(window=14, min_periods=14).std() top_band = train_SMA + (2 * train_std) bottom_band = train_SMA - (2 * train_std) train_bbp = (prices - bottom_band) / (top_band - bottom_band) # turn sma into price/sma ratio train_SMAPrice_ratio = prices / train_SMA # caculate momentum train_momentum = (prices / prices.copy().shift(14)) - 1 train_daily_rets = (prices / prices.shift(1)) - 1 train_std = train_daily_rets.rolling(14, 14).std() train_std.fillna(method='ffill', inplace=True) train_std.fillna(method='bfill', inplace=True) train_SMAPrice_ratio_n, train_bbp_n, train_momentum_n, train_std_n = self.discritize(train_SMAPrice_ratio, train_bbp, train_momentum, train_std) strategy = train_SMAPrice_ratio_n * 100 + train_bbp_n * 10 + train_momentum_n * 10 + train_std_n start = strategy.index[0] end = strategy.index[-1] dates = pd.date_range(start, end) strategy_states = strategy.values df = pd.DataFrame(index = dates) df['positions'] = 0 df['values'] = prices.ix[start:end, symbol] df['cash'] = sv df.fillna(method='ffill', inplace=True) df.fillna(method='bfill', inplace=True) train_array = df.values converged = False round = 0 while not converged: p = 0 state = strategy_states[0, 0] action = self.qlearner.querysetstate(state) total_days = strategy_states.shape[0] prev_val = sv for i in range(1, total_days): # curr_price will be used to caculate impact curr_price = train_array[i, 1] amount = 0 if p == 0 and action == 1: amount = 1000 train_array[i, 2] = train_array[i - 1, 2] + train_array[ i, 1] * 1000 - self.impact * curr_price * abs( amount) curr_val = train_array[i, 2] - 1000 * train_array[i, 1] train_array[i, 0] = -1000 p = 1 elif p == 0 and action == 2: amount = 1000 train_array[i, 2] = train_array[i - 1, 2] - train_array[ i, 1] * 1000 - self.impact * curr_price * abs( amount) curr_val = train_array[i, 2] + 1000 * train_array[i, 1] train_array[i, 0] = 1000 p = 2 elif p == 1 and action == 2: amount = 2000 train_array[i, 2] = train_array[i - 1, 2] - train_array[ i, 1] * 2000 - self.impact * curr_price * abs( amount) curr_val = train_array[i, 2] + 1000 * train_array[i, 1] train_array[i, 0] = 1000 p = 2 elif p == 2 and action == 1: amount = 2000 train_array[i, 2] = train_array[i - 1, 2] + train_array[ i, 1] * 2000 - self.impact * curr_price * abs( amount) curr_val = train_array[i, 2] - 1000 * train_array[i, 1] train_array[i, 0] = -1000 p = 1 else: train_array[i, 0] = train_array[i - 1, 0] train_array[i, 2] = train_array[i - 1, 2] curr_val = train_array[i, 2] + train_array[i, 0] * train_array[i, 1] if prev_val == 0: reward = 0 else: reward = curr_val / prev_val - 1 prev_val = curr_val state = strategy_states[i, 0] action = self.qlearner.query(state, reward) round += 1 if round > 1300: converged = True def testPolicy(self, symbol="IBM", \ sd=dt.datetime(2009, 1, 1), \ ed=dt.datetime(2010, 1, 1), \ sv=100000): # here we build a fake set of trades # your code should return the same sort of data dates = pd.date_range(sd, ed) prices_all = ut.get_data([symbol], dates) # automatically adds SPY prices = prices_all[[symbol,]] trades = prices_all[[symbol, ]] # only portfolio symbols trades_SPY = prices_all['SPY'] # only SPY, for comparison later trades.values[:, :] = 0 test_SMA = prices.rolling(window=14, min_periods=14).mean() test_SMA.fillna(method='ffill', inplace=True) test_SMA.fillna(method='bfill', inplace=True) test_std = prices.rolling(window=14, min_periods=14).std() top_band = test_SMA + (2 * test_std) bottom_band = test_SMA - (2 * test_std) test_bbp = (prices - bottom_band) / (top_band - bottom_band) # turn sma into price/sma ratio test_SMAPrice_ratio = prices / test_SMA # caculate momentum test_momentum = (prices / prices.copy().shift(14)) - 1 test_daily_rets = (prices / prices.shift(1)) - 1 test_std = test_daily_rets.rolling(14, 14).std() test_std.fillna(method='ffill', inplace=True) test_std.fillna(method='bfill', inplace=True) test_SMA_ratio_n, test_bbp_n, test_momentum_n, test_std_n = self.discritize(test_SMAPrice_ratio,test_bbp,test_momentum, test_std) test_strategy_states = (test_bbp_n * 100 + test_momentum_n * 10 + test_std_n).values test_total_dates = test_strategy_states.size p = 0 for i in range(1, test_total_dates): state = test_strategy_states[i - 1, 0] + p * 1000 action = self.qlearner.querysetstate(state) status = 0 if p == 0 and action == 1: status = -1000 p = 1 elif p == 0 and action == 2: status = 1000 p = 2 elif p == 1 and action == 2: status = 2000 p = 2 elif p == 2 and action == 1: status = -2000 p = 1 trades.values[i, :] = status if self.verbose: print type(trades) # it better be a DataFrame! if self.verbose: print trades if self.verbose: print prices_all return trades def discritize(self,SMA_ratio,bbp,momentum, vol ): SMA_ratio_n = SMA_ratio min1 = SMA_ratio.ix[:, 0].min() max1 = SMA_ratio.ix[:, 0].max() SMA_ratio_n.ix[:, 0] = np.digitize(SMA_ratio.ix[:, 0], np.linspace(min1, max1, 10)) - 1 bbp_n = bbp min2 = bbp.ix[:, 0].min() max2 = bbp.ix[:, 0].max() bbp_n.ix[:, 0] = np.digitize(bbp.ix[:, 0], np.linspace(min2, max2, 10)) - 1 momentum_n = momentum min3 = momentum.ix[:, 0].min() max3 = momentum.ix[:, 0].max() momentum_n.ix[:, 0] = np.digitize(momentum.ix[:, 0], np.linspace(min3, max3, 10)) - 1 vol_n = vol min4 = vol.ix[:, 0].min() max4 = vol.ix[:, 0].max() vol_n.ix[:, 0] = np.digitize(vol.ix[:, 0], np.linspace(min4, max4, 10)) - 1 return SMA_ratio_n,bbp_n,momentum_n, vol_n def author(self): return 'lwang496' if __name__ == "__main__": print "One does not simply think up a strategy"
14310f84092b572c9b47ea71b2237dc8941c298f
Imsurajkr/Cod001
/demo_tuples.py
121
3.890625
4
a = b = c = d = 12 print(c) a, b = 12 , 13 print(a, b) a, b = b, a print(" a is {}".format(a)) print("b is {}".format(b))
353a3606af9aa9b5c5065edaa2e35d88f9e8ec5f
Imsurajkr/Cod001
/challenge2.py
662
4.1875
4
#!/usr/bin/python3 import random highestNumber = 10 answer = random.randint(1, highestNumber) print("Enter the number betweeen 1 and {}".format(highestNumber)) guess = 0 #initialize to any number outside of the range while guess != answer: guess = int(input()) if guess > answer: print("please Select Lower Number") # guess = int(input()) elif guess < answer: print("Please Select Higher Number ") # guess = int(input()) elif guess == 0: print("Thanks For playing") break else: print("You guessed it Great") break else: print("Great You successfully Guessed on 1st attemp")
2b779a564d313cb62050b8447f610aef98a6a91f
BobbyAD/Intro-Python-II
/src/player.py
1,590
3.671875
4
# Write a class to hold player information, e.g. what room they are in # currently. from item import Item class Player: def __init__(self, name, current_room, items): self.name = name self.current_room = current_room self.items = items def move(self, d): if d == 'n' and self.current_room.n_to: self.current_room = self.current_room.n_to return f"You are now in {self.current_room}" elif d == 's' and self.current_room.s_to: self.current_room = self.current_room.s_to return f"You are now in {self.current_room}" elif d == 'e' and self.current_room.e_to: self.current_room = self.current_room.e_to return f"You are now in {self.current_room}" elif d == 'w' and self.current_room.w_to: self.current_room = self.current_room.w_to return f"You are now in {self.current_room}" else: return "There is no room in that direction" def pickup(self, item): self.items.append(item) self.current_room.items.remove(item) print_list = "\n".join([i.__str__() for i in self.items]) print(f"\nYou have:\n{print_list}\n") def drop(self, item): self.current_room.items.append(item) self.items.remove(item) print_list = "\n".join([i.__str__() for i in self.items]) print(f"\nYou have:\n{print_list}\n") def check_inventory(self): print_list = "\n".join([i.__str__() for i in self.items]) print(f"\nYou have:\n{print_list}\n")
6ca787eac5185c966f539079a8d2b890d9dc6447
OldPanda/The-Analysis-of-Algorithms-Code
/Chapter_2/2.4.py
897
4.15625
4
""" Random Hashing: Data structure: a key array X with entries x_i for 0 <= i <= N-1 and a corresponding record array R. Initial conditions: the number of entries, k, is zero and each key location, x_i, contains the value empty, a special value that is not the value of any key. Input: a query, q. Output: a location i such that q = x_i if there is such an i (i.e., q is in the table) or i such that x_i contains empty and the hash algorithm would look in location x_i when looking for q. """ import numpy as np X = np.random.randint(10, size=10) R = np.random.randint(100, size=10) # A simple function def f(h, q): return (h*2 + q)%10 def random_hashing(q): h = 0 while True: h = h + 1 i = f(h, q) if X[i] == 0: return False elif X[i] == q: return True if __name__ == "__main__": print X print "Query 5: ", random_hashing(5) print "Query 6: ", random_hashing(6)
a151b862cce83b1f7b7065ba389b4d78ba546e59
OldPanda/The-Analysis-of-Algorithms-Code
/Chapter_2/2.2.py
1,185
3.640625
4
""" Quicksort: Input: bound l and r, and an array X with elements x_l-1, ..., x_r+1 where l <= r anf for l <= i <= r, x_l-1 <= x_i <= x_r+1. Output: a sorted permutation of the array X so that for l-1 <= i <= r, x_i <= x_i+1. """ import random """ Split: Input: an array X, a lower limit l, and an upper limit r, with l <= r. The array X is partly sorted so that, for l <= j <= r, x_l-1 <= x_j <= x_r+1. Output: a splitting index i such that l <= i <= r, and a permutation of the elements x_l, ..., x_r such that for l <= j <= i, x_j <= x_i, and for i <= j <= r, x_i <= x_j. """ def split(X, l, r): i = l j = r x = X[i] while True: while l <= j and j <= r and X[j] > x: j -= 1 if j <= i: X[i] = x return X, i X[i] = X[j] i += 1 while l <= i and i <= r and X[i] < x: i += 1 if j <= i: X[j] = x i = j return X, i X[j] = X[i] j -= 1 def quicksort(X, l, r): if l >= r: return X else: X, i = split(X, l, r) X = quicksort(X, l, i-1) X = quicksort(X, i+1, r) return X if __name__ == "__main__": n = 30 X = [random.randint(0, 100) for i in range(n)] print "X: ", X X_sort = quicksort(X, 0, n-1) print "X_sort: ", X_sort
2ca5b9fd677edf64a50c6687803c91b721bee140
basakmugdha/Python-Workout
/1. Numeric Types/Excercise 1 (Number Guessing Game)/Ex1c_word_GG.py
848
4.375
4
#Excercise 1 beyond 3: Word Guessing Game from random_word import RandomWords def guessing_game(): '''returns a random integer between 1 and 100''' r = RandomWords() return r.get_random_word() if __name__ == '__main__': print('Hmmmm.... let me pick a word') word = guessing_game() guess = input(f"Guess the word ({len(word)} characters) : ") # only 6 guesses so the game is less tedious #the for loop can be replaced with 'while True:' for the original trap style game for _ in range(5): if guess>word: print("You're far ahead in the dictionary") elif guess == word: print("YOU GUESSED IT!") break else: print("You're far behind in the dictionary") word = input('Guess again :') print(word+' is the word!')
08ea076be472f843395a37dd56c02885a0072c8c
danebista/Python
/Roshan/5.1.py
392
3.78125
4
import time running=True start_time=time.time() print("start_time{}".format(start_time)) while running: now_time=time.time() print("now_time{}".format(now_time)) second_depends=now_time-start_time print("second_depends{}".format(second_depends)) if second_depends==3: start_time=now_time print("now_time:{}".format(start_time)) second_depends=int()
942d67e9bbad4dc5a890de12ef0317b6af4f571f
danebista/Python
/suzan/python3.py
2,143
4.1875
4
#!/usr/bin/env python # coding: utf-8 # Print formatting # In[1]: print ("hurry makes a bad curry") # In[3]: print("{1} makes a bad {0}".format("curry","hurry")) # In[7]: print("The {e} rotates {a} a {s}".format(e="Earth",a="around",s="Sun")) # In[8]: result=9/5 print(result) # In[9]: result=100/3 print(result) # In[82]: print("the result is {r:1.4f}".format(r=result)) # In[13]: celsius=((132-32)*5)/9 # In[14]: print(celsius) # boolean # In[17]: a=True # In[18]: a=False # Operators # In[20]: 5>=6 # In[21]: not 5>=6 # looping # # In[23]: a="hello"; if a.lower()=="hello": print(a) elif a.lower()=="hello": print(a) else: print(a) # In[24]: a="hello" for variable in a: print(variable) # In[28]: a=["hello","world"] for variable in a: print (variable) # In[29]: for i in range (0,10,2): print(i) # In[30]: for i in range(0,10): print(i%2) # In[31]: abc=[(0,1),(2,3),(4,5),(5,6),(6,7)] for i in abc: print(i) # In[33]: abc=[(0,1),(2,3),(4,5),(5,6),(6,7)] for first_number,second_number in abc: print(second_number) # In[34]: abc=[(0,1),(2,3),(4,5),(5,6),(6,7)] for first_number,second_number in abc: print(first_number) # In[35]: abc="hello" for i in enumerate(abc): print(i) # In[36]: abc="hello" for index,value in enumerate(abc): print(value) # In[39]: abc="hello" for index, value in enumerate(abc): print(index) # In[40]: a=[1,2,3,4,5] b=[6,7,8,9,10] for i in zip(a,b): print(i) # In[67]: a=[1,2,3,4,5] b=[6,7,8,9,10] c=[11,12,13,14,15] for i in zip(a,b,c): print(i) # List Comprehension # In[66]: a="hello" b=[ ] for i in a: b.append(i) print(b) # In[68]: m="hello" n=[x for x in m] print (n) # In[81]: a=[] b=[x for x in range (0,10,2)] print(b) # In[83]: a="hello" b=[x for x in enumerate(a)] print(b) # In[109]: a="hello" b=[y for (x,y) in enumerate(a) if x%2 == 0] print(b) # While loop # In[111]: x=0 while x<=5: print(x) x=x+1 else: print(x) # In[112]: x=0 while x<=5: print(x) x=x+1 # In[ ]:
1ac4b7c404234ef0dc0f1051a7f35308eac85a3d
danebista/Python
/avni/sun.py
1,038
3.90625
4
#!/usr/bin/env python # coding: utf-8 # In[4]: for i in range(10): pass # In[3]: for i in range(10): # In[6]: for i in range(10): print(i) if i==5: break # In[8]: for i in range(10): if i==5: continue print(i) # Methods vs functions # In[13]: a="Ram has a cat" def check_cat(word): if 'cat' in word: return True check_cat(a) # In[18]: a=[10,15,20,25,30,35] def sum_digits(x,y): return (x+y) for i in range(5): print(sum_digits(a[i],a[i+1])) # In[23]: def convert(f): return ((f-32)*5/9) print(convert(100)) # In[25]: f=[100,98,56,35,68] def convert(x): return ((x-32)*5/9) for i in range(5): print(convert(f[i])) # In[27]: d={'stat':5,'dsa':6,'cg':7} for i in d: print(i) # In[28]: d={'stat':5,'dsa':6,'cg':7} for i in d.items(): print(i) # In[30]: def sqrt(a): return (a**0.5) sqrt(4) # tupple unpacking # In[34]: d={'stat':5,'dsa':6,'cg':7} for x,y in d.items(): print(x,y) # In[ ]:
56b146eba5579b568901fa1d51d5a494bff47067
sragha45/helloworld
/p5.py
233
3.90625
4
a=raw_input("Enter number 1:") b=raw_input("Enter number 2:") c=raw_input("Enter number 3:") a = int(a) b = int(b) c = int(c) max=max(a,b,c) min=min(a,b,c) num=a+b+c-max-min print "Descending order is:" print(max,num,min)
804334a8092fd0965ccd8f2455eaed0d27e66ce6
wso0622/euler1
/euler1.py
98
3.9375
4
sum =0 for n in range (1, 1000): if(n%3==0 or n%5==0): sum += n print("Sum is", sum)
d4751911223fca2a2f47016042b3577af85cd8ba
mouse-pallet/SamplePython
/Exercize10-1.py
349
3.703125
4
class Player: def __init__(self,name,age,height): self.age=age self.name=name self.height=height def IncreaseAge(self): self.age+=1 def PrintInformation(self): print("This is {0}, he is {1} years old and {2} cm.".format(self.name,self.age,self.height)) player1=Player("Jhon",20,170) player1.IncreaseAge() player1.PrintInformation()
68413a9d21e272156d72d840d0e81dfb35676a42
mouse-pallet/SamplePython
/ForSample2.py
154
4.1875
4
#reverse l=['hola','Hello','konnitiwa','hallo'] for element in reversed(l): print(element) quit() for i in range(len(l)-1,-1,-1): print(l[i])
f4a8308ad335b1f4e046cf9599012a099955649f
Manasa0704/Codeforces
/133A.py
146
3.921875
4
s=str(raw_input()) #s='Hi!' i=0 while i<len(s): if(s[i]=='H' or s[i]=='Q' or s[i]=='9'): print 'YES' exit() else: i+=1 print "NO"
272d55e87dbf0a84d33c97647bc55c660b4a6476
manuhon99/ise
/mongodbConnection.py
702
3.546875
4
''' Connection data to MongoDB using pymongo lib ''' import os from pymongo import MongoClient def connect_mongo(data, collection, content): # Making Connection myclient = MongoClient("mongodb://localhost:27017/") # database db = myclient[data] # Created or Switched to collection Collection = db[collection] # Inserting the loaded data in the Collection # if JSON contains data more than one entry # insert_many is used else inser_one is used if isinstance(content, list): Collection.insert_many(content) else: Collection.insert_one(content) myclient.close() if __name__ == "__main__": connect_mongo()
125fbbd64d07295817c621b11d4dcb1ad154933b
staminazhu/Scientific-Software-Development-with-Fortran
/old stuff/forpedo/forpedo.py
8,487
3.875
4
#!/usr/bin/env python import sys import re #---------------------------- # General functions #---------------------------- def combine(*seqin): """ Returns a list of all combinations of argument sequences. For example: combine((1,2),(3,4)) returns [[1, 3], [1, 4], [2, 3], [2, 4]] """ def rloop(seqin,listout,comb): """recursive looping function""" if seqin: # any more sequences to process? for item in seqin[0]: newcomb=comb+[item] # add next item to current comb rloop(seqin[1:],listout,newcomb) else: # processing last sequence listout.append(comb) # comb finished, add to list listout=[] # listout initialization rloop(seqin,listout,[]) # start recursive process return listout #---------------------------- # Grammatical classes #---------------------------- class GrammaticalEntityParser: """ Abstract base class for a grammatical entity parser. A grammatical entity is anything in the source code that you might want to extract or modify. Subclasses of this class recognise such entities, and are responsible for extracting or modifying them. """ def __init__(self, regExString, maxMatchesPerLine = None): self.regEx = re.compile( regExString ) self.maxMatchesPerLine = maxMatchesPerLine def processLine( self, line, processFunc ): count = 0 newLines = [] changedLine = line retLines = None startSearchIndex = 0 while True: m = self.regEx.search(changedLine, startSearchIndex) if not m: break startSearchIndex = m.start(0) + 1 count = count + 1 if self.maxMatchesPerLine and count > self.maxMatchesPerLine: break retLines = processFunc(self, changedLine, m ) if retLines: changedLine = retLines[0] if retLines and len(retLines) > 0: newLines = retLines else: newLines = None return newLines def processFirstPassLine( self, line ): return self.processLine( line, lambda item, line, match: item.processFirstPassMatch( line, match ) ) def processSecondPassLine( self, line ): return self.processLine( line, lambda item, line, match: item.processSecondPassMatch( line, match ) ) def processFirstPassMatch(self, line, match): return None def processSecondPassMatch(self, line, match): return None class ImportStatementParser (GrammaticalEntityParser): """ An import statement parser. Imports the file given by the file named. Form: #import "FileName" """ def __init__(self): GrammaticalEntityParser.__init__(self, r'^\s*\#import\s*[\'\"](\w+)[\'\"]', 1) def processFirstPassMatch( self, line, matchObject ): f = open(matchObject.group(1)) newLines = f.readlines() f.close() return newLines class DefineTypeStatementParser (GrammaticalEntityParser): """ The definetype statement, which defines an instaniation of a generic type. Form: #definetype TypeName TypeTag ConcreteFortranType Replaces Typename with the fortran type in the code instance. The TypeTag can be used to name things in the global namespace, to avoid naming conflicts. For example, a module XYZ could be named XYZ<TypeName>, and the tag would be appended to the name XYZ in the generated source code. """ def __init__(self): GrammaticalEntityParser.__init__(self, r'^\s*\#definetype\s+(\w+)\s+(\w+)\s+(.+)' , 1) self.instancesPerType = {} self.instancesPerAbbrev = {} def processFirstPassMatch( self, line, matchObject ): label = matchObject.group(1) abbrev = matchObject.group(2) type = matchObject.group(3) inst = Instantiation( label, abbrev, type ) self.instancesPerType.setdefault(label, []).append(inst) return None def processSecondPassMatch( self, line, matchObject ): return [""] class DefinedTypeDeclParser (GrammaticalEntityParser): """ This is a generic type declaration. It will be replaced by the concrete types defined in the #definetype construct when generating fortran source. Form: @TypeName :: variable The #definetype construct defines different instances of a given generic type. The preprocessor will generate a separate block of source code for each instance, replacing the generic type declarations in each one with the concrete fortran type. """ def __init__(self, instantiationPerTypeName): GrammaticalEntityParser.__init__(self, r'@(\w+)') self.instantiationPerTypeName = instantiationPerTypeName def processSecondPassMatch( self, line, matchObject ): typeLabel = matchObject.group(1) newLine = line[:matchObject.start(0)] + self.instantiationPerTypeName[typeLabel].type + line[matchObject.end(0):] return [newLine] class DefinedTypeTagParser (GrammaticalEntityParser): """ A tag associated with a particular instance of a generic type. This can be used to avoid naming conflicts. Form: SomeGlobalIdentifier<DefinedTypeName> In an instance of the DefinedTypeName with the tag equal to "R", the above identifier will be replaced with "SomeGlobalIdentifierR". """ def __init__(self, instantiationPerTypeName): GrammaticalEntityParser.__init__(self, r'<(\w+)>') self.instantiationPerTypeName = instantiationPerTypeName def processSecondPassMatch( self, line, matchObject ): typeLabel = matchObject.group(1) newLine = line[:matchObject.start(0)] + self.instantiationPerTypeName[typeLabel].abbrev + line[matchObject.end(0):] return [newLine] #---------------------------- # Template instantiations #---------------------------- class Instantiation: """ Simple data storage class, used to store details of a single template instantiation. Could also use a dictionary. """ def __init__(self, typeName, abbrev, type): self.typeName = typeName self.abbrev = abbrev self.type = type #---------------------------- # Preprocessing functions #---------------------------- def ProcessLines( lines, entities, processFunc ): """ Process lines one at a time, processing each line with each grammatical entity. The processFunc is the particular processing function to use. It takes the entity and line as arguments. This function is called by the FirstPass and SecondPass functions. """ lineIndex = 0 newLines = lines[:] while lineIndex < len(newLines): for item in entities: line = newLines[lineIndex] retLines = processFunc(item, line) if retLines: newLines[lineIndex:lineIndex+1] = retLines lineIndex = lineIndex + 1 return newLines def FirstPass( lines ): "Perform first pass processing" definetypeStmt = DefineTypeStatementParser() entities = [ ImportStatementParser(), definetypeStmt ] newLines = ProcessLines( lines, entities, lambda item, line: item.processFirstPassLine(line) ) return newLines, definetypeStmt def SecondPass( lines, definetypeStmt ): "Perform second pass processing" types = definetypeStmt.instancesPerType.keys() instancesArray = [] for t in types: instancesArray.append( definetypeStmt.instancesPerType[t] ) combinations = combine(*instancesArray) newLines = [] for c in combinations: entities = [definetypeStmt] instDict = {} for inst in c: instDict[inst.typeName] = inst entities.append( DefinedTypeDeclParser(instDict) ) entities.append( DefinedTypeTagParser(instDict) ) instanceLines = ProcessLines( lines, entities, lambda item, line: item.processSecondPassLine(line) ) newLines.extend( instanceLines ) return newLines #---------------------------- # Main #---------------------------- lines = sys.stdin.readlines() lines, definetypeStmt = FirstPass( lines ) lines = SecondPass( lines, definetypeStmt ) for l in lines: print l,
5ca81d67c844790fecb6b4636164094e30975d49
AaayushUpadhyay/python-modules
/Python Tutorial-CSV Module/parse_csv.py
3,135
4.40625
4
# CSV - Comma Separated Values import csv # Reading a csv file # with open('names.csv','r') as csv_file: # csv_reader=csv.reader(csv_file) # # .read() return a generator so we have to loop over it # for line in csv_reader: # print(line) # OUTPUT # ['first_name', 'last_name', 'email'] # ['John', 'Doe', 'john-doe@bogusemail.com'] # ['Mary', 'Smith-Robinson', 'maryjacobs@bogusemail.com'] # ['Dave', 'Smith', 'davesmith@bogusemail.com'] # ['Jane', 'Stuart', 'janestuart@bogusemail.com']... # IF WE DONT WANT THE FIRST LINE THEN # with open('names.csv','r') as csv_file: # csv_reader=csv.reader(csv_file) # next(csv_reader) # # .read() return a generator so we have to loop over it # for line in csv_reader: # print(line) # OUTPUT # ['John', 'Doe', 'john-doe@bogusemail.com'] # ['Mary', 'Smith-Robinson', 'maryjacobs@bogusemail.com'] # ['Dave', 'Smith', 'davesmith@bogusemail.com'] # ['Jane', 'Stuart', 'janestuart@bogusemail.com'] # ['Tom', 'Wright', 'tomwright@bogusemail.com'] # ['Steve', 'Robinson', 'steverobinson@bogusemail.com']... # IF WE WANT ONLY THE EMAILS OR FIRST NAMES OR LAST NAMES # with open('names.csv','r') as csv_file: # csv_reader=csv.reader(csv_file) # next(csv_reader) # # .read() return a generator so we have to loop over it # for line in csv_reader: # # print(line[0]) # ONLY FIRST NAMES # # print(line[1]) # ONLY LAST NAMES # # print(line[2]) # ONLY EMAILS # WRITING A CSV FILE # # writing data in csv file with '-' as delimiter # with open('names.csv','r') as csv_file: # csv_reader=csv.reader(csv_file) # with open('new_file.csv','w') as new_file: # csv_writer=csv.writer(new_file,delimiter='-') # for line in csv_reader: # csv_writer.writerow(line) # writing data in csv file with '\t(tab space)' as delimiter # with open('names.csv','r') as csv_file: # csv_reader=csv.reader(csv_file) # with open('new_file.csv','w') as new_file: # csv_writer=csv.writer(new_file,delimiter='\t') # for line in csv_reader: # csv_writer.writerow(line) # Reading data from a file with a different delimiter # with open('names.csv','r') as csv_file: # csv_reader=csv.reader(csv_file,delimiter='@') # for line in csv_reader: # print(line) # output # ['first_name,last_name,email'] # ['John,Doe,john-doe', 'bogusemail.com'] # ['Mary,Smith-Robinson,maryjacobs', 'bogusemail.com'] # ['Dave,Smith,davesmith', 'bogusemail.com'] # ['Jane,Stuart,janestuart', 'bogusemail.com'] # Using dictionary readers and writers # reading a csv file using dictionary readers # with open('names.csv','r') as csv_file: # csv_reader=csv.DictReader(csv_file) #header values become keys # for line in csv_reader: # print(line) # # if we just want emails # # print(line['email']) # writing a csv file using dictionary writers with open('names.csv','r') as csv_file: csv_reader=csv.DictReader(csv_file) with open('new_file.csv','w') as new_file: # fieldnames = ['first_name','last_name','email'] # if we dont want emails in our new file fieldnames = ['first_name','last_name'] csv_writer=csv.DictWriter(new_file,fieldnames=fieldnames,delimiter='\t') # if we want header values to be displayed then csv_writer.writeheader() for line in csv_reader: del line['email'] # if we dont want emails in our new file csv_writer.writerow(line)
161e3cbfae915c638f02659e5d93867e465fef06
nguyenduchuy2017/2017-07-11
/homework/list_HW-1.py
440
3.75
4
lst_1 = [1, 2, 3, [1, 2], 2, [1, [1, 3]], 20] print(lst_1) str_1 = str(lst_1) # Convert to String str_2 = str_1.replace('[', '') # Delete all unneeded symbols str_3 = str_2.replace(']', '') str_4 = str_3.replace(',', '') str_5 = str_4.replace(' ', '') lst_3 = [] # Convert "string" chars to int and and fill the new emty list for elem in str_5: elem = int(elem) lst_3.append(elem) print(lst_3)
04e2d90d3a1e4f801f5885325eea7fdb2f612039
nguyenduchuy2017/2017-07-11
/homework/Cross_and_None_game.py
3,214
4.125
4
num_of_rows = int(input('Enter the quantity of rows(colums) :')) player_1 = input('Player 1, Please, enter your name: ') player_2 = input('Player 2, Please, enter your name: ') game_board_coord = {} GBC = game_board_coord max_number_way = num_of_rows**2 ways_counter = 0 def game_board_init(num_of_rows): for x in range(num_of_rows): for y in range(num_of_rows): GBC[x, y] = ' ' if (y+1) % num_of_rows == 0: print('!' + GBC.get((x, y)) + ' !') else: print('!', GBC.get((x, y)), end='') print(game_board_coord) def game_board_update(num_of_rows): for x in range(num_of_rows): for y in range(num_of_rows): if (y+1) % num_of_rows == 0: print('! ' + GBC.get((x, y)) + '!') else: print('!', GBC.get((x, y)), end='') def repeat_game(): if repeat_play == 'y': player_1_way() else: print('The game is over !') exit() def player1_way_check(x, y): while GBC[(x, y)] is not ' ': print('Incorrect ! Please, enter correct coord : ') player_1_way() def player2_way_check(x, y): while GBC[(x, y)] is not ' ': print('Incorrect ! Please, enter correct coord : ') player_2_way() def result_check(counter, player): if counter == num_of_rows: print(player, " , You are winner !!!") repeat_game() def check_for_winner(): counter_5 = counter_6 = counter_7 = counter_8 = 0 for x in range(num_of_rows): counter_1 = counter_2 = counter_3 = counter_4 = 0 for y in range(num_of_rows): if GBC[(x, y)] == 'X': counter_1 += 1 result_check(counter_1, player_1) elif GBC[(x, y)] == 'O': counter_2 += 1 result_check(counter_2, player_2) if GBC[(y, x)] == 'X': counter_3 += 1 result_check(counter_3, player_1) elif GBC[(y, x)] == 'O': counter_4 += 1 result_check(counter_4, player_2) if x == y and GBC[(x, y)] == 'X': counter_5 += 1 result_check(counter_5, player_1) elif x == y and GBC[(x, y)] == 'O': counter_6 += 1 result_check(counter_6, player_1) if (y == num_of_rows - 1 - x) and GBC[(x, y)] == 'X': counter_7 += 1 result_check(counter_7, player_1) elif (y == num_of_rows - 1 - x) and GBC[(x, y)] == '0': counter_8 += 1 result_check(counter_8, player_1) def player_1_way(): global ways_counter player1_x = int(input('Player 1, please, enter coord X : ')) player1_y = int(input('Player 1, please, enter coord Y : ')) player1_way_check(player1_x, player1_y) GBC[(player1_x, player1_y)] = 'X' game_board_update(num_of_rows) ways_counter += 1 check_for_winner() if ways_counter == max_number_way: repeat_play = input('You are draw ! Do you want to play again ? ("y" or "n") ') repeat_game() player_2_way() def player_2_way(): global ways_counter player2_x = int(input('Player 2,please, enter coord X : ')) player2_y = int(input('Player 2,please, enter coord Y : ')) player2_way_check(player2_x, player2_y) GBC[(player2_x, player2_y)] = 'O' game_board_update(num_of_rows) check_for_winner() ways_counter += 1 check_for_winner() if ways_counter == max_number_way: repeat_play = input('You are draw ! Do you want to play again ? ("y" or "n") ') repeat_game() player_1_way() game_board_init(num_of_rows) player_1_way()
c974e04a9696599ccd0f5efb7dee095163fb1aa3
RagibRishad/PythonBook
/Chapter2/6.1.py
121
3.625
4
de main(): y1 = eval(input("amount for yr 1: ")) ir = eval(input("interest: ")) yrs = eval(input("yrs: "))
378b15e29b0492c03cdeb813fa8e044dad1185dc
RagibRishad/PythonBook
/Chapter 3/3.6.py
174
3.734375
4
# 2 points are (x1, y1) and (x2, y2) def main(): x1 = 5 y1 = 6 x2 = 8 y2 = 9 slope = (y2 - y1)/(x2 - x1) print("Slope is ", round(slope)) main()
b5b486ef157b0258d81c58cfef9030821116f318
kseil/mycode
/mix-list/mixlist01.py
444
3.953125
4
#!/usr/bin/env python3 #make list my_list=["192.168.0.5", 5060, "UP"] #print item one from list print("The first item in the list (IP): " + my_list[0]) #print item two from list print("The second item in the list (port): " + str(my_list[1])) #print item three from list print("The last item in the list (state): " + my_list[2]) iplist= [5060, "80", 55, "10.0.0.1", "10.20.30.1", "ssh"] print("IPs are as follows:" , iplist[3], iplist[4])
96a224d99ebd76fa959e27363cb1a10ebc54f44b
kseil/mycode
/morningproject.py
165
3.8125
4
#!/usr/bin/env python3 items = ['biscuit', 'bed', 'desk', 'biscuit', 'books', 'computer', 'biscuit'] for i in items: if i == 'biscuit': print("SLAP!")