blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
a48e91a699fd8c9ce1a217a3a4520ff7683a0620
chenjinpeng1/python
/day4/JSQ.py
1,264
3.546875
4
#python 3.5环境,解释器在linux需要改变 #作者:S12-陈金彭 import re def jisuan(num): num=chengchu(num) # String=jiajian(num) return num def chengchu(num): # print(num) # print(re.search('\d+[\.?\d+]?[\*|\/]\d+',num)) if re.search('\-?\d+[\.?\d+]?[\*|\/]\d+',num) is None: return num String=re.search('\-?\d+\.?\d+?[\*|\/]\d+',num).group() print(String) if '/' in String: b='%.2f'%(float(re.split('\/',String)[0])/float(re.split('\/',String)[1])) print('计算结果:%s'%b) num=num.replace(String,str(b)) elif '*' in String: b='%.2f'%(float(re.split('\*',String)[0])*float(re.split('\*',String)[1])) print('计算结果:%s'%b) num=num.replace(String,str(b)) return chengchu(num) def jiajian(num): pass def Sreach(num): String=re.search('\(([\+\-\*\/]?\d+){2,}\)',num).group() String_1=String.strip('\(|\)') print('匹配到%s'%String_1) jieguo=jisuan(String_1) num=num.replace(String,str(jieguo)) num=num.replace('+-','-') print(num) return Sreach(num) Input='1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' print(Input) String=Input.replace(' ','') Sreach(String)
605e75a36708b35729165355612f2e583c6bb3bd
chenjinpeng1/python
/day1/User_login_3/login.py
3,020
3.65625
4
#python 3.5环境,解释器在linux需要改变 #用户登陆认证,阅读手册查询readme文件 #调用文件 login.txt,lock.txt #作者:S12-陈金彭 Auth_File="login.txt" #认证登陆文件 Lock_File="lock.txt" #锁定文件 F_Auth = open(Auth_File) Read_Auth=F_Auth.readlines() #执行前将账号密码文件读取到变量,避免循环读取 F_Auth.close() User_Exit=[] while True: LoginSusses=False #循环开始前先定义登陆成功失败的变量。方便循环嵌套跳转 count = 0 #定义计数器,错误三次锁定 Read_Lock=open(Lock_File) #读取锁文件到变量Lock_List Lock_List=[] for i in Read_Lock.readlines(): line = i.strip('\n') a = Lock_List.append(line) Read_Lock.close() Name=input('请输入你的账户:').strip() for i in Read_Auth: i = i.split() User_Exit.extend(i[0].split()) if Name not in User_Exit: print ('你输入的用户名不存在,请重新输入') continue if Name in Lock_List: A=input("你的账户已经被锁定!!请联系管理员解锁!输入Y解锁,任意键退出:") #,用户登陆前先判断用户是否被锁定后在进行密码判断。 if A == 'Y': f = open('lock.txt') line = f.read() b = line.replace("%s\n"%Name,"") f = open("lock.txt","w") f.write(b) #解锁用户,先将文件内容读出到内存,之后将解锁的用户名替换掉在写入即可。以下是2种方式 print ("锁定已解除,请继续输入密码") else:break for line in Read_Auth: line = line.split() if Name in line: for i in range(3): #定义3次循环, Passwd=input('请输入你的密码:') if Passwd == line[1]: LoginSusses=True print ("Good,欢迎您登陆:%s" %Name) break else: print ("你的密码错误,请重新输入") count +=1 #每次密码错误后计数器count+1,3次后锁定,写入锁文件 if count == 3: f = open(Lock_File,'a') f.write('%s\n'%Name) f.close() print ("你的密码错误次数达到3次,已被锁定") if LoginSusses is True:break #跳出2层循环 if count ==3: #锁定用户后跳出2层循环 break if LoginSusses is True: #跳出2层循环 break
d5339b7e3261d953b7187bae0f79cad2ce7cdc25
chenjinpeng1/python
/Learning/day4/learning.py
6,904
3.671875
4
#python 3.5环境,解释器在linux需要改变 #商城购物,阅读手册查询readme文件 #作者:S12-陈金彭 # li = [13, 22, 6, 99, 11] # for i in range(1,5): # for m in range(len(li)-i): # if li[m] > li[m+1]: # temp = li[m+1] # li[m+1] = li[m] # li[m] = temp # print(li) #---------------------------迭代器-----------------------# # name = iter(['chen','a','b','c']) # print(name.__next__()) # print(name.__next__()) # print(name.__next__()) # print(name.__next__()) # print(name.__next__()) #最后一次会报错 # def cash_money(money,num): # while money > 0: # money-=num # yield num,money # print('又来取钱了啊,败家子!!') # atm=cash_money(1000,200) # print('取了%s,还剩下%s'%atm.__next__()) # print('取了%s,还剩下%s'%atm.__next__()) # print('交个大保健') # print('取了%s,还剩下%s'%atm.__next__()) # print('取了%s,还剩下%s'%atm.__next__()) # import time # def chi(name): # print('%s 来买包子了!'%name) # while True: # baozi = yield # print('包子 %s 来了,被%s 吃了!'%(baozi,name)) # def zuo(name,name2): # A=name # B=name2 # c = chi(A) # c2 = chi(B) # c.__next__() # c2.__next__() # print('老子开始准备做包子了!') # for i in range(1): # time.sleep(1) # print('做了两个包子!') # c.send(i) # c2.send(i) # zuo('chen','qiu') # def chi(name,num): # print('%s来买包子,买%s个'%(name,num)) # while True: # baozi = yield # print('包子%s来了,被%s吃了'%(baozi,name)) # def zuo(name,name2): # A=chi(name,10) # B=chi(name2,10) # A.__next__() # B.__next__() # print('老子开始做包子了') # for i in range(1,20,2): # print('做了两个包子!') # A.send(i) # B.send(i+1) # zuo('陈','邱') # def login(func): # if 1==1: # print('passed user verification...') # return func # else: # return aa # def tv(name): # print('欢迎来到%s!'%name) # def aa(aa): # print('aaaaa') # tv = login(tv) # tv('Tv') #-----------------------装饰器 # def login(func): # def inner(arg): # print('passwd user verification') # func(arg) # return inner # @login # def tv(name): # print('Welcome %s to tv page!!'%name) # tv('tv') # #tv = login(tv)('tv') #----------------------------- # def Before(request,kargs): # print ('before') # # print(Before(1,2)) # def After(request,kargs): # print ('after') # def Filter(before_func,after_func): # def outer(main_func): # def wrapper(request,kargs): # before_result = before_func(request,kargs) # # if(before_result != None): # # return before_result; # main_result = main_func(request,kargs) # # if(main_result != None): # # return main_result; # after_result = after_func(request,kargs) # # if(after_result != None): # # return after_result; # return wrapper # return outer # @Filter(Before, After) # def Index(request,kargs): # print ('index') # if __name__ == '__main__': # Index(1,2) #Filter(Before,After)(Index)('1','2') # #outer (Index)('1','2') # #wrapper ('1','2') # #Before(1,2) # #Index(1,2) # #After(1,2) # def w1(func): # def inner(*args,**kwargs): # # 验证1 # # 验证2 # # 验证3 # print('yz1') # return func(*args,**kwargs) # return inner # def w2(func): # def inner(*args,**kwargs): # # 验证1 # # 验证2 # # 验证3 # print('yz2') # return func(*args,**kwargs) # return inner # # # @w1 # @w2 # def f1(arg1,arg2,arg3): # print ('f1') # f1(1,2,3) #-----------------------------迭代器 # def calc(n): # print(n) # if n/2 >1: # res = calc(n/2) # print('res',res) # # return calc(n/2) # print('N',n) # return n # calc(10) #--------------斐波那契数列-----------------# # List=[] # def func(a,b,c): # if a == 0: # print(a,b) # d=a+b # List.append(d) # if d < c: # # func(b,d,c) # # print(List) # func(1,2,50) # print(List) #----------------------二分法------------------# # def func(yuan,find): # zhongjian = int(len(yuan) / 2) # if zhongjian >= 1: # if yuan[zhongjian] > find: # print(yuan[:zhongjian]) # func(yuan[:zhongjian],find) #func(yuan[:zhongjian],find) # elif yuan[zhongjian] < find: # print(yuan[zhongjian:]) # func(yuan[zhongjian:],find) # else: # print('found find',yuan[zhongjian]) # else: # print('no found') # if __name__== '__main__': # data = [2, 3, 5, 7, 8,11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] # print(data) # func(data,3) ##不能发现第一个。如果将if zhongjian >= 1: 换成len(yuan)的话可以发现 但是如果查找的字符串不在列表里则报错 ''' 2分算法思路: 1、func(data,8)调用函数func 传入的实参为data列表,8 2、执行函数体, 此时zhongjian函数的值就等于列表data的长度/2 , 假设为300 3、进行判断此时yuan长度>=1 数据是否还有值,这里等于设置了2分算法的条件 4、进入判断,原数据的中间值是否比查找的值大, 这里暂定300 > 8 , 因此进入了第一次判断进行的操作 5、再次执行函数func(yuan[:zhongjian],find) 此时函数体里第一个形参就=600[:300] 大于索引往左切片 6、之后进行依次循环 如果循环到yuan[zhongjian] < find 则执行<判断里面的函数体知道判断结束 ''' # data=[[i for i in range(4)] for ii in range(4) ] # for r_index,row in enumerate(data): # for c_index in range(len(row)): # data[r_index][c_index] = row[r_index] # print(data) # # data=[[i for i in range(4)] for ii in range(4) ] # for r_index,row in enumerate(data): # for c_index in range(r_index,len(row)): # tmp = data[c_index][r_index] # data[c_index][r_index] = row[c_index] # data[r_index][c_index] = tmp # print(data) ''' [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3] ''' # a=[[i for i in range(4)] for ii in range(4) ] # for i in range(len(a)): # for ii in range(len(a)): # a[i][ii]=[i] # print(a[i]) # data = [[col for col in range(4)] for row in range(4)] # for i in range(len(data)): # a = [data[i][i] for row in range(4)] # print(a) # a=[[i for i in range(4)] for ii in range(4)] # print(a)
397f7c078e4240f0b5dbf8cf281ff7c4e0d38e56
chenjinpeng1/python
/Learning/day9/多线程队列.py
800
3.515625
4
#python 3.5环境,解释器在linux需要改变 # -*- encoding:utf-8 -*- #Auth ChenJinPeng import time import queue import threading q=queue.Queue() def consumer(n): while True: print("consumer [%s] get task %s"%(n,q.get())) time.sleep(1) q.task_done() def producer(n): count = 1 while True: print("prodcer [%s] produced a new task:%s"%(n,count)) q.put(count) count+=1 q.join() print("all talks has been cosumed by consumers...") c1=threading.Thread(target=consumer,args=[1,]) c2=threading.Thread(target=consumer,args=[2,]) c3=threading.Thread(target=consumer,args=[3,]) c1.start() c2.start() c3.start() p1=threading.Thread(target=producer,args=["A"]) p2=threading.Thread(target=producer,args=["B"]) p1.start() p2.start()
3ae340232a18caaf8039a021c74cce02195fb093
OlegLeva/udemypython
/data_time/weekday.py
232
3.515625
4
from datetime import date day = int(input('Введите день ')) mount = int(input('Введите месяц ')) year = int(input('Введите год ')) data_1 = date(year, mount, day) print(data_1, data_1.isoweekday())
24244974328c4d0bebafcb6849cf9f34e4a20cdf
OlegLeva/udemypython
/codewars_4.py
2,416
3.71875
4
# def divisors(integer): # res = [] # for x in range(2, integer + 1): # if x == integer: # continue # if integer % x == 0: # res.append(x) # if res == []: # return f"{integer} is prime" # else: # return res # # print(divisors(13)) # # def unique_in_order(iterable): # res = [] # i = 1 # if iterable == '' or []: # return [] # else: # res.append(iterable[0]) # while i < len(iterable): # if iterable[i] == res[-1]: # i += 1 # continue # else: # res.append(iterable[i]) # i += 1 # return res # # print(unique_in_order('')) # def tickets(people): # bill_list = [] # for bill in people: # if bill == 25: # bill_list.append(25) # print(f'25 {bill_list}') # if bill == 50 and 25 in bill_list: # bill_list.append(50) # bill_list.remove(25) # print(f'50 {bill_list}') # if bill == 100 and bill_list.count(25) > 3: # bill_list.append(100) # bill_list.remove(25) # bill_list.remove(25) # bill_list.remove(25) # print(f'100/1 {bill_list}') # elif bill == 100 and 25 in bill_list and 50 in bill_list: # bill_list.append(100) # bill_list.remove(25) # bill_list.remove(50) # print(f'100/2 {bill_list}') # if len(people)*25 == sum(bill_list): # return "YES" # else: # return "NO" # # print(tickets([25, 50, 25, 100])) # def nb_year(p0, percent, aug, p): # year = 0 # while p0 < p: # p0 = p0 + p0 * (percent/100) + aug # year += 1 # return year # # print(nb_year(1500000, 0.25, 1000, 2000000)) #https://www.codewars.com/kata/578553c3a1b8d5c40300037c/train/python # def binary_array_to_number(arr): # arr1 = arr[::-1] # i = 0 # result = [] # for x in arr1: # if x == 1: # result.append(2**i) # i += 1 # return sum(result) # def remove_smallest(numbers): # if numbers == []: # return [] # new_numbers = numbers[:] # new_numbers.remove(min(numbers)) # return new_numbers # # print(remove_smallest([5, 3, 2, 1, 4])) n = 4 a = [[0] * n for i in range(n)] for i in range(0, 0): print(i)
51870915c84356ae8b89f41116bfad1856ad5649
OlegLeva/udemypython
/tkinter_frame/temperatur_converter.py
1,396
3.609375
4
from tkinter import * from tkinter import ttk def calculate(*args): try: value = float(fahrenheit.get()) fahren = (value - 32) * 5/9 celsius.set(float('%.3f' % fahren)) except ValueError: pass root = Tk() root.title("fahrenheit to celsius") mainframe = ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(N, W, E, S), padx=5, pady=5) root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) fahrenheit = StringVar() fahrenheit_entry = ttk.Entry(mainframe, width=7, textvariable=fahrenheit) fahrenheit_entry.grid(column=0, columnspan=2, row=1, sticky=(W, E), padx=5, pady=5) celsius = StringVar(value='Temperatur in celsius') ttk.Label(mainframe, textvariable=celsius).grid(column=2, row=2, sticky=(W, E)) ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=1, columnspan=3, row=3, sticky=(W, E)) ttk.Label(mainframe, text="fahrenheit").grid(column=3, row=1, sticky=W, padx=5, pady=5) ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E, padx=5, pady=5) ttk.Label(mainframe, text="celsius").grid(column=3, row=2, sticky=W, padx=5, pady=5) for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) fahrenheit_entry.focus() root.bind("<Return>", calculate) root.mainloop()
f671ceda60fed582e53f0628e3d2c7b1420c4a79
OlegLeva/udemypython
/41/atribute.py
504
3.625
4
class BlogPost: def __init__(self, user_name, text, number_of_likes): self.user_name = user_name self.text = text self.number_of_likes = number_of_likes post1 = BlogPost(user_name='Oleg', text='Hi', number_of_likes=7) post2 = BlogPost(user_name='Nik', text='Hello', number_of_likes=5) post3 = BlogPost('Olga', 'bla bla bla', 11) post2.number_of_likes = 99 post3.number_of_likes = 999 print(post1.number_of_likes) print(post2.number_of_likes) print(post3.number_of_likes)
d0ac9c79bc132a70a1542d97018838a58e7d7835
OlegLeva/udemypython
/72 Бесконечный генератор/get_current.py
788
4.21875
4
# def get_current_day(): # week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] # i = 0 # while True: # if i >= len(week): # i = 0 # yield week[i] # i += 1 # # # amount_day = int(input('Введите количество дней ')) # current_day = get_current_day() # count = 0 # while count != amount_day: # print(next(current_day)) # count += 1 def get_infinite_square_generator(): """ :return: """ i = 1 while True: yield i ** 2 i += 1 infinite_square_generator = get_infinite_square_generator() print(next(infinite_square_generator)) print(next(infinite_square_generator)) print(next(infinite_square_generator)) print(next(infinite_square_generator))
b9f48b506100dbfe6fc37262adde19077cb606d3
choldstare/pythonstudy
/example9.py
745
3.984375
4
print "I am 6'3\" tall." # escape double-quote inside string print 'I am 6\'3" tall.' tabby_cat= "\tI'm tabbed in." # \t acts as a tab persian_cat="I'm split\non a line." # the \non split the line backslash_cat="I'm \\ a \\ cat." # the double \\ caused just one of them to print.\\ #the fat_cat below used """ so this allows me write indefinately and make a list fat_cat= """ I'll do a list: \t* cat food \t* Fishies \t* Catnip \n\t* Grass """ fat_cat1= ''' I'll do a list: \t* cat food\rpenis \t* Fishies \t* Catnip \n\t* Grass ''' print tabby_cat print persian_cat print backslash_cat print fat_cat print fat_cat1 #while True: # for i in ["/","-","|","\\","|"]: # print "%s\r" %i,
824e020881e6097c26d66fca82031bafd7431999
mekunalkishan/PythonBegin
/Excercise_Strings.py
518
4.09375
4
ex_string = "Just do it!" #Access the "!" from the variable by index and print() it print (ex_string[10]) #Print the slice "do" from the variable print(ex_string[5:7]) #Get and print the slice "it!" from the variable print(ex_string[8:11]) #Print the slice "Just" from the variable print(ex_string[:4]) #Get the string slice "do it!" from the variable and concatenate it with the string "Don't ". #Print the resulting string. print("Don't "+ex_string[5:11]) print(type(ex_string)) print ("This is \n next line")
57aca02f8c266fb2fae85692717da731e87ed325
koltpython/python-assignments-spring2020
/Assignment1/starter/tic_tac_toe.py
3,122
4.53125
5
""" Koc University, Turkey KOLT Python Certificate Program Spring 2020 - Assignment 1 Created by @ahmetuysal and @hasancaslan """ import turtle SCREEN_WIDTH = 720 SCREEN_HEIGHT = 720 PEN_SIZE = 5 SQUARE_SIZE = 100 ANIMATION_SPEED = 100 # Animation speed def draw_empty_board(): """ This function should draw the empty tic-tac-toe board using turtle module """ # TODO: Implement this function # Hints: # 1- You might want to implement a helper function for drawing only one square # 2- You can create a "nested" for loop to draw a 3x3 board using the helper function you created def draw_x_in_square(row, column): """ This function should draw and X symbol on the given square of tic-tac-toe board """ # TODO: Implement this function # Hints: # 1- You might want to use penup, pendown, setpos, setheading, forward functions from turtle module # 2- We recommend you to spend some time with turtle module in the interactive shell to understand # how it uses coordinates (which directions are positive, which angles correspond to which directions, etc.) pass def draw_o_in_square(row, column): """ This function should draw and O symbol on the given square of tic-tac-toe board """ # TODO: Implement this function # Hints: # 1- You might want to use penup, pendown, setpos, setheading, circle functions from turtle module # 2- We recommend you to spend some time with turtle module in the interactive shell to understand # how it uses coordinates (which directions are positive, which angles correspond to which directions, etc.) pass def display_setup(): turtle.screensize(SCREEN_WIDTH, SCREEN_HEIGHT) turtle.speed(ANIMATION_SPEED) turtle.pensize(PEN_SIZE) if __name__ == '__main__': # Display setup display_setup() draw_empty_board() player_names = [] # TODO: Take player names, any string other than empty string is considered a valid name # Game setup game = [['', '', ''], ['', '', ''], ['', '', '']] # Loop for the game for move_counter in range(9): # TODO: Get current user to play current_player_name = '' # TODO: take user's move move = '' # TODO: validate the user's move, you need to ask again until user enters a valid move # 1. It should be a string consisting of two parts (Hint: use "string".split(' ') function) # 2. Both its parts should be integers (Hint: "string".isnumeric() function) # 3. Integers should be in range [0, 2] inclusive # 4. Selected square should be emtpy # TODO: play the move: you should modify the game list & display the move using turtle there_is_winner = False # TODO: check win conditions # If there is a winner, terminate loop # and display winner if there_is_winner: print(f'{current_player_name} wins!') break # If there_is_winner variable is still false, game ended in a draw if not there_is_winner: print('Game ended in a draw') turtle.done()
15b88f363f9b4a6073eb4becb46d7c31e708461b
KaiFujimoto/KaiChen_Spotify
/sort_by_strings.py
972
4.03125
4
def sort_by_strings(s, t): """ sample input: "cats" "atzc" sample output: "catz" assumption(s) => 1. s does not have repeating letters 2. s and t are all lowercased 3. Overall, the goodwill of the person running my code that they will be nice. (have mercy plox) 4. Person running my code likes notes. If not, then apologies QQ. """ copy_of_t = t # don't want to modify stuff result = '' # result string set up for char in s: # iterate through each character in the first string number_of_occurences = copy_of_t.count(char) # find the number of times it occurs in t result += char * number_of_occurences # put it that many times into our result copy_of_t = copy_of_t.replace(char, '') # change the character to an empty string so we don't count it again return result + copy_of_t # add the remaining characters in the copy of t to our result print(sort_by_strings("cats", "atzc"))
4f330c0fdbe5a6cc49b506011b88c610ef1abc60
Jules-Boogie/controllingProgramFlow
/SearchAStringFunction/func.py
1,087
4.21875
4
""" A function to find all instances of a substring. This function is not unlike a 'find-all' option that you might see in a text editor. Author: Juliet George Date: 8/5/2020 """ import introcs def findall(text,sub): """ Returns the tuple of all positions of substring sub in text. If sub does not appears anywhere in text, this function returns the empty tuple (). Examples: findall('how now brown cow','ow') returns (1, 5, 10, 15) findall('how now brown cow','cat') returns () findall('jeeepeeer','ee') returns (1,2,5,6) Parameter text: The text to search Precondition: text is a string Parameter sub: The substring to search for Precondition: sub is a nonempty string """ result = () start = 0 l = len(sub) while start < len(text): print(str(start) + "first") if (sub in text) and (text.find(sub,start,start+l+1) != -1): start = (text.find(sub,start,start+l+1)) result = result + (start,) start = start + 1 print(str(start) + "end") return result
b1185e9c9738f772857051ae03af54a4fb20487e
Jules-Boogie/controllingProgramFlow
/FirstVowel-2/func.py
976
4.15625
4
""" A function to search for the first vowel position Author: Juliet George Date: 7/30/2020 """ import introcs def first_vowel(s): """ Returns the position of the first vowel in s; it returns -1 if there are no vowels. We define the vowels to be the letters 'a','e','i','o', and 'u'. The letter 'y' counts as a vowel only if it is not the first letter in the string. Examples: first_vowel('hat') returns 1 first_vowel('grrm') returns -1 first_vowel('sky') returns 2 first_vowel('year') returns 1 Parameter s: the string to search Precondition: s is a nonempty string with only lowercase letters """ result = len(s) vowels = ['a','e','i','o','u'] for x in vowels: if x in s: result = min(result,introcs.find_str(s,x)) if not x in s and "y" in s and introcs.rfind_str(s,"y") != 0: result = introcs.rfind_str(s,"y") return result if result != len(s) else -1
749309f49b5f64bd3daccbe8ded8211721e52916
hamidshahsavar/python
/senarios/prime_number_generstor.py
115
3.5
4
def is_prime(n): for i in range(n): if n i==0 return False else: return True
b7d990539a50faef24a02f8325342f385f518101
github0282/PythonExercise
/Abhilash/Exercise2.py
1,141
4.34375
4
# replace all occurrences of ‘a’ with $ in a String text1 = str(input("Enter a string: ")) print("The string is:", text1) search = text1.find("a") if(search == -1): print("Character a not present in string") else: text1 = text1.replace("a","$") print(text1) # Take a string and replace every blank space with hyphen text2 = str(input("Enter a string: ")) print("The string is:", text2) text2 = text2.replace(" ","-") print(text2) # count the number of upper case and lower-case letters in a string text3 = str(input("Enter a desired string: ")) print(text3) UpperCase = 0 LowerCase = 0 for i in text3: if( i >= "a" and i <= "z"): LowerCase = LowerCase + 1 if( i >= "A" and i <= "Z"): UpperCase = UpperCase + 1 print("No of UpperCase Characters: ", UpperCase) print("No of LowerCase Characters: ", LowerCase) # Check if a substring is present in a given string text4 = str(input("Enter a desired string: ")) substring = str(input("Enter the substring: ")) if(text4.find(substring) == -1): print("Substring is not present in the string") else: print("Substring is present in the string")
fde6c8a93608ad30bf3eba3db4fdceb1772e6089
SeanSyue/TensorflowReferences
/ZhengBo/test.py
2,516
3.6875
4
# -*- coding: utf-8 -*- import tensorflow as tf def relu(x, alpha=0.5, max_value=None): '''ReLU. alpha: slope of negative section. ''' negative_part = tf.nn.relu(-x) x = tf.nn.relu(x) if max_value is not None: x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX), tf.cast(max_value, dtype=_FLOATX)) x -= tf.constant(alpha, dtype=_FLOATX) * negative_part return x ''' A truncated normal distribution is derived from cutting off the tails from a normal distribution. The point for using truncated normal is to overcome saturation of tome functions like sigmoid (where if the value is too big/small, the neuron stops learning). ''' def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.6) return tf.Variable(initial, dtype=tf.float32, name=name) def bias_variable(shape, name): initial = tf.constant(0.6, shape=shape) return tf.Variable(initial, dtype=tf.float32, name=name) x = tf.placeholder(tf.float32, [None, 8]) y_ = tf.placeholder(tf.float32, [None, 8]) n_hidl = 3 W_fc1 = weight_variable([8, n_hidl], 'W_fc1') b_fc1 = bias_variable([n_hidl], 'b_fc1') h_fc1 = tf.nn.relu(tf.matmul(x, W_fc1) + b_fc1) W_fc2 = weight_variable([n_hidl, 8], 'W_fc2') b_fc2 = bias_variable([8], 'b_fc2') target_conv = tf.matmul(h_fc1, W_fc2) + b_fc2 iteration = 81000 cross_entropy = tf.reduce_mean(abs(target_conv-y_)*10) # Define cost function train_step = tf.train.AdamOptimizer(8e-4).minimize(cross_entropy) # Optimizer #correct_prediction = tf.equal(tf.argmax(target_conv,1), tf.argmax(y_,1)) accuracy = tf.subtract(y_, target_conv) # Define accuracy saver = tf.train.Saver() with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) sess.run(tf.global_variables_initializer()) for i in range(iteration): train_step.run(feed_dict={x: reshape_features.eval(), y_: reshape_labels.eval()}) if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict={x: reshape_features.eval(), y_: reshape_labels.eval()}) predict = target_conv.eval(feed_dict={x: reshape_features.eval(), y_: reshape_labels.eval()}) print("step %d, error %g,predict %g" % (i, train_accuracy, predict)) if i % 1000 == 0: save_path = saver.save(sess, model_filepath+'model_118_%d.ckpt' % i) coord.request_stop() coord.join(threads)
40d3602df649e0e7236ef9ed7d82eded2c0a480b
MouseDoNotLoveCat/02_Python_Liao
/5.5.py
181
3.8125
4
# _*_ coding: utf-8 _*_ """@author: Luhow 匿名函数 @time:2018/12/122:57 """ def is_odd(n): return n % 2 == 1 L = list(filter(lambda n : n % 2 == 1, range(1, 20))) print(L)
0a9af0e9f32015d7c9545e815dc04199863fb36a
chiongsterer00/cp2015
/p03/q1_display_reverse.py
200
4.0625
4
def reverse_int(n): reverse = [""]*len(n) for i in range(0, len(n)): reverse[-i-1] = n[i] print("".join(reverse)) integer = input("Please enter an integer\n") reverse_int(integer)
722b0f60d2d6c4694152fc6620ecbfa89dca4257
nathanlmetze/Algorithms_Python
/MergeSort.py
582
4.09375
4
# MergeSort algorithm # By Nathan M. Using pseudocode from the book # Using variable names found in the book # Used for floor import math # Helper method def merge(B, C, A): i = 0 j = 0 k = 0 while i < len(B) and j < len(C): if B[i] <= C[j]: A[k] = B[i] i += 1 else: A[k] = C[j] j += 1 k += 1 if i == len(B): A[k:] = C[j:] else: A[k:] = B[i:] def merge_sort(A): B = [] C = [] if len(A) > 1: B = A[:math.floor(len(A)/2)] C = A[math.floor(len(A)/2):] merge_sort(B) merge_sort(C) merge(B, C, A) print(A) merge_sort([8, 3, 2, 9, 7, 1, 5, 4])
1a46fb51ff0f9e4d59a3bd869791ef4d8aed1735
Arifuzzaman-Munaf/HackerRank
/Python/Validating Credit Card Numbers.py
368
3.75
4
import re N = input() for i in range(int(N)): credit = input().strip() validation = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',credit) if validation: flatten = "".join(validation.group(0).split('-')) valid = re.search(r'(\d)\1{3,}',flatten) print('Invalid' if valid else 'Valid') else: print('Invalid')
81a230aa7696bd7d651811e6d8fcdf22b8121f23
tomik/honey
/honey/pagination.py
1,315
3.515625
4
from flask import url_for class Pagination(object): """Simple pagination class.""" def __init__(self, per_page, page, count, url_maker, neighbours=5): self.per_page = per_page self.page = page self.count = count self.url_maker = url_maker self.neighbours = 5 def url_for(self, page): return self.url_maker(page) def __iter__(self): if self.has_previous(): yield 1 batch_lo = max(2, self.page - self.neighbours) if batch_lo > 2: yield None for p in range(batch_lo, self.page): yield p yield self.page if self.has_next(): batch_hi = min(self.pages, self.page + self.neighbours + 1) for p in range(self.page + 1, batch_hi): yield p if batch_hi < self.pages: yield None yield self.pages def has_previous(self): return self.page > 1 def has_next(self): return self.page < self.pages @property def previous(self): return self.url_for(self.page - 1) @property def next(self): return self.url_for(self.page + 1) @property def pages(self): return max(0, self.count - 1) // self.per_page + 1
f8b6d469de64fae530a908d7f861058978990ce3
shresth26/nifpy
/nifpy/financials.py
4,069
3.78125
4
from datetime import datetime import lxml from lxml import html import requests import numpy as np import pandas as pd import bs4 """ To get the name of symbol/ticker of the stocks for which you want information you can look it up on https://finance.yahoo.com/ and from there you can pass the scrip name in the parameter where required. """ headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9', 'Cache-Control': 'max-age=0', 'Pragma': 'no-cache', 'Referrer': 'https://google.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36' } def _calculate_financials(symbol, statement): """ calculate_financials function is used to fetch and preprocess the financial documents from the Yahoo Finance website. Parameters -------------------------------- symbol : It is used to specify the symbol/ticker for which the financials have to be fetched statement : The name of the financial statement that has to be fetched. Categories = [ 'balance-sheet' : Fetches the balance sheet, 'cash-flow' : Fetches the cash flow statement, 'financials' : Fetches the income statement ] Returns -------------------------------- A dataframe that contains the required financial statement. """ headers = [] temp_list = [] label_list = [] final = [] index = 0 url = 'https://finance.yahoo.com/quote/' + symbol + '/' + statement + '?p=' + symbol page = requests.get(url, headers) soup = bs4.BeautifulSoup(page.content,'html.parser') features = soup.findAll('div', class_ = 'D(tbr)') for item in features[0].find_all('div', class_='D(ib)'): headers.append(item.text) while index <= len(features) - 1: temp = features[index].findAll('div', class_='D(tbc)') for line in temp: temp_list.append(line.text) final.append(temp_list) temp_list = [] index+=1 df = pd.DataFrame(final[1:]) df.columns = headers return df def get_balance_sheet(symbol): """ Used to obtain the balance sheet of the specified ticker Parameters -------------------------------- symbol : It is used to specify the symbol/ticker for which the balance sheet has to be fetched Returns -------------------------------- A dataframe that contains the balance sheet of the company """ bal_sheet = _calculate_financials(symbol, 'balance-sheet') return bal_sheet def get_cash_flow(symbol): """ Used to obtain the cash flow statement of the specified ticker Parameters -------------------------------- symbol : It is used to specify the symbol/ticker for which the cash flow has to be fetched Returns -------------------------------- A dataframe that contains the cash flow statement of the company """ cash_flow = _calculate_financials(symbol, 'cash-flow') return cash_flow def get_income_statement(symbol): """ Used to obtain the income statement of the specified ticker Parameters -------------------------------- symbol : It is used to specify the symbol/ticker for which the income statement has to be fetched Returns -------------------------------- A dataframe that contains the income statement of the company """ inc_statement = _calculate_financials(symbol, 'financials') return inc_statement
11ccee81914bcac1b9a119b93760d1d709f5ed4e
samanbatool08/py-resize
/list.py
283
3.96875
4
from cs50 import get_int numbers = [] while True: number = get_int("Number: ") if not number: break # Avoid duplicates if numbeer not in numbers: # Add to list numbers.append(number) print() for number in numbers: print(number)
fbf4b19b08ecc9352b07afbe74cb6b461c847240
khuang7/3121-algorithms
/wk2/insertionsort.py
413
3.953125
4
# we are interested in looking specifically on how to calculate the time def main(): A = [5, 4, 3, 2, 1] print(insertionsort(A)) def insertionsort(A): for j in range(1, len(A)): key = A[j] # insert A[j] into the sorted sequence A[1..j-1] i = j while i > 0 and A[i - 1] > key: A[i] = A[i - 1] i = i - 1 A[i] = key return A main()
dffd95e9a9283ee2903f27b023ab90f5c120e7de
khuang7/3121-algorithms
/dynamic_programming/longest_common_subsequence.py
1,308
3.609375
4
''' Finds the longest common subsequence of two sequences (Given as 2 arrays) ''' from pandas import DataFrame x = [0, 3, 9, 8, 3, 9, 7, 9, 7, 0,] y = [0, 3, 3, 9, 9, 9, 1, 7, 2, 0,6] def main(): longest_subsequence(x, y) def longest_subsequence(a, b): DP = [[0] * (len(a)) for i in range(len(b))] back_trace = [[(-1,-1)] * (len(a)) for i in range(len(b))] went_here = [[False] * (len(a)) for i in range(len(b))] for i in range(1, len(b)): for j in range(1, len(a)): if a[j] == b[i]: DP[i][j] = DP[i - 1][j - 1] + 1 back_trace[i][j] = (i-1, j-1) went_here[i][j] = True else: if DP[i - 1][j] >= DP[i][j-1]: DP[i][j] = DP[i-1][j] back_trace[i][j] = (i-1,j) else: DP[i][j] = DP[i][j-1] back_trace[i][j] = (i, j-1) results = [] cur_grid = (len(y)-1, len(x)-1) while back_trace[cur_grid[0]][cur_grid[1]] != (-1,-1): if went_here[cur_grid[0]][cur_grid[1]]: results.append(b[cur_grid[0]]) cur_grid = back_trace[cur_grid[0]][cur_grid[1]] print(DataFrame(DP)) print(DataFrame(back_trace)) print(DataFrame(went_here)) print(results) main()
782b19c9bf441bca8e8c5ae754cbec05c0bce121
khuang7/3121-algorithms
/dynamic_programming/fib.py
838
4.125
4
''' A simple fibonacci but using memoization and dynamic programing An introduction to the basics of dynamic programming ''' memo = {} def main(): print(fib_naive(5)) print(fib_bottoms_up(4)) def fib_naive(n): ''' We used the recursive method in order to fine every combination from f(n) down the tree This is EXPONENTIAL and bad.. ''' #fib(1) and fib(2) are 1 if n == 1 or n == 2: return 1 else: f = fib_naive(n-1) + fib_naive(n-2) return f def fib_bottoms_up(n): ''' We iteratively start from 1..n Store it in memoization WE can actually just keep updating as we go up O(n) TIME ''' for k in range(1,n + 1): if k <= 2: f = 1 else: f = memo[k-1] + memo[k-2] memo[k] = f return memo[n] main()
14fd6a8f9fc561862baa3fead606419540d608a8
Ze1al/Algorithm-Python
/other/5.py
621
3.78125
4
# 计算最少要用几次按键 # 输入:AaAAAA # 输出8 # 1. 边界条件: n<=0, return 0 # 2. 判断第一个字符是不是大写,大写 res+1 # 3. 连着2个字母以上都是大写或者小写 就 res=长度+2(用const方法) # 4. 连着2个字母不一样就用 res += 3 def count_keyboard(): n = int(input()) a = input() count = len(a) if a[0].isupper(): count += 1 for i in range(1, n): if a[i].islower() and a[i - 1].isupper(): count += 1 elif a[i].isupper() and a[i - 1].islower(): count += 1 print(count-1) count_keyboard()
2d84645e1883150617c3caef26892c6ee45ade23
Ze1al/Algorithm-Python
/other/sort_by_name.py
790
4.0625
4
# 输入包括多行,每一行代表一个姓和名字 # 输出排好序以后的名字 from collections import Counter import sys names = ['ZHANG SAN', 'LI SI', 'WANG WU', 'WANG LIU', 'WANG QI', 'ZHANG WU', 'LI WU' ] def get_count(name): first_names = [name.split()[0] for name in names] first_name = name.split()[0] counters = Counter(first_names) return counters.get(first_name) results = sorted(names, key=lambda x: get_count(x), reverse=True) for result in results: print(result) # if __name__ == "__main__": # strList = [] # for line in sys.stdin: #当没有接受到输入结束信号就一直遍历每一行 # tempStr = line.split()#对字符串利用空字符进行切片 # strList.extend(tempStr)#把每行的字符串合成到列表
7d17735ad32cef1f0c57f05d282db03bf0258b0f
Ze1al/Algorithm-Python
/sort/SelectSort.py
212
3.625
4
def SelectSort(arr): n = len(arr) for i in range(0, n-1): min_index = i for j in range(i+1, n): if arr[i]>arr[j]: arr[i],arr[j] = arr[j],arr[i] return arr
718c4c08139313bdeeab46707056e87c505b5bc1
gomes97/codekata
/large.py
105
3.859375
4
x=input(" ") y=input(" ") z=input(" ") if x>y and x>z: print(x) elif y>z: print(y) else: print(z)
cc9687778ced87f7136faf0a49db7645b71602d1
gomes97/codekata
/isomorpic.py
242
3.84375
4
s=raw_input() s1=raw_input() l=len(s) l1=len(s1) if(l==l1): for i in range(l): for j in range(i+1,l): if(s[i]==s[j]): if(s1[i]==s1[j]): print("isomarpic") else: print("not a isomorpic") else: print("not a isomorpic")
a6bd6fcc63575cde80874ed0fb7e28af9b36453d
gomes97/codekata
/subset.py
203
3.546875
4
a1=[1,2,4] a2=[1,2,4,7] c=0 for i in range(len(a2)): if(a1[0]==a2[i]): for j in range(len(a1)): if(a1[j]==a2[i]): i=i+1 c=c+1 if(c==len(a1)): print("subset") else: print("not a subset")
a443cd1c306de6e4f030977dde74c4394a46fddd
VladislavRb/alg_lab3
/main.py
720
3.5625
4
from tree import BinaryTree from random import randint arr = list(set([randint(0, 100) for i in range(20)])) print("array length:", len(arr)) bst = BinaryTree(arr) print("=====") print("is balanced:", bst.is_balanced(bst.root)) print("tree height:", bst.get_height(bst.root)) print("=====") bst.print_tree() print("=====") print(bst.get_sorted_array()) print(bst.get_sorted_array(reverse=True)) print("=====") k = randint(1, len(arr)) print("k:", k) print("expected min k elem:", bst.get_sorted_array()[k - 1]) print("actual:", bst.k_min_node(k, bst.root).value) print("=====") bst.balance(bst.root) print("is balanced:", bst.is_balanced(bst.root)) print("tree height:", bst.get_height(bst.root)) print("=====")
eacc76f9e2a3e6a8322ec5969792f7d4d743fd0b
1nfernoS/week2
/week2/korova.py
163
3.75
4
i = int(input()) if i%10 == 1 and i//10!=1: print(i, 'korova') elif i%10<5 and i//10!=1 and i%10!=0: print(i, 'korovy') else: print(i, 'korov')
89495c7cb55268122493bb126b1e3ea9a9c19fca
Jamilnineteen91/Sorting-Algorithms
/Merge_sort.py
1,986
4.34375
4
nums = [1,4,5,-12,576,12,83,-5,3,24,46,100,2,4,1] def Merge_sort(nums): if len(nums)<=1: return nums middle=int(len(nums)//2)#int is used to handle a floating point result. left=Merge_sort(nums[:middle])#Divises indices into singular lists. print(left)#Prints list division, lists with singular items are the final results. right=Merge_sort(nums[middle:])#Divises indices into singular lists. print(right)#Prints list division, lists with singular items are the final results. return merge(left,right) def merge(left, right): sorted_list=[] index_L=0 #index_L is used to incrementally ascend the left list. index_R=0 #index_R is used to incrementally ascend the right list. #Lists containing more than one item will enter the while loop where they'll be sorted. while index_L < len(left) and index_R < len(right): #Prints left & right groups that are have entered the while loop. print(left[index_L:], right[index_R:]) if left[index_L]<=right[index_R]: sorted_list.append(left[index_L]) index_L+=1 #Prints the current sorted_list state, the smallest item between the left group and right group has been inserted into sorted_list. print(sorted_list) else: sorted_list.append(right[index_R]) index_R+=1 #Prints the current sorted_list state, the smallest item between the left group and right group has been inserted into sorted_list. print(sorted_list) #Lists containing one item will be added to the sorted_list. #The append function is unable to append lists into new_list, hence why'+=' is used. #Unable to use 'index_L' as a list index since the incrementation only takes place in the while loop,hence why 'index_L:' and 'index_R:' are used. sorted_list+= left[index_L:] sorted_list+= right[index_R:] return sorted_list print(Merge_sort(nums))
b59d828a5f75746cff11a5238a485c7cc98b594d
Expert37/python_lesson_3
/123.py
1,099
4.5
4
temp_str = 'Все счастливые семьи похожи друг на друга, каждая несчастливая семья несчастлива по-своему. Все счастливые семьи' print('1) методами строк очистить текст от знаков препинания;') for i in [',','.','!',':','?']: temp_str = temp_str.replace(i,'') print(temp_str) print() print('2) сформировать list со словами (split);') temp_str = list(temp_str.split()) # приведем к типу list и применим метод split print(type(temp_str), temp_str) print() print('3) привести все слова к нижнему регистру (map);') new_temp_str = list(map(lambda x:x.lower(),temp_str)) print(type(new_temp_str), new_temp_str) print() print('4) получить из list пункта 3 dict, ключами которого являются слова, а значениями их количество появлений в тексте;') #dict_temp = dict.new_temp_str #print(type(dict_temp))
b4253e5b362ff30e2c67bc828d655abaf35fb837
aritra14/Rosalind-Solutions
/rosalind1.py
305
3.75
4
# Counting DNA Nucleotides dna=input(' Enter the nucleotide sequence ') dna=dna.upper(); acount=dna.count('A',0,len(dna)); tcount=dna.count('T',0,len(dna)); gcount=dna.count('G',0,len(dna)); ccount=dna.count('C',0,len(dna)); X=[acount,ccount,gcount,tcount]; print (' '.join(str(x) for x in X))
aa76920f13f7b7ef89f0a86245c5aad19a0c779d
Lucas-Brum/Curso-em-Video
/mundo 2/desafios/Desafio042.py
676
4.03125
4
reta1 = float(input('Digite o tamanho da primera reta: ')) reta2 = float(input('Digite o tamanho da segunda reta: ')) reta3 = float(input('Digite o tamanho da terceira reta: ')) if (reta3 + reta2) >= reta1 and (reta1 + reta2) >= reta3 and (reta1 + reta3) >= reta2: print('\33[4:34mÉ possivel fazer um triangulo com as retas!\33[m') if reta1 == reta2 and reta2 == reta3: print('\33[1:35mTriangulo equilátero...') elif reta1 == reta2 or reta1 == reta3 or reta2 == reta3: print('\33[1:35mTriangulo isóceles...') else: print('\33[1:35mTriangulo escalenio...') else: print('\33[4:31mNão é possivel fazer um triangulo com as retas!')
9fc75a7a85a6a6d3ec3d3c327d447e8914d233f4
Lucas-Brum/Curso-em-Video
/mundo 1/Desafios/Desafio031V2.py
221
3.515625
4
distancia = float(input('Qual a distancia da sua viagem?')) preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45 print('O preço da tua viagem vai ser \33[34m{}'.format(preço)) print('\33[32mBoa viagem!')
fc18ba786b67f3239b07df14f050f96abe544ed8
Lucas-Brum/Curso-em-Video
/mundo 1/Aula/aULA10A.py
129
3.84375
4
nome = str(input('Qual teu nome: ')) if nome == 'Lucas': print('Que nome lindo você tem!') print('Bom dia {}!'.format(nome))
bf0a1713be99d38957d9fcf028fd14ea8f83b2ae
Lucas-Brum/Curso-em-Video
/mundo 1/Desafios/Desafio013.py
158
3.703125
4
salario = float(input('Digite o salario atual: ')) aumento = salario + (salario * 0.15) print('O seu novo salario fica \33[4:31m{:.2F}\33[m.'.format(aumento))
4afe476be401c4706f4e6ed5851dcd406d4090da
Lucas-Brum/Curso-em-Video
/mundo 2/desafios/Desafio038.py
498
3.84375
4
print('\33[31m-=-\33[m' * 20) print('\33[4m\33[1mQual valor é maior?') print('\33[m\33[31m-=-\33[m' * 20) valor1 = float(input('Digite um valor:')) valor2 = float(input('Digite outro valor:')) print('\33[31m-=-\33[m' * 20) if valor1 > valor2: print('\33[31m{}\33[m é maior que \33[34m{}\33[m'.format(valor1, valor2)) elif valor2 > valor1: print('\33[31m{}\33[m é maior que \33[34m{}\33[m'.format(valor2, valor1)) else: print('Os valores são iguais!') print('\33[31m-=-\33[m' * 20)
d107ae97122fa0c64aa129a7466f75ad5a8b33b1
ZJTJensen/Python-class-work
/touples.py
309
3.8125
4
def touples(my_dict): touple =() for key,data in my_dict.iteritems(): # print key, " = ", data touple += key, data # touple += data print touple my_dict = { "Speros": "(555) 555-5555", "Michael": "(999) 999-9999", "Jay": "(777) 777-7777" } print touples(my_dict)
b9bda4d7cea4da14e7a169a377bffc28e6c27e36
ZJTJensen/Python-class-work
/comparing.py
331
3.78125
4
list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] val = 0 yes = 0 while val < len(list_one): if list_one[val] == list_two[val]: val=val+1 continue elif list_one[val] != list_two[val]: print "not the same" yes = 1 break if yes == 0: print "They are the same" # 111111211 # 111111111
738efa2e2e3343519471b35b2a6a9e11ef1c0e1a
ZinGitHub/Innovative-AI-App-Final-Project-Deliverable-
/AIResearchAssistant.py
36,450
3.75
4
""" The purpose of this project is to provide students a helping tool. No matter if the student is no college,university, or high school. This program offers such tools as a text summarizer, Wikipedia scraper, text-to-speech to give presentations, text-to-PDF tool, and a chatbot which will act as extra help with providing helpful information to students. """ # General Libraries import tkinter as tk # Library for wikipedia data collection import wikipedia from tkinter import * # Specific GUI Window Tabs Libraries from tkinter import ttk from tkinter.scrolledtext import * # Import from SummarizeText.py from SummarizeText import SummarizeText # Importing Google text-to-speech library from gtts import gTTS # Importing pyttsx3 text-to-speech library import pyttsx3 # Importing fpdf library from fpdf import FPDF # Importing ChattberBot library from chatterbot import ChatBot # Importing Chatterbot.trainers library from chatterbot.trainers import ListTrainer # Importing pyjokes library import pyjokes # Imported to play the converted audio file import os # Create GUI # Create Window # Build Main Window window = tk.Tk() # Main Window Title # AI Research Assistant window.title("AI Research Assistant") # Window Size # Wide x Tall # window.geometry('825x800') window.geometry("825x800") # Set style of tabs style = ttk.Style(window) # Set location of tabs # wn = West North style.configure('lefttab.TNotebook', tabpostition='wn') # tab_control =ttk.Notebook(window) # Collect and display all tabs starting from left to right. tab_control = ttk.Notebook(window, style='lefttab.TNotebook') # Create tabs # Tab for AI that generates AI tab_summarize = ttk.Frame(tab_control) # Tab for Wikipedia Search tab_wikipedia_search = ttk.Frame(tab_control) # Tab for verbal presentation tab_verbal_presentation = ttk.Frame(tab_control) # Tab for verbal presentation that can be used offline tab_verbal_presentation_2 = ttk.Frame(tab_control) # Tab for text to PDF file converter tab_pdf_converter = ttk.Frame(tab_control) # tab_chatbot = ttk.Frame(tab_control) # Add tabs to window # Name for this tab is AI Summarizer tab_control.add(tab_summarize, text='AI Summarizer') # Name for this tab is AI Wikipedia Searcher tab_control.add(tab_wikipedia_search, text='AI Wikipedia Searcher') # Name for this tab is AI Verbal Presenter tab_control.add(tab_verbal_presentation, text='AI Verbal Presenter') # Name for this tab is AI Verbal Presenter 2 tab_control.add(tab_verbal_presentation_2, text='AI Offline Verbal Presenter') # Name for this tab is AI PDF Converter tab_control.add(tab_pdf_converter, text='AI PDF Converter') # Name for this tab is AI ChatBot tab_control.add(tab_chatbot, text='AI Chatbot') # Create GUI Labels # Place GUI Labels # Label on the text summarizer tab will state AI Summarizer Assistant label_summarize = Label(tab_summarize, text='AI Summarizer Assistant', padx=5, pady=5).grid(column=0, row=0) # Label on the Wikipedia Searcher will state AI Wikpedia Searcher label_wikipedia_search = Label(tab_wikipedia_search, text='AI Wikipedia Searcher', padx=5, pady=5).grid(column=0, row=0) # Label on the AI Verbal Presenter will state AI Verbal Text-To-Speech Assistant label_verbal_presentation = Label(tab_verbal_presentation, text='AI Verbal Text-To-Speech Assistant', padx=5, pady=5)\ .grid(column=0, row=0) # Label on the Offline AI Verbal Presenter will state AI Verbal Text-To-Speech Assistant Offline Mode label_verbal_presentation_2 = Label(tab_verbal_presentation_2, text='AI Verbal Text-To-Speech Assistant Offline Mode', padx=5, pady=5).grid(column=0, row=0) # Label on text to PDF file converter will state AI Convert Text to PDF label_pdf_converter = Label(tab_pdf_converter, text='AI Convert Text to PDF', padx=5, pady=5)\ .grid(column=0, row=0) # Label on text to PDF file converter will state AI Chatbot Named Peanut label_chatbot = Label(tab_chatbot, text='AI Chatbot Named Peanut', padx=5, pady=5).grid(column=0, row=0) # 0,0 is top left of window # Pack to make visible tab_control.pack(expand=1, fill='both') # Functions # Function to summarize text def text_summary(): # Imports for parser_config # Using sumy library for text summarization # Text parsing used to split up the sequence of text from sumy.parsers.plaintext import PlaintextParser # Importing sumy tokenizer library # Tokenization is used for splitting up large bodies of text into smaller ones from sumy.nlp.tokenizers import Tokenizer # Collect user input from the entry box text_format = summary_entry.get('1.0', tk.END) # We can use this parse format for all three when we use raw strings # Parsing all text using Lexrank, Luhn, and LSA # Lexrank = Based of the idea that sentences recommend other similar sentences # Luhn = Based on frequency of important words # LSA = Based on term frequency techniques # Tokenize the words in English parser_config = PlaintextParser.from_string(text_format, Tokenizer("english")) # variable correlating to the SummarizeText.py / SummarizeText class summarize_text = SummarizeText() # Summarize all text using Lexrank # Lexrank = Based of the idea that sentences recommend other similar sentences # summer_all = print(), summer_all summer_all = summarize_text.lex_rank_analysis(parser_config, 2) # summarize all text using LSA # LSA = Based on term frequency techniques # summer_all = print(), summer_all summer_all = summer_all + summarize_text.lsa_analysis(parser_config, 2) # An Array to collect the summarized text text_summary_list = [] # for each sentence that has gone through parsing display them and split them up using {} for sentence in summer_all: # String concatenation for each sentence concat = str(sentence) + "\n\n\n" # Split up all sentences using {} concat.replace("", "{") concat.replace("", "}") # Add the item (sentence) to the list text_summary_list.append(concat) # Display the summarized text summary_output_display.insert(tk.END, text_summary_list) # For Debug console # Print out the results through console print("\nAbout to print summer all results\n") print(summer_all) # Function to delete user input in the summary entry box def summary_erase_input(): # Delete all user input placed in the entry box summary_entry.delete(1.0, END) # Function to delete what the program outputs def summary_erase_output(): # Delete all text placed in the output display box summary_output_display.delete(1.0, END) # Function to generate a Wikipedia summary def wikipedia_summary(): # A variable that correlates to what the user inputs in the wikipedia_entry box search_phrase = wikipedia_entry.get() # A variable that correlates to what the user inputs in the Wikipedia_amount_of_sentences entry box number_of_sentences = wikipedia_amount_of_sentences.get() # A variable that correlates to the Wikipedia algorithm that generates the Wikipedia summary wikipedia_output = wikipedia.summary(search_phrase, sentences=number_of_sentences) # Display the Wikipedia summary in the wikipedia_output_display box wikipedia_output_display.insert(tk.END, wikipedia_output + '\n==================================================' '==============================') # Function to generate a Wikipedia article def wikipedia_article(): # A variable that correlates to what the user inputs in the wikipedia_entry box search_phrase = wikipedia_entry.get() # A variable that correlates to the Wikipedia algorithm that generates the Wikipedia article wikipedia_output = wikipedia.page(search_phrase).content # Display the Wikipedia summary in the wikipedia_output_display box wikipedia_output_display.insert(tk.END, wikipedia_output + '\n====================================================' '============================') # Function that deletes user input in th Wikipedia Searcher tab def wikipedia_erase_input(): # Delete any input in the wikipedia topic search box wikipedia_entry.delete(0, 'end') # Delete any input in the amount of sentences box wikipedia_amount_of_sentences.delete(0, 'end') # Function that deletes what the program outputs def wikipedia_erase_output(): # Delete all text placed in the output display box wikipedia_output_display.delete(1.0, END) # Function that collects user input and convert it into an audio file def text_to_speech_user_input(): # English language language = 'en' # Collect user input user_text_to_speech = verbal_entry.get('1.0', END) # Convert user input into audio file text_to_speech_output = gTTS(text=user_text_to_speech, lang=language, slow=False) # Save the audio file text_to_speech_output.save("audioOverwrite.mp3") # Play the converted file os.system("start audioOverwrite.mp3") # Collect user input to convert it into the output display user_text_to_speech_output = user_text_to_speech # Display user input into the output display box # Output display box will also have a divider verbal_output_display.insert(tk.END, user_text_to_speech_output + '===============================================' '=================================') # Function that collects text from text file and convert it into an audio file def text_to_speech_file(): # English language language = 'en' # Open the text file (TextSpeech.txt) text_file = open("TextSpeech.txt", "r").read().replace("\n", " ") # Convert the text in the text file into audio speech_file = gTTS(text=text_file, lang=language, slow=False) # Save the audio file speech_file.save("audioOverwrite.mp3") # Play the converted file os.system("start audioOverwrite.mp3") # Display the text from the text file into the output display box # Output display box will also have a divider verbal_output_display.insert(tk.END, text_file + '\n============================================================' '====================') # Function to delete user input in the verbal entry box def verbal_erase_input(): # Delete all text placed in the entry box verbal_entry.delete(1.0, END) # Function to delete what the program outputs def verbal_erase_output(): # Delete all text placed in the output display box verbal_output_display.delete(1.0, END) # Function that collects user input and converts it into speech def text_to_speech_user_input_2(): # Creating the engine pyttsx3 object engine = pyttsx3.init() # Setting the rate of thr speech to 155 engine.setProperty('rate', 155) # Setting the volume to 1.0 = MAX engine.setProperty('volume', 1.0) # Collect user input user_text_to_speech_2 = verbal_entry_2.get('1.0', END) # Variable that correlates to user input user_text_to_speech_output_2 = user_text_to_speech_2 # Display the user input into the output display box # Output display will also have a divider verbal_output_display_2.insert(tk.END, user_text_to_speech_output_2 + '===========================================' '=====================================') # Converting the text to speech engine.say(user_text_to_speech_2) # Run and block all queued commands engine.runAndWait() # Function to delete all user input def verbal_erase_input_2(): # Delete all text placed in the entry box verbal_entry_2.delete(1.0, END) # Function to delete the text in the output display box def verbal_erase_output_2(): # Delete all text in the output display box verbal_output_display_2.delete(1.0, END) # Function to delete input for PDF paper title def pdf_erase_input_settings(): # Delete all text in the pdf title entry box pdf_title_entry.delete(0, 'end') # Function to delete all text in the scrolled bar user text input def pdf_erase_text_input(): # Delete all text in the pdf user text entry pdf_text_entry.delete(1.0, END) # Function to generate a pdf file from user text def pdf_text_to_pdf_file(): # Variable for PDF pdf = FPDF() # Adding a PDF file page pdf.add_page() # Variable that correlate to collecting user input for PDF title pdf_title = pdf_title_entry.get() # Variable that correlates to collecting user text input pdf_body_text = pdf_text_entry.get('1.0', END) # Font for the PDF text will be Times in size 12 pdf.set_font("Times", size=12) # PDF header text pdf.cell(200, 10, txt=pdf_title, ln=1, align='C') # PDf body text pdf.multi_cell(200, 10, txt=pdf_body_text, align='L') # save the pdf with name .pdf pdf.output("AI-Assistant.pdf") # Function to erase output in ScrolledText (Text history log) def chatbot_erase_output(): # delete any text in the chatbot output display box chatbot_output_display.delete(1.0, END) # Function for Chatbot to process text def chatbot_text_process(): # chatbot_text_entry.delete(0, 'end') bot = ChatBot( 'Peanut', storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ { # Best choice logic adapter 'import_path': 'chatterbot.logic.BestMatch', # If the user inputs a something the chatbot does not understand state this below 'default_response': 'I am sorry, but I do not understand.', 'maximum_similarity_threshold': 0.90 }, # Logic adapter to solve math questions 'chatterbot.logic.MathematicalEvaluation', # Logic adapter to tell time 'chatterbot.logic.TimeLogicAdapter', # Logic adapter to solve unit conversion questions 'chatterbot.logic.UnitConversion', ], # Provide a database uri with sqlite database_uri='sqlite:///database.sqlite3' ) # Training the chatbot in introducing itself to user conversation_intro = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." ] # Training the chatbot in providing a link to a chatbot guide website conversation_create_chatbot_help = [ 'I want to create a chat bot', 'Have you read the documentation?', 'No, I have not', 'I recommend this chatbot guide website: http://chatterbot.rtfd.org/en/latest/quickstart.html' ] # Training the chatbot in providing a link to a quiz help website conversation_quiz_help = [ 'I want help with quizzes', 'I recommend this quiz website: https://quizlet.com/' ] # Training the chatbot in providing a link to a grammar assistant website conversation_grammar_help = [ 'I want help with grammar', 'I recommend this grammar website: https://www.grammarly.com/' ] # Training the chatbot in providing a link to a studying assistant website conversation_studying_help = [ 'I want help with studying', 'I recommend this studying website: https://www.wolframalpha.com/' ] # Training the chatbot in providing a link to a college/university website conversation_college_help = [ 'I want help with college/university', 'I recommend this college help website: https://www.koofers.com/' ] # Training the chatbot in providing a website to a website that helps form good habits conversation_habits_help = [ 'I want help with forming good habits', 'I recommend this website to get into good habits: https://habitica.com/static/home' ] # Training the chatbot in providing a website that help's in citation conversation_citation_help = [ 'I want help with citation', 'I recommend this citation website: https://www.citefast.com/?s=APA7#_Webpage' ] # Training the chatbot in providing a website in helping find jobs conversation_work_help = [ 'I want help with finding a job', 'I recommend this website to find work: https://www.indeed.com/' ] # Training the chatbot in providing a website in helping find digital storage conversation_storage_help = [ 'I want help with storage', 'I recommend this digital storage website: https://www.google.com/drive/' ] # Training the chatbot in telling programming jokes conversation_programmer_joke = [ 'Tell me a programmer joke', pyjokes.get_joke(), # Tell a programmer joke 'Tell me another joke', pyjokes.get_joke(), # Tell a different programmer joke 'Tell me one more joke', pyjokes.get_joke(), # Tell a different programmer joke 'One more joke', pyjokes.get_joke(), # Tell a different programmer joke 'Okay one last joke', pyjokes.get_joke(), # Tell a different programmer joke ] # Establish training modules for the chatbot trainer = ListTrainer(bot) # Establish the training module for conversation_intro conversation sequence trainer.train(conversation_intro) # Establish the training module for conversation_create_chatbot_help conversation sequence trainer.train(conversation_create_chatbot_help) # Establish the training module for conversation_quiz_help conversation sequence trainer.train(conversation_quiz_help) # Establish the training module for conversation_grammar_help conversation sequence trainer.train(conversation_grammar_help) # Establish the training module for conversation_studying_help conversation sequence trainer.train(conversation_studying_help) # Establish the training module for conversation_college_help conversation sequence trainer.train(conversation_college_help) # Establish the training module for conversation_habits_help conversation sequence trainer.train(conversation_habits_help) # Establish the training module for conversation_citation_help conversation sequence trainer.train(conversation_citation_help) # Establish the training module for conversation_work_help conversation sequence trainer.train(conversation_work_help) # Establish the training module for conversation_storage_help conversation sequence trainer.train(conversation_storage_help) # Establish the training module for conversation_programmer_joke conversation sequence trainer.train(conversation_programmer_joke) # The following loop will execute each time the user enters input while True: # Collect user input from entry box user_input = chatbot_text_entry.get() # delete text when text is sent chatbot_text_entry.delete(0, 'end') # Chatbot will not process the text response = bot.get_response(user_input) # Display the chatbot's response through ths format chatbot_output_display.insert( tk.END, "Human: " + user_input + "\n" + "Peanut: " + str(response.text) + "\n" ) # Main Home Tab # AI Text Summary Tab # Create label to instruct the user on how to use the AI summarizer program Label(tab_summarize, text='Enter any text you want in the box below to be summarized...', padx=5, pady=5)\ .grid(row=1, column=0) # Create a label to instruct the user on how to use the AI Wikipedia search program Label(tab_wikipedia_search, text='1) Enter any word or phrase in the designated box.\n2) Type the amount of sentences' 'you want in the wiki summary (OPTIONAL).\n 3) Click Generate Wikipedia Summary to ' 'generate a' 'Wikipedia summary which length will depend on your amount of sentences.\n4) Click' 'Generate Wikipedia Article to generate the entire Wikpedia article on your topic.', padx=5, pady=5).grid(row=1, column=0) # Create a label to instruct the user to input the word or phrase they want AI to search in Wikipedia Label(tab_wikipedia_search, text="Enter the word or phrase here (TOPIC):").grid(row=2) # Create a label to instruct the user to input the amount of sentences they in their Wikipedia summary Label(tab_wikipedia_search, text='Enter the amount of sentences you want in the Wikipedia summary here (OPTIONAL):')\ .grid(row=3) # Create a label to instruct the user to input the text they want converted into audio Label(tab_verbal_presentation, text='Enter any text you want in the box below to be converted to text-to-speech...', padx=5, pady=5).grid(row=1, column=0) # Create a label that says OR Label(tab_verbal_presentation, text='OR', padx=5, pady=5).grid(row=2, column=0) # Create a label that instructs the user they can edit the text file in the project they want converted into audio Label(tab_verbal_presentation, text='You can also edit the text file.', padx=5, pady=5).grid(row=3, column=0) # Create a label that will inform the user to use this AI verbal presenter if they don't internet Label(tab_verbal_presentation_2, text='Use this AI verbal presenter if you do not have an internet connection.', padx=5, pady=5).grid(row=1, column=0) # Create a label that will instruct the user on how to operate the offline AI verbal presenter Label(tab_verbal_presentation_2, text='Enter any text you want in the box below to be converted to text-to-speech...', padx=5, pady=5).grid(row=2, column=0) # Create a label that will inform the user to use the AI PDF converter to convert their text into a PDf file Label(tab_pdf_converter, text='Use this AI PDF Converter to convert your text into a PDF file.', padx=5, pady=5).grid( row=1, column=0) # Create a label that will instruct the user on how to use the AI PDF Converter Label(tab_pdf_converter, text='1) Enter the title for your PDF paper.' '\n2) Enter the text you want to implement into the PDF file.\n3) Check the PDF file in ' 'the project folder located in the file explorer.', padx=5, pady=5).grid(row=2, column=0) # Create a label that informs the user to enter a title for their PDF paper Label(tab_pdf_converter, text='Enter the title of the PDF file:', padx=5, pady=5).grid(row=4, column=0) # Create a label to instruct the user to put text in the scrolled text box below Label(tab_pdf_converter, text='Enter the body text you want in the PDF file...', padx=5, pady=5).grid(row=8, column=0) # Create a label that informs to use this AI to interact with the chatbot named Peanut Label(tab_chatbot, text='Use this AI to interact with the chatbot named Peanut.', padx=5, pady=5).grid(row=1, column=0) # Create a label that informs the user to enter the text they want to send to peanut Label(tab_chatbot, text='Enter the text you want to send to peanut:', padx=5, pady=5).grid(row=2, column=0) # Establish that the user entry box be scrolled text giving it scroll bar summary_entry = ScrolledText(tab_summarize, height=10, wrap=WORD) # Create a grid for user entry box summary_entry.grid(row=2, column=0, columnspan=2, padx=5, pady=5) # Entry box for user to input their Wikipedia subject wikipedia_entry = Entry(tab_wikipedia_search) # Entry box for user to input the amount of sentences they want in their Wikipedia summary wikipedia_amount_of_sentences = Entry(tab_wikipedia_search) # Create a grid for the wikipedia_entry box wikipedia_entry.grid(row=2, column=1) # Create a grid for the wikipedia_amount_of_sentences entry box wikipedia_amount_of_sentences.grid(row=3, column=1) # Create a entry box with a scrolled text property verbal_entry = ScrolledText(tab_verbal_presentation, height=10, wrap=WORD) # Create a grid for the verbal_entry box verbal_entry.grid(row=4, column=0, columnspan=2, padx=5, pady=5) # Create a entry box with a scrolled text property for the offline AI verbal presenter verbal_entry_2 = ScrolledText(tab_verbal_presentation_2, height=10, wrap=WORD) # Create a grid for verbal_entry_2 box verbal_entry_2.grid(row=3, column=0, columnspan=2, padx=5, pady=5) # Create a entry box for the user to input their title for the PDF paper pdf_title_entry = Entry(tab_pdf_converter) # Create a grid for the pdf_title_entry pdf_title_entry.grid(row=4, column=1) # Create a entry box with a scrolled text property for user to input text to convert to the PDF file pdf_text_entry = ScrolledText(tab_pdf_converter, height=10, wrap=WORD) # Create a grid fpr pdf_text_entry pdf_text_entry.grid(row=9, column=0, columnspan=2, padx=5, pady=5) # Create an entry box for user input chatbot_text_entry = Entry(tab_chatbot) # Create a grid for chatbot_text_entry chatbot_text_entry.grid(row=2, column=1) # Buttons # Buttons for AI Text Summary # Button to erase all text from the entry box # Button with text saying Clear Input to instruct user # Button correlates to the erase_input function # Button is blue with white text button_text_summary_input = Button(tab_summarize, text='Clear Input', command=summary_erase_input, width=30, bg='blue', fg='#fff') # Create a grid for the Clear Input button button_text_summary_input.grid(row=3, column=0, padx=10, pady=10) # Button to process user input # Button with text saying Generate Summary to instruct user # Button correlates to text_summary function # Button is red with white text button_text_summary_process = Button(tab_summarize, text="Generate Summary", command=text_summary, width=30, bg='red', fg='#fff') # Create a grid for the Generate Summary button button_text_summary_process.grid(row=4, column=0, padx=10, pady=10) # Button to erase all text in the display box # Button with text saying Clear Output to instruct user # Button correlates to the erase_output function # Button is blue with white text button_text_summary_output = Button(tab_summarize, text='Clear Output', command=summary_erase_output, width=30, bg='blue', fg='#fff') # Create a grid for the Clear Output button button_text_summary_output.grid(row=5, column=0, padx=10, pady=10) # Button to clear all user input in the entry boxes # Button with text saying Clear Output to instruct user # Button correlates to wikipedia_erase_input function # Button is green with white text button_wikipedia_search_input = Button(tab_wikipedia_search, text='Clear Input', command=wikipedia_erase_input, width=30, bg='green', fg='#fff') # Create a grid for the Clear Input button button_wikipedia_search_input.grid(row=7, column=0, padx=10, pady=10) # Button to clear all program output in the output display box # Button with text saying Clear Output to instruct user # Button correlates to wikipedia_erase_output function # Button is green with white text button_wikipedia_search_output = Button(tab_wikipedia_search, text='Clear Output', command=wikipedia_erase_output, width=30, bg='green', fg='#fff') # Create a grid for the Clear Output button button_wikipedia_search_output.grid(row=8, column=0, padx=10, pady=10) # Button to generate Wikipedia summary # Button with text saying Generate Wikipedia Summary # Button correlates to wikipedia_summary function # Button is green with white text button_wikipedia_summary_process = Button(tab_wikipedia_search, text='Generate Wikipedia Summary', command=wikipedia_summary, width=30, bg='green', fg='#fff') # Create a grid for Generate Wikipedia Summary button button_wikipedia_summary_process.grid(row=9, column=0, padx=10, pady=10) # Button to generate Wikipedia article # Button with text saying Generate Wikipedia Article # Button correlates to wikipedia_article function # Button is green with white text button_wikipedia_article_process = Button(tab_wikipedia_search, text='Generate Wikipedia Article', command=wikipedia_article, width=30, bg='green', fg='#fff') # Create a grid for Generate Wikipedia Article button_wikipedia_article_process.grid(row=10, column=0, padx=10, pady=10) # Button to clear all user input in the entry boxes # Button with text saying Clear Input to instruct user # Button that correlates to verbal_erase_input function # Button is blue with white text button_verbal_erase_input = Button(tab_verbal_presentation, text='Clear Input', command=verbal_erase_input, width=30, bg='blue', fg='#fff') # Create a grid for the Clear Input button button_verbal_erase_input.grid(row=5, column=0, padx=10, pady=10) # Button to clear all program output in the output display box # Button with text saying Clear Output to instruct user # Button that correlates to verbal_erase_output function # Button is blue with white text button_verbal_erase_output = Button(tab_verbal_presentation, text='Clear Output', command=verbal_erase_output, width=30, bg='blue', fg='#fff') # Create a grid for the Clear Output button button_verbal_erase_output.grid(row=8, column=0, padx=10, pady=10) # Button to generate speech audio from user input # Button saying Generate Speech Audio to instruct user # Button correlates with text_to_speech_user_input function # Button is red with white text button_verbal_process = Button(tab_verbal_presentation, text='Generate Speech Audio', command=text_to_speech_user_input, width=30, bg='red', fg='#fff') # Create a grid for the Generate Speech audio from user input button button_verbal_process.grid(row=6, column=0, padx=10, pady=10) # Button to Generate Speech Audio From Text File # Button saying Generate Speech Audio From Text File to instruct user # Button correlates to Generate Speech Audio From Text File function # Button is red with white text button_verbal_text_file_process = Button(tab_verbal_presentation, text='Generate Speech Audio From Text File', command=text_to_speech_file, width=30, bg='red', fg='#fff') # Create a grid for Generate Speech Audio From Text File button_verbal_text_file_process.grid(row=7, column=0, padx=10, pady=10) # Button to clear all user input in the entry boxes # Button with text saying Clear Text Input to instruct user # Button that correlates to verbal_erase_input_2 function # Button is blue with white text button_verbal_erase_input_2 = Button(tab_verbal_presentation_2, text='Clear Text Input', command=verbal_erase_input_2, width=30, bg='blue', fg='#fff') # Create a grid for the Clear Input button button_verbal_erase_input_2.grid(row=4, column=0, padx=10, pady=10) # Button to clear all program output in the output display box # Button with text saying Clear Output to instruct user # Button that correlates to verbal_erase_output_2 function # Button is blue with white text button_verbal_erase_output_2 = Button(tab_verbal_presentation_2, text='Clear Output', command=verbal_erase_output_2, width=30, bg='blue', fg='#fff') # Create a grid for the Clear Output button button_verbal_erase_output_2.grid(row=6, column=0, padx=10, pady=10) # Button to generate speech audio # Button with text saying Generate Speech Audio # Button correlates to text_to_speech_user_input_2 function # Button is red with white text button_verbal_process_2 = Button(tab_verbal_presentation_2, text='Generate Speech Audio', command=text_to_speech_user_input_2, width=30, bg='red', fg='#fff') # Create a grid for generating speech audio button button_verbal_process_2.grid(row=5, column=0, padx=10, pady=10) # Button to clear title input # Button with text saying clear Title Input # Button correlates to pdf_erase_input_settings function # Button is blue with white text button_pdf_erase_input_settings = Button(tab_pdf_converter, text='Clear Title Input', command=pdf_erase_input_settings, width=30, bg='blue', fg='#fff') # Create a grid for clearing title input button button_pdf_erase_input_settings.grid(row=5, column=0, padx=10, pady=10) # Button to Clear text input # Button with text saying Clear Text Input # Button correlates to pdf_erase_text_input function # Button is blue with white text button_pdf_input_text_erase = Button(tab_pdf_converter, text='Clear Text Input', command=pdf_erase_text_input, width=30, bg='blue', fg='#fff') # Create a grid for clearing text input button_pdf_input_text_erase.grid(row=6, column=0, padx=10, pady=10) # Button to Generate PDF File # Button with text saying Generate PDF File # Button correlates to pdf_text_to_pdf_file function # Button is red with white text button_pdf_text_process = Button(tab_pdf_converter, text='Generate PDF File', command=pdf_text_to_pdf_file, width=30, bg='red', fg='#fff') # Create a grid for generating pdf file button button_pdf_text_process.grid(row=7, column=0, padx=10, pady=10) # Button that will execute the chatbot_erase_output function button_chatot_erase_output = Button(tab_chatbot, text='Clear Output', command=chatbot_erase_output, width=30, bg='blue', fg='#fff') # Create a grid for the button_chatot_erase_output button_chatot_erase_output.grid(row=4, column=0, padx=10, pady=10) # Button that will execute the chatbot_text_process function button_chatbot_text_process = Button(tab_chatbot, text='Send Text', command=chatbot_text_process, width=30, bg='red', fg='#fff') # Create a grid for the button_chatbot_text_process button_chatbot_text_process.grid(row=3, column=0, padx=10, pady=10) # Output displaying the results gathered from the AI Text Summary # Create a scroll bar for the output display box # WORD wrap to organize the text to not be cutoff. summary_output_display = ScrolledText(tab_summarize, wrap=WORD) # Create a grid for the output display box summary_output_display.grid(row=8, column=0, columnspan=3, padx=5, pady=5) # Create a scroll bar for the output display box # WORD wrap to organize the text to not be cutoff. wikipedia_output_display = ScrolledText(tab_wikipedia_search, wrap=WORD) # Create a grid for the output display box wikipedia_output_display.grid(row=11, column=0, columnspan=3, padx=5, pady=5) # Create a scroll bar output display box # WORD wrap to organize the text to not be cutoff. verbal_output_display = ScrolledText(tab_verbal_presentation, wrap=WORD) # Create a grid for the output display box verbal_output_display.grid(row=9, column=0, padx=10, pady=10) # Create a scroll bar output display box # WORD wrap to organize the text to not be cutoff. verbal_output_display_2 = ScrolledText(tab_verbal_presentation_2, wrap=WORD) # Create a grid for the output display box verbal_output_display_2.grid(row=7, column=0, padx=10, pady=10) # Create a scroll bar output display box for the chatbot (text log) chatbot_output_display = ScrolledText(tab_chatbot, wrap=WORD) # Create a grid for the chatbot_output_display ScrolledText chatbot_output_display.grid(row=5, column=0, padx=10, pady=10) # Keep window alive window.mainloop()
ba261049c8f36c1e41f989a03c3717d68c22a26e
adityagoenka24/python
/mainproject.py
5,191
3.5625
4
import mysql.connector class Tinder: # This is the constructor def __init__(self): self.conn = mysql.connector.connect(user="root",password="",host="localhost", database="tinder") self.mycursor =self.conn.cursor() self.program_menu() # Welcome Menu for the user def program_menu(self): self.program_input=input("""Hey! Welcome to Tinder, What would you want? 1. Create Account 2. Login 3. Exit """) if self.program_input == "1": self.register() elif self.program_input == "2": self.login() else: print("\nThanks for using Tinder !!\n") def register(self): print("Enter the details: ") name=input("Name: ") email=input("Email: ") password=input("Password: ") gender = input("Gender: ") city = input("City: ") # run the insert query self.mycursor.execute("""insert into `tinder`.`users` (`user_id`,`name`,`email`,`password`,`gender`,`city`) VALUES (NULL,'%s','%s','%s','%s','%s') """ %(name,email,password,gender,city)) self.conn.commit() print("Registration successful !! ") self.program_menu() def login(self): email=input("Enter the email: ") password = input("Password: ") self.mycursor.execute("""select * from `users` where `email` like '%s' and `password` like '%s' """ %(email,password)) user_list = self.mycursor.fetchall() count=0; for i in user_list: count+=1 current_user = i if count == 1: print("You have logged in correctly") print("Hi ! ",current_user[1]) self.current_user_id=current_user[0] self.user_menu() else: print("Incorrect Credentials ! ") self.program_menu() def user_menu(self): self.user_choice=input("""What would you like to do? 1. View All Users 2. View who proposed you 3. View your proposals 4. View matches 5. Logout """) if self.user_choice=="1": self.view_users() elif self.user_choice=="2": self.view_user_proposals() elif self.user_choice=="3": self.view_user_proposed() elif self.user_choice=="4": self.view_user_matches() elif self.user_choice=="5": self.user_logout() else: print("Invalid choice ! Try again ! ") self.user_menu() def view_users(self): print("Following is the user list") self.mycursor.execute(""" select * from `users` """) user_list = self.mycursor.fetchall() print("UserID Name Gender City") for i in user_list: print(i[0]," ",i[1]," ",i[4]," ",i[5]) juliet_id=input("Enter the ID of your juliet: ") self.propose(juliet_id) def propose(self,juliet_id): self.mycursor.execute("""insert into `proposal` (`proposal_id`,`romeo_id`,`juliet_id`) VALUES (NULL,'%s','%s') """ %(self.current_user_id,juliet_id)) self.conn.commit() print("Wow! Proposal sent !") self.user_menu() def view_user_proposals(self): print("Users who proposed you: ") self.mycursor.execute(""" select * from `proposal` p join `users` u on p.`romeo_id`=u.`user_id` where p.`juliet_id` like '%s' """ %(self.current_user_id)) fan_list=self.mycursor.fetchall() print("Here it goes:") for i in fan_list: print(i[3]," ",i[4]," ",i[7]," ",i[8]) match=input("Enter the ID of the one you want to propose back (-1 to go back): ") if match != "-1": self.propose(match) else: self.user_menu() def view_user_proposed(self): print("Users who you proposed: ") self.mycursor.execute(""" select * from `proposal` p join `users` u on p.`juliet_id`=u.`user_id` where p.`romeo_id` like '%s' """ % (self.current_user_id)) fan_list = self.mycursor.fetchall() print("Here it goes:") for i in fan_list: print(i[3], " ", i[4], " ", i[7], " ", i[8]) self.user_menu() def view_user_matches(self): print("Hey ! These are your matches ! ") self.mycursor.execute(""" select * from `proposal` p JOIN `users` u ON p.`juliet_id`=u.`user_id` WHERE `romeo_id` = '%s' and `juliet_id` IN (select `romeo_id` from `proposal` where `juliet_id` like '%s' ) """ %(self.current_user_id,self.current_user_id)) match_list=self.mycursor.fetchall() for i in match_list: print(i[3], " ", i[4], " ", i[7], " ", i[8]) self.user_menu() def user_logout(self): print("You have successfully logged out") self.program_menu() obj1 = Tinder()
a20349f5a07a67fe23bdc4c80bf5533867438060
pathirrus/python_intermediate_training
/sda_exercises_oop_1/dog.py
207
3.53125
4
class Dog: def __init__(self, name: str, sound="hau"): self.name = name self.sound = sound def make_sound(self) -> str: return f'Dog name is {self.name} sound: {self.sound}'
b4d3e19be67069f37487506a473ba9bce4def0be
jeffjbilicki/milestone-5-challenge
/milestone5/m5-bfs.py
631
4.1875
4
#!/usr/bin/env python # Given this graph graph = {'A': ['B', 'C', 'E'], 'B': ['A','D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B','D'], 'F': ['C'], 'G': ['C']} # Write a BFS search that will return the shortest path def bfs_shortest_path(graph, start, goal): explored = [] # keep track of all the paths to be checked queue = [start] # return path if start is goal if start == goal: return "Home sweet home!" # Find the shortest path to the goal return "Cannot reach goal" ans = bfs_shortest_path(graph,'G', 'A') print(ans)
30e7c4a5403f6b3fd5c335ac99ba4bf9af7eda34
vitor-fernandes/EstruturaDeDadosII
/esmeralda.py
424
3.734375
4
dicionario = {} stringConhecida = input("").upper() stringCifrada = input("").upper() msgCifrada = input("").upper() msgDecifrada = "" for c in range(len(stringCifrada)): dicionario.update({stringCifrada[c] : stringConhecida[c]}) for c in range(len(msgCifrada)): if(msgCifrada[c] not in dicionario): msgDecifrada += '.' else: msgDecifrada += dicionario[msgCifrada[c]] print(msgDecifrada)
398315b831fe48d48f84742b1f2d3f75fe0d4ee6
Dhamodhiran/dhamu
/case19.py
62
3.53125
4
k=1 num=int(input()) for i in range(1,num+1): k=k*i print(k)
956a097e8d552b776f171fc4633d0d403761e267
Dhamodhiran/dhamu
/case 14.py
105
3.625
4
b,d=input().split(' ') b=int(b) d=int(d) for num in range(b+1,d+1): if (num%2!=0): print(num,end=' ')
580a215b24366f1e6dcf7d3d5253401667aa1aae
afialydia/Graphs
/projects/ancestor/ancestor.py
2,127
4.125
4
from util import Queue class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex_id): """ Add a vertex to the graph. """ if vertex_id not in self.vertices: self.vertices[vertex_id] = set() def add_edge(self, v1, v2): """ Add a directed edge to the graph. """ if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) else: raise IndexError('Vertex does not exist in graph') def get_neighbors(self, vertex_id): """ Get all neighbors (edges) of a vertex. """ if vertex_id in self.vertices: return self.vertices[vertex_id] else: raise IndexError('ERROR: No such Vertex exist.') def earliest_ancestor(ancestors, starting_node): g = Graph() for pair in ancestors: #< instead of for pair do for parent , child for more readability of code g.add_vertex(pair[0]) g.add_vertex(pair[1]) g.add_edge(pair[1],pair[0]) q = Queue() q.enqueue([starting_node]) # <- enqueue a path to starting node visited = set() #<- creating a set to store visited earliest_ancestor = -1 #<- no parents set to -1 initializing parents while q.size() > 0: path = q.dequeue()#<- gets the first path in the queue v = path[-1]#<- gets last node in the path if v not in visited:#<- check if visited and if not do the following visited.add(v) if((v < earliest_ancestor) or (len(path)>1)): #<-checks if path(v) is less than parent meaning if there was no path it would be the parent or length is longer than 1 earliest_ancestor = v #sets ancestor for neighbor in g.get_neighbors(v): # copy's path and enqueues to all its neighbors copy = path.copy() copy.append(neighbor) q.enqueue(copy) return earliest_ancestor
5e1380e5e0d57d37d9c5d6aa1fc89158e0fcbeff
shocklee/python-code
/wordplay.py
3,290
4.15625
4
def length_greater(word, length): """Returns True if a given word is greater than the specified length.""" return(len(word) > length) def avoids(word, letters): """Returns True if the given word doesn't contain one of the forbidden letters in it.""" for letter in word: if letter in letters: return False return True def has_no_e(word): """Returns True if the given word doesn't contain the letter 'e'""" #return not 'e' in word return avoids(word, 'e') def uses_only(word, letters): """Returns True if the given word contains only the letters in the list.""" for letter in word: if letter not in letters: return False return True def uses_all(word, letters): """Returns True if the given word used all the letters in the list at least once.""" """for letter in letters: if letter not in word: return False return True""" return uses_only(letters, word) def is_abecedarian(word): """Returns True if the letters in the word appear in alphabetical order.""" previousLetter = word[0] for letter in word: if letter < previousLetter: return False previousLetter = letter return True def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def is_palindrome(word): """Returns True if the word is a palindrome.""" if(len(word) <= 1): return True #Not enough letters left, we are done else: # len(word) > 1 #More than one letter left, continue if(first(word) == last(word)): return is_palindrome(middle(word)) else: return False def readFile(filename): fin = open(filename) TOTAL_WORD_COUNT = 0 LENGTH_COUNT = 0 NO_E_COUNT = 0 FORBIDDEN_COUNT = 0 USES_ONLY_COUNT = 0 USES_ALL_COUNT = 0 ABECEDARIAN_COUNT = 0 PALINDROME_COUNT = 0 for line in fin: word = line.strip() TOTAL_WORD_COUNT += 1 if(length_greater(word, 20)): LENGTH_COUNT += 1 #print word if(has_no_e(word)): NO_E_COUNT += 1 #print word if(avoids(word, 'etaon')): FORBIDDEN_COUNT += 1 #print word if(uses_only(word, 'acefhlo')): USES_ONLY_COUNT += 1 #print word if(uses_all(word, 'aeiou')): USES_ALL_COUNT += 1 #print word if(is_abecedarian(word)): ABECEDARIAN_COUNT += 1 #print word if(is_palindrome(word)): PALINDROME_COUNT += 1 #print word fin.close() print 'Total word count: ', TOTAL_WORD_COUNT print 'Words greater than length: ', LENGTH_COUNT print 'Words without e : ', NO_E_COUNT print 'Words without forbidden letters: ', FORBIDDEN_COUNT print 'Words using only specific letters: ', USES_ONLY_COUNT print 'Words using all specific letters: ', USES_ALL_COUNT print 'Words with sequencial letters: ', ABECEDARIAN_COUNT print 'Palindrome count: ', PALINDROME_COUNT readFile(r"C:\Users\shockma\Documents\Special\Python\words.txt")
94172700f1a681c39fb2bf5f9c551725fce2c0d9
shocklee/python-code
/template.py
851
3.515625
4
""" NAME this command does things SYNOPSIS command do-things nice DESCRIPTION things are nice when this command does them AUTHOR Mark Shocklee """ import argparse #This allows you to run: program --help # other stuff parser = argparse.ArgumentParser( description='Path building utility.', epilog="""Default operation is to read a list of directory names from stdin and print a semi-colon delimited path list to stdout. To terminate --add, --append, --prepend or --remove list, use -- as in: {} --remove *foo* *bar* -- input.file """.format(os.path.basename(sys.argv[0]))) parser.add_argument('--add', '--prepend', help='add specified directories to the front of the path', dest='front', type=str, nargs='+', metavar='DIR', action='append') # etc.
4e21512a276938c54dc5a26524338584d3d31673
snangunuri/python-examples
/pyramid.py
1,078
4.25
4
#!/usr/bin/python ############################################################################ #####This program takes a string and prints a pyramid by printing first character one time and second character 2 timesetc.. within the number of spaces of length of the given string### ############################################################################ seq="abcdefghijklmnopqrstuvwxyz" spaces="" letters_str="" for letter in seq: #runs for length of seq for i in range(1, len(seq) - seq.index(letter)): #uses a backwards for loop to add the number of spaces required and decrease the number of spaces by one each time spaces += " " #adds spaces to the list concat_space for j in range(0, seq.index(letter) + 1): #uses a forward for loop to add the right letter and number of letters to the triangle letters_str += letter #adds letters to the list concat_str print spaces + letters_str #joins the spaces and the letters together spaces = "" #resets for a new line of the triangle letters_str="" #resets for a new line of the triangle
2bcd46b28bdca0b9aec6c530ab677a4edaf684e8
Sweety310897/6053_CNF
/m12/CNF_Week_2/ex.py
472
3.53125
4
def main(): temp = load_file("data.csv") print(temp) def load_file(filename): dic = {} list1 = [] with open(filename, 'r') as filename: for line in filename: temp1 = line.split(",") #temp1 = temp.split(",") #print(temp1) dic[temp1[0]] = temp1[1] + temp1[2] #dic[line] = 0 # list1.append(line) # print(list1) return dic if __name__ == "__main__": main()
76c008e9115f338deac839e9e2dafd583377da46
pkongjeen001118/awesome-python
/generator/simple_manual_generator.py
517
4.15625
4
def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n if __name__ == '__main__': a = my_gen() # return generator obj. print(a) print(next(a)) # it will resume their execution and state around the last point of value print(next(a)) # and go to next yield print(next(a)) # and when no more yiled it will do a 'StopIteration' print(next(a))
5cb87538a3b33dd04ec2d3ded59f0524c04519c4
pkongjeen001118/awesome-python
/data-strucutre/dictionaries.py
480
4.375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # simple dictionary mybasket = {'apple':2.99,'orange':1.99,'milk':5.8} print(mybasket['apple']) # dictionary with list inside mynestedbasket = {'apple':2.99,'orange':1.99,'milk':['chocolate','stawbery']} print(mynestedbasket['milk'][1].upper()) # append more key mybasket['pizza'] = 4.5 print(mybasket) # get only keys print(mybasket.keys()) # get only values print(mybasket.values()) # get pair values print(mybasket.items())
ff8bc8c1966b5211da2cba678ef60cad9a4b225d
RossySH/Mision_04
/Triangulos.py
1,020
4.25
4
# Autor: Rosalía Serrano Herrera # Define qué tipo de triángulo corresponde a las medidas que teclea el usuario def definirTriangulo(lado1, lado2, lado3): #determina que tipo de triangulo es dependiendo sus lados if lado1 == lado2 == lado3: return "Equilátero" elif lado1 == lado2 or lado1 == lado3 or lado2 == lado3: return "Isósceles" elif lado1**2 == lado2**2 + lado3**2 or lado2**2 == lado1**2 + lado3**2 or lado3**2 == lado1**2 + lado2**2: return "Rectángulo" else: return "Otro" def main(): lado1 = int(input("Teclea un lado del triángulo: ")) lado2 = int(input("Teclea otro lado del triángulo: ")) lado3 = int(input("Teclea el último lado del triángulo: ")) if lado1 > lado2 + lado3 or lado2 > lado1 + lado3 or lado3 > lado2 + lado1: print("Estos lados no corresponden a un triángulo.") else: triangulo = definirTriangulo(lado1, lado2, lado3) print("El tipo de triángulo es:", triangulo) main()
a3b2da8ae5604ff56d373c204b9e25d081250990
thelyad/FinalProjects
/countingletters.py
678
3.828125
4
''' Created on Nov 18, 2017 @author: ITAUser ''' '''create a function that accepts the filename and character''' def calculate_char(filename, mychar): f = open(filename, 'r') count = 0; isDone = False while not isDone: char=f.read(1) char = char.lower() if char == mychar: count = count +1; if char == '': isDone = True print(count) import string #make a list with the alphabet letters = list(string.ascii_lowercase) #make a list to store the count of each letter #make loop that counts how many of each letter there are #define the maximum value #find the letter at the max value #print the answer
772702e6a5fa8a31ce8468a8fbc8d8102674f811
Shogo-dayo/knapsack_problem
/Memoizing_recursive_BFM.py
1,056
3.75
4
# coding:utf-8 import numpy as np import random import matplotlib.pyplot as plt import knapsack # シード値を設定(再現させるため) random.seed(151) # 商品の数 knapsack.N = 10 # ナップサックの入れられる重さ knapsack.MAX_weight = 10 # WeightandValue[i][0]:i番目商品の重さ # WeightandValue[i][1]:i番目商品の価値 knapsack.WeightandValue = knapsack.make_randdata(knapsack.N) knapsack.w = [] for i in knapsack.WeightandValue : knapsack.w.append(i[0]) # Wの最大値 knapsack.MAX_W = sum(knapsack.w) # メモ化テーブル。 # dp[i][j]はi番目以降の品物から重さの和がj以下なるように選んだときの価値の和の最大値を表す。 # -1なら値が未決定であることを表す knapsack.dp = np.zeros([knapsack.N+1,knapsack.MAX_W+1]) for i in range(knapsack.N+1) : for j in range(knapsack.MAX_W+1) : knapsack.dp[i][j] = -1 print("WeightandValue") print(knapsack.WeightandValue) print(knapsack.rec_dp(0, knapsack.MAX_weight, knapsack.dp, knapsack.WeightandValue))
5d01a0337f1d0fbee5b42b6a7573841271fb419c
JunyoungJang/Python
/Introduction/01_Introduction_python/06 Data type/2 Data type - String/2 Math operations on numbers of string type are not wise.py
119
4
4
# print '7' + 1 # Error print '7' + '1' # string concatenation print type('7') print int('7') + 1 print float('7') + 1
17c2e7f062dfe62d36fce4ad3221f5ae654f23de
JunyoungJang/Python
/Introduction/01_Introduction_python/06 Data type/2 Data type - String/13 String methods.py
1,666
3.984375
4
''' print 'string methods - capitalize, upper, lower, swapcase ---' s = "hello" print s.capitalize() print s.upper() print s.lower() print s.swapcase() ''' ''' ''' #''' #''' ''' print 'string methods - count ---' dna = 'acggtggtcac' print dna.count('g') # 4 ''' ''' ''' #''' #''' ''' print 'string methods - find ---' data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' start_index = data.find('@') print start_index # 21 end_index = data.find(' ',start_index) # find ' ' after start_index print end_index # 31 host = data[start_index+1:end_index] print host # @uct.ac.za ''' ''' ''' #''' #''' #''' print 'string methods - replace ---' dna = 'acggtggtcac' print dna.replace('t', 'x') # original dna does not change - strings are immutable print dna.replace('gt', '') # original dna does not change - strings are immutable print dna # original dna does not change - strings are immutable a = dna.replace('t', 'x') print a # acggxggxcac #''' ''' ''' #''' #''' ''' print 'string methods - split ---' a = 'Life is too short' b = a.split() print a print b ''' ''' ''' #''' #''' ''' print 'string methods - startswith ---' line = 'Life is too short' print line.startswith('Life') # True print line.startswith('l') # False ''' ''' ''' #''' #''' ''' print 'string methods - strip, lstrip,rstrip - strip white space ---' sp = ' hi ' print sp.lstrip(), '.' # strip left empty spaces print sp.rstrip(), '.' # strip right empty spaces print sp.strip(), '.' # strip empty spaces ''' ''' ''' #''' #''' ''' print 'string methods - can be called together ---' dna = 'acggtggtcac' print dna.replace('gt', '').find('gc') '''
dde1d86c4dd20e3ff2cbbfd7f5520d77d42b8f82
JunyoungJang/Python
/Introduction/01_Introduction_python/06 Data type/3 Data type - Boolean/3 Boolean works componentwise.py
363
3.5625
4
import numpy as np print np.array([3, 7]) < 5 # [ True False ] print np.array([3, 7]) != 5 # [ True True ] print np.array([3, 7]) == 5 # [ False False ] print np.array([3, 7]) >= 5 # [ False True ] # print 1 < np.array([3, 7]) < 5 # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
de32c9794eebe19116b22ac96b926b198ea6285e
JunyoungJang/Python
/Introduction/01_Introduction_python/09 How to create and use class, module, library, package/1 How to create and use class.py
10,209
4.53125
5
# -*- coding: utf8 -*- # http://cs231n.github.io/python-numpy-tutorial/#python-basic # # Classes # The syntax for defining classes in Python is straightforward: #''' print 'Construction of class using construct, instance, and destructor ---' class Greeter(object): # Constructor def __init__(self, name): self.name = name # Create an instance variable self._city = 'Seoul' # Instance method def greet(self, loud=False): if loud: print 'HELLO, %s!' % self.name.upper() else: print 'Hello, %s' % self.name # Destructor def __del__(self): print "Objects generated using class Greeter destructed!" g = Greeter('Fred') # Construct an instance of the Greeter class g.name = 'Paul' g.greet() # Call an instance method; prints "Hello, Fred" g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!" print g._city del g #''' ''' ''' #''' #''' ''' print 'class HousePark ---' class HousePark: last_name = "박" def __init__(self, first_name): self.full_name = self.last_name + first_name def __del__(self): print "Objects generated using class HousePark destructed!" def __add__(self, other): print "%s, %s 결혼했네" % (self.full_name, other.full_name) def __sub__(self, other): print "%s, %s 이혼했네" % (self.full_name, other.full_name) def fight(self, other): print "%s, %s 싸우네" % (self.full_name, other.full_name) def love(self, other): print "%s, %s 사랑에 빠졌네" % (self.full_name, other.full_name) def travel(self, where): print "%s, %s여행을 가다." % (self.full_name, where) a = HousePark('응용') a.travel('부산') # 박응용, 부산여행을 가다. del a # Objects generated using class HousePark destructed! print 'class HouseKim inherited from class HousePark with overriding ---' class HouseKim(HousePark): # inheritance last_name = '김' # overriding def __del__(self): # overriding print "Objects generated using class HouseKim destructed!" # overriding def travel(self, where, day): # overriding print "%s, %s여행 %d일 가네." % (self.full_name, where, day) # overriding pey = HousePark("응용") juliet = HouseKim("줄리엣") pey.travel("부산") # 박응용, 부산여행을 가다. juliet.travel("부산", 3) # 김줄리엣, 부산여행 3일 가네. pey.love(juliet) # 박응용, 김줄리엣 사랑에 빠졌네 pey + juliet # 박응용, 김줄리엣 결혼했네 pey.fight(juliet) # 박응용, 김줄리엣 싸우네 pey - juliet # 박응용, 김줄리엣 이혼했네 # Objects generated using class HousePark destructed! # Objects generated using class HouseKim destructed! ''' ''' ''' #''' #''' ''' # NumPy is a numerical library in Python # - Provides matrices and tools to manipulate them # - Plus a large library of linear algebra operations # What criteria can we use to recommend papers? # 1. The way the paper was rated by other people # 2. The similarity between those raters and the previous ratings for an individual # Plan # 1. Process people's ratings of various papers and store in NumPy array # 2. Introduce two similarity measures # 3. Generate recommendations # Input is triples : person, paper, score # This is (very) sparse data, so store it in a dictionary # Turn this dictionary into a dense array # Example class Recommendations: def __init__(self, EPS): self.EPS = EPS # np.finfo.eps def prep_data(all_scores): # Names of all people in alphabetical order people = all_scores.key() people.sort() # Names of all papers in alphabetical order papers = set() for person in people: for title in all_scores[person].keys(): papers.add(title) papers = list(papers) papers.sort() # Create and fill array ratings = np.zeros((len(people), len(papers))) for (person_id, person) in enumerate(people): for (title_id, title) in enumerate(papers): r = all_scores[person].get(title, 0) ratings[person_id, title_id] = float(r) return people, papers, ratings # Next step is to compare sets of ratings # Many ways to do this # We will consider: # - Inverse sums of squares # - Pearson correlation coefficient # Remember : 0 in matrix means "no rating" # Doesn't make sense to compare ratings unless both people have read the paper # Limit our metrics by masking the array def sim_distance(self, prefs, left_index, right_index): # Where do both people have preferences? left_has_prefs = prefs[left_index, :] > 0 right_has_prefs = prefs[right_index, :] > 0 mask = np.logical_and(left_has_prefs, right_has_prefs) # Not enough signal if np.sum(mask) < self.EPS: return 0 # Return sum-of-squares distance diff = prefs[left_index, mask] - prefs[right_index, mask] sum_of_square = np.linalg.norm(diff) ** 2 return 1/(1 + sum_of_square) # What if two people rate many of the same papers but one always rates them lower than the other? # If they rank papers the same, but use a different scale, we want to report # that they rate papers the same way # Pearson's Correlation reports the correlation between two individuals rather # than the absolute difference. # Pearson's Correlation Score measures the error of a best fit line between two individuals. # To calculate Pearson's Correlation, we need to introduce two quantities: # The standard deviation is the divergence from the mean: # StDev(X) = E(X^2)-E(X)^2 # The covariance measures how two variables change together # Cov(X,Y) = E(XY)-E(X)E(Y) # Pearson's Correlation is: # r=Cov(X,Y)/(StDev(X) * StDev(Y)) # Use NumPy to calculate both terms # If a and b are N*1 arrays, then np.cov(a,b) returns an array of results # Variance(a) Covariance(a,b) # Covariance(a,b) Variance(a) # Use it to calculate numerator and denominator def sim_pearson(self, prefs, left_index, right_index): # Where do both have ratings? rating_left = prefs[left_index, :] rating_right = prefs[right_index, :] mask = np.logical_and(rating_left > 0, rating_right > 0) # Summing over Booleans gives number of Trues num_common = np.sum(mask) # Return zero if there are no common ratings if num_common == 0: return 0 # Caculate Pearson score "r" varcovar = np.cov(rating_left[mask], rating_right[mask]) numerator = varcovar[0, 1] denominator = np.sqrt(varcovar[0, 0] * np.sqrt(varcovar[1, 1])) if denominator < self.EPS: return 0 r = numerator / denominator return r # Now that we have the scores we can: # 1. Find people who rate papers most similarly # 2. Find papers that are rated most similarly # 3. Recommend papers for individuals based on the rankings of other people # and their similarity with this person's previous rankings # To find individuals with the most similar ratings, # apply a similarity algorithm to compare each person to every other person # Sort the results to list most similar people first def top_matches(self, ratings, person, num, similarity): scores = [] for other in range(ratings.shape[0]): if other != person: s = similarity(ratings, person, other) scores.append((s, other)) scores.sort() scores.reverse() # highest score should be the first return scores[0:num] # Use the same idea to compute papers that are most similar # Since both similarity functions compare rows of the data matrix, # we must transpose it # And change names to refer to papers, not people def similar_items(self, paper_ids, ratings, num = 10): result = {} ratings_by_paper = ratings.T for item in range(ratings_by_paper.shape[0]): temp = self.top_matches(ratings_by_paper, item, num, self.sim_distance) scores = [] for (scores, name) in temp: scores.append((scores, paper_ids[name])) result[paper_ids[item]] = scores return result # Finally suggest papers based on their rating by people # who rated other papers similarly # Recommendation score is the weighted average of paper scores, # with weights assigned based on the similarity between individuals # Only recommend papers that have not been rated yet def recommendations(self, prefs, person_id, similarity): totals, sim_sums = {}, {} num_people, num_papers = prefs.shape for other_id in range(num_people): # Don't compare people to themselves. if other_id == person_id: continue sim = similarity(prefs, person_id, other_id) if sim < self.EPS: continue for other_id in range(num_people): for title in range(num_papers): # Only score papers person hasn't seen yet if prefs[person_id, title] < self.EPS and \ prefs[other_id, title] > 0: if title in totals: totals[title] += sim * \ prefs[other_id, title] else: totals[title] = 0 # Create the normalized list rankings = [] for title, total in totals.items(): rankings.append((total/sim_sums[title], title)) # Return the sorted list rankings.sort() rankings.reverse() # highly recommended paper should be the first return rankings # Major points: # 1. Mathematical operations on matrix were all handled by NumPy # 2. We still had to take care of data (re)formatting '''
1f291ba8c19a6b242754f14b58e0d229385efe8b
JunyoungJang/Python
/Introduction/01_Introduction_python/10 Python functions/len.py
663
4.1875
4
import numpy as np # If x is a string, len(x) counts characters in x including the space multiple times. fruit = 'banana' fruit_1 = 'I eat bananas' fruit_2 = ' I eat bananas ' print len(fruit) # 6 print len(fruit_1) # 13 print len(fruit_2) # 23 # If x is a (column or row) vector, len(x) reports the length of vector x. a = np.array([[1], [2], [3]]) b = np.array([1, 2, 3]) print len(a) print len(b) # If x is a matrix, len(x) reports the number of rows in matrix x. c = np.array([[1, 2, 3], [1, 2, 3]]) d = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) e = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]) print len(a) print len(b) print len(c)
b800cdcea930d9bb379e96bbeaf15efbaa62a915
JunyoungJang/Python
/Introduction/01_Introduction_python/10 Python functions/type.py
346
3.5
4
print type(3) # <type 'int'> print type(3.7) # <type 'float'> print type(3.7 + 2.5j) # <type 'complex'> print type([1, 2, 3]) # <type 'list'> print type((1, 2, 3)) # <type 'tuple'> print type(set([1, 2, 3])) # <type 'set'> print type("Hello world") # <type 'str'> print type(True) # <type 'bool'>
77195fcb06462de23e1cdb0cc815168bb8716eab
JunyoungJang/Python
/Introduction/02_Introduction_numpy/10 Numpy functions/random.randn.py
303
3.53125
4
import numpy as np import matplotlib.pyplot as plt # https://plot.ly/matplotlib/histograms/ gaussian_numbers = np.random.randn(1000) plt.hist(gaussian_numbers) plt.title("Gaussian Histogram") plt.xlabel("Value") plt.ylabel("Frequency") plt.show() # You must call plt.show() to make graphics appear.
3bafeb7b73587a98544f81b9c65c5eab48fb8d55
JunyoungJang/Python
/Introduction/02_Introduction_numpy/4 np.array indexing/1 Slicing.py
90
3.5625
4
import numpy as np a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print a[:2, 1:3]
da611ba0eadb1a00665e94d58e04bd24e3d22a5b
JunyoungJang/Python
/Introduction/01_Introduction_python/05 Functions/13 If the function doesn't return a value, Python returns None.py
152
3.75
4
def sign(num): if num > 0: return 1 elif num == 0: return 0 # else: # return -1 print sign(-9) # It retruns None
985178a8589d59e251bbbf81267eb43b96997eca
JunyoungJang/Python
/Introduction/01_Introduction_python/06 Data type/1 Data type - Number/1 Data type - Number.py
221
3.6875
4
# integer x = 3 print type(x) print x, x + 1, x - 1, x * 2, x ** 2 # float x = 3.7 print type(x) print x, x + 1, x - 1, x * 2, x ** 2 # complex number x = 3.7 + 2.5j print type(x) print x, x + 1, x - 1, x * 2, x ** 2
ba226c8ed3345758bc1dd093823a1c4f912ddb05
LouisFettet/Sorting_Algorithms
/HeapSort.py
2,015
3.890625
4
# Fettet, Louis # Heap Sort Algorithm Implementation # 12/16/12 from random import randint class HeapArray(): def __init__(self): self.data = [] self.data.append(None) def parent(self, item): if item == (0 or 1): return None return item//2 def leftChild(self, item): if item == 0: return None return item*2 def rightChild(self, item): if item == 0: return None return item * 2 + 1 def siftUp(self): i = len(self.data) - 1 while i >= 1: p = self.parent(i) if p == None: break if self.data[p] > self.data[i]: self.data[p], self.data[i] = self.data[i], self.data[p] i = p else: break def siftDown(self): i = 1 n = len(self.data) - 1 while 2 * i <= n: c = self.leftChild(i) if c + 1 <= n: if self.data[c + 1] < self.data[c]: c = c + 1 if self.data[i] > self.data[c]: self.data[i], self.data[c] = self.data[c], self.data[i] i = c else: i += 1 def insert(self, l): self.data.append(l) self.siftUp() def extract(self): l = self.data[1] self.data[1]=self.data[len(self.data) - 1] self.data.pop(1) self.siftDown() return l def heapSort(a, n): h = HeapArray() b = [] for i in range(0, n): h.insert(a[i]) print (h.data) for i in range(0,n): b.append(h.extract()) print (h.data) return b def genUnsortedList(size): l = [] for i in range(size): l.append(randint(0, 100000)) return l def heapTest(): l = genUnsortedList(50) print("Our unsorted list contains the following values:") print(l) h = heapSort(l, len(l)) print(h)
e0825a3da6e68014f7288c3567b07d01f6d260ca
mannickutd/project_euler
/src/solutions/solution_12.py
1,028
3.734375
4
# -*- coding: utf-8 -*- """ Solution to question 12 Nicholas Staples 2014-04-15 """ from utils.include_decorator import include_decorator def gen_tri_num(): prev = 1 cur = 3 yield prev yield cur while True: nxt = (cur - prev) + 1 + cur yield nxt prev = cur cur = nxt # Common function to determine the number factors for any given number def factors(n): return set( reduce( list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) @include_decorator(12) def problem_12_solution(): # Triangle numbers have a pattern in them # so if you know the prev two numbers you can work out the next number # 6, 10 -> (the difference between 6 and 10 is 4 so the next number will 10 + 5) 15 # There is an increasing difference in the numbers, we can write a generator # to produce the next triangle number gen = gen_tri_num() n = next(gen) while len(factors(n)) < 500: n = next(gen) print n
d49c6fcdbfcacfd90b07fc74328021fbeb60da0f
LornartheBreton/CovidTrackingApp
/python_code/main.py
1,384
3.5625
4
import pandas as pd from datetime import datetime import matplotlib.pyplot as plt #import os import json #The code below was used to test the formula locally """ today=datetime.today().strftime('%Y-%m-%d')#Get today's date location = input("Location: ") # Location to be monitored people_day=1#People you meet in a day """ limit_a = (0.88,15) #(Percentile of people no longer infectious,days since symptoms) limit_b = (0.95,20) given_period=1#Number of days on the time period (1 is one day, 30 is 30 days) #Creating and filtering Dataframes df=pd.read_csv("mexican_projections.csv") df=df.dropna() #Calculation of the contagion vectors column most_recent=df.est_infections_mean.rolling(limit_a[1]-1).sum() contagion_a=((df.est_infections_mean.rolling(limit_b[1]-1).sum()-most_recent) *(1-limit_a[0])) contagion_b=((df.est_infections_mean.rolling(limit_b[1]).sum()-contagion_a) *(1-limit_b[0])) df['contagion_vectors']=most_recent+contagion_a+contagion_b #Uploading the Dataframe to the cloud df.to_json(r'data_with_contagion_vectors.json') #The below code was used to test the formula locally """ #Calcutation of the period's contagion probability df2['contagion_probability']=(df2['contagion_vectors']/df2['population'] *people_day*given_period) ans = df2[df2.date==today]['contagion_probability'].values[0] print(ans) """
5140383e35da66e6580510032738e21154d63cd2
minhminh12/Python-Basic-ACT
/minhduc_day03.py
3,166
3.75
4
print("+--------------MENU-----------------+") print("|Chon C de tao hoa don |") print("|Chon R de xem thong tin hoa don |") print("|Chon T de tinh tong doanh thu |") print("|Chon A de tinh tong hang hoa ban ra|") print("|Chon E de thoat |") print("+-----------------------------------+") while True: danhsachhoahon=[] x=input("=> chon chuc nang:") print("=> ban da chon chuc nang:",x) if x == 'C': tiep=input("tiep tuc?y/n?") while tiep == 'y': print("moi ban tao hoa don") hoadon={} banghoadon={} stt = input("nhap so thu tu:") stt_x=str(stt) for i in range(len(stt_x),7): stt_x= ' '+stt_x tenhanghoa= input("nhap ten hang hoa muon mua :") for i in range(len(tenhanghoa),16): tenhanghoa = tenhanghoa + ' ' so=[] soluong=input("nhap so luong:") soluong_x=str(soluong) for i in range(len(soluong_x),8): soluong_x = ' '+soluong_x so.append(soluong) dongia= input("nhap gia cua san pham:") dongia_x=str(dongia) for i in range(len(dongia_x),13): dongia_x=' '+dongia_x tien=[] thanhtien=int(dongia)*int(soluong) thanhtien_x=str(thanhtien) for i in range(len(thanhtien_x),16): thanhtien_x=' '+thanhtien_x tien.append(thanhtien) hoadon["sohoadon"]=input("nhap so hoa don :") hoadon["ngaysuat"]=input("nhap ngay tao hoa don:") hoadon["tenkhachhang"]=input("nhap ten khach hang:") tiep=input("ban muon tiep tuc ko?y/n?") if x== 'R': print(" HOA DON MUA HANG ") print("so hoa don:",hoadon["sohoadon"]) print("ngay xuat:",hoadon["ngaysuat"]) print("ten khach hang:",hoadon["tenkhachhang"]) print("_____________________________thong tin hoa don_______________________________") print("+----------+------------------+----------+---------------+------------------+") print("| STT | hang hoa | so luong | don gia | thanh tien |") print("+----------+------------------+----------+---------------+------------------+") print("| "+stt_x+" | " +tenhanghoa+ " | "+soluong_x+" | "+dongia_x+" | "+thanhtien_x+" |") print("+----------+------------------+----------+---------------+------------------+") print("| "+stt_x+" | " +tenhanghoa+ " | "+soluong_x+" | "+dongia_x+" | "+thanhtien_x+" |") print("+----------+------------------+----------+---------------+------------------+") if x== 'T': print("tong doanh thu bang") t_sum = 0 tien=[] for num in tien: t_sum = t_sum + num print(t_sum) if x== 'A': print("so hang hoa ban ra") a_sum = 0 so=[] for j in so: a_sum = a_sum + j print(a_sum) if x== 'E': print("^_^ bye ^_^") break
6cc1fab83327c7e6a619741a7518af151fae0e41
wilfred321/flask_tuts
/flight.py
757
4.03125
4
class Flight(): def __init__(self,capacity): self.capacity = capacity self.passengers = [] def add_passenger(self,name): if not self.open_seats: return False self.passengers.append(name) return True def open_seats(self): return self.capacity - len(self.passengers) flight = Flight(3) people = ["Andy", "Chucks","Matt"] for person in people: if flight.open_seats(): flight.add_passenger(person) print(f"The passenger with name {person} was added to the flight") print(f"The current flight capacity is {flight.open_seats()}") else: print(f"No seats available for {person}") print(f"The final flight capacity is {flight.open_seats()}")
c45a94e149844e80de1ad7db8e3eb6b7a34ec717
DocBlack89/Courbe_elliptique
/client.py
3,113
3.6875
4
#!/usr/bin/python3 import ecc import config import diffie_hellman import chiffrement import sys import time def menu(): ''' Menu permettant de choisir ce que l'on souhaite faire ''' print("\n\n############################") print("# #") print("# Ceci n'est pas un menu #") print("# #") print("############################") print("1- Création de la courbe") print("2- Multiplication de deux points") print("3- Doublement d'un point") print("4- Vérification de la présence du point sur la courbe") print("5- Addition de deux points") print("6- Création courbe, multiplication de deux points, doublement de P, addition de deux points") print("7- Diffie-Hellman") print("8- Chiffrement") print("10- Quitter") choix = int(input("Votre choix : ")) if (choix == 1): print(creation_courbe()) if (choix == 2): multiplication_point() if (choix == 3): doublement_point() if (choix == 4): verif_presence() if (choix == 5): addition_points() if (choix == 6): tout() if (choix == 7): DH() if (choix == 8): envoie_message() if (choix == 9): sys.exit() def creation_courbe(): ''' Crée une courbe elliptique ''' curve = ecc.Curve(config.A, config.B, config.N) return curve def multiplication_point(): ''' Multiplie deux point sur une courbe ''' curve = creation_courbe() mul = ecc.Curve.mul(curve, config.l, config.P) print(mul) def doublement_point(): ''' Double un point sur une courbe ''' curve = creation_courbe() dbl = ecc.Curve.mul(curve, 2, config.P) print(dbl) def verif_presence(): ''' Vérifie la présence d'un point sur la courbe ''' curve = creation_courbe() isOn = ecc.Curve.isOn(curve, config.M) print(isOn) def addition_points(): ''' Additionne deux points sur la courbe ''' curve = creation_courbe() add = ecc.Curve.add(curve, config.P, config.Q) print(add) def tout(): ''' Crée une courbe elliptique Multiplie deux point sur une courbe Double un point sur une courbe Vérifie la présence d'un point sur la courbe Additionne deux points sur la courbe ''' curve = ecc.Curve(config.A, config.B, config.N) isOnP = ecc.Curve.isOn(curve, config.P) add = ecc.Curve.add(curve, config.P, config.Q) mul = ecc.Curve.mul(curve, config.n, config.Q) dbl = ecc.Curve.mul(curve, 2, config.P) print(curve) print(add) print(mul) print(isOnP) print(dbl) def DH(): ''' Effectue un échange Diffie-Hellman entre Bob et Alice ''' curve = ecc.Curve(config.A, config.B, config.N) Alice = diffie_hellman.Alice(curve) print(Alice) def envoie_message(): ''' Simule l'envoie d'un message chiffré par la courbe elliptique ''' curve = ecc.Curve(config.A, config.B, config.N) M = chiffrement.dechiffrement_Alice(curve) print(M) while 1: menu()
739b27500108d1541b6d1a88f0f7d79d70e4db5d
psv-git/labs
/OOD/Lab1/classes/decorators/print_to_console_decorator.py
599
3.640625
4
from classes.decorators.base_decorator import BaseDecorator class PrintToConsoleDecorator(BaseDecorator): # private methods ========================================================= def __init__(self, shape): super().__init__(shape) # public methods ========================================================== def get_parameters(self): figure_type, perimeter, area = super().get_parameters() print("This parameters was printed by PrintConsoleDecorator: {0}, {1}, {2}".format(figure_type, perimeter, area)) return figure_type, perimeter, area
b5358749a18db5e3d086f6a2c8a85602e8b28db7
psv-git/labs
/MLITA/Lab6/src/functions.py
2,065
3.890625
4
# http://comp-science.narod.ru/DL-AR/okulov.htm def read_file(file): lines = file.read().splitlines() return lines[0], lines[1] def string_to_long(str_num, base_power=3): lng_num = [] dig_count = 0 curr_num = "" for i in range(len(str_num)-1, -1, -1): dig_count += 1 curr_num += str_num[i] if dig_count == base_power: lng_num.append(int(curr_num[::-1])) dig_count = 0 curr_num = "" if len(curr_num): lng_num.append(int(curr_num[::-1])) return lng_num def long_to_string(lng_num, sign=1, base_power=3): if sign < 0: str_num = "-" else: str_num = "" lng_num_len = len(lng_num)-1 for i in range(lng_num_len, -1, -1): num = str(lng_num[i]) num_len = len(num) if num_len < base_power and i < lng_num_len: num = "0" * (base_power - num_len) + num str_num += num return str_num def __compare(lng_x, lng_y): """ 0: x = y 1: x > y 2: x < y """ len_lng_x = len(lng_x) len_lng_y = len(lng_y) if len_lng_x > len_lng_y: return 1 if len_lng_x < len_lng_y: return 2 for i in range(len_lng_x-1, -1, -1): if lng_x[i] > lng_y[i]: return 1 if lng_x[i] < lng_y[i]: return 2 return 0 def __sub(lng_x, lng_y, base_power): for i in range(len(lng_y)): lng_x[i] -= lng_y[i] for j in range(i+1, len(lng_x)): if lng_x[j-1] >= 0: break lng_x[j-1] += pow(10, base_power) lng_x[j] -= 1 for i in range(len(lng_x)-1, -1, -1): if lng_x[i] == 0: lng_x.pop(i) else: break return lng_x def subtract(lng_x, lng_y, base_power=3): """ 0, 1: x = y answ, 1: x > y answ, -1: x < y """ answ = 0 sign = 1 c = __compare(lng_x, lng_y) if c != 0: if c == 1: answ = __sub(lng_x, lng_y, base_power) if c == 2: sign = -1 answ = __sub(lng_y, lng_x, base_power) return sign, answ
9f91455daba127b6ce40a5037a8b3c60ca37a96f
chvjak/cj2017
/alphabet_cake.py
3,239
3.5
4
f = open("alphabet_cake.txt") #f = open("A-small-practice.in") # def input2(): res = f.readline() return res def get_res_cake(cake): def all_distributed(): for row in res_cake: if '?' in row: return False else: return True def is_valid_expansion(expansion, c): min_i, min_j, max_i, max_j = expansion for i in range(min_i, max_i + 1): for j in range(min_j, max_j + 1): if res_cake[i][j] not in ('?', c): return False else: return True def do_expansion(expansion, c): min_i, min_j, max_i, max_j = expansion for i in range(min_i, max_i + 1): for j in range(min_j, max_j + 1): res_cake[i][j] = c def undo_expansion(expansion): do_expansion(expansion, '?') def is_valid(r, c): R = len(res_cake) C = len(res_cake[0]) return r < R and c < C and r >= 0 and c >= 0 def get_expansions(pos): i,j = pos i += 1 while is_valid(i, j) and res_cake[i][j] == '?': i += 1 max_i = i - 1 i, j = pos i -= 1 while is_valid(i, j) and res_cake[i][j] == '?': i -= 1 min_i = i + 1 i, j = pos j += 1 while is_valid(i, j) and res_cake[i][j] == '?': j += 1 max_j = j - 1 i, j = pos j -= 1 while is_valid(i, j) and res_cake[i][j] == '?': j -= 1 min_j = j + 1 expansions = [] i0, j0 = pos for i1 in range(min_i, i0 + 1): for j1 in range(min_j, j0 + 1): for i2 in range(i0, max_i + 1): for j2 in range(j0, max_j + 1): expansions.append((i1, j1, i2, j2)) return expansions def add_initials(ii): rc = res_cake if all_distributed(): return True if ii == len(initials): return False ch = initials[ii] expansions = get_expansions(initial_pos[ch]) for expansion in expansions: if is_valid_expansion(expansion, ch): do_expansion(expansion, ch) if add_initials(ii + 1): return True else: undo_expansion(expansion) r,c = initial_pos[ch] res_cake[r][c] = ch #none of the ways to expand did it return False res_cake = [None] * R initial_pos = {} for ri in range(R): row = cake[ri] res_cake[ri] = row[:] for ci in range(C): c = row[ci] if c != '?': initial_pos[c] = (ri, ci) initials = list(initial_pos.keys()) #print(initials) initials.sort() add_initials(0) return res_cake T = int(input().strip()) for t in range(T): R, C = [int(x) for x in input().strip().split(' ')] cake = [None] * R for ri in range(R): cake[ri] = list(input().strip()) res_cake = get_res_cake(cake) print("Case #{}:".format(t + 1)) for row in res_cake: print(''.join(row))
384c0b886114ae094daee763a8759a8a839ec485
pcranger/learning-Flask
/section2/unpack arguments/define 2 asterisk.py
379
3.890625
4
# 1. **kwargs in function call def named(name, age): print(name, age) # data as dict bob = {"name": "Bob", "age": 25} named(**bob) # and unpacks the dict into arguments of named() #2. **kwargs in argument def test(**kwargs): print(kwargs) # kwargs in a dict test(name="bob", age=25) # 2 pairs with be packed into 1 dict # pack the arguments of test) to kwargs
eee674be1b7bed2732ff6710e0dfda7777f8a193
AlexJonesCU/Perceptron
/Perceptron.py
3,279
4.25
4
#~ various sources I used to learn how to code the perceptron #https://www.youtube.com/watch?v=tA9jlwXglng #https://arxiv.org/abs/1903.08519 #https://machinelearningmastery.com/implement-perceptron-algorithm-scratch-python/ -- this was an amazing tutorial page #https://julienbeaulieu.gitbook.io/wiki/sciences/machine-learning/neural-networks/perceptron-algorithm #https://queirozf.com/entries/add-labels-and-text-to-matplotlib-plots-annotation-examples #https://likegeeks.com/numpy-where-tutorial/ #https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html #https://www.kite.com/python/answers/how-to-plot-a-line-of-best-fit-in-python # I understood the concept of a perceptron and how the features are affected # by the weights to find the model based on the dataset # however I struggled with executing the code on the perceptron # I spent all week watching tutorial videos and different coding samples # and still had trouble calculating the training data import numpy as np import pandas as pd import matplotlib.pyplot as plt #Perceptron learning algorithm def train_data(train, data): weights = [-.2, .54] for run in range(100): sum_error = 0.00 #reset at beginning of each loop for row in train: prediction = predict(row, weights) sum_error += (row[-1] - prediction)**2 #subtracts answer by predicted value weights[0] = weights[0] + data * (row[-1] - prediction) for i in range(len(row)-1): weights[i + 1] = weights[i + 1] + data * (row[-1] - prediction) * row[i] print('>runs=%d, error=%.3f' % (run, sum_error)) return weights #to find the predicted value with weights applied def predict(row, weight): guess = weight[0] for i in range(len(row)-1): guess += weight[i+1] * row[i] if(guess >= 0): value = 1 else: value = 0 return value #gives us pediction value with given weight #sample data set used in many perceptron algorithms data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header = None) weight = [-.2, .54, .04, -.7] #read in values to X and y in order to determine their linear dependence y = data.iloc[0:100,4].values y = np.where(y == 'Iris-sertosa',-1,1 ) #changes label of iris setosa to int '1' X = data.iloc[0:100, [0,2]].values for row in X: prediction = predict(row, weight) print("Expected=%d, Predicted=%d" % (row[-1], prediction)) weights = train_data(X, 1) print(weights) #creating the scatter plot #We can see from looking at the data set that the first 50 are setosa and the next 50 are versicolor plt.scatter(X[:50,0],X[:50, 1], color = 'blue', marker = 'o', label = 'setosa') #first 50 rows in first and second column, plt.scatter(X[50:,0],X[50:, 1], color = 'red', marker = 'o', label = 'versicolor') #50 to the end rows in first and second column, plt.xlabel('sepal_length') plt.ylabel('petal_length') plt.text(6,2.5,'data appears linearly separable') m, b = np.polyfit(X[:50,0], X[:50, 1], 1) plt.plot(X[:50,0], m*X[:50,0] + b) m, b = np.polyfit(X[50:,0], X[50:, 1], 1) plt.plot(X[50:,0], m*X[50:,0] + b) plt.show() error = train_data(X[0:], 100) num_Of_Runs = np.arange(1, 100)
e30caa3a29aae2b49cb5bbb724d341b55294efc7
AntonPushkash/ITEA_hw
/hw8/grouping.py
1,702
3.71875
4
""" Пользователь вводит количество групп n. Далее вводится n строк, каждая строка начинается с названия группы, а затем через пробел идут элементы группы. 1. Обработать строки и вывести на экран словарь, в котором ключи - это группы, а значения - списки элементов групп. 2. Создать и вывести второй словарь, в котором ключи - элементы групп, а зачения - группы. Используйте функции! Например: [out] Введите кол-во групп: [in] 2 [out] 1 группа: [in] fruits apple banana mango kiwi lemon [out] 2 группа: [in] citrus lime lemon orange [out] { 'fruits': ['apple', 'banana', 'mango', 'kiwi', 'lemon'], 'citrus': ['lime', 'lemon', 'orange'] } [out] { 'apple': ['fruits'], 'lemon': ['citrus', 'fruits'], ... } """ def tmp_dict(n): a = {} for gr_num in range(n): elements_str = input(f'{gr_num + 1} group: ') el_list = elements_str.split() a.update({el_list[0]: el_list[1:]}) return a def mod_dict(a): b = {} for k, v in a.items(): for i in v: values = b.get(i, []) values.append(k) b[i] = values return b def main(): n = int(input('Groups qty: ')) dict_1 = tmp_dict(n) print(dict_1) dict_2 = mod_dict(dict_1) print(dict_2) main()
eccedcff0f3131ff861b5678f6f41eeac1389c14
AntonPushkash/ITEA_hw
/hw6/file_practice.py
2,185
3.671875
4
""" Выполните все пункты. * можно описывать вложенные with open(), если это необходимо. * работа в основном с одним файлом, поэтому имя можно присвоить переменной """ # 1. # Создайте файл file_practice.txt # Запишите в него строку 'Starting practice with files' # Файл должен заканчиваться пустой строкой # 2. # Прочитайте файл, выведете содержимое на экран # Прочитайте первые 5 символов файла и выведите на экран # 3. # Прочтите файл 'files/text.txt' # В прочитанном тексте заменить все буквы 'i' на 'e', если 'i' большее количество, # иначе - заменить все буквы 'e' на 'i' # Полученный текст дописать в файл 'file_practice.txt' # 4. # Вставьте строку '*some pasted text*'. # Если после вставки курсор остановился на четной позиции # - добавить в конец файла строку '\nthe end', # иначе - добавить в конец файла строку '\nbye' # Прочитать весь файл и вывести содержимое # 2. with open('file_practice.txt') as f: f.seek(0) print(f.read(5)) # 3. i_counter = e_counter = 0 with open('files/text.txt') as f: data = f.read() for l in data: if l == 'i': i_counter += 1 elif l == 'e': e_counter += 1 if i_counter > e_counter: edited = open('files/text.txt', 'r').read().replace('i', 'e') else: edited = open('files/text.txt', 'r').read().replace('e', 'i') with open('files/text.txt', 'a+') as f: f.write(edited) # 4. with open('files/text.txt', 'a+') as f: f.write('*some pasted text*') pos = (f.tell()) if pos % 2 == 0: f.write('\nthe end') else: f.write('\nbye') with open('files/text.txt') as f: print(f.read())
b60b480b8b349403a7413e8c806eae0b83ef8f5d
AntonPushkash/ITEA_hw
/hw4/practice.py
1,250
4.0625
4
""" Выполнить описанные действия над строкой. """ string = 'Lorem, Ipsum, is, simply, dummy, text, of, the, printing, industry.' # 1. Изменить строку таким образом, чтоб вместо ', ' был пробел ' ' # Вывести получившуюся строку. # 2. Вывести индекс самой последней буквы 's' в строке. # 3. Вывести количество букв 'i' в строке (регистр не имеет значения). # 4. Вывести срез строки. # Условие: от 'simply' до 'of' не включительно # Результат: 'simply dummy text' # (используйте методы find или index для получения индексов) # 5. Продублируйте первую половину строки 3 раза и склейте с второй половиной. # Выведите результат. # 1 s = string.replace(', ', ' ') print(s) # 2 print(s.rindex('s')) # 3 count = 0 for i in s: if i.isalpha(): count += 1 print(count) # 4 print(s[15:32]) # 5 b = s[:32] * 3 print(b, s[32:])
024a187aad268cb07d34fe73a7c3935002fa4f88
novita2005490/Tugas1-PemrogramanBerorientasiobjek
/luassegitiga.py
158
3.71875
4
print("Menghitung Luas Segitiga") a=float(input("Masukkan Alas : ")) t=float(input("Masukkan Tinggi : ")) luas=0.5*a*t print("Luas Segitiga= "+ str(luas))
811613f48605b29b5d667e4d089e03f8a0fd0e2c
hopeniitssaa/STRING
/string3.hope.py
352
3.546875
4
s1 = str(input("Dati un cuvant :")) s2 = str(input("Dati un cuvant :")) s3 = str(input("Dati un cuvant :")) s4 = str(input("Dati un cuvant :")) cuvant="" if (len(s1)>2 and len(s2)>2 and len(s3)>2 and len(s4)>2): cuvant+=s1[0:2]+s2[0]+s3[0:3]+s4[0:len(s4)//2] else: print("Dati un cuvant, cu mai mult decat 2 caractere") print(cuvant)
4b76507d8f332d7c1311e6c9eed50a32510956bc
hagemon/StatLearning
/Python/mat.py
564
3.546875
4
import operator import itertools def sub(a, b): assert len(a) == len(b) return list(itertools.starmap(operator.sub, zip(a, b))) def sub_square(a, b): assert len(a) == len(b) return itertools.starmap(operator.pow, zip(sub(a, b), [2]*len(a))) def mul(a, b): assert len(a) == len(b) return list(itertools.starmap(operator.mul, zip(a, b))) def dot(a, b): assert len(a) == len(b) return sum(mul(a, b)) if __name__ == '__main__': x = [1, 2, 3] z = [4, 5, 6] print(list(sub_square(x, z)))
3c415f8c53d89461f2ecf7a7d5ac6adec64d1eca
qiaocco/reading-notes
/fluent-python/chap2_list/ex_2_9.py
415
3.84375
4
""" 具名元组 """ from collections import namedtuple Product = namedtuple('Product', ('name', 'price', 'city')) p = Product('手机', '5000', 'sh') print(p.name, p.price) # 手机,5000 print(p[0]) # 手机 print(Product._fields) # ('name', 'price', 'city') params = ('手机', '5000', 'sh') print(Product._make(params)) # 生成实例==Product(*params) for k, v in p._asdict().items(): print(k, v)
2d1967816d049233b44bbe231f18edeb42c6d7e6
Adrian-Ng/Learning-Python
/Introduction/PrintFunction.py
212
3.578125
4
import math if __name__ == '__main__': n = int(input()) output = int(0) for i in range(1,n+1): output *= 10 * (10 ** math.floor(math.log(i, 10))) output += i print(output)
db50c66ed6ff86e9e69a2a68f8f0ddf8f959cac6
a01374764/Tarea_03
/PagoDeUnTrabajador.py
2,558
3.921875
4
# encoding UTF-8 # Autor: Siham El Khoury Caviedes, A01374764 # Descripción: Cálculo del pago total de un trabajador. # Calular y guardar en la variable pagoNormal el pago por las horas normales de un trabajador. def calcularPagoNormal(horasNormales, pago): pagoNormal = horasNormales * pago # Calular y guardar en la variable pagoNormal el pago por las horas normales de un trabajador. return pagoNormal # Regresar pagoNormal. # Calular y guardar en la variable pagoTotal el pago por las horas normales y extras de un trabajador. def calcularPagoTotal(pagoNormal, pagoExtra): pagoTotal = pagoNormal + pagoExtra # Calular y guardar en la variable pagoTotal el pago por las horas normales y extras de un trabajador. return pagoTotal # Regresar pagoTotal. # Función principal. def main(): horasNormales = int(input("Teclea las horas normales trabajadas: ")) # Leer y guardar en la variable horasNormales las horas normales trabajadas. horasExtras = int(input("Teclea las horas extras trabajadas: ")) # Leer y guardar en la variable horasExtras las horas extras trabajadas. pago = float(input("Teclea el pago por hora: ")) # Leer y guardar en la variable pago el pago por hora. pagoNormal = calcularPagoNormal(horasNormales, pago) # Llamar a la funcion calcularPagoNormal. pagoExtra = horasExtras * (pago*1.5) # Calcular y guardar en la variable pagoExtra el pago por las horas extras trabajadas. pagoTotal = calcularPagoTotal(pagoNormal, pagoExtra) # Llamar a la función calcularPagoTotal. print (" ") # Imprimir espacio. print ("Pago normal: %.2f" % pagoNormal) # Imprimir el pago normal. print ("Pago extra: %.2f" % pagoExtra) # Imprimir el pago extra. print ("--------------------") # Imprimir separación con guiones. print ("Pago total: %.2f" % pagoTotal) # Imprimir el pago total. main() # Ejecutar la función main.
382770a30b3ea7ca77522a407d6208a8f1f0d16b
anju-netty/pylearning
/kidsquiz.py
1,304
4.09375
4
#!/Users/bin/python3 import random """ Quiz game throwing random questions at the user, continue the game if user choses and display score at the end """ questionset = { 'Which animal lives in the North pole? : ': 'polar bear', 'Which is the largest animal? : ': 'elephant', 'Which is the fastest land animal? ': 'cheetah' } score = 0 questions = list(questionset.keys()) def get_random_question(): # TODO: delete seleted question from the list randomquestion = random.choice(questions) return randomquestion def getanswer(question): return questionset[question] def display_result(): if score != 0: print("\n\nCongratulations! Your score is : ", score) else: print("\n\nYou got Duck! :) ") if __name__ == "__main__": print("Welcome to Quiz session!") choice = 'y' while(choice.lower() == 'y'): randomq = get_random_question() answer = getanswer(randomq) ans = input(randomq) ans = ans.lower() # answers are stored in lower case print(ans) if ans == answer: print("correct") score = score+1 else: print("wrong!") choice = input( "Do you like to continue with the next question?(y/n) : ") display_result()
8ed44f676e29a187fa95e25265b30806a6d49138
anju-netty/pylearning
/fizzbuzz_test.py
795
3.578125
4
import unittest from fizzbuzz import solve_fizzbuzz class TestFizzBuzz(unittest.TestCase): def test_multiple_of_5(self): list_zz = solve_fizzbuzz(5) expected = "buzz" self.assertEqual(list_zz,expected) def test_solve_fizzbuzz_zero(self): with self.assertRaises(ValueError): solve_fizzbuzz(0) def test_multiple_of_3(self): list_zz = solve_fizzbuzz(9) expected = "fizz" self.assertEqual(list_zz,expected) def test_multiple_of_3_and_5(self): list_zz = solve_fizzbuzz(15) expected = "fizzbuzz" self.assertEqual(list_zz,expected) def test_not_multiple_of_3_and_5(self): list_zz = solve_fizzbuzz(4) expected = 4 self.assertEqual(list_zz,expected)
a7965122286820ecf5578b7e7c30fe6cd946220b
anju-netty/pylearning
/opening_reading_files.py
736
3.84375
4
# #print("\n\nHello welcome\n\n") # ##open the file in read only mode #f = open('configuration.txt','r') # ##read one character from the file to the variable 'content' #content = f.read(1) # ##print content #print(content) # ##read 3 characters from the file to the variable 'content' from the current position #content = f.read(3) #print(content) # ##this is find the current position of the pointer #print("current position : ",f.tell()) # ##seek function will move the cursor to the 2 character in the file. #print("move to position 2 now",f.seek(2)) #print(f.read(3)) # #print(f.closed) #check if file is closed #f.close() #close the file. # with open('configuration.txt','r') as file: print(file.read()) print(file.closed
c9ab056c96c7d1a0bf737d7268e8d2b991e59c12
lein-g/LiaoXuefeng_Python
/3_函数_4_递归函数.py
768
3.96875
4
def product(a, *args): s = 1 for x in args: s = s*x return a*s print('product(5) =', product(5)) print('product(5, 6) =', product(5, 6)) print('product(5, 6, 7) =', product(5, 6, 7)) print('product(5, 6, 7, 9) =', product(5, 6, 7, 9)) if product(5) != 5: print('测试失败!') elif product(5, 6) != 30: print('测试失败!') elif product(5, 6, 7) != 210: print('测试失败!') elif product(5, 6, 7, 9) != 1890: print('测试失败!') else: try: product() print('测试失败!') except TypeError: print('测试成功!') # 汉诺塔 def move(n,a,b,c): if n==1: print(a,'=>',c) else: move(n-1,a,c,b) move(1,a,b,c) move(n-1,b,a,c) move(1,'A','B','C')
12de12dc49ba043810c17210131769bb785e9918
lein-g/LiaoXuefeng_Python
/5_函数式编程_2_返回函数_闭包.py
3,268
3.96875
4
""" 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回 """ # 当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数 # 调用函数f时,才真正计算求和的结果 def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f = lazy_sum(1, 3, 5, 7, 9) print(f) print(f()) """ 我们在函数lazy_sum中又定义了函数sum, 并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量, 当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中, 这种称为“闭包(Closure)”的程序结构拥有极大的威力 """ # 当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数 f1 = lazy_sum(1, 3, 5, 7, 9) f2 = lazy_sum(1, 3, 5, 7, 9) print(f1 == f2) """ 当一个函数返回了一个函数后,其内部的局部变量还被新函数引用 另一个需要注意的问题是,返回的函数并没有立刻执行,而是直到调用了f()才执行 """ # 返回的函数引用了变量i,但它并非立刻执行。等到3个函数都返回时, # 它们所引用的变量i已经变成了3,因此最终结果为9 # 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量 def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fs print(count()) f1, f2, f3 = count() # count()的返回值为三个闭包(i*i)组成的数据 print(f1()) # 再创建一个函数,用该函数的参数绑定循环变量当前的值, # 无论该循环变量后续如何更改,已绑定到函数参数的值不变 def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs # 练习 # 利用闭包返回一个计数器函数,每次调用它返回递增整数 def createCounter(): def counter(): return 1 return counter # 测试: # 方法一: # 定义变量n用于count,但由于n为不可变对象, # 在当前作用域中的给变量赋值时,该变量将成为该作用域的局部变量,并在外部范围中隐藏任何类似命名的变量 # 所以访问外层函数的局部变量时, 要用nonlocal def createCounter(): n = 0 def count(): nonlocal n # 使用外层变量 n = n+1 return n return count # 方法二: # 定义变量li用于count,list为可变对象 # 改变其元素【0】的值时,li本身并没有改变 # 内部函数可以使用外部函数的参数和局部变量,所以不需要使用nonlocal def createCounter(): li = [0] # print(id(li)) def counter(): li[0] += 1 # print(id(li)) return li[0] return counter counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: print('测试通过!') else: print('测试失败!')
c7508cf5a5ac9d39a58c53b3bec473d5b2ced1b9
seanofconnor/web-caesar
/caesar.py
1,232
3.65625
4
def encrypt(text, rot): l = len(text) i = 0 newText = '' # cycle through chars in text while i < l: c = text[i] newText = newText + rotate_character(c, rot) i = i + 1 return(newText) def alphabet_position(letter): bet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] x = bet.index(letter) if x > 25: x = x - 25 return x else: x = x + 1 return x def rotate_character(char, rot): bet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] # check if alpha if char in bet: # calculate new letter x = alphabet_position(char) newChar = (x + rot) % 26 - 1 # check for uppercase isupper = bet.index(char) # uppercase if isupper > 25: return(bet[newChar].upper()) else: return(bet[newChar]) else: return(char)
ab9fa24c458013a8ea9b299552fdbdf75f3be47e
ICESDHR/Bear-and-Pig
/笨蛋为面试做的准备/leetcode/1.两数之和.py
582
3.84375
4
''' 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ''' def twoSum(nums, target): lookup = {} for i, num in enumerate(nums): if target - num in lookup: return [lookup[target - num], i] lookup[num] = i if __name__=="__main__": nums = [2, 7, 11, 15] target = 9 print(twoSum(nums, target))