text
stringlengths 37
1.41M
|
---|
a=int(input())
a=str(a)
f=0
for i in range(0,len(a)):
if(a[i]=='0' or a[i]=='1'):
f=1
else:
f=0
break
if(f==1):
print("yes")
else:
print("no")
|
in1=int(input())
in2=0
while(in1>0):
in3=in1%10
in2=in2*10+in3
in1=in1//10
print(in2)
|
a = input()
b = ["a","e","i","o","u","A","E","I","O","U"]
c=len(a)
for i in range(0,c):
if(a[i] in b):
print("yes")
break
else:
print("no")
|
a = int(input())
if (a>=0):
if (a%2==0):
print("Even")
elif (a%1==0):
print("Odd")
else:
print("invalid")
|
# userConverstionType = input("1: inches to mm. 2: or mm to inches. Q to quit. ")
# converstionTypeInt = int(userConverstionType)
# userNumber = input("Enter number: ")
# userNumberFloat = float(userNumber)
# 1 would convert in to mm
# TODO loop to be able to process multiple calculations
# TODO add function to improve DRY concepts
# loop to continue until user selects Q
def print_calculation(con_string): # no parameters. Go inside ()
print('Your answer is: ', con_string)
while True:
# get menu selection from user
userConverstionType = input("1: inches to mm. 2: or mm to inches. Q to quit. ")
# prior to conversion, exit while loop
if userConverstionType.isdigit() != True:
# if the user input is string ---> error message go back to main menu
if userConverstionType == 'Q':
break
print('That is not an option. Please choose from menu')
continue # exit this iteration and continue in the next while loop iteration
# converts user menu selection to an int
converstionTypeInt = int(userConverstionType)
# ask user number to convert
userNumber = input("Enter number: ")
# convert to a float for calc
userNumberFloat = float(userNumber)
if converstionTypeInt == 1:
print("Convert inches to mm.")
convertedNumber = userNumberFloat * 25.4
convertedString = "{0:.4f} inches is = {1:.4f} mm"
print_calculation(convertedString)
# 2 convert mm to in
# if converstionTypeInt == 2:
# print("Convert mm to inches")
# # 25.4 mm = 1 in
# # Convert from mm to in
# # userNumber / 25.4 mm = converted number
# convertedNumber = userNumberFloat / 25.4
# convertedString = "{0:.4f} mm is = {1:.4f} inches"
# print (convertedString.format(userNumberFloat, convertedNumber))
|
'''
Python中有join()和os.path.join()两个函数,具体作用如下:
join():连接字符串数组。
将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
os.path.join():将多个路径组合后返回
1、join()函数
语法:'sep'.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串(ps:开头和结尾不会有sep,即seq元素之间由sep来拼接)
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
2、os.path.join()函数
语法: os.path.join(path1[,path2[,......]])
返回值:将多个路径组合后返回
'''
#str.join(sequence)
s1 = "-"
s2 = ""
seq = ("r","u","n","o","o","b")
print(s1.join(seq))
print(s2.join(seq))
|
'''
撰寫一程式可供使用者輸入一整數N
a.假如(N < 60)印出"不及格"
b.假如(N≥60)而且(N < 90)印出"及格"
c.假如(N≥90)而且(N < 100)印出"表現優異"
'''
if __name__ == "__main__":
text = raw_input("enter:")
print text
n1 = int(text)
if n1 < 60:
print u"不及格"
elif n1 >= 60 and n1 < 90:
print u"及格"
elif n1 >= 90 and n1 <= 100:
print u"表現優異"
|
import tkinter
win=tkinter.Tk();
win.title("登录");
win.geometry("200x80");
L1=tkinter.Label(win,text="用户名:",width=6);
L1.place(x=1,y=1);
L2=tkinter.Label(win,text="密码:",width=6);
L2.place(x=1,y=20);
E1=tkinter.Entry(win,width=20);
E1.place(x=45,y=1);
E2=tkinter.Entry(win,width=20,show="哈");
E2.place(x=45,y=20);
B1=tkinter.Button(win,text="登录",width=8);
B1.place(x=40,y=40);
B2=tkinter.Button(win,text="取消",width=8);
B2.place(x=110,y=40);
win.mainloop();
#也可以看书38页例1-17.
#好处:可以精准把组件放在窗口
|
list1=['鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'];
list2=['鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'];
print([m+n for m in list1 for n in list2 if m!=n]);
|
import tkinter
win=tkinter.Tk();#创建一个窗口
win.title('pack几何布局');
win.geometry("800x600");#设置窗口的大小
labe1=tkinter.Label(win,text='hello,python');#创建Label组件
labe1.pack();#组件label的位置设置书40-41页图1-10
button1=tkinter.Button(win,text='BUTTON1');#创建Button组件
button1.pack(side=tkinter.LEFT);#将button1组件添加到窗口中显示,左停靠
button2=tkinter.Button(win,text='BUTTON2');
button2.pack(side=tkinter.RIGHT);#将button2组件添加到窗口中显示,右停靠(默认正中间)
win.mainloop();
|
import math
def nCr(n, r):
# Implements the combinatorics n choose r
r = min(r, n-r)
numer = 1
demon = 1
while(r >= 1):
numer *= (n-r+1)
demon *= r
r -= 1
return(int(numer/demon))
#try to help user to find upperbound by example
def upperBound(s, t):
print("A upper bound on the Ramsey numbers R(s,t)\n"
"was obtained by double induction on s and t.\n"
"Since we have observed the relationship between R(s,t) and R(s-1,t), R(s, t-1).\n"
"Such that: R(s,t) <= R(s-1,t) + R(s,t-1)\n"
"Then apply the double induction\n"
"assuming R(s,t) <= C(s+t-2, t-1) works for all s+t = n.\n"
"Since R(s-1,t) <= C(s+t-2, t-1) = C(n-2, t-1)\n"
"and R(s,t-1) <= C(s+t-2, t-2) = C(n-2, t-2).\n"
"Applying Pascal's rule: C(n-2, t-1) + C(n-2, t-2) = C(n-1, t-1)\n"
"which proves that R(s,t) <= R(s-1,t) + R(s,t-1)\n"
"<= C(n-2, t-1) + C(n-2, t-2) = C(n-1, t-1).\n"
"then it also works for s+t= n+1.\n"
"\n"
"Take R("+str(s)+","+str(t)+") for example.\n"
"Given R(s,t) <= R(s-1,t) + R(s,t-1)\n"
"To find upper bound of R(s,t)\n"
"Which two Ramsey numbers should we use?\n"
"A. R("+str(s)+","+str(t)+")\n"
"B. R("+str(s-1)+","+str(t)+")\n"
"C. R("+str(s)+","+str(t-1)+")\n"
"D. R("+str(s-1)+","+str(t-1)+")\n")
# user select the correct choice
choiceSelection1()
print("Then we take one step further\n"
"Select combinations in order to calculate the upper bound of R("+str(s)+","+str(t)+")\n"
"Which two combinations we should use?\n"
"A. C("+str(s+t-1)+","+str(t-2)+") and C("+str(s+t-1)+","+str(t-1)+")\n"
"B. C("+str(s+t-1)+","+str(t-2)+") and C("+str(s+t-1)+","+str(t-2)+")\n"
"C. C("+str(s+t-2)+","+str(t-1)+") and C("+str(s+t-2)+","+str(t-1)+")\n"
"D. C("+str(s+t-2)+","+str(t-1)+") and C("+str(s+t-2)+","+str(t-2)+")\n")
# user select the correct choice
choiceSelection2()
print("Here we have known where to find the upper bound of R(s,t).\n"
"Now to calculate the upper bound of R("+str(s)+","+str(t)+")\n"
"Here are some results of combinations:\n"
"C("+str(s+t-1)+","+str(t-3)+"): "+str(nCr(s+t-1, t-3))+"\n"
"C("+str(s+t-2)+","+str(t-2)+"): "+str(nCr(s+t-2, t-2))+"\n"
"C("+str(s+t-2)+","+str(t-3)+"): "+str(nCr(s+t-1, t-3))+"\n"
"C("+str(s+t-2)+","+str(t-1)+"): "+str(nCr(s+t-2, t-1))+"\n"
"Calculate the upper bound of R("+str(s)+","+str(t)+")\n"
"And Write down your answer below:\n"
)
#user write the upper bound
upperboundCalcualte(s, t)
print("Thanks for your particpation.\n")
# To identify if user select the right choice
# If user fail 6 times
# Then system automatically output thecorrect answer
def choiceSelection1():
selection1 = " "
selection2 = " "
times1 = 0
isFalse = True
while(isFalse):
while(isFalse):
try:
selection1,selection2 = map(str,input().split( ))
break
except(ValueError):
print("Please select two choices from A,B,C,D\n"
"Remember seperating two choices by SPACE key\n"
"Try again\n")
if (selection1 == "B") and (selection2 == "C"):
print("Good job!\n")
isFalse = False
elif (selection1 == "C") and (selection2 == "B"):
print("Good job!\n")
isFalse = False
else:
print("Sorry, try it again.\n")
isFalse = True
times1 = times1 + 1
if (times1 == 6):
print("The correct answer is B and C.\n")
break
return
# To identify if user select the right choice
# If user fail 6 times
# Then system automatically output thecorrect answer
def choiceSelection2():
selection3 = " "
times2 = 0
isFalse = True
while(isFalse):
while(isFalse):
try:
selection3 = str(input())
break
except(ValueError):
print("Please select two choices from A,B,C,D\n"
"Try again\n")
if (selection3 == "D"):
print("Good job!\n")
isFalse = False
else:
print("Sorry, try it again.\n")
isFalse = True
times2 = times2 + 1
if (times2 == 6):
print("The correct answer is D.\n")
break
return
# To identify if user write the correct upper bound
# If user fail 6 times
# Then system automatically output thecorrect answer
def upperboundCalcualte(s, t):
num = 0
times3 = 0
isFalse = True
correct_answer = nCr(s+t-2, t-1) + nCr(s+t-2, t-2)
while(isFalse):
while(isFalse):
try:
num = int(input())
break
except(ValueError):
print("Please write an intger\n"
"Try again\n")
if (num == correct_answer):
print("You have understood how to calculate upper bound of Ramsey Number.\n"
"Congradulations!\n")
isFalse = False
else:
print("Sorry, try it again.\n")
isFalse = True
times3 = times3 + 1
if (times3 == 6):
print("The correct answer is: " + str(correct_answer))
break
return
if __name__ == "__main__":
print("Test on finding the upper bound of R(s,t)")
s = 10
t = 12
print("Inputs are "+str(s)+" and "+str(t))
upperBound(s, t)
|
# this module make socket server with listening port and accept connection and decode responses
from socket import *
import random
import os
import time
import handle_request
class MakeServer():
''' Template for Server object'''
def __init__(self,port=8080):
self.port=port
self.host='127.0.0.1'
self.sock_obj=''
def make_Socket(self):
'''making of socket with a port'''
self.sock_obj=socket(AF_INET,SOCK_STREAM)
try:
self.sock_obj.bind((self.host,self.port))
except :
print 'Default Port already in use changing port'
self.port=random.randint(9000,10000)
self.sock_obj.bind((self.host,self.port))
print'server adrrs {} with port {}'.format(self.host,self.port)
self.handle_Clients()
def handle_Clients(self):
''' handle clients request and connection multiple connections'''
while True:
self.sock_obj.listen(8)
cnt,addrs=self.sock_obj.accept()
print 'Received a connection with addrs :{}'.format(addrs)
if os.fork()==0:
request=cnt.recv(1024)
dec=bytes.decode(request)
print dec
data_to_client=handle_request.request_Parser(dec)
print 'Sending data to Browser or client'
cnt.send(data_to_client)
cnt.close()
os._exit(0)
else:
cnt.close()
if __name__ == '__main__':
abc=MakeServer()
abc.make_Socket()
|
from tkinter import *
from tkinter import filedialog as tkFileDialog
#from tkFileDialog import askopenfilename
import numpy as np
from utils import *
def NewFile(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
print ("New File!... (not implemented)")
return
Label(root, text="First Name").grid(row=0)
Label(root, text="Last Name").grid(row=1)
e1 = Entry(root)
e2 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
print (e1.text())
def Defaults(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
#******** Select CaImAn folder
def button00():
print ("...selecting caiman folder location...")
root.caiman_folder = tkFileDialog.askdirectory(initialdir=root.caiman_folder, title="Select CaImAn Root Directory")
print ("Changing caiman_folder to: ", root.caiman_folder)
np.savetxt('caiman_folder_location.txt',[root.caiman_folder], fmt="%s")
e0.delete(0, END)
e0.insert(0, root.caiman_folder)
b00 = Button(root, text="Set CaImAn Folder", anchor="w", command=button00) #Label(root, text="Filename: ").grid(row=0)
b00.place(x=0,y=0)
e0 = Entry(root, justify='left') #text entry for the filename
e0.delete(0, END)
e0.insert(0, root.caiman_folder)
e0.place(x=150,y=0, width=600)
#******** Filename Selector
def button0():
print ("...selecting data folder...")
root.data_folder = tkFileDialog.askdirectory(initialdir=root.data_folder, title="Select data directory")
np.savetxt('data_folder_location.txt',[root.data_folder], fmt="%s")
e.delete(0, END)
e.insert(0, root.data_folder)
#root.title(root.data_folder)
b0 = Button(root, text="Default data dir:", anchor="w", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.place(x=0, y=30)
e = Entry(root, justify='left') #text entry for the filename
e.delete(0, END)
e.insert(0, root.data_folder)
e.place(x=150,y=30, width=600)
def Tif_merge(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
print ("Merging tifs from list of filenames")
root.minsize(width=800, height=500)
root.data = emptyObject()
#******** Select filename:
def button0():
print ("...selecting .txt containing list of .tif files...")
#root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data.root_dir)
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension=".txt", filetypes=(("txt", "*.txt"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#root.title(os.path.split(root.data.file_name)[1])
b0 = Button(root, text="Filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0,column=0)
e1 = Entry(root, justify='left') #text entry for the filename
e1.delete(0, END)
e1.insert(0, '')
e1.grid(row=0, column=1)
e1.place(x=120,width=800)
def button1():
print ("...merging files from list: ", root.data.file_name)
merge_tifs(root.data.file_name)
#os.system("python ../CaImAn/demo_OnACID.py "+root.data.file_name)
print ("... done!")
#******** Run review ROIs function
b1 = Button(root, text="merge tifs", command=button1)
b1.grid(row=1, column=0)
def Louvain_modularity(root):
print ("...compute louvain modularity ...")
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
root.data = emptyObject()
root.data.file_name = ''
root.title("Louvain Modularity")
#******** Select filename:
def button0():
print ("...select threshold file from foopsi output...")
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension="*thr*.npz", filetypes=(("npz", "*.npz"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
root.title(os.path.split(root.data.file_name)[1])
b0 = Button(root, text="Foopsi filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0, column=0)
e1 = Entry(root) #text entry for the filename
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#e1.grid(row=0, column=2)
e1.place(x=150, y=3,width=800)
#******** Correct ROIs
def button1():
#correct_ROIs(root.data.file_name, root.data.A, root.data.Cn, thr=0.95)
louvain_compute(root)
b1 = Button(root, text="Run Louvain", command=button1, justify='left')
b1.place(x=0, y=30)
#******** Select filename:
def button00():
print ("...select network file post louvain...")
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension="*network*.npy", filetypes=(("npy", "*.npy"),("All Files", "*.*") ))
e2.delete(0, END)
e2.insert(0, root.data.file_name)
root.title(os.path.split(root.data.file_name)[1])
b00 = Button(root, text="Louvain filename: ", command=button00) #Label(root, text="Filename: ").grid(row=0)
#b00.grid(row=140,column=100)
b00.place(x=0,y=70)
e2 = Entry(root) #text entry for the filename
e2.delete(0, END)
e2.insert(0, root.data.file_name)
#e2.grid(row=15, column=15)
e2.place(x=150, y=73,width=800)
#******** Visualize Results
def button2():
print ("...loading processed file: ", root.data.file_name)
visualize_louvain(root)
b2 = Button(root, text="Visualize Louvain", command=button2, justify='left')
b2.place(x=0, y=100)
pass
def Tif_convert(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
print ("Converting tif to .npy")
root.minsize(width=800, height=500)
root.data = emptyObject()
#root.data.root_dir = '/media/cat/4TB/in_vivo/rafa/alejandro/G2M5/20170511/000/'
#root.data.file_name = '/media/cat/4TB/in_vivo/rafa/alejandro/G2M5/20170511/000/Registered.tif'
#******** Select filename:
def button0():
print ("...selecting file...")
#root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data.root_dir)
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension=".tif", filetypes=(("tif", "*.tif"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#root.title(os.path.split(root.data.file_name)[1])
b0 = Button(root, text="Filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0,column=0)
e1 = Entry(root, justify='left') #text entry for the filename
e1.delete(0, END)
e1.insert(0, '')
e1.grid(row=0, column=1)
e1.place(x=120,width=800)
def button1():
print ("...converting: ", root.data.file_name)
convert_tif_npy(root.data.file_name)
#os.system("python ../CaImAn/demo_OnACID.py "+root.data.file_name)
print ("... done!")
#******** Run review ROIs function
b1 = Button(root, text="convert tif->npy", command=button1)
b1.grid(row=1, column=0)
def Tif_sequence_load(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
print ("Loading .tif sequence")
print ("... buggy... not yet fixed...(tiffilfe seems to give errors...)")
return
root.minsize(width=1200, height=500)
root.data = emptyObject()
#******** Select filename:
def button0():
print ("...selecting file...")
#root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data.root_dir)
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension=".tif", filetypes=(("tif", "*.tif"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#root.title(os.path.split(root.data.file_name)[1])
b0 = Button(root, text="Filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0,column=0)
e1 = Entry(root, justify='left') #text entry for the filename
e1.delete(0, END)
e1.insert(0, '')
e1.grid(row=0, column=1)
e1.place(x=120,width=1200)
def button1():
print (e1.get())
root.data.file_name = e1.get()
print ("...loading: ", root.data.file_name)
load_tif_sequence(e1.get())
print ("... done!")
#******** Run review ROIs function
b1 = Button(root, text="Load tif sequence", command=button1)
b1.grid(row=1, column=0)
def Crop_rectangle(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
print ("Croping image")
root.minsize(width=800, height=500)
root.data = emptyObject()
#root.data.root_dir = '/media/cat/4TB/in_vivo/rafa/alejandro/G2M5/20170511/000/'
#root.data.file_name = '/media/cat/4TB/in_vivo/rafa/alejandro/G2M5/20170511/000/Registered.tif'
#******** Select filename:
def button0():
print ("...selecting file...")
#root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data.root_dir)
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension=".tif", filetypes=(("tif", "*.tif"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#root.title(os.path.split(root.data.file_name)[1])
b0 = Button(root, text="Filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0,column=0)
e1 = Entry(root, justify='left') #text entry for the filename
e1.delete(0, END)
e1.insert(0, '')
e1.grid(row=0, column=1)
e1.place(x=120,width=800)
def button1():
print ("...croping: ", root.data.file_name)
crop_image(root.data.file_name)
#os.system("python ../CaImAn/demo_OnACID.py "+root.data.file_name)
print ("... done!")
#******** Run review ROIs function
b1 = Button(root, text="Crop tif (or .npy)", command=button1)
b1.grid(row=1, column=0)
def Crop_arbitrary(root):
print ("... arbitrary crop not yet implemented ...")
def Caiman_online(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
#print '...text************'
root.minsize(width=1000, height=600)
root.data = emptyObject()
#root.data_folder root.data.root_dir = '/media/cat/4TB/in_vivo/rafa/alejandro/G2M5/20170511/000/'
root.data.file_name = ''
#root.caiman_folder = np.loadtxt('caiman_folder_location.txt',dtype=str)
#******** Filename Selector
def button0():
print ("...selecting file...")
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension=".tif", filetypes=(("tif", "*.tif"),("npy", "*.npy"),("All Files", "*.*") ))
print (root.data.file_name)
root.data_folder = os.path.split(root.data.file_name)[0]
np.savetxt('data_folder_location.txt',[root.data_folder], fmt="%s")
e.delete(0, END)
e.insert(0, root.data.file_name)
root.title(os.path.split(root.data.file_name)[1])
b0 = Button(root, text="Filename:", anchor="w", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.place(x=0, y=0)
e = Entry(root, justify='left') #text entry for the filename
e.delete(0, END)
e.insert(0, root.data.file_name)
e.place(x=110,y=4, width=600)
x_offset=0; y_offset=30
l00 = Label(root, text='_'*200)
l00.place(x=x_offset, y=y_offset, height=30, width=1000)
#******** CNMF Parameters ******************
#
x_offset = 0; y_offset=55
l0 = Label(root, text='CNMF Initialization Parameters', fg="red", justify='left')
l0.place(x=x_offset, y=y_offset, height=30, width=190)
#Param 1
x_offset=10; y_offset=+80
l1 = Label(root, text='Merge Threshold')
l1.place(x=x_offset,y=y_offset, height=30,width=100)
e1 = Entry(root, justify='left', width=4) #text entry for the filename
e1.delete(0, END)
e1.insert(0, 0.8)
e1.place(x=x_offset+103,y=y_offset+5)
x_offset+=140
##Param 2
#l2 = Label(root, text='Autoregress order')
#l2.place(x=x_offset,y=y_offset, height=30,width=130)
#e2 = Entry(root, justify='left', width=3) #text entry for the filename
#e2.delete(0, END)
#e2.insert(0, 1)
#e2.place(x=x_offset+120,y=y_offset+5)
#x_offset+=150
#Param 3
l3 = Label(root, text='Initial Batch')
l3.place(x=x_offset,y=y_offset, height=30,width=100)
e3 = Entry(root, justify='left', width=5) #text entry for the filename
e3.delete(0, END)
e3.insert(0, 20000)
e3.place(x=x_offset+88,y=y_offset+5)
x_offset+=145
#Param 4
l4 = Label(root, text='patch_size')
l4.place(x=x_offset,y=y_offset, height=30,width=100)
e4 = Entry(root, justify='left', width=3) #text entry for the filename
e4.delete(0, END)
e4.insert(0, 32)
e4.place(x=x_offset+85,y=y_offset+5)
x_offset+=160
#Param 5
l5 = Label(root, text='stride')
l5.place(x=x_offset,y=y_offset, height=30,width=40)
e5 = Entry(root, justify='left', width=3) #text entry for the filename
e5.delete(0, END)
e5.insert(0, 3)
e5.place(x=x_offset+38,y=y_offset+5)
x_offset+=100
#Param 6
l6 = Label(root, text='K')
l6.place(x=x_offset,y=y_offset, height=30,width=15)
e6 = Entry(root, justify='left', width=3) #text entry for the filename
e6.delete(0, END)
e6.insert(0, 4)
e6.place(x=x_offset+15,y=y_offset+5)
#***************************************************
#Recording Defaults
#NEW LINE
x_offset = 0; y_offset+=50
print (x_offset, y_offset)
l_1 = Label(root, text='Recording Defaults', fg="blue", justify='left')
l_1.place(x=x_offset, y=y_offset, height=30, width=120)
y_offset+=25
#Param 2
l7 = Label(root, text='frame_rate (hz)')
l7.place(x=x_offset,y=y_offset, height=30,width=110)
x_offset+=105
e7 = Entry(root, justify='left', width=4) #text entry for the filename
e7.delete(0, END)
e7.insert(0, 10)
e7.place(x=x_offset,y=y_offset+5)
#Param 3
x_offset+=30
l8 = Label(root, text='decay_time (s)')
l8.place(x=x_offset,y=y_offset, height=30,width=110)
x_offset+=100
e8 = Entry(root, justify='left', width=4) #text entry for the filename
e8.delete(0, END)
e8.insert(0, 0.5)
e8.place(x=x_offset,y=y_offset+5)
#Param 3
x_offset+=50
l9 = Label(root, text='neuron (pixels)')
l9.place(x=x_offset,y=y_offset, height=30,width=100)
x_offset+=100
e9 = Entry(root, justify='left', width=4) #text entry for the filename
e9.delete(0, END)
e9.insert(0, '6, 6')
e9.place(x=x_offset,y=y_offset+5)
#Param 3
x_offset+=40
l10 = Label(root, text='order AR dynamics')
l10.place(x=x_offset,y=y_offset, height=30,width=145)
x_offset+=135
e10 = Entry(root, justify='left', width=3) #text entry for the filename
e10.delete(0, END)
e10.insert(0, 1)
e10.place(x=x_offset,y=y_offset+5)
#Param
x_offset+=40
l11 = Label(root, text='min_SNR')
l11.place(x=x_offset,y=y_offset, height=30,width=65)
x_offset+=62
e11 = Entry(root, justify='left', width=4) #text entry for the filename
e11.delete(0, END)
e11.insert(0, 3.5)
e11.place(x=x_offset,y=y_offset+5)
#Param
x_offset+=40
l12 = Label(root, text='rval_thr')
l12.place(x=x_offset,y=y_offset, height=30,width=65)
x_offset+=60
e12 = Entry(root, justify='left', width=4) #text entry for the filename
e12.delete(0, END)
e12.insert(0, 0.90)
e12.place(x=x_offset,y=y_offset+5)
#Param
x_offset+=40
l13 = Label(root, text='# bkgr comp')
l13.place(x=x_offset,y=y_offset, height=30,width=105)
x_offset+=95
e13 = Entry(root, justify='left', width=4) #text entry for the filename
e13.delete(0, END)
e13.insert(0, 3)
e13.place(x=x_offset,y=y_offset+5)
#***************************************************
#Temporary Initalization Defaults
#NEW LINE
x_offset = 0; y_offset+=50
print (x_offset, y_offset)
l_1 = Label(root, text='Initialization Defaults', fg="green", justify='left')
l_1.place(x=x_offset, y=y_offset, height=30, width=140)
y_offset+=30
#Param
x_offset=0; x_width=120
l14 = Label(root, text='# updated shapes')
l14.place(x=x_offset,y=y_offset, height=30,width=x_width)
x_offset+=x_width
e14 = Entry(root, justify='left', width=4) #text entry for the filename
e14.delete(0, END)
e14.insert(0, 'inf')
e14.place(x=x_offset,y=y_offset+5)
#Param
x_offset+=45; x_width=125
l15 = Label(root, text='# expected shapes')
l15.place(x=x_offset,y=y_offset, height=30,width=x_width)
x_offset+=x_width
e15 = Entry(root, justify='left', width=4) #text entry for the filename
e15.delete(0, END)
e15.insert(0, 2000)
e15.place(x=x_offset,y=y_offset+5)
#Param
x_offset+=45; x_width=80
l16 = Label(root, text='# timesteps')
l16.place(x=x_offset,y=y_offset, height=30,width=x_width)
x_offset+=x_width
e16 = Entry(root, justify='left', width=4) #text entry for the filename
e16.delete(0, END)
N_samples = np.ceil(float(e7.get())*float(e8.get()))
e16.insert(0, N_samples)
e16.place(x=x_offset,y=y_offset+5)
#Param
from scipy.special import log_ndtr
x_offset+=45; x_width=140
l17 = Label(root, text='exceptionality thresh')
l17.place(x=x_offset,y=y_offset, height=30,width=x_width)
x_offset+=x_width
e17 = Entry(root, justify='left', width=5) #text entry for the filename
e17.delete(0, END)
e17.insert(0, log_ndtr(-float(e11.get()))*N_samples)
e17.place(x=x_offset,y=y_offset+5)
#Param
x_offset+=55; x_width=105
l18 = Label(root, text='total len of file')
l18.place(x=x_offset,y=y_offset, height=30,width=x_width)
x_offset+=x_width
e18 = Entry(root, justify='left', width=5) #text entry for the filename
e18.delete(0, END)
e18.insert(0, 'all')
e18.place(x=x_offset,y=y_offset+5)
y_offset+=30; x_offset=0
l000 = Label(root, text='_'*200)
l000.place(x=x_offset, y=y_offset, height=30, width=1000)
#********** COMMAND LINE OUTPUT BOX **********
tkinter_window = False #Redirect command line outputs to text box in tkinter;
if tkinter_window:
t = Text(root, wrap='word', height = 20, width=100)
t.place(x=10, y=250, in_=root)
#********* DEMO_ONACID BUTTON **********************
def button1(l):
l.config(foreground='red')
root.update()
#Save existing config file
np.savez(str(root.data.file_name)[:-4]+"_runtime_params", \
merge_thr=e1.get(), #merge threshold
initibatch = e3.get(), #Initial batch
patch_size=e4.get(), #patch size
stride=e5.get(), #stride
K=e6.get(), #K
frame_rate=e7.get(), #frame_rate
decay_time=e8.get(), #decay_time
neuron_size=e9.get(), #neuron size pixesl
AR_dynamics=e10.get(), #AR dynamics order
min_SNR=e11.get(), #min_SNR
rval_threshold = e12.get(), # rval_threshold
no_bkgr_components=e13.get(), # #bkground componenets
no_updated_shapes=e14.get(), # #udpated shapes
no_expected_shapes=e15.get(), # #expected shapes
no_timesteps=e16.get(), # #timesteps
exceptionality_threshold=e17.get(), # exceptionatliy threshold
total_len_file=e18.get(), # total len of file
caiman_location = str(root.caiman_folder)
)
print (type(str(root.caiman_folder)))
print (type(root.caiman_folder))
if tkinter_window:
import io, subprocess
#proc = subprocess.Popen(["python", "-u", "/home/cat/code/CaImAn/demo_OnACID.py", root.data.file_name], stdout=subprocess.PIPE)
proc = subprocess.Popen(["python", "-u", str(root.caiman_folder)+"/demo_OnACID_2.py", root.data.file_name], stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if line != '':
t.insert(END, '%s\n' % line.rstrip())
t.see(END)
t.update_idletasks()
sys.stdout.flush()
else:
break
else:
print ("python -u ")
print (root.caiman_folder)
#p = os.system("python -u "+str(root.caiman_folder)+"/demo_OnACID_2.py "+root.data.file_name)
print ("python -u "+str(root.caiman_folder)+"/demo_OnACID_2.py "+str(root.data.file_name))
p = os.system("python -u "+str(root.caiman_folder)+"/demo_OnACID_2.py "+str(root.data.file_name))
l = Label(root, textvariable='green', fg = 'red')
b1 = Button(root, text="demo_OnACID", foreground='blue', command=lambda: button1(l))
b1.place(x=0, y=y_offset+50, in_=root)
def Caiman_offline(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
print ("...caiman offline...(not implemented)")
print ("...Note: caiman online is currently running in caiman offline mode... ")
def Image_registration(root):
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
print ("... image registration...")
root.minsize(width=800, height=500)
root.data = emptyObject()
#******** Select filename:
def button0():
print ("...selecting file...")
#root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data.root_dir)
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension=".tif", filetypes=(("tif", "*.tif"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#root.title(os.path.split(root.data.file_name)[1])
b0 = Button(root, text="Filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0,column=0)
e1 = Entry(root, justify='left') #text entry for the filename
e1.delete(0, END)
e1.insert(0, '')
e1.grid(row=0, column=1)
e1.place(x=120,width=800)
def button1():
print ("...motion correcting: ", root.data.file_name)
motion_correct_caiman(root)
#******** Run review ROIs function
b1 = Button(root, text="motion correct", command=button1)
b1.grid(row=1, column=0)
class emptyObject():
def __init__(self):
pass
def Review_ROIs(root):
print ("...Review ROIs ...")
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
root.data = emptyObject()
root.data.file_name = ''
root.title("Review and Cleanup ROIs")
def load_data():
print ("...loading processed file: ", root.data.file_name)
#Update filename box
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#Load data
data_in = np.load(root.data.file_name, encoding= 'latin1', mmap_mode='c')
print (data_in.keys())
A = data_in['A'] #Convert array from sparse to dense
#print (A.shape)
#print (A[()].shape)
root.data.A = A[()].toarray()
print (root.data.A.shape)
root.data.Cn = data_in['Cn']
print (root.data.Cn.shape)
root.data.YrA = data_in['YrA']
print (root.data.YrA.shape)
print (root.data.YrA)
# plt.imshow(root.data.Cn)
#plt.show(block=True)
#print (root.data.A.shape)
root.data.Yr = data_in['Yr']
print (root.data.Yr.shape)
root.data.C = data_in['C']
root.data.b = data_in['b']
root.data.f = data_in['f']
save_traces(root.data.file_name, root.data.Yr, root.data.A, root.data.C, root.data.b, root.data.f, 250, 250, YrA = root.data.YrA, thr = 0.8,
image_neurons=root.data.Cn, denoised_color='red')
#******** Select filename:
def button0():
print ("...selecting file...")
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension="*processed.npz", filetypes=(("npz", "*processed.npz"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
root.title(os.path.split(root.data.file_name)[1])
load_data()
b0 = Button(root, text="Filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0,column=0)
e1 = Entry(root) #text entry for the filename
e1.delete(0, END)
e1.insert(0, root.data.file_name)
e1.grid(row=0, column=1)
e1.place(x=120,width=800)
#******** Correct ROIs
def button1():
print ("... running correct ROIs...")
correct_ROIs(root.data.file_name, root.data.A, root.data.Cn, thr=0.95)
b1 = Button(root, text="Review ROIs", command=button1, justify='left')
b1.place(x=0, y=50)
def Review_spikes(root):
print ("...Review spikes ...")
for k, ele in enumerate(root.winfo_children()):
if k>0: ele.destroy()
root.title("Review Spikes")
root.data = emptyObject()
root.data.file_name = ''
#******** Select ROI filename
def button0():
print ("...selecting ROI file...")
root.data.file_name = tkFileDialog.askopenfilename(initialdir=root.data_folder, defaultextension="ROIs.npz", filetypes=(("ROI", "*ROIs.npz"),("All Files", "*.*") ))
e1.delete(0, END)
e1.insert(0, root.data.file_name)
#load_data()
b0 = Button(root, text="Filename: ", command=button0) #Label(root, text="Filename: ").grid(row=0)
b0.grid(row=0,column=0)
e1 = Entry(root) #text entry for the filename
e1.delete(0, END)
e1.insert(0, root.data.file_name)
e1.place(x=120,y=5, width=800)
#********* Run foopsi
#Param 1
x_offset = 0; y_offset=50
l1 = Label(root, text='Foopsi Threshold')
l1.place(x=x_offset,y=y_offset, height=30,width=110)
x_offset+=125; y_offset+=5
e2 = Entry(root, justify='left', width=4) #text entry for the filename
e2.delete(0, END)
e2.insert(0, 2.0)
e2.place(x=x_offset,y=y_offset)
def button1():
print ("...running foopsi...")
root.data.foopsi_threshold = e2.get()
run_foopsi(root)
x_offset=0; y_offset=80
b1 = Button(root, text="Run Foopsi", command=button1)
b1.place(x=x_offset,y=y_offset)
#********* View rasters
def button2():
print ("...viewing rasters...")
root.data.foopsi_threshold = e2.get()
view_rasters(root)
y_offset+=70
b2 = Button(root, text="View all rasters", command=button2)
b2.place(x=x_offset,y=y_offset)
#********* View single neuron
def button2():
print ("...viewing trace...")
root.data.foopsi_threshold = e2.get()
root.data.neuron_id = int(e3.get())
view_neuron(root)
y_offset+=70
b2 = Button(root, text="View neuron", command=button2)
b2.place(x=x_offset,y=y_offset)
#x_offset+=100
#l2 = Label(root, text='Neuron #:')
#l2.place(x=x_offset,y=y_offset, height=30,width=110)
x_offset+=125; y_offset+=5
e3 = Entry(root, justify='left', width=4) #text entry for the filename
e3.delete(0, END)
e3.insert(0, 0)
e3.place(x=x_offset,y=y_offset)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 10:51:10 2020
Minimum Height Trees
Intuition: eat away the leaf nodes until only one or two nodes are remaining. The max number of min height trees is 2.
The leaf nodes can never be part of a min height tree if more than 2 nodes. Think about it like a physical tree where
the nodes are marbles tied together with string. The min height tree is the marble with the least length of string dangling.
This can never be the leaf nodes, so we remove them and keep trying to solve the smaller problem
@author: Robert Xu
"""
class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
if n == 1: return [0]
graph = {i:set() for i in range(n)}
for u, v in edges:
graph[u].add(v)
graph[v].add(u)
leaves = [i for i in graph if len(graph[i]) == 1]
while len(graph) > 2:
new_leaves = []
for leaf in leaves:
parent = graph.pop(leaf).pop()
graph[parent].remove(leaf)
if len(graph[parent]) == 1:
new_leaves.append(parent)
leaves = new_leaves
return [key for key in graph]
a = Solution()
b = a.findMinHeightTrees(6, [[0,1],[0,2],[0,3],[3,4],[4,5]])
|
count = 0;
increasing = True;
amp = 10;
dc = 1;
graph = "";
while True:
for i in range(0,count):
if count==amp and i == count-1:
graph = graph + "*";
elif increasing:
graph = graph + "\\";
elif not increasing:
graph = graph + "/";
print(graph);
graph = "";
count = count + dc;
if (count+dc) > amp:
increasing = False;
dc = -1;
elif (count+dc) <= 0:
increasing = True;
dc = 1;
|
# A program to check if the number is positive or negative
# PRE-REQUISITES
# 0 is neither positive or negative
# Let's tart with creating the find number is +ve or -ve or 0
def posORneg(num):
if (num == "q"):
return "Invalid or not Real"
elif (num > 0):
return "Positive"
elif (num < 0):
return "Negative"
elif (num == 0):
return "Zero"
else:
return "Invalid or not Real"
while True:
try:
user_input = float(input("Enter the number which you wish to check is +ve or -ve"))
except ValueError:
print("Invalid Input!!")
user_input = "q"
finally:
print("The number is ", posORneg(user_input))
|
class InvalidValues(Exception):
pass
def compare(str1, str2):
'''compare strings.
params:
str1 -- string version 1
str2 -- string version 2
the strings are a dot seperated integers.
return:
1 if str1 = str2
0 if str1 > str1
-1 if str1 < str2
raise invalidValues exception if non integers value provided
'''
try:
str_v1 = float(''.join(str1.split('.')).replace(' ', ''))
str_v2 = float(''.join(str2.split('.')).replace(' ', ''))
if str_v2 == str_v1 and len(str1) == len(str2):
return 1
elif str_v1 > str_v2 or len(str1) > len(str2):
return 0
else:
return -1
except Exception:
raise InvalidValues(
f'invalid params. can not compare {str1} to {str2}')
|
"""
https://realpython.com/python-sockets/#handling-multiple-connections
https://docs.python.org/3/howto/sockets.html
Now we come to the major stumbling block of sockets - send and recv operate on
the network buffers. They do not necessarily handle all the bytes you hand them
(or expect from them), because their major focus is handling the network
buffers. In general, they return when the associated network buffers have been
filled (send) or emptied (recv). They then tell you how many bytes they handled.
It is your responsibility to call them again until your message has been
completely dealt with.
In Python, you use socket.setblocking(False) to make it non-blocking. In C, it’s
more complex, (for one thing, you’ll need to choose between the BSD flavor
O_NONBLOCK and the almost indistinguishable POSIX flavor O_NDELAY, which is
completely different from TCP_NODELAY), but it’s the exact same idea. You do
this after creating the socket, but before using it. (Actually, if you’re nuts,
you can switch back and forth.)
The major mechanical difference is that send, recv, connect and accept can
return without having done anything. You have (of course) a number of choices.
You can check return code and error codes and generally drive yourself crazy. If
you don’t believe me, try it sometime. Your app will grow large, buggy and suck
CPU. So let’s skip the brain-dead solutions and do it right.
Use select.
If a socket is in the output readable list, you can be
as-close-to-certain-as-we-ever-get-in-this-business that a recv on that socket
will return something. Same idea for the writable list. You’ll be able to send
something. Maybe not all you want to, but something is better than nothing.
(Actually, any reasonably healthy socket will return as writable - it just means
outbound network buffer space is available.)
But if you plan to reuse your socket for further transfers, you need to realize
that there is no EOT on a socket. I repeat: if a socket send or recv returns
after handling 0 bytes, the connection has been broken. If the connection has
not been broken, you may wait on a recv forever, because the socket will not
tell you that there’s nothing more to read (for now). Now if you think about
that a bit, you’ll come to realize a fundamental truth of sockets: messages must
either be fixed length (yuck), or be delimited (shrug), or indicate how long
they are (much better), or end by shutting down the connection. The choice is
entirely yours, (but some ways are righter than others).
-----
https://medium.com/vaidikkapoor/understanding-non-blocking-i-o-with-python-part-1-ec31a2e2db9b
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 1234))
sock.setblocking(0)
data = 'foobar\n' * 10 * 1024 * 1024 # 70 MB of data
assert sock.send(data) == len(data) # AssertionError
When you run the above client, you will notice that it did not block at all. But
there is a problem with the client — it did not send all the data. socket.send
method returns the number of bytes sent. When you make a socket non-blocking by
calling setblocking(0), it will never wait for the operation to complete. So
when you call the send() method, it will put as much data in the buffer as
possible and return. As this is read by the remote connection, the data is
removed from the buffer. If the buffer gets full and we continue to send data,
socket.error will be raised. When you try to send data more than the buffer can
accommodate, only the amount of data that can be accommodated is actually sent
and send() returns the number of bytes sent. This is useful so that we can try
to send the remaining data when the buffer becomes empty. Let’s try to achieve
that:
-----
When accepting connection, set socket to non-blocking mode and register client
socket with selector. In loop, call select and wait for server socket that's
ready to accept new connection, or client socket that's ready for writing or
reading.
Ready for writing means that outbound network buffer, write buffer, has space
available, because it was empty to begin with, or it was previously full, but
client has read data from it and now we can write more data to it. If it's full
and we try to write to it, a socket.error would be raised, but we don't need to
worry about this, because again, select ensures there's space in the outbound
write buffer. Maybe it's even totally empty.
Ready for reading means that inbound network buffer, read buffer, is NOT EMPTY,
i.e. there's at least something in it you can read that was written to the
buffer by the other end of the connection. Default buffer size for network
socket buffer is 8kb, which is not so big that you waste memory, and not so
small that you're calling send and recv too frequently.
When we get a connection, call an async function that yields immediately. Resume
it once there is data ready to read in recv buffer, and pass in the data. This
function should call an async handler that returns a response string or bytes,
then we yield again. Once there is empty space in send buffer, proceed to write
all of response string to write buffer.
Do this with several functions at once, and make sure async handler can do
things like sleep, etc. Now I'm getting closer to an async web server that can
serve a bunch of connections on a single thread.
"""
import selectors
import socket
import sys
import types
from typing import cast
sel = selectors.DefaultSelector()
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
port = int(sys.argv[1]) # Port to listen on (non-privileged ports are > 1023)
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((HOST, port))
# The argument to listen tells the socket library that we want it to
# queue up as many as 5 connect requests (the normal max) before refusing
# outside connections. If the rest of the code is written properly, that should
# be plenty.
lsock.listen(5)
print("listening on", (HOST, port))
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)
def accept_connection(sock: socket.socket):
"""
Accept connection on "server" socket
"""
# This call blocks, but "server" socket is ready for reading
conn, addr = sock.accept()
# We call accept on "server" socket, We get a "client" socket `conn` that we
# can write to and read from to communicate with client, it represents
# connection between client and server
print("accepted connection from", addr) # This is address of the client
conn.setblocking(False)
data = types.SimpleNamespace(addr=addr, inb=b"", outb=b"")
# https://realpython.com/python-bitwise-operators/#overview-of-pythons-bitwise-operators
sel.register(conn, selectors.EVENT_READ | selectors.EVENT_WRITE, data=data)
def service_connection(key: selectors.SelectorKey, mask: int):
"""
Read data from client socket
"""
sock = cast(socket.socket, key.fileobj)
data = key.data
if mask & selectors.EVENT_READ:
# Socket is ready for reading
recv_data = sock.recv(1024)
if recv_data:
data.outb += recv_data
else:
print("closing connection to", data.addr)
sel.unregister(sock)
sock.close()
if mask & selectors.EVENT_WRITE:
if data.outb:
print(f"echoing {data.outb} to {data.addr}")
# Socket is ready for writing; should always be the case with a healthy socket
sent = sock.send(data.outb)
# Remove number of bytes sent from send buffer
data.outb = data.outb[sent:]
# Event loop
while True:
events = sel.select(timeout=None)
for key, mask in events:
if key.data is None:
# Event is from listening "server" socket; accept connection and create client socket
accept_connection(cast(socket.socket, key.fileobj))
else:
# Event is from client socket that's already been accepted
service_connection(key, mask)
|
# https://snarky.ca/how-the-heck-does-async-await-work-in-python-3-5/
# Let's summarize all of this into simpler terms. Defining a method with async
# def makes it a coroutine. The other way to make a coroutine is to flag a
# generator with types.coroutine -- technically the flag is the
# CO_ITERABLE_COROUTINE flag on a code object -- or a subclass of
# collections.abc.Coroutine. You can only make a coroutine call chain pause with
# a generator-based coroutine.
# An awaitable object is either a coroutine or an object that defines
# __await__() -- technically collections.abc.Awaitable -- which returns an
# iterator that is not a coroutine. An await expression is basically yield from
# but with restrictions of only working with awaitable objects (plain generators
# will not work with an await expression). An async function is a coroutine that
# either has return statements -- including the implicit return None at the end
# of every function in Python -- and/or await expressions (yield expressions are
# not allowed). The restrictions for async functions is to make sure you don't
# accidentally mix and match generator-based coroutines with other generators
# since the expected use of the two types of generators are rather different.
import asyncio
from itertools import cycle
from typing import Iterator
def endless():
"""Yields 9, 8, 7, 6, 9, 8, 7, 6, ... forever"""
yield from cycle((9, 8, 7, 6))
def _endless():
idx = 0
nums = [9, 8, 7, 6]
while True:
yield nums[idx % 4]
idx += 1
e = _endless()
total = 0
for i in e:
if total < 100:
print(i, end=" ")
total += i
else:
print()
# Pause execution. We can resume later.
break
# Resume
next(e), next(e), next(e)
def lazy_range(up_to: int):
"""
Generator to return the sequence of integers from 0 to up_to, exclusive.
"""
index = 0
while index < up_to:
yield index
index += 1
def jumping_range(up_to: int):
"""
Generator for the sequence of integers from 0 to up_to, exclusive.
Sending a value into the generator will shift the sequence by that amount.
"""
index = 0
while index < up_to:
sent = yield index
jump = 0
if sent is None:
jump = 1
if type(sent) is int:
jump = sent
if type(sent) is tuple:
jump, new_index = sent
index = new_index
index += jump
def yield_from(gen: Iterator):
yield from gen
def bt():
yield 10
return 20
def tp():
v = yield from bt()
yield v + 1
return v + 1
g = tp()
next(g)
next(g)
next(g)
def bottom():
# Returning the yield lets the value that goes up the call stack from top->middle->bottom come back down bottom->middle->top
v = yield 42
print("bottom got", v, "returned", v * 2)
return v * 2
def middle():
v = yield from bottom()
print("middle got", v, "returned", v * 2)
return v * 2
def top():
v = yield from middle()
print("top got", v, "returned", v * 2)
return v * 2
g = top()
next(g)
# Here we send a value into the bottom generator, the one yielded by middle, which is yielded by top; when bottom generator exhausted (StopIteration raised), v * 2 is returned to middle; middle generator also exhausted here, so (v * 2) * 2 returned to top; top also exhausted, so StopIteration raised with ((v * 2) * 2) * 2
g.send(100)
# This is a generator-based coroutine (it's deprecated)
@asyncio.coroutine
def py34_coro(gen: Iterator):
yield from gen
g = tp()
cr = py34_coro(g)
next(cr)
# This is a coroutine
async def py35_coro(gen):
await gen
g = tp()
cr = py34_coro(g)
next(cr) # Not permitted, 'coroutine' object is not an iterator
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
class RidgeRegressor(object):
"""
Linear Least Squares Regression with Tikhonov regularization.
More simply called Ridge Regression.
We wish to fit our model so both the least squares residuals and L2 norm
of the parameters are minimized.
argmin Theta ||X*Theta - y||^2 + alpha * ||Theta||^2
A closed form solution is available.
Theta = (X'X + G'G)^-1 X'y
Where X contains the independent variables, y the dependent variable and G
is matrix alpha * I, where alpha is called the regularization parameter.
When alpha=0 the regression is equivalent to ordinary least squares.
http://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)
http://en.wikipedia.org/wiki/Tikhonov_regularization
http://en.wikipedia.org/wiki/Ordinary_least_squares
"""
def fit(self, X, y, alpha=0):
"""
Fits our model to our training data.
Arguments
----------
X: mxn matrix of m examples with n independent variables
y: dependent variable vector for m examples
alpha: regularization parameter. A value of 0 will model using the
ordinary least squares regression.
"""
#X = np.hstack((np.ones((X.shape[0], 1)), X))
G = np.eye(X.shape[1])
G[0, 0] = 0 # Don't regularize bias
self.params = np.dot(np.linalg.inv(np.dot(X.T, X) + (alpha *np.dot(G.T, G))),
np.dot(X.T, y))
def predict(self, X):
"""
Predicts the dependent variable of new data using the model.
The assumption here is that the new data is iid to the training data.
Arguments
----------
X: mxn matrix of m examples with n independent variables
alpha: regularization parameter. Default of 0.
Returns
----------
Dependent variable vector for m examples
"""
#X = np.hstack((np.ones((X.shape[0], 1)), X))
return np.dot(X, self.params)
if __name__ == '__main__':
# Create synthetic data
X = np.load('X_all_orient-k=15.np.npy')
y = np.load ('YY-sigma1-6.npy')
#xtest=np.load('Xflos-k=15.npy')
#V= np.load('Vtest15.npy')
xtest=np.load('Xb=15.npy')
#V= np.load('Vim-k=15.npy')
# Plot synthetic data
# Create feature matrix
"""tX = np.array([X]).T
tX = np.hstack((tX, np.power(tX, 2), np.power(tX, 3)))
"""
# Plot regressors
r = RidgeRegressor()
#r.fit(X, y)
#print (r.params)
print ("\n\n")
# plt.plot(X, r.predict(X), 'b', label=u'ŷ (alpha=0.0)')
alpha = 0.1
r.fit(X, y, alpha)
#plt.plot(X, r.predict(X), 'y', label=u'ŷ (alpha=%.01f)' % alpha)
w_0 = r.params
np.save('w_lamd0_kamen15.npy', w_0)
print (w_0)
print ("\n\n")
w = r.predict(xtest)
"""
ww =[]
for i in range(len(V)):
ww.append(np.dot(w_0.T, V[i]))
"""
print (np.sum(w))
#print np.sum(ww), "la valeur de WW"
print ("\n\n")
print np.sum(y)
#wflos = np.dot(xtest,w_0)
#print (np.sum(wflos))
#plt.legend()
#plt.show()
|
import json
# Encoding data and writing in json file
car_data = {"Name" : "Renault", "Country" : "France"} # Dictionary
# Testing code
for i in enumerate(car_data.items()):
print(i)
print(car_data.get("Name"))
# Finding out data type
print(type(car_data))
# Creating JSON object- json.dumps changes python dict to json str
# Just to illustrate theory
car_data_json_string = json.dumps(car_data)
# Data type has changing
print(type(car_data_json_string))
# Create JSON file with writing permision - W = write. Column aliasing at end
with open("new_json_file.json", "w") as jsonfile:
# Dump method takes two args. First one is dictionary created. Second is the file object
json.dump(car_data, jsonfile)
# Encoding and creating into JSON file. Car_data converted into string by
# Decoding
with open("new_json_file.json") as jsonfile:
# Reading from file I just created
# Storing data from file to car variable. This is parsing
car = json.load(jsonfile)
# Checking/testing data
print(type(car))
print(car["Name"])
# Different dictionary method for practice
print(car.get("Country"))
# Playing around
# jsonfile = json.dumps(car_data, indent = 4, seperators = ("."))
# print(jsonfile)
|
import time
import random
print('*'*65)
print('Hullo, hullo. I am Magic Eight Ball. Ask me anything!')
print()
question = input('What would you like to know? ')
time.sleep(0.7)
print('Shaking!')
time.sleep(0.7)
print("I'm thinking...")
time.sleep(0.7)
print("I'm still thinking...")
time.sleep(0.7)
choice = random.randint(1,6)
if choice == 1:
print('Why are you asking me?')
elif choice == 2:
print('Just google it.')
elif choice == 3:
print('No u.')
elif choice == 4:
print("I don't know, figure it out yourself.")
elif choice == 5:
print("Eh, maybe. Don't ask me, I don't know everything.")
else:
print('Ye.')
print('-'*65)
|
def bestSum(target, array, memo={}):
if target==0: return []
if target<0: return None
try: return memo[target]
except KeyError:
shortest_combination = None
for number in array:
reminder=target-number
reminder_result=bestSum(reminder,array, memo)
if (reminder_result) is not None:
new_array= reminder_result
new_array.append(number)
shortest_combination= new_array
if len(new_array) <= len(shortest_combination):
shortest_combination=new_array
memo[target]=shortest_combination
return shortest_combination
if __name__== '__main__':
print(bestSum(100, [1,100,50]))
|
n = int(input())
capacity = 255
for i in range(n):
liters = int(input())
if liters <= capacity:
capacity -= liters
else:
print("Insufficient capacity!")
print(255-capacity)
|
text = input().split()
total = 0
sum_total = 0
for word in text:
number = int(word[1:-1])
if word[0].isupper():
total = number / (ord(word[0]) - 64)
else:
total = number * (ord(word[0]) - 96)
if word[-1].isupper():
total -= (ord(word[-1]) - 64)
else:
total += (ord(word[-1]) - 96)
sum_total += total
print(f"{sum_total:.2f}")
|
energy = 100
coins = 100
events = input().split("|")
is_closed = False
for event in events:
event_list = event.split("-")
name = event_list[0]
num = int(event_list[1])
if name == "rest":
if energy + num >= 100:
print(f"You gained {100-energy} energy.")
energy = 100
else:
print(f"You gained {num} energy.")
energy += num
print(f"Current energy: {energy}.")
elif name == "order":
if energy >= 30:
energy -= 30
coins += num
print(f"You earned {num} coins.")
else:
energy += 50
print("You had to rest!")
else:
coins -= num
if coins > 0:
print(f"You bought {name}.")
else:
print(f"Closed! Cannot afford {name}.")
is_closed = True
break
if not is_closed:
print("Day completed!")
print(f"Coins: {coins}")
print(f"Energy: {energy}")
|
text = input().split()
first = text[0]
second = text[1]
total = 0
i = 0
while i < min(len(first), len(second)):
total += ord(first[i]) * ord(second[i])
i += 1
if len(first) > len(second):
while i < len(first):
total += ord(first[i])
i += 1
elif len(second) > len(first):
while i < len(second):
total += ord(second[i])
i += 1
print(total)
|
resources = {}
command = input()
while command != "stop":
value = int(input())
if command not in resources:
resources[command] = value
else:
resources[command] += value
command = input()
for key, value in resources.items():
print(f"{key} -> {value}")
|
fires = input().split("#")
water = int(input())
cells = []
effort = 0
for fire in fires:
individual_fire = fire.split(" = ")
if (individual_fire[0] == "High" and 81 <= int(individual_fire[1]) <= 125) or (individual_fire[0] == "Medium" and 51 <= int(individual_fire[1]) <= 80) or (individual_fire[0] == "Low" and 1 <= int(individual_fire[1]) <= 50):
if water >= int(individual_fire[1]):
cells.append(int(individual_fire[1]))
water -= int(individual_fire[1])
effort += 0.25*int(individual_fire[1])
print("Cells:")
for i in cells:
print("-", str(i))
print(f"Effort: {effort:.2f}")
print("Total Fire:", str(sum(cells)))
|
def palindrome(list1):
for num in list1:
n = len(num)
half = n // 2
is_palindrome = True
for i in range(half):
if num[i] != num[-(i+1)]:
is_palindrome = False
if is_palindrome:
print("True")
else:
print("False")
my_list = input().split(", ")
palindrome(my_list)
|
quantity = int(input())
days = int(input())
i = 0
spirit = 0
budget = 0
count_days = days
while count_days > 0:
i += 1
if i % 11 == 0:
quantity += 2
if i % 2 == 0:
budget += quantity * 2
spirit += 5
if i % 3 == 0:
budget += quantity*8
spirit += 13
if i % 5 == 0:
budget += quantity*15
spirit += 17
if i % 3 == 0:
spirit += 30
if i % 10 == 0:
spirit -= 20
budget += 23
count_days -= 1
if days % 10 == 0:
spirit -= 30
print(f"Total cost: {budget}")
print(f"Total spirit: {spirit}")
|
command = input()
courses = {}
while command != "end":
course_name, student_name = command.split(" : ")
if course_name not in courses:
courses[course_name] = {"count": 0, "names": []}
courses[course_name]["names"].append(student_name)
courses[course_name]["count"] += 1
command = input()
courses = dict(sorted(courses.items(), key=lambda x: x[1]["count"], reverse=True))
for key, value in courses.items():
print(f"{key}: {value['count']}")
names_list = []
for name in value['names']:
names_list.append(name)
names_list.sort()
for name in names_list:
print(f"-- {name}")
|
command = input()
participants = {}
languages = {}
while command != "exam finished":
command_list = command.split("-")
username = command_list[0]
if command_list[1] == "banned":
del participants[username]
else:
language = command_list[1]
points = int(command_list[2])
if username in participants:
if points > participants[username]:
participants[username] = points
else:
participants[username] = points
if language in languages:
languages[language] += 1
else:
languages[language] = 1
command = input()
participants = dict(sorted(participants.items(), key=lambda x: x[0]))
languages = dict(sorted(languages.items(), key=lambda x: x[0]))
participants = dict(sorted(participants.items(), key=lambda x: x[1], reverse=True))
languages = dict(sorted(languages.items(), key=lambda x: x[1], reverse=True))
print("Results:")
for key, value in participants.items():
print(f"{key} | {value}")
print("Submissions:")
for key, value in languages.items():
print(f"{key} - {value}")
|
numbers = input().split(", ")
numbers_int = [int(x) for x in numbers]
d = 0
collection = []
while numbers_int:
collection.clear()
d += 10
for i in numbers_int:
if i <= d:
collection.append(i)
for j in collection:
numbers_int.remove(j)
print(f"Group of {d}'s: {collection}")
|
num_people = int(input("how many people are there "))
num_pizza = input("how many pizzas are there ")
slices_per_pizza = int(input("how many slices are there "))
cost_per_pizza = float(input("how much does each pizza cost "))
total_slices = num_pizza * slices_per_pizza
slices_per_person = total_slices / num_people
print(f"there are (slices_per_person:.1f) slices per person")
|
import datetime
class Activity(object):
'''
This class represents an activity event created from 2 sensor_logs
'''
daytime_start = datetime.time(6, 30)
daytime_end = datetime.time(21, 30)
def __init__(self, uuid=None, start_datetime=None, end_datetime=None, start_log=None, end_log=None):
'''
Constructor, object can be created either by passing all params except start_log and end_log.
or by passing only start_log and end_log
Inputs:
uuid (str) -- (default None)
start_datetime (datetime) -- datetime obj (default None)
end_datetime (datetime) -- datetime obj (default None)
start_log (Entities.sensor.log) -- g class obj (default None)
end_log (Entities.sensor_log) -- Entities.log class obj (default None)
'''
if start_log == None and end_log == None: # No logs given, use start and end datetime params
self.uuid = uuid
self.start_datetime = start_datetime
self.end_datetime = end_datetime
self.seconds = (self.end_datetime - self.start_datetime).total_seconds()
else:
self.uuid = start_log.uuid
self.start_datetime = start_log.recieved_timestamp
self.end_datetime = end_log.recieved_timestamp
self.seconds = (self.end_datetime - self.start_datetime).total_seconds()
def in_daytime(self):
'''
Returns True if Activity is anywhere within the daytime period set of 06.30 > 21.30
'''
obj_start = self.start_datetime.time()
obj_end = self.end_datetime.time()
if obj_start >= Activity.daytime_start and obj_start <= Activity.daytime_end:
return True
elif obj_end >= Activity.daytime_start and obj_start <= Activity.daytime_end:
return True
else:
return False
def __str__(self):
'''
Returns str representation of object
'''
return f"ACTIVITY: uuid: {self.uuid}, secs: {self.seconds}, start_ts: {self.start_datetime.strftime('%Y-%m-%d %H:%M:%S')}, end_ts: {self.end_datetime.strftime('%Y-%m-%d %H:%M:%S')}"
def __repr__(self):
'''
Override python built in function to return string prepresentation of oject
'''
return self.__str__()
|
""" This is an example of singleton in Python"""
import threading
import factory_method as fm
from abc import ABC
class PetCache(ABC):
"""Represents the cache for pets
"""
current_instance = None
lock = threading.Lock()
def __init__(self):
self.items = dict()
super().__init__()
def AddPet(self, pet):
self.items[pet] = pet
@staticmethod
def Current():
if PetCache.current_instance is not None:
return PetCache.current_instance
# lock all thread before creating the object.
PetCache.lock.acquire()
try:
# double check lock pattern
if PetCache.current_instance is None:
PetCache.current_instance = PetCache()
finally:
PetCache.lock.release()
return PetCache.current_instance
def Show(self):
for i in self.items:
print(i)
def main():
c1 = PetCache.Current()
c2 = PetCache.Current()
c1.AddPet(fm.Cat("cat1"))
c2.AddPet(fm.Dog("dog1"))
c1.Show()
c2.Show()
pass
if __name__ == "__main__":
main()
|
import turtle as t
colors = [ "orange" , "red" , "pink" , "yellow" , "blue" , "green" ,"purple" , "brown"]
for x in range (360):
t.pencolor(colors[x % 8])
t.width(x / 5 + 1 )
t.forward(x)
t.left(20)
|
# Pythono3 code to rename multiple
# files in a directory or folder
# importing os module
import os
# Function to rename multiple files
def main():
i = 0
parent_dir = os.getcwd()
j = 1
dir_name = 'C:/Users/kumar_vaibhav/PycharmProjects/Object_Detection/Images/'
for filename in os.listdir(dir_name):
# print(filename)
src = "NoObject" + str(i) + ".jpg"
dst = "test" + str(j) + ".jpg"
# dst = 'xyz' + dst
# rename() function will
# rename all the files
os.rename(os.path.join(dir_name,filename),os.path.join(dir_name,dst))
# os.rename(os.path.join(dir_name, src), os.path.join(dir_name, dst))
i += 2
j += 1
print("File rename done.")
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
|
import random
while True:
print("make your choice:")
choice = input()
choice = choice.lower()
print("my choice is:", choice)
choices = ['rock','paper','scissors']
computerChoice = random.choice(choices)
print("computer choice is:", computerChoice)
choiceDict = {'rock': 0, 'paper': 1, 'scissors': 2}
choiceIndex = choiceDict.get(choice,3)
computerIndex = choiceDict.get(computerChoice)
resultMatrix = [[0,2,1],
[1,0,2],
[2,1,0],
[3,3,3]
]
resultIdx= resultMatrix[choiceIndex][computerIndex]
resultMessage = ['it is a tie','you win','you lose','invalid choicerock']
result = resultMessage[resultIdx]
print(result)
print()
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#sigmoid function
def sigmoid(z):
return 1/(1+np.exp(-z))
#finding the gradient of the cost function at given weights
def grad(x,y,t):
m=y.size
gradient = np.transpose(1/m*np.matmul(np.transpose(sigmoid(np.matmul(x,t))-y),x))
return gradient
#cost function to calculate the loss of the model
def cost(x,y,t):
return -np.sum(y*np.log10(sigmoid(np.matmul(x,t)))+(1-y)*np.log10(1-sigmoid(np.matmul(x,t))))
#loading the training set
dataset = pd.read_csv('data.txt',delimiter=',',header=None)
X = dataset.iloc[:,:-1].values
X = np.insert(X,0,1,axis=1)
Y = dataset.iloc[:,-1].values.reshape(X.shape[0],1)
#training the model with learning rate 1
np.random.seed(1)
w = np.random.rand(X.shape[1],1)
loss = np.zeros(1000)
for epoch in range(1000):
w=w-grad(X,Y,w)
loss[epoch]=cost(X,Y,w)
#ploting the convergence curve
plt.plot(range(1000),loss)
plt.xlabel('No of iterations')
plt.ylabel('Cost')
plt.title('Convergence')
plt.show()
#loading the test set
test_set = pd.read_csv('test_data.txt',delimiter=',',header=None)
X_test = test_set.iloc[:,:-1].values
X_test = np.insert(X_test,0,1,axis=1)
Y_test = test_set.iloc[:,-1].values.reshape(X_test.shape[0],1)
print('Expected ans:')
print(np.transpose(Y_test))
print('Predicted ans:')
#predicting the outcome of training set
ans=sigmoid(np.matmul(X_test,w))
print(np.transpose(np.round(ans)))
|
def listToString(s):
# initialize an empty string
str1 = " "
# return string
return (str1.join(s))
# Driver code
str1 = " "
s = ['Geeks', 'for', 'Geeks']
print(str1.join(s))
|
# Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
def adjacentElementsProduct(inputArray):
# initializing i
i = 0
# create a variable and setting it to the product of the first pair
maxSoFar = inputArray[i] * inputArray[i+1]
# loop through each element, except the final one
for i in range(len(inputArray)-1):
# multiply each element by the one after it
product = inputArray[i] * inputArray[i+1]
# if it is larger, set maxSoFar to the new product
if product > maxSoFar:
maxSoFar = product
# after the loop runs you will have the highest product
return maxSoFar
# Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n.
# A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below.
def shapeArea(n):
initialArea = 1
return initialArea + (n * (n - 1) * 2)
# Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.
# arrange smallest to largest
# each statue will be bigger than previous by 1
# what is missing from statue array?
# [6, 2, 3, 8]
# sort
# [2, 3, 6, 8]
# check if each one is one greater
# if it is not one greater return what the number missing
# Solution 1 -
def makeArrayConsecutive2(statues):
# 8 - 2 + 1 = 7 - 4 = 3
return (max(statues)-min(statues)+1) - len(statues)
# Solution 2
def makeArrayConsecutive2(statues):
# sorting array from least to greatest
statues.sort()
# loops from 0 - second to last element
firstLoop = 0
# loops from 1 to the last element
secondLoop = 1
lastItem = len(statues)-1
# diff var keeps track of the number of statues needed to fill between two consecutive numbers (see while loop)
differences = 0
# records number of statues that can go in-between every adjacent pair
while (firstLoop <= lastItem - 1) and (secondLoop <= lastItem):
# if the difference between two consecutive numbers is more than 1
if statues[secondLoop] - statues[firstLoop] > 1:
differences += (statues[secondLoop] - statues[firstLoop] - 1)
# increment fl and sl as they continue the loop
firstLoop += 1
secondLoop += 1
return differences
# Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
# Note: sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. Sequence containing only one element is also considered to be strictly increasing.
# iterate through array
# removed item and see if the array is increasing
# if it is
# return true
# if it cannot keep going to the end
# return false
# JS SOLUTION
"""
function almostIncreasingSequence(sequence) {
var count = 0;
for(i = 0; i < sequence.length; i++) {
if(sequence[i] <= sequence[i-1]) {
count++;
if(sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1])
return false;
}
}
if (count <= 1) {
return true
} else {
return false
}
}
"""
|
# Ammon S Mugimu
# Uber Career Prep 2019
# Assignment-1
# Question 1.
# Time complexity: O(M + N)
# Space complexity O(M)
def isStringPermution(s1, s2):
if not s1 or not s2:
return False
elif type(s1) != str or type(s2) != str or len(s1) != len(s2):
return False
char_dict = dict()
# Populate dictionary with character counts from s1.
for char in s1:
if char not in char_dict:
char_dict[char] = 1
else:
char_dict[char] += 1
# Iterate over s2, checking dictionary for similar characters.
for char in s2:
if char not in char_dict:
return False
else:
current_char_count = char_dict[char]
if current_char_count > 0:
char_dict[char] -= 1
else:
return False
# If no edge case has been reached by this point, the strings are permutations.
return True
# Question 2.
# Time complexity: O(N)
# Space complexity O(N)
# The algorithm is bulletproofed to handle undefined arguments, types, empty
# arrays, and ignores variables in the input_array that are not integers.
# Further, Negative and non-unique values are assumed to be possible.
def partsThatEqualSum(input_array, target_sum):
if not input_array or not target_sum:
return []
elif type(input_array) != list or type(target_sum) != int or len(input_array) == 0:
return []
num_dict = dict()
for num in input_array:
if type(num) == int:
if num not in num_dict:
num_dict[num] = 1
else:
num_dict[num] += 1
pair_array = []
for num in input_array:
if type(num) == int:
target_value = target_sum - num
if target_value in num_dict:
if target_value == num:
if num_dict[target_value] >= 2:
pair_array.append((num, target_value))
elif num_dict[target_value] > 0:
pair_array.append((num, target_value))
num_dict[target_value] -= 1
num_dict[num] -= 1
return pair_array
|
#!/usr/bin/python3
#Capiturar dois niumetoas no teminal
# e escrever a soma dos dos
# Se o numero resultante da soma for maior que 100
# Escrever: "Que numero grandao...."
#Caso conrtrario: "Que numero pequeno....."
# Se o numero for igual a 50, escrever "....."
texto_grotesco = 'Por conseguinte, o novo modelo estrutural aqui preconizado nos obriga à análise das condições financeiras e \
administrativas exigidas. Ainda assim, existem dúvidas a respeito de como o surgimento do comércio irtual faz parte de um processo de \
gerenciamento das regras de conduta normativas. Neste sentido, a execução dos pontos do programa exige a precisão e a definição do fluxo de informações.'
nomes = ['Hector', 'Guilherme', 'Joel', 'Flávio', 'Fabiano', 'Roger', 'Cícero', 'Hugo', 'Ayron', 'Leonel', 'Pedro', 'Lucas']
#verificar se a palavra "virtual" está dentro do texto_groptesco
#Exibir apenas os 4 ultimos nomes
#.split() contar quantas palavbras tem no texto_grotesco
#exit()
#num1 = input('Digite o primeiro numero: ')
#num2 = input('Digite o segundo numero: ')
#soma = int(num1) + int(num2)
#if soma > 100:
# print('Que numero grandao.....!')
#elif soma == 50:
# print('...')
#else:
# print('Que numeo pequeno....!')
#rint(nomes[-4:])
#Percorrer a linsta nomes e exibir apenas os nomes que começasm com a letra F e H
for i in nomes:
if i[0] == 'F' or i[0] == 'H':
print(i)
|
#Give clues (unknown)
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
print("Guess the Word!\nYou get 3 guesses. Good luck!\n")
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("\nOut of guesses, YOU LOSE!\nThe word was \"giraffe\"")
else:
print("\nCongrats! You win!")
input('\nPress Enter to leave the program')
|
r = 'S'
c = 0
while r == 'S':
n = int(input('Digite um valor: '))
r = str(input('Quer continuar? [S/N]: ')).upper()
c = c +1
print('Houve {} repetições.'.format(c-1))
print('Fim')
|
print('{:-^40}'.format('LOJA SUPER BARATÃO'))
precoT = maior1000 = menorpreco = cont = 0
barato = ' '
while True:
prod = str(input('Nome do Produto: ')).upper().strip()
preco = float(input('Preço R$ '))
cont += 1
precoT += preco
if preco > 1000:
maior1000 += 1
'''if cont == 1:
menorpreco = preco
barato = prod
else:
if preco < menorpreco:
menorpreco = preco
barato = prod'''
if cont == 1 or preco < menorpreco:
menorpreco = preco
barato = prod
status = ' '
while status not in 'SN':
status = str(input('Quer Continuar? [S/N]: ')).upper().strip()[0]
if status == 'N':
break
print('{:-^40}'.format('FIM DO PROGRAMA'))
print(f'O total da compra foi R$ {precoT:.2f}')
print(f'Temos {maior1000} produto custando mais de R$ 1000.00')
print(f'O produto mais barato foi {barato} que custa R${menorpreco:.2f}')
|
n1 = int(input('um Valor: '))
n2 = int(input('Outro Valor: '))
s = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
sb = n1 - n2
rest = n1 % n2
print('A soma é: {}, a multiplicação é: {}, a divisão é: {:.3f}'.format(s,m,d), end=' ')
print('Divisão inteira é: {}, a Exponenciação é: {}, a Subtração é: {}, e o resto da divisão é: {}'.format(di,e,sb,rest))
|
from random import randint
from time import sleep
rdpc = randint(1, 10)
nm = 0
cont = 0
print('-=-' * 20)
print('Vou pensar em um número entre 1 e 10. Tente descobrir...')
print('-=-' * 20)
print(rdpc)
while nm != rdpc:
nm = int(input('Em qual número eu pensei? '))
print('PROCESSANDO...')
sleep(0.3)
cont += 1
if nm == rdpc:
print('PARABÉNS, VOCÊ ACETOU!')
print('Você precisou de {} tentativas'.format(cont))
else:
print('GANHEI! O número que eu pensei foi {} e não o {}'.format(rdpc, nm))
|
cont = 0
soma = 0
while True:
nm = int(input(f'Digite o {cont+1}º número: '))
if nm == 999:
break
cont += 1
soma += nm
print(f'Foram lançados {cont} números, totalizando {soma}')
|
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
n3 = float(input('Digite a terceira nota: '))
media = (n1 + n2 + n3)/3
print('A sua média é: {:.2f}'.format(media))
print('PARABÉNS, VOCÊ VOI APROVADO!' if media >= 7 else 'REPROVADO, ESTUDE MAIS!')
|
nome = str(input('Qual o seu nome: ')).lower
if nome == 'Jesus Cristo':
print('É o filho de Deus, o todo poderoso, o quem pertence toda honra e toda glória!')
else:
print('Aceite Jesus Cristo como Senhor e Salvador, e serás Salvo!')
|
sx = str(input('Digite o seu sexo [M/F]: ')).strip().upper()[0]
while sx not in 'MnFf':
sx = str(input('Dados inválidos. Por favor, informe seu sexo: ')).strip().upper()[0]
print('Sexo {} registrado com sucesso'.format(sx))
|
frase = 'Jesus Cristo é o meu Senhor, dono e Deus!'
print(frase[:13])
print(frase[6:13])
print(frase[1:5:3])
print(frase.count('s'))
print(frase.upper().count('N'))
print(frase.replace('Jesus', 'Yeshua'))
print('Senhor' in frase)
print(frase.lower().find('senhor'))
div = frase.split()
print(div[1][:16])
|
n = s = 0
while n != 999:
n = int(input('Digite um número: '))
s += n
print('A soma vale {}'.format(s))
|
def savePositions():
filename = turtle.textinput("Save turtle positions",
"What is the filname you want to create?")
newfile = open(filename, "wt")
for thisTurtle in allTurtles:
#Make a string for one turtle, in the right
one_line = str(thisTurtle.xcor()) + "\t" +str(thisTurtle.ycor())+ "\n"
turtle.listen()
def loadPositions():
global allTurtles
filename = turtle.textinput("Load turtle positions",
"What is the filename you want to load?")
myfile = open (filename, "r")
turtleIndex = 0
for line in myfile:
#Read each line as a single rule
line = line.rstrip() #strip means remove things
print("line is", line)
items = line.split("\t")
print("line is", line)
x = float(
|
#fibonaci by using generators
"""def fib(num):
a, b = 0, 1
for i in range(0, num):
yield "{}: {}".format(i+1, a)
a, b = b, a+b
for item in fib(12):
print(item)"""
#generators for listing dictionarz items
"""myDict = {"throne": "iron", "ass": "huge", "number": "infinite"}
for key,val in myDict.items:
print("item {} is {}".format(key,val))"""
#recursive multiplication
"""def rec_mult(m, n):
#base case for recursive multiplication
if n == 0:
return 0
elif n >= 1:
return m + rec_mult(m, n-1)
elif n <= -1:
return -m + rec_mult(m, n+1)"""
#iterative multiplication - same case
"""def iter_mult(m, n):
if n == 0 or m == 0:
return 0
result = m * n
if n >= 1:
while n > 0:
result += m
n -= 1
elif n <= -1:
while n < 0:
result += -m
n += 1
return result
print("iterative multiplication: ")
print(iter_mult(3, 4))
print(iter_mult(-1, 4))
print(iter_mult(-2, 4))
print(iter_mult(2, -4))
print(iter_mult(0, 0))"""
#recursion of fibonachi
"""def rec_fib(n):
if n == 0 or n == 1:
return n
else:
return rec_fib(n -1) + rec_fib(n - 2)
print("recursive fibonachi is: ")
print(rec_fib(0))
print(rec_fib(1))
print(rec_fib(2))
print(rec_fib(3))
print(rec_fib(10))"""
#iterative of fibonachi
"""def iter_fib(n):
if n == 0 or n ==1:
return n
else:
previous_fib = 0
current_fib = 1
for iteration in range(1, n):
next_fib = current_fib + previous_fib
previous_fib = current_fib
current_fib = next_fib
return current_fib
print(iter_fib(10))"""
#faktorial
"""def f(n):
assert n >= 0
answer = 1
while n > 1:
answer *= n
n -= 1
return answer
def fact(n):
assert n >= 0
if n <= 1:
return n
else:
return n*fact(n - 1)
def g(n):
x = 0
for i in range(n):
for j in range(n):
x += 1
return x
def h(x):
assert type(x) == int and x >= 0
answer = 0
s = str(x)
for c in s:
answer += int(c)
return answer"""
|
str = input("Enter a string:\n> ")
print(str.lower())
|
product = "iphone and android phones"
lett_d = {}
for char in product:
if char not in lett_d:
lett_d[char] = 0
lett_d[char] = lett_d[char] +1
print(lett_d)
ks = lett_d.keys()
max_value = list(ks)[0]
for k in ks:
print(k)
if lett_d[k] > lett_d[max_value]:
max_value = k
print(max_value)
|
def square(x):
return (x * x)
def add(x,y):
return (x+y)
x = 7
y = 7
print(add(square(y), square(x)))
|
# Dibuja un octagono con una espiral dentro
from turtle import *
def octagon(tortuga, x, y, color):
tortuga.pencolor(color)
tortuga.penup()
tortuga.setposition(x, y)
tortuga.pendown()
for i in range(8):
tortuga.forward(80)
tortuga.right(45)
def spiral(tortuga, x, y, color):
distance = 0.2
angle = 40
tortuga.pencolor(color)
tortuga.penup()
tortuga.setposition(x, y)
tortuga.pendown()
for i in range(130):
tortuga.forward(distance)
tortuga.left(angle)
distance += 0.5
tortuga = Turtle()
octagon(tortuga, -45, 100, 'red')
spiral(tortuga, 0, 0, 'blue')
tortuga.hideturtle()
done()
|
words ="Why sometimes I have Believed as many as six impossible things before breakfast".split()
iterator=iter(words)
for v in iterator:# ate the end of the collection StopIterartion exception will be raised
print(v)
iterator2=iter(words)
while iterator2:
print(next(iterator2))
|
words ="Why sometimes I have Believed as many as six impossible things before breakfast".split()
# print(words)
# x=[len(word) for word in words]#[Expr(item) for item in iterable]
# print(x)
from math import factorial
f=[len(str(factorial(x))) for x in range (1,20)]# returs the list
print(f)
|
#!/d/Python/Python37/python
# import sys
# print ("Number of arguments:", len(sys.argv), "arguments.")
# print ("Argument List:" , str(sys.argv))
# print ("")
# print (sys.argv[1])
# print (sys.argv[2])
# Teste datetime
import datetime
from datetime import date
today = date.today()
newtoday = today.strftime("%y%m%d")
print("Today's date:", today)
print("NewToday's date:", newtoday)
|
# this is an example code comment
movie_count = 3 # number of movies I saw last year
arbitrary_number = 10 # an arbitrary number
# We can use a simple "if else block" to see
# if a number if bigger than another
if movie_count > arbitrary_number:
print("You watched a lot of movies!")
else:
print("You watched few movies...")
# To get the mean average of 6 values
# we add them up & divide by 6
avg_movies_watched = (20 + 6 + 8 + 11 + 0 + movie_count) / 6
print("average movies watched:", avg_movies_watched)
# I add an "elif" (else-if) inbetween my "if" and "else"
# to catch the 3rd condition (if the number of movies I've
# watched is the same as the average)
if movie_count > avg_movies_watched:
print("You watched more movies than the (mean) average.")
elif movie_count == avg_movies_watched:
print("You watched the same # of movies as the average.")
else:
print("You watched less movies than the (mean) average.")
|
"""
url: https://www.algoexpert.io/questions/Find%20Three%20Largest%20Numbers
notes:
easy one :D
"""
from typing import List
class Solution(object):
""" class object
A data inside xBinaryTree
"""
def __init__(self, name=None):
self.name = name
# remember variables used in multiple functions are within the same scope!
def findThreeLargestNumbers(self, nums: List[int]) -> int:
""" main solution function
"""
# the trick here was to break it up into helper functions :D
threelarge = [None, None, None]
testScope = 0
for n in nums:
# for the first three of course we will keep it
self.checkBigThree(threelarge, n, testScope)
print(threelarge)
print(testScope)
# expression are evaluated from left first to right!
def checkBigThree(self, threelarge, n, testScope):
testScope = 5
if threelarge[2] is None or threelarge[2] < n:
self.updateThreeLarge(threelarge, n, 2)
elif threelarge[1] is None or threelarge[1] < n:
self.updateThreeLarge(threelarge, n, 1)
elif threelarge[0] is None or threelarge[0] < n:
self.updateThreeLarge(threelarge, n, 0)
def updateThreeLarge(self, threelarge, num, index):
for i in range(index + 1):
if i == index:
threelarge[i] = num
else:
threelarge[i] = threelarge[i + 1]
def main():
sol = Solution()
input = [12,0,-2,-4,24,500,-23,234,0,1,5,5,567]
sol.findThreeLargestNumbers(input)
if __name__ == "__main__":
main()
|
from users.models import Person
def friends(name):
"""Returns a set of the friends of the given user, in the given graph.
"""
friends_list = Person.objects.get(name=name).friends.all()
return set(friends_list)
def friends_of_friends(user):
"""Returns a set of friends of friends of the given user, in the given graph.
The result does not include the given user nor any of that user's friends.
"""
friends_list = friends(user)
result_set = set()
for friend in friends_list:
result_set.update(friends(friend))
friends_list.add(user)
result_set = result_set.difference(friends_list)
return result_set
def common_friends(user1, user2):
"""Returns the set of friends that user1 and user2 have in common."""
result_set = friends(user1).intersection(friends(user2))
return result_set
def number_of_common_friends_map(user):
"""Returns a map from each user U to the number of friends U has in common
with the given user.
The map keys are the users who have at least one friend in common with the
given user, and are neither the given user nor one of the given user's
friends.
Take a graph G for example:
- A and B have two friends in common
- A and C have one friend in common
- A and D have one friend in common
- A and E have no friends in common
- A is friends with D
number_of_common_friends_map(G, "A") => { 'B':2, 'C':1 }
"""
common_friends_map = {}
user_friends = friends_of_friends(user)
for friend in user_friends:
length = len(common_friends(user, friend))
if length >= 1:
common_friends_map[friend] = length
return common_friends_map
def number_map_to_sorted_list(map):
"""Given a map whose values are numbers, return a list of the keys.
The keys are sorted by the number they map to, from greatest to least.
When two keys map to the same number, the keys are sorted by their
natural sort order, from least to greatest."""
return [v[0] for v in sorted(map.items(), key=lambda kv: (-kv[1], kv[0]))]
def recommend_by_number_of_common_friends(user):
"""Return a list of friend recommendations for the given user.
The friend recommendation list consists of names of people in the graph
who are not yet a friend of the given user.
The order of the list is determined by the number of common friends.
"""
number_of_common_friends_dict = number_of_common_friends_map(user)
sorted_recommend_key = number_map_to_sorted_list(
number_of_common_friends_dict)
return sorted_recommend_key
|
#! /usr/bin/env python
# coding: utf-8
one = 3
two = 4
three = 5
four = 4
five = 4
six = 3
seven = 5
eight = 5
nine = 4
ten = 3
eleven = 6
twelve = 6
thirteen = 8
fourteen = 8
fifteen = 7
sixteen = 7
seventeen = 9
eighteen = 8
nineteen = 8
twenty = 6
thirty = 6
forty = 5
fifty = 5
sixty = 5
seventy = 7
eighty = 6
ninety = 6
hundred = 7
print 3 + 3 + 5 + 4 + 4 + 3 + 5 + 5+ 4
# 36
print ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen +\
eighteen + nineteen
# 70
# 103
""" twenty --> 6 * 10 + 36 = 96
thirty --> 96
forty --> 86
fifty --> 86
sixty --> 86
seventy --> 106
eighty --> 96
ninety --> 96
"""
# 854
# 1297 --> 200 e kadar
|
#!/usr/bin/env python
# coding: utf-8
answer = 0
for x in str(2 ** 1000):
answer += int(x)
print answer
|
#!/usr/bin/env python
# coding: utf-8
from math import sqrt
def divisor_generator(n):
large_divisors = []
for i in xrange(1, int(sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n and n/i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield divisor
answer = 0
number = 1
while number < 10000:
divisorsSum = sum(list(divisor_generator(number)))
real_number = sum(list(divisor_generator(divisorsSum)))
if real_number == number and number != divisorsSum:
answer += number
number += 1
print answer
|
print('You are in Master Branch!')
#emoji module
from emoji import emojize
print(emojize(':angry_face_with_horns:'))
f = open('doc.txt', 'r')
print(f.read(156))
for line in f:
print(line.strip())
f.close()
f = open('doc.txt', 'r')
print(f.read(156))
for line in f:
print(line, end="")
f.close()
file = open("doc.txt", "r")
Counter = 0
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Counter += 1
print("\nThis is the number of lines in the file 'doc.txt'")
print(Counter)
lst = ['Bananas', '&', 'Coconuts']
f = open('tropic.txt','w')
for l in lst:
f.write(l)
f.close()
from datetime import (datetime, date)
print(datetime.today())
print(date.today())
|
"""
Initialize and Reshape the Networks
Now to the most interesting part. Here is where we handle the reshaping of
each network. Note, this is not an automatic procedure and is unique to
each model. Recall, the final layer of a CNN model, which is often times
an FC layer, has the same number of nodes as the number of output classes
in the dataset. Since all of the models have been pre-trained on Imagenet,
they all have output layers of size 1000, one node for each class.
The goal here is to reshape the last layer to have the same number
of inputs as before, AND to have the same number of outputs as the number
of classes in the dataset. In the following sections we will discuss
how to alter the architecture of each model individually.
But first, there is one important detail regarding the difference between
fine-tuning and feature-extraction.
When feature extracting, we only want to update the parameters of the
last layer, or in other words, we only want to update the parameters
for the layer(s) we are reshaping. Therefore, we do not need to compute the
gradients of the parameters that we are not changing, so for efficiency we
set the .requires_grad attribute to False. This is important because by default,
this attribute is set to True. Then, when we initialize the new layer and
by default the new parameters have .requires_grad=True so only the new layer’s
parameters will be updated. When we are fine-tuning we can leave all of the
'.required_grad' set to the default of True.
Finally, notice that inception_v3 requires the input size to be (299,299),
whereas all of the other models expect (224,224).
Resnet
Resnet was introduced in the paper Deep Residual Learning for Image Recognition.
There are several variants of different sizes, including Resnet18, Resnet34,
Resnet50, Resnet101, and Resnet152, all of which are available from
torchvision models. Here we use Resnet18, as our dataset is small and only has
two classes. When we print the model, we see that the last layer is a fully
connected layer as shown below:
(fc): Linear(in_features=512, out_features=1000, bias=True)
Thus, we must reinitialize model.fc to be a Linear layer with 512 input features
and 2 output features with:
model.fc = nn.Linear(512, num_classes)
Alexnet
Alexnet was introduced in the paper ImageNet Classification with Deep
Convolutional Neural Networks and was the first very successful CNN on the
ImageNet dataset. When we print the model architecture, we see the model output
comes from the 6th layer of the classifier
(classifier): Sequential(
...
(6): Linear(in_features=4096, out_features=1000, bias=True)
)
To use the model with our dataset we reinitialize this layer as
model.classifier[6] = nn.Linear(4096,num_classes)
VGG
VGG was introduced in the paper Very Deep Convolutional Networks for
Large-Scale Image Recognition. Torchvision offers eight versions of VGG with
various lengths and some that have batch normalizations layers. Here we use
VGG-11 with batch normalization. The output layer is similar to Alexnet, i.e.
(classifier): Sequential(
...
(6): Linear(in_features=4096, out_features=1000, bias=True)
)
Therefore, we use the same technique to modify the output layer
model.classifier[6] = nn.Linear(4096,num_classes)
Squeezenet
The Squeezenet architecture is described in the paper SqueezeNet: AlexNet-level
accuracy with 50x fewer parameters and <0.5MB model size and uses a different
output structure than any of the other models shown here. Torchvision has
two versions of Squeezenet, we use version 1.0. The output comes from a 1x1
convolutional layer which is the 1st layer of the classifier:
(classifier): Sequential(
(0): Dropout(p=0.5)
(1): Conv2d(512, 1000, kernel_size=(1, 1), stride=(1, 1))
(2): ReLU(inplace)
(3): AvgPool2d(kernel_size=13, stride=1, padding=0)
)
To modify the network, we reinitialize the Conv2d layer to have an output
feature map of depth 2 as
model.classifier[1] = nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1))
Densenet
Densenet was introduced in the paper Densely Connected Convolutional Networks.
Torchvision has four variants of Densenet but here we only use Densenet-121.
The output layer is a linear layer with 1024 input features:
(classifier): Linear(in_features=1024, out_features=1000, bias=True)
To reshape the network, we reinitialize the classifier’s linear layer as
model.classifier = nn.Linear(1024, num_classes)
Inception v3
Finally, Inception v3 was first described in Rethinking the Inception
Architecture for Computer Vision. This network is unique because it has
two output layers when training. The second output is known as an auxiliary
output and is contained in the AuxLogits part of the network. The primary
output is a linear layer at the end of the network. Note, when testing we only
consider the primary output. The auxiliary output and primary output of the
loaded model are printed as:
(AuxLogits): InceptionAux(
...
(fc): Linear(in_features=768, out_features=1000, bias=True)
)
...
(fc): Linear(in_features=2048, out_features=1000, bias=True)
To fine-tune this model we must reshape both layers. This is accomplished with
the following
model.AuxLogits.fc = nn.Linear(768, num_classes)
model.fc = nn.Linear(2048, num_classes)
Notice, many of the models have similar output structures, but each must
be handled slightly differently. Also, check out the printed model
architecture of the reshaped network and make sure the number of output
features is the same as the number of classes in the dataset.
"""
from __future__ import print_function
from typing import Optional
from core.imgnet_models.alexnet_model import AlexnetModel
from core.imgnet_models.densenet_model import DensenetModel
from core.imgnet_models.inception_model import InceptionModel
from core.imgnet_models.resnet_model import ResnetModel
from core.imgnet_models.squeezenet_model import SqueezenetModel
from core.imgnet_models.vgg_model import VggModel
from core.types import ModelName
model_map = {
ModelName.Resnet: ResnetModel(),
ModelName.Alexnet: AlexnetModel(),
ModelName.Vgg: VggModel(),
ModelName.Squeezenet: SqueezenetModel(),
ModelName.Inception: InceptionModel(),
ModelName.Densenet: DensenetModel(),
}
def initialize_model(
model_name: ModelName,
num_classes: int,
feature_extract: bool,
device,
use_pretrained: Optional[bool] = True
):
try:
model = model_map[model_name]
model.init(
device=device,
num_classes=num_classes,
feature_extract=feature_extract,
use_pretrained=use_pretrained
)
return model
except KeyError:
raise ValueError(f"Not supported model name {model_name}")
|
import turtle
pen = turtle.Turtle()
pen1 = turtle.Turtle()
paper = turtle.Screen()
pen1.up()
pen1.setx(-200)
pen1.down()
pen.color('brown')
for i in range(36):
pen.fd(10)
pen.right(10)
pen1.fd(10)
pen1.right(10)
|
#!/usr/bin/python
#Question 1.2
def isPermutation(str1,str2):
s1=sorted(str1)
s2=sorted(str2)
if(s1==s2):
return True
else:
return False
if __name__=="__main__":
str1 = "fast"
str2 = "tasf"
print isPermutation(str1,str2)
|
squares = [1, 4, 9, 16, 25]
squares.append(8**8)
print(squares)
print(squares[:])
for i in range(5,9):
print(i)
#print(randomRange)
|
#!/usr/bin/python
def special(lst):
ones = 0
twos = 0
for x in lst:
twos |= ones & x
ones ^= x
not_threes = ~(ones & twos)
ones &= not_threes
twos &= not_threes
return ones
if __name__ == "__main__":
# lst = [1, 2, 4, 6, 4, 1, 2, 3, 6, 4, 2, 1, 3, 6]
lst = [4, 5, 4]
print special(lst)
|
costPrice=float(input("enter the cost price "))
sellingPrice=float(input("enter the selling price"))
profit=sellingPrice-costPrice
print("Profit is ",profit)
new_Selling_Price=(105/100)*profit + costPrice
print("Adding on 5% profit Selling price is ",new_Selling_Price)
|
n=int(input('Enter list size:-'))
print('Enter elements seprated by space :-')
list=list(map(int,input('Enter a elements').split()))
for j in range(len(list)-1):
list[j]=max(list[j+1:])
print(list)
|
bread_slices=4
jars_peanutbutter=1
jars_jelly=10
if bread_slices>=2 and jars_peanutbutter>=1 and jars_jelly>=1:
print "I'm hungry, let's make a sandwich! We can make {0} sandwiches to share or {1} open faced sandwiches.".format(bread_slices/2, bread_slices)
elif bread_slices<2 or jars_peanutbutter<1 or jars_jelly<1:
print "No sandwiches for you."
if bread_slices<1:
print "You really need to go to the grocery, you don't have enough bread make sandwiches."
elif jars_peanutbutter<1
print "You really need to go to the grocery, you don't have enough peanut butter make sandwiches."
elif jars_jelly<1:
print "You really need to go to the grocery, you don't have enough jelly make sandwiches."
if bread_slices>=2 and jars_peanutbutter>0 and jars_jelly == 0:
print "I guess you could have a peanut butter sandwich, but you don't have jelly, and really, what is life worth if it ain't got any jelly in it?"
|
class Heap:
def __init__(self, lstr=None):
self.heap = []
if isinstance(lstr, list):
self.heap = lstr
self.buildheap()
def __repr__(self):
return " ,".join(str(i) for i in self.heap)
def buildheap(self):
n = len(self.heap)
for i in range(int(n/2-1), -1, -1):
self.heapify(i, n)
def heapify(self, i, n):
left = 2 * i + 1
right = 2 * i + 2
largest = None
if left < n and self.heap[left] > self.heap[i]:
largest = left
if right < n and self.heap[right] > self.heap[left]:
largest = right
if largest:
self.heap[i], self.heap[largest] = self.heap[largest], self.heap[i]
self.heapify(largest, n)
hp = Heap([5, 3, 16, 2, 10, 14])
print(hp)
|
"""
Check Primality Functions
Exercise 11
Ask the user for a number and determine whether the number is prime or
not. """
from sys import exit
def prime():
number = input(
"\nEnter a number to check if it is Prime number.\n"
)
if not number:
exit(0)
try:
number = int(number)
except ValueError:
print('invalid entry')
exit(0)
if number == 1 or number == -1 or number == 0:
print("{} is not a Prime!".format(number))
exit()
elif number < 0 :
n = number * -1
else:
n = number
# d is for division or factor
# r is for remainder
# n is for number
d = n // 2
while d != 1:
r = n % d
if r == 0:
print("{} is not a Prime!".format(number))
exit(0)
break
else:
d -= 1
print("{} is a Prime!".format(number))
if __name__ == "__main__":
prime()
|
import cv2
import numpy as np
# path to input images are specified and
# images are loaded with imread command
image1 = cv2.imread('b.png')
# cv2.bitwise_not is applied over the
# image input with applied parameters
dest_not1 = cv2.bitwise_not(image1, mask=None)
# the windows showing output image
# with the Bitwise NOT operation
# on the 1st and 2nd input image
cv2.imshow('Bitwise NOT on image 1', dest_not1)
# De-allocate any associated memory usage
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
|
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
__author__ = 'qing.li'
"""
# 异常捕获
# try:
# num = int(input("请输入一个整数:"))
# result = 8 / num
# print(result)
# except ZeroDivisionError:
# print("1")
# except ValueError:
# pass
# 错误类型
# 捕获未知错误
# try:
# num = int(input("请输入一个整数:"))
# result = 8 / num
# print(result)
# except Exception as e:
# print("exception info:", e)
def get_password():
password = input("please input your password:")
if len(password) > 8:
print("密码苏护乳正确")
return
ex = Exception("密码长度错误")
raise ex
try:
get_password()
except Exception as result:
print(result)
|
"""
计算机的硬件组成:
主板 固化(寄存器,是直接和cpu进行交互的一个硬件)
CPU 中央处理器:计算(数字计算和逻辑计算)和控制(控制所有硬件协调工作)
存储 硬盘 内存
输入设备 键盘 鼠标 话筒
输出设备 显示器 音响 打印机
早期的计算机是以计算为核心的。现在的计算机是以存储为核心的
计算机的发展过程:
电子管计算机 耗电 体积大 散热量高
晶体管计算机
白色大头计算机 集成电路计算机
大型集成电路计算机:
甚大型集成电路计算机
计算机的操作系统:
操作系统是一个软件,是一个能直接操作硬件的一个软件
微软研发的windows操作系统
人工时代:穿孔卡带
脱机时代:完全将人和机器分开
单道批处理系统:内存中只允许存放一道作业
多道批处理系统:内存中只允许存放多道作业
分时系统:将cpu的执行时间划分时间片,每个程序以时间片为单位去执行
实时系统: 少见 用于军事和工业生产上
目标:让用户使用轻松,高可用,低耦合
封装了所有硬件的接口,使用户更方便的使用
对于计算机内的所有资源,进行一个合理的调度和分配
计算机语言发展过程:
机器语言 0/1
汇编语言 指令 add n,m, 命令形式的
高级语言 面向过程语言(c),面向对象语言(python,java, c++)
os:
Dos系统 纯编程系统 单用户单任务
windows系统 但用户多任务
unix系统 多用户多任务
关于进程:
.sh shell脚本文件
.out linux中的可执行文件
.bat 批处理脚本文件
.lib 库文件
.dll 库
.exe 可执行文件
进程:正在执行的程序 是程序执行过程中的依稀 指令,数据集等的集合
也可以叫做程序的一次执行过程,是一个动态的概念
进程的组成: 代码段,数据段,PCB:进程控制块
进程的三大基本状态:
就绪状态: 已经获得了运行所需要的所有资源,除了CPU
执行状态:已经获得了所有资源包括cpu,处于正在执行的状态
阻塞状态:因为各种原因,进程放弃了cpu,导致进程无法继续执行,此时进程处于内存中,继续等待获取cpu
一个特殊状态:挂起状态:因为各种原因,进程放弃了cpu, 导致进程无法继续执行,此时进程被踢出内存
multiprocessing 内置模块 用于多进程编程, Process from multiprocessing import Process
并行:指两件或多件事情,在同一时间点开始执行
并发:指两件或多件事情,在同一时间间隔内同时执行
同步:某一个任务的执行必须依赖另一个任务的返回结果
异步:某一个任务的执行 不需要依赖另一个任务的返回,只需要告诉另一个任务一声
阻塞:程序因为蕾丝IO等待,等待时间等无法继续执行
非阻塞:程序遇到类似IO操作时,不再阻塞等待,如果没有即使处理IO,就报错活着跳过
进程的方法或属性:
start() 开启一个子进程
join()异步变同步,让父进程等待子进程执行结束,再继续执行
is_alive() 判断进程是否活着
terminate() 杀死进程
name: 子进程的名字
pid:子进程的pid
daemon:设置进程为守护进程,给一个True代表为守护进程,默认为False,不是守护进程
守护进程:
随着父进程的代码执行完毕就结束(重点:代码执行!!完毕)
守护进程不能创建子进程
守护进程必须在start之前设置
IPC--进程间通信:
锁机制:为了多进程通信时,保护数据的安全心
l = Lock()
l.acquire() 获得锁(其他进程不能访问)
l.release() 释放锁(其他进程可以访问)
信号机制:
sem = Semaphore(n)
n:初始化的时候一把锁配几把钥匙,int
l.acquire()
l.release()
信号量机制比锁机制多了一个计数器,这个计数器用来记录当前剩余几把钥匙,计数器为0,表示当前没有钥匙,acquir()处于阻塞状态
acquire一次 计数器内部减1,release一次就+1
事件机制:
e = Event(0
e.set() 设置is_set()为True (非阻塞状态)
e.clear() 设置is_set()为False(阻塞状态)
e.wait() 判断is_set()的值 ,True:非阻塞,False:zuse
e.is_set() 标志
正常情况下,多进程之间无法直接通信,因为每个进程都有自己独立的内存空间
生产者消费者模型:
主要是用于解耦:借助队列来实现生产者消费者模型
栈:先进后出
队列:先进先出
import queue # 不能进行多进程之间的数据传输
from multiprocessing import Queue 借助Queue解决生产者消费者模型
队列是安全的
q = Queue(num)
num: 队列的最大长度
q.get() 阻塞等待获取数据,如果有数据直接获取,如果没有则阻塞等待
q.put() 阻塞 如果可以继续往队列中放数据,就直接放,不能放就阻塞等待
q.get_nowait() 不阻塞 如果有数据直接获取,没有数据就报错
q.put_nowait() 不阻塞 如果可以继续往队列中放数据,就直接放,不能放就报错
from multiprocessing import JoinableQueue 可连接的队列
继承Queue,可以使用queue的方法
多的方法:
q.join() 用户生产者 接收消费者的返回结果,接收全部生产的数量,以便知道什么时候队列里的数据被消费完了
q.task_done() 每消费一个数据,就返回一个表示 返回结果 生产者就能获得当前消费者消费量多少个数据 没消费队列中的一个数据,就给join返回一个表示
管道:
from multiprocessing import Pipe
con1, con2 = Pipe()
管道是不安全的
管道是用于多进程之间通信的一种方式,
单进程中:
con1发则con2收。con2发则con1收
多进程中:
父进程con1发,子进程的con2收,
管道中的错误EOFError 腹肌 in 成如果关闭来发送端,子进程还继续接收,就会导致EOFError
进程间的内存共享
from multiprocessing import Manager, Value
m = manager()
num = m.dict({}) num = m.list([])
进程池:(一个池子,里面有固定数量的进程,且处在待命状态,一旦有任务来,马上就有进程去处理
开启进程需操作系统消耗大量的时间去管理它,大量的时间让cpu去调度它
进程池会帮助程序员去管理池中的进程
from multiprocessing import Pool
p = Pool(os.cpu_count() + 1)
进程池的三个方法:
map(func, iterable)
func: 进程池中进程执行的任务函数
iterable:可迭代对象,是把可迭代对象中的每个元素一次传给任务函数当参数
apply(func, args =())同步的执行,也就是说池中的进程一个个的去执行任务
func: 进程池中进程执行的任务函数
args: 可迭代对象型的参数,是传给任务函数的参数
同步处理任务,不需要close和join
同步处理任务时, 进程池中所有进程都是普通进程(主进程需要等待其结束)
apply_async(func, args=(), callback=None) 异步: 池中的进程一次性去执行任务
func: 进程池中进程执行的任务函数
args: 可迭代对象型的参数,是传给任务函数的参数
callback:回调函数 当进程池中有进程处理完任务来,返回的结果可以交给回调函数,由回调函数进一步的处理,只有异步才有
异步处理任务,要close和join
异步处理任务时, 进程池中所有进程都是守护进程
回调函数:
进程的任务函数的返回值,被当成回调函数的形参接收到,以此进一步的处理操作
回调函数是由主进程调用的,而不是子进程,子进程只负责把结果给回调函数
IPC: 管道 队列 (锁,信号量,事件)
"""
|
from multiprocessing import Process
import time
"""
守护进程: 跟随者父进程的代码执行结束,守护进程就结束
守护进程不允许开启子进程
"""
# def func():
# time.sleep(3)
# print("this is son")
#
#
# if __name__ == '__main__':
# p = Process(target=func)
# p.daemon = True # 设置进程为守护进程,必须在start之前设置
# p.start()
# # p.join()
# time.sleep(1)
# print('this is father')
# def func_two():
# print("this is grandson")
#
#
# def func():
# p = Process(target=func_two)
# p.start()
# time.sleep(2)
# print('this is son')
#
#
# if __name__ == '__main__':
# p = Process(target=func)
# p.daemon = True
# p.start()
# time.sleep(1)
# print('this is father')
def func():
for i in range(10):
time.sleep(1)
print(time.strftime('%Y-%m-%d %H:%M:%S'))
if __name__ == '__main__':
p = Process(target=func)
p.daemon = True
p.start()
time.sleep(5)
print('this is father')
|
import time
def func():
print(123)
sum = 0
print(333)
sum += 1
yield sum
print(444)
sum += 1
yield sum
print(555)
sum += 1
yield sum
def fff():
g = func() # 并不会开始执行函数
print("this is in fff()")
print(next(g)) # 开始执行到yeild 之后
time.sleep(1)
print("again")
print(next(g))
time.sleep(1)
print("again and again")
print(next(g))
fff()
|
from abc import ABC, abstractmethod
class Unit(ABC):
def __init__(self,team: int = 0):
self.team = team
self.is_alive = True
@property
@abstractmethod
def value(self):
"""
The worth of each unit i.e. Queen = 9, etc
"""
raise NotImplementedError
@property
@abstractmethod
def char(self):
"""
representation of unit as character
"""
raise NotImplementedError
@abstractmethod
def move(self):
"""
Movement type of each unit according to board layout
"""
raise NotImplementedError
def __repr__(self):
name = self.__class__.__name__
return f"<class={name} value={self.value} representation={self.char} team={self.team}/>"
|
print("= = = = = = = = = = = = = = =")
print("PROGRAM HITUNG GAJI KARYAWAN")
print("PT AMAN SENTOSA")
print("= = = = = = = = = = = = = = =")
nama = input("Nama Karyawan ")
gol = input("Golongan Jabaatan ")
pend = input("Pendidikan ")
jumlah = int(input("Jumlah Jam Kerja "))
gapok = 300000
#proses
if gol=="1":
tunjab=0.05*gapok
elif gol=="2":
tunjab=0.1*gapok
elif gol=="3":
tunjab=0.15*gapok
else:
tunjab=0
if pend=="SMA":
tunpend=0.25 * gapok
elif pend=="D1":
tunpend=0.05 * gapok
elif pend=="D3":
tunpend=0.2 * gapok
elif pend=="S1":
tunpend=0.3 * gapok
else:
tunpend = 0
if jumlah > 8:
lembur = (jumlah - 8) * 3500
else:
lembur = 0
total=gapok+ tunjab+tunpend+lembur
print("STRUK GAJI KARYAWAN")
print("= = = = = = = = = =")
print("Karyawan yang bernama",nama)
print("Honor yang diterima")
print(" Tunjangan Jabatan RP",tunjab)
print(" Tunjangan Pendidikan RP",tunpend)
print(" Honor Lembur RP",lembur)
print(" _______________________")
print(" Total Gaji RP",total)
print(" (Gaji pokok + tunjangan + lembur ")
|
deretangka = [[1,2,3],[4,5,6],[7,8,9],0]
print("Baris Pertama, Kolom Pertama adalah")
print(deretangka[0][0])
print("Baris Pertama, Kolom Kedua adalah")
print(deretangka[0][1])
print("Baris Pertama, Kolom Ketiga adalah")
print(deretangka[0][2])
print("Baris Ketiga, Kolom Ketiga adalah")
print(deretangka[2][2])
print("Baris Keempat, Kolom Pertama adalah")
print(deretangka[3])
|
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(map(str.upper, my_pets))
print(uppered_pets)
|
number = int(input("Enter the number to find its factors: "))
print ("factors are: ")
for x in range(1,number+1):
if number%x == 0:
print(x)
|
# Write a Python program to Print all factors of number and print if the no is perfect number.
num = int(input("Enter a number: "))
factors = []
for x in range(1,num):
if num%x == 0:
factors.append(x)
print ("factors are:", factors)
if sum(factors) == num:
print ("number:", num, "is a perfect number.")
|
def testOddEven(num):
if num%2 == 0:
return "its a even number"
else:
return "its a odd number"
num = int(input("Enter a number to test: "))
print(testOddEven(num))
|
# 6 - Faça um Programa que leia três números e mostre o maior deles.
num1 = int(input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo número: "))
num3 = int(input("Digite o terceiro número: "))
if(num1 > num2 and num1 > num3):
print("O maior é: %d" %num1)
elif(num2 > num1 and num2 > num3):
print("O maior é: %d" %num2)
elif(num3 > num1 and num3 > num2):
print("O maior é: %d" %num3)
else:
print("Todos os números são iguais!")
|
# Faça um Programa que peça a temperatura em graus Fahrenheit,
# transforme e mostre a temperatura em graus Celsius.
# C = 5 * ((F-32) / 9).
temFahrenheit = float(input("Digite a temperatura em Fahrenheit: "))
print("A temperatura em Celsius eh: ", 5 * ((temFahrenheit - 32) / 9), "ºC")
|
# 7 - Faça um Programa que leia três números e mostre o maior e o menor deles.
num1 = int(input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo número: "))
num3 = int(input("Digite o terceiro número: "))
if(num1 > num2 and num1 > num3):
print("O maior é: %d" %num1)
if(num2 > num3):
print("O menor é: %d" %num3)
else:
print("O menor é: %d" %num2)
elif(num2 > num1 and num2 > num3):
print("O maior é: %d" %num2)
if(num1 > num3):
print("O menor é: %d" %num3)
else:
print("O menor é: %d" %num1)
elif(num3 > num1 and num3 > num2):
print("O maior é: %d" %num3)
if(num1 > num2):
print("O menor é: %d" %num2)
else:
print("O menor é: %d" %num1)
else:
print("Todos os números são iguais!")
|
import time
import pandas as pd
import numpy as np
#define dictionaries and lists for filter parameters
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
LOCALES = ['chicago', 'new york city', 'washington']
MONTHS = ['january', 'february','march', 'april', 'may', 'june']
WEEKDAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) locale - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# add a nice little aesthetic pause as the program gets going :)
time.sleep(1)
# get the user's input for filtering by locale, month, day of week
while True:
locale = input('\nPlease select a city (Chicago, New York City, or Washington\n: ').lower()
if locale in LOCALES:
break
else:
print('No valid city/locale selected! Please try again.')
month = input('\nPlease specify a month (January -- June) with which to filter data (enter "all" for no month filter)\n: ').lower()
day = input('\nPlease specify a day of week (Monday -- Sunday) with which to filter data (enter "all" for no day filter\n: ').lower()
print('%'*40)
return locale, month, day
def load_data(locale, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) locale - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data from from the locale specified in the get_filters() function
df = pd.read_csv(CITY_DATA[locale])
# clean up the time formatting for data filtering
df['Start Time'] = pd.to_datetime(df['Start Time'])
#add additional columns
df['month'] = df['Start Time'].dt.month
df['weekday'] = df['Start Time'].dt.weekday_name
df['hour'] = df['Start Time'].dt.hour
#filter by month as necessary or ignore the month filter
if month != 'all':
month = MONTHS.index(month) + 1
df = df[ df['month'] == month]
#filter by day as necessary or ignore the day filter
if day != 'all':
df = df[ df['weekday'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
most_common_month = df['month'].value_counts().idxmax()
print("The most common month is :", most_common_month)
# display the most common weekday
most_common_weekday = df['weekday'].value_counts().idxmax()
print("Most common weekday travel occurred on: ", most_common_weekday)
# display the most common start hour
most_common_start_hour = df['hour'].value_counts().idxmax()
print("The most common starting hour is: ", most_common_start_hour)
print("\nThat took %s seconds to calculate!!" % (time.time() - start_time))
print('%'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
most_common_start_station = df['Start Station'].value_counts().idxmax()
print("Most common starting station was: ", most_common_start_station)
# display most commonly used end station
most_common_end_station = df['End Station'].value_counts().idxmax()
print("Most common ending stations was: ", most_common_end_station)
# display most frequent combination of start station and end station trip
most_common_start_and_end = df[['Start Station', 'End Station']].mode().loc[0]
print("Most common start and end station: {}, {}".format(most_common_start_and_end[0], most_common_start_and_end[1]))
print("\nThat took %s seconds to calculate!!" % (time.time() - start_time))
print('%'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
total_travel_time = df['Trip Duration'].sum()
print("Total time traveled: ", total_travel_time)
# display mean travel time
avg_travel_time = df['Trip Duration'].mean()
print("Average time traveled: ", avg_travel_time)
print("\nThat took %s seconds to calculate!!" % (time.time() - start_time))
print('%'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
print("Number of distinct types of users: ")
distinct_users = df['User Type'].value_counts()
for index, user in enumerate(distinct_users):
print(" {}: {}\n".format(distinct_users.index[index], user))
# Display counts of gender
print("Number of riders by gender: ")
# add logic to account for Washington's data file not containing gender data
if 'Gender' in df.columns:
distinct_gender = df['Gender'].value_counts()
for index, gender in enumerate(distinct_gender):
print(" {}: {}".format(distinct_gender.index[index], gender))
else:
print("\nThere is no gender data available for the selected locale!\n")
# Display earliest, most recent, and most common year of birth
# add logic to account for Washington's data file not containing birth date data
if 'Birth Year' in df.columns:
birth_year = df['Birth Year']
earliest_birth_year = birth_year.min()
print("Earliest birth year was: ", earliest_birth_year)
latest_birth_year = birth_year.max()
print ("Latest birth year was:", latest_birth_year)
common_birth_year = birth_year.value_counts().idxmax()
print("Most common birth year was: ", common_birth_year)
else:
print("\nThere is no birth date data available for the selected locale!\n")
print("\nThat took %s seconds to calculate!!" % (time.time() - start_time))
print('%'*40)
# Function that displays raw data from the selected city (df) 5 rows at a time.
def print_data(df):
"""Prints lines of raw data at the request of the user (input)
Args: dataframe/datafile as defined in earlier function
"""
print("\nData number crunching complete! The program can now display raw data samples upon request.\n")
data_request = input("\nWould you like to see some raw data now? ('y' or 'n')\n: ")
data_range = 0
while True:
if data_request is 'y':
data_range += 5
print(df.iloc[:data_range])
data_request = input("\nWould you like to see 5 more rows of raw data? ('y' or 'n')\n: ")
elif data_request is 'n':
print("\nAlright, not going to show any raw data...\n")
break
else:
data_request = input("\nPlease enter a 'y' or 'n'\n: ")
def main():
while True:
locale, month, day = get_filters()
df = load_data(locale, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
print_data(df)
restart = input('\nWould you like to restart? Enter y or n.\n')
if restart.lower() != 'y':
break
if __name__ == "__main__":
main()
|
import documentary
import game
from extender import *
class Container:
__length = 0
def __init__(self):
self.store = []
def print(self):
print("Container is store", len(self.store), "movies:")
for movie in self.store:
movie.print()
self.__length = self.__length + 1
print("Shell Sorting = ", )
def write(self, ostream):
ostream.write("Container is store {} movies:\n".format(len(self.store)))
for movie in self.store:
movie.write(ostream)
ostream.write("\n")
self.shell()
def shell_print(self):
for movie in self.store:
movie.print()
def shell_write(self, ostream):
ostream.write("Sorted {} movies:\n".format(len(self.store)))
for movie in self.store:
movie.write(ostream)
ostream.write("\n")
def random_print(self, count):
for i in range(int(count)):
digit = random.randint(1, 3)
typeof = random.randint(1, 3)
if digit == 1:
game = Game()
game.random_print()
self.store.append(game)
elif digit == 2:
cartoon = Cartoon()
cartoon.random_print(typeof)
self.store.append(cartoon)
elif digit == 3:
documentary = Documentary()
documentary.random_print()
self.store.append(documentary)
self.__length = self.__length + 1
def random_write(self, ostream):
ostream.write("Container is store {} movies:\n".format(len(self.store)))
for movie in self.store:
movie.random_write(ostream)
ostream.write("\n")
self.shell()
def shell_random_print(self):
print("\n")
print("\n")
for movie in self.store:
movie.random_print()
def shell_random_write(self, ostream):
ostream.write("Sorted {} movies:\n".format(len(self.store)))
for movie in self.store:
movie.write(ostream)
ostream.write("\n")
def shell(self):
for s in range(self.__length // 2, 0, -1):
for i in range(0, self.__length):
for j in range(i + s, self.__length):
first = self.store[i].year / len(self.store[i].name)
second = self.store[j].year / len(self.store[j].name)
if first > second:
temp = self.store[j]
self.store[j] = self.store[i]
self.store[i] = temp
j += s - 1
s //= 2 + 1
|
# print("Hello, World!")
# first = 9
# second = first + 1
# def add(a, b):
# print(a + b)
# add(first, second)
# """asdsdsd"""
# cars = ["audi", "mercedes-benz", "bmw", "volkswagen", "volvo", "seat"]
# name = "Sharis"
# dumb = False
# if name:
# print(name)
# if name == "Sharis" and not dumb:
# cars.append("opel")
# print(cars[:1])
# a = 9
# b = 10
# "bigger" if b > a else "smaller"
# for car in cars:
# print("The cars in the list include {0}".format(car))
# x = 0
# for index in range(10):
# x += 10
# print("The value of x is {0}".format(x))
# students = ["Antanas", "Petras", "Stasys", "Mindaugas", "Elze",
# "Jurgita", "Sarunas", "Ilona", "Virginija", "Nijole", "Egle", "Pranas"]
# for student in students:
# if student == "Sarunas":
# print("Found him - " + student)
# continue
# print("Searching for the match: " + student + " going to next")
# phrase = "Sharis is cool"
# for char in phrase:
# print(char)
# student = {
# "name": "sharis",
# "last_name": "maris",
# "id": 19,
# "attendance": "excellent"
# }
# try:
# x = student["grades"]
# except KeyError as error:
# print("This key is not found!")
# print(error)
# print("This code still executes")
friends = []
def get_friends_titlecase():
friends_titlecase = []
for friend in friends:
friends_titlecase.append(friend["name"].title())
return friends_titlecase
def print_friends_titlecase():
friends_titlecase = get_friends_titlecase()
print(friends_titlecase)
def add_friend(name, id=19):
friend = {"name": name, "id": id}
friends.append(friend)
def save_file(friend):
try:
f = open("friends.txt", "a")
f.write(friend + "\n")
f.close()
except Exception:
print("Could not save to file")
def read_file():
try:
f = open("friends.txt", "r")
# itterate through a function generator
for friend in read_friends(f):
add_friend(friend)
f.close()
except Exception:
print("Could not read file")
def read_friends(file):
for line in file:
yield line
# lambda functions
def double(x): print(x * 2)
def tripple(y): print(y * 3)
read_file()
print_friends_titlecase()
friend_name = input("Enter friend name: ")
friend_id = int(input("Enter friend ID: "))
add_friend(friend_name, friend_id)
save_file(friend_name)
read_file()
double(19)
tripple(5)
#list comprehension
numbers_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#print a new list of numbers which are less than 5 from the given numbers list in one line
print([number for number in numbers_list if number < 5])
#print([[output] [itteration] [condition]])
# => [1, 1, 2, 3]
#give divisors of a particular number from user input
def show_divisors(number_from_input):
number_range = list(range(1, 1001))
for nr in number_range:
if nr % number_from_input == 0:
print(nr)
nr_from_input = int(input("Give me a number: "))
show_divisors(nr_from_input)
#given two lists print out a new list only of common items in both lists without duplicates
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def find_in_lists(list1, list2):
common_numbers = []
for number in list1:
if number in list2:
if number not in common_numbers:
common_numbers.append(number)
print(common_numbers)
find_in_lists(a, b)
# => [1, 2, 3, 5, 8, 13]
#do the same in one line and add list c before it
c = []
print([number for number in b if number in a and number not in c])
# => [1, 2, 3, 5, 8, 13]
#check if a word is a palindrome (a string or number that read the same forwards and backwards)
def is_it_palindrome():
word = input("Print a word to check if it is a palindrome: ")
backward = word[::-1]
if word == backward:
print("The word is a palindrome!")
else:
print("The word isn't a palindrome! ")
is_it_palindrome()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.