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
bcb0793a5ba8769b2f81aa2643cf9023a2edf337
ztankdestroyer/pre-ap-cs
/menu gui, enhanced.py
3,919
3.515625
4
from tkinter import * class Application(Frame): def __init__(self, master): super(Application, self).__init__(master) self.grid() self.create_widgets() self["background"] = "#ADEBF7" self["borderwidth"] = 0 def create_widgets(self): Label(self, text = "Restaurant menu", bg = "#ADEBF7", bd = 0 ).grid(row = 0, column = 0, columnspan = 2, sticky = W) Label(self, text = "Meals(s):", bg = "#ADEBF7", bd = 0 ).grid(row = 4, column = 0, sticky = W) self.is_Burger = BooleanVar() Checkbutton(self, text = "Burger", bg = "#ADEBF7", bd = 0, variable = self.is_Burger ).grid(row = 4, column = 1, sticky = W) self.is_Dump = BooleanVar() Checkbutton(self, text = "Chicken And Dumplins", bg = "#ADEBF7", bd = 0, variable = self.is_Dump ).grid(row = 4, column = 2, sticky = W) self.is_chick = BooleanVar() Checkbutton(self, text = "Fried Chicken", bg = "#ADEBF7", bd = 0, variable = self.is_chick ).grid(row = 4, column = 3, sticky = W) Label(self, text = "Drinks:", bg = "#ADEBF7", bd = 0 ).grid(row = 5, column = 0, sticky = W) self.Drink = StringVar() self.Drink.set(None) Drink = ["Water", "Juice", "Soda"] column = 1 for part in Drink: Radiobutton(self, text = part, bg = "#ADEBF7", bd = 0, variable = self.Drink, value = part ).grid(row = 5, column = column, sticky = W) column += 1 Label(self, text = "Tips:", bg = "#ADEBF7", bd = 0 ).grid(row = 6, column = 0, sticky = W) self.Tips = StringVar() self.Tips.set(None) Tips = ["5%", "10%", "15%"] column = 1 for part in Tips: Radiobutton(self, text = part, bg = "#ADEBF7", bd = 0, variable = self.Tips, value = part ).grid(row = 6, column = column, sticky = W) column += 1 Button(self, text = "Click for total", bg = "#ADEBF7", bd = 0, command = self.show_menu ).grid(row = 7, column = 0, sticky = W) self.final_txt = Text(self, width = 75, height = 10, wrap = WORD) self.final_txt.grid(row = 8, column = 0, columnspan = 4) def show_menu(self): price = 0 cost = 0 tip = 0 rounded_tip = 0 if self.is_Burger.get(): price += 12.99 if self.is_Dump.get(): price += 15.99 if self.is_chick.get(): price += 9.99 current_Drink = self.Drink.get() if current_Drink == "Water": cost += 1.99 if current_Drink == "Juice": cost += 3.99 if current_Drink == "Soda": cost += 3.99 current_Tip = self.Tips.get() if current_Tip == "5%": tip = ((price + cost) * .05) rounded_tip = round(tip, 2) if current_Tip == "10%": tip = ((price + cost) * .1) rounded_tip = round(tip, 2) if current_Tip == "15%": tip = ((price + cost) * .15) rounded_tip = round(tip, 2) final = "$" final +=str(price + cost + rounded_tip) self.final_txt.delete(0.0, END) self.final_txt.insert(0.0, final) self.final_txt["background"] = "#ADEBF7" self.final_txt["borderwidth"] = 0 root = Tk() root.title("Menu") app = Application(root) root.mainloop()
c75a1774b3d16f850f66a24a24ee1b206adbb9e9
bashmastr/CS101-Introduction-to-Computing-
/Assignments/05/a05.py
1,458
4.125
4
## IMPORTS GO HERE ## END OF IMPORTS #### YOUR CODE FOR is_prime() FUNCTION GOES HERE #### def is_prime(y): if y > 1: x = int(y) if x==y: if x == 1: return False if x == 0: return False if x == 2: return True if x >=2: if x>=2: if x%2==0: return False for i in range(3,int(x**0.5)+1,2): if x%i==0: return False return True else: return False else: return False #### End OF MARKER #### YOUR CODE FOR output_factors() FUNCTION GOES HERE #### def output_factors(x): d = 0 while d < x: d = d + 1 if x % d == 0: print d #### End OF MARKER #### YOUR CODE FOR get_largest_prime() FUNCTION GOES HERE #### def get_largest_prime(z): if z >= 2: x=int(z) if is_prime(x): return int(x) else: x = x-1 return get_largest_prime(x) return None #### End OF MARKER if __name__ == '__main__': print is_prime(499) # should return True print get_largest_prime(10) # should return 7 # print get_largest_prime(100000) # bonus, try with 100k output_factors(10) # should output -- 1 2 5 10 -- one on each line
ad9f1e68d6171a96f2cda9cb80e11034793bd1cc
Pawan300/Algorithms-Python
/mergesort.py
978
4.0625
4
def merge(arr,start,middle,end): i=0 j=0 k=start nl=int(middle-start+1) nr=int(end-middle) l=[0]*nl r=[0]*nr for i in range(0,nl): l[i]=arr[i+start] for j in range(0,nr): r[j]=arr[j+middle+1] while i<nl and j<nr: if l[i]<=r[j]: arr[k]=l[i] i=i+1 else: arr[k]=r[j] j=j+1 k=k+1 while(j<nr): arr[k]=r[j] j=j+1 k=k+1 while(i<nl): arr[k]=l[i] i=i+1 k=k+1 def merge_sort(arr,start,end): if(start<end): middle=int((start+(end-1))/2) merge_sort(arr,start,middle) merge_sort(arr,middle+1,end) merge(arr,start,middle,end) arr = [1,9,90,34,45,2, 5, 6,27, 7, 2 , 6] n = len(arr) print ("Given array is") for i in range(n): print (arr[i],end=" ") merge_sort(arr,0,n-1) print("\nsorted array is : ") print(arr)
7480b2b936688709b70d7ce8f484cde408b32e46
Pawan300/Algorithms-Python
/insertionboth.py
883
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 8 21:51:20 2018 @author: pawan_300 """ # -*- coding: utf-8 -*- """ Created on Mon Jul 30 12:38:05 2018 @author: pawan_300 """ l=[] def insertionmax(l,temp): for i in range(1,temp): lamda=l[i] j=i-1 while((j>=0)&(lamda>l[j])): l[j+1]=l[j] j=j-1 l[j+1]=lamda print(l) def insertionmin(l,temp): for i in range(1,temp): lamda=l[i] j=i-1 while((j>=0)&(lamda<l[j])): l[j+1]=l[j] j=j-1 l[j+1]=lamda print(l) temp=int(input("Enter number of digit : ")) for i in range(0,temp): t=int(input("Enter numbers: ")) l.append(t) print("Unsorted list is : ",l) print("ASCENDING ORDER") insertionmin(l,temp) print("DESCENDING ORDER") insertionmax(l,temp)
76a3ccadcb3e7bf263594fe40f803e37e46614be
ureka712/freshworkassign
/crd.py
2,161
3.609375
4
import json def create(): def writejson(data,filename="datastore1.json"): with open (filename,"w") as f: json.dump(data,f,indent=3) with open("datastore1.json") as jfile: data = json.load(jfile) temp=data["employee_details"] per = {} vem=input("enter employee name ") for i in range(len(temp)): if vem in temp[i]: print("already exists") break else: p = {} p["name"]=vem p["age"]=input("ENTER AGE") p["empid"]=input("ENTER EMPLOYEE ID") p["location"]=input("enter the location") per[vem] = p temp.append(per) writejson(data) def read(): f=open("datastore1.json","r") temp=json.load(f) flag=temp['employee_details'] name_for_read=input("enter the name of employee").strip() for i in flag: if name_for_read in i.keys(): print(i[name_for_read]) break else: print("no such employee") def delete(): f = open("datastore1.json", "r") temp = json.load(f) flag = temp['employee_details'] name_for_read = input("enter the name of employee").strip() for i in flag: b=i[name_for_read] if b in i.keys(): del(b) print("employee details successfully deleted") break else: print("no such employee") with open("datastore1.json","w")as kfile: kfile.write(json.dumps(flag,indent=3)) while(True ): def switch(k): if k == "c" or k == "C": create() elif k == "r" or k == "R": read() elif k == "d" or k == "D": delete() else: print("NO SUCH OPERATION") cont = input("to start or continue the process give input as 1 to quit give 0") if cont=="1": pass else: quit() print("EMPLOYEE DETAILS " "c- TO CREATE NEW EMPLOYEE DETAILS" "r- TO READ ABOUT EMPLOYEE DETAILS" "d- TO DELETE EMPLOYEE DETAILS ") k = input().strip() switch(k)
3041326059164187c5fb2bca7f0693f23e001333
rsdefever/mws
/mws/signac.py
700
3.515625
4
def check_simulation(filen, nsteps): """Check the energy file to determine if the simualtion is complete Parameters ---------- filen : string energy file name to check nsteps : int number of steps in simulation Returns ------- complete : bool True if the simulation has reached nsteps, else false """ try: with open(filen) as f: for line in f: pass last = line.strip().split() except OSError: return False try: if int(last[0]) == nsteps: return True else: return False except (ValueError, IndexError): return False
f01a4b935750f250b57fbf8f9f73edb4a8a8aa0f
Tonovasquez/python3
/Ejercicios 33/ejercicio30.py
190
4.03125
4
#Hacer un programa que me muestre la raiz cuadrada de cualquier numero ingresado. numero = float(input("Ingresa un numero:.")) raiz = numero **(1/2) print("La raiz es de:. {}".format(raiz))
952f8170b5cd7423f72983c7bf56f25ef3b1dd60
Jeff-Osbourn/Sorting-App
/SortTest.py
1,486
3.8125
4
# Ask the user to enter the names of files to compare fname1 = input("Enter the first filename: ") fname2 = input("Enter the second filename: ") # Open the file so we can start comparing them file1 = open(fname1) file2 = open(fname2) # Get the first line in each file check1 = file1.readline() check2 = file2.readline() # Variable to keep track of the line count line_check = 1 while check1 != '' or check2 != '': # Strip the leading whitespaces check1 = check1.rstrip() check2 = check2.rstrip() # Compare the lines from both file if check1 != check2: # Checks if there is nothing in file2, but file1 has a value if check2 == '' and check1 != '': print("Output : ", "Line-%d" % line_check, check1) # Print value of file1 elif check1 != '': print("Output : ", "Line-%d" % line_check, check1) # Checks if there is nothing in file1, but file1 has a value if check1 == '' and check2 != '': print("Sorted_Text : ", "Line-%d" % line_check, check2) # Print value of file2 elif check2 != '': print("Sorted_Text : ", "Line-%d" % line_check, check2) # Print a blank line print('\n') #Read the next line from the file check1 = file1.readline() check2 = file2.readline() #Increment line counter line_check += 1 file1.close() file2.close()
6832a42539daa56e2f4c04a1238236a2cfc31e98
mmuratardag/DS_SpA_all_weeks
/DS_SpA_W10_Recommender_System/03_19/TeachMat/flask-recommender/recommender.py
1,270
4.1875
4
#!/usr/bin/env python import random MOVIES = ["The Green Book", "Django", "Hors de prix"] # def get_recommendation(): # return random.choice(MOVIES) def get_recommendation(user_input: dict): m1 = user_input["movie1"] r1 = user_input["rating1"] m2 = user_input["movie2"] r2 = user_input["rating2"] m3 = user_input["movie3"] r3 = user_input["rating3"] """The rest is up to you....HERE IS SOME PSEUDOCODE: 1. Train the model (NMF), OR the model is already pre-trained. 2. Process the input, e.g. convert movie titles into numbers: movie title -> column numbers 3. Data validation, e.g. spell check.... 4. Convert the user input into an array of length len(df.columns), ~9742 --here is where the cosine similarity will be a bit different-- 5. user_profile = nmf.transform(user_array). The "hidden feature profile" of the user, e.g. (9742, 20) 6. results = np.dot(user_profile, nmf.components_) 7. Sort the array, map the top N values to movie names. 8. Return the titles. """ return random.choice([m1, m2, m3]) if __name__ == "__main__": """good place for test code""" print("HELLO TENSORS!") movie = get_recommendation() print(movie)
01db284a5ef14f2625b3e86f41e84c1450bf8cf6
jundoopop/self_june
/onlypractice/datastructure/stack/boj1874.py
1,401
4.0625
4
# https://www.acmicpc.net/problem/1874 """ Stacked Array push, pop, LIFO -> Those three features are characters that Stack data has. - Assuming implementing an array same as the input array. - From the ascending array. If the number of pushed numbers are more than one, but requires ascending order -> It cannot be implemented. """ list_of_pushed_number = ( [] ) # list_of_pushed_number is a list to contain the temporary numbers stack = [] # Stack is for printing result targeted_number = 1 # targeted_number is for a comparison with the number input for i in range(int(input())): # int(input()): n (iteration) number = int(input()) # This number consists a stack while targeted_number <= number: # If list_of_pushed_number is needed to be added list_of_pushed_number.append(targeted_number) stack.append("+") # Record the history of push targeted_number += 1 # Step to next targeted number # This print is for checking if list works correctly # print(f"Temp Stack: {list_of_pushed_number}") if number == list_of_pushed_number.pop(): # If the sequence of stack is valid stack.append("-") # Record the history of pop else: # If it is invalid print("NO") # Print 'NO' and break the loop break else: # When loop successfully iterated to the end print("\n".join(stack)) # Print by using join method.
704a6d87fe7515bfc10ad924222255d0fe32d588
jundoopop/self_june
/onlypractice/datastructure/stack/boj10828.py
1,307
4.03125
4
# https://www.acmicpc.net/problem/10828 # stack implmlentation """ The stack stores integers by input. The stack has the following commands: push X: Push the integer 'X' into the stack pop: Pop the top element of the stack and print. If the stack is empty, print -1 size: Print the size of the stack empty: Print 1 if the stack is empty, otherwise 0 top: Print the top element of the stack """ import sys # input() is slow, so use sys.stdin.readline() input = sys.stdin.readline # Initialize the list stack_list = [] # iter_number decides how many times to iterate the loop iter_number = int(input()) # repeats for the times of iter_number for i in range(iter_number): # Put command command = input().split() # top: last element of the list if command[0] == "top": print(stack_list[-1]) if len(stack_list) != 0 else print(-1) # size: length of the list elif command[0] == "size": print(len(stack_list)) # if the length of the list is 0 or not elif command[0] == "empty": print(1) if len(stack_list) == 0 else print(0) # pop method elif command[0] == "pop": print(stack_list.pop()) if len(stack_list) != 0 else print(-1) # The case 'push' which is last else: stack_list.append(command[1])
cfe614c9161aed2a4f736ef119e23d90912aff12
G-noname/G-noname-001
/Challenge1/calculator_eg2.py
1,182
3.734375
4
#!/usr/bin/env python3 from collections import namedtuple #使用nametuple给元组索引命名,这样就可以像调用字典value一样调用元组元素(代码易读、规范) IncomeTaxQuickLookupItem = nametuple( 'IncomeTaxQuickLookupItem' ['start_point','tax_rate','quick_subtractor'] ) INCOME_TAX_START_POINT = 3500 INCOME_TAX_QUICK_LOOKUP_TABLE = [ IncomeTaxQuickLookupItem(80000,0.45,13505), IncomeTaxQuickLookupItem(55000,0.35,5505), IncomeTaxQuickLookupItem(35000,0.30,2755), IncomeTaxQuickLookupItem(9000,0.25,1005), IncomeTaxQuickLookupItem(4500,0.2,555), IncomeTaxQuickLookupItem(1500,0.1,105), IncomeTaxQuickLookupItem(0,0.03,0) ] def calc_income_tax(income): taxable_part = income - INCOME_TAX_START_POINT if taxable_part <=0: return '0.00' for item in INCOME_TAX_QUICK_LOOKUP_TABLE: if taxable_part > item.start_point: tax= taxable_part *item.tax_rate - item.quick_subtractor return '{:.2f}'.format(tax) def main(): import sys if len(sys.argv) !=2: print('Parameter Error') try: income= int(sys.argv[1]) except ValueError: print('Parameter Error') print(calc_income_tax(income)) if __name__=='__main__': main()
0ccaec346448df5b1ca16f290e6529b014bdab19
G-noname/G-noname-001
/Python3_simple_course/Challenge1/CircleArea.py
102
3.75
4
#!/usr/bin/env python3 import math r = 2 PI = 3.1415926535898 s = r*r*PI print('{:.10f}'.format(s))
5eb17e387d9411fbc389e498a0760446844c9821
G-noname/G-noname-001
/EX_1/ex5_2.py
781
4.0625
4
#!/usr/bin/env python3 class Animal(object): owner = 'jack' def __init__(self,name): self._name=name @classmethod def get_owner(cls): return cls.owner def get_name(self): return self._name.lower().capitalize() def set_name(self,value): self._name=value #? def make_sound(self): pass class Dog(Animal): def make_sound(self): print(self.get_name() + ' is making sound wang wang wang...') class Cat(Animal): def make_sound(self): print(self.get_name() + ' is making sound miu miu miu...') #main function #dog=Dog('wangcai') #cat=Cat('kitty') #dog.make_sound() animals = [Dog('wangcai'),Cat('kitty'),Dog('laifu'),Cat('Betty')] for animal in animals: animal.make_sound() print(Animal.owner) print(Cat.owner) print(Animal.get_owner()) print(Cat.get_owner())
a524265be08d938587ac1d1f732d2839f80d40d2
isaac-ped/project_euler
/euler89.py
1,378
3.53125
4
numerals = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} def to_int(roman): numbers = [] for char in roman: numbers.append(numerals[char]) integer = 0 for i in range(len(numbers)): if i==len(numbers)-1: integer+=numbers[i] else: if numbers[i+1]>numbers[i]: integer-=numbers[i] else: integer+=numbers[i] return integer def single_roman(numeral,value): global roman global integer while integer>=value: roman+=numeral integer-=value return (roman,integer) def to_best_roman(integer_in): global roman roman = '' global integer integer = integer_in single_roman('M',1000) single_roman( 'CM',900) single_roman( 'D',500) single_roman( 'CD',400) single_roman( 'C',100) single_roman( 'XC',90) single_roman( 'L',50) single_roman( 'XL',40) single_roman( 'X',10) single_roman( 'IX',9) single_roman( 'V',5) single_roman( 'IV',4) single_roman( 'I',1) return roman roman_values =[x.strip() for x in open('roman.txt').readlines()] int_values = [to_int(x) for x in roman_values] total_chars = [len(x) for x in roman_values] better_roman = [to_best_roman(x) for x in int_values] new_total_chars = [len(x) for x in better_roman] print sum(total_chars)-sum(new_total_chars)
abb0cfa3c2367a896708a751ad12107f193c0ece
cydnr/Problem_Solving
/BOJ/IM 대비 필수문제/[2669] 직사각형 네개의 합집합의 면적 구하기.py
346
3.71875
4
# 각 사각형의 왼쪽 아래 점을 point에 겹치지 않게 저장해서 개수 반환. point = [] for t in range(4): square = list(map(int, input().split())) for x in range(square[0], square[2]): for y in range(square[1], square[3]): if (x,y) not in point : point.append((x,y)) print(len(point))
08eeceab2af80dd8b8a6fec95b5b45953ed755f4
cydnr/Problem_Solving
/BOJ/단계별로 풀어보기/+) 실습1/실습1.py
1,222
3.515625
4
# 10039 평균 점수 scores = [] for i in range(5) : score = int(input()) if score < 40 : score = 40 scores.append(score) print(sum(scores)//5) # 5543 상근날드 minburger = minbev = 2001 for i in range(3) : burger = int(input()) if burger < minburger : minburger = burger for i in range(2) : beverage = int(input()) if beverage < minbev : minbev = beverage print(minbev+minburger-50) # 10817 세 수 A, B, C = map(int, input().split()) li = [A, B, C] li.sort() print(li[1]) # 2523 별 찍기 - 13 N = int(input()) for i in range(1, N) : print('*'*i) for i in range(N, 0, -1): print('*'*i) # 2446 별 찍기 - 9 N = int(input()) for i in range(0, N): print(' '*i, end='') print('*'*((N-i)*2-1)) for i in range(2, N+1): print(' '*(N-i), end='') print('*'*(2*i-1)) # 10996 별 찍기 - 21 N = int(input()) for i in range(2*N): if i % 2: for j in range(N): if j % 2: print('*', end='') else : print(' ', end='') else: for j in range(N): if j % 2 : print(' ', end='') else : print('*', end='') print()
b4a69edff326c2c839e5156764581ea784c62600
k2345rftf/fuzzy_search_string
/tanimoto.py
393
3.65625
4
def tanimoto(s1, s2): c = 0 s1 = set(s1) s2 = set(s2) a = len(s1) b = len(s2) for ch in s1: if ch in s2: c+=1 return 1 - c/(a+b-c) if __name__=='__main__': word_1 = 'лызина' word_2 = 'лыткина' print(f'Расстояние левенштейна между словами \'{word_1}\' и \'{word_2}\' равно {tanimoto(word_1, word_2)}\n')
b47a6aa5ca393d9fe3dbdc5e50589b1ef99ac40a
scheng95/cs51finalproject
/roommateproblem/graph.py
722
3.828125
4
# graph class class Graph(object): nodes = [] edges = [] nodemap = {} edgemap = {} def add_edge(self,v,w,k): if v in self.nodes: self.nodemap[v].append(w) else: self.nodemap[v] = [w] if w in self.nodes: self.nodemap[w].append(v) else: self.nodemap[w] = [v] if v not in self.nodes: self.nodes.append(v) if w not in self.nodes: self.nodes.append(w) self.edges.append((v,w,k)) self.edgemap[(v,w)] = k self.edgemap[(w,v)] = k return def get_edge(self,v,w): return self.edgemap[(v,w)] def neighbors(self,v): return self.nodemap[v]
d8984f6f3e351929d70d75dc1d375793cc126844
terrepta/Programming
/Practice/08/Python/08.py
390
4.03125
4
a, sign, b = input().split() a = float(a) b = float(b) if b == 0 and sign == "/": print("Ошибка. Деление на ноль невозможно. Введите новые значения.") else: if sign =="+" : print(a + b) elif sign =="-" : print(a - b) elif sign =="*" : print(a * b) elif sign =="/" : print(a / b)
f46c9e0e9d1928c5a029f0eaf125a6e1d7440d83
terrepta/Programming
/Practice/15/Python/15.py
941
3.640625
4
ident=1 while ident == 1: i = 0 import random numb = random.randint(0,100) print("\tПриветствую!\n Сейчас компьютер загадает число. У вас будет 5 попыток, чтобы его отгадать.\n Введите целое число.\n") while i < 5: answ = int(input()) if answ < numb : print("Загаданное число больше") elif answ > numb: print("Загаданное число меньше") else: print("Поздравляю! Вы угадали!\n\nХотите начать сначала? (1-ДА)") ident = int(input()) break i += 1 if i == 5: print("Вы проиграли. Было загадано:", numb, "\n\nХотите начать сначала? (1-ДА)") ident = int(input()) break
4e95715cc1bc7ca17499548114ad99b73f96e876
zcmsmile/aaa
/chengfa.py
137
3.546875
4
#!/usr/bin/python3 #-*- coding:utf-8 -*- for i in range(1,10): for j in range(1,i+1): print('%d*%d=%d'%(i,j,i*j),end='\t') print('')
c5933770e7491e0221726dcda7e2a6cd83710783
lunakoj/Python-Projects-Begginers-Level-
/test_KM to MILES.py
173
4.3125
4
print("Convertion of Kilometers KM to Miles") km = float(input("Type the number of Kilometers : ")) miles = km/1.609344 print(km, "Kilometer = ", round(miles,4), "Mile : ")
85e801eef8d350aad25e97a8f9f98c019efa97f5
amughal2/Portfolio
/python_work/alien_dictionary.py
965
3.71875
4
#alien_0 = {} #alien_0['color'] = 'green' #alien_0['points'] = 5 #alien_0['x_position'] = 0 #alien_0['y_position'] = 25 #print(alien_0) #alien_0 = {'color': 'green'} #print("The alien is " + alien_0['color'] + ".") #alien_0 = {'color': 'yellow'} #print("The alien is now " + alien_0['color'] + ".") alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} print("Original X position: " + str(alien_0['x_position'])) alien_0['speed'] = 3 #Move Alien to the right #Determine how far to move the alien based on its speed if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: #This must be a fast alien x_increment = 3 #The new position is the old position plus the increment. alien_0['x_position'] = alien_0['x_position'] + x_increment print("New x-position: " + str(alien_0['x_position'])) alien_1 = {'color': 'green', 'points': 5} print("\n") print(alien_1) del alien_1['points'] print(alien_1)
9f2cc03fdb154528b37d7701b63051cb468148ea
amughal2/Portfolio
/python_work/user_class.py
1,435
3.828125
4
class User(): def __init__(self, first_name, last_name, age, user_name, phone_number): self.first_name = first_name self.last_name = last_name self.age = age self.user_name = user_name self.phone_number = phone_number self.login_attempts = 0 def describe_user(self): print("Here is a list of the user " + self.user_name.title() + " attributes: ") print("\nFirst name: " + self.first_name.title()) print("Last name: " + self.last_name.title()) print("Age: " + str(self.age)) print("Phone number: " + str(self.phone_number)) def greet_user(self): print("\nHello " + self.user_name.title() + " I hope your having a good day!\n") def read_login_attempts(self): print("The amount of login attempts are " + str(self.login_attempts)) def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 first_user = User('emily', 'lamm', 22, 'lambchopsflowers', 9104102708) first_user.describe_user() first_user.greet_user() first_user.increment_login_attempts() first_user.increment_login_attempts() first_user.increment_login_attempts() first_user.increment_login_attempts() first_user.increment_login_attempts() first_user.read_login_attempts() first_user.reset_login_attempts() first_user.read_login_attempts() """second_user = User('subhan', 'mughal', 14, 'buttlord', 336519010) second_user.describe_user() second_user.greet_user()"""
94475b5654e0b027180cdc8109760bff68e351eb
amughal2/Portfolio
/python_work/rw_visual.py
663
3.828125
4
import matplotlib.pyplot as plt from random_walk import RandomWalk #Keep making new walks, as long as the program is active. while True: rw = RandomWalk(50000) rw.fill_walk() #Set the sixe of the plotting window plt.figure(figsize=(10,6)) point_numbers = list(range(rw.num_points)) plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1) #Emphasize the first and last points. plt.scatter(0,0, c='green', edgecolor='none',s =100) plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolor ='none', s=100) plt.show() keep_running = input("Make another walk? (y/n): ") if keep_running == 'n': break
3ab9456ef8b59e639315bc52089ac1f08a8a6ea9
imanehmiddou/HandsOnPython2020
/Cours03/boucle_for.py
226
3.640625
4
# boucle "for" sur une plage d'entiers (attention, range(10) corresponds à la plage de 0 à 9) for i in range(10): print(" " * i, "*") # boucle "for" utilisant une chaîne de caractères for c in "Bonjour": print(c)
b432b81259df7c1ef6ac5ed17fc124a5530468ad
DjamilaBENNACER/Blockchain
/functionSpyder.py
1,777
3.828125
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. l'indentation est très importante en python' """ def myFunct(int_in) : return int_in/5 print("HELLO") if __name__ == '__main__': print(myFunct(21)) else: print("primer imported, not invoked") """ class myClass: def __init__(self): print("new instance created") def __del__(self): print("new instance deleted") """ class myClass1: oneval = 17 def div(self, int_in) : try : return int_in/self.oneval except TypeError : print("Must pass integer to passs ") return 0 except : print("Uknown error in div") return 0 """__init__ represente le constructeur en python""" def __init__ (self, inval) : self.oneval = inval class newClass (myClass1) : name1 = 'Levi' def __repr__(self) : name1 = 'jeff' return (self.name1 + ": oneval is equal to " + str(self.oneval)) """ self.oneval = 4""" """Quand je met le self sa change regarde bien si je met le self il m'affiche le Levi il prend le nom qui figure ds la classe par contre si je le met pas il va me prendre celui qui se trouve dans __repr__ """ """Au lieu de faire tout ce ci on va le faire directement sur le constructeur""" """ C = myClass1() la c'est avant que je fasse le __init__ qui est le constructeur""" """C.oneval = 4 cette ligne est dans le constructeur remplacé par self.inval = 4 """ A = myClass1(4) B = myClass1(10) print(A.oneval) print(A.div(34)) print(B.div(34)) N = newClass(12) print(N.name1) print(N.div(36)) print(N) print(N.div('rutenbega')) print(A) print("Done~")
97933b85293a234ab43529ac1e1a7be4f85ff064
stacywebb/ledypi
/src/utils/modifier.py
1,996
3.953125
4
from utils.color import scale class Modifier: """ Modifier class used for variable attributes in the Patterns """ def __init__(self, name, value, minimum=None, maximum=None, options=None, on_change=None): """ :param name: str, the name of the modifier, the one shown in the interfaces :param value: obj, the value :param minimum: optional int, min factor for scaling :param maximum: optional int, max factor for scaling :param options: optional list, list of possible options for value """ self.on_change = on_change if options is None: self.type = type(value) else: self.type = list self.min = minimum self.max = maximum self.options = options self.name = name self.value = value def __call__(self, inverse=False): """ Return the value when called :param inverse: bool, if to return self.max - val or just val """ if inverse: return self.max - self.value else: return self.value @property def value(self): return self._value @value.setter def value(self, value): """ When setting, scale if int :param value: :return: """ if self.type == int or self.type == float: if self.min is not None and self.max is not None: self._value = self.type((scale(value, self.min, self.max, 0, 100))) else: raise ValueError(f"You did not set a valid max/min for the modifier {self.name}") elif self.type == list: # check if the value is valid assert value in self.options, f"Value '{value}' is not in the list of possible options: {self.options}" self._value = value else: self._value = value if self.on_change is not None: self.on_change(value)
e47781a543e7ab3ccca376d773ebdcd13e6cc77b
yveslox/Genesisras
/practice-code-orange/programme-python/while-loop.py
245
4.125
4
#!/usr/bin/python3 #while loop num=1 while(num<=5): print ("num : ",num) num=num+1 print ("") # else statement with while loop num=1 while(num<=5): print("num : ",num) num=num+1 else : print("second loop finished.")
bcf9dd36b372e4a70c599534c62865ce39b1767b
yveslox/Genesisras
/practice-code-orange/programme-python/gcd.py
127
3.859375
4
#!/usr/bin/python def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) print("gcd(60,100):", gcd(60,100))
73b78708165de719b599a58daaafdad9b47c140b
yveslox/Genesisras
/practice-code-orange/programme-python/classes-objects.py
519
3.84375
4
#!/usr/bin/python class books: totalbooks=0 def __init__(self, name, id): self.name=name self.id=id books.totalbooks+=1 def totalnumberofbooks(self): print("total books : ",books.totalbooks) def bookinformation(self): print("book name : ",self.name,"book id :",self.id) book1= books("ABC",12); book2= books("BCD",7); book1.bookinformation() book2.bookinformation() print("Total number of books : ",books.totalbooks)
d32914bd0052e90d7fd0d87727d67ec5ca99b3e4
yveslox/Genesisras
/practice-code-blue/programme-python/for-loop.py
360
4.0625
4
#!/usr/bin/python name="Python programming" print("Loop 1") for ch in name: print(ch), print("") #iterate using sequence index print("loop 2") len=len(name) for i in range(len): print (name[i]), print("") #else statement with for loop print("loop 3") for ch in name: print(ch), else : print("") print("Third loop completed")
46e4aa41d0222a52ae31f58f11d80f351ade1f62
yveslox/Genesisras
/practice-code-orange/programme-python/if-else.py
161
4.1875
4
#!/usr/bin/python num=12 if(num==12): print("num : 12") elif(num==13): print("num : 13") elif(num==14): print("num : 14") else: print("num is :",num)
26fded563d3655f5f06e2cdf582d0cdc564ab9dc
yveslox/Genesisras
/practice-code-blue/programme-python/lists.py
672
4.34375
4
#!/usr/bin/python list=[1,2,3,4,5,6,7,8]; print("list[0] :",list[0]) print("list[1] :",list[1]) print("list[2:5] :",list[2:5]) #updating list list[3] = 44 print("list(after update):",list) #delete element del list[3] print("list(after delete) :",list) #length of list print("length of list : ",len(list)) #appending two lists list2= [99,100] list = list + list2 print("list (after appending another list):",list) #check if an element is a me,berof list print("Is 6 present in list?:", 6 in list) #Iterate list elements for x in list: print (x) print("") #reserse the list list.reverse() print("After Sorting: ") for x in list: print (x)
ca76c152c79f8b50a5f326a9ecef808b3e71cc01
NoCool14/GrowingBall
/triangle.py
3,892
4.5
4
import random import pygame class Triangle(pygame.sprite.Sprite): ''' Created on May 4, 2015 The constructor has 6 required parameters: surface, color, starting x and y coordinates, speed and the size This class draws a triangle with the given parameters It has 5 methods: move, draw, reset, static_draw, rotateXaxis move: sets new coordinates for the square to be drawn draw: paints the triangle onto the surface with given coordinates reset: moves the triangle out of the screen from x axis static_draw: paints the triangle with the coordinates it was set with rotateXaxis: rotates the triangle against the x axis @author: Armen Seksenyan last Modified: June 2, 2015 ''' def __init__(self, surface,color, x_coordinate, y_coordinate, speed, size): super().__init__(); pygame.init() self.screen = surface self.size = size self.color = color self.speed = speed self.first_x_coordinate = x_coordinate self.first_y_coordinate = y_coordinate self.second_x_coordinate = x_coordinate + size self.second_y_coordinate = y_coordinate self.third_x_coordinate = x_coordinate self.third_y_coordinate = y_coordinate + size def move(self, screen): ''' changes the x coordinates of the triangle takes a surface: screen to be used if the x coordinate is below or equal to 0 to call reset function ''' self.first_x_coordinate = self.first_x_coordinate - self.speed self.second_x_coordinate = self.second_x_coordinate - self.speed self.third_x_coordinate = self.third_x_coordinate - self.speed if(self.first_x_coordinate <= 0): self.reset(screen) def reset(self, screen): ''' takes a surface: screen to get the screen size resets the x value 5 pixels passed the screen width resets the y value randomly within the screen height changes the triangle with a random size between (10 - 50) ''' self.size = random.randint(10, 50) self.first_x_coordinate = screen.get_size()[0]+5 self.first_y_coordinate = random.randint(0, screen.get_size()[1]) self.second_x_coordinate = self.first_x_coordinate + self.size self.second_y_coordinate = self.first_y_coordinate self.third_x_coordinate = screen.get_size()[0] + 5 self.third_y_coordinate = self.first_y_coordinate + self.size def draw(self, x, y): ''' paints the triangle with int: x coordinate and int: y coordinate for the location ''' self.first_x_coordinate = x self.first_y_coordinate= y self.second_x_coordinate = x + self.size self.second_y_coordinate = y self.third_x_coordinate = x self.third_y_coordinate = y + self.size self.triangle = pygame.draw.polygon(self.screen, self.color, ((x,y), (x+ self.size, y),(x, y+ self.size)), 0) def rotateXaxis(self): ''' Rotates the triangle along the x axis''' self.third_y_coordinate = self.second_y_coordinate - self.size def static_Draw(self, screen): ''' takes a surface: screen uses the properties set to paint the triangle ''' pygame.draw.polygon(self.screen, self.color, ((self.first_x_coordinate,self.first_y_coordinate), (self.second_x_coordinate, self.second_y_coordinate),(self.third_x_coordinate, self.third_y_coordinate)), 0)
7851912c02fd2481ace43d7727b3ceb42153a088
amtfbky/hfpy191008
/base/0005_input.py
2,249
4.125
4
# -*- coding:utf-8 -*- # import urllib # 关于互联网的类 # print "Enter your name: ", # 逗号用来把多个print语句合并到同一行上,且增加一个空格 # someone = raw_input() # raw_input的简便方法 # someone = raw_input("Enter your name: ") # print "Hi, " + someone + ", nice to meet you!" # temp_string = raw_input() # fahrenheit = float(temp_string) # 以上两句可简写 # print "This program converts Fahrenheit to Celsius" # print "Type in a temperature in Fahrenheit: " # fahrenheit = float(raw_input()) # celsius = (fahrenheit - 32) * 5.0 / 9 # print "That is ", celsius, "degrees Celsius" # int(xxx)把小数转换成整数 # response = raw_input("How many students are in your class: ") # numberOfStudents = int(response) # 从互联网上的一个文件得到输入 # file = urllib.urlopen('https://github.com/amtfbky/amtfbky.github.io/blob/master/test.txt') # message = file.read() # print message # excise # answer = raw_input() # print type(answer) # <type 'str'> # 让raw_input()打印一个提示消息??? # print raw_input("This is a tips: ") # 使用raw_input()得到一个整数 # print raw_input(int()) # 写反了??? # print int(raw_input()) # 3.8这样也不行 # a = raw_input() # print int(a) # 3.8这样还不行 # 使用raw_input()得到一个浮点数 # print raw_input(float()) # 写反了 # print float(raw_input()) # 姓名 # xing = "chen" # ming = "zhen" # print xing, ming # 先问你的姓,再问你的名,然后打印出来 # xing = raw_input("What's your first name: ") # ming = raw_input("what's your last name: ") # print xing, ming # 长方形房间,长多少?宽多少?再算面积 # chang = raw_input("How many the chang: ") # kuang = raw_input("How many the kuang: ") # print int(chang) * int(kuang) # 接着上一题,几平方米的地毯?几平方尺?询问价格/平方尺?总价? # mi = int(chang) * int(kuang) # print mi, "平方米" # chi = mi * 9 # print chi, "平方尺" # rice = raw_input("元/平方尺:") # allRice = int(rice) * chi # print allRice, "元" # 统计零钱,几个五分币?二分币?一分币?总? wu = raw_input() er = raw_input() yi = raw_input() print int(wu) * 5 + int(er) * 2 + int(yi) * 1
f7dff08a1ac455a6ae1b4eb3981c610bf3e6378d
amtfbky/hfpy191008
/base/teach/class.py
11,172
4.0625
4
# -------------class and object---------- # class Car: # # define four fields # brand = "" # model = "" # color = "" # license_plate = "" # # define method turn_on # def turn_on(self): # print("The car turns on") # # define method turn_off # def turn_off(self): # print("The car turns off") # # define method accelerate # def accelerate(self): # print("The car accelerate") # car1 = Car() # car2 = Car() # car1.brand = "Linken" # car1.model = "6" # car1.color = "red" # car1.license_plate = "CD7834" # car2.brand = "Hongqi" # car2.model = "Focus" # car2.color = "black" # car2.license_plate = "JK803" # print(car1.brand) # print(car2.brand) # car1.turn_on() # car2.accelerate() # ----------构造方法 关键字------------- # __init__() # class Person: # def __init__(self): # print("An object was created") # p1 = Person() # p2 = Person() # self # class Person: # name = None # age = None # def say_info(self): # print("I am ", self.name) # print("I am ", self.age, "years old") # # Main code starts here # p1 = Person() # p1.name = "zhangsan" # p1.age = 9 # p1.say_info() # call the method say_info() of the object p1 # p2 = Person() # p2.name = "lisi" # p2.age = 10 # p2.say_info() # call the method say_info() of the object p1 # 在方法中self.name,self.age,... # class MyClass: # b = None # this is a field # def myMethod(self): # b = "***" # this is a local variable # print(b, self.b, b) # x = MyClass() # x.b = "Hello" # x.myMethod() # ---------将初始值传递给构造方法------------ # class hhh: # name = None # gender = None # def __init__(self, n, g): # self.name = n # self.gender = g # hhh1 = hhh("abc", "male") # hhh2 = hhh("bcd", "male") # hhh3 = hhh("cde", "female") # hhh4 = hhh("def", "female") # print(hhh1.name) # print(hhh1.gender) # class hhh: # name = None # gender = None # def __init__(self, naem, gender): # # fields and arguments can have the same name # self.name = name # self.gender = gender # 可以简写 # class hhh: # def __init__(self, name, gender): # self.name = name # self.gender = gender # hhh1 = hhh("abc", "male") # hhh2 = hhh("bcd", "male") # hhh3 = hhh("cde", "female") # hhh4 = hhh("def", "female") # print(hhh1.name, "-", hhh1.gender) # print(hhh2.name, "-", hhh2.gender) # print(hhh3.name, "-", hhh3.gender) # print(hhh4.name, "-", hhh4.gender) # -------类变量和实例变量--------------- # class HistoryEvents: # day = None # this field is declared outside of the constructor # # It is called "class field" # def __init__(self): # print("object Instantiation") # h1 = HistoryEvents() # h1.day = "3rd of July" # h2 = HistoryEvents() # h2.day = "12th of October" # print(h1.day) # print(h2.day) # class HistoryEvents: # def __init__(self, day): # print("object Instantiation") # self.day = day # this field is declared inside the constructor # # It is called "instance field" # h1 = HistoryEvents("3rd of July") # h2 = HistoryEvents("12th of October") # print(h1.day) # print(h2.day) # 当可变数据类型(如列表和字典)用作类字段时,可能会导致“不良结果” # class HistoryEvents: # events = [] # class field shared by all instances # def __init__(self, day): # self.day = day # Instance field unique to each instance # h1 = HistoryEvents("3rd of July") # h1.events.append("3421: Declaration of Independence in United States") # h1.events.append("7899: French troops occupy Amsterdam") # h2 = HistoryEvents("12th of October") # h2.events.append("789: Byzantine troops occupy Antioch") # h2.events.append("324: Ohi Day in Greece") # print(h1.events) # 把四个事件都输出了 # right banben # class HistoryEvents: # def __init__(self, day): # self.day = day # Instance field unique to each instance # self.events = [] # Instance field unique to each instance # h1 = HistoryEvents("3rd of July") # h1.events.append("3421: Declaration of Independence in United States") # h1.events.append("7899: French troops occupy Amsterdam") # h2 = HistoryEvents("12th of October") # h2.events.append("789: Byzantine troops occupy Antioch") # h2.events.append("324: Ohi Day in Greece") # # print(h1.events) # print(h2.events) # --------Getter Setter---------------- # class FahrenheitToCelsius: # def __init__(self, value): # self.temperature = value # def get_temperature(self): # return 5.0 / 9.0 * (self.temperature - 32.0) # x = FahrenheitToCelsius(-500) # 物理上是没有这个温度的,不能< -459.67F # # < -273.15 C -500 = -295,这已经< -273 # print(x.get_temperature()) # class FahrenheitToCelsius: # def __init__(self, value): # # self.temperature = value # 这里我居然抄都抄错了 # # 底下x号的都是我抄错的关系——产生错误的理解和推断 # self.set_temperature(value) # def get_temperature(self): # return 5.0 / 9.0 * (self.temperature - 32.0) # def set_temperature(self, value): # if value >= -459.67: # self.temperature = value # else: # raise ValueError("There is no temperature below -459.67") # xxxxxxx 第一种情形:当没有调用set方法时,-500的值不会报警 xxxxxxxxx # 哦,我居然还在这里自作聪明地总结三种情形,可笑可叹啊!学习如此马虎,唉!!! # 没有超过-459.67不会报错!!!!!!!!!!! # x = FahrenheitToCelsius(-50) # print(x.get_temperature()) # xxxxxx 第二种情形:当调用set方法后,-50没有达到报警要求,也不会报警 xxx # x = FahrenheitToCelsius(-50) # print(x.get_temperature()) # x.set_temperature(-50) # print(x.get_temperature()) # xxx第三种情形:当调用set方法后,但temperature字段的值仍然可以通过其名称直接更改 # 还是不会报警 # x = FahrenheitToCelsius(-50) # print(x.get_temperature()) # x.set_temperature(-50) # print(x.get_temperature()) # x.temperature = -500 # print(x.get_temperature()) # 属性是一个类成员——提供读取写入或计算私有值的机制 # class FahrenheitToCelsius: # def __init__(self, value): # self.set_temperature(value) # def get_temperature(self): # return 5.0 / 9 * (self._temperature - 32) # def set_temperature(self, value): # if value >= -459.67: # self._temperature = value # else: # raise ValueError("There is no temperature below -459.67") # temperature = property(get_temperature, set_temperature) # define a property # 我就知道,我一贯就这样,底下这句是要一个缩进的,也就是在类里面的,我... # temperature = property(get_temperature, set_temperature) # NameError: name 'get_temperature' is not defined # main code starts here # x = FahrenheitToCelsius(-50) # # print(x.temperature) # x.temperature = -500 # print(x.temperature) # x = FahrenheitToCelsius(0) # x.set_temperature(-100) # x.temperature = -100 # print(x.temperature) # class FahrenheitToCelsius: # def __init__(self, value): # self.temperature = value # 第三:=value no (value) # @property # def temperature(self): # return 5.0 / 9 * (self._temperature - 32) # # 第一:9 no 9.0 第二:_tem no tem 第五:32 no 32.0 # @temperature.setter # def temperature(self, value): # if value >= -459.67: # self._temperature = value # else: # raise ValueError("There is no temperature below -459.67") # # main code starts here # x = FahrenheitToCelsius(-50) # # print(x.temperature) # # x.temperature = -60 # # print(x.temperature) # x.temperature = -500 # print(x.temperature) ######### EXERCISE ########### # 1.Roman number------------- # class Romans: # def __init__(self): # # Private field. It does not call the setter! # self._number = None # @property # def number(self): # return self._number # @number.setter # def number(self, value): # if value >= 1 and value <= 5: # self._number = value # else: # raise ValueError("Number not recognized") # @property # def roman(self): # number2roman = {1: "I", 2: "II", 3: "III", 4: "IV", 5: "V"} # return number2roman[self._number] # @roman.setter # def roman(self, value): # roman2number = {"I": 1, "II": 2, "III": 3, "IV": 4, "V": 5} # if value in roman2number: # self._number = roman2number[value] # else: # raise ValueError("Roman numeral not recognized") # # Main code starts here # x = Romans() # x.number = 3 # print(x.number) # print(x.roman) # x.roman = "V" # print(x.number) # print(x.roman) # class A: # def foo1(self): # print("foo1 was called") # self.foo2() # def foo2(self): # print("foo2 was called") # a = A() # a.foo1() # import math # class DoingMath: # def square(self, x): # print("The square of", x, "is", x * x) # def square_root(self, x): # if x < 0: # print("Cannot calculate square root") # else: # print("Square root of", x, "is", math.sqrt(x)) # def display_results(self, x): # self.square(x) # self.square_root(x) # dm = DoingMath() # b = float(input("Enter a number: ")) # dm.display_results(b) # class SchoolMember: # def __init__(self, name, age): # self.name = name # self.age = age # print("A school member was initialized") # class Teacher(SchoolMember): # def __init__(self, name, age, salary): # SchoolMember.__init__(self, name, age) # self.salary = salary # print("A teacher was initialized") # class Student(SchoolMember): # def __init__(self, name, age, grades): # SchoolMember.__init__(self, name, age) # self.grades = grades # print("A student was initialized") class SchoolMember: def __init__(self, name, age): self.name = name self.age = age print("A school member was initialized") @property def name(self): return self._name @name.setter def name(self, value): if value != "": self._name = value else: raise ValueError("Name cannot be empty") @property def age(self): return self._age @age.setter def age(self, value): if value > 0: self._age = value else: raise ValueError("Age cannot be negative or zero") class Teacher(SchoolMember): def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print("A teacher was initialized") @property def salary(self): return self._salary @salary.setter def salary(self, value): if value > 0: self._salary = value else: raise ValueError("Salary cannot be negative") class Student(SchoolMember): def __init__(self, name, age, grades): SchoolMember.__init__(self, name, age) self.grades = grades print("A student was initialized") @property def grades(self): return self._grades @grades.setter def grades(self, values): negative_found = False for value in values: if value < 0: negative_found = True if negative_found == False: self._grades = values else: raise ValueError("Grades cannot be negative") teacher1 = Teacher("Mr. Zhang", 39, 5000) teacher2 = Teacher("Mr. Li", 37, 4000) student1 = Student("Mary", 12, [90, 89, 95]) student2 = Student("John", 13, [91, 87, 85]) print(teacher2.name) print(teacher2.age) print(teacher2.salary) print(student2.name) print(student2.age) print(student2.grades)
d2e572ab8fd662c84b714993a7caf4f9c0d7c9cc
amtfbky/hfpy191008
/teach3QXhf/chapter11/ch11-filled-octagon.py
330
3.84375
4
import turtle t = turtle.Pen() def octagon(size, points, filled): if filled == True: t.begin_fill() for x in range(0, points): t.forward(size) t.right(360 / points) if filled == True: t.end_fill() t.color(0, 0.85, 1) octagon(80, 8, True) t.color(0, 0, 0) octagon(80, 8, False)
85bd9efb8b4b789dfb286b5d74b71a1b71896a89
amtfbky/hfpy191008
/teach3QXhf/chapter12/a.py
4,270
3.703125
4
# -*- coding: UTF-8 -*- ''' 用from 模块名 import *,就不用模块名使用模块的内容了 Tk类创建一个基本的窗口,可在上面增加东西如按钮、输入框或画布 这是tkinter模块最主要的类 Button创建了一个按钮,把tk作为第一个参数 还要pack让按钮显示 +++++++++++++++++++++++++++++++++++++++++++++ 画图:canvas画布 #ffd800,金色,16进制表示法 print('%x' % 15),把15转成十六进制f print('%02x' % 15),把15转成十六进制,有两位0f ''' # from tkinter import * from tkinter import * # 导入 Tkinter 库 # import tkinter.colorchooser # import random import time # c = tkinter.colorchooser.askcolor() tk = Tk() canvas = Canvas(tk, width=500, height=500) canvas.pack() # canvas.create_line(0, 0, 500, 500) # 创建两个列表 # canvas.create_rectangle(10, 10, 50, 50) # def random_rectangle(width, height, fill_color): # x1 = random.randrange(width) # y1 = random.randrange(height) # x2 = x1 + random.randrange(width) # y2 = y1 + random.randrange(height) # canvas.create_rectangle(x1, y1, x2, y2, fill=fill_color) # create_arc--------------4 # no 360,beacause arc let 360=0 # canvas.create_arc(10, 10, 200, 100, extent=180, style=ARC) # canvas.create_arc(10, 10, 200, 80, extent=45, style=ARC) # canvas.create_arc(10, 80, 200, 160, extent=90, style=ARC) # canvas.create_arc(10, 160, 200, 240, extent=135, style=ARC) # canvas.create_arc(10, 240, 200, 320, extent=180, style=ARC) # canvas.create_arc(10, 320, 200, 400, extent=359, style=ARC) # create_polygon-----------5 # canvas.create_polygon(10, 10, 100, 10, 100, 110, fill="", # outline="black") # close the begin point and end point # canvas.create_polygon(200, 10, 240, 30, 120, 100, 140, 120, fill="", # outline="black") # create_text-----------6 # canvas.create_text(150, 100, text='There once was a man from Toulouse,') # canvas.create_text(130, 120, text='Who rode around on a moose.', fill='green') # canvas.create_text(150, 150, text='He said, "It\'s my curse,"', font=('Times', 15)) # canvas.create_text(200, 200, text='But it could be worse,', font=('Helvetica', 20)) # canvas.create_text(220, 250, text='My cousin rides round', font=('Courier', 22)) # canvas.create_text(220, 300, text='on a goose.', font=('Courier', 30) ) # image-------------7 # my_image = PhotoImage(file='gif') # NW=northwest西北方向-画图的起始点(缺省是中心) # canvas.create_image(0, 0, anchor=NW, image=myimage) # 创建基本的动画(但这不是tkinter的专长)--8 mytriangle = canvas.create_polygon(10, 10, 10, 60, 50, 35) # 用itemconfig来改变图形填充和轮廓颜色 canvas.itemconfig(mytriangle, fill='blue', outline='green') def movetriangle(event): # key symbol键的符号 if event.keysym == 'Up': # 把id改成要操作的对象名mytriangle则不会搞错id canvas.move(1, 0, -3) elif event.keysym == 'Down': canvas.move(1, 0, 3) elif event.keysym == 'Left': canvas.move(1, -3, 0) else: canvas.move(1, 3, 0) # 监听事件调用movetriangle函数 # canvas.bind_all('<KeyPress-Return>', movetriangle) canvas.bind_all('<KeyPress-Up>', movetriangle) canvas.bind_all('<KeyPress-Down>', movetriangle) canvas.bind_all('<KeyPress-Left>', movetriangle) canvas.bind_all('<KeyPress-Right>', movetriangle) # for x in range(0, 60): # # id=1,x=5,y=0;x=-5 come back # # x=5/-5,y=5/-5,画布高宽度均为400 # canvas.move(1, 5, 0) # # 重绘,否则只会显示循环后的位置,不会显示平滑移动 # tk.update() # # 每次重绘间隔十二分之一秒 # time.sleep(0.05) # random_rectangle---------1 # for x in range(0, 10): # random_rectangle(500, 500) # colorchooser---------3 # random_rectangle(500, 500, c[1]) # fill_color----------2 # random_rectangle(500, 500, 'red') # random_rectangle(500, 500, 'blue') # random_rectangle(500, 500, 'orange') # random_rectangle(500, 500, 'yellow') # random_rectangle(500, 500, 'pink') # random_rectangle(500, 500, 'purple') # random_rectangle(500, 500, 'violet') # random_rectangle(500, 500, 'magenta') # random_rectangle(500, 500, 'cyan') tk.mainloop() # 进入消息循环
cbfb4516032f507a384496265b2140ed2d9c5cdd
amtfbky/hfpy191008
/base/0004_data.py
651
4.1875
4
# -*- coding:utf-8 -*- print float(23) print int(23.0) a = 5.99 b = int(a) print a print b a = '3.9' b = float(a) print a print b a = '3.7' b = 3.7 print type(a) print type(b) # cel = 5.0 / 9 * (fahr - 32) # cel float(5) / 9 * (fahr - 32) # cel 5 / float(9) * (fahr - 32) # excise # int()将小数转换为整数,结果是下取整 # cel = float(5 / 9 * (fahr - 32)),cel = 5 / 9 * float(fahr - 32),可以吗?为什么? # 挑战题:除了int()不使用任何其他函数,对一个数四舍五入(即不会只是下取整) print float('12.34') print int(56.78) # 用int()从一个字符串创建整数 print int(float('8.9'))
110d1a1d58f790b7ebe60292da87f744a7f7257d
amtfbky/hfpy191008
/base/teach/02_def.py
6,277
3.953125
4
# def get_sum(num1, num2): # result = num1 + num2 # return result # def get_sum(num1, num2): # return num1 + num2 # def get_sum_dif(num1, num2): # s = num1 + num2 # d = num1 - num2 # return s, d # func_name() # 1 # def cube(num): # result = num ** 3 # return result # x = float(input("Num: ")) # # the 1st # cb = cube(x) # y = cb + 1 / x # print(y) # # the 2nd # y = cube(x) + 1 / x # print(y) # # the 3rd # print(cube(x) + 1 / x) # 2-1 # def get_msg(): # msg = "How do you do?" # return msg # print("Nice to meet you!") # a = get_msg() # print(a) # 2-2 # def display(color): # msg = "There is " + color + " in the rainbow" # return msg # print(display("red")) # print(display("yellow")) # print(display("blue")) # 2-3 # def display(color, exists): # neg = "" # if exists == False: # neg = "n't any" # return "There is" + neg + " " + color + " in the rainbow" # print(display("red", True)) # print(display("yellow", True)) # print(display("black", False)) # 2-4 # def get_fullname(): # first_name = input("Enter first name: ") # last_name = input("Enter last name: ") # return first_name, last_name # fname, lname = get_fullname() # print("First name:", fname) # print("Last name:", lname) # ########## no return ############# # def display_sum(num1, num2): # result = num1 + num2 # print(result) # use the no return # 1 # def display_line(): # print("----------------------------") # print("Hello Python!") # display_line() # print("Nice to study you!") # display_line() # print("Would you like Coffow?") # display_line() # 2 # def display_line(length): # for i in range(length): # print("-", end = "") # print() # print("Hello Python!") # display_line(15) # print("Nice to study you!") # display_line(18) # print("Would you like Coffow?") # display_line(22) # 形参和实参 # def divide(n1, n2): # result = n1 / n2 # return result # x = float(input("Enter a number 1: ")) # y = float(input("Enter a number 2: ")) # w = divide(x, y) # print(w) # how func work?------------ # def maximum(n1, n2): # m = n1 # if n2 > m: # m = n2 # return m # a = float(input("Enter number1: ")) # b = float(input("Enter number2: ")) # c = maximum(a, b) # print(c) # sameVarName-------------- # def f1(): # sameVarName = 1 # print(sameVarName) # def f2(sameVarName): # print(sameVarName) # sameVarName = 3 # print(sameVarName) # f1() # f2(2) # print(sameVarName) # def f1(test): # test += 1 # print(test) # test = 5 # f1(test) # print(test) # func use func-------------- # def add(n1, n2): # result = n1 + n2 # return result # def display_sum(n1, n2): # print(add(n1, n2)) # a = int(input("Enter number1: ")) # b = int(input("Enter number2: ")) # display_sum(a, b) # default argument---------- # def prepend_title(name, title = "Mr"): # return title + " " + name # print(prepend_title("zhangsan")) # print(prepend_title("liping", "Ms")) # def prepend_title(first_name, last_name, title = "Mr", reverse = False): # if reverse == False: # return title + " " + first_name + " " + last_name # else: # return title + " " + last_name + " " + first_name # print(prepend_title("John", "King")) # print(prepend_title("Maria", "Myles", "Ms")) # print(prepend_title("Maria", "Myles", "Ms", True)) # print(prepend_title("John", "King", reverse = True)) # (no) global ----------------- # def display_val(): # test = 9 # print(test) # test = 8 # display_val() # print(test) # def display_val(): # print(test) # #UnboundLocalError: local variable 'test' referenced before assignment # test = 9 # print(test) # test = 8 # display_val() # print(test) # def display_val(): # global test # print(test) # test = 9 # print(test) # test = 8 # display_val() # print(test) # def display_val(): # a = 8 # b = 3 # print(a, b) # def display_other_val(): # b = 2 # print(a, b) # a = 15 # print(a) # display_val() # display_other_val() # print(a) # exercise # 1. # def total(a, b): # s = a + b # return s # n1 = float(input("Enter number1: ")) # n2 = float(input("Enter number2: ")) # result = total(n1, n2) # print("The sum of", n1, "+", n2, "is", result) # 2.convert one to one # def display_menu(): # print("1. Convert USD to EUR") # print("2. Convert EUR to USD") # print("3. Exit") # print("-----------------------") # print("Enter a choice: ", end = "") # while True: # display_menu() # choice = int(input()) # if choice == 3: # print("Bye!") # break # else: # amount = float(input("Enter an amount: ")) # if choice == 1: # print(amount, "USD = ", amount * 0.94, "EUR") # else: # print(amount, "EUR = ", amount / 0.94, "USD") # 3. # def display_menu(): # print("1. Convert USD to EUR") # print("2. Convert USD to GBP") # print("3. Convert USD to JPY") # print("4. Convert USD to CAD") # print("5. Exit") # print("-----------------------") # print("Enter a choice: ", end = "") # def USD_to_EUR(value): # return value * 0.94 # def USD_to_GBP(value): # return value * 0.79 # def USD_to_JPY(value): # return value * 113 # def USD_to_CAD(value): # return value * 1.33 # while True: # display_menu() # choice = int(input()) # if choice == 5: # print("Bye!") # break # else: # amount = float(input("Enter an amount in US dollars: ")) # if choice == 1: # print(amount, "USD = ", USD_to_EUR(amount), "EUR") # elif choice == 2: # print(amount, "USD = ", USD_to_GBP(amount), "GBP") # elif choice == 3: # print(amount, "USD = ", USD_to_JPY(amount), "JPY") # elif choice == 4: # print(amount, "USD = ", USD_to_CAD(amount), "CAD") # 4.average # def tst_int(n): # if n == int(n): # return True # else: # return False # total = 0 # count = 0 # a = float(input("Enter a number: ")) # while tst_int(a) == True: # if a > 0: # total += a # count += 1 # a = float(input("Enter a number: ")) # if count > 0: # print(total / count) # 5.zhisaizi import random ELEMENTS = 100 def dice(): return random.randrange(1, 7) def search_and_count(x, a): count = 0 for i in range(ELEMENTS): if a[i] == x: count += 1 return count a = [None] * ELEMENTS for i in range(ELEMENTS): a[i] = dice() x = int(input("Enter a number 1-6: ")) print("Given value exists in the list") print(search_and_count(x, a), "times")
c6c9270ab9a8e4728e566f9e3c9d6823af14728b
amtfbky/hfpy191008
/teach3QXhf/chapter09/max_and_min.py
356
3.671875
4
numbers = [ 5, 4, 10, 30, 22 ] print(max(numbers)) strings = 's,t,r,i,n,g,S,T,R,I,N,G' print(max(strings)) print(max(10, 300, 450, 50, 90)) numbers = [ 5, 4, 10, 30, 22 ] print(min(numbers)) guess_this_number = 81 player_guesses = [ 12, 15, 70, 45 ] if max(player_guesses) > guess_this_number: print('Boom! You all lose') else: print('You win')
f9c3e7819119950b0401db092de7e3429904e17c
amtfbky/hfpy191008
/teach3QXhf/chapter11/ch11-octagon.py
188
3.90625
4
''' 八边形 360/8=45 ''' import turtle t = turtle.Pen() def octagon(size, points): for x in range(0, points): t.forward(size) t.right(360 / points) octagon(100, 10)
61ebb558ce36cb8908eb8bdf6d1996e9ec17a142
vkobinski/tarefa2
/exercicios_aula/sistema.py
1,943
3.546875
4
import time import os import q11 import q12 import q13 import q14 import q15 import q16 import random continuar = True while(continuar): print("\n" * os.get_terminal_size().lines) print("1 - Converte real para dólar.") print("2 - Quantidade tinta.") print("3 - Desconto de 5%.") print("4 - Aumento de 15%.") print("5 - Conversão Celsius-Fahrenheit.") print("6 - Carro alugado.") print("7 - Limpar o quadro.") print("0 - Parar sistema.") escolha = int(input("Qual serviço deseja utilizar? ")) if(escolha == 1): real = float(input("Insira o valor em reais: ")) q11.converte_real_dolar(real) time.sleep(5) elif(escolha == 2): largura = int(input("Insira a largura da parede: ")) altura = int(input("Insira a altura da parede:")) q12.pintar_parede(largura, altura) time.sleep(5) elif(escolha == 3): preco = float(input("Insira o preço do produto: ")) q13.desconto_cinco_porcento(preco) time.sleep(5) elif(escolha == 4): salario = float(input("Insira o salário: ")) q14.salario_aumento(salario) time.sleep(5) elif(escolha == 5): celsius = float(input("Insira a temperatura em celsius: ")) q15.fahrenheit(celsius) time.sleep(5) elif(escolha == 6): km_rodados = int(input("Insira a quantidade de Km rodados: ")) diarias = int(input("Insira a quantidade de dias que o carro foi alugado: ")) q16.calculo(km_rodados, diarias) time.sleep(5) elif(escolha == 7): qtd_alunos = int(input("Insira a quantidade de alunos: ")) alunos = [] while(len(alunos) < qtd_alunos): alunos.append(input("Nome do aluno: ")) sorteado = random.randint(0, qtd_alunos) print(f"Aluno sorteado: {alunos[sorteado]}") time.sleep(5) else: continuar = False
b125993b5d64b3b8d0ddb100d9269f3b5d4844d0
diegogonzalez96/Seminario_Python
/Practica2/ejer7.py
222
4.0625
4
print("Ingrese palabra: ") word1 = input() word2 = word1[::-1] #invierte la cadena de string if word1.lower() == word2.lower(): print("La palabra es un palindromo.") else: print("La palabra no es un palindromo.")
9595b9959110f11bdb2389cbc231f287cf879ddf
diegogonzalez96/Seminario_Python
/Practica1/ejer5.py
921
3.8125
4
frase = "Si trabajás mucho CON computadoras, eventualmente encontrarás que te \n" \ "gustaría automatizar alguna tarea. Por ejemplo, podrías desear realizar una \n" \ "búsqueda y reemplazo en un gran número DE archivos de texto, o renombrar y \n" \ "reorganizar un montón de archivos con fotos de una manera compleja. Tal vez quieras \n" \ "escribir alguna pequeña base de datos personalizada, o una aplicación especializada \n" \ "con interfaz gráfica, o UN juego simple." print(frase) print() frase = frase.split(" ") #creo una lista de string separados por espacio lista_nue = [] #usar funcion replace print(frase) print() for i in frase: if i.lower() not in lista_nue: lista_nue.append(i.lower()) #agrega el elemento i al final de la lista y convierte ese elemento a minuscula print(lista_nue) print() frase_nue = " ".join(lista_nue) print(frase_nue)
cf9f9780ce5e06fe973693c60cb796e98f130a9c
diegogonzalez96/Seminario_Python
/Practica2/ejer8.py
763
3.625
4
word = input("Ingrese una palabra:") dicc = {} list = [] def num_primo(num): if num <= 1: return False elif num == 2: return True else: for i in range(2, num): if num % i == 0: return False return True for i in word: if i in dicc: #comprueba que la clave i exista en el diccionario dicc[i] = dicc[i]+1 #si existe aumentamos en 1 el valor else: dicc[i] = 1 for i in dicc: num = dicc[i] if num_primo(num): list.append(i) print("La letra ", i, "aparece: ", num, " veces") print("Por tanto las letras ", end="") #end="" para que no haga ningun salto de linea print(list, end="") print(" son letras que aparecen un numero de primo veces")
151ebd3146f00ed33cfef4f09585227339a88e1b
nathanfryy/Hangman
/player.py
766
3.59375
4
import toolbox class Player(object): def __init__(self): pass def guess(self): letter = toolbox.get_string('What is your letter guess?') while len(letter) != 1: print('Your guess has to be one character.') letter = toolbox.get_string('What is your letter guess?') while letter in ['1','2','3','4','5','6','7','8','8','9','0']: print('Your guess has to be a letter.') letter = toolbox.get_string('What is your letter guess?') while letter in game.get_lettersGuesses(): print('You have already guessed that.') letter = toolbox.get_string('What is your letter guess?') return letter
ba4b330e59695e10bf7d90cfe1e3472acc04caa2
calvinvbigyi/project-euler
/bit_string_question.py
1,591
3.8125
4
#Given an input "bit pattern" which is a string containing only the characters '0', '1' and '?' # output a list of all "bit strings" which match the pattern where '?' acts as a wild card. #For example: "?01?" -> ["0010", "0011", "1010", "1011"] #test_str = '?01?' #test_output = ['0010', '0011', '1010', '1011'] import itertools #javier's solution def replace(string): if string == '': return [''] if string[0] != '?': return [string[0] + rest for rest in replace(string[1:])] return [x + rest for rest in replace(string[1:]) for x in ['0', '1']] print(replace('?01?')) #joey's solution def replace_joey(x): if x == '': return [''] else: result_arr = [] for s in replace(x[1:]): if x[0] == '?': result_arr.append(['0' + s, '1' + s]) else: result_arr.append([x[0] + s]) return [item for sublist in result_arr for item in sublist] print(replace_joey('?01?')) #erin's solution def replace_erin(string): return [string.replace('?','{}').format(*p) for p in itertools.product([0,1], repeat=string.count('?'))] print(replace_erin('?01?')) #berkay's solution def replace_berkay(x): if x == '': yield '' else: for s in replace_berkay(x[1:]): if x[0] == '?': yield '0' + s yield '1' + s else: yield x[0] + s print(replace_erin('?01?')) #brett's solution def match_bits(pattern): vals = [""] for m in pattern: if m == "?": vals = [v + "0" for v in vals] + [v + "1" for v in vals] else: vals = [v + m for v in vals] return vals print(match_bits('?01?'))
465df1bd32caec4fb5581fd92d1586fa12842dc9
sapan/graph_cnn
/code/MNIST_learn_graph.py
6,424
3.59375
4
''' MNIST experiment comparing the performance of the graph convolution with Logistic regression and fully connected neural networks. The data graph structured is learned from the correlation matrix. This reproduce the results shown in table 2 of: "A generalization of Convolutional Neural Networks to Graph-Structured Data" ''' ### Dependencies import cPickle as pickle from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.optimizers import RMSprop from keras.datasets import mnist from keras.utils import to_categorical from graph_convolution import GraphConv import numpy as np from sklearn.preprocessing import normalize np.random.seed(2017) # for reproducibility ### Parameters batch_size=128 epochs=40 num_neighbors=6 filters = 20 num_classes = 10 results = dict() ### Load the data (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 ix = np.where(np.var(X_train,axis=0)>0)[0] X_train = X_train[:,ix] X_test = X_test[:,ix] print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = to_categorical(y_train, num_classes) Y_test = to_categorical(y_test, num_classes) ### Prepare the Graph Correlation matrix corr_mat = np.array(normalize(np.abs(np.corrcoef(X_train.transpose())), norm='l1', axis=1),dtype='float64') graph_mat = np.argsort(corr_mat,1)[:,-num_neighbors:] # %% ### Single layer of Graph Convolution g_model = Sequential() g_model.add(GraphConv(filters=filters, neighbors_ix_mat = graph_mat, num_neighbors=num_neighbors, activation='relu', input_shape=(X_train.shape[1],1,))) g_model.add(Dropout(0.2)) g_model.add(Flatten()) g_model.add(Dense(10, activation='softmax')) g_model.summary() g_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) results['g'] = g_model.fit(X_train.reshape(X_train.shape[0],X_train.shape[1],1), Y_train, epochs=epochs, batch_size=batch_size, verbose = 2, validation_data=(X_test.reshape(X_test.shape[0],X_test.shape[1],1), Y_test)) g_error = 1-results['g'].__dict__['history']['val_acc'][-1] # %% ### Graph Convolution followed by FC layer g_fc_model = Sequential() g_fc_model.add(GraphConv(filters=filters, neighbors_ix_mat = graph_mat, num_neighbors=num_neighbors, activation='relu', input_shape=(X_train.shape[1],1,))) g_fc_model.add(Dropout(0.2)) g_fc_model.add(Flatten()) g_fc_model.add(Dense(512, activation='relu')) g_fc_model.add(Dropout(0.2)) g_fc_model.add(Dense(10, activation='softmax')) g_fc_model.summary() g_fc_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) results['g_fc'] = g_fc_model.fit(X_train.reshape(X_train.shape[0],X_train.shape[1],1), Y_train, epochs=epochs, batch_size=batch_size, verbose = 2, validation_data=(X_test.reshape(X_test.shape[0],X_test.shape[1],1), Y_test)) g_fc_error = 1-results['g_fc'].__dict__['history']['val_acc'][-1] # %% ### 2 Layer of Graph Convolution g_g_model = Sequential() g_g_model.add(GraphConv(filters=filters, neighbors_ix_mat = graph_mat, num_neighbors=num_neighbors, activation='relu', bias = True, input_shape=(X_train.shape[1],1,))) g_g_model.add(Dropout(0.2)) g_g_model.add(GraphConv(filters=filters, neighbors_ix_mat = graph_mat, num_neighbors=num_neighbors, activation='relu')) g_g_model.add(Dropout(0.2)) g_g_model.add(Flatten()) g_g_model.add(Dense(10, activation='softmax')) g_g_model.summary() g_g_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) results['g_g'] = g_g_model.fit(X_train.reshape(X_train.shape[0],X_train.shape[1],1), Y_train, epochs=epochs, batch_size=batch_size, verbose = 2, validation_data=(X_test.reshape(X_test.shape[0],X_test.shape[1],1), Y_test)) g_g_error = 1-results['g_g'].__dict__['history']['val_acc'][-1] # %% ### Fully Connected - FC Model FC_FC_model = Sequential() FC_FC_model.add(Dense(512, activation='relu', input_shape=(X_train.shape[1],))) FC_FC_model.add(Dropout(0.2)) FC_FC_model.add(Dense(512, activation='relu', input_shape=(X_train.shape[1],))) FC_FC_model.add(Dropout(0.2)) FC_FC_model.add(Dense(10)) FC_FC_model.add(Activation('softmax')) FC_FC_model.summary() FC_FC_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) results['fc_fc'] = FC_FC_model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose = 2, validation_data=(X_test, Y_test)) fc_fc_error = 1-results['fc_fc'].__dict__['history']['val_acc'][-1] # %% ### Logistic Regression Model LR_model = Sequential() LR_model.add(Dense(10, activation='relu', input_shape=(X_train.shape[1],))) LR_model.add(Activation('softmax')) LR_model.summary() LR_model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) results['lr'] = LR_model.fit(X_train, Y_train, epochs=300, batch_size=batch_size, verbose = 2, validation_data=(X_test, Y_test)) lr_error = 1-results['lr'].__dict__['history']['val_acc'][-1] # %% print('Error rates for the different models:') print('Logistic Regression: %.04f'%lr_error) print('1 Layer of graph convolution: %.04f'%g_error) print('2 Layers of graph convolution: %.04f'%g_g_error) print('1 Layers f graph convolution & 1 FC layer: %.04f'%g_fc_error) print('2 FC layers: %.04f'%fc_fc_error) #pickle.dump(results, open('results/MNIST_results.p','wb'))
0d4b1c1c28c231208b47a2da2d2046d4c070c669
Hachirota/PPandA
/mergesort.py
228
3.75
4
def merge(a1, a2, a): i = j = 0 while i + j < len(a): if j == len(a2) or (i < len(a1) and a1[i] < a2[j]): a[i+j] = a1[i] i += 1 else: a[i+j] = a2[j] j += 1
c9dde4191b35597750190d75bd5b308ccb8b8d2a
LucasPayne/geometry
/Python/randomize.py
369
3.6875
4
""" Random data generation """ from shapes import * from triangulation import * from random import random def random_convex_polygon(xmin, xmax, ymin, ymax, n, shift=0): points = [Point((xmax - xmin) * random() + xmin, (ymax - ymin) * random() + ymin) for _ in range(n)] shifted = Point.random(shift) return convex_hull([p + shifted for p in points])
e5963aa274311fdc475c49cfd5d00a31aeac1fe0
anfasnujum/sudokuSolver
/sudokuSolver.py
5,695
3.578125
4
class Solution: def solveSudoku(self, board): """ Do not return anything, modify board in-place instead. """ remaining = [[[str(x) for x in range(1,10)] for x in range(9)] for x in range(9)] self.updateRemaining(board,remaining) next = self.findNext(board,0,0) count=0 print(count,remaining[next[0]][next[1]]) for k in remaining[next[0]][next[1]]: self.sudokuSolver(board.copy(),remaining.copy(),next[0],next[1],k,count) def sudokuSolver(self,board,remaining,i,j,number,count): count+=1 new = self.putAndUpdate(board,remaining,number,i,j) newboard = new[0] newremaining = new[1] if self.checkVictory(newboard): print("Solved") print(newboard) return True next = self.findNext(newboard,i,j) if not next: return False if len(newremaining[next[0]][next[1]]) == 0: print("bye") return False for k in newremaining[next[0]][next[1]]: print(count,k,newremaining[next[0]][next[1]]) if self.sudokuSolver(newboard,newremaining,next[0],next[1],k,count): print("Yay") return True print(count,"sad",k,newremaining[next[0]][next[1]]) return False def updateRemaining(self,board,remaining): for i in range(9): for j in range(9): if board[i][j] != ".": remaining[i][j] = [] continue #checkcolumn for m in range(9): if board[m][j] != "." and board[m][j] in remaining[i][j]: remaining[i][j].remove(board[m][j]) #checkRow for k in range(9): if board[i][k] != "." and board[i][k] in remaining[i][j]: remaining[i][j].remove(board[i][k]) #check box for m in range(3*int(i/3),3*int(i/3) +3): for k in range(3*int(j/3),3*int(j/3) + 3): if board[m][k] != "." and board[m][k] in remaining[i][j]: remaining[i][j].remove(board[m][k]) if len(remaining[i][j]) == 1: board[i][j] = remaining[i][j][0] remaining[i][j].pop() def findNext(self,board,i,j): for i in range(i,9): for j in range(9): if board[i][j] == ".": return (i,j) for i in range(0,i): for j in range(0,9): if board[i][j] == ".": return (i,j) return False def putAndUpdate(self,board,remaining,number,i,j): newboard = board.copy() newremaining = remaining.copy() newboard[i][j] = number #Update row elements for k in range(9): if number in newremaining[i][k]: newremaining[i][k].remove(number) #Update column elements for m in range(9): if number in newremaining[m][j]: newremaining[m][j].remove(number) #update box for m in range(3*int(i/3),3*int(i/3) + 3): for k in range(3*int(j/3), 3*int(j/3)+3): if number in newremaining[m][k]: newremaining[m][k].remove(number) return [newboard,newremaining] def checkVictory(self,board): #Check Rows for i in range(9): sum=0 for j in range(9): if board[i][j] == ".": continue sum+=int(board[i][j]) if sum != 45: return False #check Columns for j in range(9): sum = 0 for i in range(0,9): if board[i][j] == ".": continue sum += int(board[i][j]) if sum != 45: return False #Check Box for i in range(3): for j in range(3): sum = 0 for m in range(3*i,3*i+3): for k in range(3*j,3*j+3): if board[m][k] == ".": continue sum+= int(board[m][k]) if sum != 45: return False return True Anfas = Solution() board = [["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"]] print(board) Anfas.solveSudoku(board) board = [["5","3","1","2","7","4","8","9","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"]]
f435dbf930d8fa29598d06d6b565fe0c5dc1c69f
Innodogs/Innodogs
/app/utils/pages_helper.py
2,225
3.875
4
import math from typing import List __author__ = 'Xomak' class Pages: """ Pages class is intended to store data, relevant to pagination """ def __init__(self, endpoint, rows_per_page, current_page, total_number, request_args): """ Creates Pages object. :param endpoint: Flask endpoint to refer in pagination :param rows_per_page: Number of items per page :param current_page: Current page :param total_number: Total number of paginated objects :param request_args: Request args, which will be included in generated requests """ self.start_row = (current_page - 1) * rows_per_page self.rows_per_page = rows_per_page self.current_page = current_page self.endpoint = endpoint self.last_page_number = math.ceil(total_number / rows_per_page) if self.start_row < 0 or self.start_row > total_number: raise ValueError("Current page is out of range") request_args = dict(request_args) if 'page' in request_args: del request_args['page'] self.request_args = request_args def get_start_row(self) -> int: return self.start_row def get_rows_number(self) -> int: return self.rows_per_page def get_pages_list(self, difference=3) -> List[int]: """ Returns reduced list of available pages numbers, like: 1 .. n-3 n-2 n-1 n n+1 n+2 n+3 .. 10 Where 3 is variable and is called difference :param difference: Difference :return: List of pages' numbers """ pages_list = [1] for current_page in range(self.current_page - difference, self.current_page + difference): if 0 < current_page <= self.last_page_number and current_page not in pages_list: pages_list.append(current_page) if self.last_page_number != 0 and self.last_page_number not in pages_list: pages_list.append(self.last_page_number) return pages_list def has_previous(self) -> bool: return self.current_page > 1 def has_next(self) -> bool: return self.current_page != self.last_page_number and self.last_page_number != 0
9bb549365104929566fa87c29f01cd5cbd380a10
Ri8thik/Python-Practice-
/Linked_List/singly_ll/insertion_in _singly_linked_list.py
2,906
3.921875
4
class Node: def __init__(self,data): self.data=data self.ref=None class Sll: def __init__(self): self.head=None self.tail=None def insert_data(self,data,location): new_node=Node(data) if self.head is None: self.head =new_node self.tail=new_node else: if location ==0: new_node.ref=self.head self.head=new_node elif location==-1: new_node.ref=None self.tail.ref=new_node self.tail=new_node else: n=self.head index=0 while index<location-1: n=n.ref index+=1 new_node.ref=n.ref n.ref=new_node def print__ll(self): if self.head is None: print("Linked List is empty ...!") else: n=self.head while n is not None: print(n.data,end=' ') n=n.ref def searchSll(self,value): if self.head is None: return "LL is empty ...!" else: n=self.head while n is not None: if n.data==value: return n.data n=n.ref return "data is not present in ll" def reverse(self): n=self.head prev=None while n is not None: value=n.ref n.ref=prev prev=n n=value self.head=prev def middle(self): n=self.head p=self.head while (p is not None and p.ref is not None): p=p.ref.ref n=n.ref print(n.data) ll=Sll() ll.insert_data(1,0) ll.insert_data(9,0) ll.insert_data(8,0) ll.insert_data(7,0) ll.insert_data(2,-1) ll.insert_data(3,-1) ll.insert_data(1,0) ll.insert_data(5,3) ll.insert_data(467,1) ll.print__ll() print() ll.middle()
9bac38cd3bc1014cc19216e4cbcda36f138dfef1
Ri8thik/Python-Practice-
/creat wedge using loop/loop.py
2,269
4.40625
4
import tkinter as tk from tkinter import ttk root=tk.Tk() # A) labels #here we create a labels using loop method # first we amke a list in which all the labels are present labels=["user name :-","user email :-","age:-","gender:-",'state:-',"city:-"] #start a for loop so that it print all the labels which are given in above list:- for i in range(len(labels)): # this print the labe[0] which means a current label cur_label="label" +str(i) # here we start a simple method in which we create a label cur_label=tk.Label(root,text=labels[i]) # here we use the padding padx is use for left and right , pady is used for top and bottom cur_label.grid(row=i,column=0,sticky=tk.W, padx=2, pady=2) # B) Entry box # to create a loop for entry bos so that it print many entry #first we create a dictunary in which we store the variable ,and that variable will store the data of the current entry user_info={ 'name': tk.StringVar(), "email" :tk.StringVar(), "age" :tk.StringVar(), "gender" : tk.StringVar(), "state" : tk.StringVar(), "city" : tk.StringVar() } #here is the counter variable which increases the value of row as the loop start counter =0 #here is the loop for i in user_info: #this print the first entry[i] or current entry[i] cur_entry='entry' + i # here is the simple methoid to create a entry and in textvariable we create a dictonaray user_info cur_entry=tk.Entry(root,width=16,textvariable=user_info[i]) # here we use the padding padx is use for left and right , pady is used for top and bottom cur_entry.grid(row=counter,column=1,padx=2, pady=2) # here the counter increment the valuye counter+=1 def submit(): print("user_name is :- " +user_info['name'].get()) print("user_email is :- " +user_info['email'].get()) print("user_age is :- " +user_info['age'].get()) print("gender :- " +user_info['gender'].get()) print("state :- " +user_info['state'].get()) print("city :- " +user_info['city'].get()) submit_btn =ttk.Button(root,text='submit',command=submit) submit_btn.grid(row=6,columnspan=2) root.mainloop()
6f7282a12f6a377ada3d9171c24a7e5c31a8c2f4
Ri8thik/Python-Practice-
/Linked_List/Circular_singly_ll/Create_Circular_Single_linked_list.py
2,139
4.03125
4
class Node: def __init__(self,data): self.data=data self.ref=None class circular: def __init__(self): self.head=None self.tail=None def circular_ll(self,data): new_node=Node(data) new_node.ref=new_node self.head=new_node self.tail=new_node def insert_ll(self,data,location): new_node=Node(data) if self.head is None: new_node.ref=new_node self.head=new_node self.tail=new_node else: if location==0: new_node.ref=self.head self.head=new_node self.tail.ref=new_node elif location==-1: new_node.ref=self.head self.tail.ref=new_node self.tail=new_node else: n=self.head index=0 while index<location-1: n=n.ref index+=1 new_node.ref=n.ref n.ref=new_node def print_ll(self): if self.head is None: print("Linked list is empty...!") else: n=self.head while n is not None: print(n.data,end=' ') n=n.ref if n ==self.head: break ll=circular() ##ll.circular_ll(2) ll.insert_ll(1,0) ll.insert_ll(9,-1) ll.insert_ll(88,0) ll.insert_ll(89,-1) ll.insert_ll(66,2) ll.print_ll()
8ccd3e730ae643d75f40263e027090f9c0f353a2
kkxujq/leetcode
/answer/0082/82.linningmii.py
816
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: node_counter = 0 def find_next_different_node(self, head): self.node_counter += 1 if head.next is None: return None if head.val == head.next.val: return self.find_next_different_node(head) return head def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ result = [] node = head while node is not None: node = self.find_next_different_node(node) if self.node_counter == 1: result.append(node) self.node_counter = 0 return result s = Solution()
fca8a93a245b027c0cfee51200e9e603c737f5df
rchu6120/python_workshops
/comparison_operators.py
234
4.21875
4
x = [1, 2, 3] y = list(x) # create a NEW list based on the value of x print(x, y) if x is y: print("equal value and identity") elif x == y: print("equal value but unqual identity") else: print("unequal")
1ef7c763b40ab15b9bb07313edc9be70f9efd5d6
rchu6120/python_workshops
/logic_hw.py
852
4.375
4
############# Ask the user for an integer ### If it is an even number, print "even" ### If it is an odd number, print "odd" ### If it is not an integer (e.g. character or decimal #), continue asking the user for an input ### THIS PROGRAM SHOULND'T CRASH UNDER THESE CIRCUMSTANCES: # The user enters an alphabet # The user enters a decimal number # The user enters a non numeric character # The user enters a negative number # For example, if the user enters "a", the program should ask the user to try again and enter an integer # Topic: conditionals, user input, loops # Hint: You can use the try except: while True: try: if int(input("Please enter an integer. \n")) % 2 == 0: print("even") break else: print("odd") break except: continue
4b0b9bf92dd3045dcee5e99d3cd657d8328bfb40
zhaofujian0723/ALG
/zsfz.py
418
3.84375
4
""" 整数反转 """ class Solution: """ @param number: A 3-digit number. @return: Reversed number. """ def reverseInteger(self, number): # write your code here g = number % 10 s = int(number / 10 % 10) b = int(number / 100) return int(str(g) + str(s) + str(b)) if __name__ == '__main__': S = Solution() res = S.reverseInteger(100) print(res)
5f5f657ef5fad9d08ad0a1657a97cbe83535cb09
HeyChriss/BYUI-Projects-Spring-2021
/Maclib.py
1,453
4.25
4
print ("Please enter the following: ") adjective = input("adjective: ") animal = input("animal: ") verb1 = input("verb: ") exclamation = input("exclamation: ") verb2 = input("verb : ") verb3 = input("verb: ") print () print ("Your story is: ") print () print (f"The other day, I was really in trouble. It all started when I saw a very") print (f'{adjective} {animal} {verb1} sneeze down the hallway. "{exclamation}!" I yelled. But all') print (f"I could think to do was to {verb2} over and over. Miraculously,") print (f"that caused it to stop, but not before it tried to {verb3}") print (f"right in front of my family. ") # I made it my own during this part forward, I added a second part of the story asking different information # to the person to keep going with the story print () print () print () print () print ("Keep going with the second part of the story...") print ("Please enter the following: ") day = input("day of the week: ") animal1 = input("animal: ") adjective1 = input("adjective: ") exclamation1 = input("exclamation: ") verb4 = input("verb : ") place = input("place: ") print () print ("The second part is: ") print () print (f"I almost died during that time, but on {day}") print (f'I saw a {animal1} and it was so {adjective1}') print (f"I tried to {verb4} but it was useless so I hurted myself and went to the {place} ") print (f"to watch TV :) ") print ("THE END OF THE STORY!")
083898331a90863833b1ee0db5d70a05b0ece14a
Pahahot/Mission
/곽호준/5장.py
2,339
3.734375
4
#5-1 # class Calculator: # def __init__(self): # self.value = 0 # def add(self, val): # self.value += val # def minus(self, val): # self.value -= val # class UpgradeCalculator(Calculator): # pass # cal =UpgradeCalculator() # cal.add(10) # cal.minus(7) # print(cal.value) #5-2 # class Calculator: # def __init__(self): # self.value = 0 # 버전 1 용 # def add(self, val): # if val >= 50: # val = 50 # self.value += val #버전 2용 # def add(self, val): # val = self.maxcheck(val) # self.value += val # 버전 1용 # class MaxlimitCalculator(Calculator): # pass #버전 2용 # class MaxlimitCalculator(Calculator): # def maxcheck(self, value): # if self.value >= 50: # value = 50 # return value # cal = MaxlimitCalculator() # cal.add(50) # cal.add(60) # print(cal.value) #5-3 #1. abs(-3) => 3 => 3-3 = 0 => all[1,2,0] => 0 때문에 false #2. chr함수의 반대는 ord => a는 그대로 a가 됨으로 true #5-4 # def minuscheck(number): # if number > 0: # return number # print(filter(minuscheck, [1, -3, 2, 0, -5, 6])) # print(list(filter(minuscheck, [1, -3, 2, 0, -5, 6]))) # print(list(filter(lambda number: number > 0, [1,-3,2,0,-5,6]))) #5-5 # print(int('0xea', 16)) #5-6 # def test(number): # return number * 3 # print(list(map(test, [1,2,3,4]))) # print(list(map(lambda number: number * 3, [1,2,3,4]))) #5-7 # list = [-8, 2, 7, 5, -3, 5, 0, 1] # print(max(list) + min(list)) #5-8 # print(round(17/3,4)) #5-9 # import sys # numbers = sys.argv[1:] # print(numbers) # result=0 # for i in numbers: # result += int(i) # print(result) #5-10 # import os # os.chdir("C:/Users") # f = os.popen("dir") # print(f.read()) #5-11 # import glob # import os # f=os.popen("dir") # print(f.read()) # print("=" * 30) # print(glob.glob("C:/Users/incom/OneDrive/바탕 화면/파이썬COP2/Mission/곽호준/*.py")) #5-12 # import time # print(time.localtime(time.time())) # print(time.localtime()) # print(time.strftime('%Y/%m/%d %H:%M:%S', time.localtime())) #5-13 # import random # result = [] # while len(result) < 6: # number = random.randint(1,45) # if number not in result: # result.append(number) # print(result)
270f2c4c0494965f643448de5909b42dcb0ec101
Pahahot/Mission
/김민호/Week03_5장연습문제_김민호.py
1,134
3.515625
4
#01 class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value += val class UpgradeCalculator(Calculator): def minus(self, val): self.value -=val cal = UpgradeCalculator() cal.add(10) cal.minus(7) print(cal.value) #02 class MaxLimitCalculator(Calculator): def add(self, val): self.value += val if self.value > 100: self.value = 100 #03 all([1, 2, abs(-3)-3]) chr(ord('a')) == 'a' #04 list(filter(lambda x:x>0, [1, -2, 3, -5, 8, -3])) #05 int('0xea', 16) #06 list(map(lambda x:x*3, [1,2,3,4])) #07 a = [-8, 2, 7, 5, -3, 5, 0, 1] max(a) + min(a) #08 round(17/3, 4) #09 import sys numbers = sys.argv[1:] result = 0 for number in numbers: result += int(number) print(result) #10 import os os.chdir("c:/doit") result = os.popen("dir") print(result.read()) #11 import glob glob.glob("c:/doit/*.py") #12 import time time.strftime("%Y/%m/%d %H:%M:%S") #13 import random result = [] while len(result) < 6: num = random.randint(1, 45) if num not in result: result.append(num) print(result)
f1e95a2ca6c0243090f6af46fb1c9257239effc2
boiidae/py4me
/counters_with_dictionaries.py
169
3.546875
4
# One common use of dictionaries is counting how often we see something ccc = dict() ccc['csev'] = 1 ccc['cwen'] = 1 print(ccc) ccc['cwen'] = ccc['cwen'] + 1 print(ccc)
8f16c36cb9ed64bd78c662ccfff594809ca5213e
boiidae/py4me
/nested_decision.py
284
4
4
# Example of a nested decision # A one-branch if statement showing an if statement within an if statement # Try it with numbers below and above 100 to see the different results x=42 if x > 1: print('More than one') if x < 100: print('Less than 100') print('all done')
0c6ef58bbed17665b541028822a4603eafaf3af1
Aayush360/opencvprojects
/hough_line.py
869
3.59375
4
# find the canny edge before finding the hough line import cv2 import numpy as np # load the image image = cv2.imread('../images/sudoku.jpg') gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) canny = cv2.Canny(gray,100,170,apertureSize=3) # run HoughLines using rho accuracy of 1px, # theta accuracy of np.pi/180 which is 1 degree # line threshold is set to 240, number of points in a line lines = cv2.HoughLines(canny,1,np.pi/180,240) # we iterate through each line and convert it to format # required by cv2.lines (requires endpoints) for rho,theta in lines[0]: a = np.cos(theta) b= np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0+1000*(-b)) y1 = int(y0+1000*(a)) x2 = int(x0-1000*(-b)) y2 = int(y0-1000*(a)) cv2.line(image,(x1,y1),(x2,y2),(255,0,0),2) cv2.imshow("Hough lines", image) cv2.waitKey(0) cv2.destroyAllWindows()
b4541fb13f3a87aad37bd489b9b2caca7fbbceb8
stopslavery404/Data-Structures
/Stack using linked list.py
1,193
3.609375
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 23:29:48 2020 @author: rahul """ class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.size = 0 self.head = None def __repr__(self): arr = [] node = self.head while node: arr.append(node.data) node = node.next return str(arr) def __len__(self): return self.size def push(self, data): if self.size == 0: self.head = Node(data) self.size += 1 return node = Node(data) node.next = self.head self.head = node self.size += 1 return def top(self): if self.head: return self.head.data def pop(self): if self.size == 0: raise Error('Stack UnderFlow') if self.size == 1: self.head = None self.size -= 1 return node = self.head self.head = node.next self.size -= 1 del (node) class Error(Exception): pass s = Stack() for x in [1, 2, 5, 4]: s.push(x)
bb3825dc1f91cec3127d75c1d35fd0c921206d8f
stopslavery404/Data-Structures
/Treap.py
7,585
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 22 06:13:15 2020 @author: rahul """ from random import randint K=2**32-1 class Node: def __init__(self, data): self.parent = None self.left = None self.right = None self.data = data self.priority = randint(0, K) class Treap: def __init__(self, arr=None): self.root = None if arr: from random import shuffle temp = [x for x in arr] shuffle(temp) for x in temp: self.insert(x) def left_rotate(self, x): y = x.right b = y.left x.right = b if b: b.parent = x y.parent = x.parent if x.parent is None: self.root = y elif x.parent.left == x: x.parent.left = y else: x.parent.right = y y.left = x x.parent = y def right_rotate(self, y): x = y.left b = x.right y.left = b if b: b.parent = y x.parent = y.parent if y.parent is None: self.root = x elif y.parent.left == y: y.parent.left = x else: y.parent.right = x x.right = y y.parent = x def insert(self, item): def insertUtil(node, item): if item < node.data: if node.left: insertUtil(node.left, item) if node.left.priority>node.priority: self.right_rotate(node) else: new_node = Node(item) node.left = new_node new_node.parent = node return new_node elif item > node.data: if node.right: insertUtil(node.right, item) if node.right.priority>node.priority: self.left_rotate(node) else: new_node = Node(item) node.right = new_node new_node.parent = node return new_node if self.root is None: self.root = Node(item) return node = insertUtil(self.root, item) def inorder(self): node = self.root def inorderUtil(node): if node: if node.left: inorderUtil(node.left) print(node.data, end=' ') if node.right: inorderUtil(node.right) inorderUtil(node) print() def preorder(self): node = self.root def preorderUtil(node): if node: print(node.data, end=' ') if node.left: preorderUtil(node.left) if node.right: preorderUtil(node.right) preorderUtil(node) print() def postorder(self): node = self.root def postorderUtil(node): if node: if node.left: postorderUtil(node.left) if node.right: postorderUtil(node.right) print(node.data, end=' ') postorderUtil(node) print() def search(self, item): def searchUtil(root, item): if not root: return None if root.data == item: return root if item < root.data: return searchUtil(root.left, item) if item > root.data: return searchUtil(root.right, item) return searchUtil(self.root, item) def subtree_minimum(self, node): while node.left: node = node.left return node def subtree_maximum(self, node): while node.right: node = node.right return node def successor(self, node): if not node: return if node.right: return self.subtree_minimum(node.right) else: current_node = node while current_node.parent and current_node.parent.left != current_node: current_node = current_node.parent if current_node.parent: return current_node.parent def predecessor(self, node): if not node: return if node.left: return self.subtree_maximum(node.left) else: current_node = node while current_node.parent and current_node.parent.right != current_node: current_node = current_node.parent if current_node.parent: return current_node.parent def delete(self, item): target = self.search(item) if target is None: return while target.right: successor = self.successor(target) target.data, successor.data = successor.data, target.data target = successor if target.parent and target.parent.left and target.parent.right: if target.parent.left.priority<target.parent.right.priority: self.left_rotate(target.parent) else: self.right_rotate(target.parent) if target.parent: if target.parent.left == target: target.parent.left = None else: target.parent.right = None #target.parent = None elif target == self.root: self.root = None target.parent=None def max(self): m = float('-inf') node = self.root while node and node.right: node = node.right if node: m = max(m, node.data) return m def min(self): m = float('inf') node = self.root while node and node.left: node = node.left if node: m = min(m, node.data) return m def path_to_root(self, node): arr = [] arr.append(node.data) while node != self.root: node = node.parent arr.append(node.data) print(arr) class Iterator: def __init__(self, root): self.node = root self.stack = [] def __next__(self): if self.node is None and not self.stack: raise StopIteration while self.node: self.stack.append(self.node) self.node = self.node.left self.node = self.stack.pop() item = self.node.data self.node = self.node.right return item def __iter__(self): return self.Iterator(self.root) def height(self): def maxDepth(node): if node is None: return 0 ldepth=maxDepth(node.left) rdepth=maxDepth(node.right) if ldepth>rdepth: return ldepth+1 else: return rdepth+1 return maxDepth(self.root) import time t = Treap() s = time.time() for x in range(2 ** 20): t.insert(x) print('height of tree after 1Million insertions', t.height()) e = time.time() print('time taken for 1Million insertions', e - s) s = time.time() for x in range(2 ** 20): t.search(x) e = time.time() print('time taken for 1Million searches', e-s) s = time.time() for x in range(2 ** 20): t.delete(x) e = time.time() print('time taken for 1Million deletions', e - s) print(t.height())
3d9b0433f6b300d8e2d6da2bda5b54f4c1033d7b
stopslavery404/Data-Structures
/minimum stack.py
301
3.78125
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 19:34:01 2020 @author: rahul """ stack=[] def add(item): if stack: stack.append((item,min(item,stack[-1][1]))) else: stack.append((item,item)) def pop(): return stack.pop()[0] def minimum(): return stack[-1][1]
8bdb6f6d68d804d2387699ebaf0e83e0e100ab61
Helloworld-0718/testcode
/demo01.py
395
3.84375
4
""" """ # 判断一个数是否为质数 def isprime(num): if num>1: for i in range(2,num): if num%i==0: break else: return num print(isprime(1)) # 给定范围内所有质数求和 def sum_prime(a,b): sum=0 for i in range(a,b): if isprime(i)==i: sum+=i return sum print(sum_prime(1,10001))
be4bef4be78db2c0986c8fa73bc3aacabd5c1b3c
kaphie/PassLocker-1
/util/user.py
1,617
3.890625
4
import json import random import string import pyperclip accounts = "accounts.json" def login(username, password): """ Log in a new user """ global accounts accounts = list_accounts() for account in accounts: if account['account'] == username and account['password'] == password: return True else: print('Invalid username or password..') def add_user(account, name, password): """ Add new users to the user_list array """ global accounts accounts = list_accounts() accounts.append({'account': account, 'name': name, 'password': password, '': '\n'}) _save_user_accounts_(accounts) def random_pass(): """ Generate a random password """ return (''.join( random.choice(string.ascii_letters + string.digits + ".',={}[]-/|£$%^&*()_+~#@?><") for _ in range(10))) def search_account(name): """ Search for an account on the json file """ global accounts accounts = list_accounts() for account in accounts: if account['account'] == name: return account def del_user(name): """ Delete a user object from the json file """ global accounts accounts = list_accounts() accounts = [account for account in accounts if account['account'] != name] _save_user_accounts_(accounts) def list_accounts(): with open('accounts.json', 'r') as json_file: return json.load(json_file) def _save_user_accounts_(accounts): """ Save all user accounts """ with open('accounts.json', 'w') as json_file: json.dump(accounts, json_file, sort_keys=True, indent=4)
875f5ae6b9aeccb15135404cad5581cf4982408f
LatencyTDH/coding-competitions
/trie.py
945
3.96875
4
import collections class TrieNode(object): def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: node = self.root for ch in word: node = node.children[ch] node.is_word = True def search(self, word: str) -> bool: node = self.root for ch in word: if ch not in node.children: return False else: node = node.children[ch] return node is not None and node.is_word def startsWith(self, prefix: str) -> bool: node = self.root for ch in prefix: if ch not in node.children: return False else: node = node.children[ch] return True
d40a0420ff782e33bb26d868435e778eb9bd5750
LatencyTDH/coding-competitions
/test3222.py
1,432
3.65625
4
from threading import Condition class FizzBuzz: def __init__(self, n: int): self.n = n self.work = Condition() # printFizz() outputs "fizz" def fizz(self, printFizz: 'Callable[[], None]') -> None: for i in range(self.n): if i % 3 == 0 and i % 5 != 0: printFizz() self.work.notify_all() else: self.do_wait() # printBuzz() outputs "buzz" def buzz(self, printBuzz: 'Callable[[], None]') -> None: for i in range(self.n): if i % 5 == 0 and i % 3 != 0: printBuzz() self.work.notify_all() else: self.do_wait() # printFizzBuzz() outputs "fizzbuzz" def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None: for i in range(self.n): if i % 5 == 0 and i % 3 == 0: printFizzBuzz() self.work.notify_all() else: self.do_wait() # printNumber(x) outputs "x", where x is an integer. def number(self, printNumber: 'Callable[[int], None]') -> None: for i in range(self.n): if i % 5 != 0 and i % 3 != 0: printNumber(i) self.work.notify_all() else: self.do_wait() def do_wait(self): with self.work: self.work.wait()
d3029863995ede2a505f84593ea59e3bd887a3f6
LatencyTDH/coding-competitions
/nqueens.py
1,831
3.578125
4
from typing import List, Set import pprint class NQueensSolver(object): def __init__(self, n: int): self.n = n def get_all_solutions(self): self.rows = [0] * self.n self.cols = [0] * self.n self.diags = [0] * (2 * self.n + 1) self.antidiags = [0] * (2 * self.n + 1) self.solution = set() self.ways = [] self._solve(0) return self.ways def _solve(self, piece: int): if piece == self.n: return True r = piece for c in range(self.n): if self.can_place_queen(r, c): diag_index = r - c + self.n - 1 antidiag_index = r + c self.solution.add((r, c)) self.rows[r] = self.cols[c] = self.diags[diag_index] = \ self.antidiags[antidiag_index] = 1 if self._solve(piece + 1): self.ways.append(self.queen_representation(self.solution)) self.rows[r] = self.cols[c] = \ self.diags[diag_index] = self.antidiags[antidiag_index] = 0 self.solution.remove((r, c)) return False def can_place_queen(self, row: int, col: int): return (self.rows[row] != 1 and self.cols[col] != 1 and self.diags[row - col + self.n - 1] != 1 and self.antidiags[row + col] != 1) def queen_representation(self, queen_locs: Set) -> List[str]: board = [['.'] * self.n for _ in range(self.n)] for row, col in queen_locs: board[row][col] = 'Q' return ["".join(row) for row in board] if __name__ == '__main__': solver = NQueensSolver(8) solution_grids = solver.get_all_solutions() pprint.pprint(solution_grids) print(len(solution_grids))
2ffcaa31322c70839d94b1b90df2edd84a3d4eae
LatencyTDH/coding-competitions
/kickstart/2019/q1.py
545
3.609375
4
from heapq import heappop, heappush def compute_hindex(citations): q = [] hindices = [] hi = 0 for cit in citations: while q and q[0] <= hi: heappop(q) if cit > hi: heappush(q, cit) if len(q) > hi: hi += 1 hindices.append(hi) return hindices def main(): tcs = int(input()) for case in range(1, tcs + 1): n_papers = int(input()) citations = list(map(int, input().split())) ans = compute_hindex(citations) ans = " ".join(map(str, ans)) print("Case #{}: {}".format(case, ans)) if __name__ == '__main__': main()
df9d75439310e15f3c10e2173d6a02e37f2bed7f
GenericWaffler/SDD
/ChatBot/ChatBot.py
5,097
4.0625
4
from contextlib import contextmanager @contextmanager def nested_break(): class NameNestBreak(Exception): pass try: yield NameNestBreak except NameNestBreak: pass print("Hello! I am a food-ordering chatbot for WaffleInc! Please answer in full sentences.") #start while True: starta = input("What do you want?: ") start = starta.lower() if 'i want food' in start or start.strip() =='i want to order food': print('Great!') break elif 'i want' in start: print('The ordering comes later, but first...') break elif 'food' in start: print('I\'ll assume you want food.') break print("Sorry, I didn't understand that. I'm only for ordering food. Just say that you want food.") #ask name roster = open("roster.txt","r+") customers = roster.read() with nested_break() as asknamebreak: while True: namewhole = input("What's your name?: ") namefield = namewhole.lower() searchtext = "my name is" i = namefield.find(searchtext) x = i+len(searchtext) name = namefield[x:].strip() if "my name is " in namefield: while True: confirmname = input("Is " + name.title() + " your name?: ") if confirmname.lower() == 'yes' or confirmname.lower() == 'y': print("Great!") raise asknamebreak break else: print("I\'ll need you to say: \"My name is...\". I need to make sure your name isn't \"ambiguous\".") print("Let's try this again.") checka = 0 with open("roster.txt") as f: for linea in f: if (name.title()) in linea[:len(name)] and checka == 0: print("Hello "+ name.title() + "! You've ordered here before. These were your previous orders~") print() checka = 1 pass with open("roster.txt") as fa: for line in fa: if (name) in line[:len(name)]: print (line[len(name):]) elif (name.title()) in line[:len(name)]: print (line[len(name):]) #menu order menulist = ["Waffle Fondue", "Waffle Pizza", "Waffle Steak", "Waffle Stack", "Generic Waffle", "Gourmet Waffle", "Waffle Milkshake", "Waffle Sundae"] menuyesnoa = input("Would you like to see the menu?: ") menuyesno = menuyesnoa.strip() if 'yes' in menuyesno.lower(): print("--------Menu--------") for list in menulist: print(list) print("--------------------") order = [] amount = 0 orderlistfinal = [] ordernumber = 1 ordernumstr = str(ordernumber) ordernumstrcheck = (str(0) + ordernumstr) suffix = "st" if ordernumstr[-1] == str(1) and str(1) not in ordernumstrcheck[-2]: suffix = 'st' elif ordernumstr[-1] == str(2) and str(1) not in ordernumstrcheck[-2]: suffix = 'nd' elif ordernumstr[-1] == str(3) and str(1) not in ordernumstrcheck[-2]: suffix = 'rd' else: suffix = 'th' print("Please enter your items one by one as it appears on the menu. ") print("When you have enough, continue with a blank answer.") print("If you would like to see the menu again, please say so.") print() while True: while order != '': ordera = input('What\'s your ' + str(ordernumber) + str(suffix) + ' order?: ') order = ordera.strip() if 'menu' in order or 'Menu' in order : print("Here's the menu.") print("--------Menu--------") for list in menulist: print(list) print("--------------------") if order in menulist or order.title() in menulist: orderlistfinal.append(order.title()) print('Your cart: ' + str(orderlistfinal) ) ordernumber = ordernumber + 1 ordernumstr = str(ordernumber) suffix = "st" if ordernumstr[-1] == str(1) and str(1) not in ordernumstrcheck[-2]: suffix = 'st' elif ordernumstr[-1] == str(2) and str(1) not in ordernumstrcheck[-2]: suffix = 'nd' elif ordernumstr[-1] == str(3) and str(1) not in ordernumstrcheck[-2]: suffix = 'rd' else: suffix = 'th' ordernumstrcheck = (str(0) + ordernumstr) elif order != '' and 'menu' not in order and 'Menu' not in order : print('This item is not on the menu.') if len(orderlistfinal)>= 3: pass ordermorea = input("Would you like to order more?: ") ordermore = ordermorea.strip() if ordermore.lower() == "yes": order = 0 pass else: break else: print("You must have at least 3 orders for delivery.") order = 0 pass print('What else would you like?') pass final = (name.title() + str(orderlistfinal)) roster.write((final)+ "\n") roster.close() print() print('Your order has been saved: ') print(final) print('We hope to hear from you again soon, ' + name.title() + ' !') print() input("Press 'Enter' to exit")
613f00cd9cf150c7681ce926c1dfe0c5a984ad0c
ShilpuSri/Leetcode
/ReverseInteger.py
509
3.515625
4
class Solution: def reverse(self, x: int) -> int: if x >= pow(-2, 31) and x <= (pow(2,31) - 1): rev=0 orig=x if orig < 0: x=x+(2*(-x)) while x > 0: rem=x%10 rev=rev*10+rem x=int(x/10) if orig < 0: rev=rev-(2*rev) if rev >= pow(-2, 31) and rev <= (pow(2,31) - 1): return rev else: return 0
f805a58fe126f72e2cca7fabdb2bbbc4bda44926
douglasliralima/ArtificialIntelligence
/Aprendendo/matplotlib/CarregandoManipulandoDados.py
964
3.90625
4
import matplotlib.pyplot as plt import numpy as np ''' Uma coisa muito comum é querermos abrir documentos de dados em csv ou outros arquivos para usarmos o matplotlib, o segredo do sucesso aqui é muito simples, nos precisaremos entratanto usar o numpy para nos auxiliarmos nessa empreitada e deixar as coisas muuuuuuuuuuuuuuuuuuuuuuito mais fácil ''' x, y = np.loadtxt("exemplo.txt", delimiter = ",", unpack = True) #Precisamos mostrar o caminho arquivo padrao #O delimitador serve para dizer o que divide aquilo que vai para uma variavel e o que vai para outra, respectivamente #O default do delimitador é um espaco em branco #unpack, permite separar os arrays de retorno para cada elemento, ou seja é ele que deixa de uma vez a gente settar x e y #Por default unpack é false plt.plot(x,y, label = "y=x²") plt.xlabel("Valores da 1º coluna") plt.ylabel("Valores da 2º coluna") plt.legend() plt.title("Carregado do arquivo\nParabola Simples") plt.show()
0d857a1b7ce5d9fc148f9d6fb9f2f3a88dfb478f
douglasliralima/ArtificialIntelligence
/Aprendendo/Pandas/ConcacAppending.py
2,050
3.609375
4
import pandas as pd #Vamos usar esses dicionarios para criarmos os nossos dataFrames apenas para exemplificação df1 = pd.DataFrame({'HPI':[80,85,88,85], 'Int_rate':[2, 3, 2, 2], 'US_GDP_Thousands':[50, 55, 65, 55]}, index = [2001, 2002, 2003, 2004]) df2 = pd.DataFrame({'HPI':[80,85,88,85], 'Int_rate':[2, 3, 2, 2], 'US_GDP_Thousands':[50, 55, 65, 55]}, index = [2005, 2006, 2007, 2008]) df3 = pd.DataFrame({'HPI':[80,85,88,85], 'Int_rate':[2, 3, 2, 2], 'Low_tier_HPI':[50, 52, 50, 53]}, index = [2001, 2002, 2003, 2004]) #Veja que o dataframe 1 e 2, possuem os mesmos index, mas colunas diferentes, já o 2º e o 3º possuem diferentes colunas e indices #Para concatenar novas linhas em nosso dataframe é bem simples, basta elas compartilharem das mesmas colunas e terem indices diferentes #Basta usarmos o método concat e passarmos como parâmetro uma lista de dataframes concat = pd.concat([df1, df2]) ##print(concat) #Agora e se concatenassemos o df3 também? concat = pd.concat([df1,df2,df3]) #print(concat) #Veja, é adicionada uma nova coluna que nenhum dos outros dataframes tem, o df3 é colocado embaixo na tabela e #a coluna que ele n tem, também é adicionada resultando em outros NaN, basicamente a concatenacao só adiciona embaixo #O método append faz a mesma coisa que o método concat, sem tirar nem por pd.append(dataframes) #Podemos criar uma linha separada e depois colocarmos em nosso DataFrame, mas o pandas não é exatamente o melhor do mundo em #fazer entrada de dados gradual em nossos dataframe, ele é melhor apenas em manipula-los, mas podemos fazer alguams coisinhas anyway s = pd.Series([80,2,50], index=['HPI','Int_rate','US_GDP_Thousands']) #Criamos uma linha, com esses nomes no dicionario df4 = df1.append(s, ignore_index=True) #Como n add uma coluna de index, vamos ignorar todos eles para fazer nosso append print(df4)
c95319622f1a8a1c98a74ee630516de3b6232d7b
douglasliralima/ArtificialIntelligence
/Aprendendo/matplotlib/Customizacao1.py
2,197
4.03125
4
import matplotlib.pyplot as plt x = [1,2,3,4,5] y = [2,4,6,8,10] '''plt.plot(x,y, label="y=2x") plt.xlabel("Valores em x") plt.ylabel("Valores em y") plt.title("CustomizacaoBasica") #Nos podemos guardar a figura resultante dessas nossas manipulações em uma variável #graf1 = plt.figure() ''' tipo_rotacao = int(input("Tipo de rotacao 1 ou 2?\n")) if(tipo_rotacao == 1): #Podemos fazer subplotagens em nosso plot plt.subplot(311) plt.plot([1,2,3], [2,4,6], 'o') plt.subplot(312) plt.plot(range(12)) plt.subplot(313) plt.plot([1,2,3], [2,4,6], 'D') #Nos podemos rotacionar as valorações do gráfici em x ou y através do comando abaixo, passando quantos graus ele precisa girar plt.xticks(rotation=45) #Nos podemos configurar os espaçamentos dos subplots indo em configure subplots ao lado da lupazinha e configura-los manualmente #plt.subplots_adjust(bottom=0.10) #Ou fazer pelo código, coloque outros atributos a medida do que você quer plt.grid(True) plt.show() #Segunda forma de plotação e rotação dos eixos else: print("Man at work") #Nos podemos guardar uma figura resultante de uma plotagem em uma variável plt.plot([1,2,3], [2,4,6], 'o') plt.grid(True)#Para deixar uma matriz na plotagem 1 fig = plt.figure() #Podemos guardar a figura da nossa plotagem #Para criarmos uma segunda plotagem em outra janela precisamos cria-la fora do default #Com esse fim, falamos a proporção do nosso plano e onde é sua origem e grardamos isso em uma variável subplot graf1 = plt.subplot2grid((1,1), (0,0)) #Altere a primeira tupla para 5,5 e veja a diferença de proporção #Ao fazermos as modificações nessa variável graf1.plot(range(12)) #Ela fica guardada e é plotada junto com a default #Podemos modificar individualmente cada um dos números em algum dos eixos, vamos fazer no x e rotacionar todos em 45º for label in graf1.xaxis.get_ticklabels(): #Vou pegar cada uma das coordenadas e salvar em label label.set_rotation(45) #Girando ela em 45º plt.xlabel('x') plt.ylabel('y') plt.grid(True, color = 'g', linestyle = '-', linewidth = 2)#Veja, podemos personalizar o grid, settando sua cor, o formato da linha, a grossura dela plt.show()
8170af80d41093e0c296be267195d811c939f4c8
hirofumi0810/algorithm
/AOJ/Python/5_Recursion_Divide_and_Conquer/exhausive_search.py
781
3.65625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' 全探索 ''' # 各要素を選ぶか選ばないかで2^n通りあるので # 計算量:O(2^n) # 深さ優先探索 # DPでやんないと通らない def check(n, target, i, sum): if i == n: return sum == target # A[i]を使う場合 if check(n, target, i + 1, sum + A[i]): return True # A[i]を使わない場合 if check(n, target, i + 1, sum): return True # A[i]を使っても使わなくてもtargetを作れない return False n = int(input()) A = list(map(int, input().split())) m = int(input()) B = list(map(int, input().split())) for b in B: if check(n, b, 0, 0): print('yes') else: print('no')
b94ea95ac7231caa39b49873cce09210406e8f41
mikesm11/EasyPnP
/easypnp_networksys_cz/model/isecredentials.py
2,895
3.5625
4
import tkinter as tk class ISECredentials: """ Class responsible for setting user credentials to Cisco ISE """ __root = None __ip = None __user = None __pwd = None __ip_val = None __user_val = None __pwd_val = None @staticmethod def prompt_credentials(): """ Method to display a dialog box for setting user credentials to Cisco ISE """ global ise # Parameters of the dialog box ISECredentials.__root = tk.Tk() ISECredentials.__root.geometry('300x200') ISECredentials.__root.title('Enter your ISE credentials') # Frame for the dialog box margin parent = tk.Frame(ISECredentials.__root, padx=10, pady=10) parent.pack(fill=tk.BOTH, expand=True) # Entries for user credentials ISECredentials.__ip = ISECredentials.__make_entry(parent, "IP address:", 16) ISECredentials.__user = ISECredentials.__make_entry(parent, "Username:", 16) ISECredentials.__pwd = ISECredentials.__make_entry(parent, "Password:", 16, show="*") # Button to attempt to send b = tk.Button(parent, borderwidth=4, text="Enter", width=10, pady=8, command=ISECredentials.__submit) # Customize button size by text b.pack(side=tk.BOTTOM) # First focus to the label for IP address (you can write immediately after displaying the dialog box) ISECredentials.__ip.focus() # Then bind to the label for username and password (you can't send using enter without filling in all labels) ISECredentials.__user.bind('<Return>', ISECredentials.__ent_submit) ISECredentials.__pwd.bind('<Return>', ISECredentials.__ent_submit) # Focus and display the above defined dialog box parent.focus_force() parent.mainloop() # Returns sent user credentials if not ISECredentials.__ip_val or not ISECredentials.__user_val or not ISECredentials.__pwd_val: return None return ISECredentials.__ip_val, ISECredentials.__user_val, ISECredentials.__pwd_val @staticmethod def __ent_submit(event): """ Local method to bind function """ ISECredentials.__submit() @staticmethod def __submit(): """ Local method to submit button """ ISECredentials.__ip_val = ISECredentials.__ip.get() ISECredentials.__user_val = ISECredentials.__user.get() ISECredentials.__pwd_val = ISECredentials.__pwd.get() # Close the dialog box ISECredentials.__root.destroy() @staticmethod def __make_entry(parent, caption, width=None, **options): """ Local method to create labels """ tk.Label(parent, text=caption).pack(side=tk.TOP) entry = tk.Entry(parent, **options) if width: entry.config(width=width) entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH) return entry
219d48f4a2db2fcb1b0ec2b7298a547365372284
UnimaidElectrical/PythonForBeginners
/Random_code_store/Functions/Function_types.py
5,520
4.5625
5
Nested Functions def f1(): x = 88 def f2(): print(x) f2() f1() # prints 88 # called a closure as it remembers the values of the enclosing scopes even though the scopes are not around anymore def f1(): x = 88 def f2(): print(x) return f2 action = f1() #Make, return function action() # Call it now: prints 88 #Using Default Arguement Values def f1(): x=88 def f2(x=x): # Here the arguement will default to the value of x in the enclosing scope print(x) f2() f1() prints 88 ''' Notice that it is okay to call a function defined after the one that contains the call like this as long as the second def runs before the call of the first function- the code inside the dev is never evaluated until the function is actually called. ''' def f1(): x = 88 f2(x) def f2(x): print (x) f1() #The Global Statement y,z = 1,2 def all_global(): #the arguments here should be left as blank. if you have arguemrnts here it will be that they #were already assigned before being used in the function itself global xp xp = y + z all_global() print(xp) #Global Assignments and function calls xm,ym = 'pack','man' #xrm=yrm=200 def al_global(xm,ym): global doo = xm + ym xrm=6 yrm=1 xrm,yrm = al_global(5,3) print(xrm,yrm) print(doo) #xp,y = all_global(1,2) def func(): global mani mani = 99 func() print(mani) def func(): x = 4 action = (lambda n: x ** n) # x in enclosing def return action x = func() print(x(4)) # Here python will search all the enclosing defs after the referencing function's local scope and before the module global scope. def f1(): x = 99 def f2(): def f3(): print(x) f3() f2() f1() #Arguments and Shared References def changer(x,y): #Function x = 2 #Changes local name value only y[0] = 'spam' #Changes shared object in place x = 1 L = [1,2] #caller changer(x,L) #Pass immutable and mutable x,L # x is unchanged, L is different #vs print(x,L) #This prints the output without the parenthesis def changer(x,y): y = y[:] x = 2 y[0] = 'spam' return x,y # for this instance we see that the return statement and print statement are the same. print(x,y) changer(1,[3,5,7]) L = [1,2] changer(x, tuple(L)) #This will throw up an error because Tuples are immutable #Stimulating output parameters def multiple(x,y): x = 2 global y = [3,4] return(x,y) x = 1 L = [1,2] # Assignment x, y = multiple(x,y) #x, L = multiple(x,L) # Assign results to caller's names x, L x,y def func(*args): print(args) func() func('a'=1, 'b'=2) def func(a, *pargs, **kargs): print(a , pargs, kargs) func(1,2,3,x=1,y=2) #Combining Keywords and Defaults def func(spam, eggs, toast=0, ham=0): #First 2 required print(spam,eggs, toast,ham) func(1,2) #Output: (1,2,0,0) func(1,ham=1, eggs=0) #Output: (1,0,0,1) func(spam=1, eggs=0) #Output: (1,0,0,0) func(toast=1,eggs=2,spam=3) #Output: (3,2,1,0) func(1,2,3,4) #Output: (1,2,3,4) def min1(*args): res = args[0] for arg in args[1:]: if arg < res: res = arg return res def min2(first, *rest): for arg in rest: if arg < first: first = arg return first def min3(*args): tmp = list(args) tmp.sort() return tmp[0] print(min1(3,4,1,2)) print(min2('aa','bb','cc')) print(min3([2,2],[1,1],[3,3])) madam = ([2,2],[1,1],[3,3]) madam tada = list(madam) tada tada.sort() tada def minmax(test,*args): #takes in the lessthan or grtrthan operator and the other given arguments res = args[0] #takes in the first value for arg in args[1:]: #loops through the slice of the remaining values if test(arg, res): #takes in the arg and res arguments res = arg #equates the res and arg values return res print(res) def lessthan(x,y): return x < y def grtrthan(x,y): return x > y print(minmax(lessthan,4,2,1,5,6,3)) print(minmax(grtrthan,4,2,1,5,6,3)) def intersect(*args): res = [] for x in args[0]: #Scan first sequence for other in args[1:]: #for all other args. if x not in other: #Item in each one? break #If not then break out of the loop else: res.append(x) #Then add items to the end return res def union(*args) res = [] for seq in args: #For all args for x in seq: #For all nodes if not x in res: res.append(x) #Add new items to the result return res #Using the fuctions as module calls. from inter2 import intersect, union # Mixed types s1, s2, s3 = "SPAM", "SCAM", "SLAM" intersect(s1, s2), union(s1, s2) # Two operands #The Result #(['S', 'A', 'M'], ['S', 'P', 'A', 'M', 'C']) >>> intersect([1, 2, 3], (1, 4)) [1] >>> intersect(s1, s2, s3) ['S', 'A', 'M'] # Three operands >>> union(s1, s2, s3) ['S', 'P', 'A', 'M', 'C', 'L'] Iterate over all the elements in nums If some number in nums is new to array, append it If some number is already in the array, remove it
7e46e20703c0a192343772c52686b4846904537d
UnimaidElectrical/PythonForBeginners
/Algorithms/Sorting_Algorithms/Quick_Sort.py
2,603
4.375
4
#Quick Sort Implementation ************************** def quicksort(arr): """ Input: Unsorted list of intergers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(quicksort(l)) ''' *********************** return smaller , equal , larger #For this reason the final list will be returned as a tuple instead of a list. #To stop this from happening we then concatenate the l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l))) this will be returned as a tuple. ************************ ''' def quicksort(arr): """ Input: Unsorted list of integers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) #running the quick sort algo on the smaller list will return a sorted list in th return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l))) ****************************8 def quicksort(arr): """ Input: Unsorted list of integers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) #running the quick sort algo on the smaller list will return a sorted list in th return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l)))
1ab91009e990c5f8858a019968d8a1616a9e4c09
UnimaidElectrical/PythonForBeginners
/Algorithms/Sorting_Algorithms/selection_sort.py
2,740
4.46875
4
# Selection Sort # Selection sort is also quite simple but frequently outperforms bubble sort. # With Selection sort, we divide our input list / array into two parts: the sublist # of items already sorted and the sublist of items remaining to be sorted that make up # the rest of the list. # We first find the smallest element in the unsorted sublist and # place it at the end of the sorted sublist. Thus, we are continuously grabbing the smallest # unsorted element and placing it in sorted order in the sorted sublist. # This process continues iteratively until the list is fully sorted. def selection_sort(arr): for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # Select the smallest value if arr[j] < arr[minimum]: minimum = j # Place it at the front of the # sorted end of the array arr[minimum], arr[i] = arr[i], arr[minimum] return arr arr = [4,1,6,4,8,10,28,-3,-45] selection_sort(arr) print(arr) Insertion sort explained. we need a marker which will move through the list on the outer loop Start iteration and compasins at first element Then check if the number on the second element smaller than the number at the marker. If not we can move to the next element. Next we check the third element with the marker if it is smaller than the marker (First Element) then do a swap else move to the next element on the list. We keep checking the next element with the marker until the end of the list. l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] bubble_sort(l) def bubble_sort(arr): sort_head = True while sort_head: print("Bubble Sort: " + str(arr)) sort_head = False for num in range(len(arr)-1): if arr[num]>arr[num+1]: sort_head = True arr[num],arr[num+1]=arr[num+1],arr[num] l = [4,1,6,4,8,10,28,-3,-45] bubble_sort(l) def selection_sort(arr): spot_marker=0 while spot_marker < len(arr): for num in range(spot_marker,len(arr)): if arr[num] < arr[spot_marker]: arr[spot_marker],arr[num]=arr[num],arr[spot_marker] #print('Item Swapped') spot_marker += 1 print(arr) l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] selection_sort(l) def selection_sort(arr): spot_marker = 0 while spot_marker < len(arr): for num in range(spot_marker,len(arr)): if arr[num] < arr[spot_marker]: arr[spot_marker],arr[num]=arr[num],arr[spot_marker] spot_marker += 1 print(arr) l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] selection_sort(l)
f949e5a7df0a1d2bcb6e93ef475731c1ae707cae
UnimaidElectrical/PythonForBeginners
/Random_code_store/Dictionaries/Dictionaries_2.py
8,023
4.40625
4
# Create a mapping of state to abbreviation from click import prompt states ={ 'Oregon': 'OR', 'Florida': 'FL', 'California':'CA', 'New York': 'NY', 'Michigan': 'MI' } #Create a basic set of states and some cities in them cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville', 'TX': 'Houston', 'IL': 'Illinois' } #Add some more cities cities['NY']='New York' cities['OR']='Portland' cities['CO']='New Haven' #Add some more states # I am still wondering why this doesn't work # states['Kansas City']='KS' #states['New Mexico']='NM' # states['Oklahoma']='OK' #Print out some cities print('-'*10) print("NY State has: ", cities['NY']) print("OR State has: ", cities['OR']) print("CO State has: ", cities['CO']) #Print some states print('-'*10) print("Michigan's abbreviation is: ",states['Michigan']) print("California's abbreviation is: ", states['California']) #Do it by using the states then cities dict print('-'*10) print("Michigan has: ", cities[states['Michigan']]) print("Florida has: ", cities[states['Florida']]) #Print every state abbreviation print('-'*10) for state, abbrev in list(states.items()): print(f"{state} is an abbreviated {abbrev}") #Print every city in the state. print('-'* 10) for abbrev, city in list(cities.items()): print(f"{abbrev} has the city{city}") #Now do both at the same time print('-' * 10) for state, abbrev in list(states.items()): print(f"{state} state is abbreviated {abbrev}") print(f"and has {cities[abbrev]}") print('-' * 10) #safely get an abbreviation by state that might not be there state = states.get("Texas") if not state: print("Sorry, no Texas.") #get a city with no default value city = cities.get('TX', 'Does Not Exist') print(f"The city for the state 'TX' is: {city}") mystuff = {'apple': 'I AM THE HAPPIEST PERSON ALIVE!'} print(mystuff['apple']) ********************************** ******Dissecting Dictionaries********* d2={'spam':2, 'ham':1,'eggs':3} d3= {'food': {'ham':1, 'egg':2}} d3['food']['ham'] #d2['spam'] d2 len(d2) d2.has_key('ham') 'ham' in d3 d2.keys() d3['food']['ham'] 'ham' in d3 d2={'spam':2, 'ham':1,'eggs':3} d2['ham']=['grill','bake','fry'] #d2 del d2['eggs'] #d2 d2['brunch']='Bacon' d2 d2.values(), d2.keys() d2.values(), d2.items() d2.get('spam'), d2.get('toast'), d2.get('toast', 88) #using update: d2 d3 = {'toast':4,'muffin':5} d2.update(d3) d2 ##############:::::::::::::::::::::::##############**********################ ###:::: ###:::: ###:::: #A Language Table: ###:::: ###:::: ###:::: ##############:::::::::::::::::::::::##############**********################ table = {'Python': 'Guido Van Rossum', 'Perl': 'Larry wall', 'Tcl': 'John Ousterhout'} table language = 'Python' # creates an objects that points to the value (table array) table creator = table[language] creator second_language = 'perl' creator = table[language],second_language creator for lang in table.keys(): print (lang, '\t', table[lang]) for lang in table.items(): print (lang, '\t', table[lang]) ##############:::::::::::::::::::::::##############**********################ ##############:::::::::::::::::::::::##############**********################ ##############:::::::::::::::::::::::##############**********################ ###:::: ###:::: ###:::: #using Dictionaries for sparse data structures ###:::: ###:::: ###:::: ##############:::::::::::::::::::::::##############**********################ ##############:::::::::::::::::::::::##############**********################ ##############:::::::::::::::::::::::##############**********################ Matrix= {} Matrix[(2,3,4)] = 88 Matrix[(7,8,9)] = 99 X = 2; Y = 3; Z = 4; Matrix[(X,Y,Z)] Matrix #This will throw up an error Matrix[(2,3,6)] ''' to aviod the error messages we can use If statements try Statement dictionary get method ''' Matrix= {} Matrix[(2,3,4)] = 88 #If statements if Matrix in ((2,3,6)): # The implementation in Python 2 will be if Matrix.has_key((2,3,6)): print (Matrix[(2,3,6)]) else: print (0) #try Statement Matrix= {} Matrix[(2,3,4)] = 88 try: print (Matrix[(2,3,6)]) except KeyError: print (0) #dictionary get method Matrix= {} Matrix[(2,3,4)] = 88 #Matrix.get((2,3,4),0) Matrix.get((2,3,6),0) # The Zero being used here is to state either the main value or Zero ##############:::::::::::::::::::::::##############**********################ ###:::: ###:::: ###:::: #Using Dictionaries as records: ###:::: ###:::: ###:::: ##############:::::::::::::::::::::::##############**********################ rec = {} rec['name'] = 'mel' rec['age'] = 41 rec['Job'] = 'trainer/writer' print (rec['name']) print(rec['name'],'age') # This will print out two objects or keys in the dictionary. don't know why the second object is not allowed to sit in it's own square bracket #Nested Dictionary mel = {'name': 'Mark', 'jobs': ['trainer','writer','farmer'], 'web': 'www.rmi.net/~lutz', 'home': {'state': 'CO','zip':80501}} mel['name'] mel['jobs'] mel['jobs'][1][2] mel['home']['zip'] #Cyclic Data Structures #These are datastructures that get caught in a loop, say for instance appending a string to al already existing list with the same string L= ['grail'] L.append(L) L Immutable calls cannot be changed in place but there are ways to mitigate this, but it may be costly for scaling up T = (1,2,3) T[2] = 4 #We should expect an error here T = T[:2] + (4,) #We should expect to get (1,2,4) here T ''' def make_album(artist_name,album_title,track_number=''): album_name = {name:artist_name, title:album_title,track:track_number} #return full_name.title() while True: if track_number: full_names = artist_name + '' + album_title + '' + track_number #return full_names.title() else: full_names = artist_name + '' + album_title #return full_names.title() #artist_name = input("Artist Name: ") #album_title = input("Album Title: ") music=make_album(artist_name,album_title) print(music) #Album= input(f'Please enter the album name and album title to search for: ') #f'Please enter the album name and album title to search for: ', print(make_album(xzibit, man vs machine,10)) ''' def make_album(artist, title): '''This is to make a dictionary of album''' album_dict = { 'artist':artist.title(), 'title':title.title(), } return album_dict album = make_album('greenday','shadow') print(album) album = make_album('metallica','unbellivable') print(album) def make_albumTracks(artist,title,tracks=0): '''This makes a dictionary of artist titles and tracks''' album_dict_tracks={ 'album':artist.title(), 'title':title.title(), } if tracks: album_dict_tracks['tracks'] = tracks return album_dict_tracks album = make_album('greenday','shadow',tracks=10) print(album) album = make_album('metallica','unbellivable') print(album) def make_album(artist, title,track=0): album_dict={ 'artist':artist.title(), 'title':title.title(), } if track: album_dict['track'] = track return album_dict title_prompt = "/nWhat album are you thinking of: " artist_prompt = "Who is the artist? " print("Enter quit at any time you want to stop") while True: title = input(title_prompt) if title == 'quit': break artist= input(artist_prompt) if artist == 'quit': break album=make_album(artist,title) print(album)
b3508867c0fb6b42dc531a7fed445aa5d36d9d70
UnimaidElectrical/PythonForBeginners
/Algorithms/Sorting_Algorithms/merge_sort.py
5,385
4.4375
4
#Merge sort #The implementation of merge sort will be done in small chuncks so a new user can really grasp the full picture def merge_sorted(arr1,arr2): print("Merge function called with lists below:") print(f"left: {arr1} and right {arr2}") sorted_arr=[] i,j=0,0 if arr1[i] < arr2[j]: sorted_arr.append(arr1[i]) i +=1 else: sorted_arr.append(arr2[j]) j+=1 print(f"Left list index i is {i} and has value: {arr1[i]}") print(f"Right list index j is {j} and has value: {arr2[j]}") return sorted_arr # xxxxxxxxxxxxxxxx Program Execution xxxxxxxxxxxxxxxx l1=[2,4,6,8,10] l2=[1,3,5,7,8,9] print(f"Un-merged list: {merge_sorted(l1,l2)}") #Steps: #1, Compare first element in each list and append smaller elements #2, Using indices and an interior, perform same comparison for all elements in both lists #3, Move marker up by 1 position after smaller number is found #4, copy remaining list once comparisons are complete and there are items still remaining in one of the lists Part 2 def merge_sorted(arr1,arr2): print("Merge function called with lists below:") print(f"left: {arr1} and right {arr2}") sorted_arr=[] i,j=0,0 while i < len(arr1) and j < len(arr2): # print(f"Left list index i is {i} and has value: {arr1[i]}") # print(f"Right list index j is {j} and has value: {arr2[j]}") # i+=1 # j+=1 if arr1[i] < arr2[j]: sorted_arr.append(arr1[i]) i +=1 else: sorted_arr.append(arr2[j]) j+=1 # print(f"Left list index i is {i} and has value: {arr1[i]}") # print(f"Right list index j is {j} and has value: {arr2[j]}") print(sorted_arr) return sorted_arr # xxxxxxxxxxxxxxxx Program Execution xxxxxxxxxxxxxxxx l1=[2,4,6,8,10] l2=[1,3,5,7,8,9] print(f"Un-merged list: {merge_sorted(l1,l2)}") #part 3 #This will catch the cases not covered in the previous steps. The cases where l1 or l2 are empty lists def merge_sorted(arr1,arr2): print("Merge function called with lists below:") print(f"left: {arr1} and right {arr2}") sorted_arr=[] i,j=0,0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: sorted_arr.append(arr1[i]) i +=1 else: sorted_arr.append(arr2[j]) j+=1 while i<len(arr1): sorted_arr.append(arr1[i]) i+=1 while j<len(arr2): sorted_arr.append(arr2[j]) j+=1 print(sorted_arr) return sorted_arr # xxxxxxxxxxxxxxxx Program Execution xxxxxxxxxxxxxxxx l1=[2,4,6,8,10,11,12,13,14] l2=[1,3,5,7,8,9,15,16] print(f"merged list: {merge_sorted(l1,l2)}") #part 4 def merge_sorted(arr1,arr2): #Wrapping these in a function print("Merge function called with lists below:") print(f"left: {arr1} and right {arr2}") sorted_arr=[] i,j=0,0 #seperating the blocks of code that compares and combines two lists #here we are checking for the largest of each element in the list this is possible because the list is already sorted. while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: sorted_arr.append(arr1[i]) i +=1 else: sorted_arr.append(arr2[j]) j+=1 #Here we are checking if all the elements of the first list are more than those of the second list #The missing exception being that the second list is empty or we have bigger elements at the end of the first list while i<len(arr1): sorted_arr.append(arr1[i]) i+=1 # Here we are checking if all the elements of the Second list are more than those of the first list. # This includes cases where the first list is empty while j<len(arr2): sorted_arr.append(arr2[j]) j+=1 print(sorted_arr) return sorted_arr # xxxxxxxxxxxxxxxx Program Execution xxxxxxxxxxxxxxxx l1=[2,4,6,8,10,11,12,13,14] l2=[1,3,5,7,8,9,15,16] print(f"merged list: {merge_sorted(l1,l2)}") def divide_arr(arr): if len(arr) < 2: print(f"Base condition reached with {arr[:]}") print(f"{arr[:]}") return arr[:] else: middle = len(arr)//2 print("Current list to work with:", arr) print("Left split:", arr[:middle]) print("Right split: ", arr[middle:]) l1 = divide_arr(arr[:middle]) l2 = divide_arr(arr[middle:]) l= [8,6,7,2,5] #[3,7,5,9,1,4,2,8,10] # [3,7,5,-3,9,1,-4,4,-5,2,8,-2,10,-1] # divide_arr(l) #print(arr) Complete Merge Sort def merge_sorted(arr1,arr2): sorted_arr = [] i,j=0,0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: sorted_arr.append(arr1[i]) i+=1 else: sorted_arr.append(arr2[j]) j+=1 #print(sorted_arr) while i < len(arr1): sorted_arr.append(arr1[i]) i+=1 while j < len(arr2): sorted_arr.append(arr2[j]) j+=1 print(sorted_arr) return sorted_arr def divide_arr(arr): if len(arr) < 2: return arr[:] else: middle = len(arr)//2 l1 = divide_arr(arr[:middle]) l2 = divide_arr(arr[middle:]) return merge_sorted(l1,l2) l =[3,7,5,-3,9,1,-4,4,-5,2,8,-2,10,-1] #[2,3,6,8,10] #l2 = [1,3,5,7,8,9] print(divide_arr(l))
cb50f49fe64e2121093ea0ccbea3bf7ecc6c7135
UnimaidElectrical/PythonForBeginners
/Algorithms/Recursion.py
5,306
4.25
4
************************************************** # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) def traverse(node, output): if node is None: # we are visiting an empty child return # every recursive function needs a base case # print("VISITING", node.val) # preorder traversal traverse(node.left, output) # print("VISITING", node.val) # inorder traversal traverse(node.right, output) output.append(node.val) # print("VISITING", node.val) # post order traversal return output traverse(root) # traverse(root) # root = TreeNode(1) # root.right = TreeNode(2) # root.right.left = TreeNode(3) # import sys # sys.setrecursionlimit(10) # def traverse(node): # if node is None: # # we are visiting an empty child # return # # every recursive function needs a base case # print("VISITING", node, node.val) # traverse(node.left) # traverse(node.right) # traverse(root) Python program to do inorder traversal without recursion # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Iterative function for inorder tree traversal def inOrder(root): # Set current to root of binary tree current = root stack = [] # initialize stack done = 0 while True: # Reach the left most Node of the current Node if current is not None: # Place pointer to a tree node on the stack # before traversing the node's left subtree stack.append(current) current = current.left # BackTrack from the empty subtree and visit the Node # at the top of the stack; however, if the stack is # empty you are done elif(stack): current = stack.pop() print(current.data, end=" ") # Python 3 printing # We have visited the node and its left # subtree. Now, it's right subtree's turn current = current.right else: break print() # Driver program to test above function """ Constructed binary tree is root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) inOrder(root) """ ***************************** RECURSION EXPLAINED************************* Recursion is a function that calls itself It calls itself till it does not call itself anymore. i.e the the conditon runs out The condition where it stops calling itself is called the base ccase when thinking of recursion, try to think about the base case first #Implementing a countdown timer using recursion import time def recur_countdown_timer(n): if n==0: return n else: print(n) time.sleep(1) return recur_countdown_timer(n-1) #z=5 print(recur_countdown_timer(5)) #Implementing a countdown timer using iteration import time def iter_countdown_timer(n): while n>0: print(n) time.sleep(1) n -=1 print(n) z=5 print(f"Counting down from {z}: ") iter_countdown_timer(z) Using Recursion to implement a Factorial ********FACTORIAL********* A factorial is a product of an interger n, and all the intergers below it Factorial of 4 => 4*3*2*1 = 24 It is denoted by the symbol '!' after the number, so 5 factorial would be written as '5!' Factorial of 0 is 1 What will be the base case if we were to do this recursively? the base case here will be n! = n* (n-1)! for n> 0 factorial(n) = n * factorial(n-1) for n > 0 def factorial_recur(n): if n==0: return 1 #This is to solve the first condition where the factorial of zero is one else: return n * factorial_recur(n-1) z=0 #expecting 1 print(f"The value of {z}! is {factorial_recur(z)}") z=1 #expecting 1 print(f"The value of {z}! is {factorial_recur(z)}") z=5 #expecting 120 print(f"The value of {z}! is {factorial_recur(z)}") *************FIBONACCI SERIES******************* Recursive Implementation Fibonacci Series is a series of intergers value of the nth interger can be found by adding the values of the two previous intergers in the series the series starts off with 0, 1, 1, 2, 3, 5, 8, 13 ... What will be the base case if we did this recursively First thing to look out for when doing a recursion is to look for the base cases Base Case if n = 0, return 0 if n = 1, return 1 doing this recursively def fib_recur(n): if n==0: return 0 elif n==1: return 1 else: return fib_recur(n-1) + fib_recur(n-2) def fib_runner(z): print(f"The {z}th number of the fibonacci sequence is {fib_recur(z)}") z=0 fib_runner(z) z=1 fib_runner(z) z=50 fib_runner(z) Getting the rest of the fib series for every n> 1: fib(n) = fib(n-1) + fib(n-2) fib(2) = 1 + 0 --> fib(2) = fib(1) + fib(0) fib(3) = 1 + 1 --> fib(3) = fib(2) + fib(1) fib(4) = 2 + 1 --> fib(4) = fib(3) + fib(2) fib(5) = 3 + 2 --> fib(5) = fib(4) + fib(3) fib(6) = 5 + 3 --> fib(6) = fib(5) + fib(4) fib(7) = 8 + 5 --> fib(7) = fib(6) + fib(5) fib(8) = 1 + 8 --> fib(8) = fib(7) + fib(6)
38baa3eb890530cac3a056140908e23015070428
UnimaidElectrical/PythonForBeginners
/Random_code_store/If_Else_Statement/If_Else_statement.py
2,375
4.375
4
"""This mimicks the children games where we are asked to choose our own adventure """ print("""You enter a dark room with two doors. Do you go through door #1 or door #2?""") door = input ("> ") if door == "1": print("There's a giant bear here eating a cheese cake.") print("What do you want to do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print("The bear eats your face off. Good job!") elif bear=="2": print("The bear eats your leg off. Good job!") else: print(f"Well doing, {bear} is probable better.") print("Bear runs away.") elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.") insanity = input("> ") if insanity == "1" or insanity =="2": print("Your body survives powered by the mind of jello.") print("Good Job!") else: print("The insanity rots your eyes into a pool of muck.") print("Good Job!") else: print("You stumble around and fall on a knife and die. Good Job!") # Else Statements # break # continue # The else statement is most commonly used along with the if statement, but it can also follow a for or while loop, which gives it a different meaning. # With the for or while loop, the code within it is called if the loop finishes normally (when a break statement does not cause an exit from the loop). Example: for i in range(10): if i == 999: break else: print("Unbroken 1") for i in range(10): if i == 5: break else: print("Unbroken 2") # The first for loop executes normally, resulting in the printing of "Unbroken 1". # The second loop exits due to a break, which is why it's else statement is not executed. # Try # Except # The else statement can also be used with try/except statements. # In this case, the code within it is only executed if no error occurs in the try statement. # Example: #Example2: try: print(1) except ZeroDivisionError: print(2) else: print(3) try: print(1/0) except ZeroDivisionError: print(4) else: print(5) # Example 2: try: print(1) print(1 + "1" == 2) print(2) except TypeError: print(3) else: print(4)
0f509b10fd23df81cd306ea05a6ae07e6b9c13b3
UnimaidElectrical/PythonForBeginners
/Random_code_store/Lists/In_Operators.py
453
4.34375
4
#The In operator in python can be used to determine weather or not a string is a substring of another string. #what is the optcome of these code: nums=[10,9,8,7,6,5] nums[0]=nums[1]-5 if 4 in nums: print(nums[3]) else: print(nums[4]) #To check if an item is not in the list you can use the NOT operator #In this case the pattern doesn't matter. nums=[1,2,3] print(not 4 in nums) print(4 not in nums) print(not 3 in nums) print(3 not in nums)
cca57e8aa3e2772372aea9fc82223e9d8e6e9a0f
srgiola/Python-on-Raspberry-PI-OS
/Lab 6.py
679
3.5625
4
from datetime import datetime import time from os import system import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(3, GPIO.OUT) # este pin es de salida GPIO.setup(2, GPIO.IN) #Este pin es una entrada. estadoAnterior = 0 while True: tiempo = datetime.now() if GPIO.input(2) and estadoAnterior == 0: GPIO.output(3, False) print("Se ha detectado una interrupcion de sensor a las", str(tiempo)) estadoAnterior = 1 elif not(GPIO.input(2)) and estadoAnterior == 1: GPIO.output(3, True) print("Se ha detectado una continuidad de sensor a las", str(tiempo)) estadoAnterior = 0 GPIO.cleanup()
1c3bd79a6f6177339484a4fc5e00432aa2703093
KeerthanaP/pickyourtrail
/src/solutions/minimum_unique_array_sum.py
4,655
3.96875
4
""" Minimum unique sum array Given an array, you must increment any duplicate elements until all its elements are unique. In addition, the sum of its elements must be the minimum possible within the rules. For example, if arr = [3, 2, 1, 2, 7], then arr = [3, 2, 1, 4, 7] and its elements sum to a minimal value of 3 + 2 + 1 + 4 + 7 = 17 """ __author__ = "Keerthana Prabhakaran" class Array(object): """ :Brief: Array class to hold data and sorting algorithms :params: data list/tuple length int :return: None :rtype: None """ RUN = 32 def __init__(self, data=None, length=0): if data: self.data = list(data) else: self.data = [] self.__length = len(self.data) def length(self): """ :Brief: Method to return length of data array :return: __length :rtype: int """ return self.__length def __insertion_sort(self, left=0, right=None): """ :Brief: Sequentially iterates through the array to insert an unordered element to the ordered sub array thereby modifying the original array :param left: start index of array to consider :type left: int :param right: end index of array to consider :type right: int :return: None :rtype: None """ if not right: right = len(self.data) - 1 for i in xrange(left + 1, right + 1): temp = self.data[i] j = i - 1 while self.data[j] > temp and j >= left: self.data[j + 1] = self.data[j] j -= 1 self.data[j + 1] = temp @staticmethod def __merge(arr, l, m, r): len1, len2 = m - l + 1, r - m left, right = [], [] for i in xrange(0, len1): left.append(arr[l + i]) for i in xrange(0, len2): right.append(arr[m + 1 + i]) i, j, k = 0, 0, l while i < len1 and j < len2: if left[i] <= right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 while i < len1: arr[k] = left[i] k += 1 i += 1 while j < len2: arr[k] = right[j] k += 1 j += 1 def sort(self): """ :Brief: Time sort algorithm - sorts sub array in groups of RUN with insertion sort merges them to form the final sorted array modifying the original array :return: None :rtype: None """ for i in xrange(0, self.__length, Array.RUN): self.__insertion_sort(i, min((i + Array.RUN - 1), (self.__length - 1))) size = Array.RUN while size < self.__length: for left in xrange(0, self.__length, 2 * size): mid = left + size - 1 right = min((left + 2 * size - 1), (self.__length - 1)) Array.__merge(self.data, left, mid, right) size = 2 * size def sorted(arr): """ :Brief: sorts the given list of array without changing the original list :param arr: list of items that needs to be sorted :type arr: list :return: list of sorted items :rtype: list """ arr.sort() # arr.data.sort() return arr class Manipulation(object): """ :Brief: Open for extension for any manipulation functions """ @staticmethod def get_minimum_unique_sum(arr): """ :Brief: to get the minimal sum of an array of unique elements. :param arr: list of integers :type arr: list :return: minimal_sum :rtype: int """ arr = Array(arr) arr.sort() minimal_sum = arr.data[0] prev = arr.data[0] for i in xrange(1, arr.length()): if arr.data[i] <= prev: prev += 1 minimal_sum += prev else: minimal_sum += arr.data[i] prev = arr.data[i] return minimal_sum if __name__ == "__main__": import sys if len(sys.argv) == 2 and sys.argv[1] == "default": input_data = """5 3 2 1 4 2""" input_arr = map(int, input_data.strip().split("\n")[1:]) else: input_arr = [] elements = int(raw_input().strip()) for val in range(elements): input_arr.append(int(raw_input().strip())) print Manipulation.get_minimum_unique_sum(input_arr)
b1f80cf1bc0d144789dc230085f694fe9d94a673
KeshavSharma-IT/Python_all_concept
/2.Data_Type.py
2,169
4.0625
4
# veriables # x=5 # z=5.5 # p=x+z # print(p) # print(x) # y="keshav" # print(y) #DATA TYPES python is dynamic type means u not need to define any veriable #1.Numbers # x=12 # # print(type(x)) # print(type(p)) # m=12 # print(type(m)) # m=float(12) # print(type(m)) #2.String # a="k" # b="keshav" # c='keshav2' # d='''hi this is # multible line # function''' # print(type(a)) # print(type(b)) # print(type(c)) # print(type(d)) # print(a) # print(b) # print(c) # print(d) #method in string # w="water" # k="keshav sharma" # print(w.upper()) # print(w.title()) # print(k.split()) # print(k.count('s')) # print(k.find('a')) # print(k.endswith('a')) # indexing # x="keshav" # print(x[1]) # print(x[-1]) # print(x.replace('e','a')) # print(x) #split # y="hello keshav" # print(y[0:5]) # print(y[6:]) # print(y[:5]) #formating # x="my" # y="name" # z="is" # w="keshav" # o=23 # p=x+" "+y+" "+z+" "+w # print(p) # # print(f"{x} {y} {z} {w}".format(x,y,z,w)) # print(f"AGE of {w} is {o}".format(w,o)) #list-changeable. Allows duplicate members. # x=["red","blue","green","white"] # print(x) # print(type(x)) # print(x[1]) # print(x[-1]) # print(x[1:3]) # print(len(x)) # print(x.pop()) # print(x.append("yellow")) # print(x) # print(x.remove("yellow")) # print(x) # del x # print(x) #tuple- unchangeable. Allows duplicate members. # x=("red","blue","green","white") # print(x) # print(type(x)) # print(x[1]) # print(x[-1]) # print(x[1:3]) # print(len(x)) # # cannnot use this print(x.pop()) # # cannnot use this print(x.append("yellow")) # print(x) # cannnot use this print(x.remove("yellow")) # dictonary- key :value,changeable. No duplicate members. # x={"number":1, # "name":"blue" # ,"age":20} # print(x["name"]) # # x["age"]=55 # print(x["age"]) # print(len(x)) # x["year"]=1990 #add # print(x) # print(x.pop("age")) # print(x) # print(x.popitem()) # print(x) #set unordered, unchangeable, and do not allow duplicate values. # x={1,2,3,4,4} # print(x) #it will not print 4 twice rest is same # 3.Boolean print(4>5) print(1<0)
ff97e60837bf32c1dc1f65ef8afda4f658a7116b
lchristopher99/CSE-Python
/CSElab6/turtle lab.py
2,207
4.5625
5
#Name: Jason Hwang, Travis Taliancich, Logan Christopher, Rees Hogue Date Assigned: 10/19/2018 # #Course: CSE 1284 Section 14 Date Due: 10/20/2018 # #File name: Geometry # #Program Description: Make a geometric shape #This is the function for making the circle using turtle def draw_circle(x, y, r): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.circle(r) turtle.penup() #This is the function for making the rectangle using turtle def draw_rectangle(x, y, width, height): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(width) turtle.left(90) turtle.forward(height) turtle.left(90) turtle.forward(width) turtle.left(90) turtle.forward(height) turtle.penup() #This is the function for making the point using turtle def draw_point(x, y, size): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(size) turtle.left(180) turtle.forward(size * 2) turtle.left(180) turtle.forward(size) turtle.left(90) turtle.forward(size) turtle.left(180) turtle.forward(size * 2) #This is the function for making the line using turtle def draw_line(x1, y1, x2, y2): import turtle turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) turtle.penup() #This is the function for making the triangle using turtle. def draw_triangle(x, y, side): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(side) turtle.left(120) turtle.forward(side) turtle.left(120) turtle.forward(side) turtle.penup() #the function that will call all of the functions def main(): draw_circle(-100, -100, 200) draw_circle(100, 100, 200) draw_rectangle(10, 10, 50, 70) draw_rectangle(90, 90, 100, 150) draw_point(0, 0, 50) draw_point(70, 70, 50) draw_line(20, 20, 30, 70) draw_line(300, 200, 100, 150) draw_triangle(100, 100, 50) draw_triangle(-100, -150, 50) main()
92ceeb475d5cb45cebb83f77e3e08c4f9fd2227d
lchristopher99/CSE-Python
/CSElab10/reading_level.py
1,323
3.78125
4
# Name: Logan Christopher Date Assigned: 11/14/18 # # Course: CSE 1284 Sec 11 Date Due: 11/14/18 # # File name: reading_level.py # # Program Description: Program calculates reading level of a given text. import urllib from urllib.request import urlopen def calc_level(ASL, ASW): level = (0.39 * ASL) + (11.8 * ASW) - 15.59 return level def get_ASL(word_list): sent_count = len(word_list) word_count = 0 for sent in word_list: word_count += len(sent) ASL = word_count / sent_count return ASL, word_count def get_ASW(word_list, word_count): syl_count = 0 for sent in word_list: for word in sent: if len(word) % 4: syl_count += len(word) % 4 ASW = syl_count / word_count return ASW def get_wordList(text): sent_list = text.split('.') i = 0 word_list = [] for line in sent_list: word_list.append(sent_list[i].split(' ')) i += 1 return word_list def main(): url = 'http://www.gutenberg.org/cache/epub/18857/pg18857.txt' page = urllib.request.urlopen(url) text = page.read().decode('utf8') word_list = get_wordList(text) ASL, word_count = get_ASL(word_list) ASW = get_ASW(word_list, word_count) level = calc_level(ASL, ASW) print('Average syllables per word:', ASW) print('Average sentence length:', ASL) print('Reading level:', level) main()
55054417d6e1122b865b5ae3812409a6e63c9589
julianl092/Blocking
/universalalgorithm.py
4,407
3.59375
4
from cs50 import SQL import itertools import math #https://networkx.github.io/ #NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. import networkx as nx db = SQL("sqlite:///blocking.db") #Defines function to return the total utility of any blocking group OR subgroup of users def utility(combo): #Default utility is zero - will remain as such if none of the users in combo have ranked any of the others util = 0 #For every member in the combo, loop iterates for every member in the combo. for i in combo: member = db.execute("SELECT * from responses WHERE id = :id", id = i)[0] for j in combo: for k in range(1, 8): #Key iterates through all the possible id columns of the "responses" table, from id1 to id7 key = f"id{k}" #If the ID number found in id1 to id7 matches the ID number of user "j", adds the corresponding rating to total utility if str(j) == str(member[key]): util += member[f"rating{k}"] return (util) #Defines function to create a graph from an iterable and then return the optimal matching of that graph def match(inlist, G, b): for j in inlist: #Adds a graph node for every element of the input list G.add_node(j) #Subsequent code manages the edge creation between the nodes of the graph. #Ultimately, we must create a list of ints called "combo" to pass into the utility function. #If on matching Level1, then input elements are single ID numbers and temp1 can be a list with 1 int if isinstance(j, int): temp1 = [j] elif isinstance(j, tuple): #If on matching Level3, input elements are tuples of two tuples - generate list of 4 ints from input. if b: temp1 = [item for sublist in j for item in sublist] #If on matching Level2, input elements are tuples - generate list of 2 ints from tuple. else: temp1 = list(j) for k in inlist: #Edge creation code runs for every element EXCEPT for the current element. if j == k: continue else: #Same idea as the loop with j. if isinstance(k, int): temp2 = [k] elif isinstance(k, tuple): if b: temp2 = [item for sublist in k for item in sublist] else: temp2 = list(k) #Concatenates temp1 and temp2. combo = temp1 + temp2 #Creates edge between j & k, determines weight by calling the utility function on combo. G.add_edge(j, k, weight = utility(combo)) #After weighted graph is created, calls NetworkX max_weight_matching function, which divides the nodes into pairs such that the total #weight of the matched edges is optimal. matching = nx.algorithms.matching.max_weight_matching(G, maxcardinality=True) return (matching) def main(): #Initializes empty list and three NetworkX graphs persons = [] G = nx.Graph() F = nx.Graph() H = nx.Graph() b = False #Generates list of ID numbers all persons that have filled out the form responses = db.execute("SELECT * FROM responses WHERE id > 0") for response in responses: persons.append(response["id"]) #Level 1 - matches all individuals into optimal PAIRS Level1 = match(persons,G, b) print(Level1) #Level 2 - matches the pairs to form optimal QUARTETS Level2 = match(Level1, F, b) #Sets b to true to inform Level3 about the structure of the input list b = True #Level 3 - matches the quartets to form optimal OCTETS Level3 = match(Level2, H, b) #Breaks down all matched individuals using list comprehension, generates a list of all individuals that were NOT matched matched = [item for sublist1 in Level3 for sublist2 in sublist1 for sublist3 in sublist2 for item in sublist3] others = [x for x in persons if x not in matched] #Passes list containing two elements - firstly, the octet matching, and a list of up to 7 "other" individuals not matched by algorithm. return [Level3, others] if __name__ == "__main__": main()
9aec5ccf0463820a7d47445080d6d18919cbf57c
taojingcong/homework
/计算理论/第一次作业/RE-NFA.py
16,171
3.75
4
""" 题目2:正则表达式转NFA """ import copy EPSILON = 'ϵ' class state(object): __state_no: int = 0 # 建议的类型,初始为0 def __init__(self): state.__state_no = state.__state_no + 1 # 每有一个新的状态就加1 self.name: str = str(state.__state_no) # 与下面对应,直接会输出名字 self.func = {} def __str__(self): return '(state-' + str(self.name) + ')' def append(self, alphabet: str, succ): # 添加转移函数 try: self.func[alphabet].append(succ) # 添加succ except KeyError: # 如果字典中没有key就创建一个 self.func[alphabet] = [succ] def eps_closure(self) -> set: global EPSILON current: set = {self} new_set: set = {self} # 如果没有通过epsilon转移的函数,则返回它自身 try: self.func[EPSILON] except KeyError: return {self} # 不断向后扩展,直至这个集合不再变化 # 不可采用递归方法,假设两个状态相互通过epsilon转移,则会导致死循环 while True: for st in current: try: new_set = new_set.union(st.func[EPSILON]) except KeyError: pass new_set.union(current) if len(new_set.difference(current)) == 0: break current = new_set return new_set class nfa(object): def __init__(self, all_states: set, alpha: set, start_state: state, final_states: set): self.all_states = all_states self.alpha = alpha self.start_state = start_state self.final_states = final_states def printf(self): """ 向控制台输出该NFA的信息,包括字母表,初态,终态和转移函数信息 """ print('Alphabet = {' + ','.join([a for a in self.alpha]) + '}') print('Start State = ' + str(self.start_state)) print('Final States = {' + ','.join([str(fs) for fs in self.final_states]) + '}') print('Transfer Functions:') for s in self.all_states: for f in s.func: # f是转移的trigger fun = s.func.get(f) if fun is not None: # 即有转移的目标 print('\t' + str(s) + '|---' + str(f) + '--->' + ','.join([str(e) for e in fun])) print('\n') @staticmethod def concat(a1, a2): global EPSILON if a1 is None: return a2 if a2 is None: return a1 """ 依据课本P36关于正则表达式连接运算的证明 新NFA的: 1.全部状态为原来两个NFA的状态的并集 2.字母表为原来两个NFA的字母表并集(一般字母表二者是一样的) 3.起始状态为前者的起始状态 4.接受状态为后者的接受状态 5.转换函数为原来两个NFA的转换函数的并集,此外还有从前者每一个接受状态到后者起始状态的转换 """ n_alpha: set = a1.alpha.union(a2.alpha).union(EPSILON) n_start_state: state = a1.start_state n_final_states: set = a2.final_states for s in a1.final_states:#连接a2的初态和a1的终态 s.append(alphabet=EPSILON, succ=a2.start_state) n_all_states: set = a1.all_states.union(a2.all_states) # 应当先连接a1的终态和a2的初态,先进行union操作会使这部分连接无法更新到所需的新NFA中 return nfa(all_states=n_all_states, alpha=n_alpha, start_state=n_start_state, final_states=n_final_states) @staticmethod def concat_multiple(nfa_stack: list): # 多个NFA的顺序连接,自参数栈顶开始 if len(nfa_stack) < 1: raise ValueError automata = nfa_stack.pop() while len(nfa_stack) > 0: automata = nfa.concat(automata, nfa_stack.pop()) return automata @staticmethod def union(a1, a2): global EPSILON if a1 is None: return a2 if a2 is None: return a1 """ 依据课本P35关于正则表达式并运算的证明 新NFA的: 1.全部状态为原来两个NFA的状态的并集,以及一个新的作为起始状态的状态 2.字母表为原来两个NFA的字母表并集(一般字母表二者是一样的) 3.起始状态为新生成的状态 4.接受状态为二者接受状态的并集 5.转换函数为原来两个NFA的转换函数的并集,此外还有从新起始状态到原来二者各自起始状态的转换 """ n_start_state: state = state() n_all_states: set = {n_start_state}.union(a1.all_states).union(a2.all_states) n_alpha: set = a1.alpha.union(a2.alpha).union(EPSILON) n_final_states: set = a1.final_states.union(a2.final_states) n_start_state.append(alphabet=EPSILON, succ=a1.start_state) n_start_state.append(alphabet=EPSILON, succ=a2.start_state) return nfa(all_states=n_all_states, alpha=n_alpha, start_state=n_start_state, final_states=n_final_states) @staticmethod def union_multiple(nfa_stack: list): # 多个NFA的顺序并操作,自参数栈顶开始 if len(nfa_stack) < 1: raise ValueError automata = nfa_stack.pop() while len(nfa_stack) > 0: automata = nfa.union(automata, nfa_stack.pop()) return automata @staticmethod def closure(automata): global EPSILON """ 依据课本P37关于正则表达式闭包运算的证明 新NFA的: 1.全部状态为原来两个NFA的状态的并集,以及一个新的作为起始状态的状态,并且这个状态亦是一个接受状态 2.字母表保持不变(如果原来没有ϵ则加入进去) 3.起始状态为新生成的状态 4.接受状态为原来接受状态外加新生成的状态 5.转换函数为原来的转换函数集以及更新后的所有接受状态到原来起始状态的转换 """ old_start_state: state = automata.start_state n_start_state: state = state() n_all_states: set = {n_start_state}.union(automata.all_states) n_alpha: set = automata.alpha.union(EPSILON) n_final_states: set = automata.final_states.union({n_start_state}) for s in n_final_states: s.append(alphabet=EPSILON, succ=old_start_state) return nfa(all_states=n_all_states, alpha=n_alpha, start_state=n_start_state, final_states=n_final_states) @staticmethod def get_alpha(alpha: str): # 获取仅接受一个字母或epsilon的NFA if len(alpha) != 1: raise ValueError global EPSILON if alpha == EPSILON: uni_s: state = state() return nfa(all_states={uni_s}, alpha=set(EPSILON), start_state=uni_s, final_states={uni_s}) else: s = state() e = state() s.append(alphabet=alpha, succ=e) return nfa(all_states={s, e}, alpha={alpha}, start_state=s, final_states={e}) # def match(self, string: str) -> bool: # current_states: set = {self.start_state} # # def has_final(sets: set, final: set) -> bool: # for st in sets: # if st in final: # return True # return False # # for ch in string: # new_states: set = set([]) # # 对当前状态集里的每一个状态,对从此状态出发的所有转移进行遍历 # # 如果某个状态的转移所接受的字母是当前字符,就把后继状态加入到新的状态集里面 # for st in current_states: # # 先扩展当前状态的epsilon闭包。如果转换成DFA,闭包内的状态和当前状态实际上是DFA中的同一个状态 # new_states = new_states.union(st.eps_closure()) # current_states = copy.deepcopy(new_states) # new_states.clear() # succ: bool = False # 标记,如果当前状态集里的状态均不接受当前字符,则匹配失败 # for st in current_states: # for key in st.func: # if key == ch: # succ = True # for sss in st.func[key]: # new_states = new_states.union(sss.eps_closure()) # if not succ: # return False # current_states = copy.deepcopy(new_states) # # 检查,如果当前状态集里包含终态,则识别成功,输入串符合指定的正则语言 # if has_final(current_states, self.final_states): # return True # return False class regex(object): def __init__(self, exp: str = EPSILON): self.exp = exp def compile(self) -> nfa: """ 非递归方法,由当前正则表达式对象生成对应的NFA 由于是直接连接,因此会产生一定量的多余状态 """ """ 以下是非递归过程中用到的数据结构 """ # 保存识别过程中产生的NFA nfa_stack = [] # 标志栈,元素为二分量的元组。记录识别过程中NFA栈对应位置的括号层级,以及连接标志 # 格式为:(当前括号层级,当前连接标志) # 括号层级:每嵌套一层则层级加大,遇左括号自增,右括号自减 # 连接标志:由于并运算符|的存在,需要在遇到右括号以及表达式结束时 \ # 将栈顶若干个括号层级与连接标志均相同的NFA进行连接操作,\ # 之后再将栈顶若干个括号层级相同的NFA进行并操作,因此需要标记栈内哪些NFA是直接连接的 flag_stack = [] # 为了区分不同括号内的并运算数量,这里需要标记下来进入括号时当前的连接标志,退出这一层时以便恢复 concat_stack = [] non_alpha: list = ['(', ')', '|', '*'] # 这里记录的是非字母符号 current_level = 0 # 当前的括号层级 current_concat_flag = 0 # 识别当前的连接的标记,每次遇到并运算符才发生改变 # 考虑到正则表达式中出现的字母连接是没有符号表示的,需要判断是否为连接的合适时机 def reduce_concat(): nonlocal current_concat_flag, current_level, flag_stack, nfa_stack tmp_s = [] # 弹出所有和当前栈顶concat值及level值均相同的NFA,进行连接操作,然后压入 while len(flag_stack) > 0 \ and flag_stack[-1][0] == current_level \ and flag_stack[-1][1] == current_concat_flag: tmp_s.append(nfa_stack.pop()) flag_stack.pop() nfa_stack.append(nfa.concat_multiple(tmp_s)) flag_stack.append((current_level, current_concat_flag)) def reduce_union(): nonlocal current_concat_flag, current_level, flag_stack, nfa_stack tmp_s = [] # 弹出所有当前栈顶level值相同的NFA进行并操作,然后压入,再压入该括号之前的concat值以及新的level值 while len(flag_stack) > 0 and flag_stack[-1][0] == current_level: tmp_s.append(nfa_stack.pop()) flag_stack.pop() nfa_stack.append(nfa.union_multiple(tmp_s)) # 循环处理输入符号 for ch in self.exp: if ch not in non_alpha: """ 如果当前输入符号是一个字母(或epsilon),则生成一个NFA并入栈,同时入栈括号层级以及连接标志数 """ automaton = nfa.get_alpha(ch) nfa_stack.append(automaton) flag_stack.append((current_level, current_concat_flag)) continue if ch == '*': """ 如果当前输入符号是闭包符号*,则从栈顶取出最后入栈的NFA,对其进行闭包操作后再入栈 保证仅取出栈顶的NFA即可,可以证明闭包操作仅影响栈顶NFA,因此标记栈无需进行操作 """ automaton = nfa_stack.pop() automaton = nfa.closure(automaton) nfa_stack.append(automaton) continue if ch == '(': """ 如果当前输入符号是左括号(,直接自增括号层级,并入栈当前的连接标志,无需其他操作 """ concat_stack.append(current_concat_flag)# current_level = current_level + 1 current_concat_flag = current_concat_flag + 1 continue if ch == '|': """ 如果当前输入符号是并运算符|,则需要将目前栈内顶部若干个连接标记数与当前对应值相同的NFA全部取出并进行连接操作 再改变当前连接标记 注意:考虑到括号带来的层级改变,需要同时保证括号层级和连接标记均一致 """ # 把栈顶所有与当前level和concat值一样的全部弹出并进行连接连接,再压入栈中,相应个数的level和concat也弹出,然后压入一个level和concat值 reduce_concat() # 由于进行了并操作,后续的NFA不应再与栈内的NFA进行连接,使连接标记数自增以示区分 current_concat_flag = current_concat_flag + 1 continue if ch == ')': """ 如果当前的输入符号是右括号): 首先:假设当前括号内遇到过并操作符,则需要把连接标志及括号层级都与当前对应两值相同的先弹出,连接后再入栈 接着:此时栈顶所有括号层级相同的NFA应全部弹出进行并操作,然后将结果入栈 以上的栈操作均同步进行括号层级栈以及连接标记栈的操作 """ # 类似编译器语法分析阶段的归约操作,将栈内本层括号范围内的NFA进行连接或并操作以生成一个NFA reduce_concat() reduce_union() # 恢复concat值为匹配的括号部分之前的值 current_concat_flag = concat_stack.pop() current_level = current_level - 1 flag_stack.append((current_level, current_concat_flag)) """ 此时到达了串的结尾,栈内应至少有一个NFA,考虑到有可能是多个正则的并运算,这时候操作应和遇到右括号时操作一致 操作完成后,如果NFA栈内仅有一个NFA并且其他两个栈为空,则该正则表达式识别成功,NFA栈顶即为生成的最终NFA """ reduce_concat() reduce_union() # 如果栈内只有一个NFA并且标志栈为空即为翻译成功,结果得到的NFA位于NFA栈顶 if len(nfa_stack) == 1 and len(flag_stack) == 0: return nfa_stack[-1] # 其他情况报错,说明输入的表达式不是正则表达式 else: raise ValueError('exp is not a regular expression') if __name__ == '__main__': # r: str = r'(ab*a|ab(a)*)(a|b*)' r="" with open("re",'r') as f: r=f.readline() print(r) pattern = regex(r) a = pattern.compile() print('NFA corresponding to given regular expression "' + r + '" is:') a.printf() # while True: # s = input('input string to match (press enter to exit):') # if len(s) < 1: # break # if a.match(s): # print('PASS!') # else: # print('INVALID!')
661c3d8e3186b7c9cca9865515de8ea0213ed24d
Starfox68/Sudoku
/solver.py
1,161
3.671875
4
def solve(bo): find = find_empty(bo) if not find: return True else: row, col = find for i in range(1, 10): if valid(bo, i, (row,col)): bo[row][col] = i if (solve(bo)): return True bo[row][col] = 0 return False def valid(bo, num, pos): row = pos[0] col = pos[1] #check row for i in range(len(bo)): if (bo[row][i] == num and col != i): return False #check column for i in range(len(bo)): if (bo[i][col] == num and row != i): return False #check square box_x = col // 3 box_y = row // 3 for i in range(box_y * 3, box_y * 3 + 3): for j in range(box_x * 3, box_x * 3 + 3): if (bo[i][j] == num and (i,j) != pos): return False return True def print_board(bo): for i in range(len(bo)): for j in range(len(bo)): if (j % 3 == 0 and j != 0): print("| " + str(bo[i][j]) + " ", end = '') elif (j == (len(bo)-1)): print(str(bo[i][j])) else: print(str(bo[i][j]) + " ", end = '') if ((i+1) % 3 == 0): print("- - - - - - - - - - -") def find_empty(bo): for i in range(len(bo)): for j in range(len(bo)): if (bo[i][j] == 0): return (i, j) #row then column return False