blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f90156e0ff70cd910a2122df38af04c3da198e0b
nguyenhuuthinhvnpl/CS115
/test2review.py
3,355
3.875
4
''' Created on Oct 24, 2017 @author: jschm ''' #2 types of use it or lose it - power set and knapsack sort of #going down one path here and another path there, slightly altering the info for #these paths """ CHEAT SHEET!!!!!!!!!! -> put use it or lose it on one side (all of it) then dictionary, memoization, circuit, unittest, binary on the other """ """ use the coin, or lose the coin powerset - go down a single side, but use it in 2 different ways """ from cs115 import map import sys sys.setrecursionlimit(100000) import unittest def powerset(lst): """typically L=['one', 'two'] - return list of lists """ if lst == []: return [[]] #return empty list of list lose_it = powerset(lst[1:]) #lost the first element in the list use_it = map(lambda x: [lst[0]] + x, lose_it) #add the first element to the lose_it return lose_it + use_it """just linear recursion, not tree trace: powerset([1,2]) lose_it = powerset([2]) -> lose_it = powerset([]) -> [[]] use_it = [[2]] -> [[2], []] -> [[2], [1,2], [1], []] """ print(powerset([1, 2])) lst = [1,2,3,4] print(map(lambda x: lst[3] + x, range(1,5))) #lambda is a temporary function def getCoins(lst, n): if n == 0: return 0 if lst == []: return float('inf') #largest number in python - impossible if lst[0] > n: return getCoins(lst[1:], n) use_it = 1 + getCoins(lst[1:], n-lst[1]) lose_it = getCoins(lst[1:], n) return min(use_it, lose_it) print(getCoins([1,10,15,30], 25)) #dict = {key: value} dict = {} dict["steve"] = 19 dict[(11,2)] = "a" dict["steve"] = [2,19] print(dict["steve"][1]) #19 tup = (1,2) def fib(n): """generic fibonacci""" if n < 2: return n return fib(n-1) + fib(n-2) print(fib(8)) def fibWithMemo(n): def fibHelper(n, memo): if n in memo: return memo[n] if n < 2: result = n else: result = fibHelper(n-1, memo) + fibHelper(n-2, memo) memo[n] = result return result return fibHelper(n, {}) print(fibWithMemo(6000)) def subset(target, lst): """use it or lose it - determines whether or not it is possible to create target sum using the values in the list. Values in list can be positive, negative or zero""" if target == 0: return True if lst == []: return False # use-it lose-it (come back to later return subset(target - lst[0], lst[1:]) or subset(target, lst[1:]) def subset_with_values(target, lst): """determines whether or not it is possible to create the target sum using the values in the list. Values in the list can be positive, negative or 0. The function returns a tuple of the boolean and the second the values for the sum""" if target == "0": return (True, []) if lst == []: return (False, []) use_it = subset_with_values(target - lst[0], lst[1:]) if use_it[0]: return (True, [lst[0]] + use_it[1]) return subset_with_values(target, lst[1:]) #import unittest def isEven(n): return n%2 == 0 class tests(unittest.TestCase): def test1(self): self.assertTrue(isEven(8)) self.assertFalse(isEven(7)) self.assertEqual(isEven(8),True) if __name__ == "__main__": unittest.main()
c33620d3ebeb720d3a40a13334fd19094153a03e
suresh753/Guessing-Game-Challenge
/guessing_game.py
750
3.875
4
import random random_number = random.randint(1,100) guesses = [] guess = None while (True): guess = int( input( 'Enter your guess' ) ) if guess == random_number: print "You're Correct and number of tries are {}".format(len( guesses ) + 1) break else: if 1 <= guess <= 100 : if not guesses: if abs(random_number-guess) <= 10: print 'WARM!' else: print 'COLD!' else: if abs(random_number-guess) > abs(random_number-guesses[-1]): print 'COLDER!' else: print 'WARMER!' else: print 'OUT OF BOUNDS' guesses.append( guess )
3eedfcdeaced42bb60bbe11c86fadf0576dc4472
longlongtjandra/driving-simulation
/AliceNBob.py
127
4
4
def evenodd(x): return x%2 x=int(input("number of stones:")) if evenodd(x)==1: print("alice") else: print("Bob")
14282c77108b69035c9b949b182fe40c99cb4bef
raoofnaushad/GPT-3-Beginner-Workout
/gpt_3_workout.py
2,051
3.84375
4
# Source => https://github.com/bhattbhavesh91/gpt-3-simple-tutorial/blob/master/gpt-3-notebook.ipynb import json import openai from gpt import GPT from gpt import Example openai.api_key = data["API_KEY"] with open('GPT_SECRET_KEY.json') as f: data = json.load(f) gpt = GPT(engine="davinci", temperature=0.5, max_tokens=100) ## Adding Examples for GPT Model gpt.add_example(Example('Fetch unique values of DEPARTMENT from Worker table.', 'Select distinct DEPARTMENT from Worker;')) gpt.add_example(Example('Print the first three characters of FIRST_NAME from Worker table.', 'Select substring(FIRST_NAME,1,3) from Worker;')) gpt.add_example(Example("Find the position of the alphabet ('a') in the first name column 'Amitabh' from Worker table.", "Select INSTR(FIRST_NAME, BINARY'a') from Worker where FIRST_NAME = 'Amitabh';")) gpt.add_example(Example("Print the FIRST_NAME from Worker table after replacing 'a' with 'A'.", "Select CONCAT(FIRST_NAME, ' ', LAST_NAME) AS 'COMPLETE_NAME' from Worker;")) gpt.add_example(Example("Display the second highest salary from the Worker table.", "Select max(Salary) from Worker where Salary not in (Select max(Salary) from Worker);")) gpt.add_example(Example("Display the highest salary from the Worker table.", "Select max(Salary) from Worker;")) gpt.add_example(Example("Get all details of the Workers whose SALARY lies between 100000 and 500000.", "Select * from Worker where SALARY between 100000 and 500000;")) gpt.add_example(Example("Get Salary details of the Workers", "Select Salary from Worker")) ## Example - 1 prompt = "Display the lowest salary from the Worker table." output = gpt.submit_request(prompt) print(output.choices[0].text) ## Example 2 prompt = "Tell me the count of employees working in the department HR." print(gpt.get_top_reply(prompt))
a492c6827a882a66bfedb7e12501739b31217526
lilkeng/CodingChanllege
/leetcode/python/text_justification/solution.py
2,277
3.65625
4
''' 68. Text Justification QuestionEditorial Solution My Submissions Total Accepted: 37257 Total Submissions: 222236 Difficulty: Hard Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left justified and no extra space is inserted between words. For example, words: ["This", "is", "an", "example", "of", "text", "justification."] L: 16. Return the formatted lines as: [ "This is an", "example of text", "justification. " ] ''' class Solution(object): def fullJustify(self, words, L): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ res = [] i = 0 while i < len(words): size = 0; begin = i while i < len(words): # The new word size should add one to ensure between each two words there is a space newSize = len(words[i]) if size == 0 else size + len(words[i]) +1 if newSize <= L: size = newSize i += 1 else: break spaceLeft = L - size if i - begin - 1 > 0 and i < len(words): everySpace = spaceLeft / (i-begin-1) spaceLeft %= (i-begin-1) else: everySpace = 0 j = begin while j<i: if j == begin: s = words[j] else: s += ' '*(everySpace+1) if spaceLeft > 0 and i<len(words): s += ' ' spaceLeft -= 1 s += words[j] j += 1 s += ' '*spaceLeft res.append(s) return res
90c577faf8f7a3ada1b4bd12c6e4132882f26db5
KalinHar/Advanced-Python-SoftUni
/exams/reg-exam-pro-02.py
1,502
3.5625
4
def in_board(j, k): if 0 <= j < 5 and 0 <= k < 5: return True board, player, shooting_targets = [], [], [] targets = 0 direction = {'left': (0, -1), 'up': (-1, 0), 'right': (0, 1), 'down': (1, 0)} for row in range(5): line = input().split(" ") board.append(line) for col in range(5): if line[col] == "x": targets += 1 elif line[col] == "A": player = [row, col] n = int(input()) for _ in range(n): command = input().split(" ") r, c = direction[command[1]] if command[0] == "shoot": pot_r = player[0] pot_c = player[1] for _ in range(5): pot_r += r pot_c += c if in_board(pot_r, pot_c) and board[pot_r][pot_c] == "x": shooting_targets.append([pot_r, pot_c]) board[pot_r][pot_c] = "." break if targets == len(shooting_targets): break elif command[0] == "move": steps = int(command[2]) pot_r = player[0] + r * steps pot_c = player[1] + c * steps if in_board(pot_r, pot_c) and board[pot_r][pot_c] == ".": board[pot_r][pot_c] = "A" board[player[0]][player[1]] = "." player = [pot_r, pot_c] if targets == len(shooting_targets): print(f"Training completed! All {targets} targets hit.") else: print(f"Training not completed! {targets - len(shooting_targets)} targets left.") [print(target) for target in shooting_targets]
b5e9c08a1460da1d743e4abbf86554542b267a7d
AndrejLehmann/my_pfn_2019
/Vorlesung/src/Basic/datematch.py
600
3.75
4
#!/usr/bin/env python3 import re for date in ['2014-12-13','2016-01-02']: # extract numbers from a date string YYYY-MM-DD m = re.search(r'(\d{4})-(\d{2})-(\d{2})', date) if m: year = m.group(1) month = m.group(2) day = m.group(3) print('{}.{}.{}'.format(day, month, year)) def date_parse(date): m = re.search(r'(\d{4})-(\d{2})-(\d{2})', date) if not m: return None d = dict() d['y'] = int(m.group(1)) d['m'] = int(m.group(2)) d['d'] = int(m.group(3)) return d for date in ['2014-12-13','2016-01-02']: d = date_parse(date) if d is not None: print(d)
aaed9cf624f226fbbaceb5d108d8e5e3e9ee9d8a
beatriznaimaite/Exercicios-Python-Curso-Em-Video
/mundo1/exercicio015.py
691
4.125
4
""" Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 por dia e R$ 0,15 por Km rodado. """ # entrada de dados km_percorrido = float(input('Digite a quantidade de quilometros percorridos por um carro: ')) dias_alugado = int(input('O carro foi alugado por quantos dias? ')) # cálculo dos valores total_km = km_percorrido * 0.15 total_dias = dias_alugado * 60 total_gasto = total_km + total_dias print(f'Você gastou R$ {total_gasto:.2f} ao todo, sendo o total de R$ {total_km:.2f} pelos quilômetros e R$ {total_dias:.2f} por dias alugados.')
b6dd745cedb370a34e9aedadf3a9ddea8ce57113
manishawsdevops/pythonmaster
/Python Basic - Part II/short_circuiting.py
466
3.828125
4
#Short circuiting. #short ciruiting majorly explains like if there is an operation of and, if the first conditions is False. #Python interpreter will not check for the second condition after and, because anyway it is going to skip the #statement. It is the same with or condition as well. #The process of skipping the coditions validation is called as short circuiting. if_friend = True is_user = True if if_friend and is_user: print('Baahubali is released')
a90249202c69237aa8ab3ce7b3cf59d1fb7a127f
TraceIvan/PythonProjects
/gcd.py
317
3.765625
4
#辗转相除法 print("示例:求12与32的最大公约数:") a,b=32,12 while a%b: a,b=b,a%b print("12和32的最大公约数为:%d\n"%b) print("请输入两个整数:") x=input() y=input() x1=int(x) y1=int(y) if x1<y1: x1,y1=y1,x1 while x1%y1: x1,y1=y1,x1%y1 print("最大公约数为:%d\n"%y1)
2201d6f318b776c579d08edba287a9c177a4c93e
sathayas/AnalyticsClassSpring2019
/textClassExamples/NameClassifier.py
1,757
3.84375
4
import nltk import random # a function to return a feature to classify whether a name is # male or female. # The feature and the label are returned together def gender_feature(name): featureDict = {'last-letter': name[-1]} return featureDict # reading names from the names corpus from nltk.corpus import names femaleNames = names.words('female.txt') maleNames = names.words('male.txt') # creating name-label pairs, then shuffling nameData = [] for iName in femaleNames: nameData.append((iName, 'female')) for iName in maleNames: nameData.append((iName, 'male')) random.shuffle(nameData) # converting the name data into feature (i.e., just the last letter) # as well as the label (female / male) featureData = [(gender_feature(n), gender) for (n, gender) in nameData] # spliting into training and testing data sets trainData, testData = featureData[1000:], featureData[:1000] # training a classifier (Naive Bayes) clf = nltk.NaiveBayesClassifier.train(trainData) # classification example print(clf.classify(gender_feature('Nemo'))) print(clf.classify(gender_feature('Dory'))) # classifier performance on the testing data print(nltk.classify.accuracy(clf, testData)) # most informative features clf.show_most_informative_features(10) # examining classification errors errorData = [] testDataFull = nameData[:1000] # Extracting the full testing data for iData in testDataFull: trueCat = iData[1] predCat = clf.classify(gender_feature(iData[0])) if predCat != trueCat: errorData.append((trueCat, predCat, iData[0])) # printing out the errors for (y_true, y_pred, name) in sorted(errorData): print('Truth: %-6s\t' % y_true, end='') print('Pred: %-6s\t' % y_pred, end='') print('Name: %-12s' % name)
3504ff1090e10cb11d8083a812faceca21835091
wjpe/EjemplosPython-Cisco
/ej11.py
664
3.96875
4
numeroSecreto = 777 print( """ +==================================+ | Bienvenido a mi juego, muggle! | | Introduce un número entero | | y adivina qué número he | | elegido para ti. | | Entonces, | | ¿Cuál es el número secreto? | +==================================+ """) numeroUsuario = int(input("Digita un numero ")) salida = 1 while salida !=0: if numeroUsuario != numeroSecreto: print("¡Ja, Ja, Ja!, ¡Estas atrapado en mi ciclo!") numeroUsuario = int(input("Digita otro numero numero ")) else: salida = 0 print("Bien hecho muggle eres libre ahora")
a0878140048d20558fa8917718542a0ee465c567
TerryLun/Code-Playground
/generate_magic_squares.py
727
4.125
4
import copy import magic_square import rotate_matrix import flip_matrix def generate_magic_squares_three_by_three(): magic_squares = [] m = magic_square.solve(3) magic_squares.append(copy.deepcopy(m)) for _ in range(3): rotate_matrix.rotate_matrix(m) magic_squares.append(copy.deepcopy(m)) flip_matrix.flip_matrix_horizontal(m) magic_squares.append(copy.deepcopy(m)) for _ in range(3): rotate_matrix.rotate_matrix(m) magic_squares.append(copy.deepcopy(m)) return magic_squares def main(): sq = generate_magic_squares_three_by_three() for i in sq: for r in i: print(*r) print() if __name__ == '__main__': main()
de8a427f7486828a50afafa7957614c7d20876cf
Mirage-Flare/cp1404practicals
/prac_01/shop_calculator.py
360
4.09375
4
""" Calculating total price from a number of items with different prices Kyle Muccignat """ number_of_items = int(input("Number of items: ")) price_of_items = 0 for number in range(number_of_items): price_of_items += float(input("Price of item: ")) if price_of_items > 100: price_of_items *= 0.9 print("Total price for", number_of_items, "is", price_of_items)
dbca850457482b535afeb23462c8d5fe34e0d21f
MissPisces/python_GUI
/tkinter_05.py
687
3.84375
4
# 测试中文支持 import tkinter as tk import tkinter.font as tkFont root = tk.Tk() # must be here screenWidth = root.winfo_screenwidth() screenHeight = root.winfo_screenheight() f1 = tkFont.Font(family='microsoft yahei', size=30, weight='bold') f2 = tkFont.Font(family='microsoft yahei', size=30, slant='italic') f3 = tkFont.Font(family='lisu', size=30, underline=1, overstrike=1) f4 = tkFont.Font(family='TkMenuFont', size=30) tk.Label(root, text='汉字字体', font=f1).pack() tk.Label(root, text='汉字字体', font=f2).pack() tk.Label(root, text='汉字字体', font=f3).pack() tk.Label(root, text='默认汉字字体', font=f4).pack() print(tkFont.BOLD) root.mainloop()
d05f7241cc8648629f6231fc663230a5a81c0525
zzh-python/all-project
/linkedin/des.py
1,104
3.53125
4
from Crypto.Cipher import DES class MyDESCrypt: key = chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11) iv = chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22) def __init__(self,key='',iv=''): if len(key)> 0: self.key = key if len(iv)>0 : self.iv = iv def ecrypt(self,ecryptText): try: cipherX = DES.new(self.key, DES.MODE_CBC, self.iv) pad = 8 - len(ecryptText) % 8 padStr = "" for i in range(pad): padStr = padStr + chr(pad) ecryptText = ecryptText + padStr x = cipherX.encrypt(ecryptText) return x.encode('hex_codec').upper() except: return "" def decrypt(self,decryptText): try: cipherX = DES.new(self.key, DES.MODE_CBC, self.iv) str = decryptText.decode('hex_codec') y = cipherX.decrypt(str) return y[0:ord(y[len(y)-1])*-1] except: return ""
83cbc4c2656fefb97012696601244fe43252648b
MarianaPaz/Curso-Python
/05_function.py
366
3.90625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 17 18:33:49 2020 @author: CEC """ aclNum = int(input("What is the IPv4 ACL number?")) if aclNum >= 1 and aclNum <= 99: print("This is a standar IPv4 ACL.") elif aclNum >= 100 and aclNum <= 199: print("This is a extended IPv4 ACL.") else: print("This is a standar or extended IPv4 ACL.")
8135965a95f69be9f2f18c618eb99025f76cbbcb
Alic-yuan/leetcode
/Week_08/quick_sort.py
535
3.90625
4
def quick_sort(nums, left, right): if left > right: return pivot = pivotion(nums, left, right) quick_sort(nums, left, pivot-1) quick_sort(nums, pivot+1, right) def pivotion(nums, left, right): mark = left p = nums[left] for i in range(left+1, right+1): if nums[i] < p: mark +=1 nums[mark], nums[i] = nums[i], nums[mark] nums[mark], nums[left] = nums[left], nums[mark] return mark nums = list([3,5,8,1,5,10,6]) quick_sort(nums, 0, len(nums)-1) print(nums)
3f2710e318b5aaf5d0e4cffb80d5debe2d85a6ee
SoumikaNaskar/CBA
/For_TS/validate_form.py
4,216
3.828125
4
print(" *********** Enter the details **************** ") f_name=input("First Name: ") m_name=input("Middle Name (if) : ") l_name=input("Last Name: ") address=input("Address: ") pincode=input("Pincode: ") blood_group=input("Blood group: ") age=input("Age: ") contact_no=input("Contact Number: ") add_contact_no=input("Additional Contact Number: ") resident_contact_no=input("Residential Contact No. : ") dept=input("Department: ") dept_code=input("Department Code: ") emp_id=input("Employeed Id: ") blood_group_list=('A+' or 'A−' or 'B+' or 'B−' or 'AB+' or 'O+ ' or 'O−' or 'AB−') while True: # Naming_Part if (f_name.isalpha()) and l_name.isalpha() and (m_name.isalpha())==True: if(len(f_name)<=15) and (len(m_name)<=15) and (len(l_name)<=15)==True: pass elif ((f_name.isalpha()) and l_name.isalpha() and (m_name==""))==True: if(len(f_name)<=15) and (len(l_name)<=15)==True: pass elif ((f_name=="") or (f_name.isalpha()==False))==True: f_name=input("First Name: ") elif (l_name=="") or (l_name.isalpha()==False)==True: l_name=input("Last Name: ") # Age if age.isdigit()==True: age_limit=int(age) if (age_limit>=20) and (age_limit<=60): pass elif (age_limit>60) and (age_limit<20): age=input("Age: ") #Contact_feilds if (contact_no.isdigit() and add_contact_no.isdigit() and resident_contact_no.isdigit())==True: if (len(contact_no)==10)==False: contact_no=input("Contact Number: ") elif (len(add_contact_no)==10)==False: add_contact_no=input("Additional Contact Number: ") elif (len(resident_contact_no)==10)==False: resident_contact_no=input("Residential Contact No. : ") elif ((len(resident_contact_no)) and (len(add_contact_no)) and (len(contact_no))==10)==True: pass elif contact_no.isdigit()==False: contact_no=input("Contact Number: ") elif add_contact_no.isdigit()==False: add_contact_no=input("Additional Contact Number: ") elif resident_contact_no.isdigit()==False: resident_contact_no=input("Residential Contact No. : ") #Blood Group if (blood_group==blood_group_list)==True: pass elif ((blood_group=="") and (blood_group!=blood_group_list))==True: blood_group=input("Blood group: ") #address if (len(address)<=100)==True: pass elif (address=="")==True: address=input("Address: ") if pincode.isalnum()==True: if (len(pincode)<=6)==True: pass elif ((pincode.isalnum()==False) or (pincode==""))==True: pincode=input("Pincode: ") #dept if dept.isalpha()==True: if(len(dept)<=30)==True: pass elif ((dept.isalpha()==False) or (dept==""))==True: dept=input("Department: ") #dept_code if dept_code.isalnum()==True: if(len(dept_code)==6)==True: pass elif ((dept_code.isalnum()==False) or (dept_code==""))==True: dept=input("Department Code: ") #emp_id if emp_id.isdigit()==True: if(len(emp_id)==6)==True: pass elif ((emp_id.isdigit()==False) or (emp_id==""))==True: dept_code=input("Employee Id: ") if (add_contact_no and resident_contact_no and contact_no and blood_group and address and pincode and dept and dept_code and emp_id and f_name and l_name and age)!="": print("\n #### Result ###") print("First Name: {}".format(f_name)) print("Middle Name: {}".format(m_name)) print("Last Name: {}".format(l_name)) print("Address: {}".format(address)) print("Pincode: {}".format(pincode)) print("Blood group: {}".format(blood_group)) print("Age: {}".format(age)) print("Contact No: {}".format(contact_no)) print("Additional Contact No: {}".format(add_contact_no)) print("Resident Contact No: {}".format(resident_contact_no)) print("Department: {}".format(dept)) print("Department Code: {}".format(dept_code)) print("Employee Id: {}".format(emp_id)) break
ae0350db8b030dbc3cbf32edeee384e783b8da7d
fcostanz/NTupler
/TopAnalysis/TopUtils/python/tools/Timer.py
2,729
3.765625
4
import time import datetime import os class Timer: __name = 'nothing' __start = 0.0 __stop = 0.0 __secondspassed = 0.0 def __init__(self): self.__name = 'timer' "Return a formated date string" def getDate(): return time.strftime("%d%m%y", time.gmtime()) "Return a formated date and time string" def getTime(): return time.mktime(datetime.datetime.utcnow().timetuple()).__str__() def start(self): #print 'start' t0 = os.times() self.__start = t0[3] + t0[4] def stop(self): #print 'stop' t0 = os.times() self.__stop = t0[3] + t0[4] self.__secondspassed += self.__stop - self.__start "returns a formated time string: h m s" def getMeasuredTime(self): t = self.__secondspassed h = 0 m = 0 s = 0 ft = "" if t >= 3600: h = (t - t%3600)/3600 t = t -h*3600 if t >= 60: m = (t - t%60)/60 t = t-m*60 s = t if h > 0: ft = round(h,0).__str__() + "h " if m > 0: ft = ft + round(m, 0).__str__() + "m " ft = ft + round(s,2).__str__() + "s" return ft def getMeasuredSeconds(self): return self.__secondspassed def timePassed(self, osTime): t = osTime[3] + osTime[4] p = t - self.__start return p def sleep(sleeptime): time.sleep(sleeptime) def formatSFnumber(num, upto=100): out = 0 tens = 0 for i in range(1,100): if (num > 1 and num > 0) or tens >= upto: out = num break else: num = num *10 tens += 1 str = '%1.3fd%d' % (out, -tens) return str, tens def formatNumPair(num1, num2): out = Timer.formatSFnumber(num1) out1 = out[0] out2 = Timer.formatSFnumber(num2, out[1])[0] return out1, out2 def formatErrorPair(num1, num2): out = Timer.formatNumPair(num1, num2) num1 = out[0].split('d')[0] num2 = out[1].split('d')[0] exp = out[0].split('d')[1] str = '($%s \\pm %s$)\\num{d%s}' % (num1, num2, exp) return str formatErrorPair = staticmethod(formatErrorPair) formatNumPair = staticmethod(formatNumPair) formatSFnumber = staticmethod(formatSFnumber) getDate = staticmethod(getDate) getTime = staticmethod(getTime) sleep = staticmethod(sleep)
6dc489f5b4f0d680045895d2517cc3b8af220e7e
Branden-Kang/Convert-Your-Speech-to-Text-using-Python
/sp_recognition.py
457
3.59375
4
# import the module import speech_recognition as sr # create the recognizer r = sr.Recognizer() # define the microphone mic = sr.Microphone(device_index=0) # record your speech with mic as source: audio = r.listen(source) # speech recognition result = r.recognize_google(audio) # export the result with open('my_result.txt',mode ='w') as file: file.write("Recognized text:") file.write("\n") file.write(result) print("Process completed!")
e539fcd28af62517b34ac136f722bacebc1cd95e
abhay-ajith/amfoss-tasks
/task-2/Hackerrank/Time-Format Converter.py
224
3.78125
4
time = input("Enter the time") m = time[-2:] twm = time[:-2] h = int(time[:2]) if m == "AM": h = (h + 1) % 12 + 1 print("%02d" % h) + twm[2:] elif m == "PM": h = h % 12 + 12 print(str(h) + twm[2:])
45435156457b43f37fbb089fcf9e3066b113f91f
SoyeonHH/Algorithm_Python
/LeetCode/205.py
850
4.15625
4
''' Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. Example 1) Input: s = "egg", t = "add" Output: true ''' class Solution: def isIsomorphic(self, s: str, t: str) -> bool: mapping_s_t = {} mapping_t_s = {} for c1, c2 in zip(s, t): if (c1 not in mapping_s_t) and (c2 not in mapping_t_s): mapping_s_t[c1] = c2 mapping_t_s[c2] = c1 elif mapping_s_t.get(c1) != c2 or mapping_t_s.get(c2) != c1: return False return True
7759ca5c95409e284f4e8fa85c3864ef9c9e0c58
sharonsabu/pythondjango2021
/questions/between_ranges.py
230
3.859375
4
#question in book pow=int(input("enter number")) ll=int(input("enter lowerlimit")) ul=int(input("enter upperlimit")) for num in range(1,ul+1): a=num**pow if((a>=ll)&(a<=ul)): #if a in range(ll,(ul+1)): print(a)
851e3545ba323f98e9e0aaef71fe65bbf1880938
reckful88/learning-python
/class_002.py
448
4.1875
4
#######定义一个班级的类,最下面的那个班级,是把学生和老师都加进去了,但别忘记定义学生和老师的姓名####### class teacher(object): def __init__(self,name): self.__name = name def run(self): print 'hello,world' class student(object): def __init__(self,name): self.__name = name class classes(object): def __init__(self, student, teacher): self.__teacher = teacher self.__student = student
f5b6401856c88bc36c72a35d7a69f4abb4e10a4d
qinjiabo1990/Python_Project
/Assignment/Assignment_1/assignment1/trial.py
5,340
4.09375
4
""" def judgement(x): while x != 1 and x != 2 and x !=3: print('wrong') x = input ('your answer: ') return x """ """ import partners potential_partners = partners.Partners() gender='1' sexual_pref='2' height='1' height_pref='2' persionality_score=22 if gender == '1': gender_list = 'male' elif gender == '2': gender_list = 'female' elif gender == '3': gender_list = 'other' if sexual_pref == '1': sexual_pref_list = 'male' elif sexual_pref == '2': sexual_pref_list = 'female' elif sexual_pref == '3': sexual_pref_list = 'other' if height == '1': height_list = 'tall' elif height == '2': height_list = 'medium' elif height == '3': height_list = 'short' if height_pref == '1': height_pref_list = 'tall' elif height_pref == '2': height_pref_list = 'medium' elif height_pref == '3': height_pref_list = 'short' result=(gender_list, sexual_pref_list, height_list, height_pref_list, persionality_score) closest_score = float("inf") while potential_partners.available() : if (result[1] == potential_partners.get_gender() and result[0] == potential_partners.get_sexual_pref()): if abs(result[4] - potential_partners.get_personality_score()) < closest_score: closest_score = abs(result[4] - potential_partners.get_personality_score()) if (result[3] == potential_partners.get_height() and result[2] == potential_partners.get_height_pref()): print (potential_partners.get_name()) """ import partners def physical_characteristics_question(question, answer1, answer2, answer3, answer): print(question) print('1)', answer1, '\n2)', answer2, '\n3)', answer3) answer = input('Please enter your answer: ') while answer != '1' and answer != '2' and answer !='3': print('Your input is invalid') answer = input ('Please enter your answer: ') return answer def personality_question(question, answer): print(question) print('1) Yes' '\n2) Most of the time' '\n3) Neutral' '\n4) Some times' '\n5) No') answer = input('Please enter your answer: ') while answer != '1' and answer != '2' and answer !='3' and answer !='4' and answer != '5': print('Your input is invalid') answer = input ('Please enter your answer: ') return answer def match(gender, sexual_pref, height, height_pref, personality_score): potential_partners = partners.Partners() if gender == 1: gender_list = 'male' elif gender == 2: gender_list = 'female' elif gender == 3: gender_list = 'other' if sexual_pref == 1: sexual_pref_list = 'male' elif sexual_pref == 2: sexual_pref_list = 'female' elif sexual_pref == 3: sexual_pref_list = 'other' if height == 1: height_list = 'tall' elif height == 2: height_list = 'medium' elif height == 3: height_list = 'short' if height_pref == 1: height_pref_list = 'tall' elif height_pref == 2: height_pref_list = 'medium' elif height_pref == 3: height_pref_list = 'short' result=(gender_list, sexual_pref_list, height_list, height_pref_list, personality_score) closest_score = float("inf") while potential_partners.available() : if (result[1] == potential_partners.get_gender() and result[0] == potential_partners.get_sexual_pref()): if abs(result[4] - potential_partners.get_personality_score()) < closest_score: closest_score = abs(result[4] - potential_partners.get_personality_score()) if (result[3] == potential_partners.get_height() and result[2] == potential_partners.get_height_pref()): print (potential_partners.get_name()) #personal details #Gender gender_int=int(physical_characteristics_question('what is your gender?', 'male', 'female', 'other', 'gender')) print('\n') #sexual preference sexual_pref_int=int(physical_characteristics_question('what is your sexual preference?', 'male', 'female', 'other', 'sexual_pref')) print('\n') #height height_int=int(physical_characteristics_question('what is your height?', 'tall', 'medium', 'short', 'height')) print('\n') #height_preference height_pref_int=int(physical_characteristics_question('what height do you prefer your partner to be?', 'tall', 'medium', 'short', 'height_pref')) print('\n') #introduction introduction_int=int(personality_question('Do you find it easy to introduce yourself to ohter people?', 'introduction')) print('\n') #conversation conversations_int=int(personality_question('Do you usually initiate conversations?', 'conversations')) print('\n') #curiousity curiousity_int=int(personality_question('Do you often do something out of sheer curiosity?', 'curiousity')) print('\n') #communication communication_int=int(personality_question('Do you prefer being out with a large group of friends rather than \nspending time on your own?', 'communication')) print('\n') personality_score = (introduction_int + conversations_int + curiousity_int + communication_int) * 2 match(gender_int, sexual_pref_int, height_int, height_pref_int, personality_score)
019154ddda193063b137a02d67fff0e33bb12c69
woraseth/numer
/cubic_spline.py
1,764
4.21875
4
def cubic_spline(x, y): """ Parameters ---------- x : list of floats y : list of floats Returns ------- list of list of floats """ n = len(x) - 1 h = [x[i+1]-x[i] for i in range(n)] al = [3*((y[i+1]-y[i])/h[i] - (y[i]-y[i-1])/h[i-1]) for i in range(1,n)] al.insert(0,0) l = [1] * (n+1) u = [0] * (n+1) z = [0] * (n+1) for i in range(1, n): l[i] = 2*(x[i+1]-x[i-1]) - h[i-1]*u[i-1] u[i] = h[i]/l[i] z[i] = (al[i] - h[i-1]*z[i-1])/l[i] b = [0] * (n+1) c = [0] * (n+1) d = [0] * (n+1) for i in range(n-1, -1, -1): #for i in reversed(range(n)): c[i] = z[i] - u[i]*c[i+1] b[i] = (y[i+1]-y[i])/h[i] - h[i]*(c[i+1] + 2*c[i])/3 d[i] = (c[i+1]-c[i])/(3*h[i]) return [y, b, c, d] if __name__ == '__main__': import math import matplotlib.pyplot as plt import numpy as np # the function to be interpolated def f(x): return math.e ** x # input interval = 3 x = [i for i in range(interval + 1)] y = [f(i) for i in range(interval + 1)] # process a = cubic_spline(x, y) # output points_per_interval = 5 x = np.linspace(0, 3, interval * points_per_interval - (interval - 1)) y = [f(x[i]) for i in range(len(x))] xs = [] ys = [] for i in range(3): xs.append(np.linspace(i, i+1, points_per_interval)) ys.append([a[0][i] + a[1][i]*(xs[i][k]-i) + a[2][i]*(xs[i][k]-i)**2 + a[3][i]*(xs[i][k]-i)**3 for k in range(points_per_interval)]) plt.plot(x, y, 'k.-', xs[0], ys[0], 'r.--', xs[1], ys[1], 'g.--', xs[2], ys[2], 'b.--') plt.title('Cubic Spline') plt.xlabel('x') plt.ylabel('e^x') plt.show() # cubic spline interpolation # author : worasait suwannik # date : apr 2015
65f5b9d14df48f63eea942560f00f6adb88184a1
6yeQT/_CODESIGNAL_Py3
/Arcade/SmoothSailing/commonCharacterCount.py
327
3.53125
4
def commonCharacterCount(s1, s2): count = 0 done = [] for i in range(len(s1)): if s1[i] not in done: count += min([s1.count(s1[i]), s2.count(s1[i])]) print(s1[i], ' ', s2[i], ' ', count) done.append(s1[i]) return count print(commonCharacterCount('aabcc', 'adcaa'))
9046e21b451d2579a0cd09bd47200265124006fc
Ham5terzilla/python
/2nd Lesson/n5.py
171
3.90625
4
# Ввести число a/ Определить и вывести сообщение о том, чётное оно или нечётное print(int(input()) % 2 == 0)
971a54ae64373be2c91eb404f5cd4e216a606093
cyrusc008/ClassworkSpring2021
/return.py
193
3.75
4
def my_function(x): a = x + 5 if a < 0: answer = "negative number" else: answer = "positive number" return a, answer y, z = my_function(-20) print(y) print(z)
c063ddbbda27c871c724a3992ac7518ca2f8c6f6
rdiptan/Python-mini-projects
/Graham.py
1,879
3.578125
4
from tkinter import * import math root = Tk() root.geometry('500x300') root.title("Graham Formula") price = StringVar() eps = StringVar() book = StringVar() result = StringVar() verdict = StringVar() def Exit(): root.destroy() def Reset(): price.set("") eps.set("") book.set("") result.set("") verdict.set("") def Result(): a = float(eps.get()) b = float(book.get()) p = float(price.get()) res = round((math.sqrt(22.5*a*b)), 2) result.set(str(res)) if p>res: verdict.set("Over Valued: "+ str(round((p-res),2)) + " ~ " + str(round(((p-res)/p*100), 2)) + "%") else: verdict.set("Under Valued: "+ str(round((res-p),2)) + " ~ " + str(round(((res-p)/p*100), 2)) + "%") Label(root, font='arial 12 bold', text='Market Price').place(x=60, y=30) Entry(root, font='arial 10', textvariable=price, bg='ghost white').place(x=190, y=30) Label(root, font='arial 12 bold', text='EPS').place(x=60, y=60) Entry(root, font='arial 10', textvariable=eps, bg='ghost white').place(x=190, y=60) Label(root, font='arial 12 bold', text='Book value').place(x=60, y=90) Entry(root, font='arial 10', textvariable=book, bg='ghost white').place(x=190, y=90) Button(root, font='arial 10 bold', text='Calculate Price', padx=2, bg='LightGray', command=Result).place(x=60, y=120) Entry(root, font='arial 12 bold', textvariable=result, width="30", bg='ghost white', state="readonly").place(x=190, y=120) Entry(root, font='arial 12 bold', textvariable=verdict, width="30", bg='ghost white', state="readonly").place(x=190, y=150) Button(root, font='arial 10 bold', text='RESET', width=6, command=Reset, bg='LimeGreen', padx=2).place(x=80, y=190) Button(root, font='arial 10 bold', text='EXIT', width=6, command=Exit, bg='OrangeRed', padx=2).place(x=180, y=190) root.mainloop()
e2c8c62ea8f8663fe3dbcc2cc7e6d38dddb57923
bitbybitsth/automation_login
/bitbybit/assignments/dictionary_impl.py
4,001
3.953125
4
""" dict --- internally implemented as hashtable and uses closed hashing a.k.a open addressing --- Unlike other data types Dictionary holds a pair (KEY,VALUE) as a single element. --- Dictionary is mutable --- Key must be immutable(String, Number, Tuple) and no duplicates allowed. --- Value cannot be of any type(Mutable or immutable) and duplicated are allowed. --- elements are accessed using keys --- can be nested --- insertion deletion is efficient and searching is not efficient compared to insertion/deletion. --- Dict_methods: --- copy(), clear(), fromkeys(), get(), items(), keys(), values(), pop(), popitem(), setdefault(), update() """ # # --------------------------------------------------------------------------- # Syntax <name_for_dict> = {key:value, key:value, ..... ,key:value} # my_preferences = {'fruit': 'pomegranate', 'bike': 'honda', 'cuisine': 'indian', 'weather': 'winter', 'sport': 'cricket'} # print(my_preferences) # # --------------------------------------------------------------------------- # items() method is used to return the list with Key, value pair as tuple print("Items in Dictionary:-", my_preferences.items()) # items = my_preferences.items() # # for item in my_preferences.items(): # print(item) # # # --------------------------------------------------------------------------- # # keys() method is used to return the list with all dictionary keys. # keys = my_preferences.keys() # print("Keys of the dictionary are:-", keys) # s = "bike" # if "bike" in keys: # print() # # approved = ['fruit', 'bike', 'cuisine', 'weather'] # # for key in my_preferences.keys(): # if key in approved: # print(key) # # # --------------------------------------------------------------------------- # values() method is used to return the list with all dictionary values. # values = my_preferences.values() # print(values) # # # --------------------------------------------------------------------------- # get(key) , returns the value of given key # bike = my_preferences.get("scooter", "TVS") # print(bike) # bike = my_preferences["scooter"] # print(bike) # # # --------------------------------------------------------------------------- # fromKeys(sequence_type, default_value) # creates a dictionary from the sequence_type given, default value is None # message = "hello" # # new_dict = dict.fromkeys(message) # # print(len(new_dict)) # # print(len(message)) # # print(new_dict) # new_dict2 = dict.fromkeys(message, 10) # print(new_dict2) # phone_list = ["brand", "model", "price"] # phone_dict = dict.fromkeys(phone_list, "sony") # print(phone_dict) # #--------------------------------------------------------------------------- # setdefault(key,optional_default_value), returns value of key if key is present. # adds key to dict if key not present, if default_value is given the value is set with key or else None is set # value = my_preferences.setdefault("bike") # print(value) # value = my_preferences.setdefault("scooter", "TVS") # print(value) # print(my_preferences) # #--------------------------------------------------------------------------- # # update(), used to update an existing dict with new dict # new_dict = {"state": "maharashtra", "city": "solapur/pune"} # my_preferences.update(new_dict) # print(my_preferences) # #---------------------------------------------------------- # # pop() & popitem() # # value = my_preferences.pop("bike") # print(value) # print(my_preferences) # value = my_preferences.pop("bike", False) # default value # # if value: # print("key is present") # else: # print("key is not present") # print(value) # print(my_preferences) # my_preferences.popitem() # my_preferences.popitem() # print(my_preferences) #----------------------------------------------------------------- # # copy() - copy # copy_dict = my_preferences.copy() # print(copy_dict) # #--------------------------------------------------------------- # my_preferences.clear() # print(my_preferences) #
db390cb7324b0daad27cc5265cf07427983b0234
CrossLangNV/DGFISMA_definition_extraction
/data/preprocessing.py
1,011
3.984375
4
from typing import List import nltk def tokenize(sentences, option='nltk'): """For experimenting with different tokenization options: * TODO BERT tokenizer * TODO Spacy * https://www.nltk.org/ Args: sentences: list of sentence strings. option: If option not within available options it will raise an error Returns: list with list of sentence tokens. """ tokenizers = {'nltk': nltk_tokenizer} return tokenizers[option](sentences) def nltk_tokenizer(sentences: (str, List[str])) -> ([List[str]], List[List[str]]): """ tokenizer based from https://www.nltk.org/ Args: sentences: can be either list of sentences or single sentence Returns: """ if isinstance(sentences, list): sentences_tok = [] for sentence in sentences: sentences_tok.append(' '.join(nltk.word_tokenize(sentence))) else: sentences_tok = nltk.word_tokenize(sentences) return sentences_tok
ef30acf26fa0919de2e533be28cf0672e90462f9
lvolkmann/couch-to-coder-python-exercises
/Lists/battle_ship.py
4,173
4.09375
4
""" Fill in the methods below to get this battleship program working HINT: You may want to use exceptions when checking for bounds of the board """ import random def display_board_hits(board, hit): for row in range(len(board)): for col in range(len(board[0])): if hit[row][col]: print("X", end=" ") elif board[row][col] == -1: print("O", end=" ") else: print("_", end=" ") print() def initialize_board(ships): board = [ [0 for i in range(8)] for i in range(8)] hits = [ [False for i in range(8)] for i in range(8)] while ships > 0: length = random.randint(2,4) start_row = random.randint(0,7) start_col = random.randint(0,7) vert = random.choice([True, False]) if vert: try: for row_increment in range(length): if board[start_row + row_increment][start_col] != 0: raise IndexError for row_increment in range(length): board[start_row + row_increment][start_col] = length except IndexError: continue else: try: for col_increment in range(length): if board[start_row][start_col + col_increment] != 0: raise IndexError for col_increment in range(length): board[start_row][start_col + col_increment] = length except IndexError: continue ships -= 1 return board, hits def check_hit_and_update(row, col, board, hit): if board[row][col] != 0 and not hit[row][col]: hit[row][col] = True return True else: board[row][col] = -1 return False def get_move(board, hit): while True: try: row = int(input("Row ==>")) print() col = int(input("Column ==>")) if hit[row][col]: raise TypeError if board[row][col] == -1: raise TypeError return row, col except ValueError: print("It's gotta be an int") except IndexError: print("Out of range") except TypeError: print("We've seen that before") def get_opp_move(board, hit): while True: try: row = random.randint(0,len(board) -1) col = random.randint(0, len(board[0]) -1) if board[row][col] == -1 or hit[row][col]: raise TypeError return row, col except TypeError: continue def check_win(board, hit): hits = 0 hits_needed = 0 for row in board: for col in row: if col != 0: hits_needed += 1 for row in hit: for col in row: if col: hits += 1 if hits == hits_needed: return True else: return False def play(): ship_num = 4 winner = False user_board, user_hits = initialize_board(ship_num) opp_board, opp_hits = initialize_board(ship_num) user_hits_opp = False opp_hits_user = True while not winner: print("Your Turn") display_board_hits(opp_board, opp_hits) user_row, user_col = get_move(opp_board, opp_hits) user_hits_opp = check_hit_and_update(user_row, user_col, opp_board, opp_hits) if user_hits_opp: print("You got a hit!") else: print("You missed!") winner = check_win(opp_board, opp_hits) if winner: break print() print("Computer Turn") opp_row, opp_col = get_opp_move(user_board, user_hits) opp_hits_user = check_hit_and_update(opp_row, opp_col, user_board, user_hits) if opp_hits_user: print("You got hit!") else: print("You're safe this round!") display_board_hits(user_board, user_hits) winner = check_win(user_board, user_hits) print() play()
f91dbbcfab56832d07cde1a4ba534de573cacdbf
anacarolina1002/infosatc-lp-avaliativo-04
/atividade1.py
662
4.03125
4
#Crie uma função que receba uma palavra por parâmetro e permita inverter a ordem #dessa palavra. Exemplo: ATOR = ROTA #Só nessa atividade tem vários commits pq usei ela pra me ajudar no próximo exercício #pra ver como ficavam as palavras ao contrário pra usar lá #e tbm pq uma hora commitei tudo junto e fiz bagunça def parametroNome(nome): if (nome==''): #Declaração de nome como uma string return nome #Retorna o nome ao contrário parametroRes = nome[-1] + parametroNome(nome[:-1]) return parametroRes #Função que decrementa as letras e reescreve ao contrário print(parametroNome('Alice'))#Definição de nome como "Alice"
ff6f7434ebf01986756140e545975af380e4b707
AmandaRH07/AulaEntra21_AmandaHass
/Prof01/Aula11/Exercicios/exercicio1.py
1,098
4.3125
4
"""Exercício 1 (não usar o continue ou o break) Crie um programa que mostre um menu com as seguites opções: 1) Soma 2) Subtração 3) Multiplicação S) Para sair! Para número 1: Peça 2 números e mostre a soma deles Para número 2: Peça 2 númeors e mostre a subtração deles Para númeor 3: Peça 2 números e mostre a multiplicação deles Para S: Mostre uma mensagem de despedida e termine o programa. Para qualquer outra opção deve aparecer a mensagem "Opção Inválida" """ opcao = '' while opcao !='S': n1 = float(input("Insira o primeiro número: ")) n2 = float(input("Insira o segundo número: ")) opcao = input(""" 1) Soma 2) Subtração 3) Multiplicação S) Para sair! Selecione a opção: """).upper() if opcao == '1': print(f'A soma é: {n1+n2:.2f}\n') elif opcao == '2': print(f'A subtração é: {n1-n2:.2f}\n') elif opcao == '3': print(f'A multiplicação é: {n1+n2:.2f} \n') elif opcao == "S": print("Você escolheu sair\n") else: print("Operação inválida\n")
79c58ae9e76a5a245ff38e64232741056aed8ac1
niranjan2822/Interview1
/Convert Key-Value list Dictionary to List of Lists.py
1,903
4.625
5
# Convert Key-Value list Dictionary to List of Lists --we need to perform the flattening a key value pair of dictionary # to a list and convert to lists of list. ''' Input: {‘gfg’: [1, 3, 4], ‘is’: [7, 6], ‘best’: [4, 5]} Output : [[‘gfg’, 1, 3, 4], [‘is’, 7, 6], [‘best’, 4, 5]] ''' # Method #1 : Using loop + items() # This brute force way in which we can perform this task. In this, # we loop through all the pairs and extract list value elements using items() and render in a new list. # Python3 code to demonstrate working of # Convert Key-Value list Dictionary to Lists of List # Using loop + items() # initializing Dictionary test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Convert Key-Value list Dictionary to Lists of List # Using loop + items() res = [] for key, val in test_dict.items(): res.append([key] + val) # printing result print("The converted list is : " + str(res)) # Output : # The original dictionary is : {‘gfg’: [1, 3, 4], ‘is’: [7, 6], ‘best’: [4, 5]} # The converted list is : [[‘gfg’, 1, 3, 4], [‘is’, 7, 6], [‘best’, 4, 5]] # Method #2 : Using list comprehension # This task can also be performed using list comprehension. # In this, we perform the task similar to above method just in one-liner shorter way. # Python3 code to demonstrate working of # Convert Key-Value list Dictionary to Lists of List # Using list comprehension # initializing Dictionary test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Convert Key-Value list Dictionary to Lists of List # Using list comprehension res = [[key] + val for key, val in test_dict.items()] # printing result print("The converted list is : " + str(res))
35d7388dbfcef88a1c1121183efc833529f613be
ssmmchoi/python1
/workspace/chap01_Basic/lecture/step03_string.py
3,068
4.125
4
''' 문자열 처리 - 문자열(string) : 문자들의 순서(index)의 집합 - indexing / slicing 가능 - 문자열 = 상수이면, 수정 불가 ''' # 1. 문자열 처리 # 1) 문자열 유형 lineStr = "this is one line string" # 한 줄 문자열 print(lineStr) multiStr = '''this is multi line string''' print(multiStr) multiStr2 = 'this\nis multi line\nstring' print(multiStr2) # sql문 : 부서번호 deptno = int(input('부서번호 입력 :')) 20 query = f"""select * from emp where deptno = {deptno} order by sel desc""" print(query) deptno = int(input('부서변호 입력 : ')) 30 query = """select * from emp where deptno = {} order by sel desc""".format(deptno) print(query) deptno = int(input('부서번호 입력 : ')) 30 query = """select * from emp where deptno = %d order by sel desc""" %(deptno) print(query) deptno = int(input('부서번호 입력 : ')) query = """select * from emp where deptno = """, format(deptno, "2d"), "\norder by sel desc" print(query) # 2) 문자열 연산(+, *) print('Python' + " program") # Python program 결합연산자 print('python' + 37) # type error print('python' + '37') # python37 print('='*30) # ============================== ''' object.member변수 or object.member() 함수 p.51 int.member str.member ''' # 3. 문자열 처리 함수 print(lineStr, type(lineStr)) print('문자열 길이 : ', len(lineStr)) # 문자열 길이 : 23 print(lineStr.upper()) # THIS IS ONE LINE STRING print(lineStr.swapcase()) print(lineStr.count("x")) # 0 print('t의 글자수 : ', lineStr.count("t")) # t의 글자수 : 2 # 접두어 : 시작문자열 print(lineStr.startswith("this")) # True print(lineStr.startswith("that")) # False # slit : 토큰 생성 words = lineStr.split(' ') print(words) # ['this', 'is', 'one', 'line', 'string'] lineStr.split(sep=' ') # ['this', 'is', 'one', 'line', 'string'] print('단어 개수 : ', len(words)) # 단어 개수 : 5 ' '.join(words) # 'this is one line string' lineStr.index("i") # 2 lineStr.rfind("i") # 20 lineStr.replace("i", "o") # 'thos os one lone strong' sentence = " ".join(words) print(sentence) # 문단 -> 문장 print(multiStr) sentences = multiStr.split('\n') print(sentences) # ['this', 'is multi line', 'string'] print('문장 개수(길이?) : ', len(sentence)) # 문장 개수(길이?) : 3 multiStr2 = " ".join(sentences) print(multiStr2) # 4) indexing/slicing print(lineStr[0]) # t print(lineStr[-1]) # g print(lineStr[0:4]) # this print(lineStr[4]) print(lineStr[-6:]) # string # join : "구분자".join(str) print(sentence) para = ','.join(sentences) print(para) # 2. escape 문자 처리 ''' escape 문자 : 명령어 이외 특수문자(', ", \n, \t, \b) ''' print("\nescape 문자") # # escape 문자 print("\\nescape 문자") # \nescape 문자 print(r"\nescape 문자") # \nescape 문자 # C:\python\work\test print("C:\python\work\test") # C:\python\work est \t를 텝 키로 인식 print(r"C:\python\work\test") # C:\python\work\test print("C:\python\work\\test") # C:\python\work\test
cc696b95ca3298f976203b66e6004fea86f155c4
chosaihim/jungle_codingTest_study
/FEB/14th/용-즐거운막대기.py
1,476
3.6875
4
# https://programmers.co.kr/learn/courses/30/lessons/42860 name = "JAZ" # name = 'BBABA' # name = 'BBBAAB' # name = 'BBAABB' from collections import deque def ordering(name): name_list = list(name) for i in range(len(name_list)): name_list[i] = ord(name_list[i]) return name_list # A : 65 / Z :90 / mid : 77.5 def updown(letter): # 만약 65~77까지면 A에서부터 움직인다. if 65 <= letter <= 77: return letter-65 else: return 91-letter # cursor는 idx=0부터 시작한다. # 가장 가까운 def leftright(order): rtn = 0 cursor = 0 order[0] = 0 while sum(order) > 0: left = 1 right = 1 # 좌탐색 while order[cursor - left] == 0: left += 1 # 우탐색 while order[cursor + right] == 0: right += 1 # 왼쪽이 가까운 경우 if left < right: rtn += left cursor -= left else: rtn += right cursor += right order[cursor] = 0 return rtn def solution(name): order = ordering(name) que = deque() answer = 0 for i in range(len(order)): order[i] = updown(order[i]) answer += order[i] # A가 있는 자리는 0이 될 것이다. 좌우로 움직이는 경우의 수는 A만 신경쓰면 된다. answer += leftright(order) return answer print(solution(name))
1664308287f58b836f3e8d0fb03b33bca6802f8f
spaceack/codewars
/Title_Case(6kyu).py
2,109
3.9375
4
def title_case(title, minor_words = ''): new_list = [] new_string = '' title_l = title.split() minor_words_l = minor_words.split() minor_words_l_lower = [x.lower() for x in minor_words_l] title_l_num = len(title_l) minor_words_l_num = len(minor_words_l) # first word upper() if title_l_num > 0: new_list.append(initial_upper(title_l[0])) if title_l_num > 1 and minor_words_l_num > 0: for t in range(1, title_l_num): if title_l[t].lower() in minor_words_l_lower: new_list.append(title_l[t].lower()) else: new_list.append(initial_upper(title_l[t])) new_string = ' '.join(new_list) return new_string else: for t in range(1, title_l_num): new_list.append(initial_upper(title_l[t])) new_string = ' '.join(new_list) return new_string else: return new_string def initial_upper(word): new_word = '' if len(word) > 0: new_word = word[0].upper() if len(word) > 1: for t in range(1, len(word)): new_word = new_word + word[t].lower() return new_word def test(title, minor_words, expect): answer = title_case(title) if minor_words is None else title_case(title, minor_words) if answer == expect: result = 'AC! ' else: result = 'Error! ' message = "Gave title={0}{1}. Expected {2} but got {3}.".format( repr(title), '' if minor_words is None else ', minor_words=' + repr(minor_words), repr(expect), repr(answer)) print(result + message) # Test.expect(answer == expect, message) if __name__ == '__main__': test('', '', '') test('aBC deF Ghi', None, 'Abc Def Ghi') test('ab', 'ab', 'Ab') test('a bc', 'bc', 'A bc') test('a bc', 'BC', 'A bc') test('First a of in', 'an often into', 'First A Of In') test('a clash of KINGS', 'a an the OF', 'A Clash of Kings') test('the QUICK bRoWn fOX', 'xyz fox quick the', 'The quick Brown fox')
601bdbaef312b2cbbff6a06b59084b1ff4905739
htmlprogrammist/kege-2021
/tasks_12/task_12_18590.py
119
3.703125
4
s = '1' * 45 + '2' * 45 while '111' in s: s = s.replace('111', '2', 1) s = s.replace('222', '1', 1) print(s)
b753d5b99cee599954623d3575d175177627eeca
coderzhuying/Algorithm
/tencent.py
451
3.59375
4
def minDistance(s): stack = [] for i in range(len(s)): if not stack: stack.append(s[i]) else: if stack[-1] == '0' and s[i] == '1': stack.pop() elif stack[-1] == '1' and s[i] == '0': stack.pop() else: stack.append(s[i]) return len(stack) if __name__ == "__main__": count = input() s = input() print(minDistance(s))
8d083b8fbe3fdf2bf14b87085270e1bc43811379
rsshalini/practice_programs
/06_30_2018/trailingzero.py
799
4.40625
4
#!usr/bin/python #counts the number of trailing zero for n factorial import math def count_trailing_zero_n_fact(n): n_factorial = str(math.factorial(n)) reversed_factorial = reversed(n_factorial) trailing_zero_count = 0 if n_factorial.endswith('0'): for digit in reversed_factorial: #print "i", i if digit == '0': trailing_zero_count += 1 #print "ct", trailing_zero_count else: break return "Number of trailing zero in {0} factorial {1} is {2}".format(n, n_factorial,trailing_zero_count) else: return "No trailing zeros in {0} factorial".format(n) if __name__ == "__main__": n = int(raw_input("Enter an integer:")) print count_trailing_zero_n_fact(n)
85f3584646304718c6344956055b173af6779cda
zzzpp1/python
/python/停车场/ParkingLot.py
7,696
3.6875
4
from Car import Car ''' 需求1构造一个停车场,停车场可以停车和取车,停车成功后得到停车票。 用户取车的时候也需要提供停车票,停车票有效,才可以成功取到车。 ''' class ParkingLot(Car): def __init__(self, capacity=2,park_name ='park'): # todo: 构造停车场所需的字段 self.capacity = capacity #停车场最大停车数 self.name = park_name #停车场名字 self.cars = [] #车辆信息和停车票信息一致,停车证 self.cur_car = len(self.cars) #已停车数量 self.ticket_mark = [0] * capacity # 停车位停车情况 self.car_to_carid=dict() # 停车位和车辆信息对应情况 def park_car(self, car: Car): # todo: 实现停车功能,成功停车后返回一个不重复的物体(object/uuid/……)作为停车票 self.cur_car = len(self.cars) if self.cur_car>=self.capacity : print ("车库已满") return None for i in range(self.capacity): if self.ticket_mark[i] ==0: self.ticket_mark[i]=1 self.car_to_carid[car] = i # 将carid与停车票存储下来 break self.cars.append(car) ticket=car.car_number print("车牌号为%s的车辆成功入库,停车位为%d" % (car.car_number,self.car_to_carid[car])) #print (self.cars) return ticket def take_car(self,ticket): flag=0 for car in self.cars: if car.car_number == ticket: flag=1 # todo: 实现通过车票取车的功能 car_carid=self.car_to_carid[car] self.ticket_mark[car_carid]=0 print("停车位为%d已空"%car_carid) self.cars.remove(car) self.car_to_carid.pop(car) print("车牌号为%s的车辆成功出库" % ticket) return car if flag==0: print("停车票错误" ) return None ''' 需求2构造一个停车小弟(ParkingBoy),他能够将车顺序停放到多个停车场,并可以取出 ''' class parkingboy(ParkingLot): def __init__(self,parking_lot:ParkingLot,parklot_number=2): # todo: 构造停车场所需的字段 self.car_to_parklot = dict() #停车场和车辆对应表 self.parklot_number = parklot_number #停车场数量 self.park_lots=[] #停车场列表 self.car_list=[] #车辆停车清单 for i in range(self.parklot_number): park="park%d" %i parklot=ParkingLot(park_name=park) self.park_lots.append(parklot) self.park_mark = [0] * parklot_number #停车场停车情况 def park_car(self, car:Car): # todo: 实现停车功能,成功停车后返回一个不重复的物体(object/uuid/……)作为停车票 flag=0 for park_lot in self.park_lots: park_lot.cur_car = len(park_lot.cars) if park_lot.capacity - park_lot.cur_car: flag=1 print("停车场号%s"%park_lot) ticket = park_lot.park_car(car) self.car_list.append(car) self.car_to_parklot[car] = park_lot return ticket,park_lot if flag==0: print('所有停车场已停满,无法停车!') return None def take_car(self,ticket): flag = 0 for car in self.car_list: if car.car_number == ticket: flag = 1 park_lot=self.car_to_parklot[car] park_lot.take_car(ticket) self.car_list.remove(car) if flag==0: print("停车票错误" ) return None ''' 需求3构造一个聪明的停车小弟(Smart Parking Boy),他能够将车停在空车位最多的那个停车场 ''' class smart_parkingboy(parkingboy): def park_car(self, car:Car): # todo: 实现停车功能,成功停车后返回一个不重复的物体(object/uuid/……)作为停车票 remainder = [] for park_lot in self.park_lots: park_lot.cur_car = len(park_lot.cars) temp=park_lot.capacity - park_lot.cur_car if temp: remainder.append(temp) myindex = remainder.index(max(remainder)) park_lot=self.park_lots[myindex] print("停车场号%s"%park_lot) ticket = park_lot.park_car(car) self.car_list.append(car) self.car_to_parklot[car] = park_lot return ticket,park_lot def take_car(self,ticket): flag = 0 for car in self.car_list: if car.car_number == ticket: flag = 1 park_lot=self.car_to_parklot[car] park_lot.take_car(ticket) self.car_list.remove(car) if flag==0: print("停车票错误" ) return None ''' 需求4构造一个超级停车小弟(Super Parking Boy),他能够将车停在空置率最高的那个停车场 ''' class super_parkingboy(parkingboy): def park_car(self, car:Car): # todo: 实现停车功能,成功停车后返回一个不重复的物体(object/uuid/……)作为停车票 remainder = [] for park_lot in self.park_lots: park_lot.cur_car = len(park_lot.cars) temp=park_lot.capacity - park_lot.cur_car temp = temp / park_lot.capacity if temp: remainder.append(temp) myindex = remainder.index(max(remainder)) park_lot=self.park_lots[myindex] print("停车场号%s"%park_lot) ticket = park_lot.park_car(car) self.car_list.append(car) self.car_to_parklot[car] = park_lot return ticket,park_lot def take_car(self,ticket): flag = 0 for car in self.car_list: if car.car_number == ticket: flag = 1 park_lot=self.car_to_parklot[car] park_lot.take_car(ticket) self.car_list.remove(car) if flag==0: print("停车票错误" ) return None ''' 需求5构造停车场的经理(Parking Manager),他要管理多个停车仔,让他们停车,同时也可以自己停车 ''' class parkingmanager(parkingboy): def boy_park(self, car, boy,park_manner): if boy=='parkingboy': park_manner=parkingboy() park_manner.park_car(car) if boy=='smartparkingboy': park_manner=smart_parkingboy() park_manner.park_car(car) if boy=='superparkingboy': park_manner=super_parkingboy() park_manner.park_car(car) if __name__ == "__main__": parking_lot = ParkingLot(2) while True: choice = input("请输入你要的功能:(1)存车;(2)取车:\n") if choice == '1': car_number = input("请输入车牌号:") car_owner = input("请输入车主姓名:") contact_way = input("请输入车主联系方式:") car_color = input("请输入车颜色:") car_model = input("请输入车型:") car = Car(car_number, car_owner, contact_way, car_color, car_model) ticket = parking_lot.park_car(car) print("取车证",ticket) if choice == '2': car_number = input("请输入车牌号:") ticket = car_number car=parking_lot.take_car(ticket)
e149658194f5abdd88bbc334b9d9471bceecc475
heyberto/Tutorial-python
/Tutorial1.8.py
322
4.09375
4
#NESTED LOOPS filas = int(input('Cuantas filas quieres que haya?: ')) columnas = int(input('Cuantas columnas quieres que haya?: ')) simbolo = input('Dime el simbolo que quieres utilizar: ') for y in range (filas): for z in range(columnas): print(simbolo, end='') print()
9d96ba56e9d1e1e8ce90d67bd28ac80a8283afd4
shuoshuren/PythonPrimary
/18文件/xc_05_python2中文.py
156
3.921875
4
# *-* coding:utf8 *-* # 引号前面的u告诉解释器这是一个utf8编码格式的字符串 str = u"hello世界" print(str) for c in str: print(c)
965f6e11c68697adc306c833c4cc83c5b27c0556
baolibin/leetcode
/程序员面试金典/面试题 16.08. 整数的英语表示.py
1,991
3.890625
4
''' 面试题 16.08. 整数的英语表示 给定一个整数,打印该整数的英文描述。 示例 1: 输入: 123 输出: "One Hundred Twenty Three" 示例 2: 输入: 12345 输出: "Twelve Thousand Three Hundred Forty Five" 示例 3: 输入: 1234567 输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" 示例 4: 输入: 1234567891 输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" ''' UNITS = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'] TENS = [None, None, 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'] class Solution: def numberToWords(self, num: int) -> str: if not num: return 'Zero' billion = num // 1000000000 num %= 1000000000 million = num // 1000000 num %= 1000000 thousand = num // 1000 num %= 1000 def three(num): if num < 20: return UNITS[num] elif num < 100: res = TENS[num // 10] remains = num % 10 if remains: res += ' ' + UNITS[remains] return res else: res = UNITS[num // 100] + ' ' + 'Hundred' remains = num % 100 if remains: res += ' ' + three(remains) return res res = [] if billion: res.append(self.numberToWords(billion)) res.append('Billion') if million: res.append(three(million)) res.append('Million') if thousand: res.append(three(thousand)) res.append('Thousand') if num: res.append(three(num)) return ' '.join(res)
e7f58d129578b666e9e9d80c3d3be576be9fe62f
rishabjn/Iris-Classifier
/decision_tree_iris.py
956
3.5
4
import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score iris_data = pd.read_csv("iris.csv") #Reading data using pandas featues = iris_data[["SepalLength","SepalWidth","PetalLength","PetalWidth"]] #Selecting features for training target_var = iris_data.Class #selecting target class ftrain, ftest, ttrain,ttest = train_test_split(featues,target_var,test_size=0.2) #splitting dataset into train set and test set model = DecisionTreeClassifier() # Running the Model fitted_model = model.fit(ftrain, ttrain) #fitting on the training dataset prediction = fitted_model.predict(ftest) #prediction on test dataset print(confusion_matrix(ttest,prediction)) #Printing confusion matrix and accuracy print(accuracy_score(ttest, prediction))
9c3cc6a74751fdda23ffb9465bc806398a6b119e
razvannica/Numerical-Calculus
/Homework4/main.py
4,472
3.78125
4
""" Author: Răzvan NICA Study Year: 3 Group: English """ import numpy import copy import time def read_file(path, to_check): size = 0 input_list = [] matrix = [] with open(path) as file: k = 0 for num, lines in enumerate(file, 1): if num < size + 3 and k != 0: try: input_list.append(float(lines.split()[0])) except: continue if k == 0: size = int(lines.split()[0]) k = 1 matrix = [[] for i in range(0, size)] if num > size + 3: line = lines.split(",") value = float(line[0]) index_line = int(line[1]) index_col = int(line[2]) if index_line == index_col: ok = 0 for matrix_line in matrix[index_line]: if len(matrix_line) > 1: if matrix_line[1] == index_col: matrix_line[0] += value ok = 1 break if ok == 0: matrix[index_line].append(list((value, index_col))) else: ok = 0 for matrix_line in matrix[index_line]: if len(matrix_line) > 1: if matrix_line[1] == index_col: matrix_line[0] += value ok = 1 break if ok == 0: matrix[index_line].insert(0, list((value, index_col))) if to_check: for index_line in range(0, size): if len(matrix[index_line]) > 10: print(matrix[index_line]) raise ValueError("The matrix has more than 10 inputs into line " + str(index_line)) return size, input_list, matrix def main_diagonal_validation(A, n): for i in range(0, n): if A[i][len(A[i]) - 1][0] == 0: return False return True def product_with_array(A, x, n): C = [] for index in range(0, n): sum = 0 for A_list in A[index]: val_x = x[A_list[1]] sum += A_list[0] * val_x C.append(sum) return C def norm(a_list, n): return numpy.linalg.norm(a_list, numpy.inf) def compute_xc(xkplus1, xk, b, A, n): for i in range(0, n): sum1 = 0 sum2 = 0 for j in A[i]: if j[1] <= i - 1: sum1 += j[0] * xkplus1[j[1]] if j[1] >= i + 1: sum2 += j[0] * xk[j[1]] xkplus1[i] = (b[i] - sum1 - sum2) / A[i][len(A[i]) - 1][0] return xkplus1 def gauss_seidel(A, b, n, EPS): xc = [0 for i in range(0, n)] xp = [0 for i in range(0, n)] iterations = 0 xc = compute_xc(xc, xp, b, A, n) delta_x = norm( numpy.subtract(numpy.array(xc), numpy.array(xp)), n ) iterations += 1 while EPS <= delta_x <= 10 ** 8 and iterations <= 10000: xp = copy.copy(xc) xc = compute_xc(xc, xp, b, A, n) delta_x = norm( numpy.subtract(numpy.array(xc), numpy.array(xp)), n ) iterations += 1 if delta_x < EPS: return iterations, xc else: return 0, 0 if __name__ == "__main__": EPS = 0.00001 for index in range(0, 5): print("\nMatrix " + str(index + 1) + ":") """ Reading from file """ size, b, A = read_file("data/m_rar_2018_" + str(index + 1) + ".txt", True) if main_diagonal_validation(A, size): """ Searching for solutions with gauss_seidel """ t0 = time.time() iterations, xgs = gauss_seidel(A, b, size, EPS) t1 = time.time() """ Printing the outputs """ if iterations != 0: print("\tNumber of iterations: " + str(iterations)) print("\tInducted matrix norm: " + str( max(abs(i) for i in numpy.subtract(product_with_array(A, xgs, size), b)))) print("\tTime: " + str(t1 - t0)) print("\tSolution xi= " + str(xgs[:5])) else: print("\tMatrix " + str(index + 1) + " is disjoint") else: print("\tThere are null values on the main diagonal of matrix " + str(index + 1))
60c413063b2a41e58661dad0a2cc0710577222ed
toshitaka18/schoo
/PycharmProjects/SampleProject/fizz.py
416
3.9375
4
#fizzbuzz問題を再現、正しいくつまでカウントするか引数で指定 def fizzbuzz(max_num): for i in range(1,max_num ): if i % 15 == 0: print('fizzbuzz') elif i % 3 == 0: print('fizz') elif i % 5 == 0: print('buzz') else: print(i) max_num = int(input('数値を入力してください')) print(fizzbuzz(max_num))
f0e18d92da8d7174326b09ad95de8683e9f5d9b2
spandanasalian/Python
/stringbalace.py
341
3.953125
4
def stringBalanceCheck(s1,s2): flag=True for char in s1: if char in s2: continue else: flag=False return flag s1="th" s2="Python" flag=stringBalanceCheck(s1, s2) print("S1 and s2 are balance",flag) s1="tha" s2="Python" flag=stringBalanceCheck(s1, s2) print("s1 and s2 are balanced",flag)
225483d70b95e91d25b3919ced0009bd5e6076cf
GSantos23/Crash_Course
/Chapter2/Exercises/ex2_8.py
432
4.28125
4
# Exercise 2.8 # Number Eight: Write addition, subtraction, multiplication, and division operations that each result in the number 8. # Be sure to enclose your operations in print statements to see the results. You should create four lines that look # like this: # print(5 + 3) # # Your output should simply be four lines with the number 8 appearing once on each line. print(5 + 3) print(10 - 2) print(4 * 2) print(80 / 10)
89dd42eabc01f3d1865bad4210c6c2b6dd35d99c
fotavio16/PycharmProjects
/pythonjogos/cap8_jogo.py
1,815
3.984375
4
''' Bagels ''' from random import randint, shuffle def abertura(): print("Estou pensando em um número de 3 dígitos. Tente adivinhar o que é.") print("Aqui estão algumas dicas:") print("Quando digo: Isso significa:") print("Pico: Um dígito está correto, mas na posição errada.") print("Fermi: Um dígito está correto e na posição correta.") print("Bagels: Nenhum dígito está correto.") print("Eu pensei em um número. Você tem 10 palpites para obtê-lo.") def sorteia(): numeros = '0123456789' numeros = list(numeros) for i in range(10): shuffle(numeros) return ''.join(numeros)[:3] def jogarDeNovo(): if str(input("Quer jogar novamente? (S/N)")).upper()[0] == 'S': return True else: return False def mostrarDicas(chave, palpite): dica = '' for i in range(len(palpite)): if palpite[i] in chave: if palpite[i] == chave[i]: dica = dica + 'Fermi ' else: dica = dica + 'Pico ' if len(dica) == 0: dica = 'Bagels' print(dica) maxTentativas = 10 tentativas = 1 while True: if tentativas == 1: abertura() chave = sorteia() #print(chave) palpite = str(input(f'Tentativa {tentativas}: ')) if palpite == chave: print("Você Venceu!! Parabéns!!!") if jogarDeNovo(): tentativas = 1 else: print("GAME OVER") break else: mostrarDicas(chave, palpite) tentativas += 1 if tentativas > 10: print("Você gastou todas as tentativas. Você perdeu.") print(f'A palavra secreta é {chave}.') if jogarDeNovo(): tentativas = 1 else: print("GAME OVER") break
deca947ece09c0a927ec07667da83b3df2867cc4
AndersonHJB/Student_homework
/早期代码/作业二/yunshi_1.py
7,710
3.875
4
import random # 输入性别或退出 while True: gender = input('请输入您的性别(F/M),输入(exit)退出:\r\n') if gender.upper() == 'F' or gender.upper() == 'M': gender = gender.upper() break elif gender.upper() == 'EXIT': print('\r\n\r\n感谢使用,再见!') exit() else: print('您的输入有误,请重新输入\r\n') # 输入年龄并判断年龄层 while True: age = input('请输入您的年龄(0-100):\r\n') try: age = int(age) if 0 <= age <= 100: break else: print('您的输入有误,请输入0-100的整数\r\n') except: print('您的输入有误,请输入0-100的整数\r\n') # 定义函数 def fortune_test(gender, age): you = 0 if 0 <= age < 18: you = 1 elif age == 18: you = 2 elif 18 < age < 30: you = 3 elif 30 <= age < 60: you = 4 # 判断年龄层并打印随机字符串 if you == 3: if gender == 'F': lucky = ['找到女朋友', '继承巨额财富', '找到好工作', '买彩票中500万大奖', '创业成功,收获天使轮投资'] unlucky = ['被好兄弟绿', '北漂失败,落魄回家', '丢掉工作,女友坐上别人的宝马车', '创业失败,欠下巨额债务'] case_list = random.choice([lucky, unlucky]) case_len = len(case_list) random_index = random.randint(0, case_len - 1) else: lucky = ['找到男朋友', '继承巨额财富', '找到好工作', '买彩票中500万大奖', '创业成功,收获天使轮投资'] unlucky = ['被闺蜜绿', '北漂失败,落魄回家', '丢掉工作,男友的宝马车副驾坐着别的妹子', '创业失败,欠下巨额债务'] case_list = random.choice([lucky, unlucky]) case_len = len(case_list) random_index = random.randint(0, case_len - 1) print('在接下来的{time}个月,你会{case}。'.format(case=case_list[random_index], time=random.randint(1, 12))) elif you == 1: lucky = ['顺利升学', '发现亲爹很有钱', '拿到三好学生', '期末全过', '考神附体'] unlucky = ['挂科留级', '作弊被发现', '因打架被全校通报批评,记大过处分一次', '因父母参加家长会发现你成绩垫底而被揍'] case_list = random.choice([lucky, unlucky]) case_len = len(case_list) random_index = random.randint(0, case_len - 1) print('在接下来的{time}个月,你会{case}。'.format(case=case_list[random_index], time=random.randint(1, 12))) elif you == 2: school_list = ['复旦大学', '剑桥大学', '哈佛大学', '麻省理工大学', '斯坦福大学', '蓝翔职业技术学院', '克莱登大学', '中关村应用文理学院', '五道口职业技术学院', '陈经纶中学附属大学', '定福庄大学'] school = school_list[random.randint(0, len(school_list) - 1)] if gender == 'F': lucky = ['找到女朋友', '继承巨额财富', '拿到全额奖学金', '买彩票中500万大奖', '获得本校报送硕博连读机会'] unlucky = ['被发好人卡', '被告知成绩单寄错地址,你并没有被学校录取', '被调剂至水暖系烧锅炉专业', '发现班上并没有一个女生'] case_list = random.choice([lucky, unlucky]) case_len = len(case_list) random_index = random.randint(0, case_len - 1) else: lucky = ['找到男朋友', '继承巨额财富', '拿到全额奖学金', '买彩票中500万大奖', '获得本校报送硕博连读机会'] unlucky = ['被闺蜜绿', '被告知成绩单寄错地址,你并没有被学校录取', '被调剂至家政系擦玻璃专业', '发现班上全是女生,你的校园恋爱梦彻底破灭'] case_list = random.choice([lucky, unlucky]) case_len = len(case_list) random_index = random.randint(0, case_len - 1) print('你会考上{school},并{case}。'.format(case=case_list[random_index], school=school)) elif you == 4: if gender == 'F': lucky = ['喜得一子', '升职加薪', '公司上市,作为管理层而获得公司干股,陡然而富', '买彩票中500万大奖', '家族企业获得红杉资本领投,B轮融资达到1.2亿'] unlucky = ['发现妻子出轨', '北漂失败,落魄回家', '丢掉工作,妻子与你离婚并嫁给一位暴发户', '生意失败,欠下巨额债务,在自杀边缘几经挣扎,就此沉沦'] case_list = random.choice([lucky, unlucky]) case_len = len(case_list) random_index = random.randint(0, case_len - 1) else: lucky = ['为丈夫生下一子', '升职加薪', '公司上市,作为管理层而获得公司干股,陡然而富', '买彩票中500万大奖', '家族企业获得红杉资本领投,B轮融资达到1.2亿'] unlucky = ['发现丈夫出轨', '北漂失败,落魄回家', '丢掉工作,丈夫与你离婚并与一20岁嫩模结婚,你净身出户', '生意失败,欠下巨额债务,在自杀边缘几经挣扎,就此沉沦'] case_list = random.choice([lucky, unlucky]) case_len = len(case_list) random_index = random.randint(0, case_len - 1) print('在接下来的{time}个月,你会{case}。'.format(case=case_list[random_index], time=random.randint(1, 12))) else: if gender == 'F': title = '老爷子' else: title = '老太太' print('{title},您已经{age}高龄,此生命数已定,您已知天命。在以后的日子里,您子孙满堂,坐享天伦之乐。'.format(title=title, age=age)) # 执行函数 print('\r\n\r\n====您的运势====\r\n\r\n') fortune_test(gender, age) # 退出程序 print('\r\n\r\n感谢使用,再见!') exit() # 整体来说,思路清晰从输入到输出整体给出的代码清晰。 # 如下几点需要注意的: # 1.已经初步实现代码封装之美,在fortune_test()函数块中已经体现; # 2.在代码运行当中,我个人更加喜欢在不必要的使用while循环时不使用,或者尽量用if之类的判断语句来判断。 # 3.为代码划分区域; # 2.在代码运行当中,我个人更加喜欢在不必要的使用while循环时不使用,或者尽量用if之类的判断语句来判断。 # 就例如这个(看不懂没事,之后在算法课第一节也会讲到)小咖学员有体验课: # 统计一篇文章的词频部分代码: # def find_word_count(words): # # 意见优化的,减少for循环是使用; # # word_count_dict = {} #局部范围字典 # for word in words: # if word in word_count_dict: # word_count_dict[word] += 1 # else: # word_count_dict[word] = 1 # word 本身就算一个单词 # # 未优化的,两个for循环,这篇文章如果有一千字的话,就得循环两千次左右。而上面一个for循环,循环单词本身的数量就行,运行速度有明显的差异。 # # for word in set(words): # # word_count_dict[word] = 0 # # for word in words: # # word_count_dict[word] += 1 # return word_count_dict # 具体如何实现,可以参考简历修改的代码封装示例的思路来。 # 3.为代码划分区域; # 就例如简历生成中的形式: # 1.划分区域: # 虽然,你已经有写这样在每行代码上注释,但可以划分区域,使代码更加清晰明了。 # <----------------user_input_area---------------> # 输入姓名 name = input('请输入您的姓名:>') # 输入毕业院校 # ...... # <----------------while_area---------------> # 输入性别并判断 # while True: # # ...... # # 输入年龄并判断 # while True: # ...... # <----------------print_area---------------> # 格式 print('正在生成简历......') print('\r\n') # ...... # 加油哦!AI悦创
edf80b41083f3aa09b624e0ec1652ec926e5940b
Nahid-Hassan/fullstack-software-development
/code-lab/Python3 - More Variables and Printing.py
842
4.03125
4
import math # Format string my_name = "Md. Nahid Hassan" my_age = 23 # years my_height = 63 # inches my_weight = 50 # kg my_eyes = "Black" my_teeth = "White" my_hair = "Black" print(f"Let's talk about {my_name}.") print(f"He's {my_height} inches tall.") print(f"He's {my_weight} pounds heavy.") print(f"Actually that's not too heavy.") print(f"He's got {my_eyes} eyes and {my_hair} hair.") print(f"His teeth are usually {my_teeth} depending on my coffee.") # this line is tricky, try to get it exactly right total = my_age + my_height + my_weight print(f"If I had {my_age}, {my_height}, and {my_weight} I get {total}.") my_height_in_cm = my_height * 2.54 my_weight_in_ibs = my_weight * 2.20462 my_height_in_meter = my_height_in_cm / 100 print(f"My height in cm: {my_height_in_cm}.") print(f"My BMI = {my_weight / (my_height_in_meter ** 2)}")
fc331fca9451adecc56bdf7a05d0555f27e2f436
jacquerie/leetcode
/leetcode/0419_battleships_in_a_board.py
805
3.671875
4
# -*- coding: utf-8 -*- class Solution: def countBattleships(self, board): result = 0 if not board or not board[0]: return result for i in range(len(board)): for j in range(len(board[0])): result += ( 1 if ( (i == 0 or board[i - 1][j] != "X") and (j == 0 or board[i][j - 1] != "X") and board[i][j] == "X" ) else 0 ) return result if __name__ == "__main__": solution = Solution() assert 2 == solution.countBattleships( [ ["X", ".", ".", "X"], [".", ".", ".", "X"], [".", ".", ".", "X"], ] )
960740cd83825717259d8b3eabcd023d4d8d8623
juansalvatore/algoritmos-1
/ejercicios/11-objetos/11.9.py
2,671
3.53125
4
# Ejercicio 11.9. Implementar el método duplicar(elemento) de ListaEnlazada, que recibe un # elemento y duplica todas las apariciones del mismo. Ejemplo: # L = 1 -> 5 -> 8 -> 8 -> 2 -> 8 # L.duplicar(8) => L = 1 -> 5 -> 8 -> 8 -> 8 -> 8 -> 2 -> 8 -> 8 class _Nodo: def __init__(self, dato): self.dato = dato self.prox = None class LE(): def __init__(self): self.prim = None self.len = 0 def insertar(self, dato, i=None): if i is None: i = self.len if i < 0 or i > self.len: raise Exception('Indice incorrecto') nuevo = _Nodo(dato) if i == 0: nuevo.prox = self.prim self.prim = nuevo else: act = self.prim for n in range(1, i): act = act.prox nuevo.prox = act.prox act.prox = nuevo self.len += 1 def pop(self, i=None): if i is None: i = self.len - 1 if i < 0 or i > self.len: raise Exception('Posicion invalida') else: index = 0 ant = None act = self.prim while act and index < i: ant = act act = act.prox index += 1 if ant is None: dato = self.prim.dato self.prim = act.prox else: dato = act.dato ant.prox = act.prox self.len -= 1 return dato def remove(self, dato): if dato is None: raise Exception('Dato necesario') if self.prim == dato: self.prim = self.prim.prox else: ant = None act = self.prim while act and act.dato != dato: ant = act act = act.prox if act is not None and act.dato == dato: self.prim = self.prim.prox else: if act.dato != dato: raise Exception('Dato not found') ant.prox = act.prox self.len -= 1 def __repr__(self): res = [] act = self.prim while act: res.append(str(act.dato)) act = act.prox return ' - '.join(res) def duplicar(self, dato): act = self.prim while act: if act.dato == dato: nuevo = _Nodo(act.dato) nuevo.prox = act.prox act.prox = nuevo if act.prox: act = act.prox.prox else: return else: act = act.prox
473932cb0c233bd3fad1c2caec11f5560bb512dd
lpelczar/Todo-MVC
/view.py
2,457
3.703125
4
STARTING_INDEX = 1 class MenuView: """ View which shows the menu of the program """ @staticmethod def display(options): """ :param options: dict -> dictionary with number keys and option names values for menu """ print('Todo App. What do you want to do?') for k, v in options.items(): print(' {}. {}'.format(k, v)) print(' ') class AddItemView: """ View which shows the result of adding new item to tasks list """ @staticmethod def display(name): """ :param name: String -> name of the todo item """ print('Item {} successfully added to list!'.format(name)) class ModifyItemView: """ View which shows the result of modifying the item in task list """ @staticmethod def display(index): """ :param index: int -> index of the specific item """ print('Item {} successfully modified!'.format(index + STARTING_INDEX)) class DeleteItemView: """ View which shows the result of deleting item in task list """ @staticmethod def display(index): """ :param index: int -> index of the specific item """ print('Item {} has been successfully deleted!'.format(index + STARTING_INDEX)) class MarkItemView: """ View which shows the result of marking item as done """ @staticmethod def display(index): """ :param index: int -> index of the specific item """ print('Item {} successfully marked as done!'.format(index + STARTING_INDEX)) class DisplayListView: """ View which shows the list of all todo items """ @staticmethod def display(items): """ :param items: list -> list of todo items objects """ if not items: print('List is empty!') else: for k, v in enumerate(items): print(k + STARTING_INDEX, v.deadline if v.deadline else '', v) class DisplaySpecificItemView: """ View which shows the specific item informations: deadline, index, is_done, name, description """ @staticmethod def display(index, item): """ :param index: int -> index of the specific item :param item: TodoItem -> single TodoItem object """ print(index + STARTING_INDEX, item.deadline if item.deadline else '', item, '->', item.description)
caba494777dde6864b51d251f99da508a5ffe415
fabnonsoo/Matplotlib
/SubPlots/sub_plot1.py
1,495
3.796875
4
# SubPlots are used to work with plots in a object oriented matter... # SubPlots are used to replace 'gcf' & 'gca' when plotting/working w/multiple figures & axis... # By default, SubPlots creates a figure & specifies a certain number of rows & columns of axis.... # NB: 'sharex=True' removes the x-axis values for the 1st Plot (i.e All_Devs) import pandas as pd from matplotlib import pyplot as plt plt.style.use('seaborn') data = pd.read_csv('sodatamedianpay.csv') ages = data['Ages'] dev_salaries = data['All_Devs'] py_salaries = data['Python'] js_salaries = data['JavaScript'] # fig, ax = plt.subplots() # Prints the default plots... # To get the Python & JavaScript plots on one plot, we add more axis (ax)--> Prints the SubPlots... # That is it makes the 2 plots be on one figure (see Line 17); fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, sharex=True) # print(ax1) # print(ax2) ax1.plot(ages, dev_salaries, color='#444444', linestyle='--', label='All Devs') ax2.plot(ages, py_salaries, label='Python') ax2.plot(ages, js_salaries, label='JavaScript') ax1.legend() ax1.set_title('Median Salary (USD) by Age') # ax1.set_xlabel('Ages') # Commenting this line removes label of x-axis.. ax1.set_ylabel('Median Salary (USD)') ax2.legend() # ax2.set_title('Median Salary (USD) by Age') # Commenting this line removes title from ax2.. ax2.set_xlabel('Ages') ax2.set_ylabel('Median Salary (USD)') plt.tight_layout() plt.show()
6e9ed828b4ddf7c3d3958ac6d5d311b1395356e1
VAEH/TiempoLibre
/Funcionesv1.py
1,114
4.03125
4
##Realiza el mismo ejercicio pasado, respecto a la evaluación de unos valores #Pero la verdad toma los posibles valores dentro de una matriz """ Escriba un programa que solicite repetidamente a un usuario números enteros hasta que el usuario ingrese 'hecho'. Una vez que se ingresa 'hecho', imprima el número más grande y el más pequeño. Si el usuario ingresa algo que no sea un número válido, agárrelo con un try / except y envíe un mensaje apropiado e ignore el número. Ingrese 7, 2, bob, 10 y 4 y coincida con la salida a continuación. """ largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break try: inp=float(num) except: print("Invalid input") continue for value in [7,2,10,4]: if largest is None: largest = value elif value>largest: largest=value print("Maximum is", largest) for value in [7,2,10,4]: if smallest is None: smallest = value elif value < smallest: smallest=value print("Minimum is", smallest)
7dc0a2aeb566afeb7a2a102720d1f3aa1fc150ba
faizanzafar40/Intro-to-Programming-in-Python
/2. Practice Programs/31. customer_class.py
1,216
4.15625
4
''' Write a Amazon Customer class which can do basic customer operations when using with statement - no need to close the file put file.close() in finally block else it wil stay in memory readlines() returns a list of lines .append() makes a nested list .extend() enlarges the original list .append() and extend() return type None i.e. modify the original list ''' class Customer(): def __init__(self, name, email="na", age="na", address="na",cart=[]): self.name = name self.email = email self.age = age self.address = address self.cart = cart def add_to_cart(self, cart): self.cart.append(cart) print (cart, "added for", self.name) def show_cart(self): return self.cart def remove_from_cart(self, cart): self.cart.remove(cart) print (cart, "removed for", self.name) def place_order(self): print("Order placed successfully!") cust = Customer("faizan") cust.add_to_cart("Pixel Xl 3") cust.add_to_cart("IPhone") cust.add_to_cart("Macbook") print("Selected items", cust.show_cart()) cust.remove_from_cart("IPhone") print("Selected items", cust.show_cart()) cust.place_order()
a7c7a823f35f718155e3fb2ebe0a0a3e3e613e88
shikha1997/Interview-Preparation-codes
/Day5/delgivennode.py
979
3.90625
4
class Node: def __init__(self, data): self.next = None self.data = data class LL: def __init__(self): self.head = None def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def printll(self): t = self.head while (t): print(t.data, end=" ") t = t.next print() def delgivennode(self,k): if(k.next==None): k.data="END" return k.data=k.next.data k.next=k.next.next if __name__ == '__main__': # Create linked list : # 10->20->30->40->50 list1 = LL() list1.append(10) list1.append(20) list1.append(30) # list1.append(40) # list1.append(50) list1.delgivennode(list1.head.next.next) list1.printll()
58f9901d848b8aea90babb768f8f62def31e9e92
Steps-devmyself/shiyanlouSratches
/py.checkio/面向对象高级编程.py
1,774
3.671875
4
'''使用__slots__限制实例的属性''' '''使用@property,把方法变成属性只读,@函数名.setter可写,有setter必须有property''' class Stundet(): #__slots__ = ('name','gender','score') def __init__(self,name,gender,_score): self.name=name self.gender=gender self._score=_score @property def get_score(self): return self._score def set_score(self,vaule): if not isinstance(vaule,int): raise ValueError('must be an integer') if vaule<0 or vaule>100: raise ValueError('out of range') self._score=vaule @property def birth(self): return self._birth #初始化属性 @birth.setter def birth(self,value): self._birth=value #设置属性 @property def age(self): return 2019-self._birth Tom=Stundet(name='Tom',gender='M',_score=110) print(hasattr(Tom,'name')) print(Tom.get_score) Tom.birth=1988#可赋值 print(Tom.birth,Tom.age)#可取值 class Screen(object): @property def shape(self): return self._width,self._height @shape.setter def shape(self,val): self._width,self._height=val @property def resolution(self): return self._height*self._width s=Screen() s.shape=(1024,768) print('resolution=',s.resolution) #鸭子语言 class Animal(): def run(self): print('Animal is running!') class Dog(Animal): def run(self): print('Dog is running!') dog=Dog() dog.run() def run_twice(animal): animal.run() animal.run() run_twice(dog) class timer(): def run(self): print('start to time') def stop(self): print('Stop!') time=timer() run_twice(time) print(type(dog),isinstance(dog,(Dog,Animal)))
54fd1b6b2c41a3c546d02b729bd1ea61b565c806
wszeborowskimateusz/cryptography-exam
/extended_euclides.py
878
3.59375
4
from polynomials import x, pol_div def euclides(a, b): x, x_prim, y, y_prim = 1, 0, 0, 1 while b != 0: q = a // b r = b b = a%b a = r t = x_prim x_prim = x - q*x_prim x = t t = y_prim y_prim = y - q*y_prim y = t return (a, x, y) def solve_equation(a, b, n): d, y, z = euclides(a, n) if d == 1: x0 = (y * b) % n print(f"Solution: x = {x0} +- k*{n}") return x0 if d > 1: if b % d != 0: print("There are no solutions") return None else: x0 = y * b // d print(f"Solution: x = {x0} +- k * {n//d}") return x0 def simple_euclides_poli(p1,p2, mod): while p1 != 0 and p2 != 0: c = p2 _, r = pol_div(p1,p2, mod) p2 = r p1 = c return p1 + p2
4e5bc6ca079d011944ab67d8ce76e3538d77760c
MachFour/info1110-2019
/week9/nahian/person.py
1,808
4.4375
4
class Person: """ The person class simulates the attributes and actions of a person. """ species = "Homo Sapiens" """ This is a class variable. Notice that the self key word is missing. This attribute is shared by all persons and is non-unique. """ def __init__(self, name, age): """ This is the constructor function for the class Person. All objects which belong to Person, e.g. Bob, Alice will have their own unique names and ages. """ self.name = name self.age = age def introduce(self): """ This is an instance method. This means, only a unique object can call this function. e.g. Alice.introduce() or Bob.introduce() """ print("Hi, I am {}. I am {} years old.".format(self.name, self.age)) def say_birthyear(self, current_year): """ Similar to the previous method, this method is also invoked using a specific object, e.g. Alice.say_birthyear(2019), but this method takes in an additional parameter @param : current_year -> int """ print("I was born in {}.".format(current_year-self.age)) def converse(p1, p2): """ This is a class/static method. Notice that the self keyword is missing here again. This means that a unique object will not invoke this method, rather the class will. Usage: Person.converse(Alice, Bob) """ conversation = """{0}: Hi! I am {0}. Nice to meet you.\n{1}: Hello! My name is {1}. Nice to meet you too!""".format(p1.name, p2.name) print(conversation) # if __name__ == "__main__": #Alice = Person("Alice", 22) #Bob = Person("Bob", 21) #Person.converse(Alice, Bob)
d47680c4174b1b5c68109cbf60816726dedcc199
Steven-Kha/CPSC-386-Pong-no-walls
/top_paddle.py
2,157
3.609375
4
# By Steven Kha 2018 import pygame pygame.init() from pygame.sprite import Sprite class Top_Paddle(Sprite): def __init__(self, ai_settings, screen): """Create the Top_Paddle and set its starting position.""" super(Top_Paddle, self).__init__() self.screen = screen self.ai_settings = ai_settings self.rect = pygame.Rect(0, 0, ai_settings.top_paddle_width, ai_settings.top_paddle_height) self.screen_rect = screen.get_rect() self.color = ai_settings.top_paddle_color self.height = float(ai_settings.top_paddle_height) #Top_Paddle starts at top center of screen self.rect.centerx = 900 self.rect.top = self.screen_rect.top # print("Top Paddle position: " + str(self.rect)) # Store a decimal value for the ship's center. self.x = float(self.rect.x) self.speed_factor = ai_settings.top_paddle_speed_factor # Movement flag for continuous movement self.moving_right = False self.moving_left = False def update(self, ai_settings, balls): """Update the ship's position based on the movement flag.""" # Update the ship's center value, not the rect. for ball in balls.sprites(): if ball.rect.centerx + ai_settings.cpu_slow\ > self.rect.centerx: self.x += (ai_settings.top_paddle_x_direction * ai_settings.top_paddle_speed_factor) else: self.x -= (ai_settings.top_paddle_x_direction * ai_settings.top_paddle_speed_factor) self.rect.x = self.x # if fails see top_left code def center_top_paddle(self): """Center the ship on the screen.""" self.center = self.screen_rect.midright def check_edges(self): if self.rect.left <= 600: return True elif self.rect.right >= 1200: return True def draw_top_paddle(self): """Draw the bullet to the screen.""" pygame.draw.rect(self.screen, self.color, self.rect) # By Steven Kha 2018
c0fa4cbdedd8fe271d67fde576eaf46966e87fed
parthpatel361999/Hunting
/rule3MAST.py
2,805
4.34375
4
import random as rnd import time from common import Agent, Target, manhattanDistance, numActions ''' This is Basic Agent 3 for the stationary target. We initialize all cells with their respective probabilities in the first for loop and select the first cell that we want to explore. After exploring that first cell, we start to pick the next cells to explore by using the score of their Manhattan Distance divided by their probability. The minimum "score" cell is the one that we travel to from here on. ''' def rule3MAST(agent, target): highest = 0 r = c = 0 # the initializing of the first probabilities (no score here) for row in agent.map: for cell in row: cell.score = cell.probability * (1 - cell.falseNegativeProbability) if cell.score > highest: highest = cell.score r, c = cell.row, cell.col # while the target has not been found, keep searching cells while (agent.hasFoundTarget == False): minScore = agent.dim**4 prevr = r prevc = c searchResult = agent.searchCell(r, c, target) if searchResult == False: # update the probabilties of the cell we just searched scale = 1 - agent.map[r][c].probability + \ agent.map[r][c].probability * \ agent.map[r][c].falseNegativeProbability agent.map[r][c].probability = agent.map[r][c].falseNegativeProbability * \ agent.map[r][c].probability i = 0 while i < agent.dim: j = 0 while j < agent.dim: # if we reach the same cell that we already updated, skip, as the distance will be zero and this will always be the lowest scored cell if i == prevr and j == prevc: j += 1 continue # update the probabilties of each of the other cells in the board agent.map[i][j].probability = agent.map[i][j].probability / scale # update the score of each of the other cells in the board. dist = manhattanDistance((prevr, prevc), (i, j)) agent.map[i][j].score = (1 + float(dist)) / ( agent.map[i][j].probability * (1 - agent.map[i][j].falseNegativeProbability)) if minScore > agent.map[i][j].score: minScore = agent.map[i][j].score r = i c = j j = j + 1 i = i + 1 # imcrement number of actions between the previous cell and the one we have just explored numActions((prevr, prevc), (r, c), agent) return agent.numMoves
7ee17bb6e4c1830549ebcd329087b0857e6fb0d9
fedoseev-sv/Course_GeekBrains_Python
/lesson_6/hw_6_2.py
1,501
4.28125
4
"""Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу: длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом, толщиной в 1 см * чи сло см толщины полотна. Проверить работу метода. Например: 20м * 5000м * 25кг * 5см = 12500 т""" class Road: def __init__(self, length, width): self._length = length self._width = width def calculat(self): return self._length * self._width * 0.05 * 25 length_to_tyumen = float(input("Введите длину дорожного полотна: ")) width_to_tyumen = float(input("Введите ширину дорожного полотна: ")) road_to_tyumen = Road(length=length_to_tyumen, width=width_to_tyumen) print(f"Для строительства дорожного полотна необходимо {road_to_tyumen.calculat()} т асфальта")
23fa2e27dc96b3e2dff8995646836f97e56a0ec2
mikochou/leetcode_record
/LongestConsecutiveSequence.py
803
3.53125
4
# 建一个哈希表,存储每个num的最大序列,如果本身包含在一个序列里就删除 def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ dic, maxl = set(nums), 0 for n in set(nums): cur, r = 1, n + 1 while r in dic: cur += 1 dic.remove(r) r += 1 l = n - 1 while l in dic: cur += 1 dic.remove(l) l -= 1 maxl = max(maxl, cur) return maxl # 讨论里看到的简洁的写法 def longestConsecutive(self, nums): nums = set(nums) best = 0 for x in nums: if x - 1 not in nums: y = x + 1 while y in nums: y += 1 best = max(best, y - x) return best
f28bf735e0b72024d62ea3a95538e69cb1346deb
Anirudh-27/Nodal-Analysis
/Data_Clustering.py
1,976
3.515625
4
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('musae_facebook_target.csv') X = dataset.iloc[:, [2,3]].values #Encoding categorical data in X from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder, LabelEncoder le_1 = LabelEncoder() X[:,1] = le_1.fit_transform(X[:,1]) ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(),[1])], remainder="passthrough") X = ct.fit_transform(X) X = X[:,1:] le_3 = LabelEncoder() X[:,3] = le_3.fit_transform(X[:,3]) ct_1 = ColumnTransformer(transformers=[('encoder', OneHotEncoder(),[3])], remainder="passthrough") X = ct_1.fit_transform(X) # Using the elbow method to find the optimal number of clusters from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42) kmeans.fit(X) wcss.append(kmeans.inertia_) plt.plot(range(1, 11), wcss) plt.title('The Elbow Method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') plt.show() # Fitting K-Means to the dataset after finding no. of clusters kmeans = KMeans(n_clusters = 4, init = 'k-means++', random_state = 42) y_kmeans = kmeans.fit_predict(X) #Print the cluster numbers for each datapoint print(y_kmeans) """ # Visualising the clusters plt.scatter(X_test[y_kmeans == 0, 0], X_test[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Company') plt.scatter(X_test[y_kmeans == 1, 0], X_test[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Government') plt.scatter(X_test[y_kmeans == 2, 0], X_test[y_kmeans == 2, 1], s = 100, c = 'green', label = 'TV Show') plt.scatter(X_test[y_kmeans == 3, 0], X_test[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Politician') plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids') plt.show() """
96635ab4bbf8985257cc486d8ca54283da1b9498
ezekie97/Connect5-AI-Project
/Connect_5/src/board.py
12,394
4.21875
4
__author__ = 'Bill' class Board: """ Class for the Connect 5 Game Board. The Board is always a 7 long by 9 high. A board always remembers the last move made. """ # Class Constants BLANK_SPACE = "_" # Blank Space PLAYER_ONE = "R" # Red Chip PLAYER_TWO = "B" # Black Chip BOARD_HEIGHT = 7 BOARD_LENGTH = 9 SCORE_TO_WIN = 5 def __init__(self): """ Create a new board. """ self.grid = self.create_grid() self.last_move = None def piece_at(self, row, col): """ Get the value of the piece at the specified location. :param row: specified row :param col: specified column :return: the value of the piece at row 'row' and column 'col'. """ return self.grid[col][row] def can_drop(self, col_num): """ :param col_num: the column number . :return: An array containing a boolean and an integer. The boolean is used to determine if a piece can be dropped and the integer is used to tell which row the piece will be dropped into. """ blank_found = False row_num = self.BOARD_HEIGHT - 1 while not blank_found and row_num >= 0: if self.grid[col_num][row_num] is not self.BLANK_SPACE: row_num -= 1 else: blank_found = True return [blank_found, row_num] def drop(self, dropped_char, col_num): """ Drop a piece into a column. :param dropped_char: the value of the piece being dropped. :param col_num: the column to drop the piece into. :return: true if the drop was successful or false if the column is full. """ drop = self.can_drop(col_num) can_drop = drop[0] row_num = drop[1] if can_drop: self.grid[col_num][row_num] = dropped_char self.last_move = [dropped_char, col_num, row_num] def is_filled(self): """ :return: true if there are no blank spaces on the board. """ blank_found = False for i in range(0, self.BOARD_HEIGHT): if blank_found: break for j in range(0, self.BOARD_LENGTH): if blank_found: break if self.grid[j][i] == self.BLANK_SPACE: blank_found = True return not blank_found def find_n_in_a_row(self, piece, n): """ Find the number of times on the board where there are N adjacent non-blank pieces of the same type on the board. :param piece: the value of the piece. :param n: Look for n in_a_row :return: the number of n in_a_row for the specific piece on this board. """ count = 0 for row in range(0, Board.get_height()): for col in range(0, Board.get_length()): current_piece = self.grid[col][row] if current_piece == piece: count += self.num_n_in_a_row_horizontal(row, col, current_piece, n) # 0 or 1 count += self.num_n_in_a_row_vertical(row, col, current_piece, n) # 0 or 1 count += self.num_n_in_a_row_diagonal(row, col, current_piece, n) # 0, 1, or 2 return count def num_n_in_a_row_horizontal(self, row, col, piece, n): """ Find the number of times on the board where there are N adjacent non-blank pieces of the same type in a horizontal line on the board. :param row: the row number of the piece :param col: the column number of the piece :param piece: the value of the piece :param n: Look for n_in_a_row :return: the number of times this piece satisfies the n_in_a_row condition horizontally. (Either 0 or 1) """ streak = 0 for curr_col in range(col, col + n): # count the initial piece automatically if curr_col > Board.get_length() - 1: # check out of bounds break if self.grid[curr_col][row] != piece: return 0 else: streak += 1 if streak == n: return 1 else: return 0 def num_n_in_a_row_vertical(self, row, col, piece, n): """ Find the number of times on the board where there are N adjacent non-blank pieces of the same type in a vertical line on the board. :param row: the row number of the piece :param col: the column number of the piece :param piece: the value of the piece :param n: Look for n_in_a_row :return: the number of times this piece satisfies the n_in_a_row condition vertically. (Either 0 or 1) """ streak = 0 for curr_row in range(row - n + 1, row + 1): # count the initial piece automatically if curr_row < 0: # check out of bounds break if self.grid[col][curr_row] != piece: return 0 else: streak += 1 if streak == n: return 1 else: return 0 def num_n_in_a_row_diagonal(self, row, col, piece, n): """ Find the number of times on the board where there are N adjacent non-blank pieces of the same type in a diagonal line on the board. :param row: the row number of the piece :param col: the column number of the piece :param piece: the value of the piece :param n: Look for n_in_a_row :return: the number of times this piece satisfies the n_in_a_row condition diagonally. (Either 0, 1, or 2) """ result = 0 streak = 0 for modifier in range(0, n): # count the initial piece automatically curr_col = col + modifier curr_row = row - modifier if curr_col > Board.get_length() - 1 or curr_row < 0: # check out of bounds break if self.grid[curr_col][curr_row] != piece: break else: streak += 1 if streak == n: result += 1 streak = 0 # reset streak for modifier in range(0, n): # count the initial piece automatically curr_col = col - modifier curr_row = row - modifier if curr_col < 0 or curr_row < 0: # check out of bounds break if self.grid[curr_col][curr_row] != piece: break else: streak += 1 if streak == n: result += 1 return result def find_winner(self): """ Check if the current board has a winner. A winner has 5 in a row horizontally, vertically, or diagonally. :return: a character representing a player, or None if there is no winner. """ win_amount = self.SCORE_TO_WIN if self.find_n_in_a_row(Board.PLAYER_ONE, win_amount) >= 1: return Board.PLAYER_ONE elif self.find_n_in_a_row(Board.PLAYER_TWO, win_amount) >= 1: return Board.PLAYER_TWO else: return None def find_disconnected_wins(self, piece): """ Find blank areas that, when filled in with the given type of piece, cause a victory for that piece. :param piece: the player piece :return: the number of unconnected wins. """ count = 0 for row in range(0, Board.get_height()): for col in range(0, Board.get_length()): current_piece = self.grid[col][row] if current_piece == Board.BLANK_SPACE: count += self.find_horizontal_disconnected_wins(piece, col, row) count += self.find_disconnected_diagonal_wins(piece, col, row) return count def find_horizontal_disconnected_wins(self, piece, col_num, row_num): """ :param piece: the character to check for. :param col_num: the column number of the last move made. :param row_num: the row number of the last move made. :return: 1 if the filled in blank piece causes a horizontal victory for its corresponding player. """ connection = 1 curr_col = col_num - 1 while curr_col >= 0: if self.grid[curr_col][row_num] == piece: connection += 1 curr_col -= 1 else: # can't possibly have a longer connection this way. break curr_col = col_num + 1 while curr_col < self.BOARD_LENGTH: if self.grid[curr_col][row_num] == piece: connection += 1 curr_col += 1 else: # can't possibly have a longer connection this way. break if connection >= 4: return 1 return 0 def find_disconnected_diagonal_wins(self, piece, col_num, row_num): """ :param piece: the character to check for. :param col_num: the column number of the last move made. :param row_num: the row number of the last move made. :return: 1 if the filled in blank piece causes a diagonal victory for its corresponding player. """ result = 0 connection = 1 # Upper Left to Lower Right Diagonal curr_row = row_num - 1 curr_col = col_num - 1 while curr_row >= 0 and curr_col >= 0: if self.grid[curr_col][curr_row] == piece: connection += 1 curr_col -= 1 curr_row -= 1 else: # can't possibly have a longer connection this way. break curr_row = row_num + 1 curr_col = col_num + 1 while curr_row < self.BOARD_HEIGHT and curr_col < self.BOARD_LENGTH: if self.grid[curr_col][curr_row] == piece: connection += 1 curr_col += 1 curr_row += 1 else: # can't possibly have a longer connection this way. break if connection >= 4: result += 1 # Lower Left to Upper Right Diagonal connection = 1 curr_row = row_num - 1 curr_col = col_num + 1 while curr_row >= 0 and curr_col < self.BOARD_LENGTH: if self.grid[curr_col][curr_row] == piece: connection += 1 curr_row -= 1 curr_col += 1 else: # can't possibly have a longer connection this way. break curr_row = row_num + 1 curr_col = col_num - 1 while curr_row < self.BOARD_HEIGHT and curr_col >= 0: if self.grid[curr_col][curr_row] == piece: connection += 1 curr_row += 1 curr_col -= 1 else: # can't possibly have a longer connection this way. break if connection >= 4: result += 1 return result def create_grid(self): """ :return: a 2-dimensional array representing the game grid. """ grid = [] for i in range(0, self.BOARD_LENGTH): grid.append(self.create_empty_column()) return grid def get_last_move(self): """ :return: An array containing information about the last move, including the value of the piece, the column, and the row. """ return self.last_move def __str__(self): """ :return: a string representation of the board. """ board_string = "" for i in range(0, self.BOARD_HEIGHT): for j in range(0, self.BOARD_LENGTH): board_string += " " + self.grid[j][i] + " " board_string += "\n" return board_string def create_empty_column(self): """ :return: an array representing an empty column on the board. """ column = [] for i in range(0, self.BOARD_HEIGHT): column.append(self.BLANK_SPACE) return column @staticmethod def get_length(): """ :return: the length of this board. """ return Board.BOARD_LENGTH @staticmethod def get_height(): """ :return: the height of this board. """ return Board.BOARD_HEIGHT
9bcafcc6ebc7d95f6cb5d7b3fa76b42068ee7270
himominul/DS_and_Algorithm
/Stack/stackFuncation.py
481
4.03125
4
def create_stack(): stack = [] return stack def is_Empty(stack): return len(stack) == 0 def push (stack,item): stack.append(item) print('item Pushed',item) def pop(stack): if is_Empty(stack): return ' Stack Is Empty' return stack.pop() stack = create_stack() push(stack,str(1)) push(stack,str(2)) push(stack,str(9)) push(stack,str(5)) print('-------------------') print(str(stack)) print('\n_____After POP----') pop(stack) print(stack)
b366523cf0f5d16db0bae2767da2494eeaecb0a6
theLoFix/30DOP
/Day23/Day23_Excercise01.py
371
4
4
# Write a generator that generates prime numbers in a specified range. def gen_primes(limit): for dividend in range(2, limit + 1): for divisor in range(2, dividend): if dividend % divisor == 0: break else: yield dividend primes = gen_primes(101) print(next(primes)) print(next(primes)) print(next(primes))
5dd2b1c33214e41d08e4af2ffa0879c06d999695
ArthurKhakimov/python_hw
/hw11.py
222
3.828125
4
#!/usr/bin/env python3 def letters_range(start, stop, step=1): abc=list(map(chr, range(97, 123))) return abc[abc.index(start):abc.index(stop):step] if __name__ == "__main__": print(letters_range('p', 'g',-2))
454147f473920ae07a60c680e4e4e8f576101293
nsbradford/CS525-DeepNeuralNetworks
/HW5_3LayerNN/homework5_nsbradford.py
14,887
3.90625
4
""" homework5_nsbradford.py Nicholas S. Bradford Wed 03/17/2017 In this problem you will train a 3-layer neural network to classify images of hand-written digits from the MNIST dataset. Similarly to Homework 4, the input to the network will be a 28 x 28-pixel image (converted into a 784-dim vector); the output will be a vector of 10 probabilities (one for each digit). Hyperparam tuning: # of units in hidden layer {30, 40, 50} Learning rate {0.001, 0.005, 0.01, 0.05, 0.1, 0.5} Minibatch size {16, 32, 64, 128, 256} # of training epochs Regularization strength Specifically, implement f: R784 -> R10, where: z1 = p1(x) = W1 * x + b1 z2 = p2(x) = W2 * x + b2 h1 = f1(x) = a1(p1(x)) yhat = f2(h1) = a2(p2(h1)) f(x) = f2(f1(x)) = a2(p2(a1(p1(x)))) For activation functions a1, a2 in network, use: a1(z1) = relu(z1) a2(z2) = softmax(z2) Task A) Implement stochastic gradient descent (SGD; see Section 5.9 and Algorithm 6.4 in the Deep Learning textbook) for the 3-layer neural network shown above. B) Optimize hyperparams by creating a findBestHyperparameters() that tries at least 10 different settings (Remember, optimize hyperparams on ONLY the validation set) C) Report cross-entropy and accuracy on test set, along with screenshot of these values with final 20 epochs of SGD. Cost should be < 0.16, accuracy should be > 95%. Unregularized test accuracy after 30 epochs: 96.2% Regularized with Alpha=1/1e-3: 96.42% """ import numpy as np import math import scipy from sklearn.metrics import accuracy_score DEBUG = False N_INPUT = 784 N_OUTPUT = 10 def load_data(): """ Load data. In ipython, use "run -i homework2_template.py" to avoid re-loading of data. Each row is an example, each column is a feature. Returns: train_data (nd.array): (55000, 784) train_labels (nd.array): (55000, 10) val_data (nd.array): (5000, 784) val_labels (nd.array): (5000, 10) test_data (nd.array): (10000, 784) test_labels (nd.array): (10000, 10) """ prefix = 'mnist_data/' train_data = np.load(prefix + 'mnist_train_images.npy') train_labels = np.load(prefix + 'mnist_train_labels.npy') val_data = np.load(prefix + 'mnist_validation_images.npy') val_labels = np.load(prefix + 'mnist_validation_labels.npy') test_data = np.load(prefix + 'mnist_test_images.npy') test_labels = np.load(prefix + 'mnist_test_labels.npy') assert train_data.shape == (55000, 784) and train_labels.shape == (55000, 10) assert val_data.shape == (5000, 784) and val_labels.shape == (5000, 10) assert test_data.shape == (10000, 784) and test_labels.shape == (10000, 10) return train_data, train_labels, val_data, val_labels, test_data, test_labels def crossEntropy(y, yhat): m = y.shape[0] cost = np.sum(y * np.log(yhat)) # sum element-wise product return (-1.0 / m) * cost def relu(z): return (z >= 0) * z def grad_relu(z): return (z >= 0) * 1 def softmax(z): bottom_vec = np.exp(z) bottom = np.sum(bottom_vec, axis=1, keepdims=True) # sum of each row = sum for each dimension top = np.exp(z) yhat = np.divide(top, bottom) # could alternatively use bottom[:, None] to keep rows return yhat #================================================================================================== def flattenW(W1, b1, W2, b2): """ Flattens all weight and bias matrices into a weight vector. Can be used just as well for the gradients. Args: W1 (np.array): n_hidden x 784 W2 (np.array): 10 x n_hidden b1 (np.array): n_hidden x 1 b2 (np.array): 10 x 1 x (np.array): m x 784 Returns: w (np.array): length * 1 """ n_hidden_units = W1.shape[0] flattened = (W1.flatten(), b1.flatten(), W2.flatten(), b2.flatten()) w = np.concatenate(flattened) length = (N_INPUT * n_hidden_units) + (n_hidden_units * N_OUTPUT) + n_hidden_units + N_OUTPUT assert w.shape == (length,), (w.shape, (length,)) return w def expandW(w, n_hidden_units): """ Unpacks the weight and bias matrices from a weight vector. Can be used just as well for the gradients. """ i1 = 784 * n_hidden_units i2 = i1 + n_hidden_units i3 = i2 + n_hidden_units * 10 i4 = i3 + 10 assert i4 == w.size, str(i4) + ' ' + str(w.size) W1 = w[0:i1].reshape((n_hidden_units, 784)) b1 = w[i1:i2] W2 = w[i2:i3].reshape((10, n_hidden_units)) b2 = w[i3:i4] return W1, b1, W2, b2 def forwardPropagate(W1, b1, W2, b2, x): """ Produce output from the neural network. Args: W1 (np.array): n_hidden x 784 W2 (np.array): 10 x n_hidden b1 (np.array): n_hidden x 1 b2 (np.array): 10 x 1 x (np.array): m x 784 Returns: yhat (np.array): m x 10 """ z1 = x.dot(W1.T) + b1 h1 = relu(z1) z2 = h1.dot(W2.T) + b2 yhat = softmax(z2) assert yhat.shape == (x.shape[0], W2.shape[0]), yhat.shape return yhat def J(W1, b1, W2, b2, x, y): """ Computes cross-entropy loss function. J(w1, ..., w10) = -1/m SUM(j=1 to m) { SUM(k=1 to 10) { y } } Args: W1 (np.array): n_hidden x 784 W2 (np.array): 10 x n_hidden b1 (np.array): n_hidden x 1 b2 (np.array): 10 x 1 x (np.array): m x 784 y (np.array): m x 10 Returns: J (float): cost of w given x and y Use cross-entropy cost functino: J(W1, b1, W2, b2) = -1/m * SUM(y * log(yhat)) """ yhat = forwardPropagate(W1, b1, W2, b2, x) # OLD: yhat = softmax(x.dot(w)) return crossEntropy(y, yhat) def JWrapper(w, x, y, n_hidden_units): W1, b1, W2, b2 = expandW(w, n_hidden_units) return J(W1, b1, W2, b2, x, y) def gradJ(W1, b1, W2, b2, x, y): """ Args: W1 (np.array): n_hidden x 784 W2 (np.array): 10 x n_hidden b1 (np.array): n_hidden x 1 b2 (np.array): 10 x 1 x (np.array): m x 784 y (np.array): m x 10 """ m = x.shape[0] n_hidden_units = W1.shape[0] if DEBUG: print('\t\tgradJ() backprop...') z1 = x.dot(W1.T) + b1 h1 = relu(z1) yhat = forwardPropagate(W1, b1, W2, b2, x) if DEBUG: print('\t\t\tBegin Layer 2...') g2 = yhat - y dJ_dW2 = g2.T.dot(h1) #np.outer(g2, h1) dJ_db2 = np.copy(g2) dJ_db2 = np.sum(dJ_db2, axis=0) # sum of each column if DEBUG: print('\t\t\tBegin Layer 1...') g1 = g2.dot(W2) g1 = np.multiply(g1, grad_relu(z1)) if DEBUG: print('\t\t\tdJ_dW1...') dJ_dW1 = g1.T.dot(x) #np.outer(g1, x.T) dJ_db1 = np.copy(g1) dJ_db1 = np.sum(dJ_db1, axis=0) # sum of each column assert yhat.shape == (m, N_OUTPUT), yhat.shape assert z1.shape == h1.shape == (m, n_hidden_units), (z1.shape, h1.shape, (m, n_hidden_units)) assert g2.shape == (m, N_OUTPUT), g2.shape assert dJ_dW2.shape == W2.shape, dJ_dW2.shape assert g1.shape == h1.shape == (m, n_hidden_units), (g1.shape, h1.shape) assert dJ_dW1.shape == W1.shape, dJ_dW1.shape assert dJ_db2.shape == b2.shape, dJ_db2.shape assert dJ_db1.shape == b1.shape, dJ_db1.shape return flattenW(dJ_dW1, dJ_db1, dJ_dW2, dJ_db2) / m def gradJWrapper(w, x, y, n_hidden_units): """ """ length = (N_INPUT * n_hidden_units) + (n_hidden_units * N_OUTPUT) + n_hidden_units + N_OUTPUT assert w.shape == (length,), (w.shape, (length,)) W1, b1, W2, b2 = expandW(w, n_hidden_units) return gradJ(W1, b1, W2, b2, x, y) def backprop(w, x, y, n_hidden_units, learning_rate, alpha): dJ_dW1, dJ_db1, dJ_dW2, dJ_db2 = expandW(gradJWrapper(w, x, y, n_hidden_units), n_hidden_units) W1, b1, W2, b2 = expandW(w, n_hidden_units) decay = (1 - learning_rate * alpha) newW1 = decay * W1 - (dJ_dW1 * learning_rate) newb1 = decay * b1 - (dJ_db1 * learning_rate) newW2 = decay * W2 - (dJ_dW2 * learning_rate) newb2 = decay * b2 - (dJ_db2 * learning_rate) return flattenW(newW1, newb1, newW2, newb2) #================================================================================================== def shuffleArraysInUnison(x, y): assert x.shape[0] == y.shape[0] p = np.random.permutation(x.shape[0]) return x[p, :], y[p, :] def getMiniBatches(data, labels, minibatch_size): x, y = shuffleArraysInUnison(data, labels) n_batches = int(math.ceil(x.shape[0] / minibatch_size)) batch_x = np.array_split(x, n_batches, axis=0) batch_y = np.array_split(y, n_batches, axis=0) return batch_x, batch_y def gradient_descent(x, y, learning_rate, minibatch_size, n_hidden_units, alpha, n_epochs): """ """ W1, b1, W2, b2 = initializeWeights(n_hidden_units, n_inputs=N_INPUT, n_outputs=N_OUTPUT) w = flattenW(W1, b1, W2, b2) prevJ = JWrapper(w, x, y, n_hidden_units) epochJ = prevJ print ('Initial Cost:', prevJ) batch_x, batch_y = getMiniBatches(x, y, minibatch_size) # a list of individual batches print(len(batch_x)) for i in range(n_epochs): for x, y in zip(batch_x, batch_y): w = backprop(w, x, y, n_hidden_units, learning_rate, alpha) if DEBUG: print('\tUpdated weights.') newJ = JWrapper(w, x, y, n_hidden_units) diff = prevJ - newJ prevJ = newJ # print('\t\t{} \tCost: {} \t Diff: {}'.format(i+1, newJ, diff)) epochDiff = epochJ - prevJ epochJ = prevJ print('\tEnd Epoch {} \tCost: {} \t EpochDiff: {}'.format(i+1, newJ, epochDiff)) W1, b1, W2, b2 = expandW(w, n_hidden_units) return W1, b1, W2, b2 def train_model(x, y, params): print('\nTrain 3-layer ANN with learning {}, batch_size {}, n_hidden_units {}, alpha {}'.format( params.learning_rate, params.minibatch_size, params.n_hidden_units, params.alpha)) return gradient_descent(x, y, params.learning_rate, params.minibatch_size, params.n_hidden_units, params.alpha, n_epochs=3) #================================================================================================== class HyperParams(): range_learning_rate = {0.1, 0.5} #{0.001, 0.005, 0.01, 0.05, 0.1, 0.5} range_minibatch_size = {256} # {16, 32, 64, 128, 256} range_n_hidden_units = {30, 40, 50} #{30, 40, 50} range_alpha = {1/1e2, 1/1e3} #{1e3, 1e4, 1e5} def __init__(self, learning_rate, minibatch_size, n_hidden_units, alpha): self.learning_rate = learning_rate self.minibatch_size = minibatch_size self.n_hidden_units = n_hidden_units self.alpha = alpha @staticmethod def getHyperParamList(): answer = [] for rate in HyperParams.range_learning_rate: for size in HyperParams.range_minibatch_size: for units in HyperParams.range_n_hidden_units: for alpha in HyperParams.range_alpha: answer.append(HyperParams(rate, size, units, alpha)) # return answer return [HyperParams(0.5, 256, 50, 1/1e3)] # best def toStr(self): return ('learning_rate :' + str(self.learning_rate), 'minibatch_size :' + str(self.minibatch_size), 'n_hidden_units :' + str(self.n_hidden_units), 'alpha :' + str(self.alpha)) def getLossAndAccuracy(W1, b1, W2, b2, data, labels): predictions = forwardPropagate(W1, b1, W2, b2, data) predict_labels = predictions.argmax(axis=1) true_labels = labels.argmax(axis=1) accuracy = accuracy_score(y_true=true_labels, y_pred=predict_labels) loss = J(W1, b1, W2, b2, data, labels) return loss, accuracy def findBestHyperparameters(train_data, train_labels, val_data, val_labels): best_params = None best_accuracy = 0.0 print('\nBegin findBestHyperparameters(): checking {} sets'.format(len(HyperParams.getHyperParamList()))) for params in HyperParams.getHyperParamList(): print('\nTesting pararms: {', params.toStr(), '}') W1, b1, W2, b2 = train_model(train_data, train_labels, params) loss, accuracy = getLossAndAccuracy(W1, b1, W2, b2, val_data, val_labels) reportResults(loss, accuracy, 'Validation') if accuracy > best_accuracy: best_params = params best_accuracy = accuracy print('\nBest params found: {', best_params.toStr(), '}\n') return best_params #================================================================================================== def initializeWeights(n_hidden_units, n_inputs, n_outputs): """ Normally we use Xavier initialization, where weights are randomly initialized to a normal distribution with mean 0 and Var(W) = 1/N_input. """ W1 = np.random.randn(n_hidden_units, n_inputs) * np.sqrt(1/(n_inputs*n_hidden_units)) W2 = np.random.randn(n_outputs, n_hidden_units) * np.sqrt(1/(n_hidden_units*n_outputs)) b1 = np.random.randn(n_hidden_units, 1) * np.sqrt(1/n_hidden_units) b2 = np.random.randn(n_outputs, 1) * np.sqrt(1/n_outputs) return W1, b1, W2, b2 def testBackpropGradient(x, y, n_hidden_units): """ Use check_grad() to ensure correctness of gradient expression. """ assert x.shape[1] == 784 and y.shape[1] == 10 print('testBackpropGradient...') W1, b1, W2, b2 = initializeWeights(n_hidden_units, n_inputs=784, n_outputs=10) w = flattenW(W1, b1, W2, b2) point_to_check = w gradient_check = scipy.optimize.check_grad(JWrapper, gradJWrapper, point_to_check, x, y, n_hidden_units) print('check_grad() value: {}'.format(gradient_check)) print('Gradient is good!' if gradient_check < 1e-4 else 'WARNING: bad gradient!') def reportResults(loss, accuracy, text='Test'): print() print(text + ' Loss: {}'.format(loss)) print(text + ' Accuracy: {}'.format(accuracy)) def main(): np.random.seed(7) train_data, train_labels, val_data, val_labels, test_data, test_labels = load_data() testBackpropGradient(x=val_data[:5, :], y=val_labels[:5, :], n_hidden_units=30) params = findBestHyperparameters(train_data, train_labels, val_data, val_labels) W1, b1, W2, b2 = train_model(train_data, train_labels, params) loss, accuracy = getLossAndAccuracy(W1, b1, W2, b2, test_data, test_labels) reportResults(loss, accuracy) if __name__ == '__main__': main()
ae2d220de68581c10fedf5547d9bad379463a47b
ejdeposit/nb_capstone
/src/readingGroups.py
29,172
3.625
4
# ---------------------------------------------------------------------------------------------------------------------------------- # $match # ---------------------------------------------------------------------------------------------------------------------------------- class Graph(): def __init__(self): self.queue=[] self.U=None self.V=None self.E=None self.unionVU=[] #for vertex in U: #self.unionVU.insert(vertex.num, vertex) #for vertex in V: #self.unionVU.insert(vertex.num, vertex) def print_matches(self): print('vetex->mate') for vertex in self.unionVU: if (vertex.mate): print('{} {} {} {} {}'.format('v', vertex.num, '->', vertex.mate.num, ' ')) else: print('{} {} {} {} {}'.format('v', vertex.num, '->', 'N', ' ')) print('') def print_queue(self): print('queue: ', end='') for v in self.queue: v.print_vertex() print('') def print_set(self, part): print('set ', end='') for v in part: v.print_vertex() print('') def init_queue(self): self.queue=[] for vertex in self.V: if vertex.mate is None: self.queue.append(vertex) def remove_labels(self): for vertex in self.V: vertex.label=None for vertex in self.U: vertex.label=None def print_debug(self, loc): print('{} {}'.format(loc, 'vetex->mate')) for vertex in self.unionVU: if (vertex.mate): print('{} {} {} {}'.format(vertex.num, '->', vertex.mate.num, ' ')) else: print('{} {} {} {}'.format(vertex.num, '->', 'N', ' ')) print('') def max_match(self): # Maximum Matching in Bipartite Graph Algorithm # the purpose of this function is to match up teachers with reading groups. # another function will generate edges based on times the teacher is available #and which reading levels they can work with self.init_queue() while self.queue: w= self.queue.pop(0) #change to my own search function if time if w in self.V: for u in self.E[w.num]: #if u is free in list of vertices connected to w if u.mate is None: w.mate=u u.mate=w #following labeling, umatching, etc will take place after finding last free v=w while(v.label is not None): u=v.label if((u.mate == v) and (v.mate== u)): v.mate=None u.mate=None v=u.label v.mate=u u.mate=v self.remove_labels() self.init_queue() #break from for loop because at end of traversal break else: if((w.mate != u) and (u.mate != w) and (u.label is None)): u.label= w self.queue.append(u) #else: w in U and matched else: #label the mate v of w with "w" w.mate.label= w #enqueue(Q, v) v as in mate v of w? self.queue.append(w.mate) return # ---------------------------------------------------------------------------------------------------------------------- # $act $event $vertex # --------------------------------------------------------------------------------------------------------------------- class Vertex(): #vertex will be parent class of reading activities and scheduled events classes def __init__(self): self.num=None self.label=None self.mate=None def print_vertex(self): print(self.num, end=' ') #classes class Activity(Vertex): def __init__(self, actType): super().__init__() self.type=actType eventTime=None class Reading_Group_Activity(Activity): def __init__(self, group, day, actType): super().__init__(actType) self.readingGroup= group self.readingLevel=None self.day=day # self.groupNumber= groupNumber # self.studentList=[] # self.activityList=[] def print_act(self): print('Group: ', self.readingGroup.groupNumber) print('Day: ', self.day) print('Activity Type: ', self.type) #if self.num: # print('vertex number: ', self.num) print('vertex number: ', self.num) class Event(Vertex): def __init__(self, day, start, end, eventType, teacher=None): super().__init__() self.day= day self.start=start self.end= end self.teacher=teacher #can be either pointer to one student or group of students self.type=eventType self.students=None def print_event(self): print() print('Event: ', self.type) if self.teacher: print('Teacher: ', self.teacher.name) if self.day != None: print('day: ', self.day) if self.start and self.end: print('Start: ', tm.min_to_time(self.start), 'End: ', tm.min_to_time(self.end)) if self.num: print('vertex number: ', self.num) # ---------------------------------------------------------------------------------------------------------------------- # $sched # --------------------------------------------------------------------------------------------------------------------- class Reading_Group_Sched(Graph): def __init__(self, teacherSchedule, classList, scheduleTimes): super().__init__() self.teacherSchedule=teacherSchedule self.classList=classList #schedule times is schedule_parameters object self.schedParams=scheduleTimes #dictionary key= day, item list of events on that day self.eventSched={} #dictionary key= day, item list of activities of all groups self.actSched={} def print_group_teacher(self): weekLen= self.schedParams.days for groupNumber in self.classList.groupNumberList: self.classList.readingGroups[groupNumber] print('Group', self.classList.readingGroups[groupNumber].groupNumber, 'Activity Event Match') for act in self.classList.readingGroups[groupNumber].activityList: act.print_act() print() if act.mate: act.mate.print_event() else: print('NO MATCH') print() print() print() print() print() def make_group_event(self): """ input:self used to access teacher objects output: creates event, adds it to list for teachers and master events list """ weekLen= self.schedParams.days allEvents=[] #interate through teachers for teacher in self.teacherSchedule.teacherList: #print(teacher.name) #iterate through each day in teachers schedule for day in range(0, weekLen): teacherDayEventList=[] #get event times for that day from parameters object #get in/out times for that day from teacher class eventTimes= self.schedParams.get_days_eTime(day) teacherTimes= teacher.get_days_inOuts(day) # test print e times and teacher times to see if they line up #self.schedParams.print_days_eTimes(day) #print('day ', day, 'teacher availability') #print(teacherTimes) #interate over list of inout times` and comapre to event times for each day for event in eventTimes: for inOut in teacherTimes: #if list is not empty #compare if in time is less than or equal to event start #and out time is greater than or equal to event end time if inOut and inOut[0] <= event[0] and inOut[1]>= event[1]: #create event make_event(day, start, stop, teacher) newEvent= Event(day, event[0], event[1], "Small Group Lesson", teacher) teacherDayEventList.append(newEvent) #add to master list doesn't have to be function can just append it to allEvents.append(newEvent) #newEvent.print_event() #add to teachers list teacher.add_event(teacherDayEventList, day) #allEvents not organized by day need separate function #self.groupEventList= allEvents self.add_events(allEvents) random.shuffle(allEvents) self.V= allEvents def add_events(self, eventList): #input: list of events #output: dictionary of events by day #function interates through list of events makes list for each day, list is not organized, just for max match for event in eventList: if event.day in self.eventSched: self.eventSched[event.day].append(event) else: self.eventSched[event.day]= [] self.eventSched[event.day].append(event) #generate activity list for each readingGroup def make_group_act(self): weekLen= self.schedParams.days classActList=[] for groupNumber in self.classList.groupNumberList: groupActList=[] for day in range(0, weekLen): #reading_group_Act(self, group, day, actType): newAct= Reading_Group_Activity(self.classList.readingGroups[groupNumber], day, 'Small Group Lesson') #newAct.print_act() #add each act to groups list and sched act list for maxMatch groupActList.append(newAct) classActList.append(newAct) #add group act list to group class object. in group function add it to each stuent too self.classList.readingGroups[groupNumber].add_actList(groupActList) #add group act list to class schedule (dictionary day:actList) if keeping as a list instead of dictionary by day self.add_act_list(classActList) #add group act to set u in graph class random.shuffle(classActList) self.U= classActList #print('U in make grup act funct') #self.print_set(self.U) #self.print_act_list(self.U) def print_act_list(self, actList): print('print act list') for act in actList: act.print_act() def add_act_list(self, classActList): #input: unordered list of all activities created for every group #output: add activities to Reading Group sched.actSched by day for activity in classActList: if activity.day in self.actSched: self.actSched[activity.day].append(activity) else: self.actSched[activity.day]=[] self.actSched[activity.day].append(activity) def add_teacher_pref_test(self): str1= 'For each staff member, enter the group number of each group that may be scheduled with the staff member' str2= 'separating each group number with a spae and entering return when finished' str3= 'If all groups may be scheduled with the staff member, enter all' GroupsNumbers=[] print('{} {} {}'.format(str1, str2, str3)) for teacher in self.teacherSchedule.teacherList: #remove break when finished testing break groupPref=[] line=input(teacher.name +': ') if 'all' in line or 'All' in line: #add group pref to teacher allGroups= self.classList.numOfGroups for i in range(1, allGroups+1): groupPref.append(i) else: numList=line.split(' ') for numStr in numList: isNumber= re.match('^\d+$', numStr) if isNumber: num= int(numStr) groupPref.append(num) #add group pef to teacher teacher.groupPref=groupPref print(groupPref) #hard code teacher pref for repeated testing self.teacherSchedule.teacherList[0].groupPref= [1,2,3] self.teacherSchedule.teacherList[1].groupPref= [1,2,3] self.teacherSchedule.teacherList[2].groupPref= [3] def add_teacher_pref(self): str1= 'For each staff member, enter the group number of each group that may be scheduled with the staff member' str2= 'separating each group number with a spae and entering return when finished' str3= 'If all groups may be scheduled with the staff member, enter all' GroupsNumbers=[] print('{} {} {}'.format(str1, str2, str3)) for teacher in self.teacherSchedule.teacherList: #remove break when finished testing groupPref=[] line=input(teacher.name +': ') if 'all' in line or 'All' in line: #add group pref to teacher allGroups= self.classList.numOfGroups for i in range(1, allGroups+1): groupPref.append(i) else: numList=line.split(' ') for numStr in numList: isNumber= re.match('^\d+$', numStr) if isNumber: num= int(numStr) groupPref.append(num) #add group pef to teacher teacher.groupPref=groupPref print(groupPref) #for teacher in self.teacherSchedule.teacherList: #print(teacher.name, teacher.groupPref) def set_edges(self): vertexCount=0 weekLen=self.schedParams.days edgeList={} #number vertexes for i in range(0, weekLen): for event in self.eventSched[i]: event.num=vertexCount vertexCount= vertexCount+1 for i in range(0, weekLen): for act in self.actSched[i]: act.num=vertexCount vertexCount= vertexCount+1 for teacher in self.teacherSchedule.teacherList: pref= teacher.groupPref for day in range(0, weekLen): for event in teacher.lessonEventSched[day]: for act in self.actSched[day]: if act.readingGroup.groupNumber in pref: if act.num in edgeList: edgeList[act.num].append(event) else: edgeList[act.num]=[] edgeList[act.num].append(event) if event.num in edgeList: edgeList[event.num].append(act) else: edgeList[event.num]=[] edgeList[event.num].append(act) #print('match') #act.print_act() #event.print_event() #print() self.E=edgeList def input_sched_testTimes(numberOfDays): #set set weeks eTimes weekTimes=[] for i in range(0, numberOfDays): start1=tm.time_to_min('11:15') end1=tm.time_to_min('11:55') start2=tm.time_to_min('12:40') end2=tm.time_to_min('1:20') dayTimes=[] dayTimes.append(start1) dayTimes.append(end1) dayTimes.append(start2) dayTimes.append(end2) weekTimes.append(dayTimes) #test with extra padding #test with less parameters #start1=time_to_min('11:15') #end1=time_to_min('11:55') #dayTimes=[] #dayTimes.append(start1) #dayTimes.append(end1) #weekTimes.append(dayTimes) return weekTimes def input_sched_Times(numberOfDays): #set set weeks eTimes str1 ='For each day, enter a start time, followed by a stop time for to indicate when the morning and afternoon sessions' str2= 'or the reading time should begin and end. If there is no afternoon start and end time, press enter.' print(str1 + '\n' + str2) weekTimes=[] for i in range(0, numberOfDays): print('day:', i) start1= tm.time_to_min(input('Morning start time:')) end1= tm.time_to_min(input('Morning end time:')) start2= tm.time_to_min(input('Afternoon start time:')) end2= tm.time_to_min(input('Afternoon end time:')) dayTimes=[] if start1 and end1: dayTimes.append(start1) dayTimes.append(end1) if start2 and end2: dayTimes.append(start2) dayTimes.append(end2) weekTimes.append(dayTimes) #test with extra padding #test with less parameters #start1=time_to_min('11:15') #end1=time_to_min('11:55') #dayTimes=[] #dayTimes.append(start1) #dayTimes.append(end1) #weekTimes.append(dayTimes) return weekTimes class Schedule_Parameters(): #def __init__(self, days, actPerDay, duration, start1, end1, start2=None, end2=None): def __init__(self, days, actPerDay, duration): self.days=days self.actPerDay=actPerDay self.duration = duration #list of of days, each day is list of start and stop times self.dailyEvents=[] def week_len(self): return self.days def set_weeks_eTimes(self, startEndList): #input: list of start and end times for each day of the week #output: list of event times for each day for times in startEndList: start1 = times[0] end1 = times[1] if len(times) > 2: start2= times[2] end2= times[3] else: start2=None end2 =None daysEvents=[] daysEvents= self.set_days_eTimes(start1, end1, start2, end2) self.dailyEvents.append(daysEvents) def set_days_eTimes(self, start1, end1, start2, end2): daysEvents=[] event=0 periodStart=start1 periodEnd=end1 actStart=None actEnd=None nonScheduled=self.actPerDay #figure out how many activities in first time chunk actInPeriod=int((periodEnd-periodStart)/self.duration) while(actInPeriod and nonScheduled): actStart=periodStart actEnd= periodStart+self.duration #add atart and end times to event times list startEnd=[] startEnd.append(actStart) startEnd.append(actEnd) daysEvents.append(startEnd) #update variables for next time through loop nonScheduled=nonScheduled-1 #print('start: ', actStart) #print('end: ', actEnd) #print(startEnd) #print('remaining events to plan: ', nonScheduled) #add to list of event times periodStart= actEnd actInPeriod=int((periodEnd-periodStart)/self.duration) if(nonScheduled and start2): periodStart=start2 periodEnd=end2 actStart=None actEnd=None actInPeriod=int((periodEnd-periodStart)/self.duration) while(actInPeriod and nonScheduled): actStart=periodStart actEnd= periodStart+self.duration #add atart and end times to event times list startEnd=[] startEnd.append(actStart) startEnd.append(actEnd) daysEvents.append(startEnd) #update variables for next time through loop nonScheduled=nonScheduled-1 #print('start: ', actStart) #print('end: ', actEnd) #print(startEnd) #print('remaining events to plan: ', nonScheduled) #add to list of event times periodStart= actEnd actInPeriod=int((periodEnd-periodStart)/self.duration) #for event in self.eventTimes: #print(event) return daysEvents def print_days_eTimes(self, day): """ input: day that exist in list of events times for each day in schedule output: void, prints list of events on that day """ print('day', day, 'event times') if(self.dailyEvents[day]): print(self.dailyEvents[day]) else: print('list empty') def print_all_eTimes(self): print('All events times for week') print(self.dailyEvents) def get_days_eTime(self, day): """ input day output list of n elements, each element is list of start and stop time of that event """ return self.dailyEvents[day] #------------------------------------------------------------------------------------------------------------------------------- # $teacher # ----------------------------------------------------------------------------------------------------------------------------- class Staff_Schedule(): def __init__(self): self.dayCount=0 self.maxTimesInOut=0 self.teacherList=[] def read_teachers(self, filePath): #throw away first line or maybe use to determine day fin = open(filePath, 'rt') line=fin.readline() #line=line[:-1:] #print(line) teacherData=[] teacherDataList=[] while True: #read in each student by line and count total line= fin.readline() if not line: break #line=line[:-1:] #print each line of student data #print(line) #add to teacherData list teacherData=line.split(',') teacherDataList.append(teacherData) fin.close() #print(teacherDataList) return teacherDataList #add pattern matching to identify how many in/out times for eac day def teacher_sched(self, teacherTimes): #input: list of strings each string lis line from teacher schedule file #output list of teacher objects #start by just making general schedule for one day/all week teacherList=[] #print('teacherTimes list') #print(teacherTimes) #orgainize teacher schedule by teacher or day? teacher #count how many days in schedule and how many in/out times in day from file #need to have class set up before this point #hard coded, need to add functions self.dayCount=4 self.maxTimesInOut=2 dayCount=self.dayCount inOutCount=self.maxTimesInOut for line in teacherTimes: #list of days, each day is list of in/out lists dayList=[] name =line.pop(0) #list of days, each day is list of time chunks which is list clockin/out times #loop for each day for i in range(0, dayCount): #each day is list of in/out times dayList.append([]) #get each time that teacher enters/leaves class in one day for j in range(0, inOutCount): #get in and out Time as string inTimeStr=line.pop(0) outTimeStr=line.pop(0) #convert int time to min int times with function #need handling for empty strngs if:else intime=NONE inOut=[] if(inTimeStr): inTime=tm.time_to_min(inTimeStr) outTime=tm.time_to_min(outTimeStr) #add to list tuple list inOut.append(inTime) inOut.append(outTime) #add to tuple to lis day list dayList[i].append(inOut) #change to separate function #print(name) #print each day #for i in range(0, dayCount): #print('day', i) #for j in range(0, inOutCount): #for j in range(0, len(dayList[i])): #if(dayList[i][j]): #print('In: ', dayList[i][j][0]) #print('Out: ', dayList[i][j][1]) self.teacherList.append(Teacher(name, dayList, dayCount)) return def print_staff(self): print('print staff function') for teacher in self.teacherList: teacher.print_teacher() def sched_to_file(self, weekLen): fout=open('teacher_sched.csv', 'wt') fout.close() for teacher in self.teacherList: teacherLines=teacher.sched_to_file(weekLen) temp=dict(teacherLines[0]) headers=list(temp.keys()) #print(headers) fout=open('teacher_sched.csv', 'at') fout.write(teacher.name + '\n') cout = csv.DictWriter(fout, headers) cout.writeheader() cout.writerows(teacherLines) fout.close() #with open('student_sched.csv', 'wt') as fout: #cout = csv.DictWriter(fout, headers) #cout.writeheader() #cout.writerows(studentLines) class Teacher(): def __init__(self, name, schedule, weekLen): self.name=name self.schedule=schedule #dictionary is schedule with day as key and list of lesson events as item self.lessonEventSched={} self.groupPref=[] def print_teacher(self): print(self.name) day=0 for i in self.schedule: print('day ', day) inOut= 0 for time in self.schedule[day]: if self.schedule[day][inOut]: print(self.schedule[day][inOut][0]) print(self.schedule[day][inOut][1]) inOut= inOut + 1 day=day + 1 def get_days_inOuts(self, day): return self.schedule[day] def add_event(self, eventList, day): self.lessonEventSched[day]=eventList def sched_to_file(self, weekLen): fileLines=[] startTimeList=[] # lessonEventSched #go through all schedules to get lst of all the times for day in range(0, weekLen): for event in self.lessonEventSched[day]: if event.start not in startTimeList: startTimeList.append(event.start) startTimeList.sort() #print(self.name) #print(startTimeList) #initalize dictionary just to avoide using if else statements later schedTime={} for time in startTimeList: schedTime[time]={} schedTime[time]['Time']=tm.min_to_time(time) #go through student sched dictionary again for day in range(0, weekLen): for event in self.lessonEventSched[day]: if event.mate: schedTime[event.start]['Day '+ str(event.day+1)]=event.type + '- Group' + str(event.mate.readingGroup.groupNumber) else: schedTime[event.start]['Day '+ str(event.day+1)]= 'No Group Scheduled' #fileLines.append(self.fullName) for time in startTimeList: #print(schedTime[time]) fileLines.append(schedTime[time]) #print(fileLines) return fileLines import timeConvert as tm import student as st import csv import random import re
46d1ba7031ec4fd659e659edeb655627e1bdae0d
EwertonRod/EstudoPython
/1Exercicio_Estrutura de decisão.py
395
4.03125
4
""" Faça um programa que peça dois números e imprima o maior deles. """ print("\t\tImprime o Maior numero\n") num1 = int (input("Digite o primeiro número: ")) num2 = int(input("Digite o segundo número: ")) maiornum1 = num1 > num2 if maiornum1 == True : print("o numero {} e maior".format(num1)) else: print("o numero {} e maior".format(num2))
1184014aebe713f125b72e9d875a997166cbe519
jbalderasgit/pruebas_pyhon
/schoolar_age.py
290
4
4
edad= int (input("Dame tu edad: ")) if edad <6: print("Kinder") elif edad >=6 and edad<12: print("Primaria") elif edad >=13 and edad<15: print("Secundaria") elif edad >=15 and edad<18: print("Bachillerato") else : print("Universidad")
6a945a517039e112648afc92f2d1733c1d84591c
liuzh825/myAlgorithm
/Algorithm/如何把一个有序整数数组放到二叉树中/ep_01.py
1,308
3.859375
4
''' 思路:递归思想 取数组中间的数字作为根节点,将数组分成左右两部分,左右两部分递归处理 ''' class BiTNode(): def __init__(self): self.data = None self.lchild = None self.rchild = None def arraytotree(arr, start, end): root = None if end >= start: root = BiTNode() mid = int((start+end+1)/2) root.data = arr[mid] # 递归的处理左子树 root.lchild = arraytotree(arr, start, mid-1) # 递归的处理右子树 root.rchild = arraytotree(arr, mid+1, end) else: root = None return root # 中序遍历的方式打印出二叉树节点的内容 def printTreeMidOrder(root): if root == None: return # 遍历root节点的左子树 if root.lchild != None: printTreeMidOrder(root.lchild) # 遍历root节点 print(root.data) # 遍历root节点的右子树 if root.rchild != None: printTreeMidOrder(root.rchild) if __name__ == '__main__': arr = [1,2,3,4,5,6,7,8,9,10] print('数组:', end='') i = 0 while i < len(arr): print(arr[i], end='') i += 1 root = arraytotree(arr, 0, len(arr)-1) print('转化成树的中序遍历结果是:') printTreeMidOrder(root)
27fc408ec20342ac52337d59574e3a5174d503fc
wangjiliang1983/test
/crashcourse/ex06_08_pets.py
276
3.671875
4
kitty = {'catigory': 'yingduan', 'host': 'Frank',} doggy = {'catigory': 'muyang', 'host': 'Xin',} piggy = {'catigory': 'yezhu', 'host': 'Ling',} pets = [kitty, doggy, piggy] for animal in pets: print(animal['catigory'].title() + " belongs to " + animal['host'].title())
b4a65662a827bf68673e13272fd61b1185160736
abhinav0000004/Criminal-Database-Management-System
/form.py
2,663
3.546875
4
import tkinter as tk from tkinter import ttk from criminal import insert_rec win = tk.Tk() # Application Name win.title("Python GUI App") win.geometry("400x400") # Label headd = ttk.Label(win, text = "ENTER THE DETAILS OF CRIMINAL",font='Helvetica 17 bold underline').place(x=0,y=0) id = ttk.Label(win, text = "ACCUSED ID:",font='Helvetica 12 bold').place(x=0,y=30) name = ttk.Label(win, text = "NAME:",font='Helvetica 12 bold').place(x=0,y=55) age = ttk.Label(win, text = "AGE:",font='Helvetica 12 bold').place(x=0,y=80) sex = ttk.Label(win, text = "SEX:",font='Helvetica 12 bold').place(x=0,y=105) height = ttk.Label(win, text = "HEIGHT:",font='Helvetica 12 bold').place(x=0,y=130) eye = ttk.Label(win, text = "EYE COLOR:",font='Helvetica 12 bold').place(x=0,y=155) city = ttk.Label(win, text = "CITY:",font='Helvetica 12 bold').place(x=0,y=180) nationality = ttk.Label(win, text = "NATIONALITY:",font='Helvetica 12 bold').place(x=00,y=205) crime = ttk.Label(win, text = "CRIME:",font='Helvetica 12 bold').place(x=0,y=230) last = ttk.Label(win, text = "LAST RECORD:",font='Helvetica 12 bold').place(x=00,y=255) # Click event # Textbox widget idd = tk.StringVar() nameEntered = ttk.Entry(win, width = 12, textvariable = idd).place(x=150,y=30) namee = tk.StringVar() nameEntered = ttk.Entry(win, width = 25, textvariable = namee).place(x=150,y=55) agee = tk.StringVar() nameEntered = ttk.Entry(win, width = 12, textvariable = agee).place(x=150,y=80) sexx = tk.StringVar() nameEntered = ttk.Entry(win, width = 12, textvariable = sexx).place(x=150,y=105) heightt = tk.StringVar() nameEntered = ttk.Entry(win, width = 12, textvariable = heightt).place(x=150,y=130) eyee = tk.StringVar() nameEntered = ttk.Entry(win, width = 20, textvariable = eyee).place(x=150,y=155) cityy = tk.StringVar() nameEntered= ttk.Entry(win, width = 20, textvariable = cityy).place(x=150,y=180) nation = tk.StringVar() nameEntered = ttk.Entry(win, width = 20, textvariable = nation).place(x=150,y=205) crimee = tk.StringVar() nameEntered = ttk.Entry(win, width = 40, textvariable = crimee).place(x=150,y=230) lastt = tk.StringVar() nameEntered = ttk.Entry(win, width = 40, textvariable = lastt).place(x=150,y=255) def click(): dict={'ACCUSED ID':idd.get(),'NAME':namee.get(),'AGE':agee.get(),'SEX':sexx.get(),'HEIGHT':heightt.get(),'EYE COLOR':eyee.get(),'CITY':cityy.get(),'NATIONALITY':nation.get(),'CRIME':crimee.get(),'PREVIOUS RECORD':lastt.get()} insert_rec(dict) # Button widget button = ttk.Button(win, text = "submit", command = click).place(x=150,y=300) win.mainloop()
e3983a3e29767d37f0a050193ae050c86e27a71a
scottshepard/advent-of-code
/2020/day22.py
2,373
3.578125
4
from utils import read_input class Game: def __init__(self, p1, p2, mode='normal'): self.p1 = p1.copy() self.p2 = p2.copy() self.round = 0 self.mode = mode self.configurations = [] self.solved = False def __next__(self): if (self.p1, self.p2) in self.configurations: self.solved = True self.winner = 1 else: self.configurations.append((self.p1.copy(), self.p2.copy())) p1_card = self.p1.pop(0) p2_card = self.p2.pop(0) winner = self._determine_winner(p1_card, p2_card) if winner == 1: self.p1.extend([p1_card, p2_card]) else: self.p2.extend([p2_card, p1_card]) if len(self.p1) == 0: self.solved = True self.winner = 2 if len(self.p2) == 0: self.solved = True self.winner = 1 self.round += 1 def _determine_winner(self, p1_card, p2_card): if (p1_card <= len(self.p1)) and (p2_card <= len(self.p2)) and (self.mode == 'recursive'): g = Game(self.p1[:p1_card], self.p2[:p2_card], 'recursive') winner, _ = g.play() else: if p1_card > p2_card: winner = 1 elif p2_card > p1_card: winner = 2 return winner def __repr__(self): return 'P1: ' + str(self.p1) + '\nP2: ' + str(self.p2) def play(self): while not self.solved: self.__next__() return self.winner, self.score() def score(self): if len(self.p1) == 0: x = self.p2 else: x = self.p1 return sum([(i+1) * int(c) for i, c in enumerate(x[::-1])]) def parse_input(input): lines = read_input(input, '\n\n') players = [] for l in lines: x = l.split('\n') x.pop(0) players.append([int(i) for i in x]) return players p1, p2 = parse_input('day22_test.txt') g = Game(p1, p2) assert g.play() == (2, 306) g2 = Game(p1, p2, mode='recursive') assert g2.play() == (2, 291) p1, p2 = parse_input('day22.txt') g = Game(p1, p2) _, score = g.play() print('Part 1:', score) p1, p2 = parse_input('day22.txt') g2 = Game(p1, p2, mode='recursive') _, score = g2.play() print('Part 2:', score)
b649624f582358d5751847d09edd4bb19c914f5a
Official-BlackHat13/100_days_of_python
/day_1_5/day_4_1.py
183
3.890625
4
import random random_seed = int(input('enter a number: ')) random.seed(random_seed) random_int = random.randint(0, 1) if random_int == 0: print('heads') else: print('tails')
39aca1a68dd4c5935b355c687d12754acc8b0a3a
AlexCC1943/challenge_computing_Endava
/ordenamiento_y_busqueda/heapSort.py
1,027
3.640625
4
def heapIfy(lis2, pos): # si el nodo tiene dos hijos if 2 * pos + 2 <= len(lis2)-1: if lis2[2 * pos + 1] <= lis2[2 * pos + 2]: min = 2 * pos + 1 else: min = 2 * pos + 2 if lis2[pos] > lis2[min]: aux = lis2[pos] lis2[pos] = lis2[min] lis2[min] = aux heapIfy(lis2, min) # si el nodo solo tiene un hijo elif 2 * pos + 1 <= len(lis2) - 1: if lis2[pos] > lis2[2 * pos + 1]: aux = lis2[pos] lis2[pos] = lis2[2 * pos + 1] lis2[2 * pos + 1] = aux return lis2 def heapSort(lis): lisN = [] for i in range(len(lis)//2 - 1, -1, -1): lis = heapIfy(lis, i) for i in range(0, len(lis)): aux = lis[0] lis[0] = lis[len(lis) - 1] lis[len(lis) - 1] = aux lisN.append(aux) lis = lis[:len(lis) - 1] lis = heapIfy(lis, 0) return lisN lista = [28, 47, 31, 26, 12, 5, 10, 58] print(lista) print(heapSort(lista))
49508a6c49dc58fa28b87fd111c2308f52c8331f
romulogm/EstudosPython
/cursoUSP/calc.py
411
4.03125
4
def num_fat(i): result = 1 while i >= 1: result = result * i i = i - 1 return result def numerobinomial(num1,num2): return num_fat(num1) // num_fat(num2) * (num_fat(num1-num2)) num1 = int(input("Digite o valor do primeiro número binomial: ")) num2 = int(input("Digite o valor do segundo número binomial: ")) print ("O número binomial é: ", numerobinomial(num1,num2))
26832affa8741ff6449de067f6d7794c562c44f8
Fluffhead88/blackjack
/blackjack_1.py
4,112
3.71875
4
import random class Card: def __init__(self, value, suit): self.value = value self.suit = suit def get_value(self): if self.value == 'J': return 10 if self.value == 'Q': return 10 if self.value == 'K': return 10 if self.value == 'A': return 11 return self.value def __str__(self): pass class Deck: def __init__(self): # creates range of cards and shuffles self.cards =[] values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] suits = ['Clubs', 'Spades', 'Hearts', 'Diamonds'] for value in values: for suit in suits: self.cards.append(Card(value, suit)) random.shuffle(self.cards) def draw(self): # takes off cards for use somewhere else return self.cards.pop() def __str__(self): # shows you cards for card in self.cards: print(card.value, card.suit) return "" class Player: def __init__(self): self.hand= [] def add(self, card): self.hand.append(card) return self.hand def draw(self, deck): self.add(deck.draw()) return self.hand def hit(self, deck): self.draw(deck) return self.hand_value() def check(self): score = self.hand_value() if score > 21: print("Bust!") elif score == 21: print("Blackjack!") def hand_value(self): value = 0 for card in self.hand: value += card.get_value() if value > 21 and "A" in self.hand: value -= 10 return value """def __str__(self): return self.hand""" """def __repr__(self): return Player(self.hand)""" def __gt__(self, dealer): return self.hand_value() > dealer.hand_value() def __eq__(self, dealer): return self.hand_value() == dealer.hand_value() print("Dealing cards") deck = Deck() """hand = Player() print (hand)""" # Start game with 2 cards choice = True while choice: choice = input("Would you like to play Blackjack? y/n ").lower() if choice == "y": player = Player() dealer = Player() for i in range(2): player.draw(deck) dealer.draw(deck) # Player hit sequence print(f"Player:{player.hand_value()}") print(f"Dealer:{dealer.hand_value()}") if player.hand_value() < 21: choices = input("Would you like to hit? Y/N > ").lower() for choice in choices: if choice == "y": player.hit(deck) if choice == "n": pass print(f"Player:{player.hand_value()}") print(f"Dealer:{dealer.hand_value()}") if player.hand_value() < 21: choices = input("Would you like to hit? Y/N > ").lower() for choice in choices: if choice == "y": player.hit(deck) if choice == "n": pass player.check() # Dealer hit sequence while dealer.hand_value() < 17: print ("Dealer draws\n") dealer.draw(deck) print(f"Dealer:{dealer.hand_value()}") dealer.check() print(f"Player:{player.hand_value()}, Dealer:{dealer.hand_value()}") # check who wins if player.hand_value() <= 21 and dealer.hand_value() <= 21 and dealer.hand_value() > player.hand_value(): print("Dealer wins") elif player.hand_value() > 21 and dealer.hand_value() <= 21: print("Dealer wins") elif player.hand_value() <= 21 and dealer.hand_value() <= 21 and dealer.hand_value() < player.hand_value(): print("You win!") elif player.hand_value() <= 21 and dealer.hand_value() > 21: print("You win!") elif player.hand_value() <= 21 and dealer.hand_value() <= 21 and dealer.hand_value() == player.hand_value(): print("You tied") if choice == "n": exit()
35d874672650a3242dbad04c0e4d0d2dbb0d9cd4
SartJ/Notes
/Data Pre-Processing Test/DPP_Handling_Imputting.py
1,719
3.859375
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 8 14:05:03 2021 @author: sartaj """ import pandas as pd import numpy as np # import sklearn volunteer = pd.read_csv('volunteer_opportunities.csv') #.head(n) used to return first n rows of a dataFrame to check print(volunteer.head(3)) #To check the shape (no_rows or samples, no_colums or features) of the dataFrame:- print(volunteer.shape) #return boolean value where dataFrame has null or not:- print(volunteer.isnull()) #to find out how many null values each feature has:- print(volunteer.isnull().sum()) #Dropping some columns:- volunteer = volunteer.drop(['BIN','BBL','NTA'], axis = 1) print(volunteer.shape) # Check how many values are missing in # the category_des column:- print("Number of rows with null values in category_desc column:-") print(volunteer['category_desc'].isnull().sum()) #Subset the volunteer dataset:- volunteer_subset = volunteer[volunteer['category_desc'].notnull()] print('Shape after removing null values:-') print(volunteer_subset.shape) print("Shape of dataframe before dropping:") print(volunteer.shape) volunteer = volunteer.dropna(axis = 0, subset = ['category_desc']) print('Shape after dropping:') print(volunteer.shape) """ Sales Dataset: """ sales = pd.read_csv('sales.csv', index_col=['month']) print(sales) #Fills the null place with the passed value:- # sales = sales.fillna(50) print(sales) from sklearn.impute import SimpleImputer impute = SimpleImputer(missing_values=np.nan, strategy='mean') impute.fit(sales[ ['salt'] ]) sales['salt'] = impute.transform(sales[['salt']]) print(sales)
037be673b8224f5f0e6d1cf07712df1afb486974
loraxiss/MITx6.00.1x
/BattleShip.py
3,137
4.28125
4
# -*- coding: utf-8 -*- # Import function to generate a random integer from random import randint # Create the playing board board = [] for x in range(5): board.append(["O"] * 5) def print_board(board): """ input: board is a list of equal sized lists of single characters to be printed for use as a playing board output: print the lists of characters in rows to the screen """ for row in board: print " ".join(row) # Welcome and print the playing field print "Let's play Battleship!" print_board(board) def random_row(board): """ generate a random list index (row) for the playing board """ return randint(0, len(board) - 1) def random_col(board): """ generate a random list index (column) for the playing board """ return randint(0, len(board[0]) - 1) # Determine a random location for the ship in the game in reference to a playing board location ship_row = random_row(board) ship_col = random_col(board) # Allow 4 turns or guesses as to the location of the ship for turn in range(4): # Accept the user's input/guess data guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:")) # If the guess is correct, indicate and end the game if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sunk my battleship!" break # Else the guess is incorrect: else: # Check data validity - indicate the problem if out-of-limits guess, if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): print "Oops, that's not even in the ocean." # Check if guess was already made at that location elif(board[guess_row][guess_col] == "X"): print "You guessed that one already." # Indicate a missed guess and print the board else: print "You missed my battleship!" board[guess_row][guess_col] = "X" print_board(board) # Notify user of the current Turn print "Turn", turn + 1 # Check to see if the game is over if turn == 3: print "Game Over" """ Extra Credit You can also add on to your Battleship! program to make it more complex and fun to play. Here are some ideas for enhancements—maybe you can think of some more! - Make multiple battleships: you'll need to be careful because you need to make sure that you don’t place battleships on top of each other on the game board. You'll also want to make sure that you balance the size of the board with the number of ships so the game is still challenging and fun to play. - Make battleships of different sizes: this is trickier than it sounds. All the parts of the battleship need to be vertically or horizontally touching and you’ll need to make sure you don’t accidentally place part of a ship off the side of the board. - Make your game a two-player game: Use functions to allow your game to have more features like rematches, statistics and more! """
cd8a54cec4efedc475e8e400f45cda6d6a33ede9
MahaAmin/Learn-Python-By-Games
/jokes.py
931
3.859375
4
# Some Silly Jokes print('What do you get when you cross a snowman with a vampire?') input() print('Frostbite!') print() print("What do dentists call an astronaut's cavity?") input() print("A black hole!") input() print('Knock knock.') input() print("Who's there?") input() print('Interrupting cow.', end='') print('Interrupting cow wh-MOO!') # Escape characters in Python #------------------------------------------------------ # Escape Charater | What is actually printed #-----------------------|------------------------------ # \\ | Backslash (\) # | # \' | Single quote (') # | # \" | Double quote (") # | # \n | Newline # | # \t | Tab #-------------------------------------------------------
f8d80e8a35574c1efa0ed7ac4243f2368f864176
VioletMyth/CTCI
/Zero matrix 1.8.py
861
3.765625
4
def zeroMatrix(matrix): positions = {"x": [], "y": []} i,j = 0,0 while i < len(matrix): if 0 in matrix[i]: positions["x"].append(i) while j < len(matrix[i]): if matrix[i][j] == 0 and j not in positions["y"]: positions["y"].append(j) j += 1 j = 0 i += 1 i,j = 0,0 while i < len(matrix): while j < len(matrix[i]): if i in positions["x"]: matrix[i][j] = 0 j += 1 j = 0 i+=1 row,column = 0,0 while column < len(matrix[row]): while row < len(matrix): if column in positions["y"]: matrix[row][column] = 0 row += 1 row = 0 column += 1 return matrix print(zeroMatrix([[0,1,1], [1,2,1], [2,3,1], [2,0,1]]))
cc593514b7713d629d1a37e94df6400d45a74a80
orlyrevalo/Personal.Project.2
/Project2.7.4.py
677
4.1875
4
'''While Loop''' # Using break to Exit a Loop print("Using break to Exit a Loop") prompt = "\nPlease enter the name of the city you have visited" prompt += "\n(Enter 'quit' when you are finished.)" city = input(prompt) while True: if city == 'quit': break else: print("I'd love to go to " + city.title() + "!") # Using continue in a Loop print("\nUsing continue in a Loop") current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number) # Avoiding Infinite Loops print("\nAvoiding Infinite Loops") x = 1 while x <= 5: print(x) x += 1
1417487717918201ac31142a9e2cb58c0b873865
jiangyoudang/python3
/algorithm/leetcode/wildcard.py
1,617
3.5
4
class Solution: # @param s, an input string # @param p, a pattern string # @return a boolean #'solution 1 #dp, time cost N^2 # def isMatch(self, s, p): # s_len = len(s) # p_len = len(p) # dp = [[False for i in range(s_len+1)] for j in range(p_len+1)] # dp[0][0] = True # # for j in range(1,p_len+1): # for i in range(1,s_len+1): # if dp[j-1][i-1] and (s[i-1] == p[j-1] or p[j-1]=='?'): # dp[j][i] = True # break # elif p[j-1] == '*': # if dp[j-1][i-1]: # dp[j-1][i-1:] = [True for k in dp[j-1][i-1:]] # break # # return dp[j][i] def isMatch(self, s, p): len_s = len(s) len_p = len(p) p_pointer = 0 s_pointer = 0 ss = 0 star = -1 while s_pointer < len_s: if p_pointer<len_p and (p[p_pointer]==s[s_pointer] or p[p_pointer]=='?'): p_pointer += 1 s_pointer += 1 elif p_pointer<len_p and p[p_pointer]=='*': star = p_pointer ss = s_pointer p_pointer += 1 elif star!=-1: ss += 1 s_pointer = ss p_pointer = star+1 else: return False while p_pointer<len_p and p[p_pointer]=='*': p_pointer += 1 return p_pointer==len_p test = Solution() if test.isMatch('a','aaaa'): print('True') else: print('False')
81222c382d345adbf7b84417fdf94f3dc3dbdd40
I201821180B/Machine-Learning-Lab
/Assignment_9_ANN/ANN_faceRecognition.py
6,864
3.671875
4
#!/usr/bin/env python import numpy as np import cv2 import random import os import matplotlib.pyplot as plt from math import exp # Initialize a network def initialize_network(n_inputs, n_hidden, n_outputs): network = list() hidden_layer = [{'weights':[random.uniform(0.1,1.0) for i in range(n_inputs + 1)]} for i in range(n_hidden)] network.append(hidden_layer) output_layer = [{'weights':[random.uniform(0.1,1.0) for i in range(n_hidden + 1)]} for i in range(n_outputs)] network.append(output_layer) return network def activate(weights, inputs): activation = weights[-1] #last weight is the bias for i in range(len(weights)-1): activation += weights[i] * inputs[i] return activation #sigmoid function def transfer(activation): if activation < 0: return 1 - 1/(1 + exp(activation)) else: return 1/(1 + exp(-activation)) def forward_propagate(network, row): inputs = row for layer in network: new_inputs = [] for neuron in layer: activation = activate(neuron['weights'], inputs) neuron['output'] = transfer(activation) new_inputs.append(neuron['output']) inputs = new_inputs return inputs def transfer_derivative(output): return output * (1.0 - output) def backward_propagate_error(network, expected): for i in reversed(range(len(network))): layer = network[i] errors = list() if i != len(network)-1: for j in range(len(layer)): error = 0.0 for neuron in network[i + 1]: error += (neuron['weights'][j] * neuron['delta']) errors.append(error) else: for j in range(len(layer)): neuron = layer[j] errors.append(expected[j] - neuron['output']) for j in range(len(layer)): neuron = layer[j] neuron['delta'] = errors[j] * transfer_derivative(neuron['output']) def update_weights(network, row, l_rate): for i in range(len(network)): inputs = row[:-1] if i != 0: inputs = [neuron['output'] for neuron in network[i - 1]] for neuron in network[i]: for j in range(len(inputs)): neuron['weights'][j] += l_rate * neuron['delta'] * inputs[j] neuron['weights'][-1] += l_rate * neuron['delta'] def train_network(network, train, l_rate, n_epoch, n_outputs): for epoch in range(n_epoch): sum_error = 0 for row in train: outputs = forward_propagate(network, row) expected = [0 for i in range(n_outputs)] expected[int(row[-1])] = 1 sum_error += sum([(expected[i]-outputs[i])**2 for i in range(len(expected))]) backward_propagate_error(network, expected) print('>epoch=%d, lrate=%.3f' % (epoch, l_rate)) if(sum_error < 200): l_rate = 0.5 #if(sum_error < 150): # l_rate = 0.3 update_weights(network, row, l_rate) print('>error=%.3f' % (sum_error)) def predict(network, row): outputs = forward_propagate(network, row) return outputs.index(max(outputs)) if __name__ == "__main__": #Step 1: Create Face database: people_total = 40 faces_dir = 'att_faces/' train_count = 6 test_faces_count = 4 t = train_count * people_total m = 92 n = 112 mn = m * n p = people_total*10 #total= mn*p #Training set training_ids = [] T = np.empty(shape=(mn, t), dtype='float64') cur_img = 0 print "TRAINING SET:" for face_id in xrange(1, people_total + 1): #print face_id training_id_curr = random.sample(range(1, 11), train_count) #pick 6 items randomly for each person training_ids.append(training_id_curr) #print "Face id=",face_id,"Image Id=",training_id_curr for training_id in training_id_curr: path_to_img = os.path.join(faces_dir, 's' + str(face_id), str(training_id) + '.pgm') img = cv2.imread(path_to_img, 0) #as reading grayscale img #print path_to_img img_col = np.array(img, dtype='float64').flatten() #making it mn*1 col matrix T[:, cur_img] = img_col[:] #storing it in a column in mn*t database cur_img += 1 #print T #Step 2: Mean Calculation mean_img_col = np.sum(T, axis=1) / t #Step 3: Subtract mean face from all training faces. Now they are mean aligned faces for j in xrange(0, t): T[:, j] -= mean_img_col[:] #print T #Step 4: Co-Variance of the Mean aligned faces(Turk and peterland: p*p instead of mn*mn) C = np.matrix(T.transpose()) * np.matrix(T) C /= t #print C #step 5: eigenvalue and eigenvector decomposition: evalues, evectors = np.linalg.eig(C) #print evalues #step 6: Find the best direction (Generation of feature vectors) #sort acc to descending eigen value sort_indices = evalues.argsort()[::-1] evalues = evalues[sort_indices] evectors = evectors[sort_indices] #print evalues evalues_count = 100 #i.e. "k" as in "k" highest eigen values x_list = [] y_list = [] featureVector = (evectors[0:evalues_count]).transpose() #p*k #Step 7: Generating Eigenfaces eigenFaces = featureVector.transpose() * T.transpose() #k*mn #Step 8: Generate Signature of Each Face: signature = eigenFaces * T #k*p K = evalues_count p = 240 signature = signature.tolist() print (len(signature)) list_temp = [] class_ = 0 flag = 0 for i in range(len(signature[0])): flag = flag + 1 list_temp.append(class_) if(flag == 6): flag = 0 class_ = class_+1 signature.append(list_temp) dataset = np.matrix(signature).transpose() dataset = dataset.tolist() print len(dataset[0]) #print dataset[6] ''' dataset = [[2.7810836,2.550537003,0], [1.465489372,2.362125076,0], [3.396561688,4.400293529,0], [1.38807019,1.850220317,0], [3.06407232,3.005305973,0], [7.627531214,2.759262235,1], [5.332441248,2.088626775,1], [6.922596716,1.77106367,1], [8.675418651,-0.242068655,1], [7.673756466,3.508563011,1]] ''' n_inputs = len(dataset[0]) - 1 n_outputs = len(set([row[-1] for row in dataset])) print "n_inputs=",n_inputs print "n_outputs=",n_outputs network = initialize_network(n_inputs, 25, n_outputs) train_network(network, dataset, 0.8, 200, n_outputs) #0.7,100: 9% nearly #Step 1: Make test database test_count = test_faces_count * people_total test_correct = 0 count = 0 for face_id in xrange(1, people_total + 1): for test_id in xrange(1, 11): if (test_id in training_ids[face_id-1]) == False: #selecting left over 4 faces path_to_img = os.path.join(faces_dir, 's' + str(face_id), str(test_id) + '.pgm') img = cv2.imread(path_to_img, 0) img_col = np.array(img, dtype='float64').flatten() #make it 1*mn img_col -= mean_img_col img_col = np.reshape(img_col, (mn, 1)) #mn*1 projected_face = eigenFaces * img_col #k*1 dataset = projected_face.transpose() #1*k dataset = dataset.tolist() row = dataset[0] #there is no dataset[1] onwards row.append(face_id-1) prediction = predict(network,row) print('Expected=%d, Got=%d' % (row[-1], prediction)) count = count+1 if((face_id-1) == prediction): test_correct = test_correct+1 accuracy = float(100. * test_correct / count) print 'Correct: ' + str(accuracy) + '%'
22c1713ccc10d8c450c12ff437ba321730a6e6de
yuanbitnu/Study_Python
/Python_Study_oldboy/day34_进程_进程间数据共享_进程锁_进程池/多进程创建.py
1,172
3.640625
4
## 方式一:使用multiprocessing模块创建 # import multiprocessing # def fun(arg): # process = multiprocessing.current_process() # 获取执行本方法的进程 # process.name = '进程%s'%arg # 为进程重新设置名称 # print(arg,arg+10,process.name) # if __name__ == "__main__": # for i in range(1,11): # print(i) # process = multiprocessing.Process(target=fun,args=(i,)) # process.start() # process.join() # 阻塞主进程,只有当执行join的进程执行完后才会执行主进程,for循环属于主线程,因此每进行一次for循环就会停一次等待当 前for循环的子进程执行完 ## 方式二:使用面向对象方式创建多进程 import multiprocessing class MyProcess(multiprocessing.Process): def run(self): print(multiprocessing.current_process().name) if __name__ == "__main__": for i in range(1,11): myprocess = MyProcess() myprocess.start() ## 调用父类中的start()方法,父类中的start()方法会调用run方法,此时MyProces中有run方法,则会调用MyProces类中 方法
439d014f2226a208d3e55b44b1ad0e083ac60b7d
leifdenby/markdown-toc-tree
/mdtoctree/__main__.py
1,576
3.578125
4
import tree_text import operator import sys class Node: def __init__(self, parent, value): self.children = [] self.parent = parent self.value = value @property def depth(self): if not self.parent is None: return 1 + self.parent.depth else: return 1 @property def index(self): if self.parent is None: return '' else: return self.parent.index + '%d' % (self.parent.children.index(self) + 1) def tolist(self): if len(self.children) > 0: return (self.value, [c.tolist() for c in self.children]) else: return self.value if __name__ == "__main__": current_node = Node(parent=None, value='') root_node = current_node for line in sys.stdin: if line.startswith('#'): d = sum([s == '#' for s in line]) title = line[d+1:].strip() while d != current_node.depth: if d > current_node.depth: parent_node = current_node current_node = Node(parent=parent_node, value=title) parent_node.children.append(current_node) else: current_node = current_node.parent parent_node = current_node current_node = Node(parent=parent_node, value=title) parent_node.children.append(current_node) print tree_text.format_tree(root_node, format_node=lambda n: '%s. %s' % (n.index, n.value), get_children=lambda n: n.children)
c268b2c6f0917df8bf832d787d3ab902c3d05485
actecautomacao/automatiza
/arquivofunc/principal.py
477
3.609375
4
from registrousuario import connect1 while True: operacao = int(input('Informe senha padrão (223) para processeguir: ')) try: if operacao != 223: print('Usuario Invalido!') elif operacao == 223: print('Inicio do processo!! ') print(operacao) connect1(operacao) # chamada da função dentro do arquivo registro de usuarios.py except ValueError: print('Erro de valor')
8170f1b9d557f81beeca52b8fdc3c567592ac4a3
shivam221098/data-structures
/program.py
9,031
4.5
4
# PROGRAM(WORKING ON LIST): # starting with list # Initialising a list name = [] # inserting values in a list using insert function print('Inserting values in a list using insert function :- ') name.insert(0, 'Rida') name.insert(0, 'Ali') print(name, '\n') # inserting values in a list using append function print('inserting values in a list using append function :- ') name.append('Khan') print(name, '\n') # Deleting values from a list using remove print('Deleting values from a list using remove function :- ') name.remove('Ali') print(name, '\n') # Deleting values from a list using POP print('Deleting values from a list using POP function :- ') name.remove('Khan') print(name, '\n') # searching in list print('Searching in list :- ') for i in name: if i == 'Rida': print("Found Name 'Rida' in List.") else: print("Not Found") # updating list print('\nUpdating list :- ') name[0] = 'Ali' print(name) # Lab No 3 (All Sortings In One Program): # Initialising a list and assigning values nums = [5, 9, 8, 7, 6, 0] # function for Bubble Sort def bub_sort(nums): for i in range(len(nums) - 1, 0, -1): for j in range(i): if nums[j] > nums[j + 1]: temp = nums[j] nums[j] = nums[j + 1] nums[j + 1] = temp print("Bubble Sort Method :- ", nums) # function for Selection Sort def selc_sort(nums): for i in range(5): mine = i for j in range(i, 6): if nums[j] < nums[mine]: mine = j temp = nums[i] nums[i] = nums[mine] nums[mine] = temp print("Selection Sort Method :- ", nums) # function for Shell Sort def shell_sort(arr): size = len(arr) gap = size // 2 while gap > 0: for i in range(gap, size): anchor = arr[i] j = i while j >= gap and arr[j - gap] > anchor: arr[j] = arr[j - gap] j -= gap arr[j] = anchor gap = gap // 2 def foo(arr): size = len(arr) gap = size // 2 gap = 3 for i in range(gap, size): anchor = arr[i] j = i while j >= gap and arr[j - gap] > anchor: arr[j] = arr[j - gap] j -= gap arr[j] = anchor # function for Insertion Sort def insertion_sort(nums): for i in range(1, len(nums)): anchor = nums[i] j = i - 1 while j >= 0 and anchor < nums[j]: nums[j + 1] = nums[j] j = j - 1 nums[j + 1] = anchor print("Insertion Sort Method :- ", nums) # function for Merge Sort def merge_sort(arr): if len(arr) <= 1: return mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) merge_two_sorted_lists(left, right, arr) def merge_two_sorted_lists(a, b, arr): len_a = len(a) len_b = len(b) i = j = k = 0 while i < len_a and j < len_b: if a[i] <= b[j]: arr[k] = a[i] i += 1 else: arr[k] = b[j] j += 1 k += 1 while i < len_a: arr[k] = a[i] i += 1 k += 1 while j < len_b: arr[k] = b[j] j += 1 k += 1 # function for quick sort def swap(a, b, arr): if a != b: tmp = arr[a] arr[a] = arr[b] arr[b] = tmp def quick_sort(elements, start, end): if start < end: pi = partition(elements, start, end) quick_sort(elements, start, pi - 1) quick_sort(elements, pi + 1, end) def partition(elements, start, end): pivot_index = start pivot = elements[pivot_index] while start < end: while start < len(elements) and elements[start] <= pivot: start += 1 while elements[end] > pivot: end -= 1 if start < end: swap(start, end, elements) swap(pivot_index, end, elements) return end bub_sort(nums) selc_sort(nums) shell_sort(nums) print("Shell Sort Method :- ", nums) insertion_sort(nums) merge_sort(nums) print("Merge Sort Method :- ", nums) quick_sort(nums, 0, len(nums) - 1) print("Quick Sort Method :- ", nums) # Queue program # Initializing a queue # taking example a friend queue rida_friends = [] # Adding elements to the queue using append function rida_friends.append('Sam') rida_friends.append('john') rida_friends.append('umrao') rida_friends.append('Stephen') rida_friends.append('Bravo') print("Queue after adding Elements into it") print(rida_friends) # Removing elements from the queue print("\nRemoving Elements One By One from Queue (FIFO).\n") for i in range(0, len(rida_friends)): print("Removed ", f"'{rida_friends.pop(0)}'", " in this iteration.") print(rida_friends, '\n') # TASK NO 5 (STACK) # Initializing a Stack # taking example a friend Stack rida_friends = [] # Adding elements to the Stack using append function rida_friends.append('Sam') rida_friends.append('john') rida_friends.append('umrao') rida_friends.append('Stephen') rida_friends.append('Bravo') print("Stack after adding Elements into it.") print(rida_friends) # Removing elements from the Stack print("\nRemoving Elements One By One from Stack (LIFO).\n") for i in range(0, len(rida_friends)): print("Removed ", f"'{rida_friends.pop()}'", " in this iteration.") print(rida_friends, '\n') # TASK NO 6 (Linked List) class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def add_in_begin(self, data): if self.head is None: node = Node(data) self.head = node else: node = Node(data) node.next = self.head self.head = node def add_at_end(self, data): if self.head is None: self.head = Node(data) return i = self.head while i.next: i = i.next i.next = Node(data) def insert_list(self, dl): self.head = None for d in dl: self.add_at_end(d) def length(self): counter = 0 i = self.head while i: counter += 1 i = i.next print("\nLength of Linked List is :- ", counter) return counter def remove_i(self, index): if index < 0 or index >= self.length(): raise Exception("Wrong Index Pointer..") if index == 0: self.head = self.head.next return counter = 0 i = self.head while i: if counter == index - 1: i.next = i.next.next break i = i.next counter += 1 def insert_at_i(self, index, data): if index < 0 or index >= self.length(): raise Exception("Wrong Index Pointer..") if index == 0: self.add_in_begin(data) counter = 0 i = self.head while i: if counter == index - 1: node = Node(data) i.next = node break i = i.next counter += 1 def __str__(self): if self.head is None: print("Empty Linked List... ") return i = self.head linked_list = '' while i: linked_list += str(i.data) + ', ' i = i.next return linked_list if __name__ == '__main__': link_list = LinkedList() print("Linked List Values :- ") link_list.add_in_begin(5) link_list.add_in_begin(1) link_list.add_at_end(29) link_list.add_in_begin(1000) print(link_list) link_list.insert_list([5, 6, 44, 64, 4]) link_list.length() link_list.remove_i(3) link_list.length() link_list.insert_at_i(3, 64) print(link_list) # TASK NO 7 (STRING OPERATIONS): print('\nString operations in python ::') # initializing a string name = 'Hii I Am Rida Khan' print("Default String :- ", name, "\n\n") # Capitalizing a string x = name.capitalize() print("Capitalized String :- ", x) # converts to case folded string x = name.casefold() print("\nCase folded String :- ", x) # returns occurrences of substring in string x = name.count('a') print("\nNumber of Occurrences of 'a' in string :- ", x) # Checks if String Ends with the Specified Suffix x = name.endswith('n') print("\nIf string is ending with letter 'n' or not :- ", x) # Returns the lower string x = name.lower() print("\nLower String :- ", x) # Encoded String x = name.encode() print("\nEncoded String :- ", x) # Checking Alpha String x = name.isalpha() # Returns False because of spaces between words in string print("\nChecking Alpha String :- ", x) # Doing string Partitions x = name.partition(name) print("\nDoing string Partitions", x) x = name.rfind('Khan') print("\nReturning index where 'Khan' was lastly found :- ", x) # if starts with 'H'. x = name.startswith('H') print("\nif starts with 'H' :- ", x)
cc2eed4379c074e76f43483e1e653f084ebb5839
syurskyi/Algorithms_and_Data_Structure
/Data Structures & Algorithms - Python/Section 6 Data Structures Stacks & Queues/src/47.SOLUTION-Queue-Constructor.py
514
3.953125
4
class Node: def __init__(self, value): self.value = value self.next = None class Queue: def __init__(self, value): new_node = Node(value) self.first = new_node self.last = new_node self.length = 1 def print_queue(self): temp = self.first while temp is not None: print(temp.value) temp = temp.next my_queue = Queue(4) my_queue.print_queue() """ EXPECTED OUTPUT: ---------------- 4 """
1be96f710c6fe646c8702bca76d04880b7f6993f
mapozhidaeva/other
/Test_yourself_before_exam/Guess_definition.py
2,012
3.875
4
import random def file_reading(filename): with open(filename, 'r') as f: return f.read().split('\n') terminology = file_reading('Terminology.tsv') definitions = file_reading('Definitions.tsv') #for i in range(len(definitions)): # print (i + 1, definitions[i]) the_dictionary = dict(zip(terminology, definitions)) #for key, value in the_dictionary.items(): # print (key.upper(), ' - ', value, '\n') '''for i in range(3): dic_len = len(the_dictionary) a = random.randint(0, dic_len) b = random.randint(0, dic_len) while a == b: b = random.randint(0, dic_len) c = random.randint(0, dic_len) while a == c or b == c: c = random.randint(0, dic_len)''' print ('Let\'s start the test!') #while input() != '': #one, two, three = the_dictionary.values[a], the_dictionary.values[b], \ # the_dictionary.values[c] #options = random.shuffle([one, two, three]) answer = 1 while answer != '': random_term = random.choice(list(the_dictionary.keys())) print ('\n', random_term.upper() + ':\n') # print (the_dictionary[random_term]) one = random.choice(list(the_dictionary.keys())) while one == random_term: one = random.choice(list(the_dictionary.keys())) two = random.choice(list(the_dictionary.keys())) while two == one or two == random_term: two = random.choice(list(the_dictionary.keys())) # print ('\n', the_dictionary[one], '\n\n', the_dictionary[two], '\n') answers = [random_term, one, two] right_answer = the_dictionary[random_term] random.shuffle(answers) n = 1 for i in answers: print ('{}) '.format(n), the_dictionary[i], '\n') n += 1 answer = int(input('Введите ответ: 1, 2 или 3: ')) if the_dictionary[random_term] == the_dictionary[answers[int(answer) - 1]]: print ('Правильно') else: print ('Неверно! Правильный ответ - ', the_dictionary[random_term])
5afe9ee03178b30f52f1575f1959ec75ca3aca99
Sancus/pyinvoice
/worked.py
3,658
3.609375
4
#!/usr/bin/env python3 import argparse import calendar import collections import datetime import jsondate3 as json import os import sys def main(): pfile = 'project.json' parser = argparse.ArgumentParser( description=""" worked start -s Feb 24 2017 worked 8 -s Feb 24 2017 comment worked 8 comment (default today) worked summary (lists days and hours worked as well as total) """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-s', '--start-date', dest='start_date', type=valid_date_type, default=datetime.date.today(), help='start datetime in format "YYYY-MM-DD"') parser.add_argument('first', nargs='?') parser.add_argument('other', nargs='*') args = parser.parse_args() # set the date that work happened work_date = args.start_date # set first args and the rest of 'em first = args.first other = args.other # assume we're adding work log work = True # assume we're not creating a new project file create = False if first =='summary': # Build a list of days and how many hours were worked project = check_project_file(pfile) days = {} for entry in project['work_log']: base = days.get(entry['date'], 0) days[entry['date']] = base + entry['hours'] days = collections.OrderedDict(sorted(days.items())) for k, v in days.items(): print("{0} {1} - {2} hours.".format(calendar.day_name[k.weekday()], k, v)) print("You've worked {0} hours on project {1} since {2}.".format(project['total']//project['rate'], project['name'], project['start_date'])) sys.exit() elif first == 'start': create = True work = False else: try: first = int(first) except (ValueError, TypeError): parser.print_help() sys.exit(1) project = check_project_file(pfile, create, work_date) if work: comment = ' '.join(other) log_entry = {'comment': comment, 'date': work_date, 'hours': first, 'subtotal': project['rate'] * first} project['work_log'].append(log_entry) project['total'] = total_cost(project['work_log']) project['totalhours'] = project['total']/project['rate'] write_project_data(project, pfile) def total_cost(work_logs): total = 0 for log in work_logs: total = total + log['subtotal'] return total def write_project_data(project, pfile): with open(pfile, 'w') as f: res = json.dump(project, f, indent=4, sort_keys=True) return res def check_project_file(pfile, create=False, date=False): if os.path.isfile(pfile): with open(pfile, 'r') as f: project = json.load(f) else: if create: project = { 'name': '', 'invoice': '001', 'rate': 0, 'start_date': date or datetime.date.today(), 'work_log': []} else: sys.exit('No {0} found, '.format(pfile)) return project def valid_date_type(arg_date_str): """custom argparse *date* type for user dates values given from the command line""" try: return datetime.datetime.strptime(arg_date_str, "%Y-%m-%d").date() except ValueError: msg = "Given Date ({0}) not valid! Expected format, YYYY-MM-DD!".format(arg_date_str) raise argparse.ArgumentTypeError(msg) if __name__ == '__main__': main()