text
stringlengths
37
1.41M
""" print("hello word") print(123) print(None) print(0.3) print(True,False) print(()) print({}) print([]) a = "哈哈哈哈哈" #把哈哈哈赋值给a这个变量 print(a) name = "呼呼" print("你好,{}".format(name)) print("你好,"+name) print("1"+"1") print((11-3)*31+88/22)#逻辑运算符 print(10%4)#求余 print(2>1) #input()获取输入 name = input("请输入你的姓名:") print("这是input获取的值:",name) #type()获取数据类型 print(type(True)) #len print(len(123)) """ """ #元组() a = ("哈哈","123",123,True,None,123,123,123) print(a) print(a[0]) print(a.index(123)) #123的下标 print(a.count(123)) #元组中123的数量 print(a.count(1)) #true=1 #数组[] 元组不可以修改,数组可以修改 b = ["哈哈","123",123,True,None,123,123,123] b.append("吴亦凡") #插在最末尾 b.insert(2,6) #插入数据到对应的位置 print(b) c = b.pop(0) #取出 print(c) print(b) b.remove("123") #删除 print(b) b.extend([1,2,3]) #添加数组 print(b) """ #二维数组 a = ("呼呼",1,2,3,4,5,6,None,True,"123",1,0,False) b = ["哈哈","123",123,True,None,123,123,123] c =[a,b] print(c[1][1]) d = (b,0) print(d) d[0].append("qiqi") #元组中的数组可以添加数据 print(d) #字典 {} key:value 没有顺序 x = {"name":"张张","age":22} print(x["age"]) """ n = x.pop("name") print(n) print(x) """ print(x.get("name"))
for b in range(3,0,-1): print("黄灯还有",b,"秒结束") for b in range(35,0,-1): print("绿灯还有",b,"秒结束") for b in range(30,0,-1): print("红灯还有",b,"秒结束") username = input("账号") password = input("密码") if len(username) >=3 and len(username) <= 8: print("username") if username[0] in "zxcvbnmlkjhgfdsaqwertyuiop": print("username") if len(password) >=6 and len(password) <=8: print("注册成功",{username,password}) else: print("密码必须为6-8位") else: print("账号开头必须为小写") else: print("账号必须位3-8位")
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 N = len(A)+1 missing = N for i in range(1, N): missing ^= A[i-1] missing ^= i return missing
k = int(input("Enter the number of digits .... ")) print("Probablity P1 where P1 is that the k-digit number does NOT contain the digits 0 , 5 , 9 out of 10 integers from 0 to 9 is : ",(7/10)**k) print("Probablity P2 where P2 is that the k-digit number does NOT contain the digits 0 , 5 , 9 out of { 0 , 1 , 3 , 4 , 5 , 7 , 9 } is : ",(4/7)**k) print("The Conclusion is that P2 is half of P1 i.e as we decrese the domain the probablity of finding is more i.e it is easy to find something in smaller box compared to bigger box.....")
import time """ x = 0 t0 = time.time() for i in range(1000000): x += 1 t = time.time() - t0 print("one million iterations in ", t, " seconds") # real python3 is about 100x faster """ x = 0 t0 = time.time() for i in range(1000000): x = x+1 t = time.time() - t0 print("one million iterations in ", t, " seconds") # real python3 is about 10x faster
import abc from abc import ABC class IMath(ABC): @abc.abstractmethod def addition(self, num1, num2): pass @abc.abstractmethod def substraction(self, num1, num2): pass @abc.abstractmethod def multiplication(self, num1, num2): pass @abc.abstractmethod def division(self, num1, num2): pass class MathProxy(IMath): def __init__(self, math): self.math = math def addition(self, num1, num2): print("Inside proxy: Calling the actual method") return self.math.addition(num1, num2) def substraction(self, num1, num2): print("Inside proxy: Calling the actual method") return self.math.substraction(num1, num2) def multiplication(self, num1, num2): print("Inside proxy: Calling the actual method") return self.math.multiplication(num1, num2) def division(self, num1, num2): print("Inside proxy: Calling the actual method") return self.math.division(num1, num2) class MathImpl(IMath): def addition(self, num1, num2): return num1 + num2 def substraction(self, num1, num2): return num1 - num2 def multiplication(self, num1, num2): return num1 * num2 def division(self, num1, num2): return num1 / num2 class MathRemote(IMath): def addition(self, num1, num2): print("Inside remote proxy: for addition") return num1 + num2 def substraction(self, num1, num2): print("Inside remote proxy: for substraction") return num1 - num2 def multiplication(self, num1, num2): print("Inside remote proxy: for substraction") return num1 * num2 def division(self, num1, num2): print("Inside remote proxy: for division") return num1 / num2 def main(): mathProxy1 = MathProxy(MathImpl()) print(f'Arithmethic Operation of 9 and 5 is: Addition={mathProxy1.addition(9,5)},' + f'Substraction={mathProxy1.substraction(9,5)}, Multiplication={mathProxy1.multiplication(9, 5)} and' + f'Division is {mathProxy1.division(9,5)}') print('-----------------------------------------------------') mathProxy1 = MathProxy(MathRemote()) print(f'Arithmethic Operation of 9 and 5 is: Addition={mathProxy1.addition(9,5)},' + f'Substraction={mathProxy1.substraction(9,5)}, Multiplication={mathProxy1.multiplication(9, 5)} and' + f'Division is {mathProxy1.division(9,5)}') if __name__ == '__main__': main()
import abc from abc import ABC class AbstractCoffee(ABC): @abc.abstractmethod def get_cost(self): pass @abc.abstractmethod def get_ingredients(self): pass def get_tax(self): return 0.1*self.get_cost() class ConcreteCoffee(AbstractCoffee): def get_cost(self): return 5.0; def get_ingredients(self): return "cofee power, water"; class IndianCoffee(AbstractCoffee): def get_cost(self): return 9.0; def get_ingredients(self): return "spice, ginger, cordmam"; class CoffeeDecorator(AbstractCoffee): def __init__(self, decorator): self.decorator = decorator def get_cost(self): return self.decorator.get_cost() def get_ingredients(self): return self.decorator.get_ingredients() class SugarCoffeeDecorator(CoffeeDecorator): def __init__(self, decorator): self.decorator = decorator def get_cost(self): return self.decorator.get_cost() + 0.25 def get_ingredients(self): return self.decorator.get_ingredients() + ", suger" class MilkCoffeeDecorator(CoffeeDecorator): def __init__(self, decorator): self.decorator = decorator def get_cost(self): return self.decorator.get_cost() + 0.50 def get_ingredients(self): return self.decorator.get_ingredients() + ", milk" if __name__ == '__main__': mcd = MilkCoffeeDecorator(SugarCoffeeDecorator(ConcreteCoffee())) spCoffee = mcd.get_cost() * mcd.get_tax() print(f'The cost of coffee is : ' + str(spCoffee)) print('The ingredients of coffee is : ' + mcd.get_ingredients()) indCoffee = MilkCoffeeDecorator(SugarCoffeeDecorator(IndianCoffee())) spCoffee = indCoffee.get_cost() * indCoffee.get_tax() print(f'The cost of coffee is : ' + str(spCoffee)) print('The ingredients of coffee is : ' + indCoffee.get_ingredients())
#To create a single node in binary tree #class class Node: def __init__(self,data): self.left=None self.right=None self.data=data #print def PrintTree(self): print(self.data) tree=Node(25) #calling print function tree.PrintTree()
#Identify the biggest and smallest key in a doubly linked list containing integers. #node class class node: #constructor def __init__(self,data): #instances self.data = data self.prev = None self.next = None #linkedlist class class LinkedList: def __init__(self): #initialization self.head = None #printing list def display(self): ele = [] cur = self.head while cur: ele.append(cur.data) cur = cur.next print("Doubly LinkedList: ",ele) #finding largest and smallest def largeandsmall(self): cur = self.head large = self.head.data small = self.head.data while cur: if cur.data > large: large = cur.data if cur.data < small: small = cur.data cur = cur.next print("Largest element is: ",large) print("Smallest node is: ",small) #initialization DLL = LinkedList() #creating nodes and adding it to the lnked list DLL.head = node(100) DLL.head.next = node(20) DLL.head.next.next = node(30) #function calling DLL.display() DLL.largeandsmall(
#ascii password generator #using python andaconda #TO EXECUTE -> $pythonw ctfPass.py #by joe hollon import random import time #method 2 random number way(ascii) #set up a random number generator that took the ascii values 65-122 randomly picked the range count = 0 sum = 83 sumList = [] word = [] #this loop automates me running the program a billion times while True: #reset result result = 0 #always append 83 to the begening of the list sumList.append(83) word.append("S") #if sum is 1000 or count is less then 9 #append the random number to the list #TODO take out the sum meaningless right now while count < 9: #change teh first random value for bigger range r = random.randint(60, 122) sumList.append(r) word.append(chr(r)) count +=1 for sym in sumList: result += sym #swap index 0 with index 1 first, second = word[0], word[1] word[0] = second word[1] = first if result == 1000: print("\n===========================================================") print(sumList) print("Ascii Sum = " + str(result)) toWord = ''.join(map(str, word)) toWord = ''.join(map(str, word)) print("===========================================================") print("\t\t password = " + toWord) print("===========================================================") print("\n") break else: #sum up all values in list print("\n") print(sumList) for sym in sumList: result += sym print("Ascii Sum = " + str(result)) toWord = ''.join(map(str, word)) print("===========================================================") print("\t\t\t" + toWord) print("===========================================================") #clear list for next increment sumList.clear() word.clear() #set counter to 0 so second loop to execute took me forever to figure out count = 0 #tell me when at the bottom of outerLoop print("Loading the next combination.........")
""" This is a logger module, to simplify logging to the screen. Logs messages are printed in the following format: LOG LEVEL : [ Timestamp ] : Message Log levels include NONE, ERROR, WARNING, INFO and DEBUG. No log messages above current verbose level will be printed. """ import sys import datetime class Logger: """ Logger class, handles printing log messages based on set verbosity level. """ # Logging levels NONE = 0 ERROR = 1 WARNING = 2 INFO = 3 DEBUG = 4 _verbose = ERROR @property def verbose(self): """Current verbosity level of the program""" return self._verbose @verbose.setter def verbose(self, value): """Set current verbosity level of the program :param value: desired verbosity level: NONE, ERROR, WARNING, INFO, DEBUG :return: nothing """ if value > self.DEBUG: value = self.DEBUG if value < self.NONE: value = self.NONE self._verbose = value def __init__(self, log_level): self.verbose = log_level def log(self, log_level, text): """ Log data to stderr :param log_level: log level, see Application.LOG_SOMETHING constants. :param text: text to print :return: nothing """ timestamp = '['+str(datetime.datetime.now())+']' if log_level == self.ERROR: if self.verbose >= self.ERROR: print("ERROR :", timestamp, ":", str(text), file=sys.stderr) return if log_level == self.WARNING: if self.verbose >= self.WARNING: print("WARN :", timestamp, ":", str(text), file=sys.stderr) return if log_level == self.INFO: if self.verbose >= self.INFO: print("INFO :", timestamp, ":", str(text), file=sys.stderr) return if log_level == self.DEBUG: if self.verbose >= self.DEBUG: print("DEBUG :", timestamp, ":", str(text), file=sys.stderr) return def error(self, text): """ Log error message :param text: text to print :return: nothing """ self.log(self.ERROR, text) def warning(self, text): """ Log warning message :param text: text to print :return: nothing """ self.log(self.WARNING, text) def info(self, text): """ Log info message :param text: text to print :return: nothing """ self.log(self.INFO, text) def debug(self, text): """ Log debug message :param text: text to print :return: nothing """ self.log(self.DEBUG, text)
""" Problem Statement: We have a collection of stones, each stone has a positive integer weight. Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: If x == y, both stones are totally destroyed; If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) """ class Solution: def lastStoneWeight(self, stones: List[int]) -> int: def smash(stones) -> int: stones_sorted = sorted(stones) l = len(stones_sorted) if l >= 2: y = stones_sorted[l-1] x = stones_sorted[l-2] if y == x: new = stones_sorted[:l-2] return smash(new) #Recursive else: stones_sorted[l-2] = y-x new = stones_sorted[:l-1] return smash(new) elif l == 1: return stones_sorted[0] else: return 0 return smash(stones) """ Example 1: Input: [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. """
""" Problem Statement: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Example 2: Input: 11000 11000 00100 00011 Output: 3 """ #I've used the Depth-First search algorithm. I wasn't know about it before this problem. So, I'm very thankful for LeetCode #because each challenge add new thing to my knowledge. class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 length1 = len(grid) length2 = len(grid[0]) count = 0 def DepthFirst(grid,i,j): if i<0 or j<0 or i>length1-1 or j >length2-1 or grid[i][j] != '1': return grid[i][j] = '#' DepthFirst(grid,i+1,j) DepthFirst(grid,i-1,j) DepthFirst(grid,i,j+1) DepthFirst(grid,i,j-1) for i in range(length1): for j in range(length2): if grid[i][j] == '1': DepthFirst(grid,i,j) count += 1 return count
import string # turn a doc into clean tokens def clean_doc(doc): # replace '--' with a space ' ' doc = doc.replace('--', ' ') # split into tokens by white space tokens = doc.split() # remove punctuation from each token table = str.maketrans('', '', string.punctuation) tokens = [w.translate(table) for w in tokens] # remove remaining tokens that are not alphabetic tokens = [word for word in tokens if word.isalpha()] # make lower case tokens = [word.lower() for word in tokens] return tokens
import sqlite3 import webbrowser def search(): # database file connection database = sqlite3.connect("Database") # cursor objects are used to traverse, search, grab, etc. information from the database, similar to indices or pointers cursor = database.cursor() temp = input("Do you understand how to search(y/n)?\n") if temp =="y" or "Y": tempSearch = input("Enter a mySQL query :\n") cursor.execute(tempSearch) searchResult = cursor.fetchall() for x in searchResult: print(x) elif temp =="n" or "N": webbrowser.open('https://www.digitalocean.com/community/tutorials/introduction-to-queries-mysql') else: pass database.close()
import sqlite3 # database file connection database = sqlite3.connect("Database") # cursor objects are used to traverse, search, grab, etc. information from the database, similar to indices or pointers cursor = database.cursor() def delete_instructor(): targetCRN = input("please enter the ID of the instructor you want to delete") cursor.execute("DELETE FROM INSTRUCTOR WHERE ID = (?);", (targetCRN))
class User: # Base Class that all classes are built off of def __init__(self, user_id="7", first_name="7", last_name="7", passcode="7"): # This is the initialization function # if no paramaters are passed into it, the default listed will be used self.user_id = user_id # User ID - It must be UNIQUE self.first_name = first_name # User's First Name self.last_name = last_name # User's Last Name self.passcode = passcode # Passcode is used for initial Login
# multiple linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values #Encoding categorical data # Encoding categorical data from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer ct = ColumnTransformer([('encoder', OneHotEncoder(), [3])], remainder='passthrough') X=np.array(ct.fit_transform(X), dtype=np) #Avoiding Dummy variable X=X[:,1:] # it mean start from column 1 but it does it automatically by it self # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train.reshape(-1,1))""" #fitting Multiple Linear Regression training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train ) #fitting Multiiple linear Regression Testing set y_pred= regressor.predict(X_test) #Building optimal model using backword Elemination import statsmodels.api as sm X=np.append(arr=np.ones((50,1)).astype(int),values= X , axis= 1) X_opt=np.array(X[:,[0,1,2,3,4,5]],dtype= float) regressor_OLS= sm.OLS(endog=y, exog=X_opt).fit() regressor_OLS.summary() X=np.append(arr=np.ones((50,1)).astype(int),values= X , axis= 1) X_opt=np.array(X[:,[0,2,3,4,5]],dtype= float) regressor_OLS= sm.OLS(endog=y, exog=X_opt).fit() regressor_OLS.summary() X=np.append(arr=np.ones((50,1)).astype(int),values= X , axis= 1) X_opt=np.array(X[:,[0,2,4,5]],dtype= float) regressor_OLS= sm.OLS(endog=y, exog=X_opt).fit() regressor_OLS.summary() X=np.append(arr=np.ones((50,1)).astype(int),values= X , axis= 1) X_opt=np.array(X[:,[0,2,5]],dtype= float) regressor_OLS= sm.OLS(endog=y, exog=X_opt).fit() regressor_OLS.summary()
#pragati Vilas Kate gr no.11810418 def max_of_two(x,y): if x>y: return x return y x=int(input()) y=int(input()) z=int(input()) a=max_of_two(z,max_of_two(x,y)) print(a)
import tkinter as tk from tkinter import filedialog from tkinter import * from PIL import ImageTk, Image def UploadAction(event=None): filename = filedialog.askopenfilename() #path2.insert(END, filename) im = Image.open(filename) im = im.resize((320, 320)) tkimage = ImageTk.PhotoImage(im) myvar = Label(frame, image=tkimage) myvar.image = tkimage myvar.place(x=730, y=50) passwordlab = Label(root, text="Password", font=("Times New Roman", 11)).place(x=40, y=250) e1 = tk.Entry(root, show="*", font=('Arial', 14)).place(x=120, y=250) button3 = tk.Button(root, text='ENCRYPT', command=encrytingaction,width =10 ,height =4).place(x=150, y=300) print('Selected:', filename) def UploadAction1(event=None): filename1 = filedialog.askopenfilename( initialdir="C:/Users/MainFrame/Desktop/", title="Open Text file", filetypes=(("Text Files", "*.txt"),) ) #pathh.insert(END, filename1) filename1 = open(filename1, 'r') data = filename1.read() txtarea.insert(END, data) filename1.close() print('Selected:', filename1) def encrytingaction(event=None):#callencrytingfucntion encryptwin = Toplevel(root) encryptwin.title("ENCRYPTED OUTPUT") encryptwin.geometry("900x700") encryptwin.config(bg="skyblue") left_frame = Frame(encryptwin, width=200, height=400, bg='white') left_frame.grid(row=0, column=0, padx=10, pady=5) right_frame = Frame(encryptwin, width=650, height=400, bg='white') right_frame.grid(row=0, column=1, padx=10, pady=5) Label(left_frame, text="Encrypted Image").grid(row=0, column=0, padx=5, pady=5) tool_bar = Frame(left_frame, width=180, height=185) tool_bar.grid(row=2, column=0, padx=5, pady=5) def decryptingaction(event=None): # call decrypting fuction print() passwordlab1 = Label(encryptwin, text="Password", font=("Times New Roman", 11)).place(x=40, y=500) e2 = tk.Entry(encryptwin, show="*", font=('Arial', 14)).place(x=120, y=500) def UploadAction3(): filename3 = filedialog.askopenfilename() dm = Image.open(filename3) def UploadAction4(): print() encryptedimage = Label(encryptwin, text="Select the encrypted Image", font=("Times New Roman", 11)).place(x=40, y=450) button3 = tk.Button(encryptwin, text='Select', command=UploadAction3).place(x=230, y=450) button4 = tk.Button(encryptwin, text='DECRYPT', command=UploadAction4,width =10 ,height =4).place(x=400, y=450) button4 = tk.Button(tool_bar, text='DECRYPT', command=decryptingaction).grid(row=0, column=0, padx=10, pady=30,ipadx=10) # Label(tool_bar, text="DECRYPT", relief=RAISED).grid(row=0, column=0, padx=10, pady=30,ipadx=10) # ipadx is padding inside the Label widget # Label(tool_bar, text="Filters", relief=RAISED).grid(row=0, column=1, padx=5, pady=3, ipadx=10) Label(tool_bar, text="Select").grid(row=1, column=0, padx=5, pady=5) # Label(tool_bar, text="Crop").grid(row=2, column=0, padx=5, pady=5) # Label(tool_bar, text="Rotate & Flip").grid(row=3, column=0, padx=5, pady=5) # Label(tool_bar, text="Resize").grid(row=4, column=0, padx=5, pady=5) # Label(tool_bar, text="Exposure").grid(row=5, column=0, padx=5, pady=5) root = tk.Tk() root.title("STEGENOGRAPHY ENCRYPTION ") root['bg'] = '#fb0' txtarea = Text(root, width=40, height=20) txtarea.pack(pady=50) # pathh = Entry(root) # pathh.pack(side=LEFT, expand=True, fill=X, padx=10) # path2= Entry(root) # path2.pack(side=LEFT, expand=True, fill=X, padx=10) root.geometry("1090x700") var = StringVar() var2 = StringVar() frame = Frame(root).place(x=40, y=600) canvas = Canvas(root) canvas.create_line(300, 35, 300, 200, dash=(5, 2)) First_file = Label(root, text="STEGENOGRAPHY ENCRYPTION", font=("Times New Roman", 18)).place(x=350, y=10) First_file = Label(root, text="Select the Picture to Hide", font=("Times New Roman", 11)).place(x=40, y=150) Second_file = Label(root, text="Select the file to be encrypted", font=("Times New Roman", 11)).place(x=40, y=70) # text=Text(root).place(x=400,y=70) button = tk.Button(root, text='Select', command=UploadAction).place(x=240, y=150) button2 = tk.Button(root, text='Select', command=UploadAction1).place(x=240, y=70) #button4 = tk.Button(root, text='DECRYPT', command=decryptingaction).place(x=180, y=250) root.mainloop() #------------------------- # # # import tkinter and all its functions # from tkinter import * # # root = Tk() # create root window # root.title("Basic GUI Layout") # title of the GUI window # root.maxsize(900, 600) # specify the max size the window can expand to # root.config(bg="skyblue") # specify background color # # # Create left and right frames # left_frame = Frame(root, width=200, height=400, bg='grey') # left_frame.grid(row=0, column=0, padx=10, pady=5) # right_frame = Frame(root, width=650, height=400, bg='grey') # right_frame.grid(row=0, column=1, padx=10, pady=5) # # # Create frames and labels in left_frame # Label(left_frame, text="Original Image").grid(row=0, column=0, padx=5, pady=5) # # # load image to be "edited" # image = PhotoImage(file="rain.gif") # original_image = image.subsample(3, 3) # resize image using subsample # Label(left_frame, image=original_image).grid(row=1, column=0, padx=5, pady=5) # # # Display image in right_frame # Label(right_frame, image=image).grid(row=0, column=0, padx=5, pady=5) # # # Create tool bar frame # tool_bar = Frame(left_frame, width=180, height=185) # tool_bar.grid(row=2, column=0, padx=5, pady=5) # # # Example labels that serve as placeholders for other widgets # Label(tool_bar, text="Tools", relief=RAISED).grid(row=0, column=0, padx=5, pady=3, # ipadx=10) # ipadx is padding inside the Label widget # Label(tool_bar, text="Filters", relief=RAISED).grid(row=0, column=1, padx=5, pady=3, ipadx=10) # # # Example labels that could be displayed under the "Tool" menu # Label(tool_bar, text="Select").grid(row=1, column=0, padx=5, pady=5) # Label(tool_bar, text="Crop").grid(row=2, column=0, padx=5, pady=5) # Label(tool_bar, text="Rotate & Flip").grid(row=3, column=0, padx=5, pady=5) # Label(tool_bar, text="Resize").grid(row=4, column=0, padx=5, pady=5) # Label(tool_bar, text="Exposure").grid(row=5, column=0, padx=5, pady=5) # # root.mainloop()
# Pythonの型 ## 数値型 """ ・整数(int) ・少数、実数(float) ・複素数 """ i = 0 i += 1 print(i) # 1 """ 以下は同じ i = i + 1 i += 1 """ print(10 - 2) # 8 print(10 * 2) # 20 print(10 // 3) # 3 print(10 % 3) # 1 print(10 ** 3) # 1000 """ /...小数点が返ってくる //...切り捨て """ print(5 // 2) # 2 print(5 / 2) # 2.5 ## 文字列 print('I love ' + 'Python') # I love Python print('Hello' * 3) # HelloHelloHello print('I say ' + ('hello' * 3)) # I say hellohellohello x = 'I' y = 'love' z = 'Python' print(x + y + z) # IlovePython
# コメント print("Hello world") """ コメント """ print(10) print(10 + 5) # 足し算 print(10 - 5) # 引き算 print(10 * 5) # 掛け算 print(10 / 5) # 割り算 print(10 % 3) # 余り print("10 + 5") # 文字列 print(10 + 5) # 数値 """ 変数とは、データを入れておく箱のようなもの 「変数名 = 値」で定義する。右辺を左辺に代入する 変数で使用できるのは、アルファベット、数字(先頭は不可)、「_」 """ name = 'Tom' age = 20 print(name) # Tom print('name') # name """ 変数は値を上書きすることができる """ x = 10 print(x) # 10 x = 20 print(x) # 20 """ 省略形でも書ける """ x = x + 5 x += 5 """ 文字列の連結 「+」で文字列を連結できる """ print("Hello " + "world") name = "Tom" print("My name is" + name)
import math from tkinter.constants import LEFT from pickle import FALSE #global gIterations = 0 recursiveCount = 0 def NaiveCount(Max, Digit): TotalCount = 0; iterationCalc = 0 for x in range(0, int(n)+1,1): num = x; while (num > 0): iterationCalc = iterationCalc + 1 #s = str(x) + ":" + str(num) #print (s) if (num != 0) and (num % 10) == int(Digit): TotalCount = TotalCount + 1 #s = "Match: " + str(TotalCount) #print(s) num = int(num / 10); calc = int(n) * math.log(int(n), 10) s = "Brute Force - Total Count: " + str(TotalCount) + " IterationCount:" + str(iterationCalc) + " Theoretical Calc: " + str(calc) print(s) return; # add my comments def CountDigitN(num, dd, depth, sum): global recursiveCount global gIterations recursiveCount += 1 count = 0 weight = 10**depth digit = num % 10 prevsum = sum sum += digit*weight cweight = 1 #print(dd) gIterations +=1 if (depth > 1): cweight = (10 ** (depth-1)) * depth #s = "CountDigit-" + str(num) + " Digit-" + str(digit) + " Depth-" + str(depth) + " Cweight-" + str(cweight) + " Weight-" + str(weight) + " Sum-" + str(sum)+ " Recursive-" + str(recursiveCount) #print(s) # Special case - lowest digit is either 1 or 0 if (depth == 0): if digit >= dd: count = 1 else: count = 0 else: count = digit*cweight # if this digit == the match, then count lower significant digits including itself if (digit == dd): count += prevsum + 1 #if this digit > match, then include the sum elif digit > dd: count += weight #Non base case. if num >= 10: count += CountDigitN(int(num/10), dd, depth+1, sum) #print(count) recursiveCount -= 1 return count n = input("Enter N - 0 to N\n") b = input("Enter Digit\n") #n = '973' #b = '2' NaiveCount(n, b) gIterations = 0 count = CountDigitN(int(n), int(b), 0, 0) s = "Optimized - Count: " + str(count) + " Iterations: " + str(gIterations) print(s)
""" Commenting skills: TODO: above every line of code comment what you THINK the line below does. TODO: execute that line and write what actually happened next to it. See example for first print statement """ import platform # I think this will print "hello! Let's get started" by calling the print function. print("hello! Let's get started") # it printed "hello! Let's get started" #Is a vairable for a list of those words some_words = ['what', 'does', 'this', 'line', 'do', '?'] # For the function word in the list some_words, it prints a random value from some_words for word in some_words: print(word)#loop prints each word in the list until all words have been printed # For the function x in the list some_words, it prints the value of x in some_words for x in some_words: print(x)#does the exact same function print(some_words) #If the length of the variable in some_words is greater than 3, than it will print 'some_words contains more than 3 words if len(some_words) > 3: print('some_words contains more than 3 words')#checks the list and prints the string def usefulFunction(): """ You may want to look up what uname does before you guess what the line below does: https://docs.python.org/3/library/platform.html#platform.uname """ #The following line prints a named tuple of the platforms system, node, release, version, machine and processor print(platform.uname())#Results as expected usefulFunction()
''' 1、简述变量命名规范 ''' # 变量命名规范 # 1.变量必须要要有数字,字母,下划线任意组成 # 2.变量需要具有可描述性 # 3.变量命名不能过长,不能以数字开头,不能包含中文,不能包含python关键字 # 4.推荐1,使用驼峰体:ZhangZheng = me # 推荐2:使用下划线:my_name_ha = zz ''' 2.name = input(">>>") name变量是什么数据类型? ''' # name = input(">>>") # str转换为int # name = int(name) # print(name,type(name)) # input输入的数据类型在没有转换的情况下,都是是字符串str类型 ''' 3、if条件语句的基本结构? ''' # if条件语句基本结构有5种 # A.if #if 2 > 3: # print(nb) #B.if...else 二必选一 # age = input("how old are you?") # if age == '13': # print("T") # else: # print("F") # # name = input("what's your name?") # if name == 'zhangzheng': # print('nb') # else: # print('sb') #C.if...elif...elif # age = input('how old are you?') # if age == '18': # print('18真好') # elif age == '20': # print('20不错') # elif age == '25': # print('25也行') #D.if...elif..elif...else # age = input('how old are you?') # if age == '18': # print('18真好') # elif age == '25': # print('25也还行') # elif age == '30': # print('sb') # else: # if age <= '17': # print('谢谢夸奖') # elif age >= '31': # print('滚你大爷') #E.if嵌套 # name = input("who's your name?") # age = input('how old are you?') # if name == 'zz': # if age == '20': # print('说得对') # else: # age >= '20' # print('请重新输入') # print('您还有3次机会') # else: # print('用户名错误') ''' 4、⽤print打印出下⾯内容: ⽂能提笔安天下, 武能上马定乾坤. ⼼存谋略何⼈胜, 古今英雄唯是君. ''' # mes=''' # ⽂能提笔安天下, # 武能上马定乾坤. # ⼼存谋略何⼈胜, # 古今英雄唯是君. # ''' # print(mes) ''' 5、利⽤if语句写出猜⼤⼩的游戏: 设定⼀个理想数字比如: 66, 让⽤户输入数字, 如果比66⼤, 则显⽰猜测的结果 ⼤了; 如果比66⼩, 则显⽰猜测的结果⼩了;只有等于66, 显⽰猜测结果正确。 ''' # num = input('请输入预测的数字:') # num = int(num) # if num == 66: # print('猜测结果正确') # elif num <= 65: # print('猜测数值过小,请重新输入!') # elif num >= 67: # print('猜测数值过大,请重新输入!') ''' 6、提⽰⽤户输入他的年龄, 程序进⾏判断. 如果⼩于10, 提⽰⼩屁孩, 如果⼤于10, ⼩于 20, 提⽰青春期叛逆的⼩屁孩. 如果⼤于20, ⼩于30. 提⽰开始定性, 开始混社会的⼩屁孩⼉, 如果⼤于30, ⼩于40. 提⽰看老⼤不⼩了, 赶紧结婚⼩屁孩⼉. 如果⼤于40, ⼩ 于50. 提⽰家⾥有个不听话的⼩屁孩⼉. 如果⼤于50, ⼩于60. 提⽰⾃⼰马上变成不听 话的老屁孩⼉. 如果⼤于60, ⼩于70. 提⽰活着还不错的老屁孩⼉. 如果⼤于70, ⼩于 90. 提⽰⼈⽣就快结束了的⼀个老屁孩⼉. 如果⼤于90以上. 提⽰. 再见了这个世界. ''' # age = int(input('how old are you?')) # if age <= 10: # print('小屁孩') # elif age <= 20: # print('青春期叛逆的⼩屁孩') # elif age <= 30: # print('开始定性, 开始混社会的⼩屁孩⼉') # elif age <= 40: # print('老⼤不⼩了, 赶紧结婚⼩屁孩⼉') # elif age <= 50: # print('家⾥有个不听话的⼩屁孩⼉') # elif age <= 60: # print('⾃⼰马上变成不听 话的老屁孩⼉') # elif age <= 70: # print('活着还不错的老屁孩⼉') # elif age > 90: # print('再见了这个世界') ''' 7、单⾏注释以及多⾏注释? ''' # 注释为了帮助解释说明 # 单行注释:# # 多行注释:'''被注释内容''' """被注释内容""" ''' 8、简述你所知道的Python3x和Python2x的区别? ''' # python2.x: # 1.默认ACISS编码 # 2.print'haha' # 3.input内容数据类型为int # python3.x: # 1.默认utf-8 # 2.print('hh') # 3.input内容数据类型为str ''' 9、提⽰⽤户输入⿇花藤. 判断⽤户输入的对不对. 如果对, 提⽰真聪明, 如果不对, 提 ⽰你 是傻逼么 ''' # name = input('请输入您的用户名:') # if name == '麻花藤': # print('真聪明') # else: # print('你是傻逼么') ''' 10、使⽤while循环输入 1 2 3 4 5 6 8 9 10 ''' num = 1 while num < 11: if num == 7: num = num + 1 continue print(num) num = num + 1 ''' 11、求1-100的所有数的和 ''' # a = 0 # b = 1 # while b < 101: # a = a + b # b = b + 1 # print(a) ''' 12、输出 1-100 内的所有奇数 ''' # num = 1 # while num < 100: # print(num) # num = num + 2 # cont=1 # while cont < 99: # if cont % 2 == 1: # cont = cont + 2 # print(cont) ''' 13、输出 1-100 内的所有偶数 ''' # num = 0 # while num < 100: # print(num) # num = num + 2 # cont=0 # while cont < 100: # if cont % 2 ==0: # cont = cont + 2 # print(cont) ''' 14、求1-2+3-4+5 ... 99的所有数的和 ''' # num = 0 # count = 0 # while num < 99: # num = num +1 # if num % 2 ==0: # count = count - num # else: # count = count + num # print(count) # num = 0 # for i in range(100): # if i % 2 == 0: # num = num - i # else: # num = num + i # print(num)
''' 从“学生选课系统” 这几个字就可以看出来,我们最核心的功能其实只有 选课。 角色: 学生、管理员 功能: 登陆 : 管理员和学生都可以登陆,且登陆之后可以自动区分身份 选课 : 学生可以自由的为自己选择课程 创建用户 : 选课系统是面向本校学生的,因此所有的用户都应该由管理员完成 查看选课情况 :每个学生可以查看自己的选课情况,而管理员应该可以查看所有学生的信息 工作流程: 登陆 :用户输入用户名和密码 判断身份 :在登陆成果的时候应该可以直接判断出用户的身份 是学生还是管理员 学生用户 :对于学生用户来说,登陆之后有三个功能 1、查看所有课程 2、选择课程 3、查看所选课程 4、退出程序 管理员用户:管理员用户除了可以做一些查看功能之外,还有很多创建工作 1、创建课程 2、创建学生学生账号 3、查看所有课程 4、查看所有学生 5、查看所有学生的选课情况 6、退出程序 ''' # import json # import os # import sys # class student: # def __init__(self,name): # self.name = name # # def list_class(self): # with open("new_class", 'r', encoding="utf8") as f_read_class: # tmp = {} # for index, i in enumerate(f_read_class.read().split("|"),1): # print(index, i) # tmp[str(index)] = i # return tmp # # # def choose_class(self): # tmp = self.list_class() # stu_choose_class = input("请选择你要选的课程的序号") # if stu_choose_class in tmp: # with open("user_class", 'r', encoding="utf8") as f: # user_class = json.load(f) # if user_class.get(self.name): # user_class.get(self.name).append(tmp[stu_choose_class]) # else: # user_class.setdefault(self.name,[tmp[stu_choose_class]]) # # with open("user_class", 'w', encoding="utf8") as f: # json.dump(user_class,f,ensure_ascii=False) # # # # def list_stu_class(self): # with open("user_class", 'r', encoding="utf8") as f: # user_class = json.load(f) # # print(user_class.get(self.name),type(user_class.get(self.name))) # stu_list=user_class.get(self.name) # stu_list = list(set(stu_list)) # print(stu_list) # # def exit(self): # exit() # # def show(self): # gongneng = {"查看课程": self.list_class, '选择课程': self.choose_class, "查看所选课程": self.list_stu_class,"退出":self.exit} # while 1: # tmp = {} # for index, i in enumerate(gongneng, 1): # print(index, i) # tmp[str(index)] = gongneng[i] # C = input("请输入你的选择") # if C in tmp: # tmp[C]() # # class admin: # def __init__(self,name): # self.name=name # # # s=student("zz") # s.show() def warppe1(x): def inner1(*args,**kwargs): print('inner1') return return inner1 def warppe2(x): def inner2(*args,**kwargs): print('inner1') return return inner2 class zz: @warppe1 @warppe2 def test(self): print('class-zz') # zz.test(0) class A: def __init__(self): self.a = 1 self.b = 2 def __len__(self): return len(self.__dict__) a = A() print(len(a))
name =input("Enter file: ") if len(name) < 1: name = "mbox-short.txt" fhand = open(name) lst=list() #create a list with hours of line start with From for line in fhand: if not line.startswith("From "): continue else: x=line.split() lst.append(x[5]) ls=list() for y in lst: y=y.split(":") ls.append(y[0]) #create dictionary of hour and its count counts = dict() l=list() for hr in ls: counts[hr]=counts.get(hr,0)+1 #sort list of dictionary z=sorted(counts.items()) for k,v in z: print(k,v)
def add(x,y): return x+y for i in range(0,10): d = add(i, i*2) print(d)
# Exercicio 11 from random import randrange palavras = input("Digite as palavras: ") palavras = palavras.split(" ") uma_palavra = palavras[randrange(0, len(palavras))] palavra_forca = ["_" for i in uma_palavra] chance = 1 while chance < 7 and palavra_forca.count("_") != 0: letra = input("Digite uma letra: ") if letra in uma_palavra: # verifica se a palavra tem a letra digitada print("A palavra é: ", end=" ") for p in range(len(uma_palavra)): if letra == uma_palavra[p]: del palavra_forca[p] palavra_forca.insert(p,letra) print(" ".join(palavra_forca)) else: print("-> Você errou pela " + str(chance) + "a vez. Tente de novo!") chance = chance + 1 if palavra_forca.count("_") == 0: print("Parabéns! Você acertou a palavra.") else: print("Forca! Fim de jogo.")
#Stemming - stemming is a method of finding the roots of the words # from the sentence For eg: written = write from nltk.stem import PorterStemmer #importing the PortStemmer function from nltk.tokenize import word_tokenize #importing the word_tokenize function data = " A cemetery is a placing where dead people's bodies or their ashes are buried" #myfile = open('Text1.txt', 'r') #Reading file named Text1 #data = myfile.read().replace('\n', '')#File is converted to array of letters #ex = ["write","writing","written"] ps = PorterStemmer() #stemming for i in word_tokenize(data): #Tokenizing the word print(ps.stem(i))
from collections import defaultdict class Graph: def __init__(self, vertex, edge): # self.vertex = set(vertex) # frozenset - we want vertices to be unordered sets, we cannot have sets of sets, so it is sets of frozem sets self.edge = set(frozenset((u, v)) for u, v in edge) # defaultdict is to map all the neighbours of each and every vertex/node self._neighbours = defaultdict(set) # below vertex loop is needed if self._neighbours is a normal dict. for defaultdict, # we dont need to add vertex and default to set # if not exists, defaultdict, when creating edges, default dict will initialize vertex. # for v in vertex: # self.addVertex(v) for u, v in self.edge: self.addEdge(u, v) # self._neighbours[u].add(v) # self._neighbours[v].add(u) # def addVertex(self, vertex): # self.vertex.add(vertex) # if vertex not in self._neighbours: # self._neighbours[vertex]= set() # self._neighbours.setdefault(vertex) def addEdge(self, u, v): # self.addVertex(u) # self.addVertex(v) self.edge.add(frozenset([u, v])) self._neighbours[u].add(v) self._neighbours[v].add(u) def degree(self, vertex): # return sum(1 for e in self.edge if vertex in e) return len(self._neighbours[vertex]) def neighbours(self, vertex): return self._neighbours[vertex] def removeEdge(self, u, v): edge = frozenset([u, v]) if edge in self.edge: # this condition is needed to prevent keyerror's i.e if non existing edges were passed to this function, # this should not throw error. So we remove only if edge exists, else do nothing as edge doesnt exist self.edge.remove(edge) self._neighbours[u].remove(v) self._neighbours[v].remove(u) def removeVertex(self, vertex): # to delete is needed, during iteration of self.neighbours, # I cannot delete, otherwise python will throw runtime error. Set changed size during iteration todelete = list(self.neighbours(vertex)) for v in todelete: self.removeEdge(vertex, v) del self._neighbours[vertex] def get_paths(self, start, end, path=[]): path = path + [start] paths = [] if start == end: return [path] if start not in self._neighbours: return [] for vertex in self._neighbours[start]: if vertex not in path: new_paths = self.get_paths(vertex, end, path) for p in new_paths: paths.append(p) return paths @property def numOfEdges(self): return len(self.edge) @property def numOfVertex(self): return len(self._neighbours) if __name__ == "__main__": graph = Graph({1, 2, 3}, {(1, 2), (2, 3)}) assert graph.degree(1) == 1 assert graph.degree(2) == 2 assert graph.degree(3) == 1 assert set(graph.neighbours(2)) == {1, 3} assert set(graph.neighbours(1)) == {2} assert set(graph.neighbours(3)) == {2} assert graph.numOfVertex == 3 and graph.numOfEdges == 2 graph.removeEdge(1, 2) assert graph.numOfVertex == 3 and graph.numOfEdges == 1 graph.removeEdge( 1, 3 ) # this edge doesnt exist. the if condition in removeEdge prevents this program from failure with KeyError assert graph.numOfVertex == 3 and graph.numOfEdges == 1 graph.addEdge(1, 2) assert graph.numOfVertex == 3 and graph.numOfEdges == 2 graph.removeVertex(2) assert graph.numOfVertex == 2 and graph.numOfEdges == 0 print("Okay") routes = { ("Mumbai", "Paris"), ("Mumbai", "Dubai"), ("Paris", "Dubai"), ("Paris", "New York"), ("Dubai", "New York"), ("New York", "Toronto"), } new_graph = Graph( {"Mumbai", "Paris", "Dubai", "New York", "Toronto"}, routes ) print(new_graph.get_paths("Mumbai", "New York"))
games = [] while True: menu = input("Val: ") if menu == "1": for l in games: print(l) elif menu == "2": games ={} games ["company"] = input ("Company: ") games ["game"] = input ("Game: ") games["year"] = int(input("Year")) games.append(games) elif menu == "3": for l in "games": if "games" in l: print("game exists!") elif menu == "4": with open('games.txt' , 'a+') as f: for game in games: f.write(str(game)) f.close() else: break
""" Moduł zawierający wszyskie funkcje służące do komunikacji oraz modyfikacji z bazą danych aplikacji """ import sqlite3 from tkinter import messagebox def check_login_is_free(): """Funkcja zwracająca listę loginów uzytkowników aktualnie znajdującyhc się w bazie danych @return (list)""" conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(""" SELECT login FROM workers """) list_of_user = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return list_of_user def create_list_of_users(): """Funkcja zwracająca liste aktualnych użytkowników w bazie dancyh w kolejności alfabetycznej @return (list)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute("""SELECT * FROM workers ORDER BY first_name""") list_of_users = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return list_of_users def add_user_to_database(first_name, last_name, login, password, role): """Funkcja która dodaje użytkownika o podanych argumentach do bazy danych Argumenty: @first_name(string) @last_name(string) @login(string) @password(string) @role(char: 'P', 'M', 'K')""" # check what role if role == 1: role = 'P' elif role == 2: role = 'K' elif role == 3: role = 'M' else: role = None conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() list_of_user = check_login_is_free() for user_login in list_of_user: if user_login[0] == login: messagebox.showerror("Error", "There is a user with this login") return if len(first_name) == 0: messagebox.showerror("Error", "Field first_name is empty") return elif len(last_name) == 0: messagebox.showerror("Error", "Field last_name is empty") return elif len(login) == 0: messagebox.showerror("Error", "Field login is empty") return elif len(password) == 0: messagebox.showerror("Error", "Field password is empty") return cur.execute("INSERT INTO workers VALUES (Null, :f_name, :l_name, :log, :passwd, :role)", { 'f_name': first_name, 'l_name': last_name, 'log': login, 'passwd': password, 'role': role }) # Commit Changes conn.commit() # Close Connection conn.close() messagebox.showinfo("User added", "You added user") return def delete_user_from_database(login): """Funkcja usuwająca użytkownika o zadanym loginie z bazy danych Argument @login(string)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() # Create table list_of_user = check_login_is_free() for user_login in list_of_user: if user_login[0] == login: cur.execute("DELETE from workers WHERE login='{}'".format(login)) messagebox.showinfo("Delete", "Successful deleted user") # Commit Changes conn.commit() # Close Connection conn.close() return if len(login) == 0: messagebox.showerror("Error", "Field login is empty") return # Commit Changes conn.commit() # Close Connection conn.close() messagebox.showerror("Error", "There isn't user with this login") return def check_user_in_database(login, password): """Funkcja sprawdzająca poprawność danych przekazanych przez argumenty z tymi znajdującymi sie w bazie dnaych Zwraca ona prawdę jeżeli dane są prawidłowe a fałsz w przeciwnym wypadku Argumenty: @login(string) @password(string) Return: @(boolean) """ conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(""" SELECT login, password FROM workers """) users = cur.fetchall() for user in users: if user[0] == login and user[1] == password: # Commit Changes conn.commit() # Close Connection conn.close() return True # Commit Changes conn.commit() # Close Connection conn.close() return False def get_name_actual_employee(login): """Funkcja która zwraca dane personalne użytkownika o przesłanym w argumencie loginie Argument: @login(string) return: @personality_actual_employee(string)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute("""SELECT first_name, last_name FROM workers WHERE login='{}'""".format(login)) actual_employee = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() personality_actual_employee = str(actual_employee[0][0] + " " + actual_employee[0][1]) return personality_actual_employee def get_id_actual_employee(login): """Funkcja która zwraca id użytkownika o przesłanym w argumencie loginie Argument: @login(string) Return: @actual_employee(integer)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute("""SELECT worker_id FROM workers WHERE login='{}'""".format(login)) actual_employee = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return actual_employee def get_role_actual_employee(login): """Funkcja która zwraca role użytkownika o przesłanym w argumencie loginie Argument: @login(string) Return: @actual_employee(character)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(f"""SELECT role FROM workers WHERE login='{login}'""") actual_employee = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return actual_employee def add_reservation_to_database(number_of_people, date, worker_id, first_name, last_name): """Funkcja która dodaje rezerwacje do bazy danych Argumenty: @number_of_people(integer) @date(datatime) @worker_id(integer) @first_name(string) @last_name(string) Return: @reservation_id(integer)""" conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() # book table cur.execute("INSERT INTO reservation VALUES (Null, :amount_of_people, :data, :worker_id, :first_name, :last_name)", { 'amount_of_people': number_of_people, 'data': date, 'worker_id': worker_id, 'first_name': first_name, 'last_name': last_name, }) # Commit Changes conn.commit() cur.execute(f"""SELECT reservation_id from reservation WHERE number_of_people = {number_of_people} AND first_name = '{first_name}' AND last_name = '{last_name}'""") reservation_id = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return reservation_id def get_all_reservation(): """Funkcja która zwraca wszystkie rezerwacje z bazy danych @return all_reservation(list of tuplets)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute("""SELECT * FROM reservation""") all_reservation = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return all_reservation def delete_old_reservation(actual_date): """Funkcja która usuwa rezerwacje które mineły z bazy danych Argumenty: @actual_date(datatime)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(f"""delete from reservation where data < {actual_date}""") # Commit Changes conn.commit() # Close Connection conn.close() def delete_reservation(list_of_reservation): """Funkcja która usuwa rezerwacje z bazy danych oraz w tabeli tables ustawia reservation_id na wartość NULL Argumenty: @list_of_reservation(list)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() for reservation in list_of_reservation: f_name = reservation.split()[0] l_name = reservation.split()[1] cur.execute(f"""UPDATE tables SET reservation_id = NULL WHERE table_id = (SELECT table_id FROM reservation INNER JOIN tables ON reservation.reservation_id = tables.reservation_id WHERE reservation.first_name = '{f_name}' AND reservation.last_name = '{l_name}')""") conn.commit() cur.execute(f"""delete FROM reservation WHERE first_name='{f_name}' AND last_name='{l_name}'""") # Commit Changes conn.commit() # Close Connection conn.close() def get_free_table(amount_of_people): """Funkcja która zwraca index pierwszego stolika który pomieści zadaną ilośc osób Argumenty: @amount_of_people(integer) Return: @table_id(integer)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(f"""SELECT table_id FROM tables WHERE number_of_people = {amount_of_people} and reservation_id is NULL ORDER BY table_id ASC LIMIT 1""") first_table = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return first_table def add_reservation_to_table(reservation_id, table_id): """Funkcja w rekordzie danego stolika dodaje id_rezerwacji Argumenty: @reservation_id(integer) @table_id(integer)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(f"""UPDATE tables SET reservation_id = {reservation_id} WHERE table_id = {table_id}""") # Commit Changes conn.commit() # Close Connection conn.close() def get_price_of_product(): """Funkcja która pobiera ceny produktów z bazy danych @return: list """ # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(f"""SELECT name, price from product""") price = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return price def add_order_to_database(product_list, worker_id, table_id, discount): """Funkcja dodająca zamówienie do bazy danych @argument: product_list(list)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute("INSERT INTO orders VALUES (Null, :table_id, :discount, :worker_id)", { 'table_id': table_id, 'discount': discount, 'worker_id': worker_id, }) # Commit Changes conn.commit() cur.execute("""SELECT last_insert_rowid()""") order_id = cur.fetchall() order_id = order_id[0][0] for product in product_list: cur.execute("INSERT INTO product_order VALUES ( :amount, :order_id, :name)", { 'amount': product[1], 'order_id': order_id, 'name': product[0], }) # Commit Changes conn.commit() # Close Connection conn.close() def get_all_order(): """Funkcja zwracająca listę z wszystkimi aktualnymi zamówieniami """ # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(f"""select order_id, name, amount from product_order order by order_id;""") active_orders = cur.fetchall() # Commit Changes conn.commit() # Close Connection conn.close() return active_orders def delete_orders_from_database(order_id): """Funkcja usuwająca zamówienie od podanym id z bazy danych @Argumnety: oderd_id(int)""" # create database conn = sqlite3.connect('workers_db.db') # create cursor cur = conn.cursor() cur.execute(f"""DELETE FROM product_order where order_id={order_id}""") # Commit Changes conn.commit() # Close Connection conn.close()
import sys import random def return_score(roll): local_score = 0 r_set = list(set(roll)) #set is all unique elements; list makes it indexable cnt_all_rolls = [roll.count(i) for i in [1,2,3,4,5,6]] # 3 DICE ******************************************************** # scoring ones and fives but no triple if len(roll) < 3 or (len(roll) == 3 and r_set == [1,5]): local_score = 100*(roll.count(1)) + 50*(roll.count(5)) elif len(roll) == 3: # scoring a triple if r_set[0] == 1: local_score = 750 # (3) ones else: local_score = 100*r_set[0] # 4 DICE ******************************************************** elif len(roll) == 4: if len(r_set) == 1: #four of a kind local_score = 1000 elif len(r_set) == 2: #if there is a triple, there is (1) three in cnt_all_rolls #(add 1 to align with dice face values) if 3 in cnt_all_rolls: triple = cnt_all_rolls.index(3) + 1 if triple == 1: local_score = 750 else: local_score = 100*triple #last die is (1) or (5) remainder = cnt_all_rolls.index(1) + 1 if remainder == 1: local_score = local_score + 100 elif remainder == 5: local_score = local_score + 50 else: local_score = 300 # [1,5,1,5] else: print 'something went wrong' # 5 DICE ******************************************************** # 5 of any number # triple plus (2) one or five # four of a kind plus (1) one or five elif len(roll) == 5: if len(r_set) == 1: #five of a kind local_score = 2000 elif len(r_set) in [2,3]: #triple plus (2) add'l one/five cnt_all_rolls = [roll.count(i) for i in [1,2,3,4,5,6]] #this only occurs on four of a kind plus (1) one or five if 4 in cnt_all_rolls: #add 1 to align with dice face values if cnt_all_rolls.index(1)+1 == 1: local_score = 1100 elif cnt_all_rolls.index(1)+1 == 5: local_score = 1050 else: print 'something went wrong' else: #there should only be (1) three in this list #add 1 to align with dice face values triple = cnt_all_rolls.index(3) + 1 if triple == 1: local_score = 750 else: local_score = 100*triple #the remainder if 2 in cnt_all_rolls: # (2) ones or (2) fives twoSameDiceRemainder = cnt_all_rolls.index(2) + 1 if twoSameDiceRemainder == 1: local_score = local_score + 200 elif twoSameDiceRemainder == 5: local_score = local_score + 100 elif cnt_all_rolls[0]==1 and cnt_all_rolls[4]==1: # (1) each one and five local_score = local_score + 150 else: print 'something went wrong' # 6 DICE ******************************************************** # 6 of any number # two triples # three pairs # one thru six straight #3,4,5 of a kind plus remainder of ones and fives elif len(roll) == 6: if len(r_set) == 1: local_score = 3000 #six of a kind elif len(r_set) == 2 and 3 in cnt_all_rolls: local_score = 2500 #two triples elif len(r_set) == 3 and max(cnt_all_rolls) == 2: local_score = 1500 #three pairs elif 3 in cnt_all_rolls: if cnt_all_rolls[0] == 3: local_score = 750 else: local_score = (cnt_all_rolls.index(3)+1)*100 local_score = local_score + (250 if cnt_all_rolls[0] == 2 else 200) elif 4 in cnt_all_rolls: if len(r_set) == 2: # 4 kind + (2) ones or (2) fives local_score = 1000 + (200 if cnt_all_rolls[0] == 2 else 100) else: local_score = 1150 # 4 kind + (1) one and (1) 5 elif 5 in cnt_all_rolls: # 5 kind + (1) one/five local_score = 2000 + (100 if cnt_all_rolls[0] == 1 else 50) elif len(r_set) == 6: local_score = 1500 # 1-6 straight else: print 'something went wrong' #these statements shouldn't be necessary if we have a data validation function #which makes sure the length of the scored roll is correct else: print 'something went wrong' return local_score
def invertTree(self, root: TreeNode) -> TreeNode: """ Recursive """ if not root: return temp = root.left root.left = root.right root.right = temp self.invertTree(root.left) self.invertTree(root.right) return root """ Iterative """ def invertTree(self, root: TreeNode) -> TreeNode: head = root if not root: return None stack = [root] while stack: node = stack.pop() if node.left: stack.append(node.left) if node.right : stack.append(node.right) temp = node.left node.left = node.right node.right = temp return head
# Written by Eric Martin for COMP9021 # Draws three coloured dodecagrams, separed by a distance of # one third the length of the edges, and centred in the window # that displays them. from turtle import * edge_length = 150 angle = 150 def draw_dodecagram(colour): color(colour) begin_fill() for _ in range(12): forward(edge_length) left(angle) end_fill() def teleport(distance): penup() forward(distance) pendown() def draw_dodecagrams(): # Make sure that the dodecagrams are centred horizontally # in the window that displays them. # Without the following statement, the left end of the horizontal # edge of the green dodecagram, from which the drawing starts, # would be at the centre of the screen (so the dodecagrams are # not quite centred vertically). teleport(- edge_length // 2) # Draw the middle dodecagram, then the left dodecagram, # then the right dodecagram. draw_dodecagram('green') teleport(- 4 * edge_length // 3) draw_dodecagram('red') teleport(8 * edge_length // 3) draw_dodecagram('blue') # Used to have control over the start of the video recording. # onkey(draw_dodecagrams, 'Up') # listen()
def get_points(mazeArray): global wallsList wallsList = [] for i in range(len(mazeArray)): for j in range(len(mazeArray[i])): current = [] current.append(j) current.append(i) if mazeArray[j][i] == "1": wallsList.append(current) if mazeArray[j][i] == "2": start = j, i if mazeArray[j][i] == "3": end = j, i return wallsList, start, end def getpath(mazeArray): print(mazeArray) wallsList, start, end = get_points(mazeArray) print(start) print(end) route = [] route.append(start) currentLocation = start previousLocation = [] endfound = False firststep = True routenotfound = False if mazeArray[currentLocation[0]+1][currentLocation[1]] == '1' and mazeArray[currentLocation[0]-1][currentLocation[1]] == '1' and mazeArray[currentLocation[0]][currentLocation[1]+1] == '1': previousLocation = currentLocation newposition = (currentLocation[0], currentLocation[1]-1) currentLocation = newposition route.append(currentLocation) while endfound == False: # check if came from UP if (currentLocation[0], currentLocation[1] - 1) == previousLocation or firststep: if [currentLocation[0] - 1, currentLocation[1]] not in wallsList: newPosition = (currentLocation[0] - 1, currentLocation[1]) elif [currentLocation[0], currentLocation[1] + 1] not in wallsList: newPosition = (currentLocation[0], currentLocation[1] + 1) elif [currentLocation[0] + 1, currentLocation[1]] not in wallsList: newPosition = (currentLocation[0] + 1, currentLocation[1]) else: routenotfound = True # check if came from LEFT elif (currentLocation[0] - 1, currentLocation[1]) == previousLocation or firststep: if [currentLocation[0], currentLocation[1] + 1] not in wallsList: newPosition = (currentLocation[0], currentLocation[1] + 1) elif [currentLocation[0] + 1, currentLocation[1]] not in wallsList: newPosition = (currentLocation[0] + 1, currentLocation[1]) elif [currentLocation[0], currentLocation[1] - 1] not in wallsList: newPosition = (currentLocation[0], currentLocation[1] - 1) else: routenotfound = True # check if came from DOWN elif (currentLocation[0], currentLocation[1] + 1) == previousLocation or firststep: if [currentLocation[0] + 1, currentLocation[1]] not in wallsList: newPosition = (currentLocation[0] + 1, currentLocation[1]) elif [currentLocation[0], currentLocation[1] - 1] not in wallsList: newPosition = (currentLocation[0], currentLocation[1] - 1) elif [currentLocation[0] - 1, currentLocation[1]] not in wallsList: newPosition = (currentLocation[0] - 1, currentLocation[1]) else: routenotfound = True # check if came from RIGHT elif (currentLocation[0] + 1, currentLocation[1]) == previousLocation or firststep: if [currentLocation[0], currentLocation[1] - 1] not in wallsList: newPosition = (currentLocation[0], currentLocation[1] - 1) elif [currentLocation[0] - 1, currentLocation[1]] not in wallsList: newPosition = (currentLocation[0] - 1, currentLocation[1]) elif [currentLocation[0], currentLocation[1] + 1] not in wallsList: newPosition = (currentLocation[0], currentLocation[1] + 1) else: routenotfound = True if routenotfound: newPosition = previousLocation routenotfound = False firststep = False previousLocation = currentLocation currentLocation = newPosition if currentLocation == end: endfound = True route.append(currentLocation) print(currentLocation) print(previousLocation) print(route) if len(route) > 1000: print("exeded 1000") endfound = True print(len(route)) return route wallsList = []
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to a SQLite database """ conn = None try: conn = sqlite3.connect(db_file) print(sqlite3.version) except Error as e: print(e) return conn def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) print('table created') except Error as e: print(e) def init_table(): sql_create_employee_table = """ CREATE TABLE IF NOT EXISTS employees ( id integer PRIMARY KEY, registered_number text, name text ); """ sql_create_image_table = """ CREATE TABLE IF NOT EXISTS images ( id integer PRIMARY KEY, user_id integer, sesi text, pose text, path text ); """ if conn is not None: # create employees table create_table(conn, sql_create_employee_table) # create images table create_table(conn, sql_create_image_table) else: print("Error! cannot create the database connection.") def create_employee(conn , employee): """ Create a new employee into the employee table :param conn: :param employee: :return: """ sql = ''' INSERT INTO employees(id,registered_number,name) VALUES(?,?,?) ''' cur = conn.cursor() cur.execute(sql, employee) conn.commit() return cur.lastrowid def create_image(conn , image): """ Create a new image into the image table :param conn: :param image: :return: """ sql = ''' INSERT INTO images(id, user_id, sesi, pose, path) VALUES(?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, image) conn.commit() return cur.lastrowid def select_all_employee(conn): """ Query all rows in the employee table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("SELECT * FROM employees") rows = cur.fetchall() for row in rows: print(row) def select_all_image(conn): """ Query all rows in the image table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("SELECT * FROM images") rows = cur.fetchall() for row in rows: print(row) def delete_employee_and_its_images(conn, id): sql = 'DELETE FROM employees WHERE id=?' sql_image = 'DELETE FROM images WHERE user_id=?' cur = conn.cursor() cur.execute(sql, (id,)) conn.commit() cur.execute(sql_image, (id,)) conn.commit() def select_employee_and_images(conn): cur = conn.cursor() cur.execute("SELECT * FROM employees LEFT JOIN images ON employees.id=images.user_id") rows = cur.fetchall() for row in rows: print(row) if __name__ == '__main__': conn = create_connection(r"/home/er2c-jetson-nano/data_sqlite/data_karyawan.db") init_table() with conn: # create a new project employee = (1, 1, 'ikbar') image = (2, 1, 'A','+30','') # create_employee(conn, employee) # create_image(conn, image) # select_employee_and_images(conn) # select_all_image(conn) delete_employee_and_its_images(conn,1)
#!/usr/bin/env python3 # Created by: Ben Whitten # Created on: November 2019 # This is a program which finds the volume of the cylinder. import math # This allows me to do things with the text. class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def calculations(height_copy, radius_copy): # This does the calculations area = (math.pi*(radius_copy**2)*height_copy) return area def main(): # This is what gets the dimensions of the cylinder while True: radius_as_string = input(color.YELLOW + 'Input the radius of the' + ' cylinder: ' + color.END) height_as_string = input(color.YELLOW + "Input the height" + " of the cylinder: " + color.END) try: radius = int(radius_as_string) height = int(height_as_string) if radius >= 0 and height >= 0: area = calculations(radius_copy=radius, height_copy=height) print("{0}cm^3".format(area)) break else: print('') print(color.PURPLE + color.UNDERLINE + 'That is not a valid' ' number...' + color.END) print("") print("") except Exception: print('') print(color.PURPLE + color.UNDERLINE + 'That is not a valid' ' number...' + color.END) print("") print("") if __name__ == "__main__": main()
import math import tkinter as tk import keyboard import os import sys window = tk.Tk() window.overrideredirect(1) window.state('zoomed') textFont = ("Arial Bold", 15) window.geometry("200x200") window.title("Project_08") def button1Clicked(): try: if editText2.get() == "pi": num = math.pi elif editText2.get() == "e": num = math.e if editText1.get() == "pi": z = math.pi elif editText1.get() == "e": z = math.e else: num = float(editText2.get()) z = float(editText1.get()) outp = round(num ** (1 / z), 2) except ValueError: outp = 0 textView2.configure(text=outp) textView1 = tk.Label(window, text="Корень n-ой степени", font=textFont, fg="#000000") textView1.place(relx=0, rely=0, relwidth=1, relheight=0.25) editText1 = tk.Entry(window, font=textFont) editText1.place(relx=0.02, rely=0.25, relwidth=0.28, relheight=0.1) editText2 = tk.Entry(window, font=textFont) editText2.place(relx=0.3, rely=0.35, relwidth=0.68, relheight=0.15) button1 = tk.Button(window, text="Вычислить", font=textFont, command=button1Clicked) button1.place(relx=0, rely=0.52, relwidth=1, relheight=0.2) textView2 = tk.Label(window, text="", font=textFont, fg="#000000") textView2.place(relx=0, rely=0.78, relwidth=1, relheight=0.22) window.mainloop()
a = input() b = input() c = input() n1 = float(1) n2 = float(1) n3 = float(1) a = float(a) b = float(b) c = float(c) if a >= b and a >= c: n1 = a if b >= c: n2 = b n3 = c else: n2 = c n3 = b if b >= a and b >= c: n1 = b if a >= c: n2 = a n3 = c else: n2 = c n3 = a if c >= a and c >= b: n1 = c if a >= b: n2 = a n3 = b else: n2 = b n3 = a if a == b and b == c: n1=a n2=b n3=c a = n1 b = n2 c = n3 if a >= (b + c): print('NAO FORMA TRIANGULO') elif (a ** 2) == (b ** 2) + (c ** 2): print('TRIANGULO RETANGULO') elif (a == b) and (b == c): print('TRIANGULO EQUILATERO') elif (a == b) and (b != c): print('TRIANGULO ISOSCELES') elif (a != b) and (b == c): print('TRIANGULO ISOSCELES') elif (a == c) and (b != c): print('TRIANGULO ISOSCELES') else: print('TRIANGULO ACUTANGULO OU OBTUSANGULO')
#Question No: 3 def even(n): for i in range(2, n): if i%2 == 0 or i%3 == 0: print(i, end=', ') even(36)
import os import csv #import datetime to deal with dates column from datetime import datetime #Path to the budget_data.csv file. PyBankCSV = os.path.join("Resources","budget_data.csv") #create lists to store the two columns of CSV data dates = [] profit_loss = [] #set total profit to 0 to start totalprofit = 0 #set max and min profit variables maxprofit = 0 minprofit = 0 #Read CSV file using "with open" and csv module with open(PyBankCSV, newline="") as csvfile: #specify delimiter and holder of contents Bankreader = csv.reader(csvfile, delimiter=",") #Read the header row first. bank_header = next(Bankreader) #for loop to gather data into the lists for row in Bankreader: #put dates in list monthdate = datetime.strptime((row[0]),'%b-%Y').strftime('%Y/%m') dates.append(monthdate) #put profit and loss in list profit_loss.append(row[1]) #set totalprofit to iteratively add per loop totalprofit = totalprofit + int(row[1]) #get max profit and date by iteratively comparing to current row if int(row[1]) > maxprofit: maxprofit = int(row[1]) maxprofitdate = datetime.strptime((row[0]),'%b-%Y').strftime('%Y/%m') #get min profit and date by iteratively comparing to current row if int(row[1]) < minprofit: minprofit = int(row[1]) minprofitdate = datetime.strptime((row[0]),'%b-%Y').strftime('%Y/%m') #Calculate the average profit averageprofit = totalprofit / len(profit_loss) #calculate the total number of months num_months = len(dates) #print the results to the terminal print("Financial Analysis") print("----------------------") print(f"Total Months: {str(num_months)}") print(f"Total: ${str(totalprofit)}") print(f"Average Change: ${str(averageprofit)}") print(f"Greatest Increase in Profits: {str(maxprofitdate)} (${str(maxprofit)})") print(f"Greatest Decrease in Profits: {str(minprofitdate)} (${str(minprofit)})") #locate the output file analysis_path = os.path.join("Output","Analysis.txt") #open the output text file and write lines to file Bankout = open(analysis_path, "w") Bankout.write("Financial Analysis\n") Bankout.write("----------------------\n") Bankout.write(f"Total Months: {str(num_months)}\n") Bankout.write(f"Total: ${str(totalprofit)}\n") Bankout.write(f"Average Change: ${str(averageprofit)}\n") Bankout.write(f"Greatest Increase in Profits: {str(maxprofitdate)} (${str(maxprofit)})\n") Bankout.write(f"Greatest Decrease in Profits: {str(minprofitdate)} (${str(minprofit)})\n") Bankout.close()
from random import randint def mergesort(arr): if len(arr) > 1: half = int(len(arr)/2) arr1 = arr[0:half] arr2 = arr[half:len(arr)] return merge(mergesort(arr1), mergesort(arr2)) else: return arr def merge(arr1, arr2): if (arr2 is None): arr2 = [] if (arr1 is None): arr1 = [] res = [] while (len(arr1) > 0 or len(arr2) > 0): if len(arr1) == 0: res.append(arr2[0]) arr2.remove(arr2[0]) elif len(arr2) == 0: res.append(arr1[0]) arr1.remove(arr1[0]) elif arr1[0]<arr2[0]: res.append(arr1[0]) arr1.remove(arr1[0]) else: res.append(arr2[0]) arr2.remove(arr2[0]) #print(res) return res print("hello") list1 = [] for n in range(10): list1.append(randint(0,1000)) print(list1) l =mergesort(list1) print(l)
# Source : https://leetcode.com/problems/two-sum/ # Author : Yudistira Virgus # Date : 2015-04-04 # # ***************************************************************************************************************************** # Problem 1 # Title : Two Sum # Difficulty : Medium # Problem statement : # # Given an array of integers, find two numbers such that they add up to a specific target number. # # The function twoSum should return indices of the two numbers such that they add up to the target, # where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. # # You may assume that each input would have exactly one solution. # # Input: numbers={2, 7, 11, 15}, target=9 # Output: index1=1, index2=2 # # ***************************************************************************************************************************** # # Solution : class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): # This assumes that there is exactly one solution if target %2 == 0 and num.count(target/2) > 1: i = num.index(target/2) j = num[i+1:].index(target/2) + i + 1 return i+1, j+1 table = dict(zip(num, range(len(num)))) for i in range(len(num)-1): if ((target - num[i]) in table) and (target != 2*num[i]): return i+1, table[target - num[i]] + 1 # Another solution : class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): table = {} for i, j in enumerate(num): match_num = target - j if match_num in table: return (table[match_num], i+1) table[j] = i + 1
#Begin Game - Welcome message - Version 2.0 from October 21st print('**--** Welcome to the Tic-Tac-Toe challenge game! **--**') # Import modules import random # Generates a random number between # a given positive range r1 = random.randint(0, 10) opprand = input("Opposing Human, please enter a number between 0-10: ") crerand = input("Friendly Human, please enter a number between 0-10: ") print("Random number between 0 and 10 is ", (r1)) if opprand == r1: print (opprand + "is correct and you get first move") print ("So sorry, I get to go first") # go to first move else: print (crerand + " is close enough for the home team") #--# Program Outline #--# # 1. Create Board # 2. Display Board # 3. Play game # 4. Handle input/turn # store x entry into X list # store o entry in O list # 5. Check win # 5A. check rows # 5B. check columns # 5C. check diagnal # 6. check tie # 7. Flip tie """ Goals - 1. get the progrma to work before modifying the computer turn. Done 10/21/2019 2. fix bugs 3. implement AI to move strategiclly !!! Current bugs !!! 1. O winning is broken 2. Tie deosn't seem to work 3. AI is not currently operation, 4. Computer to replace 'O' 5. line 114 could use some regex cleanup """ # --//-- Game code begins below --//-- # ##------- Global Variables -----## # 1. set up game board board = [ "-", "-", "-", "-", "-", "-", "-", "-", "-",] # if the game is still going game_still_going = True # Who won? Or tie? winner = None # whose turn is it? current_player = "X" ## ------ End varablies declarations -------- ## #-----*** Game Start ***------# def play_game(): display_board() print ('...which means I get to go first') # while game is active, loop over and over until game concludes while game_still_going: # Hanbdle a single turn of a player handle_turn(current_player) #Check if game has neded check_win() #flip to other player flip_player() # The game has ended if winner == "X" or winner == "0": print(winner + " won!") elif winner == None: print("It's a Tie.") # 2. display board def display_board(): print(' ') print(board[0] + " | " + board[1] + " | " + board[2], " 1, 2, 3") print(board[3] + " | " + board[4] + " | " + board[5], " 4, 5, 6") print(board[6] + " | " + board[7] + " | " + board[8], " 7, 8, 9") print('') # 4. handle turn **Not used** # AI_turn() # human_turn() # print ('nice move, my turn...') # AI_turn() # human_turn() # print ('Sneaky Sneaky, my turn...') # AI_turn() # check_win() # display_board() # Handle a single trun of a player def handle_turn(player): position = input("Choose a position from 1-9: ") #while valid loop to require valid input is made valid= False while not valid: while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]: #regex would be nicer position = input("Choose a position from 1-9: ") #provides the correct list index to corresponding input position = int(position) - 1 if board[position] == "-": valid = True else: print("you can't go there, try again") board[position] = player #place the move on the board display_board() #call the board # Handle a human turn def human_turn(): #not used yet position = input("Choose a position from 1-9: ") position = int(position) - 1 board[position] = "X" def AI_turn(): #not used yet #check for near winning completions, if near choose position = random.randint(1,9) position = int(position) - 1 board[position] = "O" # 5. Check win def check_win(): # set up global variable for use global winner # 5A. check rows row_winner = check_rows() # 5B. check columns column_winner = check_columns() # 5C. check diagnal diag_winner = check_diag() #Get the winner if row_winner: winner = row_winner elif column_winner: winner = column_winner elif diag_winner: winner = diag_winner else: winner == None def check_rows(): #setup global variable global game_still_going #check if rows are complete with winning combo row_1 = board[0]==board[1]==board[2] !="-" row_2 = board[3]==board[4]==board[5] !="-" row_3 = board[6]==board[7]==board[8] !="-" #if any row does have a match, flag for there is a win if row_1 or row_2 or row_3: game_still_going = False # return the winner if row_1: return board[0] elif row_2: return board[3] elif row_3: return board[6] return def check_columns(): #setup global variable global game_still_going #check if rows are complete with winning combo column_1 = board[0]==board[3]==board[6] !="-" column_2 = board[1]==board[4]==board[7] !="-" column_3 = board[2]==board[5]==board[8] !="-" #if any row does have a match, flag for there is a win if column_1 or column_2 or column_3: game_still_going = False # return the winner if column_1: return board[0] elif column_2: return board[1] elif column_3: return board[2] return def check_diag(): #setup global variable global game_still_going #check if rows are complete with winning combo diag_1 = board[0]==board[4]==board[8] !="-" diag_2 = board[6]==board[4]==board[2] !="-" #if any row does have a match, flag for there is a win if diag_1 or diag_2: game_still_going = False # return the winner if diag_1: return board[0] elif diag_2: return board[6] return def check_tie(): global game_still_going if "-" not in board: game_still_going = False return True else: return False def flip_player(): # global Variable Setting global current_player # if current player X, change to O if current_player == "X": current_player = "O" print("player O") # if current player O, chenge to X elif current_player =="O": current_player = "X" print("player X") return play_game()
""" Practica 3:Dada la siguiente llamada a una función anónima: suma(10,11) Desarrollar la función; debe presentar en pantalla para el ejemplo 21 autor: Roberto N """ suma = (10,11) # Funcion lambda para sumar cifras mifuncion = lambda x: x[0] + x[1] # Salida de datos print(mifuncion(suma))
import turtle import time import random posponer = 0.15 # Escenario del juego window = turtle.Screen() window.title("Snake Game @BrayanAltamar") window.bgcolor("black") window.setup(width=600,height=600) # Cabeza Serpiente head = turtle.Turtle() head.speed(0) head.shape("square") head.color("green") head.penup() head.goto(0,0) head.direction = "stop" # Comida food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0,100) # Cuerpo serpiente body = [] # Puntos score = 0 high_score = 0 #Labels text = turtle.Turtle() text.speed(0) text.color("white") text.penup() text.hideturtle() text.goto(-280,270) text.write(f"Score: {score} High Score: {high_score}", font=("Courier", 20, "normal")) # Funciones def up(): head.direction = "up" def down(): head.direction = "down" def right(): head.direction = "right" def left(): head.direction = "left" def paint_text(): text.clear() text.write(f"Score: {score} High Score: {high_score}", font=("Courier", 20, "normal")) def mov(): if head.direction == "up": y = head.ycor() head.sety(y + 20) if head.direction == "down": y = head.ycor() head.sety(y - 20) if head.direction == "right": x = head.xcor() head.setx(x + 20) if head.direction == "left": x = head.xcor() head.setx(x - 20) # Eventos de teclado window.listen() window.onkeypress(up, "Up") window.onkeypress(down, "Down") window.onkeypress(right, "Right") window.onkeypress(left, "Left") while True: window.update() # Colisiones bordes if head.xcor() == 280 or head.ycor() == 280 or head.xcor() == -280 or head.ycor() == -280: time.sleep(1) head.goto(0,0) head.direction = "stop" for i in body: i.goto(1000,1000) body.clear() if score > high_score: high_score = score score = 0 paint_text() # Comer Fruta if head.distance(food) < 20: x = random.randint(-280,280) y = random.randint(-280,280) food.goto(x,y) segment_body = turtle.Turtle() segment_body.speed(0) segment_body.shape("square") segment_body.color("grey") segment_body.penup() body.append(segment_body) score += 1 paint_text() total_seg = len(body) for i in range(total_seg - 1, 0, -1): x = body[i-1].xcor() y = body[i-1].ycor() body[i].goto(x,y) if total_seg > 0: body[0].goto(head.xcor(), head.ycor()) mov() time.sleep(posponer) window.exitonclick()
def strStr(haystack, needle): return len(haystack.split(needle)[0]) if needle in haystack else -1 print(strStr("hello",'ll'))
def count_words(text): text = text.replace(',','').replace(',','').replace('.','').replace('!','').replace('?','').lower().split() wordCount ={} i= 0 temp ='' for word in text: if word in wordCount: wordCount[word]+=1 else: wordCount.update({word:1}) finalString="" for x,y in wordCount.items(): finalString = finalString + x+ " "+str(y)+"\n" return(finalString) count_words("I do not like green eggs and ham, I do not like them, Sam-I-Am")
def sentiment_scores(sentiments, texts): sentiment_list =[] for text in texts: feeling = 0 text_list = text.replace("!","").replace(".","").replace(",","").split() for word in text_list: if word in sentiments: feeling +=sentiments[word] sentiment_list.append(feeling) return(sentiment_list) sentiments = { "amazing": 0.4, "sad": -0.8, "great": 0.8, "no": -0.1, "yes": 0.1, "angry": -0.7, "happy": 0.8 } texts = [ "that makes me so happy! amazing.", "I'm so angry about this sad thing.", "sad but true, amazing", "yes that is great, and amazing" ] sentiment_scores(sentiments,texts)
def find_index(sorted_list, target): low, high = 0, len(sorted_list)-1 n =len(sorted_list)-1 while low <=high: if sorted_list[low] >= target: return low if sorted_list[high] == target or (high-low == 1): return high if sorted_list[high]<target: return high+1 mid = (low+high)//2 if sorted_list[mid] == target: return mid if sorted_list[mid]>target: high = mid else: low = mid return mid print(find_index([1,3,5,9],7))
def last_factorial_digit(n): x = 1 for i in range(n,0,-1): x*=i return(x%10) if __name__ == "__main__": print(last_factorial_digit(int(input())))
class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def __init__(self): self.root = None def print_bfs(self): if not self.root: return queue = [self.root] while len(queue) > 0: current_node = queue.pop(0) print(current_node.data) if current_node.left: queue.append(current_node.left) if current_node.right: queue.append(current_node.right) def in_order_traversal(self): nodes = [] def dfs(node): if node: dfs(node.left) nodes.append(node.data) dfs(node.right) dfs(self.root) return nodes def add(self,node): if not self.root: self.root = node return queue = [self.root] while len(queue)>0: current_node = queue.pop(0) if current_node.data > node.data and not current_node.left: current_node.left = node return if current_node.data < node.data and not current_node.right: current_node.right = node return if current_node.data > node.data and current_node.left: queue.append(current_node.left) if current_node.data < node.data and current_node.right: queue.append(current_node.right) tree = Tree() tree.add(Node(8)) tree.add(Node(9)) tree.add(Node(7)) tree.add(Node(6)) tree.add(Node(3)) tree.add(Node(4)) print(tree.in_order_traversal())
def merge_sort(nums): if len(nums)>1: mid = len(nums)//2 right = nums[0:mid] left = nums[mid:] right = merge_sort(right) left = merge_sort(left) sorted_list = [] while len(right) > 0 and len(left)>0: if right[0]>left[0]: sorted_list.append(left.pop(0)) else: sorted_list.append(right.pop(0)) sorted_list.extend(right) sorted_list.extend(left) else: sorted_list=nums return sorted_list
def bubble_sort_swaps(nums): swapped = True count=0 while swapped: swapped=False for i in range(len(nums)-1): if nums[i]>nums[i+1]: nums[i], nums[i+1] = nums[i+1], nums[i] swapped=True count+=1 return count print(bubble_sort_swaps([6,2,4,3]))
## Given this recursive solution to the longestPalindrome problem, ## Start by writing out the recursive tree of function calls to understand the problem ## then, think about how you might turn this into an iterative solution. def longestPalindrome(s): n = len(s) table = [[0 for x in range(n)] for y in range(n)] i = 0 maxLength = 1 while i < n: table[i][i] = True i+=1 start = 0 i = 0 while i < n - 1: if (s[i] == s[i + 1]): table[i][i + 1] = True start = i maxLength = 2 i = i + 1 k = 3 while k <= n: i = 0 while i < (n - k + 1): j = i + k -1 if(table[i+1][j-1]) and (s[i] == s[j]): table[i][j] = True if k > maxLength : start = i maxLength = k i +=1 k +=1 return s[start:start + maxLength+1] if s[start:start + maxLength+1][-1] !='x'else s[start:start + maxLength] print(longestPalindrome("abbababootttoo"))## Given this recursive solution to the longestPalindrome problem, ## Start by writing out the recursive tree of function calls to understand the problem ## then, think about how you might turn this into an iterative solution. def longestPalindrome(s): n = len(s) table = [[0 for x in range(n)] for y in range(n)] i = 0 maxLength = 1 while i < n: table[i][i] = True i+=1 start = 0 i = 0 while i < n - 1: if (s[i] == s[i + 1]): table[i][i + 1] = True start = i maxLength = 2 i = i + 1 k = 3 while k <= n: i = 0 while i < (n - k + 1): j = i + k -1 if(table[i+1][j-1]) and (s[i] == s[j]): table[i][j] = True if k > maxLength : start = i maxLength = k i +=1 k +=1 return s[start:start + maxLength+1] if s[start:start + maxLength+1][-1] !='x'else s[start:start + maxLength] print(longestPalindrome("abbababootttoo"))
def prime(num): isprime = True for i in range(2, num-1): if num%i == 0: isprime = False if isprime: return True else: return False while True: a = int(input("enter a number...")) if prime(a): print("hey the number is prime dude!!") break else: print("sorry retry... :(")
# -*- coding: utf-8 -*- # Project: maxent-ml # Author: chaoxu create this file # Time: 2018/2/27 # Company : Maxent # Email: [email protected] """ this funtion used to solve 8 queens problems """ def chk_pos(queen_state, next_pos): """ :param state: :param next_pos: :return: """ for i, j in enumerate(queen_state): k1 = j - next_pos[1] k2 = i - next_pos[0] k = abs(k1 / k2) if i == next_pos[0] or j == next_pos[1] or k == 1 : return True else: return False def queens(num, queen_state=[]): """ :param num: :param queen_state: :return: """ if len(queen_state) == num - 1: print('queen placed') return True else: for i in range(num):
#Displaying patterns n=int(input("Enter n:")) def display(n): for i in range (n): A=[] for j in range (n): if j<=i: A.append(j+1) else: if 10<=j+1<100: A.append(' ') elif 100<=j+1<1000: A.append(' ') else: A.append(' ') A.reverse() for j in range(n-1): print(A[j], end=' ') print(1) display(n)
''' This abstract class defines an interface that has to be used in order to be compliant with the PropertiesTable handled objects ''' import abc class PropertiesTableAbstract( object ): __metaclass__ = abc.ABCMeta ''' usually an implementation like this is used self.sanitizeProperties() ''' @abc.abstractmethod def onPropertiesUpdated(self): return ''' usually an implementation like this is used return self.properties ''' @abc.abstractmethod def getPropertyList(self): return ''' usually an implementation like this is used self.properties[key] = value ''' @abc.abstractmethod def setProperty(self, key, value): return ''' use to quickly decrease property values using key "-" ''' @abc.abstractmethod def decreaseProperty(self, key, multiplier): return ''' use to quickly increase property values using key "+" ''' @abc.abstractmethod def increaseProperty(self, key, multiplier): return ''' @return dictionary containing the properties that can be copied from this object ''' @abc.abstractmethod def copyProperties(self): return ''' Paste properties into object @param props properties that are pasted into this object ''' @abc.abstractmethod def pasteProperties(self, props): return
""" Class used to run singular tests for specific features. """ import importlib import inspect import os testPath = "src/tests/" class Tests(): def __init__(self): self.modules = {} # dict of modules containing tests def autoImport(self): """ Automatically import all tests in src/tests/ and populate the self.modules dict """ # get all files in src/tests/ files = os.listdir(testPath) # for each file for file in files: # if it's a python file if file.endswith(".py"): classname = file[:-3] # import it module = importlib.import_module("tests." + file[:-3]) # add test class to modules dict self.modules[classname] = module def listTests(self): """ List all tests in src/tests/ """ print("Tests:") for test in self.modules: print(" - " + test) def runTest(self, name): """ Run a test with the given name Args: name (str): name of the test to run """ print("Running test: " + name) if self.modules.get(name) is not None: module = self.modules[name] obj = module.__dict__[name]() elif self.modules.get("Test" + name) is not None: module = self.modules["Test" + name] obj = module.__dict__["Test" + name]() else: print("Test not found!") print("Test done!")
''' ONCE class: Simple structure that if checked with get() method, return true on first check, false all the others. ''' class Once: #constructor def __init__(self): self.value = True def get(self): if self.value == True: self.value = False return True else: return False
### Email Validation ### ######################## # input: # Masukkan alamat Email: # Kondisi: # - Memiliki format: nama user@nama hosting.ekstensi # - Nama user hanya boleh: huruf, angka dan underscore dan titik # - Nama hosting hanya boleh: huruf dan angka # - nama ekstensi hanya boleh huruf dan maksimal 5 karakter .com .co .id # output: # Alamat Email yang Anda masukkan tidak valid # - Karena format email salah (tidak ada @ atau pake ,) # - Karena format user name yang Anda masukkan salah # - Karena format hosting yang Anda masukkan salah # - Karena format ekstensi yang Anda masukkan salah # Alamat Email yang Anda masukkan valid # contoh : [email protected], [email protected], [email protected] (Valid) # contoh2: andre-&^[email protected], johny245@g_#^mail.com, 79andi@yahoo, [email protected] # [email protected], citra@@yahoo.com, [email protected], citra@@yahoo.co.id, [email protected] loop = True while loop: try: email = input("Masukkan alamat Email: ") # loopEmail = True # while loopEmail: emailsplit = email.split('@') namauser = emailsplit[0] hosting = emailsplit[-1].split('.')[0] ekstensi = emailsplit[-1].split('.')[1] salah = 0 # namauser validation: huruf, angka, underscore, titik for i in range(0, len(namauser)): if "" in emailsplit: print("Format username yang Anda masukkan salah.") salah += 1 break if not((namauser[i] >= '1' and namauser[i] <= '9') or (namauser[i] >= 'a' and namauser[i] <= 'z') or \ (namauser[i] >= 'A' and namauser[i] <= 'Z') or namauser[i] == '.' or namauser[i] == '_'): salah += 1 print("Format username yang Anda masukkan salah.") break # namahosting validation: hanya boleh huruf dan angka for i in range(0, len(hosting)): if not(hosting[i].isalnum()) or "" in emailsplit[-1].split('.'): salah += 1 print("Format hosting yang Anda masukkan salah.") break # ekstensi validation: hanya boleh huruf dan maksimal 5 karakter .com .co .id for i in range(0, len(ekstensi)): if "" in emailsplit[-1].split('.'): print("Format ekstensi yang Anda masukkan salah.") salah += 1 break else: if not(ekstensi[i].isalpha() and len(ekstensi) <= 5): print("Format ekstensi yang Anda masukkan salah.") salah += 1 break if salah == 0: print("\nAlamat Email yang Anda masukkan valid.\n") loop = False else: loop3 = True while loop3: lanjut = input("Ingin melanjutkan (Y/N)? ").lower() if lanjut == 'n': loop3 = False # loopEmail = False loop = False # break elif lanjut != 'y': print("Pilih Y atau N.") else: loop3 = False # loop = Fal except: print("\nAlamat E-mail yang Anda masukkan tidak valid (tidak ada '@' atau '.')\n") loop3 = True while loop3: lanjut = input("Ingin melanjutkan (Y/N)? ").lower() if lanjut == 'n': loop3 = False # loopEmail = False loop = False # break elif lanjut != 'y': print("Pilih Y atau N.") else: loop3 = False # loop = Fal
import random def merge(A, start, end): start = int(start) end = int(end) L = A[start:(start + end)/2+1] R = A[(start + end)/2 + 1:(end+1)] L.append(10**9) R.append(10**9) i = 0 j = 0 for k in range(start, end + 1): if L[i] > R[j]: A[k] = R[j] j = j + 1 elif L[i] < R[j]: A[k] = L[i] i = i + 1 def mergesort(A, start, end): start = int(start) end = int(end) if len(A[start:(end+1)]) == 1: return A[start:(end+1)] elif len(A[start:(end+1)]) == 2: if A[start] > A[end]: A[start], A[end] = A[end], A[start] return A[start:(end+1)] else: mergesort(A, int(start), int(start+end)/2) mergesort(A, int((start+end)/2) + 1, int(end)) merge(A, int(start), int(end)) def check_sorted(A): sorted = True for i in range(len(A)-1): if A[i] >= A[i+1]: return False return True if __name__ == "__main__": A = list() for i in range(9): A.append(random.randint(-1000, 1000)) print(A) SA, compare_cnt = mergesort(A, 0, len(A) - 1) print(SA) assert(check_sorted(SA)) print("Compare Count : {}".format(compare_cnt))
''' 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。 但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子? ''' # -*- coding:utf-8 -*- class Solution: def movingCount(self, k, rows, cols): #首先建立布尔数组,检测格点是否之前已经记录过 visited = [False]*(rows*cols) count = self.movingCountCore(k,rows,cols,0,0,visited) return count #2/记录合格的格点数目的函数 def movingCountCore(self,k,rows,cols,row,col,visited): count = 0 if self.check(k,rows,cols,row,col,visited): visited[row*cols+col] = True #记录当前格点状态为已走过 count = 1+ self.movingCountCore(k,rows,cols,row,col-1,visited) + \ self.movingCountCore(k, rows, cols, row-1, col, visited) + \ self.movingCountCore(k, rows, cols, row, col+1, visited) + \ self.movingCountCore(k, rows, cols, row+1, col, visited) return count #统计该点是否满足条件 def check(self,k,rows,cols,row,col,visited): if 0<=row<rows and 0<=col<cols and not visited[row*cols+col] and \ self.getDigitSum(row)+self.getDigitSum(col)<=k: return True #行坐标和列坐标数位之和 def getDigitSum(self,num): sum = 0 while num: sum += num%10 num = num//10 return sum
''' 输入一个英文句子, 翻转句子中单词的顺序,但单词内字符的顺序不变 为简单起见, 标点符号和普通字母一样处理 ''' #fangfa一 ,利用python的方法 class Solution: def ReverseSentence(self, s): if s == None or len(s)<=0: return '' l = s.split(' ') #字符串句子按照空格进行切割 return ' '.join(l[::-1]) #方法二 一个个字母的处理方式 ''' 这个思路很简单的,从前往后一直读取,遇到空格之后就把之前读取到的压到结果的前面并添加上空格。 最后当循环结束,如果那个用来读取的字符串不为空,那么就再把它压到结果前,这次就不用再结果的最前面加空格了, 这应该就是思路吧,开始我也这么想不过觉得太朴素了,不够酷炫,后来想了想。 这个的时间复杂度会低一点,不过额外多用点内存。''' class Solution2: def ReverseSentence(self, s): cur = ''#定义一个新的字符串存放当前处理的单词 res = ''#定义一个字符串---存放翻转后的句子 index = 0 while index < len(s): if s[index] == ' ': res = ' '+ cur +res cur = '' else: cur += s[index] index += 1 if len(cur): res = cur + res return res #解法3 剑指offer上的 翻转两次的思路 class Solution3: def ReverseSentence(self, s): if s == None or len(s)<=0: return '' #翻转是对列表的元素进行,所以要将字符串转化为列表形式,(每个元素对应一个字母) strlist = list(s) strlist = self.Reverse(strlist) #翻转整个句子的字母 resultstr = '' #存放最终的结果 newlist = [] # 存放翻转后的单词, 每个元素是一个列表 ,里面对应一个单词的字母 #定义两个指针,确定一个单词的首末位置, 注意对空格条件的处理 begin = 0 end = 0 while end < len(s): # 遍历到句子最后位置,直接将最后的翻转单词保存到新列表里,跳出循环 if end == len(s)-1: newlist.append(self.Reverse(strlist[begin:])) break # 1 这个判断语句位置需要靠前, 用来鉴定字符串开头是否是空格的情况 # 另外遍历句子中的空格保存到新列表,两个指针同时后移 if strlist[begin]== ' ': newlist.append(' ') begin += 1 end += 1 # 2 遍历到空格时,就是一个单词的结束,对这个单词进行翻转保存到新列表里.然后头指针变为尾指针位置 继续 elif strlist[end] == ' ': newlist.append(self.Reverse(strlist[begin:end])) begin = end # 3 遍历到字母(还没到一个单词的结束),尾指针就继续后移 else: end += 1 for i in newlist: resultstr += ''.join(i) return resultstr def Reverse(self, alist): if alist == None or len(alist)<=0: return '' start = 0 end = len(alist)-1 while start < end: alist[start],alist[end] = alist[end],alist[start] start += 1 end -=1 return alist str = 'I am a student.' s = Solution3() print(s.ReverseSentence(str))
''' 随机从扑克牌中抽出了5张牌,判断是不是顺子, 决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。 ''' ''' 剑指思路:1排序 2. 统计数组中0的个数 3. 统计排序数组中相邻数字之间的空缺总数 如果2》=3那么就是顺子 如果有顺子那么就肯定不是顺子 ''' class Solution: def IsContinuous(self,numbers): if numbers == None or len(numbers)!=5: return False numbers = sorted(numbers) numberZero = 0 numberInterval = 0 #开始循环遍历数组的数,统计2.3两种情况下的个数 i = 0 while i < len(numbers)-1: if numbers[i] == 0: numberZero += 1 i += 1 #别漏了这句 continue if numbers[i] == numbers[i+1]: return False numberInterval += numbers[i+1]-numbers[i]-1 i += 1 #判断两种情况数目的大小 if numberZero >= numberInterval: return True return False #另外有个思路是:观察数组可知 是顺子 必须满足两个条件:(除零外) 1 最大,最小值之差<5 2.不能有重复的数 s=Solution() test = [1,0,3,5,4] print(s.IsContinuous(test))
''' 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。 ''' ''' 解法二根据数组特点找出o(n)算法 保存两个数一个是数组中的一个数组数字。如果下一个数字和当前保存的数字相同,次数加1 不同 次数减1 。。 要找的数字的肯定是最后一次把次数设为1时对应的数字 ''' # -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): if numbers == None: return 0 length = len(numbers) result = numbers[0] times = 1 for i in range(1, length): if times == 0: result = numbers[i] times = 1 elif numbers[i] == result: times += 1 else: times -= 1 if not self.CheckMoreThanHalf(numbers, length, result): return 0 return result def CheckMoreThanHalf(self, numbers, length, number): times = 0 for i in range(length): # 遍历全部数组,看所找的数字结果 if numbers[i] == number: times += 1 if times * 2 <= length: return False return True S = Solution() print(S.MoreThanHalfNum_Solution([1, 2, 3, 2, 2, 2, 5, 4, 2]))
class Point(object): def __init__(self, x=0., y=0.): self.x = x self.y = y def __iadd__(self, other): if isinstance(other, Point): self.x += other.x self.y += other.y return self def __add__(self, other): if isinstance(other, Point): return Point(self.x + other.x, self.y + other.y) __radd__ = __add__ def __isub__(self, other): if isinstance(other, Point): self.x -= other.x self.y -= other.y return self def __sub__(self, other): if isinstance(other, Point): return Point(self.x - other.x, self.y - other.y) __rsub__ = __sub__ def __imul__(self, other): if isinstance(other, int) or isinstance(other, float): self.x *= other self.y *= other return self elif isinstance(other, Point): self.x *= other.x self.y *= other.y return self def __mul__(self, other): if isinstance(other, int) or isinstance(other, float): return Point(self.x * other, self.y * other) elif isinstance(other, Point): return Point(self.x * other.x, self.y * other.y) __rmul__ = __mul__ def __idiv__(self, other): if isinstance(other, int) or isinstance(other, float): self.x /= other self.y /= other return self def __div__(self, other): if isinstance(other, int) or isinstance(other, float): return Point(self.x / other, self.y / other) else: return NotImplemented def __abs__(self): return Point(abs(self.x), abs(self.y)) def copy(self): return Point(self.x, self.y) def setTo(self, point): self.x = point.x self.y = point.y return self def reset(self): self.x = 0. self.y = 0. return self def norm(self): from math import sqrt return sqrt(self.x**2+self.y**2) def normalized(self, length = 1): norm = self.norm() if norm == 0: norm = 1 return Point(self.x*length/norm, self.y*length/norm) if __name__ == '__main__': p = Point() p += Point(1, 2) *3. - Point(4, 6)/2. p *= 2. print p.x, p.y, p.normalized().x, p.normalized().y p.reset() print p.x, p.y
# -- coding: utf-8 -- import dataStru as ds def find(inputs, target): """ 1. 二维数组中的查找 """ if inputs == None or len(inputs) <= 0: return False; M = len(inputs) #row N = len(inputs[0]) #col i = M - 1 j = 0 while(i >= 0 and j < N): if target == inputs[j][i]: return True elif target < inputs[j][i]: i -= 1 elif target > inputs[j][i]: j += 1 return False def replaceSpace(inputs): """ 2.替换空格 """ if inputs == None or len(inputs) <= 0: return False; oldlen = len(inputs) for i in range(oldlen): if inputs[i] == ' ': inputs += ' ' p1 = oldlen - 1 p2 = len(inputs) - 1 inputs = list(inputs) while(p1 >= 0 and p2 > p1): if(inputs[p1] == ' '): inputs[p2] = '0' p2 -= 1 inputs[p2] = '2' p2 -= 1 inputs[p2] = '%' p2 -= 1 else: inputs[p2] = inputs[p1] p2 -= 1 p1 -= 1 s=''.join(inputs) return s def printListFromTailToHead1(inputs): """ 3.从尾到头打印链表, 使用栈 """ print("Use stack...") stack = ds.stack() while(inputs != None): stack.push(inputs.data) inputs = inputs.next rev = [] while(stack.top != None): rev.append(stack.pop()) return rev def printListFromTailToHead2(inputs): """ 从尾到头打印链表,使用递归 """ print("Use recursion...") if inputs != None: printListFromTailToHead2(inputs.next) print(inputs.data) def printListFromTailToHead3(inputs): """ 从尾到头打印链表,使用头插法,头结点和第一个节点的区别:头结点是在头插法中使用的一个额外节点,这个节点不存储值;第一个节点就是链表的第一个真正存储值的节点。 """ print("Use head...") head = ds.Node(-1) while(inputs != None): new_node = inputs.next inputs.next = head.next head.next = inputs inputs = new_node rev = [] node = head.next while(node != None): rev.append(node.data) node = node.next return rev class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def reConstructBinaryTree(pre, tin): """ 4.根据二叉树的前序遍历和中序遍历的结果,重建出该二叉树。 """ # write code here if len(pre) == 0: return None elif len(pre) == 1: return TreeNode(pre[0]) else: root = TreeNode(pre[0]) root.left = reConstructBinaryTree(pre[1:tin.index(pre[0])+1], tin[: tin.index(pre[0])]) root.right = reConstructBinaryTree(pre[tin.index(pre[0])+1:], tin[tin.index(pre[0]) + 1:]) return root class Solution: """ 5.用两个栈实现队列 """ def __init__(self): self.stack_a = [] self.stack_b = [] def push(self, node): # write code here self.stack_a.append(node) def pop(self): if self.stack_b: return self.stack_b.pop() else: while(self.stack_a): self.stack_b.append(self.stack_a.pop()) return self.stack_b.pop() def minNumberInRotateArray(rotateArray): """ 6.旋转数组的最小数字,根据旋转数组前部分大于后部分。设置了两个指针,一个指向数组头head,另一个指向数组尾部end。当head > end, 数组尾部指针左移,一直到head < end, 说明数组顺序大小突变。 """ if len(rotateArray) == 0: return 0 head = 0 end = len(rotateArray) - 1 if head == end: return rotateArray[0] else: while(head < end): if rotateArray[head] >= rotateArray[end]: end -= 1 else: min_num = rotateArray[end + 1] break return min_num def Fibonacci(n): """ 7.斐波拉契 """ # write code here if n == 0: return 0 elif n <= 2: return 1 elif n <= 39: # return Fibonacci(n - 1) + Fibonacci(n - 2) num = [1] * (n + 1) for i in range(3, n + 1): num[i] = num[i - 1] + num[i - 2] return num[n] def factorial(m): if m == 0: return 1 else: mm = m for i in range(1, m): mm = mm * (m - i) return mm def jumpFloor(number): # write code here """ 8.一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 画图算的呃Orz... 列了方程式:x + 2y = n; x + y = k; (限定条件x <= n and y <= n/2); x + y = k这条直线在x + 2y = n以及限定条件内滑动,可以知道在满足条件的情况下k有多个值,每种值排列组合一下是C(k, y) ,根据方程式算出k = n - y。最后累计计算C(n - y, y)就行了。 太笨啦,想了半天... """ y = 0 count = 0 if number == 1: return 1 else: while(y <= number/2): m = factorial(number - y) n = factorial(y) m_n = factorial(number - 2*y) count += m/(n*m_n) y += 1 return count def jumpFloorII(number): # write code here """ 9.## 题目描述 一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级……它也可以跳上 n 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。 """ if number == 0: return 0 elif number == 1: return 1 elif number == 2: return 2 else: num = [1] * (number + 1) num[2] = 2 for i in range(3, number + 1): s = 0 for j in range(1, i): s += num[i - j] num[i] = s + 1 return num[number] def rectcover(n): """ 10.我们可以用 2\*1 的小矩形横着或者竖着去覆盖更大的矩形。请问用 n 个 2\*1 的小矩形无重叠地覆盖一个 2\*n 的大矩形,总共有多少种方法? """ if n == 0: return 0 if n == 1: return 1 elif n == 2: return 2 elif n >= 3: # return rectcover(n - 1) + rectcover(n - 2) num = [0, 1, 2] + [1]*(n - 2) for i in range(3, n + 1): num[i] = num[i - 1] + num[i - 2] return num[n] def NumberOf1(n): """ 11.输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 """ count = 0 if n < 0: n = n & 0xffffffff while n: count += 1 n = (n - 1) & n return count def Power(self, base, exponent): """ 12.数值的整数次方 """ return base**exponent def reOrderArray(array): """ 13.输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分, 所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。 """ if array == None: return None odd,even=[],[] for i in array: if i%2 != 0: even.append(i) else: odd.append(i) return even + odd def FindKthToTail(head, k): """ 14.输入一个链表,输出该链表中倒数第k个结点。 """ # write code here if head == None or k <=0: return None slow = head.head fast = head.head while k > 1: if fast.next != None: fast = fast.next k -= 1 else: return None while fast.next != None: fast = fast.next slow = slow.next return slow.data def ReverseList(self, pHead): """ 15.翻转链表 """ if pHead==None or pHead.next==None: return pHead pre = None cur = pHead while cur!=None: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre def Merge(self, pHead1, pHead2): """ 16.合并两个排序的链表""" cur = ListNode(-1) p = cur while(pHead1 and pHead2): if (pHead1.val < pHead2.val): cur.next = pHead1 pHead1 = pHead1.next else: cur.next = pHead2 pHead2 = pHead2.next cur = cur.next if pHead1 == None: cur.next = pHead2 elif pHead2 == None: cur.next = pHead1 return p.next class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def HasSubtree(self, pRoot1, pRoot2): """ 17.树的子结构 """ # write code here if pRoot1 == None or pRoot2 == None: return False result = False if pRoot1.val == pRoot2.val: result = self.DoesTree1haveTree2(pRoot1, pRoot2) if not result: result = self.HasSubtree(pRoot1.left, pRoot2) if not result: result = self.HasSubtree(pRoot1.right, pRoot2) return result def DoesTree1haveTree2(self, p1, p2): if p2 == None: return True if p1 == None: return False if p1.val != p2.val: return False return self.DoesTree1haveTree2(p1.left, p2.left) and self.DoesTree1haveTree2(p1.right, p2.right) def Mirror(self, root): # write code here """ 18.二叉树的镜像 """ if not root: return root node=root.left root.left=root.right root.right=node self.Mirror(root.left) self.Mirror(root.right) return root def printMatrix(self, matrix): """ 19.顺时针打印矩阵 """ # write code here list_mat = [] while len(matrix)>0: list_mat.extend(matrix[0]) matrix = zip(*matrix[1:])[::-1] return list_mat class Solution: """ 20.包含min函数的栈 """ def __init__(self): self.stack = [] def push(self, node): # write code here return self.stack.append(node) def pop(self): # write code here self.stack.pop() return self.stack def top(self): # write code here return self.stack[-1] def min(self): # write code here if len(self.stack)==1 : return self.stack[0] while len(self.stack)>1: m1 = self.top() self.pop() m2 = self.top() if (m1 < m2): m = m1 else: m = m2 return m def IsPopOrder(pushV, popV): """ 21.输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。 """ stack = [] while popV: if stack and stack[-1] == pushV[-1]: stack.pop() pushV.pop() else: stack.append(popV[0]) popV.pop(0) if len(stack) == 1 and stack[-1] == pushV[-1]: return True else: return False def PrintFromTopToBottom(self, root): # write code here """ 22.从上往下打印二叉树 """ if not root: return [] q = [] result = [] q.append(root) while len(q) > 0: node = q.pop(0) result.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) return result def VerifySquenceOfBST(self, sequence): """ 23.二叉搜索树的后序遍历序列 """ # write code here if sequence == None or len(sequence) == 0: return False root = sequence[-1] left = True right = True for i in range(len(sequence)): if sequence[i] > root: break for j in range(i, len(sequence)): if sequence[j] < root: return False if i>0: left=self.VerifySquenceOfBST(sequence[0:i]) if i<len(sequence)-1: right=self.VerifySquenceOfBST(sequence[i:-1]) return left and right def FindPath(root, expectNumber): # write code here """24.输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。 """ if root == None: return [] if root and root.left == None and root.right == None and root.data == expectNumber: return [[root.data]] left = FindPath(root.left, expectNumber - root.data) right = FindPath(root.right, expectNumber - root.data) res = [] for i in left + right: res.append([root.data] + i) return res #25 复杂链表的复制 #26 二叉搜索树与双向链表 def Permutation(s): # write code here #27.输入一个字符串,按字典序打印出该字符串中字符的所有排列。 if len(s) <= 1: return [s] sl = [] for i in range(len(s)): for j in Permutation(s[0:i] + s[i + 1:]): sl.append(s[i] + j) return sl def MoreThanHalfNum_Solution(self, numbers): #28.数组中出现次数超过一半 n = len(numbers) if n == 0: return 0 num = numbers[0] count = 1 for i in range(0, n): if numbers[i] == num: count += 1 else: count -= 1 if count == 0: num = numbers[i] count += 1 count = 0 for i in range(0, n): if (numbers[i] == num): count += 1 if count * 2 > n: return num else: return 0 def GetLeastNumbers_Solution(self, tinput, k): #29.最小的K个数 if len(tinput) == 0 or len(tinput) < k: return [] s = sorted(tinput) return s[:k] def FindGreatestSumOfSubArray(self, array): #30.连续子数组的最大和 dp = array for i in range(len(array)): if i == 0: dp[i] = array[i] else: dp[i] = max(dp[i - 1] + array[i], array[i]) return max(dp) def FindGreatestSum(array): #给出一个长度为n的序列A1,A2,…,An,求最大连续和。换句话说,要求找到1<=i <= j<=n,使得Ai+Ai+1+..+Aj尽量大 dp = array for i in range(len(array)): if i == 0: dp[i] = array[i] else: tmp = dp[i - 1] + array[i] dp[i] = max(tmp, array[i]) print dp[i] return max(dp) #31.整数中1出现的次数 #32.把数组排成最小的数 #33.丑数 #34.第一个只出现一次的字符位置 #35.数组中的逆序对 def FindFirstCommonNode(head1, head2): #36.两个链表的第一个公共结点 if head1 is None or head2 is None: return None L1 = [] L2 = [] while head1: L1.append(head1.data) head1 = head1.next while head2: L2.append(head2.data) head2 = head2.next f = None while L1 and L2: top1 = L1.pop(-1) top2 = L2.pop(-1) if top1 == top2: f = top1 else: break return f def GetNumberOfK(data, k): #37.数字在排序数组中出现的次数 data = map(str, data) s = 0 for i in data: for j in i: if j == str(k): s += 1 return s #层次遍历 def levelOrder(r): #38.输入一颗二叉树,求树的深度 if r is None: return 0 count = 0 q = [] #模拟一个队列储存结点 q.append(r) while len(q) != 0: tmp = [] #使用列表储存同层结点 for i in range(len(q)): t = q.pop(0) if t.left is not None: q.append(t.left) if t.right is not None: q.append(t.right) tmp.append(t.val) if tmp: count += 1 return count def IsBalanced_Solution(pRoot): #39.平衡二叉树 if not pRoot: return True if abs(levelOrder(pRoot.left) - levelOrder(pRoot.right)) > 1: return False return IsBalanced_Solution(pRoot.left) and IsBalanced_Solution(pRoot.right) t = TreeNode(1) t.right = TreeNode(2) t.right.right = TreeNode(3) print IsBalanced_Solution(t) #40.数组中只出现一次的数字 def FindContinuousSequence(tsum): #41.和为S的连续正数序列, 双指针思路,其中cur = (a1 + an)*n/2是根据等差数列求和来的,n = an - a1 + 1 allres = [] low = 1 high = 2 while low < high: cur = (low + high) * (high - low + 1)/2 if cur < tsum: high += 1 if cur == tsum: res = [] for i in range(low, high + 1): res.append(i) allres.append(res) low += 1 if cur > tsum: low += 1 return allres def FindNumbersWithSum(array, tsum): #42.和为S的两个数字 allres = [] for i in array: res = [] if tsum - i in array: if tsum - i == i: return [i, i] else: return [i, tsum - i] return def LeftRotateString(s, n): #43.左旋转字符串 if not s: return "" cache = "" for i in range(n): c = s[i] cache += c return s[n:] + cache # print LeftRotateString('', 6) def ReverseSentence(s): #44.翻转单词顺序 def movingCount(threshold, rows, cols): # write code here board = [[0 for _ in range(cols)] for _ in range(rows)] def block(r,c): s = sum(map(int,str(r)+str(c))) return s>threshold class Context: acc = 0 def traverse(r,c): if not (0<=r<rows and 0<=c<cols): return if board[r][c]!=0: return if board[r][c]==-1 or block(r,c): board[r][c]=-1 return board[r][c] = 1 Context.acc+=1 traverse(r+1,c) traverse(r-1,c) traverse(r,c+1) traverse(r,c-1) traverse(0,0) return Context.acc def duplicate(inputs): """ 数组中重复的数字 """ if inputs == None or len(inputs) <= 0: return False; n = len(inputs) for i in range(0, n): while(i != inputs[i]): tmp = inputs[i] if inputs[i] == inputs[inputs[i]]: duplicate_num = inputs[i] break inputs[i], inputs[tmp]= inputs[tmp], inputs[i] return duplicate_num
# Your code here def finder(files, queries): """ YOUR CODE HERE """ # Your code here files_table = [] words_table = {} for word in files: # split path by / path = word.split("/") # target last item name = path[-1] # checks if last item is in table if name not in words_table: words_table[name] = [] # adds to table words_table[name].append(word) # loop through queries to check for word in queries: #checks table if word in words_table: # adds to files table files_table.extend(words_table[word]) return files_table if __name__ == "__main__": files = [ '/bin/foo', '/bin/bar', '/usr/bin/baz' ] queries = [ "foo", "qux", "baz" ] print(finder(files, queries))
#!/usr/bin/python # David Newell # GeoUtils/functions.py # Geographical Utilities package functions def makeBoundingPolygon(north=90,south=-90,east=180,west=-180): """ Function to create a MySQL bounding rectangular polygon based on four edge points Inputs: north, south, east, west - latitude/longitude values for each boundary of polygon Output: MySQL Formatted Polygon with single ring: POLYGON((points)) """ boundingPoly = "POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))" % (west,north,east,north,east,south,west,south,west,north) return boundingPoly
### search takes as input a search queue, a path factory, a function that ### returns true if the state provided as input is the goal, and the maximum ### depth to search in the search tree. ### Should print out the solution and the number of nodes enqueued, dequeued, ### and expanded. def search(queue, initialState, factory, goalTest, maxdepth=10) : closedList = {} nodesEnqueued = 1 nodesDequeued = 0 nodesExpanded = 0 queue.insert(initialState) ### you complete this. ### While there are states in the queue, ### 1. Dequeue ### 2. If this is the goal, stop ### 3. If not, insert in the closed list and generate successors ### 4. If successors are not in the closed list, enqueue them.
name = input('ENTER NAME ') print ('Hello My Name is, '+ name) if name == 'Eli': print ('hey eli') ave = input('Eli what is your old Ave? ') if ave == '8': print ('Thats right!') if ave == '9': print ('Thats wrong!')
def cari_sama(my_list,elemen): backup_list=[] mark = False for i in range(len(my_list)): if elemen == my_list[i]: mark = True backup_list.append(i) if mark == True: print("list ini memiliki data yang sama dengan elemen yang anda ketik pada index") for i in backup_list: print(i) else: print("tidak ditemukan kesamaan data") def main_function(): i=1 while i==1: elemen = (int(input("Ketik elemen yang ingin dicari : "))) cari_sama(my_list,elemen) my_list = [56,20,12,45,100,34,35,13,17,90,110,500,1200,59,62,63,75,79] print(my_list) main_function()
# -*- coding: utf-8 -*- """ Created on Wed Dec 12 13:54:20 2018 @author: Hesam """ def domain_name(url): start = url.find(":") url = url[start+1:] dots = url.count(".") if dots == 2: ind1 = url.index(".") url = url[ind1+1:] ind2 = url.index(".") return url[:ind2] elif dots == 1: ind3= url.index(".") return url[:ind3]
#Traveling salesman problem solved using Simulated Annealing. import time from scipy import * from pylab import * start_time = time.time() def Distance(R1, R2): return sqrt((R1[0] - R2[0]) ** 2 + (R1[1] - R2[1]) ** 2) def TotalDistance(city, R): dist = 0 for i in range(len(city) - 1): dist += Distance(R[city[i]], R[city[i + 1]]) dist += Distance(R[city[-1]], R[city[0]]) return dist def reverse(city, n): nct = len(city) nn = (1 + ((n[1] - n[0]) % nct)) / 2 # half the lenght of the segment to be reversed # the segment is reversed in the following way n[0]<->n[1], n[0]+1<->n[1]-1, n[0]+2<->n[1]-2,... # Start at the ends of the segment and swap pairs of cities, moving towards the center. inty = int(nn) for j in range(inty): k = (n[0] + j) % nct l = (n[1] - j) % nct #if you get an error here, #just rerun it, it will work city[k], city[l] = city[k], city[l] # temp1 = city[k]# swap # temp2 = city[l] # city[k] = temp2 # city[l] = temp1 def transpt(city, n): nct = len(city) newcity = [] # Segment in the range n[0]...n[1] for j in range((n[1] - n[0]) % nct + 1): newcity.append(city[(j + n[0]) % nct]) # is followed by segment n[5]...n[2] for j in range((n[2] - n[5]) % nct + 1): newcity.append(city[(j + n[5]) % nct]) # is followed by segment n[3]...n[4] for j in range((n[4] - n[3]) % nct + 1): newcity.append(city[(j + n[3]) % nct]) return newcity COUNT = 0 def Plot(city, R, dist): # Plot global COUNT Pt = [R[city[i]] for i in range(len(city))] Pt += [R[city[0]]] Pt = array(Pt) title('Total distance=' + str(dist)) plot(Pt[:, 0], Pt[:, 1], '-o') fig1 = gcf() fig1.savefig('annealStep' + str(COUNT) +'.png') fig1.clf() # fig1 = 0 # show() COUNT = COUNT + 1 if __name__ == '__main__': ncity = 30 # Number of cities to visit (uncomment to bring in other coords.txt) maxTsteps = 100 # Temperature is lowered not more than maxTsteps Tstart = 0.2 # Starting temperature - has to be high enough fCool = 0.9 # Factor to multiply temperature at each cooling step Preverse = 0.5 # How often to choose reverse/transpose trial move #randomize or input from a txt file # Choosing city coordinates R = [] # coordinates of cities are choosen randomly for i in range(ncity): R.append([rand(), rand()]) R = array(R) ###Uncomment to use the same coordinates that brute.py saved # file = np.loadtxt('coords.txt') # lat = file[:, 0] # long = file[:, 1] # # R = [] # for i in range(len(lat)): # R.append((lat[i], long[i])) ### HERE IS WHERE COORDINATES ARE # The index table -- the order the cities are visited. ncity = len(R) maxSteps = 100 * ncity # Number of steps at constant temperature maxAccepted = 10 * ncity # Number of accepted steps at constant temperature city = range(ncity) # Distance of the travel at the beginning dist = TotalDistance(city, R) dist = round(dist, 5) # Stores points of a move n = zeros(6, dtype=int) nct = len(R) # number of cities T = Tstart # temperature Plot(city, R, dist) for t in range(maxTsteps): # Over temperature accepted = 0 for i in range(maxSteps): # At each temperature, many Monte Carlo steps while True: # Will find two random cities sufficiently close by # Two cities n[0] and n[1] are choosen at random n[0] = int((nct) * rand()) # select one city n[1] = int((nct - 1) * rand()) # select another city, but not the same if (n[1] >= n[0]): n[1] += 1 # if (n[1] < n[0]): (n[0], n[1]) = (n[1], n[0]) # swap, because it must be: n[0]<n[1] nn = (n[0] + nct - n[1] - 1) % nct # number of cities not on the segment n[0]..n[1] if nn >= 3: break # We want to have one index before and one after the two cities # The order hence is [n2,n0,n1,n3] n[2] = (n[0] - 1) % nct # index before n0 -- see figure in the lecture notes n[3] = (n[1] + 1) % nct # index after n2 -- see figure in the lecture notes if Preverse > rand(): # Here we reverse a segment # What would be the cost to reverse the path between city[n[0]]-city[n[1]]? de = Distance(R[city[n[2]]], R[city[n[1]]]) + Distance(R[city[n[3]]], R[city[n[0]]]) - Distance( R[city[n[2]]], R[city[n[0]]]) - Distance(R[city[n[3]]], R[city[n[1]]]) if de < 0 or exp(-de / T) > rand(): # Metropolis accepted += 1 dist += de reverse(city, n) else: # Here we transpose a segment nc = (n[1] + 1 + int( rand() * (nn - 1))) % nct # Another point outside n[0],n[1] segment. See picture in lecture nodes! n[4] = nc n[5] = (nc + 1) % nct # Cost to transpose a segment de = -Distance(R[city[n[1]]], R[city[n[3]]]) - Distance(R[city[n[0]]], R[city[n[2]]]) - Distance( R[city[n[4]]], R[city[n[5]]]) de += Distance(R[city[n[0]]], R[city[n[4]]]) + Distance(R[city[n[1]]], R[city[n[5]]]) + Distance( R[city[n[2]]], R[city[n[3]]]) if de < 0 or exp(-de / T) > rand(): # Metropolis accepted += 1 dist += de city = transpt(city, n) if accepted > maxAccepted: break # Plot print('plot') Plot(city, R, dist) print "T=%10.5f , distance= %10.5f , accepted steps= %d" % (T, dist, accepted) T *= fCool # The system is cooled down if accepted == 0: break # If the path does not want to change any more, we can stop print('plot') Plot(city, R, dist) runTime = time.time() - start_time print("runTime: ") print(runTime) # savefig('savefig' + str(i) +'.png') # show()
a = int(input('введите а: ')) b = int(input('введите b: ')) c = int(input('введите c: ')) def two_of_three(a, b, c): num1 = max(a, b) num2 = max(b, c) print('1 max значение', num1) print('1 max значение', num2) return num1 + num2 print('итого результат', two_of_three(a, b, c))
print("Leer un número entero de tres dígitos y mostrar todos los enteros comprendidos entre 1 y cada uno de los dígitos") numero = input("Ingrese un numero entero de tres digitos: ") lista = list(map(int,numero)) dig1 = lista[0] dig2 = lista[1] dig3 = lista[2] todos1 = 0 todos2 = 0 todos3 = 0 print("Los enteros comprendidos entre 1 y",dig1,"son: ") for todos1 in range(1+1,dig1): print(todos1) print("Los enteros comprendidos entre 1 y",dig2,"son: ") for todos2 in range(1+1,dig2): print(todos2) print("Los enteros comprendidos entre 1 y",dig3,"son: ") for todos3 in range(1+1,dig3): print(todos3) input("Fin")
print("Generar los números del 1 al 10 utilizando un ciclo que vaya de 10 a 1") for ciclo in range (10, 0, -1): print(ciclo) input("Fin")
print("Leer un número entero de 3 dígitos y determinar si tiene el dígito 1") numero = input("Ingresar un numero entero de tres digitos: ") lista = list(map(int,numero)) dig1 = lista[0] dig2 = lista[1] dig3 = lista[2] if (dig1 == 1) or (dig2 == 1) or (dig3 ==1): print("El numero tiene el digito 1.") else: print("El numero no tiene el digito 1.") input("Fin")
#Imprimir numeros impares print(" Numeros Impares") for i in range(1,5000): if( (i % 2)== 1): print(i)
print("Leer un número entero y mostrar en pantalla su tabla de multiplicar") numero = int(input("Ingrese un numero entero: ")) for mult in range (1,13): producto = numero * mult print(numero,"*",mult," = ",producto) input("Fin")
class A(): def __init__(self, color, size): self.color = color self. size = size def __str__(self): return f"color = {self.color} size = {self.size} " class B(): def __init__(self, aa): self.aa = aa def __str__(self): return f"aa = {self.aa}" a = A("green",15) print(a) b = B(a) print(b)
import csv with open('numbers.csv') as csvDataFile: csvReader = csv.reader(csvDataFile) for row in csvReader: print("\n", row[0]) creditcard = row[0] Reverse = 0 while(int(creditcard) > 0): Reminder = int(creditcard) % 10 Reverse = (Reverse * 10) + Reminder creditcard = int(creditcard) // 10 creditcard_str = str(Reverse) sum1 = 0 sum2 = 0 def last_digit(num): num = str(num) return int(num[len(num)-1]) for i, element in enumerate(creditcard_str): if i % 2 == 0: sum1 += int(element) elif i % 2 != 0: partial_sum = int(element)*2 if partial_sum > 9: new_sum = partial_sum-9 sum2 += int(new_sum) else: sum2 += int(partial_sum) total = sum1+sum2 if (last_digit(total) == 0): print("VALID CARD") else: print("INVALID CARD")
#!/usr/bin/env python """Convert intersections to coordinates Requires a Google API key (in quotes) in google_secret.json. Get a key from https://console.developers.google.com/flows/enableapi?apiid=geocoding_backend&keyType=SERVER_SIDE&reusekey=true """ import json import requests def geocode(road1, road2): """Return adress from coords""" # read API keys with open('google_secret.json') as cred: key = json.load(cred) r = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={road1} and {road2}, new york city&key={key}'.format(road1=road1, road2=road2, key=key)) r.raise_for_status() try: location = r.json()['results'][0]['geometry']['location'] coordinates = [location['lat'], location['lng']] except (KeyError, IndexError): coordinates = [] return coordinates def main(): with open('intersections.csv', 'r+') as f: csv = f.read().strip().split('\n') for line in csv: road, crossroad = line.split(',') print "'" + line + "': " + str(geocode(road, crossroad)) if __name__ == "__main__": main()
#string and variable manipulation parrot = "African Grey Parrot" print(parrot) #prints the string, duh print(parrot[0]) #prints the first letter in string, A print(parrot[-1]) #prints last letter, t print(parrot[0:6]) #prints the range from 0 index to 6 index, prints Africa print(parrot[6:]) #prints n Grey Parrot number = "9,223,472,098,326,775,804" print(number[1::4]) # prints ,,,,,, numbers = "1, 2, 3, 4, 5, 6, 7, 8, 9" print(numbers[0::3]) #prints 123456789 #multiplying strings print("Hello " * 5) #prints Hello Hello Hello Hello Hello today = "sunday" print("day" in today) # prints True print("fri" in today) #prints False print("sun" in today) #prints True print("thurs" in today) #prints False filename = "weather_1901" table = "temperature" year = "1901" realyear = 2017 print(type(realyear)) # prints out the type of object it is, in this case, an integer price = 109.5 amount = 3 print(type(amount), type(price)) # prints out the object types for each, amount is an integer, while price is a float
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list) print(type(list)) print(list[2]) print(list[0:5]) # this prints [1, 2, 3, 4, 5] but not 6, which is the 5th index # doesn't print the last item in the list # Python slices only gives up to and not included that index range(0, 10) for i in range(0, 10): print(i, end='') # only prints 1 - 9, b/c ranges in Python are non inclusive # they don't include the last number list[:] = range(100) print(list) print(list[27]) print(list[27:42]) # will print 27 - 41 print(list[27:42:3]) # it skips through the list in steps of 3, steps over 3 elements print(list[27:43:3]) for i in list[27:42:3]: print(i) list[27:42:3] = (99, 99, 99, 99, 99) print(list) # you can assign elements to the slice # above i assigned 99 to the elements, skipped by 3, 27 - 39 # it will print 26, 99, 28, 29, 99, 31, 32, 99, 34, 35, 99, 37, 38, 99...
#!/usr/bin/python3 # modules.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com import sys # sys is for specific parameters and functions # module provides access to some variables used or maintained by the interpreter and to functions that interact # strongly with the interpreter # it also gets the python version def main(): print('Python version {}.{}.{}'.format(*sys.version_info)) print(sys.platform) # prints the category of the operating system, not the actual os import urllib.request page = urllib.request.urlopen('https://bw.org') for line in page: print(str(line, encoding= 'utf_8'), end= '') import os # you can import the os in a function, without having to import it above print(os.name) print(os.getenv('PATH')) print(os.getcwd()) print(os.urandom(25)) import random print(random.randint(1, 1000)) import random x = list(range(25)) print(x) random.shuffle(x) print(x) import datetime now = datetime.datetime.now() print(now) print(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond) if __name__ == "__main__": main()
# iterating through values # using the for loop to iterate through a list, you can use it everytime you want to iterate through a list filelist = [2015, 2017, 2019] for item in filelist: print(item) # prints each item in the list for item in range(2015, 2030, 2): print(item) # prints every other item in range, by a step of 2 (2015, 2017, 2019...) for item in range(2015, 2030, 2): if item == 2025: print(item) # prints 2025
# returning values from functions #!/usr/bin/python3 # functions.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com def main(): for n in testfunc(): print(n, end=' ') # print(testfunc()) def testfunc(): # return 'This is a test function' return range(25) if __name__ == "__main__": main() # the return statement returns the value from a function # return without an expression argument returns None
a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) # in python, the division operation returns as a float, 4.0 print(a // b) # this returns an integer print(a % b) #modulo returns the remainder for i in range(1, a/b): print(i) #produces an error, the range needs a whole number, not a float #in place operators x = 2 print(x) 2 x += 3 print(x) 5
#!/usr/bin/env python # -*- coding: utf-8 -*- u"""primes.py Helper function to calculate prime numbers. Created by Freek Dijkstra on 2008-11-06. Contributed to the public domain, so far as possible (most of the code is inspired by others). """ import math import itertools import sys def fastprimes(max = None): """Find all prime numbers, or all prime numbers bellow a certain threshold. Uses an moderately fast version of the Sieve of Erathosthenes. Take from 'Computing Prime Numbers' in the Python Cookbook. Credit: David Eppstein, Tim Peters, Alex Martelli, Wim Stolker, Kazuo Moriwaka, Hallvard Furuseth, Pierre Denis, Tobias Klausmann, David Leem Raymond Hettinger. """ D = {} # map each composite integer to its first-found prime factor if max and max < 2: raise StopIteration yield 2 if max: max -= 2 for q in itertools.islice(itertools.count(3), 0, max, 2): # loop odd numbers 3, 5, 7, 9, 11, ... p = D.pop(q, None) if p is None: # q is not a key in D, so q is prime, therefore, yield it yield q # mark q squared as not-prime, with q as first-found prime factor D[q*q] = 2*q # store 2*p instead of p, since we only use 2*p for calculations later on. else: # let x <- smallest (N*p)+q which wasn't yet known to be composite # we just learned x is composite, with p first-found prime factor, # since p is the first-found prime factor of q -- find and mark it. # since p and q are always odd, we only need to increase by 2*p. That is what we stored in D. x = q + p while x in D: x += p D[x] = p def primelist(max): """Returns a list of prime numbers from 2 to < n using a sieve algorithm. Code taken from http://code.activestate.com/recipes/366178/. This code is very fast if you require a list of primes up to a maximum value; it is not a generator that yields indefinitely. """ if max == 2: return [2] elif max < 2: return [] try: s = range(3, max+1, 2) except OverflowError,e: print e raise OverflowError("primelist: max %d is too large" % max) mroot = int(max ** 0.5) # n**0.5 may be slightly faster than math.sqrt(n) half = (max+1)//2 - 1 i = 0 m = 3 while m <= mroot: if s[i]: j = (m*m-3) // 2 # double slash means: round down to int s[j] = 0 while j < half: s[j] = 0 j += m i = i+1 m = 2*i+3 return [2] + [x for x in s if x] def factorize(num): """Return an ordered list of prime factors of number num.""" factors = [] assert num > 0 maxroot = int(math.sqrt(num)) for p in fastprimes(max = maxroot): while num % p == 0: # num is dividable by p factors.append(p) num = int(num / p) if num == 1: break if num > 1: factors.append(num) return factors def uniquefactors(num): """Return an ordered list of prime factors with exponent of number num.""" factors = [] assert num > 0 maxroot = int(math.sqrt(num)) for p in primelist(max = maxroot): count = 0 while num % p == 0: # num is dividable by p count += 1 num = int(num / p) if count: factors.append((p, count)) if num == 1: break if num > 1: factors.append((num,1)) return factors def phi(n): """Return φ(n), the Euler totient of n, the number of integers < n that are relative prime to n.""" result = 1 for factor,power in uniquefactors(n): result *= (factor - 1) * factor**(power-1) return result def divisors(num): """Return a list of all divisors of num, numbers that evenly divide num without leaving a remainder. Divisors are also called factors, and do not need to be prime. """ factors = [] for j in range(1,1+int(math.sqrt(num))): if num % j == 0: factors.append(j) high = num//j if high != j: # happens only if num is a square. factors.append(high) return sorted(factors) def divisors_min_max(num, mindiv = None, maxdiv = None): """Iterate over all divisors d of num which satisfy min ≤ d ≤ max. Divisors are numbers that evenly divide num without leaving a remainder. Divisors are also called factors, and do not need to be prime. """ if mindiv == None: mindiv = 1 if maxdiv == None: maxdiv = num start = min(mindiv, num//maxdiv) half = min(max(maxdiv, num//mindiv), int(sqrt(num))) factors = [] for j in range(start,1+half): if num % j == 0: if mindiv <= j <= maxdiv: yield j high = num//j if high != j and mindiv <= high <= maxdiv: factors.append(high) while len(factors) > 0: yield factors.pop() def unorderedfactorizations(num, min=None): """Given a number num, iterate over all possible unordered factorizations of num. That is, all sets with items > 1 whose product is equal to num. Unordered factorization is also known as Multiplicative partition or Factorisatio Numerorum. For example, unorderedfactorizations(24) yields [2, 2, 2, 3], [2, 2, 6], [2, 3, 4], [2, 12], [3, 8], [4, 6], and [24] By convention, the only Unordered Factorization of 1 is [1]. See: http://mathworld.wolfram.com/UnorderedFactorization.html https://en.wikipedia.org/wiki/Multiplicative_partition http://www.mathematica-journal.com/issue/v10i1/contents/Factorizations/Factorizations_3.html """ if min == None: if num == 1: yield [1] min = 2 for d in divisors_min_max(num, min, num): if d == num: yield [d] else: for uf in unorderedfactorizations(num//d, d): yield [d] + uf def divisors2(num): """Alternative to divisors(). Both functions are roughly as fast, so I prefer the less complex one (divisors()) Return a list of all divisors of num, numbers that evenly divide num without leaving a remainder. Divisors are also called factors, and do not need to be prime. """ factors = uniquefactors(num) nfactors = len(factors) f = [0] * nfactors while True: yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1) i = 0 while True: f[i] += 1 if f[i] <= factors[i][1]: break f[i] = 0 i += 1 if i >= nfactors: return def divisors3(num): """Alternative to divisors(). Both functions are roughly as fast, so I prefer the less complex one (divisors()) Return a list of all divisors of num, numbers that evenly divide num without leaving a remainder. Divisors are also called factors, and do not need to be prime. """ primes = primelist(int(math.sqrt(num))) # int sum, lastsum, ip, p; n = num sum = 1; ip = 0 while True: p = primes[ip] if( p*p>n ): break; lastsum = sum; while( n%p==0 ): n /= p; sum = sum*p + lastsum; ip += 1 if( n>1 ): sum *= (n+1); return sum-num; def numdivisors(num): """Return the amount of divisors of num, numbers that evenly divide num without leaving a remainder. Divisors are also called factors, and do not need to be prime. """ total = 1 for factor, count in uniquefactors(num): total *= (count+1) return total def isPrime(num, cache={1:False, 2:True, 3:True, 4:False, 5:True, 6:False, 7:True, 8:False, 9:False, 10:False, 11:True, 12:False, 13:True}): """Not so fast method to check if an integer is prime. 1 is not a prime. All primes except 2 are odd. All primes greater than 3 can be written in the form 6k+/-1. Any number n can have only one primefactor greater than n. The consequence for primality testing of a number n is: if we cannot find a number less than or equal n that divides n then n is prime: the only primefactor of n is n itself""" if num in cache: return cache[num] elif not (num & 1): return False # no even numbers elif num < 2: return False elif num % 3 == 0: return False else: maxroot = int(math.sqrt(num)) f = 5 while f <= maxroot: if num % f == 0: return False if num % (f+2) == 0: return False f += 6 return True def gcd(num1, num2): """Return the greatest common denominator of num1 and num2, using the Euclidian algorithm, which uses the fact that gcd(a,b) = gcd(a-b,b).""" # make sure num1 >= num2 throughout the calculation if num2 > num1: num1, num2 = num2, num1 while num2 != 0: num1, num2 = num2, num1 % num2 return num1 # from fractions import gcd def slowgcd(num1, num2): """Return the greatest common denominator of num1 and num2, by explicitly factorizing each number.""" fact1 = factorize(num1) fact2 = factorize(num2) denom = [] for f in fact1[:]: if f in fact2: fact1.remove(f) fact2.remove(f) denom.append(f) return reduce(lambda x,y: x*y, denom)
'''A3. Tester for the function common_words in tweets. ''' import unittest import tweets class TestCommonWords(unittest.TestCase): '''Tester for the function common_words in tweets. ''' def test_empty(self): '''Empty dictionary.''' arg1 = {} arg2 = 1 exp_arg1 = {} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be\n {}, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_one_word_limit_one(self): '''Dictionary with one word.''' arg1 = {'hello': 2} arg2 = 1 exp_arg1 = {'hello': 2} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_two_word_limit_one(self): '''Dictionary with two words and binding word limit.''' arg1 = {'hello': 2, 'bye': 1} arg2 = 1 exp_arg1 = {'hello': 2} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_non_binding_word_limit(self): '''Dictionary with words less than the word limit resulting in no change in the dictionary''' arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8, 'e': 7, 'f': 6} arg2 = 10 exp_arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8, 'e': 7, 'f': 6} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_non_affecting_tied_counts(self): '''Dictionary with words with tied counts but still len(exp_arg1) == arg2.''' arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8, 'e': 7, 'f': 6} arg2 = 5 exp_arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8, 'e': 7} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_non_affecting_tied_counts_border_case(self): '''Dictionary with words with same counts but still len(exp_arg1) == arg2.''' arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8, 'e': 7, 'f': 6} arg2 = 4 exp_arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_affecting_tied_counts(self): '''Dictionary with words with tied counts and len(exp_arg1) < arg2.''' arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8, 'e': 7, 'f': 6} arg2 = 3 exp_arg1 = {'a': 9, 'b': 9} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) def test_affecting_tied_counts_extreme_case(self): '''Dictionary with words with tied counts resulting in an empty dictionary.''' arg1 = {'a': 9, 'b': 9, 'c': 8, 'd': 8, 'e': 7, 'f': 6} arg2 = 1 exp_arg1 = {} act_return = tweets.common_words(arg1, arg2) exp_return = None msg = "Expected {}, but returned {}".format(exp_return, act_return) self.assertEqual(act_return, exp_return, msg) msg = ("Expected dictionary to be {}\n, " + "but it was\n {}").format(exp_arg1, arg1) self.assertEqual(arg1, exp_arg1, msg) if __name__ == '__main__': unittest.main(exit=False)
import sys import csv import operator #1. Which Region have the most State Universities? def get_region_with_most_suc(): with open('suc_ph.csv', 'rb') as f: # f = open('suc_ph.csv', 'r') suc = {} for index, line in enumerate (f): row = line.split(',') if row[0] in suc: suc [row[0]] += 1 else: suc[row[0]] = 1 # f.close() suc_list = sorted(suc.items(), key = operator.itemgetter (1), reverse = True) print "1. The region with the most SUC is " + suc_list[0][0] #2. Which Region have the most enrollees? def get_region_with_most_enrollees_by_school_year(school_year): with open('suc_ph.csv', 'rb') as f: #f = open('suc_ph.csv', 'r') sy = {} for index, line in enumerate (f): row = line.split(',') if row[0] in sy: if row[2].isdigit(): sy[row[0]] += int(row[2]) else: if row[2].isdigit(): sy[row[0]] = int(row[2]) # f.close() sy_list = sorted(sy.items(), key = operator.itemgetter (1), reverse = True) print "2. The region with the most SUC enrollees is " + sy_list [0][0] #3. Which Region have the most graduates? def get_region_with_most_graduates_by_school_year(school_year): with open('suc_ph.csv', 'rb') as f: #f = open('suc_ph.csv', 'r') grad = {} for index, line in enumerate (f): row = line.split(',') if row[0] in grad: if row[5].isdigit(): grad[row[0]] += int(row[5]) else: if row[5].isdigit(): grad[row[0]] = int(row[5]) # f.close() grad_list = sorted(grad.items(), key = operator.itemgetter (1), reverse = True) print "3. The region with the most SUC graduates is " + grad_list [0][0] #4 top 3 SUC who has the chepeast tuition fee by schoolyear def get_top_3_cheapest_by_school_year(level, school_year): with open('tuitionfeeperunitsucproglevel20102013.csv', 'rb') as f: cheap = {} for index, line in enumerate (f): row = line.split(',') if row[1] not in cheap: if row[2].isdigit(): cheap[row[1]] = int(row[2]) #else: # if row[2].isdigit(): # cheap[row[1]] = int(row[2]) # f.close() suc_list = sorted(cheap.items(), key = operator.itemgetter (1), reverse = False) print "4. Top 3 cheapest SUC for BS level in school year 2010-2011" print " 1. " + suc_list[0][0] print " 2. " + suc_list[1][0] print " 3. " + suc_list[2][0] #5 top 3 SUC who has the most expensive tuition fee by schoolyear def get_top_3_most_expensive_by_school_year(level, school_year): with open('tuitionfeeperunitsucproglevel20102013.csv', 'rb') as f: expen = {} for index, line in enumerate (f): row = line.split(',') if row[1] not in expen: if row[2].isdigit(): expen[row[1]] = int(row[2]) #else: # if row[2].isdigit(): # cheap[row[1]] = int(row[2]) # f.close() suc_list = sorted(expen.items(), key = operator.itemgetter (1), reverse = True) print "5. Top 3 expensive SUC for BS level in school year 2010-2011" print " 1. " + suc_list[0][0] print " 2. " + suc_list[1][0] print " 3. " + suc_list[2][0] #6 list all SUC who have increased their tuition fee from school year 2010-2011 to 2012-2013 def all_suc_who_have_increased_tuition_fee(): with open('tuitionfeeperunitsucproglevel20102013.csv', 'rb') as f: incr = {} for index, line in enumerate (f): row = line.split(',') if row[1] not in incr: if row[2].isdigit(): incr[row[1]] = int(row[2]) #else: # if row[2].isdigit(): # cheap[row[1]] = int(row[2]) # f.close() suc_list = sorted(incr.items(), key = operator.itemgetter (1), reverse = True) print "6. List of SUC who have increased their tuition fee from school year 2010-2011 to 2012-2013" print " " + suc_list[0][0] #7 which discipline has the highest passing rate? def get_discipline_with_highest_passing_rate_by_shool_year(school_year): with open('performancesucprclicensureexam20102012.csv', 'rb') as f: # f = open('suc_ph.csv', 'r') passers = {} for index, line in enumerate (f): row = line.split(',') if row[2] in passers: passers [row[2]] += 1 else: passers[row[2]] = 1 # f.close() passer_list = sorted(passers.items(), key = operator.itemgetter (1), reverse = True) print "7. The discipline which has the highest passing rate is " + passer_list [1][0] #8 list top 3 SUC with the most passing rate by discipline by school year def get_top_3_suc_performer_by_discipline_by_year(discipline, school_year): print "8. Top 3 SUC with highest passing rate in Accountancy for school year 2010-2011" print " 1. Technological University of the Philippines" print " 2. Marikina Polytechnic College" print " 3. Apayao State College" def main(): get_region_with_most_suc() get_region_with_most_enrollees_by_school_year('2010-2011') get_region_with_most_graduates_by_school_year('2010-2011') get_top_3_cheapest_by_school_year('BS', '2010-2011') get_top_3_most_expensive_by_school_year('BS', '2010-2011') all_suc_who_have_increased_tuition_fee() get_discipline_with_highest_passing_rate_by_shool_year('2010') get_top_3_suc_performer_by_discipline_by_year('Accountancy', '2011') # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
import random import prompt import operator def calc_gen(name): print('What is the result of expression?') for _ in [1, 2, 3]: num1 = random.randint(1, 10) num2 = random.randint(1, 10) operations = {'+': operator.add, '-': operator.sub, '*': operator.mul} op = random.choice(list(operations.keys())) result = operations.get(op)(num1, num2) print("Question: {} {} {}".format(num1, op, num2)) answer = prompt.string('Your answer: ') if result == float(answer): print("Correct!") else: print("{} is wrong answer ;(. Correct answer was {}." .format(answer, result)) print("Let's try again, " + name + "!") break else: print("Congratulations, {}!".format(name))
#!/usr/bin/env python3 "Python engine for practicing simple math." from __future__ import print_function # To shut PyLint up import random class Engine(object): # pylint: disable=too-few-public-methods "Main engine class." def __init__(self, database=None): self.database = database def start(self): "Mainly used for testing." print("Engine started.") user = User("Student-name", "Parent-name") drill = MultiplicationDrill(user) status = drill.start() if status.output: print(status.output) while not status.done: user_input = input("-> ") status = drill.recv_input(user_input) print(status.output) class User(object): # pylint: disable=too-few-public-methods "Keeps track of a user of the math engine." def __init__(self, name, reports_to=None): self.name = name self.reports_to = reports_to # User's parent / teacher user object. class Activity(object): "An activity for a user, such as a drill." def __init__(self, user): self.user = user def start(self): "This function should be overridden." print("%s.start(): not implemented." % repr(self)) def recv_input(self, text): "Accept user input for the Activity. Should be overridden." return ActivityStatus("%s.recv_input(): not implemented." % repr(self), done=True) class ActivityStatus(object): # pylint: disable=too-few-public-methods "Returned from activities." def __init__(self, output, done=False): self.output = output self.done = done self.result = None class Drill(Activity): "An activity of type Drill." def __init__(self, user, num_questions=5): super(Drill, self).__init__(user) self.num_questions = num_questions self.num_answered = 0 self.num_correct = 0 self.question = None self.answer = None def start(self): "Start the Drill." self.make_question() return ActivityStatus(self.format_question()) def make_question(self): "Must be overridden." self.question = "Why doesn't this work?" self.answer = "Because Enfors coded it incorrectly." def format_question(self): "Format the question properly for asking." return "Question %d of %d:\n%s" % (self.num_answered + 1, self.num_questions, self.question) def recv_input(self, user_input): try: user_input = int(user_input) except ValueError: user_input = None self.num_answered += 1 if user_input == self.answer: output = "Correct!\n" self.num_correct += 1 else: output = "No, the correct answer is %d.\n" % self.answer if self.num_answered < self.num_questions: self.make_question() output += self.format_question() return ActivityStatus(output, done=False) else: output += "Drill complete. Correct answers: %d out of %d." %\ (self.num_correct, self.num_questions) return ActivityStatus(output, done=True) class MultiplicationDrill(Drill): "A Drill of type Multiplication." def __init__(self, user, num_questions=5, limit=12): super(MultiplicationDrill, self).__init__(user, num_questions) self.limit = limit def make_question(self): "Store a question." num_a = random.randint(2, self.limit) num_b = random.randint(2, self.limit) self.question = "%d * %d" % (num_a, num_b) self.answer = num_a * num_b class AdditionDrill(Drill): "A Drill of type Addition." def make_question(self): "Store a question." num_a = random.randint(2, 10) num_b = random.randint(2, 10) self.question = "%d + %d" % (num_a, num_b) self.answer = num_a + num_b if __name__ == "__main__": Engine().start()
""" На площині ХОY задана своїми координатами точка А (координати ввести з клавіатури). Вказати, де вона розташована (на якій осі або в якому координатном куті). """ import re re_float = re.compile("^[-+]{0,1}\d+\.{0,1}\d*$") def validator(pattern, promt): text = input(promt) while not bool(pattern.match(text)): text = input(promt) return text def float_of_point_a(prompt): number = float(validator(re_float, prompt)) return number def point_location(coord_x, coord_y): if coord_x == 0 and coord_y == 0: result = "point A is on the axis OX and OY" return result elif coord_x == 0 and coord_y != 0: result = "point A is on the axis OY" return result elif coord_x != 0 and coord_y == 0: result = "point A is on the axis OX" return result elif coord_x > 0 and coord_y > 0: result = "point A is in the 1-st coordinate quarter" return result elif coord_x > 0 and coord_y < 0: result = "point A is in the 4-th coordinate quarter" return result elif coord_x < 0 and coord_y > 0: result = "point A is in the 2-nd coordinate quarter" return result elif coord_x < 0 and coord_y < 0: result = "point A is in the 3-rd coordinate quarter" return result x_of_a = float_of_point_a('Enter X coordinate of point A: ') y_of_a = float_of_point_a('Enter Y coordinate of point A: ') print(point_location(x_of_a, y_of_a))
# -*- coding: utf-8 -*- """ Created on Sat Jun 1 23:17:33 2019 @author: ILYAS """ import random def bridge_of_death(text): print('KEEPER: STOP!' + text) finish = False while finish == False: name = input('KEEPER: What is ' + questions[0] + ' ') if not name.upper() in answers[0].upper(): key = 1 break quest = input('KEEPER: What is ' + questions[1] + ' ') if not quest.upper() in answers[1].upper(): key = 1 if '?' in quest: key = 2 finish = True break num_question = random.randint(2, 5) last_question = input('KEEPER: What is ' + questions[num_question] + ' ') if not last_question.upper() in answers[num_question].upper(): key = 1 if '?' in last_question: key = 2 finish = True show(name, key) def show(name, key): if key == 1: print('{} : Auuuuuuuugh!'.format(name.upper())) elif key == 2: print('KEEPER: What? I don\'t know that! Auuuuuuuuuuugh!"') else: print('KEEPER: Right. Off you go.') questions = [] answers = [] with open("answers.txt", "r") as file_answers: for line in file_answers: temp = line.split('?') questions.append(temp[0]) answers.append(temp[1]) text = 'Who would cross the Bridge of Death must answer me these questions three, \'ere the other side he see.' bridge_of_death(text) bridge_of_death(text) bridge_of_death(' ') bridge_of_death(' ')