text
stringlengths
37
1.41M
#!/usr/bin/env python # encoding: utf-8 """ @author: Kimmyzhang @license: Apache Licence @file: kimmyzhang_20170911_03.py @time: 2017/9/11 17:01 """ # 尽量不要重复代码 def get_max_index(nums): len_nums = len(nums) max_num = max(nums) max_index = [] for i in range(len_nums): if nums[i] == max_num: max_index.append(i) left_max_index = max_index[0] right_max_index = max_index[-1] return max_num, left_max_index, right_max_index def solution(nums): max_num, left_max_index, right_max_index = get_max_index(nums) res_list = [0 for _ in range(left_max_index)] # 考虑其他位置 i = 0 while i <= left_max_index: j = i + 1 while j <= left_max_index: if nums[j] <= nums[i]: # 要对j进行加1操作 j = j + 1 continue else: res_list[i: j] = [nums[i] for _ in range(j - i)] break i = j return res_list def solution_rain(nums): # 获取信息 max_num, left_max_index, right_max_index = get_max_index(nums) temp1 = solution(nums) nums.reverse() temp2 = solution(nums) temp2.reverse() return temp1 +[max_num for _ in range(right_max_index - left_max_index + 1)] +temp2 if __name__ == '__main__': nums = [1, 2, 1, 3, 1, 4, 3, 2, 4, 3, 1, 2, 1] print(nums) print(solution_rain(nums))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @date : 2018-05-05 16:22:39 # @author : lyrichu # @email :[email protected] # @link : https://www.github.com/Lyrichu # @version : 0.1 # @description: ''' Q3:给定一个链表a1->a2->...->an,返回a1->an->a2->a(n-1)->... tips:将链表从中间一分为二,然后转换为链表插入问题 ''' class Node: def __init__(self,data = None,next_ = None): self.data = data self.next = next_ class LinkedList: def __init__(self): self.head = Node() def is_empty(self): return self.head.next is None def insert(self,data): new_node = Node(data) cur_node = self.head while cur_node.next: cur_node = cur_node.next cur_node.next = new_node def print(self): if self.is_empty(): print("This is an empty linkedlist!") else: cur_node = self.head.next print(cur_node.data,end = " ") while cur_node.next: cur_node = cur_node.next print(cur_node.data,end = " ") print("") def length(self): if self.is_empty(): return 0 else: n = 0 cur_node = self.head while cur_node.next: n += 1 cur_node = cur_node.next return n def solution(linkedlist): n = linkedlist.length() # 链表长度 cur_node = linkedlist.head index = 0 while index < (n+1)//2: cur_node = cur_node.next index += 1 cur_node1 = linkedlist.head.next cur_node2 = cur_node.next cur_node.next = None #linkedlist.print() tmp = [] # 辅助栈 # 将第二个链表逆序 while cur_node2: tmp.append(cur_node2) cur_node2 = cur_node2.next #print(len(tmp)) while cur_node1.next and tmp: cur_node2 = tmp.pop() # 弹出栈 cur_node2.next = None pre_node = cur_node1.next cur_node1.next = cur_node2 cur_node2.next = pre_node cur_node1 = pre_node if tmp: cur_node1.next = tmp.pop() cur_node1.next.next = None if __name__ == '__main__': li = LinkedList() for i in range(11): li.insert(i) # li.print() # print(li.length()) solution(li) li.print()
# 当我们在传入函数时,有些时候,不需要显示的定义函数,直接传入匿名函数更方便。 lambda x: x * x # 上面这个匿名函数就是: def f(x): return x * x # 匿名函数有一个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。 # 匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数复制给一个变量,然后再利用变量来调用该函数 f = lambda x:x * x print(f(4)) # 同样,可以把匿名函数作为返回值返回 def build(x, y): return lambda: x * x + y * y r = build(4, 5) print(r()) L = list(filter(lambda n: n % 2 == 1, range(1, 20))) print(L)
# python 内建的 filter() 函数用于过滤序列; # fitter() 把传入的函数一次作用与每个元素,然后根据返回值是True 还是 False 决定保留还是丢弃该元素 # 例如:在一个list中,删掉偶数,只保留奇数: def is_off(n): return n % 2 == 1 L = list(filter(is_off, [1,2,3,4,5,6,8,9])) print(L) # 求出素数 # 先构造一个从3开始的奇数序列 def _odd_iter(): n = 1 while True: n = n + 2 yield n # 再定义一个筛选函数 def _not_divisible(n): return lambda x:x % n > 0 # 定义个生成器,不断返回下一个素数: def primes(): yield 2 it = _odd_iter() while True: n = next(it) yield n it = filter(_not_divisible(n), it) it1 = primes() n = 1 for n in range(10): print(next(it1)) # 练习:回数,指的是从左向右读和从右向左读都是一样的数,例如12321,909,利用filter() 筛选出回数: def is_palindrome(n): s = str(n) for i in range(len(s)): if s[i] != s[-i-1]: return False return True output = filter(is_palindrome, range(1, 200)) print(list(output)) # 利用切片的方法: def is_palindrome_1(n): s = str(n) return s[:] == s[::-1] # [::-1] 这种切片操作表示取整个列表,并倒序显示 output = filter(is_palindrome_1, range(1, 300)) print(list(output))
# tuple类型数据,叫元组,也是一种有序列表,tuple一旦初始化就不能更改。写代码的时候,可以利用其不可变的特性,使代码变得更安全。 a = ('white', 'yellow', 'red') print(a) print(a[0]) print(a[1]) print(a[2]) print(a[-1]) print(a[-2]) print(a[-3]) # 定义一个空的tuple b = () print(b) # 如果要定义一个只有1个元素的tuple,就需要注意了 c = (1) print(c) # 这时候定义的就不是tuple,而是 1 这个数,这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义。因此,python规定,上面这种情况,按小括号进行计算 # 定义只有一个元素的tuple,必须加一个逗号,以免误解成数学计算意义上的括号 d = (1,) print(d) # tuple中可以包含list,而这个list中的元素是可变的,因为对于tuple而言,它的元素list没有变 e = (1, 2, 3, ['a', 'b', 'c']) print(e) e[3][0] = 'engineer' print(e)
# this is the class and the methods class Budget: def __init__(self, balance): self.balance = balance def deposit(self, amount): self.balance = self.balance + amount return self.balance def withdraw(self, amount): self.balance = self.balance - amount return self.balance def checkBalance(self): return self.balance #this are the instance of the class food = Budget(2000) clothing = Budget(3000) entertainment = Budget(500) #this is a function to implement the transfer def Transfer(): count = 0 check = True while (check == True): WhatToDo = int(input( "What Operation do you want to perform:\n1) Transfer from food to clothings Account \n2) Transfer from food to entertainment Account \n3) Transfer from clothing to food Account \n4) Transfer from clothing to entertainment Account \n5) Transfer from entertainment to food Account \n6) Transfer from entertainment to clothings Account\n7) Exit Program \n0)Back \nType here: ")) if WhatToDo == 1: amount = int(input("Enter your money: ")) foodAcc = food.withdraw(amount) clothingAcc = clothing.deposit(amount) print( f'Your food Balance is now: GH₵{foodAcc} and your clothing Balance is: GH₵{clothingAcc}') elif WhatToDo == 2: amount = int(input("Enter your money: ")) foodAcc = food.withdraw(amount) entertainmentAcc = entertainment.deposit(amount) print( f'Your food Balance is now: GH₵{foodAcc} and your clothing Balance is: GH₵{entertainmentAcc}') elif WhatToDo == 3: amount = int(input("Enter your money: ")) clothingAcc = clothing.withdraw(amount) foodAcc = food.deposit(amount) print( f'Your food Balance is now: GH₵{clothingAcc} and your clothing Balance is: GH₵{foodAcc}') elif WhatToDo == 4: amount = int(input("Enter your money: ")) clothingAcc = clothing.withdraw(amount) entertainmentAcc = entertainment.deposit(amount) print( f'Your food Balance is now: GH₵{clothingAcc} and your clothing Balance is: GH₵{entertainmentAcc}') elif WhatToDo == 5: amount = int(input("Enter your money: ")) entertainmentAcc = entertainment.withdraw(amount) foodAcc = food.deposit(amount) print( f'Your food Balance is now: GH₵{entertainmentAcc} and your clothing Balance is: GH₵{foodAcc}') elif WhatToDo == 6: amount = int(input("Enter your money: ")) entertainmentAcc = entertainment.withdraw(amount) clothingAcc = clothing.deposit(amount) print( f'Your food Balance is now: GH₵{entertainmentAcc} and your clothing Balance is: GH₵{clothingAcc}') elif (WhatToDo == 0): break elif(WhatToDo == 7): exit() else: print("Invalid Option!") count += 1 if count == 3: print("Program returned to main menu\n") break count = 0 check = True print("\n\n==================================== Welcome to Bugeting System ====================================\n") while (check == True): WhatToDo = int( input("\nWhat Operation do you want to perform:\n1) Deposit \n2) Withdraw \n3) Check Balance \n4) Transfers \n5) Exit Program\nType here: \n")) if (WhatToDo == 1): while (check == True): WhatToDo = int(input( "What Operation do you want to perform:\n1) Deposit to food Account \n2) Deposit to clothing Account \n3) Deposit to entertainment Account\n4) Exit Program\n0)Back\nType here: ")) if (WhatToDo == 1): amount = int(input("Enter your money: ")) foodAcc = food.deposit(amount) print("Your Food balance is: GH₵", foodAcc) elif (WhatToDo == 2): amount = int(input("Enter your money: ")) clothingAcc = clothing.deposit(amount) print("Your clothing balance is: GH₵", clothingAcc) elif (WhatToDo == 3): amount = int(input("Enter your money: ")) entertainmentAcc = entertainment.deposit(amount) print("Your entertainment balance is: GH₵", entertainmentAcc) elif(WhatToDo == 0): break elif(WhatToDo == 4): exit() else: print("Invalid Option!") count += 1 if count == 3: print("Program returned to main menu\n") break print("\n") elif (WhatToDo == 2): while (check == True): WhatToDo = int(input( "What Operation do you want to perform:\n1) Withdraw from food Account \n2) Withdraw from clothing Account \n3) Withdraw from entertainment Account\n4) Exit Program \n0) Back \nType here: ")) if (WhatToDo == 1): amount = float(input("Enter your money: ")) foodAcc = food.withdraw(amount) print("Your entertainment balance is: GH₵", foodAcc) elif (WhatToDo == 2): amount = float(input("Enter your money: ")) clothingAcc = clothing.Withdraw(amount) print("Your entertainment balance is: GH₵", clothingAcc) elif (WhatToDo == 3): amount = float(input("Enter your money: ")) entertainmentAcc = entertainment.Withdraw(amount) print("Your entertainment balance is: GH₵", entertainmentAcc) elif (WhatToDo == 0): break elif(WhatToDo == 4): exit() else: print("Invalid Option!") count += 1 if count == 3: print("Program returned to main menu\n") break print("\n") elif (WhatToDo == 3): while (check == True): WhatToDo = int(input( "What Operation do you want to perform:\n1) Check food Account \n2) Check clothing Account \n3) Check entertainment Account\n4) Exit Program \n0) Back \nType here: ")) if (WhatToDo == 1): foodAcc = food.checkBalance() print("Your food Balance is: GH₵", foodAcc) elif (WhatToDo == 2): clothingAcc = clothing.checkBalance() print("Your clothing Balance is: GH₵", clothingAcc) elif (WhatToDo == 3): entertainmentAcc = entertainment.checkBalance() print("Your entertainment Balance is: GH₵", entertainmentAcc) elif(WhatToDo == 0): break elif(WhatToDo == 4): exit() else: print("Invalid Option!") count += 1 if count == 3: print("Program returned to main menu\n") break print("\n") elif (WhatToDo == 4): Transfer() print("\n") elif(WhatToDo == 5): break else: print("Invalid Option!") count += 1 if count == 5: print("Program Aborted") break
import numpy as NP from matplotlib import pyplot as PT from operator import itemgetter class KNN(object): """ Class provides implementation of classification problem via k-Nearest Neighbour Algorithm. Given a training data set and a test data, we look for the k most similar training example by computing the Euclidean distance between each data point and consequently vote for the label that has the most occurrence among the training data. For KNN, there is no training phase with the training data is loaded in to the memory. This will make it prone to overfitting. The hyperparameter, K can be tuned to provide the best model btw under and over fitting. Memory usage by KNN grows linearly with the size of the training data. It tends to work well with substantially sized features. KNN complexity is O(n + klogk) i.e the 'n' comes from computing the distances between the test vector each items in the training data. 'klogk' comes from sorting the k class labels """ def __init__(self, training, trainingLabels): if not isinstance(training, NP.ndarray): self.training = NP.array(training) else: self.training = training if not isinstance(trainingLabels, NP.ndarray): self.trainingLabels = NP.array(trainingLabels) else: self.trainingLabels = trainingLabels try: self.NoOfTrainingFeatures = training.shape[1] self.NoOfTrainingSamples = training.shape[0] except Exception as e: raise e if self.NoOfTrainingSamples != self.trainingLabels.shape[0]: raise ValueError("Number of training sample is not the same as the number of labels.") def Classify(self, testVector, k=1): if not isinstance(testVector, NP.ndarray): testVector = NP.array(testVector) else: testVector = testVector noOfTestFeatures = testVector.shape[0] if self.NoOfTrainingFeatures != noOfTestFeatures: raise ValueError("The Number of features in the training and test data is not the same") # Repeat test data vertically no of training data times to calc difference # O(n) the second param in tile() = (noOfRepetitionAlongY, NoOfRepetitionAlongX) diffMat = NP.tile(testVector, (self.NoOfTrainingSamples, 1)) - self.training squareDiffMat = diffMat ** 2 sqDistance = squareDiffMat.sum(axis=1) euclideanDist = sqDistance ** 0.5 sortedDistance = NP.argsort(euclideanDist) if self.NoOfTrainingSamples < k: k = self.NoOfTrainingSamples labelClassCountMap = {} for index in range(k): label = self.trainingLabels[sortedDistance[index]] labelClassCountMap[label] = labelClassCountMap.get(label, 0) + 1 sortedClassCount = sorted(labelClassCountMap.items(), key=itemgetter(1), reverse=True) return sortedClassCount[0][0] def TestClassifier(self, testVectors, testLabels, k=1): if not isinstance(testVectors, NP.ndarray): testVectors = NP.array(testVectors) else: testVectors = testVectors if not isinstance(testLabels, NP.ndarray): testLabels = NP.array(testLabels) else: testLabels = testLabels noOfTestData = testVectors.shape[0] noOfTestLabels = testLabels.shape[0] if noOfTestData != noOfTestLabels: raise ValueError("The number of test data and label are not the same.") errorCount = 0 for vectorIndex in range(noOfTestData): classifierResult = self.Classify(testVectors[vectorIndex, :], k) actualLabel = testLabels[vectorIndex] print("The classifier result: %s, actual result: %s" % (classifierResult, actualLabel)) if actualLabel != classifierResult: errorCount += 1 errorRate = errorCount / noOfTestData print("The total classification error rate is %s" % errorRate) @staticmethod def normalize(dataSet, maxValMat, minValMat): """ Normalize data if features are measured in different ranges. newValue = (oldVal - columnMinVal) / (columnMaxVal - columnMinVal) """ if len(dataSet) < 1: raise ValueError("The dataset contains no values.") if not isinstance(dataSet, NP.ndarray): dataSet = NP.array(dataSet) if len(maxValMat) < 1: maxValMat = NP.max(dataSet, axis=0) if len(minValMat) < 1: minValMat = NP.min(dataSet, axis=0) # axis = 0 find min along y axis i.e column noOfDatasetRows = dataSet.shape[0] normDataset = dataSet - NP.tile(minValMat, (noOfDatasetRows, 1)) rangeData = minValMat - maxValMat normDataset = normDataset / NP.tile(rangeData, (noOfDatasetRows, 1)) return normDataset, maxValMat, rangeData
def create_sql_table_from_df(df, name, conn): ''' Args: df, name, conn: Function takes in each dataframe Returns: table: Converts each dataframe to a sql table ''' # Use try except # it will try to make a table # if a table exists the except part of the code will stop the program from making duplicates try: df.to_sql(name, conn) print(f"Created table {name}") # if the table exists t will tell you, and won't cause an error except Exception as e: print(f"Could not make table {name}") print(e)
def update(): x = open("db.txt", "r") list1 = x.readlines() list2 = [] for ele in list1: list2 += ele.split() for ele in list2: if ele == "Name:" or ele == "Num:": list2.remove(ele) name = "name" number = "number" i = 1 phonebook = dict() for ele in list2: if list2.index(ele) % 2 == 0: name = ele if list2.index(ele) % 2 != 0: number = ele if name != "name" and number != "number": phonebook.update({i: {"name": name, "number": number}}) i += 1 name = "name" number = "number" return phonebook def add(): length = len(phonebook) + 1 name = input("Enter the name: ") number = input("Enter the number: ") phonebook.update({length: {"name": name, "number": number}}) save(phonebook) def browse(): list1 = [] mainlist = [] count = 0 for ele in phonebook.keys(): list1 = list(phonebook[ele].values()) mainlist.append(list1) for ele in mainlist: count += 1 for val in ele: if ele.index(val) == 0: print(str(count) + ". Name: ", val) else: print(" Num: ", val, end="\n\n") def search(): x = input("Enter name or number to be searched: ") for ele in phonebook.keys(): for val in phonebook[ele].values(): if val == x: print("Found!!") for ele in phonebook[ele].values(): print(str(ele), end=" ") flag = True break else: flag = False if flag == False: print("Not in register!") def edit(): x = input("Enter the name of the contact to edit: ") flag = 0 for ele in phonebook.keys(): for val in phonebook[ele].values(): if val == x: print("Contact Found!") choice = input("What would you like to edit (name/num/both): ") if choice == "name": temp = [] temp = list(phonebook[ele].values()) number = temp[1] newname = input("Enter the new name: ") phonebook.update({ele: {"name": newname, "number": number}}) if choice == "num": temp = [] temp = list(phonebook[ele].values()) name = temp[0] newnum = input("Enter the new number: ") phonebook.update({ele: {"name": name, "number": newnum}}) if choice == "both": newname = input("Enter the new name: ") newnum = input("Enter the new number: ") phonebook.update({ele: {"name": newname, "number": newnum}}) flag = 1 break if flag == 1: break if flag == 0: print("Not found!!") save(phonebook) def export(): loc = input("Enter the destination url: ") fname = input("Enter the name of the file to be made: ") x = open("{url}/{file}.txt".format(url=loc, file=fname), "w") mainlist = [] for ele in phonebook.keys(): list1 = list(phonebook[ele].values()) mainlist.append(list1) for ele in mainlist: for val in ele: if ele.index(val) == 0: new = "Name: " + val + "\n" x.write(new) else: new1 = "Num: " + val + "\n\n" x.write(new1) print("Export Complete! Check destination for exported file.") x.close() def save(phonebook): x = open("db.txt", "w") mainlist = [] for ele in phonebook.keys(): list1 = list(phonebook[ele].values()) mainlist.append(list1) for ele in mainlist: for val in ele: if ele.index(val) == 0: new = "Name: " + val + "\n" x.write(new) else: new1 = "Num: " + val + "\n\n" x.write(new1) print("Records Updated!") x.close() phonebook = update() print("********************* PhoneBook v.1.0 *********************", end="\n") print("Options: ") print("1. Browse phonebook") print("2. Add entry") print("3. Search for an entry") print("4. Edit an entry") print("5. Export phonebook to text file") print("************************************************************", end="\n\n") choice = "y" while choice == "y": x = int(input("Choose an option (1/2/3/4/5): ")) if x == 1: browse() elif x == 2: add() elif x == 3: search() elif x == 4: edit() elif x == 5: export() else: print("Invalid Choice!") choice = input("Do you wish to continue working? (y/n): ")
from tkinter import * root = Tk() root.title("First GUI") content = "" txt_input = StringVar(value="0" ) def btn(number): global content content = content+str(number) txt_input.set(content) def equal(): global content calculate = float(eval(content)) txt_input.set(calculate) content = "" def clear(): global content content = "" txt_input.set("") display.insert(0,'0') display = Entry(font=('arial',25,'bold'),fg="black",bg="white",textvariable=txt_input,justify="right") display.grid(columnspan=4) #row1 btn7=Button(fg='purple',bg='white',font=('arial',25,'bold'),text="7",command=lambda:btn(7),padx=20,pady=10).grid(row=1,column=0) btn8=Button(fg='purple',bg='white',font=('arial',25,'bold'),text="8",command=lambda:btn(8),padx=20,pady=10).grid(row=1,column=1) btn9=Button(fg='purple',bg='white',font=('arial',25,'bold'),text="9",command=lambda:btn(9),padx=20,pady=10).grid(row=1,column=2) btnc=Button(fg='white',bg='pink',font=('arial',25,'bold'),command=clear,text="c",padx=20,pady=10).grid(row=1,column=3) #row2 btn4=Button(fg='blue',bg='white',font=('arial',25,'bold'),text="4",command=lambda:btn(4),padx=20,pady=10).grid(row=2,column=0) btn5=Button(fg='blue',bg='white',font=('arial',25,'bold'),text="5",command=lambda:btn(5),padx=20,pady=10).grid(row=2,column=1) btn6=Button(fg='blue',bg='white',font=('arial',25,'bold'),text="6",command=lambda:btn(6),padx=20,pady=10).grid(row=2,column=2) btnplus=Button(fg='white',bg='violet',font=('arial',25,'bold'),text="+",padx=20,command=lambda:btn("+"),pady=10).grid(row=2,column=3) #row3 btn1=Button(fg='cyan',bg='white',font=('arial',25,'bold'),text="1",command=lambda:btn(1),padx=20,pady=10).grid(row=3,column=0) btn2=Button(fg='cyan',bg='white',font=('arial',25,'bold'),text="2",command=lambda:btn(2),padx=20,pady=10).grid(row=3,column=1) btn3=Button(fg='cyan',bg='white',font=('arial',25,'bold'),text="3",command=lambda:btn(3),padx=20,pady=10).grid(row=3,column=2) btnminus=Button(fg='white',bg='violet',font=('arial',25,'bold'),text="-",command=lambda:btn("-"),padx=24,pady=10).grid(row=3,column=3) #row4 btndot=Button(fg='lime',bg='white',font=('arial',25,'bold'),text=".",command=lambda:btn("."),padx=24,pady=10).grid(row=4,column=0) btn0 =Button(fg='lime',bg='white',font=('arial',25,'bold'),text="0",command=lambda:btn(0),padx=20,pady=10).grid(row=4,column=1) btnvisiob=Button(fg='lime',bg='white',font=('arial',25,'bold'),command=lambda:btn("/"),text="/",padx=24,pady=10).grid(row=4,column=2) btnmultiply=Button(fg='white',bg='violet',font=('arial',25,'bold'),text="x",command=lambda:btn("*"),padx=20,pady=10).grid(row=4,column=3) #row5 btnequal=Button(fg='white',bg='pink',font=('arial',25,'bold'),text="=",command=equal,padx=64,pady=10).grid(row=5,column=0,columnspan=2) btnopen=Button(fg='white',bg='violet',font=('arial',25,'bold'),text="(",command=lambda:btn("("),padx=23,pady=10).grid(row=5,column=2) btnclose=Button(fg='white',bg='violet',font=('arial',25,'bold'),text=")",command=lambda:btn(")"),padx=24,pady=10).grid(row=5,column=3) root.mainloop()
from tkinter import* from tkinter import ttk, messagebox class Register: def __init__ (self,root): self.root=root self.root.title("REGISTRATION WINDOW") self.root.geometry("1350x700+0+0") frame1=Frame(self.root,bg="gray") frame1.place(x=480,y=100,width=700,height=500) title= Label(frame1,text="------------------REGISTER TO Softwarica Hotel:-------------------", font=("New times roman", 20,"italic"),fg="black",bg="gray").place (x=50,y=30) #---------------Row1-----------# self.var_fname=StringVar() f_name= Label(frame1,text="First name:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=50,y=100) txt_fname= Entry(frame1,font=("times new roman", 15),bg="dark gray",textvariable= self.var_fname).place(x=50,y=130,width = 250) l_name= Label(frame1,text="Last name:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=370,y=100) self.txt_lname= Entry(frame1,font=("times new roman", 15),bg="dark gray") self.txt_lname.place(x=370,y=130,width = 250) #---------------Row2-----------# Address= Label(frame1,text="Address:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=50,y=170) self.txt_address= Entry(frame1,font=("times new roman", 15),bg="dark gray") self.txt_address.place(x=50,y=200,width = 250) Age= Label(frame1,text="Age:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=370,y=170) self.txt_Age= Entry(frame1,font=("times new roman", 15),bg="dark gray") self.txt_Age.place(x=370,y=200,width = 250) #------------ Row-------------# username= Label(frame1,text="Username:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=50,y=240) self.txt_username= Entry(frame1,font=("times new roman", 15),bg="dark gray") self.txt_username.place(x=50,y=270,width = 250) password= Label(frame1,text="Password:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=370,y=240) self.txt_password= Entry(frame1,font=("times new roman", 15),bg="dark gray") self.txt_password.place(x=370,y=270,width = 250) email= Label(frame1,text="E-mail:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=50,y=310) self.txt_email= Entry(frame1,font=("times new roman", 15),bg="dark gray") self.txt_email.place(x=50,y=350,width = 250) confirm_password= Label(frame1,text="Confirm password:", font=("New times roman", 15,"bold"),fg="black",bg="gray").place (x=370,y=310) self.txt_cpassword= Entry(frame1,font=("times new roman", 15),bg="dark gray") self.txt_cpassword.place(x=370,y=350,width = 250) #---------------------------------------------------------------------------------------------# self.var_chk = IntVar() chk=Checkbutton(frame1,text="I agree to the terms and conditions.",variable=self.var_chk,onvalue=1,offvalue=0,font=("ariel",14,"italic"),bg="gray").place(x=50,y=380) btn_register= Button(frame1,text="Register",font=("New times roman",15,"bold"),bg="gray",fg="blue",cursor="hand2", command = self.register_data).place(x=50,y=420, width = 300) btn_signin= Button(frame1,text="Sign in",font=("New times roman",15,"bold"),bg="gray",fg="red",cursor="hand2").place(x=370,y=420, width = 300) #------------------------------------------------------# def register_data(self): if self.var_fname.get()=="" or self.txt_lname.get()=="" or self.txt_username.get()=="" or self.txt_cpassword.get()==""or self.txt_password.get()=="" or self.txt_Age.get()=="" or self.txt_address.get()=="" or self.txt_email.get()=="": messagebox.showerror("Error","All fields are must!",parent=self.root) elif self.txt_cpassword.get()!= self.txt_password.get(): messagebox.showerror("Wrong password ", "Both the password should match each other",parent= self.root) elif self.var_chk.get()== 0: messagebox.showerror("Error","Please agree to our terms and conditions", parent= self.root) else: try: con= pymysql.connect(host="localhost",user="root",password="",database="mydb") cur=con.cursor() cur.execute("insert into registeration table(fname,lname,Age,Address,email,username,password)values(%s,%s,%s,%s,%s,%s,%s)", (self.txt_fname.get(), self.txt_lname.get(), self.txt_address.get(), self.txt_Age.get(), self.txt_email.get(), self.txt_username.get(), self.txt_password.get(), )) con.commit() con.close() messagebox.showinfo("SUCCESS","You are successfully registered to softwarica 5-star Hotel") except Exception as es: messagebox.showerror("Error",f"ERROR{str(es)}", parent= self.root) root=Tk() obj = Register(root) root.mainloop()
#!/usr/bin/env python3.0 #!-*coding:utf-8 -*- #!@Time :2018-5-22 10:59 #!@Author : LYC #!@File : Leecode_singleNumber_function2_.PY class Solution(object): """ :type nums :list[int] :rtype : int """ def singleNumber(self,nums): num = 0 for p in nums: num ^= p return num if __name__ == '__main__': ins1 = Solution() nums1 = [1,1,2,2,3,3,4,5,5,4,6] nums2 = [1,2,2,3,3,4,4,5,5,] print(ins1.singleNumber(nums1),ins1.singleNumber(nums2))
#!/usr/bin/env python3.0 #!-*coding:utf-8 -*- #!@Time :2018-5-22 11:07 #!@Author : LYC #!@File : Leecode_intersect_function1_.PY class Solution(object): def intersect(self, nums1, nums2): list_interset = [] for p in nums1: for k in nums2: if p == k: list_interset.append(p) nums2.remove(k) break return list_interset if __name__ == '__main__': ins1 = Solution() nums1 =[1,2,2,1] nums2 =[2,2] print(ins1.intersect(nums1,nums2))
a=int(input("enter 1st number")) one=a b=int(input("enter 2nd number")) two=b def odd(one,two): newlist = [] for i in range(one,two): if i%2 !=0: newlist.append(i) print(newlist) return newlist odd(one,two) #alternate way def oddRange(num1, num2): for i in range(num1+1, num2): if i%2 != 0: print(i) num1 = int(input("Enter first number")) num2 = int(input("Enter second number")) oddRange(num1, num2)
def changeString(p): for i in range(len(p)): if i=='a'or i=='e' or i=='i' or i=='o' or i=='u' p.replace(i,upper(i)) x=print("enter string") changeString(p)
'''raw_input = input('Enter the CSV : ') str_list = [x for x in raw_input.split(",")] str_list.sort() #print(str_list) print (','.join(str_list))''' lines = [] print('Enter the input in multi lines : ') while True: test = input() if test: lines.append(test) else: break print('\n'.join(lines).upper())
x = 2 y = 7 z = 10 if x > y: print(x,'is greater than y') if x < y: print(x,'is less than y') if x==y: print(x,'is equals to',y) ''' cannot do this if x < '2': print(x,'is less than 2') ''' if z > y > x: print(z,'is greater than',y,'which is greater than',x) ##################################### x = 3 y = 6 if x < y: print(x,'is less than',y) else: print(x,'is not less than',y)
#3! = 3*2*1 ''' fact_number = int(input('Enter the number : ')) factorial = 1 if fact_number < 0: print('Fatorial for negative numbers not possible') elif fact_number==1: print('Factorial of 0 is 1') else: for i in range(1,fact_number+1): factorial = factorial*i #print(i) print(factorial) ''' def fact(x): if x == 0: return 1 else: factorial = x*fact(x-1) return factorial factorial=fact(4) print(factorial)
import urllib2 import requests import pandas as pd from bs4 import BeautifulSoup import time import sys def get_wga_database(): """ Download a CSV of the WGA collection. ** currently doesn't work """ url = 'http://www.wga.hu/database/download/data_txt.zip' response = urllib2.urlopen(url) # cat_file = response.read() print ' -- Downloading records for the WGA collection -- ' # with open('data/wga_collection.csv', 'wb') as f: # f.write(cat_file) zipfile = ZipFile(StringIO(response.read())) with open('data/wga_collection.csv', 'wb') as f: f.write(zipfile) def download_wga_collection(csv_loc='data/wga_collection.csv', location='collections/wga/', start=0, res='detail'): """ res = 'detail' or 'art' """ df = pd.read_csv('data/catalog.csv', delimiter=';') df = df[df['FORM'].isin(['painting','graphics']) == True] df = df.reset_index() # create output message for user output = """ \n\r -- Downloading WGA collection -- \r ---------------------------- \r Download Location --> {} \r ---------------------------- \r Total Works: {}\n""" print output.format(location, len(df)) for i in xrange(start, len(df)): time.sleep(0) sys.stdout.write("\r -- %d of %d Works -- %d %% Artwork Downloaded -- " % (i, len(df), 1.*i/len(df)*100)) sys.stdout.flush() # grab the URL if type(df['URL'][i]) is str: try: url = df['URL'][i] html = requests.get(url) soup = BeautifulSoup(html.content, 'lxml') s = url.split('/')[-3:] name = s[1] + '/' + s[2].split('.')[0] image_url = ('http://www.wga.hu/' + res + '/' + s[0] + '/' + name + '.jpg') uopen = urllib2.urlopen(image_url) stream = uopen.read() fname = location + 'wga_' + name.replace('/', '_') + '.jpg' with open(fname, 'w') as f: f.write(stream) except IndexError: print 'No image URL' print '\n\n Download was successful!!!\n' if __name__ == '__main__': download_wga_collection(start=0)
def add_all(nums): ret_num = 0 for n in nums: ret_num += n return(ret_num) # main all_nums = [1,2,3,4,5,6,7,8,9,10] sum_num = add_all(all_nums) print("合計は、" + str(sum_num) + "です")
""" @file: cci_10-5.py @author: Taylor Curran @brief: Solution to problem 10.5 from Cracking the Coding Interview @version 0.1 @date 2020-07-01 @note McDowell, Gayle Lakkmann. Cracking the Coding Interview. 6th ed. Palo Alto, CA: CareerCup, 2016. @copyright Copyright (c) 2020 """ """ Problem 10.5: "Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string" """ """ Approach: Use a modifed binary search. Query the middle index. If it is empty, linearly for the first non-empty string; the search the appropriate half recursively """ import math as m def find_string(list, value): """ Returns the index of `value` in `list`; if value is not in the list, returns -1. """ return find_string_recursive(list, value, 0, len(list) - 1) def find_string_recursive(list, value, start, end): # Base cases if end < start: return -1 elif end == start: if list[start] == value: return start else: return -1 else: # Find mid mid = m.floor((start + end) / 2) if list[mid] == '': # Search both direction left = mid - 1 right = mid + 1 while True: # (1) Only empty strings left if start > left and right > end: return -1 # (2) Non-empty string at left elif start <= left and list[left] != '': mid = left break # (3) Non-empty string at right elif right <= end and list[right] != '': mid = right break # (4) Increment value else: left -= 1 right += 1 # Recursive binary search if list[mid] > value: return find_string_recursive(list, value, start, mid - 1) elif list[mid] < value: return find_string_recursive(list, value, mid + 1, end) else: return mid print("Beginning tests...") list = ['at','','','','ball','','','car','','','dad','',''] assert find_string(list, 'at') == 0 assert find_string(list, 'am') == -1 assert find_string(list, 'ball') == 4 assert find_string(list, 'base') == -1 assert find_string(list, 'car') == 7 assert find_string(list, 'dad') == 10 assert find_string(list, 'dog') == -1 assert find_string([], 'dad') == -1 print("All tests passed!")
# File: 01_03_new-year-chaos.py # Name: Taylor Curran # Date: September 22, 2020 # Description: # HackerRank > Interview Preparation Kit > Arrays > New Year Chaos """ Problem: It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride! There are a number of people queued up, and each person wears a sticker indicating their initial position in the queue. Initial positions increment by 1 from 1 at the front of the line to 'n' at the back. Any person in the queue can bribe the person directly in front of them to swap positions. If two people swap positions, they still wear the same sticker denoting their original places in line. One person can bribe at most two others. For example, if n = 8 and Person 5 bribes Person 4, the queue will look like this: [1,2,3,5,4,6,7,8] Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place to get the queue into its current state! Parameters: - 'q': an array on integers Returns: - int: minimum number of brides required Contraints: - 1 <= n <= 10^5 """ # Complete the minimumBribes function below. def minimumBribes(q): swaps = 0 exp_first = 1 exp_second = 2 exp_third = 3 for i in range(len(q) - 1): if q[i] == exp_first: exp_first = exp_second exp_second = exp_third elif q[i] == exp_second: swaps += 1 exp_second = exp_third elif q[i] == exp_third: swaps += 2 else: print('Too chaotic') return exp_third += 1 print('{}'.format(swaps))
""" @file: cci_10-9.py @author: Taylor Curran @brief: Solution to problem 10.9 from Cracking the Coding Interview @version 0.1 @date 2020-07-01 @note McDowell, Gayle Lakkmann. Cracking the Coding Interview. 6th ed. Palo Alto, CA: CareerCup, 2016. @copyright Copyright (c) 2020 """ """ Problem 10.9: "Sorted Matrix Search: Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element" """ """ Approach: Based on binary search. Choose the 'middle' value in the matrix. Use it to split the matrix into four quadrants. Recursively search three of these. """ """ Notes: - The minimum value will always be in the top-left corner; the maximum will be in the bottom right - For any value in the matrix: values to the top-left are smaller; values to the bottom-right are larger; values elsewhere can be either larger or smaller. - This solution is slightly different than the textbook solution, which performs binary search on the diagonal to find the first element larger than the target, and then searches the top-right and bottom-left quadrants recursively, but both are based on binary search, recursion, and the properties of the sorted matrix. """ # Imports import math as m import numpy as np def search_sorted(matrix, value): m,n = matrix.shape return search_sorted_recursive(matrix, value, 0, m-1, 0, n-1) def search_sorted_recursive(matrix, value, top, bottom, left, right): # Base case: empty if top > bottom or left > right: return False # Base case : one cell if top == bottom and left == right: if matrix[top,left] == value: return (top,left) else: return False # Recursive case mid_row = m.floor((top + bottom) / 2) mid_col = m.floor((left + right) / 2) # Eliminate top-left if value > matrix[mid_row, mid_col]: # Search to right right_res = search_sorted_recursive(matrix, value, top, bottom, mid_col + 1, right) if right_res is not False: return right_res # Search to bottom-left else: return search_sorted_recursive(matrix, value, mid_row + 1, bottom, left, mid_col) # Eliminate bottom-right elif value < matrix[mid_row, mid_col]: # Search to left left_res = search_sorted_recursive(matrix, value, top, bottom, left, mid_col - 1) if left_res is not False: return left_res # To top-right else: return search_sorted_recursive(matrix, value, top, mid_row - 1, mid_col, right) else: return (mid_row, mid_col) print("Beginning tests...") #0 matrix = np.array([[]]) assert search_sorted(matrix, 1) is False #1 matrix = np.array([[1]]) assert search_sorted(matrix, 1) in [(0,0)] #2 matrix = np.array([[2]]) assert search_sorted(matrix, 1) is False #3 matrix = np.array([[1,2],[4,6]]) assert search_sorted(matrix, 1) in [(0,0)] #4 matrix = np.array([[0,1],[1,2]]) assert search_sorted(matrix, 1) in [(0,1),(1,0)] #5 matrix = np.array([[0,0],[0,1]]) assert search_sorted(matrix, 1) in [(1,1)] #6 matrix = np.array([[0,1],[1,1]]) assert search_sorted(matrix, 1) in [(0,1),(1,0),(1,1)] #7 matrix = np.array([[0,0],[1,1]]) assert search_sorted(matrix, 1) in [(1,0),(1,1)] #8 matrix = np.array([[0,1],[0,1]]) assert search_sorted(matrix, 1) in [(0,1),(1,1)] #9 matrix = np.array([[0,0,0],[0,1,2],[0,2,2]]) assert search_sorted(matrix, 1) in [(1,1)] #10 matrix = np.array([[0,0,0],[0,0,2],[0,1,2]]) assert search_sorted(matrix, 1) in [(2,1)] #11 matrix = np.array([[0,0,0],[0,0,1],[0,0,2]]) assert search_sorted(matrix, 1) in [(1,2)] #12 matrix = np.array([[0,0,1]]) assert search_sorted(matrix, 1) in [(0,2)] #11 matrix = np.array([[0],[0],[1]]) assert search_sorted(matrix, 1) in [(2,0)] #11 matrix = np.array([[-1,0],[0,0],[1,1]]) assert search_sorted(matrix, 1) in [(2,0),(2,1)] print("All tests passed!")
from threading import Timer class GorrabotTimer: """Call a function every specified number of seconds: gt = GorrabotTimer(f, 1800) gt.start() gt.stop() # stop the timer's action """ def __init__(self, function, interval): self._timer = None self.function = function self.interval = interval self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function() def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False
import numpy as np a = np.array([1, 2, 3]) # Tạo array 1 chiều print(type(a)) # Prints "<class 'numpy.ndarray'>" print(a.shape) # Prints "(3,)" print(a[0], a[1], a[2]) # Prints "1 2 3" a[0] = 5 # Thay đổi phần tử vị trí số 0 print(a) # Prints "[5, 2, 3]" b = np.array([[1,2,3],[4,5,6]]) # Tạo array 2 chiều print(b.shape) # Prints "(2, 3)" print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4" #In other hand a = np.zeros((2,2)) # Tạo array với tất cả các phần tử 0 print(a) # Prints "[[ 0. 0.] # [ 0. 0.]]" b = np.ones((1,2)) # Tạo array với các phần tử 1 print(b) # Prints "[[ 1. 1.]]" c = np.full((2,2), 7) # Tạo array với các phần tử 7 print(c) # Prints "[[ 7. 7.] # [ 7. 7.]]" d = np.eye(2) # Tạo identity matrix kícch thước 2*2 print(d) # Prints "[[ 1. 0.] # [ 0. 1.]]" e = np.random.random((2,2)) # Tạo array với các phần tử được tạo ngẫu nhiên print(e) # Might print "[[ 0.91940167 0.08143941] # [ 0.68744134 0.87236687]]
# A program that calculates BMI name = input("What is Your Name: ") hieght = float(input("Write Your height in Meters: ")) weight = float(input("Write Your weight in KG: ")) def bmi_calc(name, hieght, weight): bmi = weight / (hieght**2) if bmi < 20: return "{0}, your BMI is {1:.3f} you're underweight".format(name, bmi) elif bmi > 25: return "{0}, your BMI is {1:.3f} you're Overweight".format(name, bmi) else: return "{0}, your BMI is {1:.3f} you're in shape".format(name, bmi) userinfo = bmi_calc(name, hieght, weight) print(userinfo)
# Lists pl = ["C","C++","Java","Go","Python"] # Swap Python to C temp = pl[0] pl[0] = pl[4] pl[4] = temp # print(pl) # Dictionary userInfo = { "Name":"Gorad", "age":20, "Study": True, "Work": False, "Email":"[email protected]" } # Classes class Employee: def __init__(self,name,age,email): self._name = name self._age = age self._email = email def greeting(self): print("Hello, My Name is {}, I'm {} years old. contact me at {} ".format(self._name,self._age,self._email)) person1 = Employee(userInfo["Name"],userInfo["age"],userInfo["Email"]) # person1.name = userInfo["Name"] # person1.age = userInfo["age"] # person1.email = userInfo["Email"] person1.greeting() ''' Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 # Then, the output should be: # 40320''' # number = int(input("Enter a number: ")) def fact(number): if number == 0: return 1 return number * fact(number - 1) # x=int(raw_input()) # print(fact(number)) '''With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. Suppose the following input is supplied to the program: 8 Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() ''' # # n = int(input("Enter a Number")) # d=dict() # for i in range(1,n+1): # d[i]=i*i a = [1,2,4,8,16,32,64] # Comprehensive list b = [ i*2 for i in a] print(a) print(b)
''' Sets: Unordered collection of unique, immutable objects ''' s = {112, 23, 34, 454, 56, 57, 676, 7878} print(type(s)) d = {} print(type(d)) # Empty set makes it dictionary so for empty use set ss = set() ss.add(12) ss.add(12) # Adding multiple items to sort ss.update([123, 3434, 454, 56, 56, 55]) # Memebership and containment for set 10 in ss # false 10 not in ss # returns true # [.Remove ]Removing item from set - if item is not found it returns an error ss.remove(12) ss.discard(123) # remove Items from set if not found do nothing # to find type use type print(type(ss)) print(ss) # it holds unique value so it will hold only 12 # Removing duplicates from a list l = [12, 1, 23, 34, 45, 45, 45, 565, 767, 677] l.sort() removedDL = set(l) # Usefull scenario for set peopleWithBlueEyes = {'Hassan', 'Amin', 'Abdihalim', 'Farah', 'Fardowso'} peopleWithBlackHair = {'Hassan', 'Ahmed', 'Geedi', 'Farah', 'Fardowso'} peopleWhoLikeSugar = {'Amin', 'Abdihalim'} peopleWhoLikesalty = {'Amin', 'Hassan', 'Farah', 'Abdihalim'} O_Blood = {'Amin', 'Hassan', 'Farah', 'Abdihalim'} B_Blood = {'Ahmed', 'Omar', 'Geedi', 'Goosab'} # Lets find people with blue eyes or black hair - union blueEyesOrBlackHair = peopleWithBlueEyes.union( peopleWithBlackHair) # returns Hassan, Farah print(blueEyesOrBlackHair) # Lets find people with blue eyes and black hair - intersect blueEyesAndBlackHair = peopleWithBlueEyes.intersection( peopleWithBlackHair) # returns Hassan, Farah print(blueEyesAndBlackHair) # Lets find people with blue eyes and don't have black hair - difference blueEyesAndNotBlackHair = peopleWithBlueEyes.difference( peopleWithBlackHair) # returns Hassan, Farah print(blueEyesAndNotBlackHair) # Lets find people with blue eyes and don't have black hair or vise verse - symmetric_difference blackHairNotBlueEyes = peopleWithBlueEyes.symmetric_difference( peopleWithBlackHair) # returns Hassan, Farah print(blackHairNotBlueEyes) # people with blue eyes like sugar # issubset marunbaa = peopleWhoLikeSugar.issubset(peopleWithBlueEyes) print(marunbaa) # people who like sugar have blue eyes # issuperset marunbaa_mise = peopleWithBlueEyes.issuperset(peopleWhoLikeSugar) print(marunbaa_mise) # to test two sets have no members in common use use isdisjoint O_Blood.isdisjoint(B_Blood) # true
from math import factorial words = "I will watch the match after I take dinner".split() # Modern length = [len(word) for word in words] print(length) # Legacy oldLength = [] for word in words: oldLength.append(len(word)) print(oldLength) # Modern try: f = [len(str(factorial(x))) for x in range(30)] # using list [] print("Unfiltered Result", f) s = {len(str(factorial(x))) for x in range(30)} # using set {} print("filtered Result", s) except TypeError as e: print(e) # Legacy def legacy(): fa = [] for x in range(30): fa.append(len(str(factorial(x)))) print(fa) legacy()
""" Tarea: día anterior Autor: Juan Oablo Rubio Fecha: 07/abr/21 Grupo: ESI-232 Profesor: Jorge A. Zaldívar Carrillo Descripción: Calcula el dia anterior de una fecha dada. """ dia = int(input("Intodusca el numero del día: ")) mes = int(input("Intodusca el numero del mes: ")) año = int(input("Intodusca el numero del año: ")) """dia<1""" if dia == 1: """1,2,4,6,8,9,11""" if mes==1 or mes ==2 or mes==4 or mes==6 or mes==8 or mes==9 or mes==11: dia = 31 mes -= 1 """Febrero, año bisiesto""" if mes ==3 and año%4 == 0: dia = 29 mes -= 1 """3""" if mes ==3: dia = 28 mes -= 1 """5,7,10,11""" if mes==5 or mes ==7 or mes==10 or mes==11: dia = 30 mes -= 1 else: dia = dia-1 if mes <= 0: mes = 12 año = año -1 print(dia) print(mes) print(año)
from enum import Enum from enum import IntEnum class CronType(Enum): """The type of event in cron.""" off = 0 class PowerMode(IntEnum): """Power mode of the light.""" LAST = 0 NORMAL = 1 RGB = 2 HSV = 3 COLOR_FLOW = 4 MOONLIGHT = 5 class BulbType(Enum): """ The bulb's type. This is either `White` (for monochrome bulbs), `Color` (for color bulbs), `WhiteTemp` (for white bulbs with configurable color temperature), `WhiteTempMood` for white bulbs with mood lighting (like the JIAOYUE 650 LED ceiling light), or `Unknown` if the properties have not been fetched yet. """ Unknown = -1 White = 0 Color = 1 WhiteTemp = 2 WhiteTempMood = 3 class LightType(IntEnum): """Type of light to control.""" Main = 0 Ambient = 1 class SceneClass(IntEnum): """ The scene class to use. The scene class (as named in Yeelight docs) specifies how the `Bulb.set_scene` method should act. | `COLOR` changes the light to the specified RGB color and brightness. | `HSV` changes the light to the specified HSV color and brightness. | `CT` changes the light to the specified color temperature. | `CF` starts a color flow. | `AUTO_DELAY_OFF` turns the light on and sets a timer to turn it back off after the given number of minutes. """ COLOR = 0 HSV = 1 CT = 2 CF = 3 AUTO_DELAY_OFF = 4
# Y = c0 + c1x class Line(object): def __init__(self, c0, c1): self.c0, self.c1 = c0, c1 def __call__(self,x): print 'Line', self.c0 + self.c1*x return self.c0 + self.c1*x def table(self, L, R,n): """return a table with n points for L <= x <= R.""" s = '' import numpy as np for x in np.linspace(L, R, n): y = self(x) s += '%12g %12g\n' % (x, y) return s #Parabola Y = c0 + c1x + c2x^2 class Parabola(Line): def __init__(self, c0, c1, c2): Line.__init__(self, c0, c1) self.c2 = c2 def __call__(self,x): print 'Parabola', Line.__call__(self, x) + self.c2*x**2 return Line.__call__(self, x) + self.c2*x**2 #Cubic Y = c3x^3 + c2x^2 + c1x + c0 class Cubic(Parabola): def __init__(self, c0, c1, c2, c3): Parabola.__init__(self, c0, c1, c2) self.c3 = c3 def __call__(self,x): print 'Cubic', Parabola.__call__(self,x) + self.c3*x**3 return Parabola.__call__(self,x) + self.c3*x**3 #Poly4 Y = c4x^4 + c3x^3 + c2x^2 + c1x + c0 class Poly4(Cubic): def __init__(self, c0, c1, c2, c3, c4): Cubic.__init__(self, c0, c1, c2, c3) self.c4 = c4 def __call__(self,x): print 'poly', Cubic.__call__(self,x) + self.c4*x**4 return Cubic.__call__(self,x) + self.c4*x**4 pol = Poly4(1, 1, 2, 2, 10) pol(4) """ Terminal> python Cubic_Poly4.py poly Cubic Parabola Line 5 37 Line 5 165 Parabola Line 5 37 Line 5 2725 Cubic Parabola Line 5 37 Line 5 165 Parabola Line 5 37 Line 5 """
class Line: def __init__(self,p1,p2): self.p1, self.p2 = p1,p2 def value(self): x0, y0 = self.p1[0], self.p1[1] x1, y1 = self.p2[0], self.p2[1] a = (y1 - y0)/float(x1-x0); b = y0*a*x0 return b def test_Line(): comp = Line((1.5,3.4), (4,1.1)).value() expect = -4.692 tol = 1e-15 success = abs(comp - expect) < tol msg = 'it did not go as planned' assert success, msg test_Line() print Line((3, 5.5), (5, 6.5)).value() """ Terminal> python Line.py 8.25 """
#formula: #start with i=1 set i=i+2, repeat until i=n n = 9 odd = 1 print odd while odd < n-1: odd = odd + 2 print odd """ Terminal>python odd.py 1 3 5 7 9 """
import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error, r2_score import matplotlib.pyplot as plt x = 2 - 3 * np.random.normal(0, 1, 100) y = 2 * (x ** 1.5) + np.random.normal(-100, 100, 100) df = pd.DataFrame({'X':x, 'y': y}) df = df.fillna(0) plt.scatter(x, y) plt.show() df = df.sort_values(by=['X']) x_train, y_train = df[['X']], df[['y']] # create a linear regression model and fit the data model = LinearRegression() model.fit(x_train, y_train) y_pred = model.predict(x_train) # printing metrics of the linear model print('The RMSE of the linear regression model is {}'.format(mean_squared_error(y_train, y_pred))) print('The R2 score of the linear regression model is {}'.format(r2_score(y_train, y_pred))) plt.scatter(x_train, y_train, s=10) plt.plot(x_train, y_pred, color='r') plt.show() # transform the features to higher degree for degree in range(2,10): polynomial_features = PolynomialFeatures(degree=degree) x_poly_train = polynomial_features.fit_transform(x_train) # train a polynomial regression model with higher degree features polynomial_model = LinearRegression() polynomial_model.fit(x_poly_train, y_train) y_pred = polynomial_model.predict(x_poly_train) print('The RMSE of the polynomial regression of degree {} is {}'.format(degree,mean_squared_error(y_train, y_pred))) print('The R2 score of the polynomial regression of degree {} is {}'.format(degree, r2_score(y_train, y_pred))) plt.scatter(x_train, y_train) plt.plot(x_train, y_pred, color='r') plt.show() decision_tree_model = DecisionTreeRegressor(max_depth = 10, min_samples_split = 3) decision_tree_model.fit(x_train, y_train) y_pred = decision_tree_model.predict(x_train) print('The RMSE of the Decision Tree regression {}'.format(mean_squared_error(y_train, y_pred))) print('The R2 score of the DecisionTree regression {}'.format(r2_score(y_train, y_pred)))
# Committing changes to github new import math as m print("Calculator Operations\n" "1. Addition\n" "2. Subtraction\n" "3. Multiplication\n" "4. Division\n" "5. Square\n" "6. Square Root\n" "7. Sine\n" "8. Cosine\n" "9. Tangent\n" "10.Log\n" "11.Reciprocal") operationNumber = int(input("Enter the respective number you want to perform operation: ")) if operationNumber > 4: number = float(input("Enter the number: ")) else: number1 = float(input("Enter number1: ")) number2 = float(input("Enter number2: ")) def add(number_1, number_2): return number_1 + number_2 def sub(number_1, number_2): return number_1 - number_2 def multiply(number_1, number_2): return number_1 * number_2 def divide(number_1, number_2): return number_1 / number_2 def square(num): return num ** 2 def square_root(num): return m.sqrt(num) def sine(num): return m.sin((m.pi / 180) * num) def cosine(num): return m.cos((m.pi / 180) * num) def tangent(num): return m.tan((m.pi / 180) * num) def logarithm(num): return m.log10(num) def reciprocal(num): return 1 / num if operationNumber == 1: print(f'Addition of {number1} and {number2} is {add(number1, number2)}') elif operationNumber == 2: print(f'Subtraction of {number1} and {number2} is {sub(number1, number2)}') elif operationNumber == 3: print(f'Multiplication of {number1} and {number2} is {multiply(number1, number2)}') elif operationNumber == 4: print(f'Division of {number1} and {number2} is {divide(number1, number2)}') elif operationNumber == 5: print(f'Square of {number} is {square(number)}') elif operationNumber == 6: print(f'Square Root of {number} is {square_root(number)}') elif operationNumber == 7: print(f'Sine of {number} is {sine(number)}') elif operationNumber == 8: print(f'Cosine of {number} is {cosine(number)}') elif operationNumber == 9: print(f'Tangent of {number} is {tangent(number)}') elif operationNumber == 10: print(f'Logarithm of {number} is {logarithm(number)}') else: print(f'Reciprocal of {number} is {reciprocal(number)}')
# Beginning Python (From Novice to Professional) # Chapter 1 name = input("What is your name?") print("Hello, " + name + "!") # Page 14 input("Press <enter>")
# Section CNN - Convert Images Into Tensors # Author Jose Smith # Start Date: 20210119 # End Date: # Importing the relevant packages print('=============Importing the relevant packages================================') import numpy as np from PIL import Image import datetime # programstart stores current time programstart = datetime.datetime.now() # Define the name of the image file we will use filename = "CNN_with_TensorFlow_in_Python/Dataset/Test_image.jpg" # Load the image as a Python variable # We can manipulate this variable with the Pillow package # Useful image functions: # Image.crop(box=None) - Returns a rectangular region from the image. # Image.filter(filter) - Filters the image using the given filter (kernel) # Image.getbox() - Calculates the bounding box of the non-zero regions in the image. # Image.rotate(angle, ...) - Returns a rotated copy of the image. image = Image.open(filename) # Displays the image contained in the variable through your default photo veiwer print('=============Show the Test Image============================================') image.show() # Resize the image while keeping the aspect ration constant # The 'image' variable is updated with the new image image.thumbnail((90,120)) print('=============Show the Thumbnail=============================================') image.show() # Convert the variable into a NumPy array (tensor) image_array = np.asarray(image) # Check the dimensions of the array # The convention for image arrays is (height x width x channels) # 'channels' refferes to the colors # - 1 for grayscale (only 1 value for each pixel) # - 3 for color images (red, green and blue values/channels) print('=============Show the Tensor Array==========================================') print(np.shape(image_array)) # programend stores current time programend = datetime.datetime.now() roundedstart = programstart - datetime.timedelta(microseconds=programstart.microsecond) roundedend = programend - datetime.timedelta(microseconds=programend.microsecond) print("Program Started:-", roundedstart) print("Program Ended:-", roundedend)
#!/usr/bin/env python # -*- encoding: utf-8 -*- # 插入排序 def insertion_sort(seq): for i in range(1, len(seq)): item = seq[i] for j in range(i)[::-1]: if item < seq[j]: seq[j+1] = seq[j] seq[j] = item else: break return seq if __name__ == '__main__': seq = [5, 2, 4, 6, 1, 3] insertion_sort(seq) print(seq)
numList = (10,23,40,90) print("numList values are : ",numList) for num in numList: if num % 5 == 0: print(num)
# coding: utf-8 # In[1]: import mpl_toolkits.mplot3d as mplt3d import matplotlib.pyplot as plt import scipy.integrate as scint import math import numpy as np #%matplotlib inline # In[ ]: # In[19]: def Getx(nx, xmin, xmax): dx = abs(xmax-xmin)/float(nx) x = np.arange(nx+1)*dx + xmin return x # In[59]: # reduce is not recognized by python 3.5.2 #def fact(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1)) def fact(n):return math.factorial(n) # In[60]: ''' Calculate binomial coefficient nCk = n! / (k! (n-k)!) ''' def binomial(n, k): if n<0 or k<0 or k>n: binom=0 else: binom = fact(n) // fact(k) // fact(n - k) return binom #Print Pascal's triangle to test binomial() def pascal(m): for x in range(m + 1): print([binomial(x, y) for y in range(x + 1)]) # In[61]: def trinomial(n,k): coef = 0 j_l = np.arange(n+1) #print("j_l",j_l) for j in j_l: val1 = binomial(n, j) val2 = binomial(2*n-2*j, n-k-j) coef = coef + (-1)**j * val1 * val2 #print("n = %d, k = %d, j = %d, coef = %d"%(n, k, j, coef)) #print("binomial(n, j) = %d"%val1) #print("binomial(2*n-2*j, n-k-j) = %d"%val2) return coef #Print Trinomial's triangle to test trinomial() def tri_tri(m): for x in range(m + 1): #print("Row %d"%x) #print(range(-x, x+1)) print([trinomial(x, y) for y in range(-x, x+1)]) # In[ ]: # In[ ]: # In[20]: def GetOrd1(x,x0,dx): xi=(x-x0)/dx izeros = np.argwhere(abs(xi) > 1.) ileft = np.argwhere(xi < 0.) iright = np.argwhere(xi >= 0.) shape = np.zeros(len(x)) shape[ileft] = xi[ileft]+1. shape[iright] = 1.-xi[iright] shape[izeros] = 0. return (shape) # In[21]: def GetOrd2(x,x0,dx): xi=(x-x0)/dx iequ1 = np.argwhere( abs(xi) < 0.5 ) iequ2 = np.argwhere( abs(xi) >= 0.5 ) izeros = np.argwhere( abs(xi) > 1.5 ) shape = np.zeros(len(x)) shape[iequ1] = 0.75 - abs(xi[iequ1])**2. shape[iequ2] = 0.5*(1.5 - abs(xi[iequ2]))**2. shape[izeros] = 0. return (shape) # In[22]: def GetOrd3(x,x0,dx): xi=(x-x0)/dx iequ1 = np.argwhere( abs(xi) < 1. ) iequ2 = np.argwhere( abs(xi) >= 1. ) izeros = np.argwhere( abs(xi) > 2. ) shape = np.zeros(len(x)) shape[iequ1] = 0.5*abs(xi[iequ1])**3. - xi[iequ1]**2. + 2./3. shape[iequ2] = 4./3.*(1. - 0.5*abs(xi[iequ2]))**3. shape[izeros] = 0. return (shape) # In[23]: def GetOrd4(x,x0,dx): xi=(x-x0)/dx iequ1 = np.argwhere( abs(xi) < 0.5 ) iequ2 = np.argwhere( abs(xi) >= 0.5 ) iequ3 = np.argwhere( abs(xi) >= 1.5 ) izeros = np.argwhere( abs(xi) > 2.5 ) shape = np.zeros(len(x)) shape[iequ1] = 1./192.*( 115. - 120.*xi[iequ1]**2. + 48.*xi[iequ1]**4. ) shape[iequ2] = 1./96.*( 55. + 20.*abs(xi[iequ2]) - 120.*xi[iequ2]**2. + 80.*abs(xi[iequ2])**3. - 16.*xi[iequ2]**4.) shape[iequ3] = 1./24.*(2.5 - abs(xi[iequ3]))**4. shape[izeros] = 0. return (shape) # In[ ]: # In[25]: bmin = 2. bmax = 6. x = Getx(10000, bmin, bmax) shape = GetOrd2(x, 4., 1.) plt.plot(x,shape) #plt.xlim(bmin, bmax) plt.show() # In[ ]: # In[26]: fig = plt.figure() ax = mplt3d.Axes3D(fig) X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot') plt.show() # In[ ]: # In[9]: X = np.arange(-4, 4, 0.25) print(X) # In[ ]: # In[49]: def GetOrd2_2d(x_vect, y_vect, x0, y0, dx, dy): Xshape = GetOrd2(x_vect, x0, dx).reshape(np.size(x_vect), 1 ) Yshape = GetOrd2(y_vect, y0, dy).reshape(1 , np.size(y_vect)) shape = Xshape * Yshape return (shape) # In[ ]: # In[50]: fig = plt.figure( figsize=(18,10) ) ax = mplt3d.Axes3D(fig) bmin = 2. bmax = 6. order = 2 dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 x0 = 4. y0 = 4. nbcellx = 100 nbcelly = 100 nbx = nbcellx+1 nby = nbcelly+1 x_vect = Getx(nbcellx, bmin, bmax) y_vect = Getx(nbcelly, bmin, bmax) x2, y2 = np.meshgrid(x_vect, y_vect) print(x2.shape) print(y2.shape) #Xshape = GetOrd2(x_vect, x0, dx_L0).reshape(nbx, 1 ) #Yshape = GetOrd2(y_vect, y0, dx_L0).reshape(1 , nby) #shape = Xshape * Yshape shape = GetOrd2_2d(x_vect, y_vect, x0, y0, dx_L0, dx_L0) print(shape.shape) ax.plot_surface(x2, y2, shape, rstride=1, cstride=1, cmap='hot') plt.show(fig) # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[83]: bmin = 2. bmax = 6. nbcellx = 100 nbcelly = 100 order = 2 dx_L0 = 1. dx_L1 = dx_L0/2. RF = dx_L0/dx_L1 x0 = 4. y0 = 4. nbx = nbcellx+1 nby = nbcelly+1 x = Getx(nbcellx, bmin, bmax) y = Getx(nbcelly, bmin, bmax) xm, ym = np.meshgrid(x, y) print(xm.shape) print(ym.shape) shape = GetOrd2_2d(x, y, x0, y0, dx_L0, dx_L0) nt = order+1 # Calcul des coefficients w = np.array([float(binomial(nt, bk)) for bk in range(0, nt+1)]) print(w) w_2d = w.reshape(order+2, 1) * w.reshape(1, order+2) print(w_2d) w_2d[:,:] = w_2d[:,:]/RF**(2*order) print(w_2d) wtot = np.sum(w) print("wtot = %.2f"%wtot) nbpts = int( (2*RF - 1) + (RF-1)*(order-1) ) print("nbpts = %d"%nbpts) ik_l = np.arange(nbpts) print(ik_l) jk_l = np.arange(nbpts) print(jk_l) iNew_l = np.arange(nbpts**2) nb_2d = nbpts**2 print("nb_2d = %d"%nb_2d) xvec = np.array( np.zeros(nbpts) ) yvec = np.array( np.zeros(nbpts) ) ix = -(nbpts-1)/2. for ik in ik_l: xvec[ik] = x0 + ix*dx_L1 yvec[ik] = y0 + ix*dx_L1 ix = ix + 1. print(xvec) print(yvec) split_tab = np.zeros((nb_2d, len(x), len(y))) shape_split = np.zeros((len(x), len(y))) iNew = 0 for ik in ik_l: for jk in jk_l: #shape_split[:, :] = shape_split[:,:] + w_2d[ik,jk]*GetOrd2_2d(x, y, xvec[ik], yvec[jk], dx_L1, dx_L1) split_tab[iNew, :, :] = w_2d[ik,jk]*GetOrd2_2d(x, y, xvec[ik], yvec[jk], dx_L1, dx_L1) shape_split[:, :] = shape_split[:,:] + split_tab[iNew, :, :] iNew = iNew+1 #split_tab[ik, :, :] = w_2d[ik,jk]*GetOrd2_2d(x, y, xvec[ik], yvec[ik], dx_L1, dx_L1) delta_shape = np.zeros((len(x), len(y))) delta_shape[:, :] = shape[:, :] - shape_split[:, :] fig = plt.figure( figsize=(16,10) ) ax = mplt3d.Axes3D(fig) ax.plot_surface(xm, ym, shape, rstride=1, cstride=1, cmap='hot') fig = plt.figure( figsize=(16,10) ) ax = mplt3d.Axes3D(fig) ax.plot_surface(xm, ym, delta_shape, rstride=1, cstride=1, cmap='hot') #i2d_l = np.arange(nb_2d) #print(i2d_l) #fig = plt.figure( figsize=(18,10) ) #for i2d in i2d_l: ## fig = plt.figure( figsize=(18,10) ) # ax = mplt3d.Axes3D(fig) # ax.plot_surface(xm, ym, split_tab[i2d, :, :], rstride=1, cstride=1, cmap='hot') # #plt.show() # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
#assign some boolean variables a=True b=False print('a=',a,'b=',b) #reassign a a=False print('a=',a,'b=',b)
#Get diividend and divisor from user dividend,divisor=eval(input('Please enter the dividend and divisor: ')) #we want to divide only if divisor is not zero #otherwise, we will print an error message msg=dividend/divisor if divisor!=0 else 'Error: Cannot divide by zero ' print(msg)
import numpy as np from matplotlib import pyplot as plt import random import math ##### Parameters C = 2 N1,N2 = 3,C randomWeightsRange = 1 alpha = 0.1 ##### ## Setting the random seed for testing purposes random.seed(6) ## This lets 2/3 neurons in the hidden layer have non-zero values after relu activation ## Debugging print functionality myDebug = True def show(*T): if (myDebug): for o in list(T): print o, print ## Neural Network functions def gfunction(x): return x if x > 0 else 0 def gMfunction(X): fvectorized = np.vectorize(gfunction,otypes=[np.float]) return fvectorized(X) def ggradfunction(x): return 1 if x > 0 else 0 def ggradMfunction(X): fvectorized = np.vectorize(ggradfunction,otypes=[np.float]) return fvectorized(X) def gSoftmaxfunction(x,Sum): return (math.exp(x)/Sum) def gMSoftmaxfunction(X): expVectorized = np.vectorize(math.exp,otypes=[np.float]) expX = expVectorized(X) Sum = np.sum(expX) fvectorized = np.vectorize(gSoftmaxfunction,otypes=[np.float]) return fvectorized(X,Sum) def innerInitializeWeights(W): size = W.shape for i in range(size[0]): for j in range(size[1]): W[i,j] = random.uniform(-randomWeightsRange,randomWeightsRange) def initializeWeights(W): for i in range(len(W)): innerInitializeWeights(W[i]) return # target activation is a class from 1 to C def crossEntropyLoss(finalActivations,targetActivation): oneHot = [] for i in range(1,C+1): if (targetActivation == i): oneHot.append(1) else: oneHot.append(0) loss = -math.log(np.dot(oneHot,finalActivations)) return loss,oneHot def batchUpdate(myImages,myLabels,Activations,Weights,alpha): W0 = [] W1 = [] finalWeights = [W0, W1] for i in range(len(myImages)): # Calculate the loss Loss,oneHot = crossEntropyLoss(Activations[2],myLabels[i]) E = [] a0Shape = int(Activations[0].shape[0]) activations0 = np.reshape(Activations[0],(a0Shape, 1)) a1Shape = int(Activations[1].shape[0]) activations1 = np.reshape(Activations[1],(a1Shape, 1)) a2Shape = int(Activations[2].shape[0]) activations2 = np.reshape(Activations[2],(a2Shape, 1)) for j in range(len(Activations[2])): if (oneHot[j] == 1): E.append(-math.log(Activations[2][j])) else: E.append(-math.log(1-Activations[2][j])) outputDeltas = [] for j in range(len(Activations[2])): print(oneHot[j],Activations[2][j]) outputDeltas.append(oneHot[j] - Activations[2][j]) outputDeltas = np.reshape(np.asarray(outputDeltas),(len(outputDeltas),1)) WeightUpdatesHidden = np.copy(Weights[1]) # second set of weights size = WeightUpdatesHidden.shape WeightUpdatesHidden = activations1.dot(outputDeltas.transpose()) # weightupdateshidden is deltas multiplied by the weights, just multiply with gradients and activations now # define the hidden deltas WeightUpdatesInput = np.copy(Weights[0]) # second set of weights size = WeightUpdatesInput.shape WeightUpdatesTemp = Weights[1].dot(outputDeltas) WeightUpdatesTemp = np.delete(WeightUpdatesTemp,3,0) # hardcoded 3 !!!! ALERT derivatives = ggradMfunction(activations1) derivatives = np.delete(derivatives,3,0) temp = np.multiply(WeightUpdatesTemp,derivatives) WeightUpdatesInput = activations0.dot(temp.transpose()) print temp # remove last bias term from outputDeltas if (i == 0): # zeros for this finalWeights[0] = np.zeros(Weights[0].shape) finalWeights[0] = np.add(finalWeights[0],WeightUpdatesInput) finalWeights[1] = np.zeros(Weights[1].shape) finalWeights[1] = np.add(finalWeights[1],WeightUpdatesHidden) else: finalWeights[0] = np.add(WeightUpdatesInput,finalWeights[0]) finalWeights[1] = np.add(WeightUpdatesHidden,finalWeights[1]) print "Initial Weights",Weights print "my updated weights",finalWeights m = -0.99 updatedWeight = np.subtract(Weights,np.multiply(finalWeights,m)) print updatedWeight return updatedWeight ##### def showWeight(W): size = W.shape newImage = np.empty([size[0],size[1],3],np.float64) difference = W.max() - W.min() if difference == 0: return for i in range(0,size[0]): for j in range(0,size[1]): a = ((W[i,j]-W.min())*255)/255 r,g,b = a,random.randint(0,255),a newImage[i,j] = r,g,b plt.imshow(newImage, interpolation="nearest") plt.xlim([0,size[0]]) plt.show() ##### def activateNetwork(input,W): Act1 = gMfunction(np.dot(input,W[0])) ##### adding the bias term to the activation Act1 = np.append(Act1,gfunction(1)) Act2 = np.dot(Act1,W[1]) Act2 = gMSoftmaxfunction(Act2) return input,Act1,Act2 ##### print("A neural net implementation for the Deep Learning class by Fuxin Lee, by Viktor Milleghere (D.T.)") h, w = 2, 2 myImage = np.empty([h, w, 3], dtype = np.float64) for i in range(0,h): for j in range(0,w): r,g,b = [random.uniform(0,1),random.uniform(0,1),random.uniform(0,1)] myImage[i,j] = r,g,b # plt.imshow(myImage, interpolation='nearest') # plt.show() ##### Network initialization # ----weights include the bias weights Win = np.empty([(h*w*3+1),N1], dtype = np.float64) Wout = np.empty([N1+1,N2], dtype = np.float64) Weights = [Win,Wout] initializeWeights(Weights) ##### add bias term myImageFlattened = myImage.flatten() myImageFlattened = np.append(myImageFlattened,(1)) Activations = activateNetwork(myImageFlattened,Weights) show("Network Activations ---v") show("Activations[0] ---v\n",Activations[0]) show("Activations[1] ---v\n",Activations[1]) show("Activations[2] ---v\n",Activations[2]) ##### Backpropagation batchSize = 1 myImages = [] myLabels = [] for i in range(batchSize): myImages.append(myImage) myLabels.append(random.randint(1,C)) newWeights = batchUpdate(myImages,myLabels,Activations,Weights,alpha) Activations = activateNetwork(myImageFlattened,newWeights) show("Network Activations ---v") show("Activations[0] ---v\n",Activations[0]) show("Activations[1] ---v\n",Activations[1]) show("Activations[2] ---v\n",Activations[2])
#!/usr/bin/env python3 set = [5, 2, 4, 6, 1, 3] for j in range(1, len(set)): key = set[j] i = j - 1 while (i >= 0 and set[i] > key): set[i+1] = set[i] i = i - 1 set[i+1] = key print(set)
n =str(input("Digite seu nome: ")) s = str(input("Digite sua senha: ")) while n==s: print("Senha inválida") n =str(input("Digite seu nome: ")) s = str(input("Digite sua senha: ")) print("Obrigado")
#!/bin/usr/env python # MIT by Vitali # Prints count of substring occurrences in a string s = raw_input() start=0 count=0 while start<=len(s): n=s.find('b',start,len(s)) prnt=(s[start:start+3]) if prnt =='bob': start=n+2 count+=1 else: start+=1 print "Number of times bob occurs is:", count
num1 = float(input("Ingrese el primer número: ")) operacion = input("Ingrese la operación matemática a realizar: ") num2 = float(input("Ingrese el segundo número: ")) # Suma, Resta, Multiplicación, División if operacion == "+": print(num1 + num2) elif operacion == "-": print(num1 - num2) elif operacion == "*": print(num1 * num2) elif operacion == "/": print(num1 / num2)
from sklearn.model_selection import GridSearchCV, StratifiedKFold, \ RandomizedSearchCV class ModelTunerCV: def __init__(self, model, scorer, cv=3): """ Args: model: sklearn model, Model the user wishes to tune scorer: string or valid scorer, The scoring method to be used for finding the optimal hyperparameters. For more information on what makes a valid scorer, see https://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter cv: int, number of folds in cross validation """ self.model = model self.scorer = scorer self.cv = cv # Setting the defaults for values the user will want to see and access self.best_params_ = {} self.best_score_ = 0.0 def tune(self, X, y, param_grid, method='grid', n_iter=10): """Tunes the model to the supplied data using the given method and parameters The model is tuned utilizing cross validation rather than train-test splitting Args: X: Dataframe, Data for the model to be tuned with y: Series, Target values for supervised learning models param_grid: dict, keys are hyperparameters and values are the values that the user wants to compare. Note that they need to be valid for the model being used as well as the method to tune the model. For example, RandomizedCV requires distributions to randomly choose values from. method: string, method to perform the tuning n_iter: int, number of trials performed by random cv, only matters when method is 'random' Returns: Nothing, but self.best_params_ and self.best_score_ are set by this method. self.best_params_ is a dict that holds which values were the best for a given hyperparameter. self.best_score_ is the best average score from the cross validation performed. """ method_options = ['grid', 'random'] if method not in method_options: msg = f"method must be one of {method_options} "\ f"{method} was given" raise ValueError(msg) if method == method_options[0]: self.best_params_, self.best_score_ = self.tune_grid(X, y, param_grid) elif method == method_options[1]: self.best_params_, self.best_score_ = self.tune_random(X, y, \ param_grid, n_iter) def tune_grid(self, X, y, param_grid): """Tunes the model to the supplied data using grid search Args: X: Dataframe, Data for the model to be tuned with y: Series, Target values for supervised learning models param_grid: dict, keys are hyperparameters and values are the values that the user wants to compare Returns: best_params: dict, key is hyperparameter value is the value for the hyperparameter which performed best best_score: float, The best average score achieved from the given hyperparameter grid """ # Ensuring classes are balanced in the kfold cross-validation kfold = StratifiedKFold(n_splits=self.cv, shuffle=True, random_state=44) try: grid = GridSearchCV(estimator=self.model, param_grid=param_grid, scoring=self.scorer, cv=kfold, iid=False, n_jobs=-1) except ValueError as e: msg = e + f" The given values were {grid.get_params()}" raise ValueError(msg) grid.fit(X, y) best_params, best_score = grid.best_params_, grid.best_score_ return best_params, best_score def tune_random(self, X, y, param_dist, n_iter): """Tunes the model to the supplied data using randomized search Args: X: Dataframe, Data for the model to be tuned with y: Series, Target values for supervised learning models param_dist: dict, keys are hyperparameters and values are the distributions the user wants to randomly choose values from n_iter: int, number of trials performed in the cross-validation Returns: best_params: dict, key is hyperparameter value is the value for the hyperparameter which performed best best_score: float, The best average score achieved from the given hyperparameter distributions """ # Ensuring classes are balanced in the kfold cross-validation kfold = StratifiedKFold(n_splits=self.cv, shuffle=True, random_state=44) try: random = RandomizedSearchCV(estimator=self.model, param_distributions=param_dist, random_state=44, iid=True, cv=kfold, n_jobs=-1, n_iter=n_iter, scoring=self.scorer ) except ValueError as e: msg = e + f" The given values were {random.get_params()}" raise ValueError(msg) random.fit(X, y) best_params, best_score = random.best_params_, random.best_score_ return best_params, best_score
# 获取mnist数据集 import matplotlib.pyplot as plt from keras.datasets import mnist (train_x, train_y), (test_x, test_y) = mnist.load_data() print(train_x.shape, train_y.shape) print(test_x.shape, test_y.shape) # 可视化数据集 fig = plt.figure() for i in range(15): plt.subplot(3, 5, i+1) plt.tight_layout() plt.imshow(train_x[i], cmap='Greys') plt.title('label:{}'.format(train_y[i])) plt.xticks([]) plt.yticks([]) plt.show()
""" General drawing methods for graphs using Bokeh. """ import math from bokeh.io import show, output_file from bokeh.plotting import figure from bokeh.models import (GraphRenderer, StaticLayoutProvider, Circle, Oval, LabelSet, ColumnDataSource) from bokeh.palettes import Spectral8 from graph import Graph class BokehGraph: """Class that takes a graph and exposes drawing methods.""" def __init__(self, graph): self.graph = graph #should be a object. instance of Graph def show(self): N = len(self.graph.vertices.keys()) #length of vertices node_indices = list(range(N)) plot = figure(title="Graph of Nodes and Edges", x_range=(-1.1,1.1), y_range=(-1.1,1.1), tools='', toolbar_location=None) graph = GraphRenderer() graph.node_renderer.data_source.add(node_indices, 'index') graph.node_renderer.data_source.add(Spectral8, 'color') graph.node_renderer.glyph = Oval(height=0.1, width=0.2, fill_color='color') graph.edge_renderer.data_source.data = dict( start=[0]*N, end=node_indices ) circ =[i*2*math.pi/len(self.graph.vertices.keys()) for i in node_indices] x = [math.cos(i) for i in circ] y = [math.sin(i) for i in circ] graph_layout = dict(zip(node_indices, zip(x,y))) graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) plot.renderers.append(graph) output_file('graph.html') show(plot) test = Graph() vertex_one = test.add_vertex("0") vertex_two = test.add_vertex("1") vertex_three = test.add_vertex("2") test.add_edge_two_way(vertex_one, vertex_two) test.add_edge_two_way(vertex_two, vertex_three) test_Bokeh = BokehGraph(test) test_Bokeh.show()
# f1 = open("test.txt", 'w') # # f1.write("Life is too short") # # f1.close() # # f2 = open("test.txt", 'r') # # print(f2.readline()) # f1 = open("test.txt", 'a') # str= input("저장할 내용을 입력하세요.:") #, end=' ' # f1.write(str) # f1.write("\n") # f1.close() # # f = open("새파일.txt", 'r') # while True: # line = f.readline() # if not line: break # print(line) # f.close() # f = open('새파일.txt', 'r') # body = f.read() # f.close() # print(body) # # body = body.replace('java', 'python') # print(body) # f = open('test.txt', 'w') # f.write(body) # f.close() class Calculator: def __init__(self): self.result = 0 def add(self, num): self.result += num return self.result cal1 = Calculator() cal2 = Calculator() print(cal1.add(3)) print(cal1.add(4)) print(cal2.add(3)) print(cal2.add(7)) # 클래스에의해 생성된 객체들은 서로에게 전혀 영향을 주지 않는다. # # ※ pass는 아무것도 수행하지 않는 문법이다. 임시로 코드를 작성할 때 주로 사용한다. # ※ 메서드의 첫번째 매개변수를 self를 명시적으로 구현해야 하는 것은 파이썬만의 독특한 특징이다. 예를들어 자바같은 언어는 첫번째 매개변수인 self가 필요없다. # ※ 객체변수는 속성, 멤버변수 또는 인스턴스 변수라고도 표현한다. class FourCal: def __init__(self, first, second): self.first = first self.second = second def setdata(self, first, second): self.first = first self.second = second def add(self): result = self.first + self.second return result def mul(self): result = self.first * self.second return result def sub(self): result = self.first - self.second return result def div(self): result = self.first / self.second return result class MoreFourCal(FourCal): pass a= MoreFourCal(4,2) print(a.add()) print(a.mul()) # a = FourCal(4,0) # a.div() class SafeFourCal(FourCal): def div(self): if self.second ==0: return 0 else: return self.first / self.second a= SafeFourCal(4,0) print(a.div())
class Solution: def isValid(self, s: str) -> bool: paren_list = list() for i in range(len(s)): if s[i] == '(' or s[i] == '{' or s[i] == '[': paren_list.append(s[i]) elif (len(paren_list) != 0): if s[i] == ')' and paren_list[len(paren_list)-1] == '(': paren_list.pop() elif s[i] == '}' and paren_list[len(paren_list)-1] == '{': paren_list.pop() elif s[i] == ']' and paren_list[len(paren_list)-1] == '[': paren_list.pop() else: return False else: return False return len(paren_list) == 0
def Largest(A, low_index, high_index): if(len(A)==0): return 0 max = 0 if(low_index == high_index): return A[low_index] else: max = Largest(A, low_index +1, high_index) if A[low_index] >= max: return A[low_index] else: return max lista = [1,6,7,2,8,10] print(Largest(lista, 0, len(lista)-1))
class Num: def __init__(self, value): self.value = value def eval(self): return int(self.value) class MulStr: def __init__(self, value): self.value = value def eval(self): return self.value * 5
#!/user/bin/python #Accept two list from user and return the intersection of them def intersectionTwoList(L1,L2): L3=[] i=0 j=0 while i<len(L1): while j<len(L2): if L1[i]==L2[j]: if L1[i] not in L3: L3.append(L1[i]) j+=1 if i>=len(L1) and j>=len(L2): break i+=1 j=0 return L3 def main(): L1=eval(input("Enter the First list:")) L2=eval(input("Enter the Second list:")) intersection=intersectionTwoList(L1,L2) print (intersection) if __name__=='__main__': main()
#! /usr/bin/python def CountBit(no): count=0 x=1 while x<=no: if (no & x)!=0: count +=1 x=x<<1 return count def main(): no=eval(input("Enter Number to count number of Bits:")) output=CountBit(no) print("{} Number of one bits in {}" .format(output,no)) if __name__=="__main__": main()
#!/user/bin/python #Pattern 5: # * # *** # ***** #******* #******* # ***** # *** # * def pattern5(no): for i in range(1,no+1): for j in range (1,no-i+1): print('\t',end='') for k in range (1,i+1): print ('*\t',end='') for l in range (1,i): print ('*\t',end='') print ("\n") for i in range(1,no+1): for j in range (1,i): print('\t',end='') for k in range (1,no-i+2): print ('*\t',end='') for l in range (1,no-i+1): print ('*\t',end='') print ("\n") def main(): no=eval(input("Enter Number to for pattern5:")) pattern5(no) if __name__=='__main__': main()
#!/user/bin/python #WAP :Accept number from user and define a function Sum of cubes of digit def sumOfCubes (no): sum=0 while no!=0: rem=no%10 sum=(rem*rem*rem)+sum no=no//10 print(sum) def main(): no=eval(input("Enter Number to obtain Sum of cubes of digit:")) sumOfCubes(no) if __name__=='__main__': main()
#!/user/bin/python # Program: Print below pattern # * # ** # *** # **** def pattern1(no): for i in range(1,no+1): for j in range(1,i+1): print ('*\t',end='') print ("\n") def main(): no=eval(input("Enter Number to for pattern1:")) pattern1(no) if __name__=='__main__': main()
#!/user/bin/python def variableArgsAdd(*args): sum=0 print(type(args)) for x in args: sum+=x print(sum) variableArgsAdd(10,20,30,40,50,60,70) variableArgsAdd(1,2,3,4,5,6,7,8)
#!/user/bin/python def CompareTwoList(L1,L2): if type(L1)!= list or type(L2) != list: print ("L1 is not list") return if len(L1)!=len(L2): return 0 L1.sort();L2.sort() for i in range(len(L1)): if L1[i]==L2[i]: continue break else: print("Both List are same") return 0 def main(): L1=[eval(input("Enter the First list:"))] L2=[eval(input("Enter the First list:"))] CompareTwoList(L1,L2) if __name__=='__main__': main()
import numpy as np import random # Times to run epoch = 10000 # There are 2 inputs inputLayerSize = 2 # NN nodes hiddenLayerSize = 3 # Only one output outputLayerSize = 1 # Learning rate L = 0.1 # There are 2 inputs for XOR X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # The truth table of XOR # ANN just can learn from truly examples!!! # (adjust the weight and bias to make output is getting close to target by input) Y = np.array([[0], [1], [1], [0]]) def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_deriv(x): return x * (1 - x) Wh = np.random.uniform(size=(inputLayerSize, hiddenLayerSize)) Wz = np.random.uniform(size=(hiddenLayerSize, outputLayerSize)) for i in range(epoch): H = sigmoid(np.dot(X, Wh)) Z = np.dot(H, Wz) E = Y - Z dZ = E * L Wz += H.T.dot(dZ) dH = dZ.dot(Wz.T) * sigmoid_deriv(H) Wh += X.T.dot(dH) print("**************** error ****************") print(E) print("***************** output **************") print(Z) print("*************** weights ***************") print("input to hidden layer weights: ") print(Wh) print("hidden to output layer weights: ") print(Wz) # Test fail = 0 for i in range(0,100): x1 = random.randint(0,1) x2 = random.randint(0,1) y_ground_truth = x1 ^ x2 y_predict = np.dot(sigmoid(np.dot(np.array([x1, x2]), Wh)), Wz)[0] y_predict_round = round(y_predict) print('ground truth:', y_ground_truth, 'predict:', y_predict, 'round:', y_predict_round) if y_ground_truth != y_predict_round: fail += 1 print('fail rate:', fail, '/100')
#4. Create a list of thousand number using range and xrange and see the difference between each other. """ x-range is used on python 2 which shows the whole result as type list where as range # is used on python 3 which does not show the whole result and type is range """
# 5. Write a program to complete the task given below: # Ask the user to enter any 2 numbers in between 1-10 and add both of them to another variable call z. # Use z for adding 30 into it and print the final result by using variable result. x = int (input("Enter 1st number between 1 to 10: ")) y = int (input("Enter 2nd number between 1 to 10: ")) z = x+y if(0 < x <= 10 and 0 < y <= 10): total = z+30 print("Grand Total(z+30)= "+str(total)) else: print("Enter the proper number between 1 to 10.")
# 8 If one data type value is assigned to ‘a’ variable and then a different data type value is assigned to ‘a’ again. #Will it change the value. If Yes then Why? #Value will change assigned to “a” even if they are a different data type because python automatically takes # care of the physical representation for the different types of data i.e an integer values will be stored in different # memory locations than a float or a string.
# 6 What is the output of the following code examples? x=123 for i in x: print(i) #int obj is not iterable(error) i = 0 while i < 5: print(i) i += 1 if i == 3: break else: print('error') #output: 0,1,2 count = 0 while True: print(count) count += 1 if count >= 5: Break #output: 0,1,2,3,4
# Assignment-1 # TASK ONE: NUMBERS AND VARIABLES # 1.Create three variables in a single line and assign different values to them and # make sure their data types are different. Like one is int, another one is float and the last one is a string. a, b, c = 10, 15.5, 'Welcome to Consult add'
veta = "Cez vikend je planovana odstavka tunela pod hradom".split() print(f'Veta pozostava z {len(veta)} slov.') nova_veta = "" for slovo in veta: nova_veta += slovo[0].upper() + slovo[1:] print(nova_veta) uplne_nova_veta = "" for pismeno in nova_veta: if pismeno.isupper(): uplne_nova_veta += ' ' uplne_nova_veta += pismeno.upper() print(uplne_nova_veta[1:])
rawdata = [] required_fields = ["byr","iyr","eyr","hgt","hcl","ecl","pid"] with open("input.txt","r") as file: num = 1 rawdata = file.read().split("\n\n") #print(rawdata) def valid(item): for field in required_fields: if field not in item: return False return True print(rawdata) is_valid = 0 for item in rawdata: if valid(item): is_valid += 1 print(is_valid)
import re def get_policy_info(key): dash = key.find("-") minimum = int(key[:dash]) maximum = int(key[dash+1:-2]) char = key[-1] return [minimum,maximum,char] def meets_policy(value,minimum,maximum,char): if len(re.findall(char,value)) >= minimum and len(re.findall(char,value)) <= maximum: return True else: return False count = 0 with open("input.txt","r") as file: for line in file.readlines(): split = line.split(":") modified_val = split[1][1:] info = get_policy_info(split[0]) if meets_policy(modified_val,info[0],info[1],info[2]): count += 1 else: continue print(count) file.close()
#1. Write a program in Python to perform the following operation: # If a number is divisible by 3 it should print “Consultadd” as a string # If a number is divisible by 5 it should print “Python Training” as a string # If a number is divisible by both 3 and 5 it should print “Consultadd Python Training” as a string. x=33 if x%5==0 and x%3==0: print("Consultadd Python Training") elif x%3==0: print("Consultdd") elif x%5==0: print("Python Training") else: pass #2. Write a program in Python to perform the following operator based task: _operator = int(input(" Enter 1 for Addition \n Enter 2 for Subtraction \n Enter 3 for Division \n Enter 4 for Multiplacation \n Enter 5 for Average:\n")) if 0 < _operator < 5: print("0<operator<5") _first=int(input("Enter first number: ")) _second=int(input("Enter second number: ")) if _operator == 1: if _first+_second <0: print("Oops option 1 is returning the negative number", _first+_second) else: print(_first+_second) elif _operator == 2: if _first-_second <0: print("Oops option 2 is returning the negative number", _first-_second) else: print(_first-_second) elif _operator == 3: if _first/_second <0: print("Oops option 3 is returning the negative number", _first/_second) else: print(_first/_second) elif _operator == 4: if _first*_second <0: print("Oops option 4 is returning the negative number", _first*_second) else: print(_first*_second) else: print("Something wrong with 0<opeartor<5 part of if statement" ) elif _operator == 5: print("operator = 5") _first=int(input("Enter first number: ")) _second=int(input("Enter second number: ")) _first2=int(input("Enter third number: ")) _second2=int(input("Enter forth number: ")) if (_first+_second+_first2+_second2)/4 <0: print("Oops option 5 is returning the negative number", (_first+_second+_first2+_second2)/4) else: print((_first+_second+_first2+_second2)/4) else: print("Enter valid number") #3.Write a program in Python to implement the given flowchart: a,b,c = 10,20,30 avg=(a+b+c)/3 print("avg: ", avg) if avg>a and avg>b and avg>c: print("avg is higher than a,b,c") elif avg>a and avg>b: print("avg is higher than a,b") elif avg>a and avg>c: print("avg is higher than a,c") elif avg>b and avg>c: print("avg is higher than b,c") elif avg>a: print("avg is just bigger than a") elif avg>b: print("avg is just higher than b") elif avg>c: print("avg is just higher than c") else: print("a,b,c less than avg ") #4.Write a program in Python to break and continue if the following cases occurs: #If user enters a negative number just break the loop and print “It’s Over” #If user enters a positive number just continue in the loop and print “Good Going” while True: _entered = int(input("Enter either negative or positive number:")) #print(_entered) if _entered<0: break elif _entered>0: print("Good Going") continue print("It's over") #5. Write a program in Python which will find all such numbers which are divisible # by 7 but are not a multiple of 5, between 2000 and 3200. _list=[] for i in range(2000,3200): if i%7==0 and i%5!=0: _list.append(i) else: continue print(_list) #6.What is the output of the following code examples? def check_output(): #6.1 FIXED ONE x=123 for i in range(100,x,2): print("First output: ", i) #6.1 ERROR # x=123 # for i in x: # print(i) #6.2 FIXED ONE i = 0 while i < 5: print(i) i += 1 if i == 3: break else: print("Second output:","error") #6.2 HAVE ERRORS: """ i = 0 while i < 5: print(i) i += 1 if i == 3: break else: print(“error”) """ #6.3 FIXED count = 0 while True: print("Third output",count) count += 1 if count >= 5: break #6.3 HAVE ERROR """ count = 0 while True: print(count) count += 1 if count >= 5: Break """ check_output() #abive check code, fix errors, however answer for question no:6 is below:----> # Answers for question: 6.1 :TypeError: 'int' object is not iterable # 6.2 AS I SEE THERE IS TWO ERROR: # 6.2.1 # print(“error”) # ^ #SyntaxError: invalid character in identifier #6.2.2 INDENTATION ERRROR: ELSE BLOCK HAVE TO INDENTED # #6.3 NameError: name 'Break' is not defined #7. Write a program that prints all the numbers from 0 to 6 except 3 and 6. # Expected output: 0 1 2 4 5 # Note: Use ‘continue’ statement for i in range(6): if i!=3: print(i) continue #8. Write a program that accepts a string as an input from user and # calculate the number of digits and letters. _input = input("Enter Leter and number: ") _digit_count=0 _letter_count=0 for i in _input: if i.isnumeric(): _digit_count+=1 elif i.isalpha(): _letter_count+=1 else: continue print(" Letter: ", _letter_count, " and Digits:", _digit_count) # 9. Read the two parts of the question below: # 9.1 Write a program such that it asks users to “guess the lucky number”. # If the correct number is guessed the program stops, otherwise it continues forever. # 9.2 Modify the program so that it asks users whether they want to guess again each time. # Use two variables, ‘number’ for the number and ‘answer’ for the answer to the question # whether they want to continue guessing. The program stops if the user guesses the correct # number or answers “no”. ( The program continues as long as a user has not answered “no” and # has not guessed the correct number) import random def guess_number(): _number=random.randint(0,20) print(_number) while True: _answer=input("Guess the lucky number-Enter number between 0 to 20:") if _answer.isdigit and int(_answer)==_number: print(" Congratulation!!! You find the number") break elif _answer.isdigit and int(_answer)!=_number: _answer = input("No rigth! like to play again: Yes/No: ") if _answer.capitalize()=="Yes": continue elif _answer.capitalize()=="No": break else: print("Sorry do not caght it!!") continue else: break guess_number() #10 and 11. Write a program that asks five times to guess the lucky number. # Use a while loop and a counter, such as def five_guess(): _count = 1 _number=random.randint(0,20) print("random number:", _number) while _count <= 5: _answer=int(input("Guess the lucky number-Enter number between 0 to 20:")) _count+=1 print("guess count",_count) if _answer==_number: print("Good Guess") break elif _answer != _number and _count!=6: print("Try again") else: print("Sorry but that was not very successful. It's over!!!") print("Here starts five_guess------ ") five_guess()
##############WEEKEND ACTIVITY- THEORETICAL JOURNEY######################################## # 1.What is Pickling and Unpickling in Python? Explain with the help of example. ### pickling and unpickling powerful algorithm for serializing and de-serializing a # Python object structure. dict_obj = {1:"Serdar", 2:"Riyaz",3:"Durbayev", 4:"John"} import pickle with open("pickle_dic.pickle","wb") as f: pickle.dump(dict_obj,f) print(dict_obj) del dict_obj #print(dict_obj) with open("pickle_dic.pickle","rb") as f: dict_obj=pickle.load(f) print("Deserialized dictionary:", dict_obj ) # 2.How Memory Management is achieved in Python? Explain with the help of example. #Fistly, memory management is handling by interprter itself in python. no programmer need do nothing about it. #in Python two momery type or kind- stack memory and heep memory- stack memory is where all functions run, # also where referance veriable names sit and the other hand heap memory is where actuall data stored and keep untill # their reference count to be zero when it happens periodically garbage collector come place and free the memory #from that unused data. #when programmer create x variable and assign to it interger 10 #in heap memory alocatated place for inerger 10, in stack portion of memory be placed x reference variable name # that references to number 10, reference counter now is one. if programmer create varriable y and assign to it # number 10( a same interger with x) and reference counter become two(2) # when programmer assigns y and x a number integer 12, so now the data integer 10 reference counter is zero #so garbage collerter come and freed 10's memory place and delete 10 # 3.Write a Program In Python to explain Multithreading in Python. # 4.What are the Collection in Python. Explain following terms with Example. #Collections in Python are containers that are used to store collections of data, # for example, list, dict, set, tuple etc. These are built-in collections. # Several modules have been developed that provide additional data structures to store collections of data. # One such module is the Python collections module. #4.1 namedtuple() #Python supports a type of container like dictionaries called “namedtuples()” present in module, “collection“. #Like dictionaries they contain keys that are hashed to a particular value. But on contrary, #it supports both access from key value and iteration, #the functionality that dictionaries lack. #4.2 Counter() #A counter tool is provided to support convenient and rapid tallies. For example: from collections import Counter cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: cnt[word] += 1 print(cnt) #4.3 OrderedDict #An OrderedDict is a dictionary subclass that remembers the order in which its contents are added. #import collections #from collections import OrederedDict #An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. # The only difference between dict() and OrderedDict() is that: #OrderedDict preserves the order in which the keys are inserted. #A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. #By contrast, the order the items are inserted is remembered by OrderedDict. #4.4 ChainMap #ChainMap is used to combine several dictionaries or mappings. It returns a list of dictionaries. from collections import ChainMap dict1 = { 'a' : 1, 'b' : 2 } dict2 = { 'c' : 3, 'b' : 4 } chain_map = ChainMap(dict1, dict2) print(chain_map.maps) #4.5 deque #The deque is a list optimized for inserting and removing items. from collections import deque list = ["a","b","c"] deq = deque(list) print(deq) deq.append("d") deq.appendleft("e") print(deq) c="abcabcacbadscd" print(deque(c)) # NOTE: Make sure to write at least one program on each and comment what each line of the code is doing. # 5. Learn about PEP8 - How to write beautiful Python Code? # 6. Difference between the pip, virtualenv, conda? #In short, pip is a general-purpose manager for Python packages; # conda is a language-agnostic cross-platform environment manager. # For the user, the most salient distinction is probably this: # pip installs python packages within any environment; # conda installs any package within conda environments ####################WEEKEND ACTIVITY- GITHUB TASK#################################################### # (https://drive.google.com/file/d/1E8MY1ML_SsYDmN_MFwAgbApur_1OqqLQ/view?usp=sharing) # 1.What is Version Control System and their types of tools available mentioned any top 5?. #A version control system allows users to keep track of the changes in software development projects, #and enable them to collaborate on those projects. #Using it, the developers can work together on code and separate their tasks through branches. #1. GitHub # GitHub helps software teams to collaborate and maintain the entire history of code changes. # You can track changes in code, turn back the clock to undo errors and share your efforts with other team members. # It is a repository to host Git projects. # For those wondering what is Git? It is an open source version control system that features local branching, # multiple workflows, and convenient staging areas. Git version control is an easy to learn option and offers # faster operation speed. # 2. GitLab # GitLab comes with a lot of handy features like an integrated project, a project website, etc. # Using the continuous integration (CI) capabilities of GitLab, you can automatically test and deliver the code. # You can access all the aspects of a project, view code, pull requests, and combine the conflict resolution. # 3. PerForce # Perforce delivers the version control capabilities through its HelixCore. # The HelixCore comes with a single platform for seamless team collaboration, # and support for both centralized and distributed development workflows. # It is a security solution that protects the most valuable assets. # HelixCore allows you to track the code changes accurately and facilitates a complete Git ecosystem. # 4. AWS CodeCommit # AWS CodeCommit is a managed version control system that hosts secure and scalable private Git repositories. # It seamlessly connects with other products from Amazon Web Services (AWS) and hosts the code in secured AWS environments. # Hence, it is a good fit for the existing users of AWS. # AWS integration also provides access to several useful plugins from AWS partners, which helps in software development. # 5. Bitbucket # Bitbucket is a part of the Atlassian software suite, so it can be integrated with other Atlassian services # including HipChat, Jira, and Bamboo. The main features of Bitbucket are code branches, # in-line commenting and discussions, and pull requests. #It can be deployed on a local server, data center of the company, as well as on the cloud. # Bitbucket allows you to connect with up to five users for free. # This is good because you can try the platform for free before deciding to purchase. # 2.What is the difference between Git and GitHub? #Git is a version control system that lets you manage and keep track of your source code history. #GitHub is a cloud-based hosting service that lets you manage Git repositories. # If you have open-source projects that use Git, then GitHub is designed to help you better manage them. # 3.Answer the following question: # 3.1 PR is Version Control Systems #Pull requests let you tell others about changes you've pushed to a branch in a repository on GitHub. #Once a pull request is opened, you can discuss and review the potential changes with collaborators and #add follow-up commits before your changes are merged into the base branch. #3.2 Fork VS Commit #Commit is record changes to the repository. #Forking #A fork is a copy of a repository that allows you to freely experiment with changes without # affecting the original project. A forked repository differs from a clone in that a connection # exists between your fork and the original repository itself. In this way, your fork acts as a bridge # between the original repository and your personal copy where you can contribute back to the original # project using Pull Requests. #Forking a project is as easy as clicking the Fork button in the header of a repository. Once the process # is complete, you'll be taken right to your the forked copy of the project so you can start collaborating! #3.3 Init VS Clone #git-init - Create an empty Git repository or reinitialize an existing one #Cloning #When you create a new repository on GitHub, it exists as a remote location where your project is stored. #You can clone your repository to create a local copy on your computer so that you can sync between both #the local and remote locations of the project. #Unlike forking, you won't be able to pull down changes from the original repository you cloned from, #and if the project is owned by someone else you won't be able to contribute back to it unless you are #specifically invited as a collaborator. Cloning is ideal for instances when you need a way to quickly #get your own copy of a repository where you may not be contributing to the original project. #3.4 Branching and Merging #git-branch - List, create, or delete branches #git-merge - Join two or more development histories together # 4.Create a Git Repositories using CLI and Console make sure to give them a name AssingmentUpload_Through_CLI and # AssignmentUpload_Through_Console respectively.cd # 5.Make sure to upload all your assignment into both of your repositories again using CLI and Console. # HINT: Use following Commands for CLI # git Init # git add # git commit -m “Message” # git status # git push # git config --global user.name "FIRST_NAME LAST_NAME" # git config --global user.email "[email protected]" # 6. Make sure to create three new branches and follow the instructions given below: # Main Branch - Master # First Branch - Dev ---> Copy of Master # Second Branch - Test ---> Copy of Dev # First Branch - Prod ---> Copy of Master # Once you are done creating temp branches see how to delete them but make sure delete them only when the changes have been pushed to the master branch or any main branch.
a= 1+2j b=10 c=5 temp=a,b a=c b=c print ('after swapping: {}' .format(a)) print ('after swapping: {}' .format(b))
#!/usr/bin/env python __author__ = "Rafael Caballero" # Problem: Given an array of integers, # return a new array such that each element # at index i of the new array is the product # of all the numbers in the original array # except the one at i. # Example1: if our input was [1, 2, 3, 4, 5], # the expected output would be [120, 60, 40, 30, 24] # Example2: if our input was [3, 2, 1], # the expected output would be [2, 3, 6]. from functools import reduce def get_new_array_mul(array): if not array: return [] total_mul = reduce(lambda x, y: x*y, array) new_array = list() for i in array: new_array.append(total_mul/i) return new_array def get_new_array_mul_no_div(array): #using no division if not array: return [] new_array = list() for i in range(len(array)): count = 0 total = 1 for element in array: if i == count: count += 1 continue else: total *= element count += 1 new_array.append(total) return new_array
s = 'azcbobobegghakl' size = len(s) string1 = s[0] largest = "" for i in range(len(s)-1): if s[(i+1)] >= s[i]: string1 = string1 + s[(i+1)] else: if len(string1) > len(largest): largest = string1 string1 = s[i+1] else: string1 = s[i+1] if len(string1) > len(largest): largest = string1 print('Longest substring in alphabetical order is:', largest)
import os def align(s,w): if len(s) > w: return s else: spaces = (w - len(s))//2 result = " " * spaces + s return result w = os.get_terminal_size().columns s = input('Please input a string:') print(len(s)) print (align(s,w)) #print('hello world'.center(width)) #print("{:>12}".format('hello world')) #align(s,w)
score = input("Please enter score:") try: score=float(score) except: print("Error, score must be numeric") quit() if score < 0 or score > 1: print("Error,score must be between 0 and 1:") quit() if score >= .9: grade = "A" elif score >= .8: grade = "B" elif score >= .7: grade = "C" elif score >= .6: grade = "D" else: grade = "F" print(grade)
fname=input("Enter file name:") if len(fname)< 1: fname= "mbox-short.txt" fh = open(fname) count = 0 largest = None counts=dict() namelist=list() for line in fh: line = line.rstrip() if line.startswith('From:'): countlist=list(line.split(" ")) namelist.append(countlist[1]) count = count + 1 for names in namelist: if names not in counts: counts[names] = 1 else: counts[names] = counts[names] + 1 #keymax = max(counts,key=counts.get) #print(max(counts.keys()),max(counts.values())) for k,v in counts.items(): if largest is None: email = k largest = v elif v > largest: email = k largest = v print(email,largest) #print(k,v) #largest = counts[key] #for names in namelist: # if names not in counts: # counts[names] = 1 # else: # counts[names] = counts[names] + 1 #keymax = max(counts,key=counts.get) #print(keymax,max(counts.values()))
balance = 320000 int_rate = 0.2 monthly_int_rate = int_rate/12 monthly_pmt_lb = balance/12 monthly_pmt_ub = (balance * (1 + monthly_int_rate)**12)/12 originalbalance = balance while abs(balance) > .02: balance = originalbalance payment = (monthly_pmt_ub - monthly_pmt_lb)/2 + monthly_pmt_lb for month in range(12): balance -= payment balance *= (1 + monthly_int_rate) if balance > 0: monthly_pmt_lb = payment else: monthly_pmt_ub = payment print(balance) print('Lowest payment: ', round(payment, 2))
x = input('Please input string:') s = len(x) l = x[ ::-1] r = -s count = 0 while s > 0: if x[(-r-s)] == l[(0-s)]: count = count+1 else: print('The string is not a palindrome.') break s -= 1 if count == len(x): print('The string is a palindrome.')
import copy def comma(list): #Function takes a list and returns a string with items separated by a comma and a space (', '), # with ('and ') inserted before the last item if len(list) == 0: return list else: editedList = [] for i in list: if len(list) != list.index(i) + 1: editedList.append(list[list.index(i)]) editedList.append(', ') else: editedList.append('and ') editedList.append(list[list.index(i)]) for i in editedList: print(editedList[editedList.index(i)], end='') if(len(editedList) == editedList.index(i) + 1 ): print() return editedList comma(["one", "two", "three", "four", "five"])
#! python3 # ProjectEUler.net Problem 2 def fibonacci(): sequence = [1,2] while (sequence[-1] + sequence[-2]) < 4000000: sequence.append(sequence[-1] + sequence[-2]) print(sequence[-1]) return sequence fibfourmillion = fibonacci() evenFibNumbers = [] for i in fibfourmillion: if i % 2 == 0: print(i) evenFibNumbers.append(i) print(sum(evenFibNumbers))
import sys from colorama import Fore, Style, init #colorama required for easily displaying colored text import random init() # initialises colorama for windows # collatz sequence takes any integer and works its way to one, using only two operations: # if the integer if even it is divided by two # if the integer is odd it's multiplied by 3 and 1 is added # This program can either run recursively, starting with a number and testing every # higher number. Or run once based on a user entered number. # Global Variables: # For the automated version this is the number which collatz() will start at. trials = 0 version = input("(r)ecursive or (i)nput? ") # FUNCTIONS: # COLLATZ() takes any integer and works its way to 1. def collatz(number): if (int(number) % 2 == 0): # print(str(int(number) // 2)) return int(number) // 2 else: # print(str(3 * int(number) + 1)) return 3 * int(number) + 1 # this function determines how the next number which will be tested will be determined def getTestNumber(): # testNumber = random.randint(2**40000, 2**50000) # return random.getrandbits(60000) ** 2 # testNumber = int(input("Enter a large starting integer: ")) return testNumber + 1 if version == 'i': while True: try: userInput = int(input("Enter a number: ")) while userInput != 1: userInput = collatz(userInput) except ValueError: print('Invalid input, enter an integer.') except KeyboardInterrupt: raise sys.exit(0) else: # if not (i), then (r)ecursive mode: while True: # Main loop testNumber = int(input("Enter a large starting integer: ")) # starting int while testNumber != 1: #if we haven't reached 1 do the following print("Trying: " + Fore.RED + str(testNumber) + Style.RESET_ALL) #print the number we're trying testingInt = testNumber #store our test number in a temporary value "testingInt" steps = 0 # keeps track of how many steps we take to reach 1 while testingInt != 1: # loop which reaches 1 running collatz() testingInt = collatz(testingInt) # collatz the temporary testingInt steps += 1 #increase steps taken by one else: # if testingInt has reached one, do the following # print that it works print(str(testNumber) + " Works, " + Fore.GREEN + str(steps) + Style.RESET_ALL + " step taken.") # set testNumber = to the next untested number using getTestNumber() testNumber = getTestNumber() #increase the count of trials we've run trials += 1
#! python3 from pathlib import Path import pprint as pp import pyinputplus as pyip workingDirectory = Path.cwd() def findkeyword(searchterm, glob, directory): files = {} directory = Path(directory) for file in list(directory.glob(str(glob))): currentFile = open(file, "r") lineIndex = 0 linesItemWasFound = [] for line in currentFile: lineIndex += 1 if searchterm in line: linesItemWasFound.append(lineIndex) if linesItemWasFound != []: files[str(file)] = linesItemWasFound return files searchTerm = pyip.inputStr('Text to search for: ') directoryToSearch = pyip.inputFilepath('Directory to search: ', mustExist=True) globmatch = pyip.inputStr("Enter a glob for filetype: ") # pp.pprint(findkeyword(searchTerm,globmatch ,directoryToSearch )) for filePath, lines in findkeyword(searchTerm, globmatch, directoryToSearch).items(): print(filePath +": [", end='') for line in lines: if line != lines[-1]: print(str(line) + ", ", end='') else: print(str(line), end='') print(']')
""" dai o que preciso fazer: 1. tirar os timestamps (ja fiz!) 2. tirar os simbolos (ja fiz) 3. selecionar so as linhas que tem C: no comeco 4. dessas linhas, contar as palavras de cada linha 5. fazer isso pra todos os textos numa pasta """ import nltk from nltk.tokenize import word_tokenize import string import re nltk.download('punkt') files_to_read = [ "input.txt", "input2.txt" ] output = [] for filename in files_to_read: # Open the file with open(filename, "r") as file: # Saves the current filename in the output output.append(filename) # Creates as list with all lines of the file lines = file.readlines() # Read each line of lines for line in lines: # Read line just if it contains 'C:' if 'E:' in line: # Removes 'C:' headless = line.replace('E:', '') # Remove numbers numberless = re.sub(r"\d", "", headless) # Remove timestamp timeless = re.sub(r'(\[::.])+', "", numberless) # Creates cleaner token table = str.maketrans( '', '', string.punctuation ) # Removing punctuation cleaned = timeless.translate(table) # Separate works words = word_tokenize(cleaned) # Count words number_of_words = str(len(words)) output.append(number_of_words) # Write output outputfile = open("output.txt","w+") text = '\n'.join(output) outputfile.write(text) outputfile.close() file.close()
import os # -----Euler Problem 1----- # Work out the first ten digits of the sum of the following one-hundred 50-digit numbers (data/euler13_data.txt) os.chdir(str(os.getcwd())) with open("data/euler13_data.txt", 'r') as f: lines = f.readlines() s = 0 for x in range(0, len(lines)): lines[x] = int(lines[x]) s += lines[x] print "The sum is", s
from IPython.display import clear_output, display import random def display_board(board): clear_output() print(board[7] + '|' + board[8] + '|' + board[9]) print('-----') print(board[4] + '|' + board[5] + '|' + board[6]) print('-----') print(board[1] + '|' + board[2] + '|' + board[3]) def player_name(): name1 = input('Player 1, Enter your name: ') print('Good Luck ' + name1) name2 = input('Player 2, Enter your name: ') print('Good Luck ' + name2) return name1, name2 def place_marker(): marker = ' ' while marker != 'X' and marker != 'O': marker = input('Player 1, Choose X or O: ').upper() if marker == 'X': return 'X', 'O' else: return 'O', 'X' def renamed_function(board, marker, position): board[position] = marker def check_winner(board, mark): return ((board[7] == mark and board[8] == mark and board[9] == mark) or (board[4] == mark and board[5] == mark and board[6] == mark) or (board[1] == mark and board[2] == mark and board[3] == mark) or (board[1] == mark and board[5] == mark and board[9] == mark) or (board[7] == mark and board[5] == mark and board[3] == mark) or (board[7] == mark and board[4] == mark and board[1] == mark) or (board[8] == mark and board[5] == mark and board[2] == mark) or (board[9] == mark and board[6] == mark and board[3] == mark)) def first_move(): if random.randint(0, 1) == 0: return 'Player 1' else: return 'Player 2' def position_open(board, position): return board[position] == ' ' def position_not_open(board): for i in range(1, 10): if position_open(board, i): return False return True def player_next_move(board): position = 0 while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not position_open(board, position): position = int(input('Please enter your next move (1-9) ')) return position def replay(): return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y') print('Welcome and thank you for playing Tic Tac Toe!') while True: board = [' '] * 10 player_name1, player_name2 = player_name() player1, player2 = place_marker() turn = first_move() print(turn + ' will make the first move') play_game = input('Are you ready to begin?') if play_game.lower()[0] == 'y': game_on = True else: game_on = False while game_on: if turn == 'Player 1': display_board(board) position = player_next_move(board) renamed_function(board, player1, position) if check_winner(board, player1): display(board) print('Congratulations ' + player_name1 + '! You won the game!') game_on = False else: if position_not_open(board): display_board(board) print('This game is a draw!') break else: turn = 'Player 2' else: display_board(board) position = player_next_move(board) renamed_function(board, player2, position) if check_winner(board, player2): display(board) print('Congratulations ' + player_name2 + '! You won the game!') game_on = False else: if position_not_open(board): display_board(board) print('This game is a draw!') break else: turn = 'Player 1' if not replay(): break
# coding:utf-8 ## 字符串类型 #无需转义,直接打印字符串 print(r'\\\\\\tttt\\\\') # 打印普通字符串 print('abc"') print("abc'") print("abc\"") print('abc\'') #打印多行字符串,包括换行符 print('''line1 line2 line3''') ## boolean 类型 print(3>2) if not 1>2: print("1>2 is false") # 算法运算符 print(10/3) print(10//3) print(10%3) # 编码问题 # 计算机中都是以unicode编码的方式处理字符,Unicode一般是两个字节的长度 # utf-8是一种变长的编码方式,较长使用的字符如a-z是以一个字节进行编码的,但是汉字可能以3个字节进行编码.比较适合进行网络传输 print(ord('c')) print(chr(99)) ## python中的字符串在内存中以unicode表示, 如果要在网络上进行传输或者保存到磁盘上,就需要把str转换为以字节为单位的bytes x=b'abc' print(x) bytes='中国'.encode('utf-8') print(bytes) print(ord("中")) ## 字符串输出进行格式化 print('abc%s' %('妹妹')) ## 字符串中包含特征符号 print('pass rate %d %%' %(90)) test1='{name}abc{age}'.format(name='妹妹',age=3) print(test1 ) ## list数据类型 namelist=['name','age','time'] print(namelist) ## 获取list的最后一个字符 print(namelist[-1]) ## 获取list的倒数第二个字符 print(namelist[-2]) ## 把元素插入到list中的指定位置 namelist.insert(5,'hometown') namelist.insert(2,'river') print(namelist) ## 删除list中指定位置的元素 print('pop namelist') print(namelist.pop(1)) print(namelist) ## 修改list中指定位置上的元素 namelist[0]="first" print(namelist) ## list中元素的类型可以不相同,同时list中的元素可以为一个list mixList=[1,2,3,['a','b','c'],'more'] print(mixList) print(mixList[3][0]) ## tuple (tuple与list非常相似,但是tuple一旦初始化就不能修改),增强了代码安全性 classmates=("michel",'bob','tracy') print(classmates) ##需要注意的是定义只有一个元素的tuple时,需要加逗号(,) singleTuple=(1,) print(singleTuple) ## 注意这种形式与上中形式的差别 singleTuple=(1) print(singleTuple) ## tuple内的元素不可变指的是指向的变量地址不能改变,但是指向地址内的内容是可以改变的 t = ('a', 'b', ['A', 'B']) t[2][0]='X' t[2][1]="Y" print(t)
import sys def distanceCalc (x , y): return x*y def speedCalc (x , y): return x/y def timeCalc (x , y): return x/y def calc_mins(x): x.strip(" ") if x.find("h")>0: formattedHours = x.strip("h") return float(formattedHours) elif x.find("m")>0: formattedMins = x.strip("m") return float(formattedMins)/60 else: print("Dodgy time format") sys.exit(0) print("Select Operation Type: /n Distance (1), Speed (2) or Time (3)") Opselect = input () invalidChoice = False if int(Opselect) == 1: speed = input("Input average speed in mph: ") time = input("Input travel time in mins or hrs e.g. 60m or 2h: ") print("The distance you travelled is: %.1f miles" % (distanceCalc(float(speed),calc_mins(time)))) elif int(Opselect) == 2: distance = input("Input miles to travel: ") time = input("Input timeframe in mins or hrs e.g. 60m or 2h: ") print("The speed you must travel to reach your destination in time is: %.1f mph" % speedCalc(float(distance),calc_mins(time))) elif int(Opselect) == 3: distance = input("Input distance to travel in miles: ") speed = input("Input speed in mph: ") print("The time that the journey will take at current speeds is: %.2f hours" % timeCalc(float(distance),float(speed))) else: invalidChoice = True if invalidChoice: print ("Selection not valid")
#!/usr/bin/python3 """[a class MyInt that inherits from int] """ class MyInt(int): """[summary] Arguments: int {[class]} -- [inheritance class] Returns: [bool] -- [MyInt is a rebel. MyInt has == and != operators inverted] """ pass def __eq__(self, other): """[it's a revealing comparison] Returns: [bool] -- [false if other is equal] """ return super().__ne__(other) def __ne__(self, other): """[it's a revealing comparison] Returns: [bool] -- [true if other is not equal] """ return super().__eq__(other)
#!/usr/bin/python3 def print_square(size): """[unction that prints a square with the character #] Arguments: size {[int]} -- [the size length of the square] Raises: TypeError: [size must be an integer] ValueError: [size must be >= 0] """ if type(size) != int: raise TypeError('size must be an integer') if size < 0: raise ValueError('size must be >= 0') for pos in range(size): print('#' * size)
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): sq = [] for elm in matrix[:]: sq.append(list(map(lambda x: x ** 2, elm))) return sq
#!/usr/bin/python3 """[function that appends a string at the end of a text file] """ def append_write(filename="", text=""): """ Keyword Arguments: filename {str} -- [file path] (default: {""}) text {str} -- [text to add to the file] (default: {""}) Returns: [int] -- [the number of characters written] """ with open(filename, 'a', encoding='UTF-8') as f_obj: f_obj.write(text) return len(text)
import threading class BankAccount(object): def __init__(self): self.balance = 0 self.actived = True self._value_lock = threading.Lock() def get_balance(self): with self._value_lock: if self.actived: return self.balance else: raise ValueError("Account has been closed;") def open(self): with self._value_lock: self.actived = True def deposit(self, amount): with self._value_lock: if self.actived: if amount < 0: raise ValueError("amount should not be negative") self.balance += amount else: raise ValueError("Account has been closed;") def withdraw(self, amount): with self._value_lock: if self.actived: if amount > self.balance: raise ValueError("balance is not enough.") elif amount < 0: raise ValueError("cann't withdraw negative amount.") self.balance -= amount else: raise ValueError("Account has been closed;") def close(self): with self._value_lock: self.actived = False
x=5 while (x>=1): print(x) x=x-1
sentence=input("give me a sentence") number_words=0 for letter in sentence: if letter==" ": number_words=number_words+1 print("there are",number_words+1,"words")
# This script is used to help me create the world generation algorithm. # It's included for anyone curious as to how it works, feel free to use any # parts of the algorithm! # Uses https://imgur.com/a/EoXWh as a reference, credit to the tModLoader team! from PIL import Image import matplotlib.pyplot as mpplot from enum import Enum import random import math # Map constants WORLD_WIDTH = 1000 WORLD_HEIGHT = 250 WORLD_SMOOTH_PASSES = 5 class Tiles(Enum): NOTHING = (123, 152, 254) STONE = (128, 128, 128) DIRT = (152, 106, 76) GRASS = (38, 127, 0) IRON = (140,101,80) WOOD = (151, 107, 75) PLATFORM = (191, 141, 111) VINE = (23, 177, 76) TREE = (151, 107, 75) SAND = (186, 168, 84) WATER = (9, 61, 191) # Call whenever you want to see the world def show(): mpplot.imshow(image) mpplot.show() # Gets replaced with the appropriate function in the actual code def setTile(x, y, tile): if x < 0 or x >= WORLD_WIDTH or y < 0 or y >= WORLD_HEIGHT: return image.putpixel((int(x), int(y)), tile.value) def getTile(x, y): if x < 0 or x >= WORLD_WIDTH or y < 0 or y >= WORLD_HEIGHT: return None pixel = image.getpixel((x, y)) for tile in Tiles: if pixel == tile.value: return tile return None ##### MAP ALGORITHM ##### # Everything in here gets translated into C def interpolate(a, b, x): f = (1.0 - math.cos(x * math.pi)) * 0.5; return a * (1.0 - f) + b * f; def randFloat(): return random.random() def poisson(mean): k = 0 p = 1 L = math.pow(math.e, -mean) while p > L: k += 1 u = random.random() p *= u return k - 1 def perlin(amplitude, wavelength, baseY, tile, iterations): yPositions = [int(baseY)] * WORLD_WIDTH for i in range(iterations): a = randFloat() b = randFloat() for x in range(WORLD_WIDTH): if(x % wavelength == 0): a = b b = randFloat() perlinY = a * amplitude else: perlinY = interpolate(a, b, (x % wavelength) / wavelength) * amplitude yPositions[x] += int(perlinY) wavelength >>= 1 amplitude >>= 1 for x in range(WORLD_WIDTH): for y in range(yPositions[x], WORLD_HEIGHT): setTile(x, y, tile) # Very versatile function # skewHorizontal and skewVertical must be between 0 and 1 # Only one should be above 0 def clump(x, y, num, tile, maskEmpty, skewHorizontal, skewVertical): if maskEmpty and getTile(x, y) == Tiles.NOTHING: return coords = [(x, y)] while num > 0: if len(coords) == 0: return selected = random.randrange(0, len(coords)) selectedTile = coords[selected] del coords[selected] setTile(*selectedTile, tile) num -= 1 for delta in ((0, -1), (1, 0), (0, 1), (-1, 0)): checkX = selectedTile[0] + delta[0] checkY = selectedTile[1] + delta[1] if skewHorizontal > 0: if delta[1] != 0 and random.random() < skewHorizontal: continue if skewVertical > 0: if delta[0] != 0 and random.random() < skewVertical: continue if getTile(checkX, checkY) == tile or (maskEmpty and getTile(checkX, checkY) == Tiles.NOTHING): continue coords.append((checkX, checkY)) def box(x, y, width, height, tile, coverage, swap): for dX in range(width): for dY in range(height): if dY == 0 or dY == height - 1 or dX == 0 or dX == width - 1: if random.random() < coverage: setTile(x + dX, y + dY, tile) else: setTile( x + dX, y + dY, swap) else: setTile(x + dX, y + dY, Tiles.NOTHING) def generateTree(x, y, baseHeight): top = 0 height = max(1, baseHeight + random.randrange(0, 3) - 1) if x == 0 or x == WORLD_WIDTH - 1 or y < 0 or y >= WORLD_HEIGHT - height: return for i in range(height): if getTile(x - 1, y - i) == Tiles.TREE \ or getTile(x + 1, y - i) == Tiles.TREE \ or getTile(x - 2, y - i) == Tiles.TREE \ or getTile(x + 2, y - i) == Tiles.TREE: return while top < height: setTile(x, y - top, Tiles.TREE) top += 1 setTile(x, y - top, Tiles.TREE) if getTile(x - 1, y + 1) == Tiles.GRASS and random.randrange(0, 3) <= 1: setTile(x - 1, y, Tiles.TREE) if getTile(x + 1, y + 1) == Tiles.GRASS and random.randrange(0, 3) <= 1: setTile(x + 1, y, Tiles.TREE) def parabola(x, y, width, depth, material): multiplier = -depth / (width / 2) ** 2 for dX in range(width): if x + dX < 0: continue elif x + dX >= WORLD_WIDTH: return for dY in range(y): if getTile(x + dX, dY) != Tiles.NOTHING: setTile(x + dX, dY, Tiles.NOTHING) for dY in range(int(multiplier * (dX - width / 2) ** 2 + depth)): setTile(x + dX, y + dY, material) def generate(): print("Generating dirt...") perlin(10, 30, WORLD_HEIGHT // 5, Tiles.DIRT, 3) print("Generating stone...") perlin(6, 20, WORLD_HEIGHT // 2.8, Tiles.STONE, 1) print("Tunnels...") x = 100 while x < WORLD_WIDTH - 100: if random.random() < 0.01: yPositions = [] for dX in range(0, 50, 5): y = 0 while y < WORLD_HEIGHT and getTile(x + dX, y + 8) != Tiles.DIRT: y += 1 yPositions.append(y) for dX, position in enumerate(yPositions): clump(x + 5 * dX, position, 20, Tiles.DIRT, False, 0.5, 0) x += 100 else: x += 1 print("Sand...") for i in range(60): x = random.randrange(0, WORLD_WIDTH) y = random.randrange(WORLD_HEIGHT // 3.5, WORLD_HEIGHT // 2) clump(x, y, poisson(50), Tiles.SAND, True, 0, 0) for i in range(max(2, poisson(3))): width = poisson(75) mul = -30 / width x = random.randrange(0, WORLD_WIDTH - width) for dX in range(width): left = min(10, mul * abs(dX - width / 2) + 15) y = 0 while left > 0 : if getTile(x + dX, y) != Tiles.NOTHING: setTile(x + dX, y, Tiles.SAND) left -= 1 y += 1 print("Rocks in dirt...") for i in range(1000): x = random.randrange(0, WORLD_WIDTH) y = random.randrange(0, WORLD_HEIGHT // 2.8) if getTile(x, y) == Tiles.DIRT: clump(x, y, poisson(10), Tiles.STONE, True, 0, 0) print("Dirt in rocks...") for i in range(3000): x = random.randrange(0, WORLD_WIDTH) y = random.randrange(WORLD_HEIGHT // 2.8, WORLD_HEIGHT) if getTile(x, y) == Tiles.STONE: clump(x, y, poisson(10), Tiles.DIRT, True, 0, 0) print("Small holes...") for i in range(250): x = random.randrange(0, WORLD_WIDTH) y = random.randrange(WORLD_HEIGHT // 3.2, WORLD_HEIGHT) clump(x, y, poisson(50), Tiles.WATER, False, 0, 0) for i in range(750): x = random.randrange(0, WORLD_WIDTH) y = random.randrange(WORLD_HEIGHT // 3.2, WORLD_HEIGHT) clump(x, y, poisson(50), Tiles.NOTHING, True, 0, 0) # A 500-length coord array should be enough for this print("Caves...") for i in range(150): x = random.randrange(0, WORLD_WIDTH) y = random.randrange(WORLD_HEIGHT // 3.2, WORLD_HEIGHT) clump(x, y, poisson(200), Tiles.NOTHING, True, 0, 0) print("Generating grass...") for x in range(WORLD_WIDTH): for y in range(int(WORLD_HEIGHT // 2.8)): if getTile(x, y) == Tiles.DIRT: setTile(x, y, Tiles.GRASS) if getTile(x - 1, y) == Tiles.NOTHING or getTile(x + 1, y) == Tiles.NOTHING: setTile(x, y + 1, Tiles.GRASS) break elif getTile(x, y) != Tiles.NOTHING: break for x in range(WORLD_WIDTH): for y in range(int(WORLD_HEIGHT // 2.8)): if getTile(x, y) == Tiles.DIRT and ( getTile(x - 1, y) == Tiles.NOTHING or getTile(x + 1, y) == Tiles.NOTHING or getTile(x, y - 1) == Tiles.NOTHING or getTile(x, y + 1) == Tiles.NOTHING): setTile(x, y, Tiles.GRASS) print("Shinies...") for i in range(750): x = random.randrange(WORLD_WIDTH) y = random.randrange(0, WORLD_HEIGHT) if getTile(x, y) != Tiles.SAND: clump(x, y, poisson(10), Tiles.IRON, True, 0, 0) print("Lakes...") for i in range(max(2, poisson(3))): x = random.randrange(75, WORLD_WIDTH - 75) width = max(15, poisson(15)) depth = max(5, poisson(10)) leftY = WORLD_HEIGHT // 5 while getTile(x, leftY) == Tiles.NOTHING: leftY += 1 if getTile(x, leftY + 6) == Tiles.NOTHING: leftY += 6 rightY = WORLD_HEIGHT // 5 while getTile(x + width, rightY) == Tiles.NOTHING: rightY += 1 if getTile(x + width, rightY + 6) == Tiles.NOTHING: rightY += 6 y = max(leftY, rightY) parabola(x, y, width, depth, Tiles.WATER) print("Beaches...") leftY = 0 while getTile(60, leftY) == Tiles.NOTHING: leftY += 1 rightY = 0 while getTile(WORLD_WIDTH - 60, rightY) == Tiles.NOTHING: rightY += 1 # Left beach parabola(-62, leftY, 124, 32, Tiles.DIRT) parabola(-60, leftY, 120, 30, Tiles.SAND) parabola(-50, leftY + 2, 100, 20, Tiles.WATER) # Right beach parabola(WORLD_WIDTH - 62, rightY, 124, 32, Tiles.DIRT) parabola(WORLD_WIDTH - 60, rightY, 120, 30, Tiles.SAND) parabola(WORLD_WIDTH - 50, rightY + 2, 100, 20, Tiles.WATER) print("Gravitating Sand...") for x in range(WORLD_WIDTH): for y in range(WORLD_HEIGHT, 0, -1): if getTile(x, y) == Tiles.SAND and getTile(x, y + 1) == Tiles.NOTHING: tempY = y while tempY < WORLD_HEIGHT - 1 and getTile(x, tempY + 1) == Tiles.NOTHING: tempY += 1 setTile(x, tempY, Tiles.SAND) setTile(x, y, Tiles.NOTHING) print("Smooth World...") for i in range(WORLD_SMOOTH_PASSES): for passDir in range(2): for y in range(WORLD_HEIGHT): if getTile((WORLD_WIDTH - 1) if passDir else 0, y) != Tiles.NOTHING: ySave = y break for x in range((WORLD_WIDTH - 1) if passDir else 0, 0 if passDir else WORLD_WIDTH, -1 if passDir else 1): y = 0 while getTile(x, y) == Tiles.NOTHING: y += 1 deltaY = ySave - y tile = getTile(x, y) if tile == Tiles.WATER and deltaY > 0: for dY in range(deltaY): setTile(x, y + dY, Tiles.NOTHING) ySave = y + deltaY - 1 elif deltaY > (2 if tile != Tiles.SAND else 1) and getTile(x, y + 6) != Tiles.NOTHING: for dY in range(min(deltaY - 1, 2)): setTile(x, y + dY, Tiles.NOTHING) ySave = y + deltaY - 1 else: ySave = y print("Buried Chests...") for i in range(30): num = min(max(1, round(poisson(1.25))), 3) x = random.randrange(25, WORLD_WIDTH - 25) y = random.randrange(int(WORLD_HEIGHT / 2.8), WORLD_HEIGHT) while getTile(x, y) != Tiles.NOTHING: x = random.randrange(25, WORLD_WIDTH - 25) y = random.randrange(int(WORLD_HEIGHT / 2.8), WORLD_HEIGHT) for room in range(num): width = random.randrange(10, 20) box(x, y, width, 6, Tiles.WOOD, 0.9, Tiles.NOTHING) platformX = random.randrange(x + 1, x + width - 5) for dX in range(random.randrange(2, 5)): setTile(platformX + dX, y, Tiles.PLATFORM) y += 7 x += random.randrange(-(width - 3), width - 3) print("Spreading grass...") for x in range(WORLD_WIDTH): for y in range(int(WORLD_HEIGHT // 2.8)): if getTile(x, y) == Tiles.DIRT: setTile(x, y, Tiles.GRASS) if getTile(x - 1, y) == Tiles.NOTHING or getTile(x + 1, y) == Tiles.NOTHING: setTile(x, y + 1, Tiles.GRASS) break elif getTile(x, y) != Tiles.NOTHING: break print("Planting Trees...") x = 0 while x < WORLD_WIDTH: if random.randrange(0, 40) == 0: copseHeight = random.randrange(1, 8) while random.randrange(0, 10) != 0 and x < WORLD_WIDTH: x += 4 for y in range(1, WORLD_HEIGHT): tile = getTile(x, y) if tile == Tiles.GRASS: generateTree(x, y - 1, copseHeight) break elif tile != Tiles.NOTHING: break x += 1 print("Vines...") for x in range(WORLD_WIDTH): for y in range(int(WORLD_WIDTH // 4.5)): if getTile(x, y) == Tiles.GRASS and getTile(x, y + 1) == Tiles.NOTHING and random.randrange(0, 3) > 0: for dY in range(1, random.randrange(3, 11)): if getTile(x, y + dY) != Tiles.NOTHING: break; setTile(x, y + dY, Tiles.VINE) ##### END ALGORITHM ##### image = Image.new("RGB", (WORLD_WIDTH, WORLD_HEIGHT), (123, 152, 254)) generate() show() if input("Save image? ").lower() in ('y', 'yes'): image.resize((2000, 500), Image.NEAREST).save("./map.png")
# defining my functions before starting the base program #I prefer integers to floats as they don't take up as much space as floats. Though I will use floats in this. def getFloat(prompt): while True: x= float(input(prompt)) return x def getOperator (): while True: operator= input("Which operator do you chose? +, -, /, *") if operator == "+" or operator == "-" or operator == "/" or operator == "*": return operator else: print("You have entered incorrectly try again.") def doWork (oper, x, y): if op == "+": return x+y elif op == "-": return x-y elif op == "*": return x*y elif x != 0 and y != 0 and op == "/": return x/y else: print("Either your first or last number was 0. You can not divide.") while True: print("This is a console calculator.") num1 = getFloat("First number: ") num2= getFloat("Second number: ") op = getOperator() end = doWork(op,num1,num2) print("Results: \n >>>", end) cont = input("Again? Y/N ") if cont != "Y": break #Was my old code before critques. #def multiply(x,y): #z=x*y #print(z) #def subtract(x,y): # z=x-y # print(z) #def divide(x,y): # z=x/y # print(z) #def add(x,y): #z=x+y # print(z) #putting the program in a small loop to help with some error checking. #\n just creates a new line for the ease of seeing in the output file. #while True: # operation = input("What would you like to do? *,/,+,- \n") # if operation == "+": # x=int(input("First number: \n")) # y=int(input("Second number: \n")) # add(x,y) # break # elif operation == "/": # x=int(input("First number: \n")) # y=int(input("Second number: \n")) # divide(x,y) # break # elif operation == "-": # x=int(input("First number: \n")) # y=int(input("Second number: \n")) # subtract(x,y) # break # elif operation == "*": # x=int(input("First number: \n")) # y=int(input("Second number: \n")) # multiply(x,y) # break #else: # print("that was not a correct operation...") #loop will start again if one of the operators is not put in by user.
from sys import argv script, nome_usuario = argv prompt = '> ' print("Olá %s, Eu sou o %s script." % (nome_usuario, script)) print("Eu gostaria de lhe fazer algumas perguntas.") voce_gosta = input("%s, você gosta de mim? " % nome_usuario) onde_mora = input("Onde você mora, %s? " % nome_usuario) computador = input("Que tipo de computador você tem? ") print(""" Certo, você disse %r sobre gostar de mim. Você mora em %r, mas eu não sei onde fica. E você tem um computador %r. Bom! """ % (voce_gosta, onde_mora, computador))