text
stringlengths
37
1.41M
def sort_alphabetically(file_name): with open(file_name) as the_file: lines = the_file.readlines() list_sorted = False while not list_sorted: list_sorted = True for i in range(len(lines) - 1): if lines[i].lower() > lines[i + 1].lower(): temp = lines[i] lines[i] = lines[i + 1] lines[i + 1] = temp list_sorted = False return lines def selection_sort(the_list): for i in range(len(the_list)): min_index = i for j in range(i, len(the_list)): if the_list[min_index] > the_list[j]: min_index = j temp = the_list[min_index] the_list[min_index] = the_list[i] the_list[i] = temp return the_list # Bubble sort is Omega(n) and O(n^2) # selection sort is Omega(n^2) and O(n^2) so overall Theta(n^2) # Quick Sort is Omega(n lg(n)) and O(n^2) # linear search is Omega(1) and O(n) # binary search is Omega(1) and O(lg(n)) def divides_evenly(n, x): if n % x != 0 or n == 0: return 0 else: return 1 + divides_evenly(n // x, x) if __name__ == '__main__': the_dictionary = {} the_dictionary['hello'] = 3 print(the_dictionary.get('robots')) the_dictionary['robots'] = 17 the_dictionary['keys'] = 32 the_dictionary['glue'] = 654 the_dictionary['battle bottle'] = 9 the_dictionary['bees?'] = 37 print(the_dictionary['glue']) print(the_dictionary.keys()) print(the_dictionary.values()) # number of times that x divides n, evenly # 127, 5 -> 0 # 125, 5 -> 3 # 24 (8 * 3), 2 -> 3 print(sort_alphabetically('blah.txt'))
def funcion_primo(num): resp = 0 if num == 2: print(f"EL NUMERO {num} ES PRIMO ") else: for i in range(2, num): if num % i == 0: resp = resp + 1 if resp == 0: print(f"EL NUMERO {num} ES PRIMO ") else: print(f"EL NUMERO {num} NO ES PRIMO ") def main(): num = int(input("DIGITE UN NUMERO: ")) funcion_primo(num) if __name__ == "__main__": main()
##aliquot number def summation(lis): s=0 for i in lis: s=s+i return s def aliquot(n): l=[] for i in range(1, n): if(n%i==0): l.append(i) return summation(l) print "Enter number" x=int(raw_input()) print aliquot(x) #Output: #Enter number #12 #16
##calculate bishop moves from(x, y) def bishop(x, y): x1,x2,x3 = x,x,x y1,y2,y3 = y,y,y while(x1<8 and y1<8): x1+=1 y1+=1 print x1, y1 while(x2>1 and y2>1): x2-=1 y2-=1 print x2, y2 while(x3>1 and y3<8): x3-=1 y3+=1 print x3, y3 while(x<8 and y>1): x+=1 y-=1 print x, y print "Enter the current position of bishop" print "x:" x=int(raw_input()) print "y:" y=int(raw_input()) print "Possible moves could be" bishop(x, y) ##Output: ##Enter the current position of bishop ##x: ##3 ##y: ##3 ##Possible moves could be ##4 4 ##5 5 ##6 6 ##7 7 ##8 8 ##2 2 ##1 1 ##2 4 ##1 5 ##4 2 ##5 1
class Bicycle(object): """Models bicycles""" def __init__(self, model, weight, cost): self.model=model self.weight=weight self.cost=cost class BikeShop(object): """Models Bike Shops""" def __init__(self, name, inventory, markup, bikesSold, profit): self.name=name self.inventory=inventory self.markup=markup self.bikesSold=bikesSold self.profit=profit def sellBike(self, model, cost): if model in self.inventory: self.bikesSold += 1 self.profit+=(cost*(self.markup+1) - cost) self.inventory[model] -= 1 else: print("Sorry, we do not have that bike") def printInventory(self): print("Our current inventory is as follows:") for key in self.inventory: print("{} : {} bikes".format(key.model, self.inventory[key])) def numBikesSold(self): print("We have sold {} bikes".format(self.bikesSold)) def profitEarned(self): print("We have earned {} in profit.".format(self.profit)) class Customer(object): """Makes customers""" def __init__(self, name, budget): self.name=name self.budget=budget def buyBike(self, model): print("I would like to buy a {}".format(model))
PRINT_BEEJ = 1 HALT = 2 memory = [ PRINT_BEEJ, PRINT_BEEJ, PRINT_BEEJ, PRINT_BEEJ, PRINT_BEEJ, HALT ] pc = 0 running = True while running: instruction = memory[pc] if instruction == PRINT_BEEJ: print("BEEJ!") elif instruction == HALT: running = False else: print(f"Error at index {pc}") pc += 1
# Write a Python program to add an item in a tuple. sample_tuple = (1,2,3,4,5) print(sum(sample_tuple))
# 44. Write a Python program to slice a tuple. sample_tuple = ( 1,2,3,4,5) print("Slicing of tuple::") print("For 1st two elements:",sample_tuple[:2]) print("For 3rd element to end::",sample_tuple[3:])
# 24. Write a Python program to clone or copy a list. list_items= [1,(2,4),[1,2,3],'a'] output_items = list_items.copy() print("Original items of list is::",list_items) print("\nClone items of list is::",output_items)
# 10. Write a Python program to print the even numbers from a given list. def even(lst): output_list =[] for i in lst: if i % 2 == 0: output_list.append(i) else: continue return output_list sample_list =[1, 2, 3, 4, 5, 6, 7, 8, 9] print(even(sample_list))
# 13. Write a Python program to sort a list of tuples using Lambda. sortTuple = lambda lst: sorted(lst,key=lambda ls: ls[0]) sample_list = [(1,2),(5,2),(0,2),(7,0),(2,1),(0,0)] print(sortTuple(sample_list))
# 1. Write a Python program to count the number of characters (character frequency) in a string. Sample String : google.com' input_string = input("Enter a string::") dict_string= {} for i in input_string: if i.isalpha()== True: count=input_string.count(i) dict_string.update({i:count}) print(dict_string)
# 3. Write a Python function to multiply all the numbers in a list. def mul(sample_list): result=1 for item in sample_list: result *= item return result sample_list = [8, -2, 3, -1, 7] print("Multiplication of all the numbers::",mul(sample_list))
# 1. Write a Python function to find the Max of three numbers. def Greatest(num1,num2,num3): if num1<num2: return num3 if num2<num3 else num2 elif num2<num3: return num1 if num3 < num1 else num3 else: return num3 if num1<num3 else num1 print("----------Finding Greatest Number----------------") num1,num2,num3= int(input("Enter 1st numbers::")),int(input("Enter 2nd numbers::")),int(input("Enter 3rd numbers::")) print("The greatest number is::",Greatest(num1,num2,num3))
# -*- coding: utf-8 -*- # あとから使うために例外文字列を作っておく。 BalanceError = "現在の口座残高は、 $%9.2f しかありません。" class BankAccount: def __init__(self, initialAmount): self.balance = initialAmount print "口座を開設しました。口座残高は $%9.2f です。" % self.balance def deposit(self, amount): self.balance = self.balance + amount def withdraw(self, amount): if self.balance >= amount: self.balance = self.balance - amount else: raise BalanceError % self.balance def getBalance(self): return self.balance def transfer(self, amount, account): try: self.withdraw(amount) account.deposit(amount) except BalanceError: print BalanceError class InterestAccount(BankAccount): def deposit(self, amount): BankAccount.deposit(self, amount) self.balance = self.balance * 1.03 class ChargingAccount(BankAccount): def __init__(self, initialAmount): BankAccount.__init__(self, initialAmount) self.fee = 3 def withdraw(self, amount): BankAccount.withdraw(self, amount+self.fee)
# -*- coding: utf-8 -*- def printList(L): # リストが空なら、何もしない if not L: return # 戦闘の項目の型がリストであれば、 # 戦闘の項目を渡してprintListを呼び出す if type(L[0]) == type([]): printList(L[0]) else: # リストでなければ、単純に先頭項目を表示する print L[0] # Lの残りの部分を処理する printList(L[1:])
import math # def定义函数 # 示例:自定义一个求绝对值的函数my_abs() def my_abs(n): if n >= 0: return n else: return -n print(my_abs(-3)) # 空函数 def nop(): pass # pass语句什么也不做,相当于一个占位符,保证语法正确 # 通过isinstance()函数可以对自定义函数的参数做类型检查 def my_abs(n): if not isinstance(n,(int,float)): raise TypeError('bad operand type') if n >= 0: return n else: return -n # print(my_abs('A')) # python中的函数可以返回多个值 # 示例:在游戏中经常需要从一个点移动到另一个点,给出坐标、位移和角度,就可以计算出新的新的坐标: def move(x,y,step,angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx,ny x,y = move(100,100,60,math.pi / 6) print(x,y) # 但其实这是一种假象,Python的函数返回的任然是单一的值:tuple。在语法上返回一个tuple括号可以省略, # 而多个变量同时接受一个tuple,按位置赋给对应的值 r = move(100,100,60,math.pi / 6) print(r) # (151.96152422706632, 70.0)
# int(x, [base]) 函数可以把字符串转换为整数,base指定int把字符串x视为对应进制来转成十进制 # 示例:将'1010101'当做二进制转换 v = int('1010101',base=2) # print(v) # 如果有大量的二进制需要转换,每调用int都需要指定base=2,我们可以定义下面函数来简化(将base=2作为默认参数): def int2(s,base=2): return int(s,base) # print(int2('1010101')) # 偏函数:借用functools模块的partial帮助我们创建一个偏函数的,不需要我们自己定义int2() # 简单总结functools.partial的作用就是,把一个函数的某些参数给固定住(设置默认值),返回一个新的函数,调用这个新函数会更简单。 import functools int2 = functools.partial(int,base=2) print(int2('0000011')) # 在创建偏函数时可以接受函数、*args(可变参数)、**kwargs(关键字参数) int2 = functools.partial(int,base=2) # 传入关键字参数base max2 = functools.partial(max,10) # 把10作为可变参数自动加入参数列表右边 print(max2(5,6,7)) # 10
class Student(object): # def getScore(self): # return self.__score # # def setScore(self, score): # if not isinstance(score, int): # raise ValueError('score type must is int') # if score < 0 or score > 100: # raise ValueError('score value is between 0 and 100') # self.__score = score # 利用@property装饰器定义score属性 @property def score(self): return self.__score @score.setter def score(self, score): if not isinstance(score, int): raise ValueError('score type must is int') if score < 0 or score > 100: raise ValueError('score must between 0 ~ 100!') self.__score = score if __name__ == '__main__': s = Student() # getter/setter 方式访问score属性,略显复杂 # s.setScore(9999) # s.score = 9999 # print(s.score) # ValueError s.score = 89 print(s.score)
# help()方法可以查看函数的帮助信息 help(abs) # abs() 求绝对值 print(abs(-88)) print(abs(88)) # 数据转换函数:int()、float()、str()、bool() var = '123' print(int(var)) var = '23.3' print(float(var)) var = 123 print(str(var)) var = 1 print(bool(var)) var = 0 print(bool(var)) var = '' print(bool(var)) # hex():把一个整数转为十六进制表示的字符串 n = 255 print(hex(n))
class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') # 静态语言VS动态语言 # - 对于静态语言(如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或其子类 # - 对于Python等动态语言来说,不一定需传入Animal类型,只要保证传入对象有run()方法即可(具有鸭子类型) class Timer(object): def run(self): print('Start...') def runing(animal): animal.run() if __name__ == '__main__': d = Dog() c = Cat() # 多态 print(isinstance(d,Animal)) # True print(isinstance(d,Dog)) # True runing(d) runing(c) runing(Timer())
# ############################## sorted ################################## # sorted(iterable,key,reverse) # - 通过key指定的函数,作用到iterable上,并根据key函数返回的结果进行排序 # - reverse=True,反向排序 # 示例1:根据绝对值排序 L = [36, 5, -12, 9, -21] # print(sorted(L,key=abs)) # 示例2:忽略大小写,按照字母序排序 L = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(L)) # 默认根据首字母ASCII的大小排序:['Credit', 'Zoo', 'about', 'bob'] print(sorted(L,key=str.lower)) # ['about', 'bob', 'Credit', 'Zoo'] # 倒序 print(sorted(L,key=str.lower,reverse=True)) # ['Zoo', 'Credit', 'bob', 'about'] # 练习:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] # 1)、请用sorted()对上述列表分别按名字排序: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] r = sorted(L,key=lambda t:t[0]) print(r) # 2)、再按成绩从高到低排序 r = sorted(L,key=lambda t:t[1],reverse=True) print(r)
import sys def threeSumClosest(numbers, target): result = 2**31 - 1 length = len(numbers) if length < 3: return result numbers.sort() larger_count = 0 for i, item_i in enumerate(numbers): start = i + 1 end = length - 1 # optimization 1 - filter the smallest sum greater then target if start < end: sum3_smallest = numbers[start] + numbers[start + 1] + item_i if sum3_smallest > target: larger_count += 1 if larger_count > 1: return result while (start < end): sum3 = numbers[start] + numbers[end] + item_i if abs(sum3 - target) < abs(result - target): result = sum3 # optimization 2 - filter the sum3 closest to target sum_flag = 0 if sum3 > target: end -= 1 if sum_flag == -1: break sum_flag = 1 elif sum3 < target: start += 1 if sum_flag == 1: break sum_flag = -1 else: return result return result numbers={ 1, 2, 4, 8, 16, 32, 64, 128 } target=82 res = threeSumClosest(numbers, target) print res
import unittest import re from exercise_04.PasswordGenerator import PasswordGenerator class TestPasswordGenerator(unittest.TestCase): def test_should_be_callable(self): self.assertTrue(callable(PasswordGenerator), 'Should be callable') def test_should_return_a_string(self): generator = PasswordGenerator() password = generator.new_password() self.assertTrue(isinstance(password, str), 'Should be a string') def test_should_return_a_string_enough_length(self): generator = PasswordGenerator() password = generator.new_password() expected_length = 32 self.assertGreaterEqual(len(password), expected_length, f'Should have at least {expected_length} characters') def test_should_contain_at_least_one_letter_lowercase(self): generator = PasswordGenerator() password = generator.new_password() self.assertTrue(re.search('[a-z]', password), 'Should contain a letter in lowercase') def test_should_contain_at_least_one_number(self): generator = PasswordGenerator() password = generator.new_password() self.assertTrue(re.search('[0-9]', password), 'Should contain a number') def test_should_return_different_token_on_every_call(self): generator = PasswordGenerator() list_of_tokens = [] number_of_tokens_to_generate = 9999 number_of_expected_tokens = number_of_tokens_to_generate while number_of_tokens_to_generate > 0: password = generator.new_password() if password not in list_of_tokens: list_of_tokens.append(password) number_of_tokens_to_generate -= 1 self.assertEqual(len(list_of_tokens), number_of_expected_tokens, f'Should generate {number_of_expected_tokens} unique tokens') if __name__ == '__main__': unittest.main()
''' A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12). ''' def partition(s): length=len(s) l=['']*length k=0 j=0 i=0 stat=True while i<length: if stat: if s[i]=='1' or s[i]=='2': stat=False j=i;i+=1 else: l[k]+=s[i] else: if s[i]=='1' or s[i]=='2': i+=1 elif s[i]=='0': l[k]+=s[j:i-1] i+=1;k+=1;stat=True elif s[i-1]=='1' or (s[i-1]=='2' and int(s[i])<7): l[k]+=s[j:i+1] i+=1;k+=1;stat=True else: l[k]+=s[j:i] i+=1;k+=1;stat=True if not stat: l[k]+=s[j:i+1] print(l) return l def fibone(n): l=[1]*(n+1) if n<2: return l else: for i in range(2,n+1): l[i]=l[i-1]+l[i-2] print(l) return l s='121' ss=partition(s) ml=1 for i in ss: ml=max(len(i),ml) L=fibone(ml) for i in range(len(ss)): ss[i]=L[len(ss[i])] print(ss) result=1 for j in ss: result*=j print(result)
''' A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. ''' obstacle=[[0,0,0], [0,1,0], [0,0,0]] def uniquePath(obstacleGrid): length=len(obstacleGrid[0]) width=len(obstacleGrid) j=0 for i in range(length): if obstacleGrid[0][i]==0: obstacleGrid[0][i]=1 else: j=i break if j!=0: for i in range(j,length): obstacleGrid[0][i]=0 j=0 for i in range(1,width): if obstacleGrid[i][0]==0: obstacleGrid[i][0]=1 else: j=i break if j!=0: for i in range(j,width): obstacleGrid[i][0]=0 for i in range(1,width): for j in range(1,length): if obstacleGrid[i][j]!=1: obstacleGrid[i][j]=obstacleGrid[i-1][j]+obstacleGrid[i][j-1] else: obstacleGrid[i][j]=0 return obstacleGrid[-1][-1] uniquePath(obstacle)
''' Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: 3 索引的方法:数组A 中如果只出现一次 A[i] 表示索引 只出现一次/ ''' def findDuplicate(nums): for i in range(len(nums)): index=nums[i] if nums[index]>0: nums[index]=-nums[index] else: return index
'''Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] ''' def groupAngrams(strs): dicts={} for s in strs: ones=list(s) l=list(s) l.sort() s1=''.join(l) dicts.setdefault(s1,[]) dicts[s1].append(s) result=list(dicts.values()) return result
''' Input: Binary tree: [1,2,3,4] 1 / \ 2 3 / 4 Output: "1(2(4))(3)" Explanation: Originallay it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)". Example 2: Input: Binary tree: [1,2,3,null,4] 1 / \ 2 3 \ 4 Output: "1(2()(4))(3)" ''' def tree2str(t): """ :type t: TreeNode :rtype: str """ if not t:return "" if t.right==None and t.left==None: return str(t.val) if t.right!=None and t.left!=None: return str(t.val)+'('+self.tree2str(t.left)+')'+'('+self.tree2str(t.right)+')' if t.left != None: return str(t.val)+'('+self.tree2str(t.left)+')' return str(t.val)+'()'+'('+self.tree2str(t.right)+')'
#Input: 1->2->3->4->5->NULL #Output: 1->3->5->2->4->NULL def oddEvenList(head): if head==None or head.next==None: return head p0=head p1=head.next while p1.next!=None: p0.next=p1.next p0=p0.next if p0.next !=None: p1.next=p0.next p1=p1.next return head
''' Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. ''' from collections import deque def uglyNumber(n): nums=deque([0,1,2,3,4,5]) i2=2 i3=3 i5=5 if n<=5: return nums[n] count=5 num=6 status=True while count<n: if num%2==0: val=num//2 for i in range(i2,count): if nums[i]>val: if nums[i-1]==val: nums.append(num) count+=1 i2=i-1 status=False else: break if status: if num%3==0: val=num//3 for i in range(i3,count): if nums[i]>val: if nums[i-1]==val: nums.append(num) count+=1 i3=i-1 status=False else: break if status: if num%5==0: val=num//5 for i in range(i5,count): if nums[i]>val: if nums[i-1]==val: nums.append(num) count+=1 i5=i-1 status=False else: break num+=1 status=True print(nums[n]) print(nums) def uglyNumber1(n): nums=[0]*n nums[0]=1 p2=0;p3=0;p5=0 count=1 while count<n: f2=nums[p2]*2 f3=nums[p3]*3 f5=nums[p5]*5 mini=min(f2,f3,f5) nums[count]=mini if mini==f2: p2+=1 if mini==f3: p3+=1 if mini==f5: p5+=1 count+=1w print(nums[-1]) print(nums) uglyNumber1(1)
''' Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example: Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4 ''' def maximalSquare(matrix): """ :type matrix: List[List[str]] :rtype: int """ l=len(matrix) if l<1:return 0 w=len(matrix[0]) if w<1:return 0 for i in range(l): for j in range(w): matrix[i][j]=int(matrix[i][j]) maxs=0 for i in range(l): if matrix[i][0]==1: maxs=1 break for i in range(w): if matrix[0][i]==1: maxs=1 break for i in range(1,l): for j in range(1,w): if matrix[i][j]==1: diag=matrix[i-1][j-1] left=matrix[i][j-1] up=matrix[i-1][j] mins=min(diag,left,up) if mins!=0: matrix[i][j]=mins+1 maxs=max(mins+1,maxs) return maxs*maxs
''' There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? Example 1: Input: 2, [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: 2, [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. ''' def canFinish(numCourses,prerequisites): if not prerequisites: return True status=[1]*numCourses for i in prerequisites: status[i[0]]=0 cans=set() j=len(prerequisites) for i in range(numCourses): if status[i]: cans.add(i) l=len(cans) if l==0:return False _j=-1 print(cans) while not(l==0 or j==_j): _j=j _cans=set() i=0 while i<j: if prerequisites[i][1] in cans: _cans.add(prerequisites[i][0]) prerequisites[j-1],prerequisites[i]=prerequisites[i],prerequisites[j-1] j-=1 else: i+=1 i=0 cans=_cans l=len(cans) if j==0:return True return False a=[[1,0],[1,2],[0,1]]#False print(canFinish(3,a))
import numpy as np from matplotlib import pyplot as plt plt.style.use('seaborn') # x = np.arange(-5, 5, 0.01) # y = x ** 2 # # print(x) # # print(y) # plt.plot(x, y) # plt.xlabel("X-axis") # plt.ylabel("Y-axis") # plt.title('Simple 2d Plot') # plt.show() x = np.arange(0, 2 * np.pi, 0.1) y = np.cos(x) # plt.plot(x, y) # plt.xlabel("Angle in radian") # plt.ylabel("Value of Y") # plt.title("Curve of sinx") # plt.show()
import turtle def draw_art(): window = turtle.Screen() window.bgcolor("red") brad = turtle.Turtle() brad.shape("turtle") brad.color("yellow") brad.speed(1) n=4 m=0 while(m<n): brad.forward(100) brad.right(90) m=m+1 #brad.forward(100) #brad.right(90) #brad.forward(100) #brad.right(90) #brad.forward(100) #brad.right(90) angie = turtle.Turtle() angie.shape("turtle") angie.color("green") angie.circle(100) window.exitonclick() draw_art()
import random class Square: def __init__(self, row, col, game): self.is_mine = False self.is_revealed = False self.is_flagged = False self.neighboring_mines = 0 self.row = row self.col = col self.game = game self.neighbors = [] def find_neighbors(self): """ Calculates how many neighboring squares contain mines Adjusts class variable self.neighboring_mines to reflect this :return: None """ if self.is_mine: return row_inds = (self.row - 1, self.row, self.row + 1) col_inds = (self.col - 1, self.col, self.col + 1) for r in row_inds: for c in col_inds: if r < 0 or c < 0: continue try: if self.game[r][c].is_mine: self.neighboring_mines += 1 if not (r == self.row and c == self.col): self.neighbors.append(self.game[r][c]) except IndexError: continue def reveal(self): """ Reveals the square Will not reveal a flagged square Will not reveal an already revealed square Ends game if the square is a mine If square contains no neighboring mines (i.e. square is blank), reveals neighbors :return: None """ if self.is_flagged or self.is_revealed: return elif self.is_mine: self.is_revealed = True self.game.end_condition = True self.game.win = False # to be explicit that this is a loss return elif not self.neighboring_mines: # must reveal other squares as well self.is_revealed = True self.game.num_revealed += 1 self.game.updated_squares.append(self) for sq in self.neighbors: if not sq.is_revealed: sq.reveal() else: # no extra squares to be revealed self.is_revealed = True self.game.num_revealed += 1 self.game.updated_squares.append(self) def flag(self): """ Flags a square if it is not flagged, un-flags a square if it is flagged :return: None """ if not self.is_revealed and self.is_flagged: # Sqaure is alread flagged self.is_flagged = False self.game.num_flagged -= 1 self.game.updated_squares.append(self) elif not self.is_revealed and not self.is_flagged and (self.game.num_flagged < self.game.n_mines): # last condition in above --> make sure you have at least one flag left to give! self.is_flagged = True self.game.num_flagged += 1 self.game.updated_squares.append(self) def __str__(self): """ For printing the board properly in cmd :return: square's appropriate symbol """ if self.is_mine and self.is_revealed: return 'x' elif self.is_revealed: return str(self.neighboring_mines) elif self.is_flagged: return '^' else: return '@' class Game: def __init__(self, difficulty, nrows=None, ncols=None, n_mines=None): self.difficulties = {'beginner': (9, 9, 10), 'intermediate': (16, 16, 40), 'expert': (16, 30, 99), 'custom': (nrows, ncols, n_mines)} self.nrows, self.ncols, self.n_mines = self.difficulties[difficulty] self.board = [] self.num_revealed = 0 self.num_flagged = 0 self.updated_squares = [] self.end_condition = False self.win = False def make_game(self, row, col): self.create_board() self.place_mines(row, col) def create_board(self): """ Creates board of empty Square() objects in self.board self.board is an array of arrays, indexed by self.board[row][col] :return: nothing """ # will go as O(n^2) always for i in range(self.nrows): temp_row = [] for j in range(self.ncols): temp_row.append(Square(i, j, self)) self.board.append(temp_row) def place_mines(self, row, col): """ Randomly selects indices to place the n_mines mines, then places them. Also calculates square.neighboring_mines for each Square() in self.board. To ensure a mine is not clicked from the start and that the player has something to work with, the starting click and all neighbors are removed from the possible mine locations :param row: Initially-clicked square row :param col: Initially-clicked square column :return: """ rows = (row - 1, row, row + 1) cols = (col - 1, col, col + 1) no_mine_locs = () for i in rows: for j in cols: if not (i < 0 or j < 0): no_mine_locs += (i * self.ncols + j), sample_list = list(range(self.nrows * self.ncols)) for loc in no_mine_locs: try: sample_list.remove(loc) except ValueError: continue mine_locations = random.sample(sample_list, self.n_mines) for loc in mine_locations: row = loc // self.ncols col = loc % self.ncols self.board[row][col].is_mine = True for i in range(self.nrows): for j in range(self.ncols): self.board[i][j].find_neighbors() def check_win(self): """ Checks if a player has won :return: True if win, False else """ if (self.num_revealed == (self.nrows * self.ncols) - self.n_mines) and not self.end_condition: # second condition in case player has two squares left and clicks on the mine instead of the blank self.end_condition = True self.win = True if self.end_condition and self.win: return True else: return False def check_lose(self): """ Checks if a player has lost Note: this is necessary because it is possible to have neither won nor lost :return: True if loss, False else """ if self.end_condition and not self.win: return True else: return False def reveal(self, row, col): # alternatively, for Game obj x, could call x[row][col].reveal()... # UPDATE: apparently I did that a while ago and never commented about it! self.board[row][col].reveal(row, col) def __getitem__(self, key): return self.board[key] def __str__(self): final = '' for row in self.board: for sq in row: final += str(sq) + ' ' final += '\n' return final if __name__ == '__main__': print('~~~This is not the code you are looking for~~~')
import pdb import re from edge import Edge """ The Graph class works by maintaining a map where in the keys of the map are nodes and the values are lists of edges originating from that node. """ class Graph(): def __init__(self, edges=[]): self.graph_map = {} self.edges = [] """ populate edge list """ for edge in edges: self.edges.append(Edge(edge[0], edge[1], int(edge[2]))) """ populate graph map """ for edge in self.edges: if edge.start not in self.graph_map: self.graph_map[edge.start] = [] self.graph_map[edge.start].append(edge) elif edge.start in self.graph_map: self.graph_map[edge.start].append(edge) def get_edges(self): return self.edges def get_graph_map(self): return self.graph_map def compute_distance(self, route): """ compute the distance along a certain route """ if not re.match(r'^[A-Z](-[A-Z])*$', route): raise Exception("Invalid input route syntax") route_nodes = route.split('-') if not route_nodes: return 'NO SUCH ROUTE' curr_node = route_nodes[0] distance = 0; for target_node in route_nodes[1:]: """ check if edge exists from curr_node to target_node """ if self.graph_map[curr_node]: for edge in self.graph_map[curr_node]: if edge.end == target_node: distance += int(edge.weight) curr_node = target_node break # out of loop """ handle if edge to target_node not found """ if curr_node != target_node: return 'NO SUCH ROUTE' else: return 'NO SUCH ROUTE' return distance def depth_first_search(self, start, end, curr_route=[]): """ finds a route between two nodes """ if start not in self.graph_map or end not in self.graph_map: return curr_route curr_node = start edge_list = self.graph_map[curr_node] if not edge_list: return curr_route for edge in edge_list: if edge.end == end: curr_route.append(edge) return curr_route elif edge not in curr_route: curr_route.append(edge) curr_route = self.depth_first_search(edge.end, end, curr_route) return curr_route def find_all_routes(self, start, end, curr_route=[]): """ finds all routes between two nodes, no cycles allowed """ try: if start not in self.graph_map or end not in self.graph_map: return [] except Exception: print "Invalid input" raise if start == end and curr_route != []: return [curr_route] edge_list = self.graph_map[start] if not edge_list: return [curr_route] routes = [] for edge in edge_list: if edge not in curr_route: curr_route.append(edge) found_routes = self.find_all_routes(edge.end, end, list(curr_route)) for route in found_routes: routes.append(route) curr_route.pop() return routes def find_all_routes_with_cycles(self, start, end, curr_route=[], stops=None): """ finds all routes between two nodes with exactly stops number of stops, allowing cycles """ if not stops: return [] try: if start not in self.graph_map or end not in self.graph_map: return [] except Exception: print "Invalid input" raise if len(curr_route) > stops: return [] if start == end and curr_route != []: if len(curr_route) == stops: return [curr_route] edge_list = self.graph_map[start] if not edge_list: return [curr_route] routes = [] for edge in edge_list: curr_route.append(edge) found_routes = self.find_all_routes_with_cycles(edge.end, end, list(curr_route), stops) for route in found_routes: if route not in routes: routes.append(route) curr_route.pop() return routes def get_number_routes_with_max_stops(self, start, end, max_stops=None): """ the number of different routes between two nodes with a maximum of max_stops stops """ routes = [] for i in range(1, max_stops+1): found_routes = self.find_all_routes_with_cycles(start, end, [], i) if found_routes: for route in found_routes: if route: routes.append(route) return len(routes) def get_number_routes_with_exactly_stops(self, start, end, stops=None): """ the number of different routes between two nodes with exactly stops number of stops """ routes = [] routes = self.find_all_routes_with_cycles(start, end, [], stops) return len(routes) def find_length_shortest_route(self, start, end): """ finds the distance of the shortest route from start to end""" routes = self.find_all_routes(start, end) smallest = None for route in routes: route_distance = 0 for edge in route: edge_distance = int(edge.weight) route_distance += edge_distance if smallest: if smallest[1] > route_distance: smallest = (route, route_distance) else: smallest = (route, route_distance) if smallest: return smallest[1] else: return "NO SUCH ROUTE" def get_route_distance(self, route): """ returns the distance of a route """ if not route: return 0 route_distance = 0 for edge in route: route_distance += int(edge.weight) return route_distance def find_routes_with_distance(self, start, end, curr_route=[], distance=None): """ finds a route between two nodes with less than distance between them, allowing cycles """ routes = [] if start not in self.graph_map or end not in self.graph_map: return [] if self.get_route_distance(curr_route) > distance: return [] if start == end and curr_route != []: if self.get_route_distance(curr_route) == distance: pass elif self.get_route_distance(curr_route) < distance: routes.append(curr_route) edge_list = self.graph_map[start] if not edge_list: return [curr_route] for edge in edge_list: curr_route.append(edge) found_routes = self.find_routes_with_distance(edge.end, end, list(curr_route), distance) for route in found_routes: if route not in routes: routes.append(route) curr_route.pop() return routes def find_number_routes_with_distance(self, start, end, distance): """ finds the number of routes from start to end with distance less than distance """ routes = [] routes = self.find_routes_with_distance(start, end, [], distance) return len(routes) def main(): my_edge_list = ['AB5', 'BC4', 'CD8', 'DC8', 'DE6', 'AD5', 'CE2', 'EB3', 'AE7'] my_graph = Graph(my_edge_list) # print "Edges: {edges}".format(edges=my_graph.get_edges()) # print "Graph: {graph}".format(graph=my_graph.get_graph_map()) print "1. The distance of the route A-B-C..... {answer}".format(answer=my_graph.compute_distance("A-B-C")) print "2. The distance of the route A-D..... {answer}".format(answer=my_graph.compute_distance("A-D")) print "3. The distance of the route A-D-C..... {answer}".format(answer=my_graph.compute_distance("A-D-C")) print "4. The distance of the route A-E-B-C-D..... {answer}".format(answer=my_graph.compute_distance("A-E-B-C-D")) print "5. The distance of the route A-E-D..... {answer}".format(answer=my_graph.compute_distance("A-E-D")) print "6. The number of trips starting at C and ending at C with a maximum of 3 stops..... {answer}".format(answer=my_graph.get_number_routes_with_max_stops('C', 'C', 3)) print "7. The number of trips starting at A and ending at C with exactly 4 stops..... {answer}".format(answer=my_graph.get_number_routes_with_exactly_stops('A', 'C', 4)) print "8. The length of the shortest route (in terms of distance to travel) from A to C.....{answer}".format(answer=my_graph.find_length_shortest_route('A', 'C')) print "9. The length of the shortest route (in terms of distance to travel) from B to B.....{answer}".format(answer=my_graph.find_length_shortest_route('B', 'B')) print "10. The number of different routes from C to C with a distance of less than 30.....{answer}".format(answer=my_graph.find_number_routes_with_distance('C', 'C', 30)) if __name__ == "__main__": main()
#-*- coding:utf8 -*- __author__ = 'admin' # 应用: # # 典型的,函数在执行时,要带上所有必要的参数进行调用。 # # 然后,有时参数可以在函数被调用之前提前获知。 # # 这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。 def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return func(*(args + fargs), **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc # def A(*args,**kargs): # print args,kargs.get('d') # print A(1,2,3,4,5,65,6,7,7,a=3,b=5) def A(*args, **kargs): print args,kargs; A = partial(A,a="1",b='2'); A((1,2,3,4),b=4,c=5) A = partial(A,a="1",b='2'); A() def add(a, b): return a + b print add(4, 2) plus3 = partial(add,5) print plus3(4)
#!/usr/bin/evn python #-*- coding:utf-8 -*- __author__ = 'admin' #类静态变量 class Super: def __init__(self,x): self.key = x class Sub(Super): def __init__(self,x,y): Super.__init__(self,x) self.value = y super1 = Super('key') print super1.key sub = Sub('key','value') print sub.key print sub.value #一定要带object class A(object): def __init__(self,x=None): self.key = x class B(A): def __init__(self,x,y): super(B, self).__init__(x) self.value = y a = A('key') b = B('key1','value1') print a.key print b.key,b.value
#!/usr/bin/evn python #-*- coding:utf-8 -*- __author__ = 'admin' #类静态变量 class ShareData: spam = 3 x = ShareData() y = ShareData() print x.spam print y.spam print ShareData.spam ShareData.spam = 24 print x.spam print y.spam print ShareData.spam class ShareData: data = "spam" def __init__(self, value): self.data = value #this def display(self): print(self.data, ShareData.data) x1 = ShareData(1) x2 = ShareData(2) print x1.display() print x2.display()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by iFantastic on 15-2-14 __author__ = 'cluo' import urllib2 # map 这一小巧精致的函数是简捷实现 Python 程序并行化的关键。 # map 源于 Lisp 这类函数式编程语言。它可以通过一个序列实现两个函数之间的映射。 urls = ['http://www.yahoo.com', 'http://www.reddit.com'] results = map(urllib2.urlopen, urls) print results # 上面的这两行代码将 urls 这一序列中的每个元素作为参数传递到 urlopen 方法中, # 并将所有结果保存到 results 这一列表中。其结果大致相当于: results = [] for url in urls: results.append(urllib2.urlopen(url)) print results
class ElementId(object): """ The ElementId object is used as a unique identification for an element within a single project. ElementId(parameterId: BuiltInParameter) ElementId(categoryId: BuiltInCategory) ElementId(id: int) """ def Compare(self,id): """ Compare(self: ElementId,id: ElementId) -> int Compares two element ids. id: The ElementId to be compared with this ElementId. Returns: -1 if this element id is less than id,0 if equal,1 if greater. """ pass def Equals(self,obj): """ Equals(self: ElementId,obj: object) -> bool Determines whether the specified System.Object is equal to the current System.Object. obj: Another object. """ pass def GetHashCode(self): """ GetHashCode(self: ElementId) -> int Gets the integer value of the id as hash code """ pass def ToString(self): """ ToString(self: ElementId) -> str Gets a String representation of the integer value of the id. """ pass def __cmp__(self,*args): """ x.__cmp__(y) <==> cmp(x,y) """ pass def __eq__(self,*args): """ x.__eq__(y) <==> x==y """ pass def __ge__(self,*args): pass def __gt__(self,*args): pass def __le__(self,*args): pass def __lt__(self,*args): pass @staticmethod def __new__(self,*__args): """ __new__(cls: type,parameterId: BuiltInParameter) __new__(cls: type,categoryId: BuiltInCategory) __new__(cls: type,id: int) """ pass def __ne__(self,*args): pass IntegerValue=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides the value of the element id as an integer. Get: IntegerValue(self: ElementId) -> int """ InvalidElementId=None
class DigitGroupingSymbol(Enum,IComparable,IFormattable,IConvertible): """ The symbol used to separate groups of digits when numbers are formatted with digit grouping. enum DigitGroupingSymbol,values: Apostrophe (3),Comma (1),Dot (0),Space (2),Tick (3) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self,*args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self,*args): pass def __gt__(self,*args): pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self,*args): pass def __lt__(self,*args): pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass Apostrophe=None Comma=None Dot=None Space=None Tick=None value__=None
class Arc(object,IEquatable[Arc],IEpsilonComparable[Arc]): """ Represents the value of a plane,two angles and a radius in a subcurve of a three-dimensional circle. The curve is parameterized by an angle expressed in radians. For an IsValid arc the total subtended angle AngleRadians()=Domain()(1) - Domain()(0) must satisfy 0 < AngleRadians() < 2*PiThe parameterization of the Arc is inherited from the Circle it is derived from. In particulart -> center + cos(t)*radius*xaxis + sin(t)*radius*yaxiswhere xaxis and yaxis,(part of Circle.Plane) form an othonormal frame of the plane containing the circle. Arc(circle: Circle,angleRadians: float) Arc(circle: Circle,angleIntervalRadians: Interval) Arc(plane: Plane,radius: float,angleRadians: float) Arc(center: Point3d,radius: float,angleRadians: float) Arc(plane: Plane,center: Point3d,radius: float,angleRadians: float) Arc(startPoint: Point3d,pointOnInterior: Point3d,endPoint: Point3d) Arc(pointA: Point3d,tangentA: Vector3d,pointB: Point3d) """ def BoundingBox(self): """ BoundingBox(self: Arc) -> BoundingBox Computes the 3D axis aligned bounding box for this arc. Returns: Bounding box of arc. """ pass def ClosestParameter(self,testPoint): """ ClosestParameter(self: Arc,testPoint: Point3d) -> float Gets parameter on the arc closest to a test point. testPoint: Point to get close to. Returns: Parameter (in radians) of the point on the arc that is closest to the test point. If testPoint is the center of the arc,then the starting point of the arc is (arc.Domain()[0]) returned. If no parameter could be found, RhinoMath.UnsetValue is returned. """ pass def ClosestPoint(self,testPoint): """ ClosestPoint(self: Arc,testPoint: Point3d) -> Point3d Computes the point on an arc that is closest to a test point. testPoint: Point to get close to. Returns: The point on the arc that is closest to testPoint. If testPoint is the center of the arc,then the starting point of the arc is returned. UnsetPoint on failure. """ pass def EpsilonEquals(self,other,epsilon): """ EpsilonEquals(self: Arc,other: Arc,epsilon: float) -> bool Check that all values in other are within epsilon of the values in this """ pass def Equals(self,*__args): """ Equals(self: Arc,other: Arc) -> bool Determines whether another arc has the same value as this arc. other: An arc. Returns: true if obj is equal to this arc; otherwise false. Equals(self: Arc,obj: object) -> bool Determines whether another object is an arc and has the same value as this arc. obj: An object. Returns: true if obj is an arc and is exactly equal to this arc; otherwise false. """ pass def GetHashCode(self): """ GetHashCode(self: Arc) -> int Computes a hash code for the present arc. Returns: A non-unique integer that represents this arc. """ pass def PointAt(self,t): """ PointAt(self: Arc,t: float) -> Point3d Gets the point at the given arc parameter. t: Arc parameter to evaluate. Returns: The point at the given parameter. """ pass def Reverse(self): """ Reverse(self: Arc) Reverses the orientation of the arc. Changes the domain from [a,b] to [-b,-a]. """ pass def TangentAt(self,t): """ TangentAt(self: Arc,t: float) -> Vector3d Gets the tangent at the given parameter. t: Parameter of tangent to evaluate. Returns: The tangent at the arc at the given parameter. """ pass def ToNurbsCurve(self): """ ToNurbsCurve(self: Arc) -> NurbsCurve Initializes a nurbs curve representation of this arc. This amounts to the same as calling NurbsCurve.CreateFromArc(). Returns: A nurbs curve representation of this arc or null if no such representation could be made. """ pass def Transform(self,xform): """ Transform(self: Arc,xform: Transform) -> bool Transforms the arc using a Transformation matrix. xform: Transformations to apply. Note that arcs cannot handle non-euclidian transformations. Returns: true on success,false on failure. """ pass def Trim(self,domain): """ Trim(self: Arc,domain: Interval) -> bool Sets arc's angle domain (in radians) as a subdomain of the circle. domain: 0 < domain[1] - domain[0] <= 2.0 * RhinoMath.Pi. Returns: true on success,false on failure. """ pass def __eq__(self,*args): """ x.__eq__(y) <==> x==y """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,*__args): """ __new__[Arc]() -> Arc __new__(cls: type,circle: Circle,angleRadians: float) __new__(cls: type,circle: Circle,angleIntervalRadians: Interval) __new__(cls: type,plane: Plane,radius: float,angleRadians: float) __new__(cls: type,center: Point3d,radius: float,angleRadians: float) __new__(cls: type,plane: Plane,center: Point3d,radius: float,angleRadians: float) __new__(cls: type,startPoint: Point3d,pointOnInterior: Point3d,endPoint: Point3d) __new__(cls: type,pointA: Point3d,tangentA: Vector3d,pointB: Point3d) """ pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass def __str__(self,*args): pass Angle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the sweep -or subtended- angle (in Radians) for this arc segment. Get: Angle(self: Arc) -> float Set: Angle(self: Arc)=value """ AngleDegrees=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the sweep -or subtended- angle (in Radians) for this arc segment. Get: AngleDegrees(self: Arc) -> float Set: AngleDegrees(self: Arc)=value """ AngleDomain=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the angle domain (in Radians) of this arc. Get: AngleDomain(self: Arc) -> Interval Set: AngleDomain(self: Arc)=value """ Center=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the center point for this arc. Get: Center(self: Arc) -> Point3d Set: Center(self: Arc)=value """ Circumference=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the circumference of the circle that is coincident with this arc. Get: Circumference(self: Arc) -> float """ Diameter=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the Diameter of this arc. Get: Diameter(self: Arc) -> float Set: Diameter(self: Arc)=value """ EndAngle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the end angle (in Radians) for this arc segment. Get: EndAngle(self: Arc) -> float Set: EndAngle(self: Arc)=value """ EndAngleDegrees=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the end angle (in Radians) for this arc segment. Get: EndAngleDegrees(self: Arc) -> float Set: EndAngleDegrees(self: Arc)=value """ EndPoint=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the end point of the arc. Get: EndPoint(self: Arc) -> Point3d """ IsCircle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether or not this arc is a complete circle. Get: IsCircle(self: Arc) -> bool """ IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether or not this arc is valid. Detail: Radius>0 and 0<AngleRadians()<=2*Math.Pi. Get: IsValid(self: Arc) -> bool """ Length=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the length of the arc. (Length=Radius * (subtended angle in radians)). Get: Length(self: Arc) -> float """ MidPoint=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the mid-point of the arc. Get: MidPoint(self: Arc) -> Point3d """ Plane=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the plane in which this arc lies. Get: Plane(self: Arc) -> Plane Set: Plane(self: Arc)=value """ Radius=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the radius of this arc. Get: Radius(self: Arc) -> float Set: Radius(self: Arc)=value """ StartAngle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the start angle (in Radians) for this arc segment. Get: StartAngle(self: Arc) -> float Set: StartAngle(self: Arc)=value """ StartAngleDegrees=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the start angle (in Radians) for this arc segment. Get: StartAngleDegrees(self: Arc) -> float Set: StartAngleDegrees(self: Arc)=value """ StartPoint=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the start point of the arc. Get: StartPoint(self: Arc) -> Point3d """
#datos de entrada print("ingrsar el presio del producto:") pp=input() pp=float(pp) print("ingrasr la cantidad de unidades adquiridas:") ua=input() ua=int(ua) #proceso ic=pp*ua pd=0.10*ic sd=0.10*(ic-pd) dt=pd+sd ip=ic-dt #salida print("importe de la compra es:",ic) print("importe del descuento total es:",dt) print("importe a pagar es:",ip)
var1 = raw_input("Please input single character?") varLength=len(var1) print "the length or input variable -", var1, "is ", varLength if varLength > 1: print "False and it is not single character." elif varLength < 1: print "False and empty character is not acceptable." else: print "True and thanks."
## Class 10 Homework: Model Evaluation import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score from nltk import ConfusionMatrix #set headers for the dataframe headers = ['ID num', 'Ref Index', 'Sodium', 'Mag', 'Alum', 'Silicon', 'Potassium', 'Calcium', 'Barium', 'Iron', 'Type'] #read data from CSV into the dataframe glass_data = pd.read_csv('/Users/roellk/Desktop/Python/DAT4-students/david/glass.data', header=None, names=headers) glass_data.columns = headers #basic data exploration print 'type\n', "*"*10 print type(glass_data) print 'head\n', "*"*10 print glass_data.head() print 'shape\n', "*"*10 print glass_data.shape print 'describe\n', "*"*10 print glass_data.describe print 'dtypes\n', "*"*10 print glass_data.dtypes print 'values\n', "*"*10 print glass_data.values #add a binary column to the dataframe for holding glass types 1-4 and 5-7 glass_data['binary'] = 1 glass_data.loc[glass_data.Type.between(1, 4), 'binary'] = 0 glass_data.loc[glass_data.Type.between(5, 7), 'binary'] = 1 print glass_data.head() print glass_data.tail() #print glass_data[(glass_data.Type > 2) & (glass_data.Type < 7)] #part 2 X = glass_data[['Ref Index', 'Sodium', 'Mag', 'Alum', 'Silicon', 'Potassium', 'Calcium', 'Barium', 'Iron']] y = glass_data.binary #print X.shape #print y.shape #set up train test split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) #part 3 #fit the model LR = LogisticRegression() LR.fit(X_train, y_train) score = LR.score(X_test, y_test) print score, "model accuracy score" #score: 0.94444 #make predictions preds = LR.predict(X_test) print "Predictions for X_test\n", preds print "Actual y_test\n", y_test probs = LR.predict_proba(X_test) #print "probabilities for LR test\n", probs # predict in one step, calculate accuracy in a separate step from sklearn import metrics print "accuracy score\n", metrics.accuracy_score(y_test, preds) #null accuracy rate print "y_test mean\n", y_test.mean() #0.148148148148 print "1-y_test mean\n", 1-y_test.mean() #0.851851851852 print "ugly confusion matrix\n", metrics.confusion_matrix(y_test, preds) print "pretty confusion matrix\n", ConfusionMatrix(list(y_test), list(preds)) # predict probabilities probs = LR.predict_proba(X_test)[:, 1] plt.hist(probs) plt.show() # plot ROC curve fpr, tpr, thresholds = metrics.roc_curve(y_test, probs) plt.plot(fpr, tpr) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.xlabel('False Positive Rate (1 - Specificity)') plt.ylabel('True Positive Rate (Sensitivity)') plt.show() #calculate AUC print "AUC: ", metrics.roc_auc_score(y_test, probs) # part 4 #compare models LogReg, KNN-1, KNN-3 #Logistic Regression Model LR = LogisticRegression() print cross_val_score(LR, X, y, cv=3, scoring='roc_auc').mean() # AUC 0.939354 #KNN - 1 from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=1) print cross_val_score(knn, X, y, cv=3, scoring='roc_auc').mean() # AUC 0.821532 #KNN - 3 knn = KNeighborsClassifier(n_neighbors=3) print cross_val_score(knn, X, y, cv=3, scoring='roc_auc').mean() # AUC 0.879533 '''* Part 5 (Optional): * Explore the data to see if any features look like good predictors. * Use cross-validation to compare a model with a smaller set of features with your best model from Part 4. '''
x = int(input(" enter number 1 : ")) y = int(input(" enter number 2 : ")) z =int(input(" enter number 3 : ")) if (x < y + z) & (y < x + z) & (z < y + x): print("true ") else: print("false")
d = 6 r = input("press r to roll, q to quit:") if r == "r": print("you got:", d) d = 2 r = input("press r to roll, q to quit:") if r== "r": print("you got:", d) d = 3 r = input("press r to roll, q to quit:") if r== "r": print("you got:",d) d = 6 r = input("press r to roll, q to quit:") if r== "r": print("you got:",d) d = 2 r = input("press r to roll, q to quit:") if r== "r": print("you got:",d) d = 3 r = input("press r to roll, q to quit:") if r== "r": print("you got:",d) print("HURRAYYY! YOU WON THE GAME")
def function1(): n=int(input("Enter a number: ")) if n>0: print("the number is a positive number") elif n<0: print("the number is negative") elif n==0: print("the number is zero") function1()
n=int(input("Give a number:")) if n%2==1: print(n,"is an odd number.") else: print(n,"ia an even number.")
import pygame from model.CarregadorImagem import load_image class Wall(pygame.sprite.Sprite): """This class represents the bar at the bottom that the player controls """ def __init__(self, x, y, width, height): """ Constructor function """ # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # Make a BLUE wall, of the size specified in the parameters self.image, self.rect = load_image('view/img/wall.jpg') # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x
# Visualize the data # Here are the first 9 images in the training dataset. As you can see, label 1 is "dog" and label 0 is "cat". import matplotlib.pyplot as plt plt.figure(figsize=(10, 10)) for images, labels in train_ds.take(1): for i in range(9): ax = plt.subplot(3, 3, i + 1) plt.imshow(images[i].numpy().astype("uint8")) plt.title(int(labels[i])) plt.axis("off")
"""[ITC106 - Programming Principles] Assignment A4 by Gavin Eke """ #Variables #Program Metadata __author__ = "Gavin Eke" __version__ = "$Revision: 1.0 $" # Car Names car_name = ["Toyota Kluger","Nisson Patrol","Ford Territory"] number_of_cars = len(car_name) # Calculate Number of Cars based on list length # Configure Allowed Years Input year_earliest_allowed = 1900 year_oldest_allowed = 2100 # Global Statements welcome_message = "Aussie Best Car Software v1.0\n" invalid_data = "Please enter all data as numbers only, E.g. Type 30000 if you want $30,000" invalid_percent = "Please enter all data as decimal numbers only, E.g. Type 50.0 if you want %50" invalid_menuresponse = "\nInvalid Response, Please enter A to ADD, S to SEARCH or Q to QUIT" invalid_yearresponse = "\nInvalid Response, Year must be between %s and %s" invalid_response = "\nInvalid Response, Please enter Y for YES or N for NO" # Global Response List response_add = ["A","ADD"] response_search = ["S","SEARCH"] response_quit = ["Q","QUIT"] response_positive = ["Y","YES"] response_negative = ["N","NO"] # Database Information database = {} # Initialize dictionary database_filename = "sales.txt" # Choose the database txt file path # Open the database txt file and store the contents as database try: # Attempt to open the datebase file database_file = open(database_filename, 'r') # Open database txt file in read mode for line in database_file: # Store the contents of the database file in a dictionary database_line = line.strip('\n').split(', ') database[database_line[0]] = database_line[1:] database_file.close() # Close the database txt file except: # If the database can not be opened possible due to the file not existing print error and exit print("\nError: Failed to open database txt file. \nPlease make sure the file", database_filename, "exists and is in the same path as the program file. \nIf the program continues to produce this error please contact your System Administrator.") raise SystemExit(1) # Exit with code 1 failure # Display Welcome Message - Shown at the start of program launch print(welcome_message) #Functions # Main Function def main(): # Intentionally left blank print("\n") # Print new line to make it more pleasant on the eye # Main Menu Function - Performs the tasks choosen by the user in the main menu def mainMenu(main_menu_selection): if main_menu_selection in response_add: # If response is A do the following if yearrun in database: # If year is in database inform user print("\nDuplicate entry is not permitted") # Ask the user if they would like to search the datebase instead get_response = input("Would you like to use the data in the database instead (Y/N): ").upper() while not responseValidation(get_response): # Call responseValidation function to check that input is a valid response if not keep looping asking for valid input response print(invalid_response) get_response = input("Would you like to use the data in the database instead (Y/N): ").upper() # Perform actions as per users response if get_response in response_positive: print("\n") # Print new line to make it more pleasant on the eye mainMenu("S") # Call mainMenu function elif get_response in response_negative: main() # Call main function else: print("\nError: responseValidation function failed to catch invalid response. \nThis Error should have never occured please contact your System Administrator.") raise SystemExit(1) # Exit with code 1 failure else:# If year isn't in database do the following # Assignment A1 car_sellprice = getSellingPrice() # Call getSellingPrice function and store the return as car_sellprice car_carssold = getCarsSold() # Call getCarsSold function and store the return as car_carssold car_totalincome = calculateCarsSold(car_sellprice,car_carssold) # Call calculateCarsSold function and store the return as car_totalincome displayTotalIncome(car_totalincome) # Call displayTotalIncome # Assignment A2 awardbonus = abcAwardBonus(car_totalincome[3]) # Call abcAwardBonus function and store the return as awardbonus car_contribution = calculateCarContribution(car_totalincome,awardbonus) # Call calculateCarContribution function and store the return as car_contribution displayAwardBonus(awardbonus,car_contribution) # Call displayAwardBonus # Assignment A3 car_additionalbonusrate = getAdditionalBonusRate() # Call getAdditionalBonusRate function and store the return as car_additionalbonusrate car_additionalbonus = calculateAdditionalBonus(car_contribution,car_additionalbonusrate) # Call calculateAdditionalBonus function and store the return as car_additionalbonus displayAditionalBonus(car_additionalbonus) # Call displayAditionalBonus totalbonus = calculateTotalBonus(awardbonus,car_additionalbonus) # Call calculateTotalBonus function and store the return as totalbonus displayTotalBonus(totalbonus)# Call displayTotalBonus # Create Database Strings db = car_sellprice + car_carssold + car_additionalbonusrate dbstr = yearrun + ", " + db[0] + ", " + db[1] + ", " + db[2] + ", " + db[3] + ", " + db[4] + ", " + db[5] + ", " + db[6] + ", " + db[7] + ", " + db[8] + "\n" # Update Database and Dictionary database_file = open(database_filename, 'a') # Open database txt file in read mode database_file.write(dbstr) # Append the Database stirng to the database txt file database_file.close() # Close the database txt file database[yearrun] = db # Add the data to the dictionary elif main_menu_selection in response_search: # If response is S do the following if yearrun in database: # If year is in database do the following # Get car_sellprice, car_carssold and car_additionalbonusrate for the year entered and run the calculations db = database[yearrun] car_sellprice = db[0:3] car_carssold = db[3:6] car_additionalbonusrate = db[6:9] # Assignment A1 car_totalincome = calculateCarsSold(car_sellprice,car_carssold) # Call calculateCarsSold function and store the return as car_totalincome displayTotalIncome(car_totalincome) # Call displayTotalIncome # Assignment A2 awardbonus = abcAwardBonus(car_totalincome[3]) # Call abcAwardBonus function and store the return as awardbonus car_contribution = calculateCarContribution(car_totalincome,awardbonus) # Call calculateCarContribution function and store the return as car_contribution displayAwardBonus(awardbonus,car_contribution) # Call displayAwardBonus # Assignment A3 car_additionalbonus = calculateAdditionalBonus(car_contribution,car_additionalbonusrate) # Call calculateAdditionalBonus function and store the return as car_additionalbonus displayAditionalBonus(car_additionalbonus) # Call displayAditionalBonus totalbonus = calculateTotalBonus(awardbonus,car_additionalbonus) # Call calculateTotalBonus function and store the return as totalbonus displayTotalBonus(totalbonus)# Call displayTotalBonus else: # If year isn't in database inform user print("\n", yearrun, " is not in the databse.") # Ask the user if they would like to add the data to the datebase instead get_response = input("Would you like to add the data in the database instead (Y/N): ").upper() while not responseValidation(get_response): # Call responseValidation function to check that input is a valid response if not keep looping asking for valid input response print(invalid_response) get_response = input("Would you like to add the data in the database instead (Y/N): ").upper() # Perform actions as per users response if get_response in response_positive: print("\n") # Print new line to make it more pleasant on the eye mainMenu("A") # Call mainMenu function elif get_response in response_negative: main() # Call main function else: print("\nError: responseValidation function failed to catch invalid response. \nThis Error should have never occured please contact your System Administrator.") raise SystemExit(1) # Exit with code 1 failure else: # This should not be possible due to responseValidation but if it happens print error and quit print("\nError: menuValidation function failed to catch invalid response. \nThis Error should have never occured please contact your System Administrator.") raise SystemExit(1) # Exit with code 1 failure # Data Validation Function - Checks if input is an integer and >= 0 def dataValidation(data): try: # Attempts to turn the data into an integer int(data) except: # If it cannot turn the data into an integer return False return False if (int(data) >= 0): # Makes sure value is >= 0 and returns True if it does return True else: # If it is an integer but not >= 0 return False return False # Percent Validation Function - Checks if input is a float between 0 and 100 def percentValidation(data): try: # Attempts to turn the data into an float float(data) except: # If it cannot turn the data into a float return False return False if (float(data) >= 0) and (float(data) <= 100): # Makes sure value is between 0 and 100 and returns True if it does return True else: # If it is an float but not between 0 and 100 return False return False # Menu Validation Function - Checks if input is a valid response for the menu selction def menuValidation(data): if data in response_add or data in response_search or data in response_quit: # Returns True if data is in the response list return True else: # If value is not in list return False return False # Year Validation Function - Checks if input is an integer between the years in the configurable allowed years def yearValidation(data): try: # Attempts to turn the data into an integer int(data) except: # If it cannot turn the data into a integer return False return False if (int(data) >= int(year_earliest_allowed)) and (int(data) <= int(year_oldest_allowed)): # Returns True if data meets the conditions return True else: # If value does not meet the conditions return False return False # Response Validation Function - Checks if input is a valid response for positive or negative questions def responseValidation(data): if data in response_positive or data in response_negative: # Returns True if data is in the response list return True else: # If value is not in list return False return False # Get Selling Price Function - Gets the price of each car def getSellingPrice(): sellingprice = 'Please enter the selling price of the %s: ' invalidsellingprice = '\nInvalid Data, %s\nPlease enter the selling price of the %s: ' car_sellprice = [None] * number_of_cars # Create a list the length of the amount of cars for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 car_sellprice[iteration_count] = input(sellingprice % car_name[iteration_count]) while not dataValidation(car_sellprice[iteration_count]): # Call dataValidation function to check that input is an integer and is > 0 car_sellprice[iteration_count] = input(invalidsellingprice % (invalid_data, car_name[iteration_count])) # Inform user of invalid data and ask for input again print("\n") # Print new line to make it more pleasant on the eye return car_sellprice # Get Cars Sold Function - Gets the amount of cars sold def getCarsSold(): carssold = 'How many %s have been sold in %s?: ' invalidcarssold = '\nInvalid Data, %s\nHow many %s have been sold in %s?: ' car_carssold = [None] * number_of_cars # Create a list the length of the amount of cars for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 car_carssold[iteration_count] = input(carssold % (car_name[iteration_count], yearrun)) while not dataValidation(car_carssold[iteration_count]): # Call dataValidation function to check that input is an integer and is > 0 car_carssold[iteration_count] = input(invalidcarssold % (invalid_data, car_name[iteration_count], yearrun)) # Inform user of invalid data and ask for input again print("\n") # Print new line to make it more pleasant on the eye return car_carssold # Calculate Cars Sold Function - Calculates the total income of each car and the grand total def calculateCarsSold(car_sellprice,car_carssold): car_totalincome = [None] * (number_of_cars + 1) # Create a list the length of the amount of cars + 1 for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 car_totalincome[iteration_count] = int(car_sellprice[iteration_count]) * int(car_carssold[iteration_count]) car_totalincome[3] = car_totalincome[0] + car_totalincome[1] + car_totalincome[2] # Calculate the total income of all 3 cars and assign it to the 4th item on the list return car_totalincome # Display Total Income Function - Displays the grand total and the total income of each car def displayTotalIncome(abc_totalincome): totalincome = 'The total income of all cars for %s is $%s' print(totalincome % (yearrun, '{:0,d}'.format(abc_totalincome[3]))) print("\n") # Print new line to make it more pleasant on the eye carincome = 'The %s had a total income of $%s in %s' for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 print(carincome % (car_name[iteration_count], '{:0,d}'.format(abc_totalincome[iteration_count]), yearrun)) print("\n") # Print new line to make it more pleasant on the eye # ABC Award Bonus Function - Determines the total award that should be paid def abcAwardBonus(abc_totalincome): if abc_totalincome >= 0 and abc_totalincome <= 500000: # Calculate award bonus for abc_totalincome between 0 - 500000 awardbonus = abc_totalincome * 0.001 return awardbonus elif abc_totalincome >= 500001 and abc_totalincome <= 1000000: # Calculate award bonus for abc_totalincome between 500001 - 1000000 awardbonus = (abc_totalincome - 500000) * 0.002 + 500 return awardbonus elif abc_totalincome >= 1000001 and abc_totalincome <= 5000000: # Calculate award bonus for abc_totalincome between 1000001 - 5000000 awardbonus = (abc_totalincome - 1000000) * 0.003 + 1500 return awardbonus elif abc_totalincome >= 5000001 and abc_totalincome <= 10000000: # Calculate award bonus for abc_totalincome between 5000001 - 10000000 awardbonus = (abc_totalincome - 5000000) * 0.004 + 13500 return awardbonus elif abc_totalincome > 10000000: # Calculate award bonus for abc_totalincome over 10000000 awardbonus = (abc_totalincome - 10000000) * 0.005 + 33500 return awardbonus else: # This should not be possible due to dataValidation but if it happens print error and quit print("\nError: dataValidation function failed to catch invalid response. \nThis Error should have never occured please contact your System Administrator.") raise SystemExit(1) # Exit with code 1 failure # Calculate Car Contribution Function - Calculates the total award bonus and award bonus contributed by each car def calculateCarContribution(abc_totalincome,abc_awardbonus): car_contribution = [None] * number_of_cars # Create a list the length of the amount of cars for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 car_contribution[iteration_count] = abc_awardbonus * (abc_totalincome[iteration_count] / abc_totalincome[3]) # Calculate the % the car contributed towards the total award bonus return car_contribution # Display Award Bonus - Display the total award bonus and award bonus each car contributed def displayAwardBonus(abc_awardbonus,abc_contribution): # Display the total award bonus allcars_awardbonus = 'The total award bonus to be paid is $%s' print(allcars_awardbonus % '{:0,.2f}'.format(abc_awardbonus)) print("\n") # Print new line to make it more pleasant on the eye # Display the award bonus each car contributed # Individual car award bonus is total reward bonus * contribution % (Eg. Total = 1mil, npatrol = 50% then idvidual car contribution is 500k) eachcar_awardbonus = 'The %s contributed $%s towards the total award bonus' for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 print(eachcar_awardbonus % (car_name[iteration_count], '{:0,.2f}'.format(abc_contribution[iteration_count]))) print("\n") # Print new line to make it more pleasant on the eye # Get Additional Bonus Rate Function - Gets the additional bonus rate def getAdditionalBonusRate(): additionalbonusrate = 'Please enter the additional bonus rate of the %s: ' invalidadditionalbonusrate = '\nInvalid Data, %s\nPlease enter the additional bonus rate of the %s: ' car_additionalbonusrate = [None] * number_of_cars # Create a list the length of the amount of cars for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 car_additionalbonusrate[iteration_count] = input(additionalbonusrate % car_name[iteration_count]) while not percentValidation(car_additionalbonusrate[iteration_count]): # Call percentValidation function to check that input is valid car_additionalbonusrate[iteration_count] = input(invalidadditionalbonusrate % (invalid_percent, car_name[iteration_count])) # Inform user of invalid data and ask for input again print("\n") # Print new line to make it more pleasant on the eye return car_additionalbonusrate # Calculate Additional Bonus Function - Calculates the additional bonus that should be paid for each car def calculateAdditionalBonus(abc_contribution,abc_additionalbonusrate): car_additionalbonus = [None] * number_of_cars # Create a list the length of the amount of cars for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 car_additionalbonus[iteration_count] = abc_contribution[iteration_count] * (float(abc_additionalbonusrate[iteration_count]) / 100) # Calculate the % the car contributed towards the total award bonus return car_additionalbonus # Display Additional Bonus Function - Displays the additional bonus paid of each car def displayAditionalBonus(abc_additionalbonus): additionalbonus = 'The %s will pay an additional bonus of $%s for %s' for iteration_count in range(number_of_cars): # Loop through for each car and have variable interation_count as which interation number is currently running starting at 0 print(additionalbonus % (car_name[iteration_count], '{:0,.2f}'.format(abc_additionalbonus[iteration_count]), yearrun)) print("\n") # Print new line to make it more pleasant on the eye # Calculate Total Bonus Function - Calculates the grand total bonus (bonus award + additional bonus) def calculateTotalBonus(abc_awardbonus,abc_additionalbonus): totalbonus = abc_awardbonus + (abc_additionalbonus[0] + abc_additionalbonus[1] + abc_additionalbonus[2]) return totalbonus # Display Total Income Function - Displays the grand total and the total income of each car def displayTotalBonus(abc_totalbonus): grandtotalbonus = 'The grand total bonus to be paid for %s is $%s' print(grandtotalbonus % (yearrun, '{:0,.2f}'.format(abc_totalbonus))) print("\n") # Print new line to make it more pleasant on the eye #Run Program while True: # Keep running the program until the user decides to QUIT # Display the Main Menu of the program print("===========================================") print("Welcome to ABC Car Shop:") print("Please choose an option from the followings.") print("< A>dd sales details in the database.") print("< S>earch sales details for a given year in the database.") print("< Q>uit.") print("===========================================\n") # Ask the user for input to the menu menu_selection = input("Please enter your slection (A/S/Q): ").upper() while not menuValidation(menu_selection): # Call menuValidation function to check that input is a valid response if not keep looping asking for valid input response print(invalid_menuresponse) menu_selection = input("Please enter your slection (A/S/Q): ").upper() # Perform the action based on the users input if menu_selection in response_add: # Check if response is A yearrun = input("What year would you like to calculate the costs for (Eg. 2014): ") while not yearValidation(yearrun): # Call yearValidation function to check that input is a valid response if not keep looping asking for valid input response print(invalid_yearresponse % (year_earliest_allowed, year_oldest_allowed)) yearrun = input("What year would you like to calculate the costs for (Eg. 2014): ") mainMenu(menu_selection) elif menu_selection in response_search: # Check if response is S yearrun = input("What year would you like to calculate the costs for (Eg. 2014): ") while not yearValidation(yearrun): # Call yearValidation function to check that input is a valid response if not keep looping asking for valid input response print(invalid_yearresponse % (year_earliest_allowed, year_oldest_allowed)) yearrun = input("What year would you like to calculate the costs for (Eg. 2014): ") mainMenu(menu_selection) elif menu_selection in response_quit: # Check if response is Q print("Thank you for using", welcome_message) raise SystemExit(0) # Exit with code 0 successful else: # This should not be possible due to menuValidation but if it happens print error and quit print("\nError: menuValidation function failed to catch invalid response. \nThis Error should have never occured please contact your System Administrator.") raise SystemExit(1) # Exit with code 1 failure print("\n") # Print new line to make it more pleasant on the eye
# load the iris dataset import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap #import seaborn as sns from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # splitting X and y into training and testing sets from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # training the model on training set from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import ComplementNB # Gaussian Naive Bayes gnb = GaussianNB() gnb.fit(X_train, y_train) y_pred_gnb = gnb.predict(X_test) # Multinomial Naive Bayes mnb = MultinomialNB() mnb.fit(X, y) y_pred_mnb = mnb.predict(X_test) # Complement Naive Bayes cnb = ComplementNB() cnb.fit(X, y) y_pred_cnb = cnb.predict(X_test) # comparing actual response values (y_test) with predicted response values (y_pred) from sklearn import metrics print("Gaussian Naive Bayes model accuracy(in %):", metrics.accuracy_score(y_test, y_pred_gnb) * 100) print("Multinomial Naive Bayes model accuracy(in %):", metrics.accuracy_score(y_test, y_pred_mnb) * 100) print("Complement Naive Bayes model accuracy(in %):", metrics.accuracy_score(y_test, y_pred_cnb) * 100)
word = 'abcdefghij' print(word[:3] + word[3:]) """ it prints the whole word word[:3] => excludes the third index element and prints from 0 to 2 index word[3:] => prints the rest staring frm index 3 concatenation results in whole word """
""" circle """ from math import pi class circle(): def __init__(self,r=1): self.r=r def perimeter(self): return 2*pi*self.r def area(self): return pi*(self.r ** 2) if __name__ == "__main__": c = circle(int(input("Enter the radius of the circle"))) print("Area is {}".format(c.area())) print("Perimeter is {}".format(c.perimeter()))
""" iterate over dictionaries using for loops. """ dict={'1':1,'2':2,'3':3} for key,value in dict.items(): print(key,value)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def upside_down(root): res = root while res.left: res = res.left helper(root) return res def helper(root): if root.left: new_root = helper(root.left) new_root.left = root.right new_root.right = root root.left = None root.right = None return root
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def longestConsecutive(self, root): """ :type root: TreeNode :rtype: int """ # dfs self.maxlen = 0 self.dfs(root, 0) return self.maxlen def dfs(self, root, n): if not root: return self.maxlen = max(self.maxlen, n+1) if root.left and root.val + 1 == root.left.val: self.dfs(root.left, n+1) else: self.dfs(root.left, 0) if root.right and root.val + 1 == root.right.val: self.dfs(root.right, n+1) else: self.dfs(root.right, 0) if __name__ == '__main__': one = TreeNode(1) two = TreeNode(2) three = TreeNode(3) four = TreeNode(4) five = TreeNode(5) root = one root.right = three three.left = two three.right = four four.right = five s = Solution() assert s.longestConsecutive(root) == 3 one = TreeNode(1) two = TreeNode(2) three = TreeNode(3) two_two = TreeNode(2) root = two root.right = three three.left = two_two two_two.left = one assert s.longestConsecutive(root) == 2 assert s.longestConsecutive(None) == 0
def unique(list1): # insert the list to the set list_set = set(list1) # convert the set to the list unique_list = (list(list_set)) for x in unique_list: print(x) # driver code list1 = [10, 20, 10, 30, 40, 40] print("the unique values from 1st list is") unique(list1)
print("ALUMNOS Y EDADES") bandera=False numalumnos=0 contmax=0 mayores=[] lista=[] cont=0 contedad=1 contnombre=0 listaedades=[] listaedades2=[] max=0 suma=0 nombre=str(input("Escribe el nombre del alumno: ")) while nombre != "*": numalumnos=numalumnos+1 edad=int(input("Escribe la edad del alumno %s: " % nombre)) lista.append(nombre) lista.append(edad) nombre=str(input("Escribe el nombre del alumno: ")) print("La lista queda así: ",lista) for i in range(numalumnos): num=lista[contedad] suma=suma+num nombre=lista[contedad-1] contedad=contedad+2 if num > max: listaedades.append(nombre) max=num if num >= 18: mayores.append(nombre) mayores.append(num) contedad=1 suma=0 for i in range(numalumnos): num=lista[contedad] suma=suma+num nombre=lista[contedad-1] contedad=contedad+2 if num==max: listaedades2.append(nombre) contmax=contmax+1 #descomenta la linea de abajo para imprimir la lista de los mayores de edad #print(mayores) if mayores: print("los alumnos mayores de edad son: ") for i in range(len(mayores)//2): print(" -",mayores[cont], "con", mayores[cont+1], "años") cont=cont+2 else: print("No hay alumnos mayores de edad en esta clase") cont=0 if contmax<=1: print ("El alumno con más edad es:",listaedades[len(listaedades)-1]) else: print ("Los alumnos con más edad son: ",end="") edades=','.join(listaedades2) print(edades) print ("La media de los alumnos de la clase es %.2f" % (suma/numalumnos)) nombre=str(input("Escribe el alumno que quieres buscar: ")) for i in range(numalumnos): if nombre==lista[contnombre]: print(lista[contnombre],lista[contnombre+1],"años") contnombre=contnombre+2 bandera=True else: contnombre=contnombre+2 if not bandera: print("Ese alumno no se encuentra en nuestra base de datos.")
print("SUBCADENA") cad1=str(input("Escrbie una cadena: ")) cad2=str(input("Escrbie una segunda cadena: ")) if cad2 in cad1: print("La segunda cadena es una subcadena de la primera") else: print("La segunda cadena no es una subcadena de la primera")
print("MISMAS PALABRAS") num=int(input("¿Cuántas palabras quieres que tenga la primera lista?: ")) cont=1 lista1=[] lista2=[] encontrado=[] primera=[] segunda=[] contador=0 for i in range(num): palabra=str(input("Escribe la palabra %d: " % cont)) cont=cont+1 lista1.append(palabra) print("La primera lista es:", lista1) num=int(input("¿Cuántas palabras quieres que tenga la segunda lista?: ")) cont=1 for i in range(num): palabra=str(input("Escribe la palabra %d: " % cont)) cont=cont+1 lista2.append(palabra) print("La segunda lista es:", lista2) for i in lista1: if i in lista2: if i not in encontrado: encontrado.append(i) elif i not in lista2: if i not in primera: primera.append(i) for i in lista2: if i not in lista1: if i not in segunda: segunda.append(i) print("Palabras que aparecen en la 2 listas: ", encontrado) print("Palabras que aparecen solo en la primera lista: ", primera) print("Palabras que solo aparecen en la segunda lista: ", segunda) print("Todas las palabras: ", encontrado+primera+segunda)
print("SUBCADENA") cad=str(input("Escribe una cadena: ")) bool=False comprobar=cad.upper() for i in cad: if comprobar.count(i)>=2: bool=True if bool: print("La cadena '%s' tiene caracteres repetidos"%cad) else: print("La cadena '%s' NO contiene caracteres repetidos"%cad)
import unittest import shunting_yard as sy class TokenizeTest(unittest.TestCase): def test_single_operator(self): tokens = list(sy.tokenize('1+2')) self.assertListEqual(tokens, ['1', '+', '2']) def test_multiple_operators(self): tokens = list(sy.tokenize('1+2-3')) self.assertListEqual(tokens, ['1', '+', '2', '-', '3']) ''' IsOperatorTest tests the helper function 'isOperator(arg1)' in shunting_yard.py. 'isOperator(arg1)' should return true when testing the following math operators: (plus [+], minus [-], multiplication [*], and division operators [/]). ------------------------------------------------------------------------------------- :param: single string-character mathematics operator accepted. ''' class IsOperatorTest(unittest.TestCase): #Pass an operator def test_an_operator(self): isOperator = sy.isOperator('-') self.assertTrue(isOperator) #Pass a numeric character def test_non_operator(self): isOperator = sy.isOperator('0') self.assertFalse(isOperator) #Pass a string def test_a_string(self): with self.assertRaises(ValueError): sy.isOperator('21') #Pass an empty string def test_empty_char(self): with self.assertRaises(ValueError): sy.isOperator('') #Pass an integer type def test_wrong_input_type(self): with self.assertRaises(TypeError): sy.isOperator(1) ''' IsDigitTest tests the helper function 'isDigit(arg1)' in shunting_yard.py. 'isDigit(arg1)' should return true when testing for single-digit numeric characters. ------------------------------------------------------------------------------------- :param: single string-character digit accepted. ''' class IsDigitTest(unittest.TestCase): #Pass a single digit character. def test_single_digit(self): isDigit = sy.isDigit('0') self.assertTrue(isDigit) #Pass a multiple-digit character. def test_large_digit(self): with self.assertRaises(ValueError): sy.isDigit('666') #Pass a non-digit def test_non_digit(self): sy.isDigit('a') self.assertRaises(Exception) #Pass an empty char def test_empty_char(self): with self.assertRaises(ValueError): sy.isDigit('') #Pass an integer type def test_wrong_input_type(self): with self.assertRaises(TypeError): sy.isDigit(1) ''' IsLeftBracketTest tests the helper function 'isLeftBracket(arg1)' in shunting_yard.py. 'isLeftBracket(arg1)' should return true when testing for a single opening-bracket. Accepted opening brackets are: (left parenthesis [(], left square bracket [[]) ------------------------------------------------------------------------------------- :param: single character opening-bracket or opening-parenthesis accepted. ''' class IsLeftBracketTest(unittest.TestCase): #Pass a single opening bracket def test_single_left_bracket(self): self.assertTrue(sy.isLeftBracket('[')) #Pass a single closing parenthesis def test_single_right_parenthesis(self): self.assertFalse(sy.isLeftBracket(']')) #Pass a single closing bracket def test_single_right_bracket(self): self.assertFalse(sy.isLeftBracket(')')) #Pass multiple opening brackets def test_multiple_left_brackets(self): with self.assertRaises(ValueError): sy.isLeftBracket('[(') #Pass a non-opening bracket def test_non_left_bracket(self): self.assertFalse(sy.isLeftBracket('a')) #Pass an empty char def test_empty_char(self): with self.assertRaises(ValueError): sy.isLeftBracket('') #Pass an integer type def test_wrong_input_type(self): with self.assertRaises(TypeError): sy.isLeftBracket(1) ''' IsRightBracketTest tests the helper function 'isRightBracket(arg1)' in shunting_yard.py. 'isRightBracket(arg1)' should return true when testing for a single closing-bracket. Accepted closing brackets are: (right parenthesis [)], right square bracket []]) ------------------------------------------------------------------------------------- :param: single character closing-bracket or closing-parenthesis accepted. ''' class IsRightBracketTest(unittest.TestCase): #Pass a single closing bracket def test_single_right_bracket(self): self.assertTrue(sy.isRightBracket(']')) #Pass a single opening parenthesis def test_single_left_parenthesis(self): self.assertFalse(sy.isRightBracket('(')) #Pass a single opening bracket def test_single_left_bracket(self): self.assertFalse(sy.isRightBracket('[')) #Pass multiple closing brackets def test_multiple_right_brackets(self): with self.assertRaises(ValueError): sy.isRightBracket(')]') #Pass a non-closing bracket def test_non_left_bracket(self): self.assertFalse(sy.isRightBracket('a')) #Pass an empty char def test_empty_char(self): with self.assertRaises(ValueError): sy.isRightBracket('') #Pass an integer type def test_wrong_input_type(self): with self.assertRaises(TypeError): sy.isRightBracket(1) ''' IsNumberTest tests the helper function 'isNumber(arg1)' in shunting_yard.py. 'isNumber(arg1)' should return true if passed arguments are valid integer numbers. ------------------------------------------------------------------------------------- :param: single or multi-digit numbers string-characters accepted ''' class IsNumberTest(unittest.TestCase): #Pass a single digit def test_single_digit(self): self.assertTrue(sy.isNumber('0')) #Pass a large number def test_large_digit(self): self.assertTrue(sy.isNumber('420')) #Pass a non-digit def test_non_digit(self): self.assertFalse(sy.isNumber('A113')) #Pass an empty char def test_empty_char(self): with self.assertRaises(ValueError): sy.isNumber('') #Pass an integer type def test_wrong_input_type(self): with self.assertRaises(TypeError): sy.isNumber(1) ''' PeekAtStackTest tests the helper function 'peekAtStack(arg1)' in shunting_yard.py. 'peekAtStack(arg1)' should return a copy of the top-most (most recently added) item from the given stack, arg1. ------------------------------------------------------------------------------------- :param: python list ''' class PeekAtStackTest(unittest.TestCase): #Get the most recently added item from a stack containing already three items. def test_get_from_non_empty_stack(self): testStack = [] testStack.insert(0, 'WALL-E') testStack.insert(0, '2001: A Space Odyssey') testStack.insert(0, 'Monsters Inc.') mostRecentItem = sy.peekAtStack(testStack) self.assertEqual(mostRecentItem, 'Monsters Inc.', 'Top-most item not copied from stack') #Get the most recently added item from an empty stack. def test_get_from_empty_stack(self): testStack = [] with self.assertRaises(IndexError): sy.peekAtStack(testStack) #Send a wrong type into the arguments. def test_pass_wrong_arg(self): with self.assertRaises(TypeError): sy.peekAtStack('Hello, world!') ''' PopFromStackTest tests the helper function 'popFromStack(arg1)' in shunting_yard.py. 'popFromStack(arg1)' should remove and return the top-most (most recently added) item from the given stack, arg1. ------------------------------------------------------------------------------------- :param: python list ''' class PopFromStackTest(unittest.TestCase): #Pop the most recently added item from a stack containing already three items. def test_pop_from_non_empty_stack(self): testStack = [] testStack.insert(0, 'Things you should know for the exam: ') testStack.insert(0, 'Everything') testStack.insert(0, 'Everything + 1') self.assertEqual(sy.popFromStack(testStack), 'Everything + 1', 'Top-most item not copied from stack') self.assertEqual(len(testStack), 2, 'Top-most item not popped (removed) from stack') #Pop from an empty stack def test_pop_from_empty_stack(self): testStack = [] with self.assertRaises(IndexError): sy.popFromStack(testStack) #Send wrong type into arguments def test_pass_wrong_arg(self): with self.assertRaises(TypeError): sy.peekAtStack('Hello, World') ''' PushToStackTest tests the helper function 'pushToStack(arg1, arg2)' in shunting_yard.py. 'pushToStack(arg1, arg2)' should add an item to the top of the stack ------------------------------------------------------------------------------------- :param: python list ''' class PushToStackTest(unittest.TestCase): #Push (add) an item to an empty stack def test_push_to_empty_stack(self): testStack = [] sy.pushToStack(testStack, 'Quotes') self.assertEqual(len(testStack), 1, 'Stack does not contain 1 item.') #Push (add) an item to a non-empty stack def test_push_to_non_empty_stack(self): testStack = ['Minas Tirith', 'Minas Ithil', 'Barad-dûr'] sy.pushToStack(testStack, 'Isengard') self.assertEqual(len(testStack), 4, 'Stack does not contain 4 items') self.assertEqual(testStack[0], 'Isengard') self.assertEqual(testStack[1], 'Minas Tirith') #Pass wrong argument types def test_pass_wrong_arg(self): with self.assertRaises(AttributeError): sy.pushToStack(0, 'World') ''' StackIsEmptyTest tests the helper function 'stackIsEmpty(arg1)' in shunting_yard.py 'stackIsEmpty(arg1)' should return true if the stack is empty, and false otherwise. ------------------------------------------------------------------------------------- :param: python list ''' class StackIsEmptyTest(unittest.TestCase): #Test an empty stack def test_empty_stack(self): testStack = [] self.assertTrue(sy.stackIsEmpty(testStack)) #Test non-empty stack def test_non_empty_stack(self): testStack = ['definently not empty'] self.assertFalse(sy.stackIsEmpty(testStack)) #Send wrong types into arguments def test_pass_wrong_arg(self): testStack = [] with self.assertRaises(TypeError): sy.stackIsEmpty() with self.assertRaises(TypeError): sy.stackIsEmpty('')
# lambda аргументууд: илэрхийлэл x = lambda a: a*a for i in range(5, 7): print(x(i)) # Үр дүн: 25 # 36 # 2 аргументтай ламбда y = lambda a, b: a + b print(y(25, 30)) # 55 print(y(22.5, 100)) # 122.5 # lambda def evenOrOdd(x): return lambda x: x> 0 value = evenOrOdd(-5) print(value(-5)) # True value = evenOrOdd(5) print(value(5)) # False
# set үүсгэх colors = {'улаан', 'ногоон', 'шар'} print(colors) # {'улаан', 'шар', 'ногоон'} # давталт for x in colors: print(x) # ногоон # улаан # шар print('улаан' in colors) # True # add() colors.add('цэнхэр') print(colors) # {'шар', 'ногоон', 'цэнхэр', 'улаан'} # update() colors.update(['цагаан', 'ягаан']) print(colors) # {'ягаан', 'шар', 'цэнхэр', 'улаан', 'ногоон', 'цагаан'} # len() print(len(colors)) # 6 # remove() # устгахаас өмнө {'цагаан', 'ногоон', 'улаан', 'шар', 'ягаан', 'цэнхэр'} colors.remove('цагаан') print(colors) # устгасны дараа {'ногоон', 'улаан', 'шар', 'ягаан', 'цэнхэр'} # colors.remove('хар') # Алдаа заана # KeyError: 'хар' # discard() # устгахаас өмнө {'шар', 'улаан', 'ягаан', 'цэнхэр', 'ногоон'} colors.discard('шар') print(colors) # устгасны дараа {'ягаан', 'ногоон', 'цэнхэр', 'улаан'} colors.discard('хар') # алдаа заахгүй # pop() # устгахаас өмнө {'ягаан', 'ногоон', 'цэнхэр', 'улаан'} x = colors.pop() print(colors) # {'улаан', 'ногоон', 'ягаан'} print(x) # цэнхэр # clear() numbers = {5, 6, 7} numbers.clear() print(numbers) # set() # del numbers = {8, 6, 7} del numbers # union() set1 = {1, 5, 10} set2 = {'улаан', 'ногоон'} set3 = set1.union(set2) print(set3) # {1, 'ногоон', 5, 'улаан', 10} # update() set1.update(set2) print(set1) # {1, 5, 'улаан', 10, 'ногоон'} # давхардал sets = {1, 1, 2, 8} print(sets) # {8, 1, 2} print(len(sets)) # 3 # байгуулагч функц newset = set((5, 8, 'цагаан')) print(newset) # {8, 'цагаан', 5}
# list жагсаалт = ['элемент1', 'элемент2', 'элемент3'] print(жагсаалт) # ['элемент1', 'элемент2', 'элемент3'] newlist = list(('элемент1', 'элемент2')) print(newlist) # ['элемент1', 'элемент2'] weekdays = ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан'] print(weekdays[0]) # Даваа print(weekdays[4]) # Баасан print(weekdays[-1]) # Баасан print(weekdays[-3]) # Лхагва # индексийн муж newlist = weekdays[1:3] print(newlist) # ['Мягмар', 'Лхагва'] anotherlist = weekdays[-3:-1] print(anotherlist) # ['Лхагва', 'Пүрэв'] # элементийг өөрчлөх #weekdays[0] = 'Monday' #weekdays[3] = 'Thursday' print(weekdays) # ['Monday', 'Мягмар', 'Лхагва', 'Thursday', 'Баасан'] # жагсаалтын урт print(len(weekdays)) # 5 print(len(newlist)) # 2 # append() weekdays.append("Бямба") print(weekdays) # ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан', 'Бямба'] # insert() weekdays.insert(1, 'Monday') print(weekdays) # ['Даваа', 'Monday', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан', 'Бямба'] # remove() weekdays.remove('Monday') print(weekdays) # ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан', 'Бямба'] # pop() weekdays.pop(-1) print(weekdays) # ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан'] item = weekdays.pop() print(weekdays) # # ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв'] print(item) # Баасан # del keyword del weekdays[0] print(weekdays) # ['Мягмар', 'Лхагва', 'Пүрэв'] # delete whole list del weekdays #clear() weekends = ['Бямба', 'Ням'] weekends.clear() print(weekends) # [] # copy() days = ['Даваа', 'Мягмар', 'Лхагва'] newdaylist = days.copy() days.append('Пүрэв') print(days) # ['Даваа', 'Мягмар', 'Лхагва', 'Пүрэв'] print(newdaylist) # ['Даваа', 'Мягмар', 'Лхагва'] # list() anotherdaylist = list(newdaylist) newdaylist.append('Thursday') print(newdaylist) # ['Даваа', 'Мягмар', 'Лхагва', 'Thursday'] print(anotherdaylist) # ['Даваа', 'Мягмар', 'Лхагва'] # join + operator list1 = ['Monday'] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) # ['Monday', 1, 2, 3] # extend() list1 = ['Monday'] list2 = [1, 2, 3] list2.extend(list1) print(list2) # [1, 2, 3, 'Monday']
#! /usr/local/bin/python3 d = {'jcw':26, 'jxr': 10, 'yyr': 10} print('d["jcw"]:', d["jcw"]) print('d["yyr"]:', d.get("yyr")) d.pop("yyr") #print('d["yyr"]:', d["yyr"]) print('d["yyr"]:', d.get("yyr"))
#! /usr/local/bin/python3 def add_end(L = []): L.append("END") return L def add_end2(L = None): if L is None: L = [] L.append("END") return L
#! /usr/local/bin/python3 # -*- coding:utf-8 -*- class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer') if value < 0 or value > 100: raise ValueError('score must between 0 and 100') self._score = value def __init__(self, name): self.name = name def __str__(self): return 'Student object (name: %s)' % self.name __repr__ = __str__
b=int(input("ingrese el valor del angulo: ")) if b == 0: print("nulo") elif 0<b<90: print("agudo") elif b==90: print("recto") elif 90<b<180: print("obtuso") elif b==180: print("llano") elif 180<b>360: print("concavo") elif b==360: print("completo") else: print("no encontrado")
num = int(input("Please enter a Number")) list_d = [] for n in range(2,num+1): if num%n == 0: list_d.append(n) print(list_d)
from bs4 import BeautifulSoup import requests # It works but not complete Artical is there # html_url = "https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture" html_url = 'https://en.wikipedia.org/wiki/Salman_Khan' def download_html(url): r = requests.get(url) return r def prase_html(html): soap = BeautifulSoup(html.text,'html.parser') for story_heading in soap.find_all(['p']): print(story_heading.text) prase_html(download_html(html_url))
import random NUM_I=1 NUM_L=9 while True: print("Type 'exit' to quit application") random_number=random.randint(NUM_I,NUM_L+1) num =input("Guess a Number Shriman :) :\t") if num == 'exit': print("exiting now") break if int(num) > random_number: print("You guess too high ", random_number) elif int(num) < random_number: print("You guess to low", random_number) elif int(num) == random_number: print("Wow" , random_number)
#!/usr/bin/env python3 def climbing_stairs1(n): if n <= 2: return n else: return climbing_stairs1(n-1) + climbing_stairs1(n-2) def climbing_stairs2(n): num = [0, 1, 2] if n <= 2: return num[n] else: for i in range(3, n+1): num.append(num[i-1] + num[i-2]) return num[n] assert climbing_stairs1(1) == 1, 'Fail' assert climbing_stairs1(2) == 2, 'Fail' assert climbing_stairs1(3) == 3, 'Fail' assert climbing_stairs1(4) == 5, 'Fail' assert climbing_stairs1(5) == 8, 'Fail' assert climbing_stairs1(6) == 13, 'Fail' #assert climbing_stairs1(45) == 1836311903, 'Fail' assert climbing_stairs2(1) == 1, 'Fail' assert climbing_stairs2(2) == 2, 'Fail' assert climbing_stairs2(3) == 3, 'Fail' assert climbing_stairs2(4) == 5, 'Fail' assert climbing_stairs2(5) == 8, 'Fail' assert climbing_stairs2(6) == 13, 'Fail' assert climbing_stairs2(45) == 1836311903, 'Fail'
bilar = [] while True: menu = input("Val: ") if menu == "1": for l in bilar: print(l) elif menu == "2": bilen = {} bilen["brand"] = input("Brand: ") bilen["model"] = input("Model: ") bilen["year"] = input("Year: ") bilar.append(bilen) else: break
# 机器学习实战 学习记录 # Chapter 4 基于概率论的分类方法:朴素贝叶斯 # coding='UTF-8' ''' 优 点 :在数据较少的情况下仍然有效,可以处理多类别问题。 缺 点 :对于输入数据的准备方式较为敏感。 适用数据类型:标称型数据 ''' ''' 使用朴素贝叶斯进行文档分类 朴素:意味着两个假设: 1. 特征的独立性,对于文本来说即:一个特征或单词出现的可能性与其他单词没有关系 2. 每个特征同等重要 这两个假设实际中均存在问题,但实际效果不错 ''' # 从文本中构建词向量: # 考虑所有文档中出现的单词,决定将那些放入到词汇表中; # 将每篇文档转换为词汇表上的向量 # 简单的示例1:鱼分类 def loaddataset(): postinglist = [['my','dog','has','flea','problem','help','please'], ['maybe','not','take','him','to','dog','park','stupid'], ['my','dalmation','is','so','cute','I','love','him'], ['stop','posting','stupid','worthless','garbage'], ['mr','licks','ate','my','steak','how','to','stop','him'], ['guit','buying','worthless','dog','food','stupid']] classvec = [0,1,0,1,0,1] # 1 表示侮辱性文字,0 表示正常言论 return postinglist,classvec # 创建词汇表 def createvocablist(dataset): vocabset = set([]) #创建一个空集 for document in dataset: vocabset = vocabset | set(document) # 取并集 所有词不重复 return list(vocabset) # 集合不能以下标调用,需要将其转换为list # 将输入文档转换为词汇表上的向量 def set2vec(vocablist,inputset): inputvec = [0]*len(vocablist) #创建一个全为0的list for item in inputset: if item in vocablist: # 对于输入文本的每个词,检查其是否再字典中,若有,则把相应位置置1 inputvec[vocablist.index(item)] = 1 else: print('the word: #s is not in my vocabulary!' % (item)) return inputvec # postinglist,classvec = sz_c4.loaddataset() # vocabset = sz_c4.createvocablist(postinglist) # sz_c4.set2vec(vocabset,postinglist[0]) # 训练算法:从词向量计算概率 ''' 伪代码:?? 计算每个类别中的文档数目 对每篇训练文档: 对每个类别: 如果词条出现文档中―增加该词条的计数值 增加所有词条的计数值 对每个类别: 对每个词条: 将该词条的数目除以总词条数目得到条件概率 返回每个类别的条件概率 ''' from numpy import * def trainNB0(trainset,trainlabel): # 输入 已经映射到词汇表的训练样本,和训练样本对应的分类标签(标称型数值 0 1) numtraindoc = len(trainset) # 训练样本数量 numword = len(trainset[0]) # 词汇表长度 pc1 = sum(trainlabel)/float(numtraindoc) # 1对应类别的先验概率p(c1) 【针对二分类问题,多分类需要修改】 # p0num = zeros(numword) # 初始化,计算词汇表中每个词在两个类别中出现的次数-频率 # p1num = zeros(numword) p0num = ones(numword) #考虑到概率的乘积中若一个为0,则最后结果为0,因此所有词出现的次数初始化为1 p1num = ones(numword) p0denom = 2.0 # 分母初始化为2?这样所有概率相加和不等于1?? p1denom = 2.0 # 我觉得书上设置为2是错误的,应该是所有可取值的个数,即c1类别中出现的词条类型个数 for i in range(numtraindoc): if trainlabel[i] == 1: #判断每个文档属于哪个类别 p1num = p1num + trainset[i] #对于仅统计词条是否存在的模型,和 统计词条出现次数的模型 均适用 p1denom += sum(trainset[i]) else: p0num = p0num + trainset[i] p0denom += sum(trainset[i]) # p0vec = p0num/p0denom # p1vec = p1num/p1denom # p0vec = log(p0num/p0denom) #很多很小的数相乘会引起“下溢出”,因此取自然对数 # p1vec = log(p1num/p1denom) p0vec = log(p0num/sum(p0num)) p1vec = log(p1num/sum(p1num)) return p0vec,p1vec,pc1 ''' postinglist,classvec = sz_c4.loaddataset() vocabset = sz_c4.createvocablist(postinglist) trainset = [] for doc in postinglist: trainset.append(sz_c4.set2vec(vocabset,doc)) p0vec,p1vec,pc1 = sz_c4.trainNB0(trainset,classvec) ''' def classifynb(vec2classify,p0vec,p1vec,pc1): p0 = sum(vec2classify * p0vec)+log(1.0-pc1) p1 = sum(vec2classify * p1vec)+log(pc1) if p0>p1: return 0 else: return 1 ''' def testnb(): postinglist,classvec = loaddataset() vocabset = createvocablist(postinglist) trainset = [] for doc in postinglist: trainset.append(set2vec(vocabset,doc)) p0vec,p1vec,pc1 = trainNB0(trainset,classvec) testinput = ['love','my','dalmation'] testvec = set2vec(vocabset,testinput) print(testinput,'classified as:',classifynb(testvec,p0vec,p1vec,pc1)) testinput = ['stupid','garbage'] testvec = set2vec(vocabset,testinput) print(testinput,'classified as:',classifynb(testvec,p0vec,p1vec,pc1)) ''' ''' 一个词在文档中出现的次数在上述方法中没考虑; 考虑出现次数:“词袋模型” ''' def bagset2vec(vocablist,inputset): inputvec = [0]*len(vocablist) #创建一个全为0的list for item in inputset: if item in vocablist: # 对于输入文本的每个词,检查其是否再字典中,若有,则把相应位置置1 inputvec[vocablist.index(item)] += 1 else: print('the word: %s is not in my vocabulary!' % (item)) return inputvec ''' 示例2:使用朴素贝叶斯过滤垃圾邮件 ''' # 准备数据:切分文本,即将文档转换成词条 # 使用正则表达式切分文本; # 注意当文本中有URL、HTML等网址对象时,需要用更高级的过滤器来解析; # 文本解析是个复杂的过程,本例仅是极其简单的情况 def textparse(fulltext): import re # 正则表达式 temp = re.split(r'\W*',fulltext) return [tok.lower() for tok in temp if len(tok)>2] # 长度大于2 是考虑到URL和HTML中各种小字符串 def spamtest(): doclist=[]; classlist=[]; fulltext=[] # 每个文件夹中各有25份邮件 for i in range(1,26): #从1到25 # print(i) emailtext = open(r'.\email\ham\%d.txt' % (i)).read() wordlist = textparse(emailtext) #词条 doclist.append(wordlist) classlist.append(0) fulltext.extend(wordlist) # 用处? emailtext = open(r'.\email\spam\%d.txt' % (i)).read() wordlist = textparse(emailtext) #词条 doclist.append(wordlist) classlist.append(1) #1:垃圾邮件 fulltext.extend(wordlist) # 用处? vocablist = createvocablist(doclist) # 从共50份邮件中随机选取一部分构建训练集 和 测试集(10份) # 留存交叉验证 为了更精确地估计错误率,应该进行多次迭代求平均错误率 trainlist = list(range(50));testlist = [] for i in range(10): randindex = int(random.uniform(0,len(trainlist))) #随机产生训练集中的一个下标 testlist.append(trainlist[randindex]) del(trainlist[randindex]) trainset = []; trainclass = [] # 将各个词条转换成词汇表上的向量 for index in trainlist: trainset.append(set2vec(vocablist,doclist[index])) trainclass.append(classlist[index]) p0vec,p1vec,pc1 = trainNB0(trainset,trainclass) # 测试分类器,计算错误率 errorcount = 0 for index in testlist: classified = classifynb(set2vec(vocablist,doclist[index]),p0vec,p1vec,pc1) if classified != classlist[index]: errorcount += 1 print('error classified email:',doclist[index],'true class is:',classlist[index]) print('the error rate is: %f.' % (errorcount/float(len(testlist)))) return errorcount/float(len(testlist)) # 注意将垃圾邮件误判为正常邮件要比将正常邮件误判为垃圾邮件好,为避免错误,需要修正分类器——》第7章 ''' 示例3:使用朴素贝叶斯分类器从个人广告中获取区域倾向 ''' def calmostfreq(vocablist,fulltext): import operator freqdict = {} for word in vocablist: freqdict[word] = fulltext.count(word) #count list中word出现的次数 sortedfreq = sorted(freqdict.items(),key=operator.itemgetter(1),reverse=True) return sortedfreq[:30] def localword(feed1,feed0): import feedparser doclist = [];classlist=[];fulltext=[] minlen = min(len(feed0['entries']),len(feed1['entries'])) for i in range(minlen): wordlist = textparse(feed1['entries'][i]['summary']) # 类似于一份邮件的全部文本,然后解析成词条 doclist.append(wordlist) classlist.append(1) fulltext.extend(wordlist) wordlist = textparse(feed0['entries'][i]['summary']) # 类似于一份邮件的全部文本,然后解析成词条 doclist.append(wordlist) classlist.append(0) fulltext.extend(wordlist) vocablist = createvocablist(doclist) top30word = calmostfreq(vocablist,fulltext) #出现频次最高的30个词 及其 次数 【dict】 for pairw in top30word: if pairw[0] in vocablist: vocablist.remove(pairw[0]) # 从词汇表中去除这些高频词汇 ''' 移除高频词的原因:很多词汇是冗余和结构辅助性内容,很少的词会占用所有用词的很大比率。 除了移除高频词,还可以使用“停用词表”:从某个预定词表中移除结构上的辅助词 ''' # 随机抽出一部分作为训练集,一部分作为测试集 trainlist = list(range(2*minlen));testlist = [] for i in range(20): #20个作为测试集 randindex = int(random.uniform(0,len(trainlist))) testlist.append(trainlist[randindex]) #注意:trainset大小一直变化,其中存的数值不再等于变化后的下标 del(trainlist[randindex]) trainset = [];trainclass=[] for index in trainlist: trainset.append(bagset2vec(vocablist,doclist[index])) #这里使用词袋模型,即统计词条在一个文本中出现的次数 trainclass.append(classlist[index]) p0vec,p1vec,pc1 = trainNB0(trainset,trainclass) errorcount = 0 for index in testlist: classified = classifynb(bagset2vec(vocablist,doclist[index]),p0vec,p1vec,pc1) if classlist[index] != classified: errorcount += 1 print('the error rate is: %f' % (float(errorcount/len(testlist)))) return vocablist,p0vec,p1vec # ny = feedparser.parse('http://newyork.craigslist.org/stp/index.rss') # sf = feedparser.parse('http://sfbay.craigslist.org/stp/index.rss') # vocablist,psf,pny = sz_c4.localword(ny,sf) # 分析得到的两个地域的各词条使用频率数据,得到显示区域相关的用词 def gettopword(ny,sf): import operator vocablist,psf,pny = localword(ny,sf) topny = [];topsf=[] for i in range(len(psf)): if psf[i]>-6.0: topsf.append((vocablist[i],psf[i])) # 先选出概率大于一定值的词条 if pny[i]>-6.0: topny.append((vocablist[i],pny[i])) sortedsf = sorted(topsf,key = lambda pair:pair[1],reverse=True) # 再将词条按照频率排序,输出 # 注意key的使用:指示如何从要比较的对象中获得比较的标准,例如,从dict中获得值;从tuple中获得第二项等 # 指示的是获得的方式(即类似函数的形式),而不是具体的对象,如a[1] print('SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**') for item in sortedsf: print(item[0]) sortedny = sorted(topny,key = lambda pair:pair[1],reverse=True) print('NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**') for item in sortedny: print(item[0]) # ny = feedparser.parse('http://newyork.craigslist.org/stp/index.rss') # sf = feedparser.parse('http://sfbay.craigslist.org/stp/index.rss') # sz_c4.gettopword(ny,sf)
#abs() # print(abs(-5)) # max() 函数 :求最大值 max(数据) # lst = [2,1,6,3,4] # ret = max(lst) # print(ret) # lst2 = [-2,5,-8,3,6,1] # def abs(num): # if num>0: # return num # else: # return -1*num #求绝对值最大的数 -8 # ret = max(lst2,key=abs) #[2,5,8,3,6,1] # print(ret) #练习: # lst3 = [2,6,-10,50] #求相反数最大的数 -10 # def func(num): # return -1*num # ret = max(lst3,key=func) # print(ret) lst = [ {"name":"梁少天","age":20,"score":90}, {"name":"朱益锋","age":22,"score":95}, {"name":"魏春平","age":21,"score":97}, ] #返回年龄最大的那组信息 {"name":"朱益锋","age":22,"score":95} #返回分数最大的那组信息 {"name":"魏春平","age":21,"score":97} # def max_age(dic): # return dic["age"] # ret1 = max(lst,key=max_age) # print(ret1) # # def max_score(dic): # return dic["score"] # ret2 = max(lst,key=max_score) # print(ret2) # string = "abc1122aabdddccddwddd" # #使用max()函数找出出现次数最多的字符 # ret = max(string,key=string.count) # print(ret) # map(func,iterable) 函数,第一个参数是函数,第二个参数是可迭代对象。 # 函数会作用在可迭代内容的每一个元素上进行计算,返回一个新的可迭代内容 #求列表中每一个元素的平方 # lst3 = [1,2,3] # ret = [i*i for i in lst3] # print(ret) # def func(num): # return num**2 # ret = map(func,lst3) # print(ret) # # for i in ret: # # print(i,end=' ') # print(list(ret)) #求两个列表中元素相加的和 # lst1 = [1,2,3,4,5,6,7,8] # lst2 = [2,3,4,5,6] # def func(x,y): # return x+y # ret = map(func,lst1,lst2) # print(list(ret)) # filter(func,iterable) 函数:用于过滤序列,过滤不符合条件的元素, # 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进判 # 然后返回 True 或 False,最后将返回 True 的元素放到新列表中 # lst4 = [1,2,3,4,5,6,7,8,9] # #过滤列表中的所有奇数 # def func(num): # if num%2==0: # return True # else: # return False # return num%2==0 # return True if num%2==0 else False # ret = filter(func,lst4) # print(list(ret)) # zip 函数接受任意多个可迭代对象作为参:数,将对象中对应的元素打包成一个 tuple # 然后返回一个可迭代的 zip 对象zip() # lst1 = [1,2,3] # lst2 = [4,5,6] # #转换为(1,4),(2,5),(3,6) # ret = zip(lst1,lst2) # print(list(ret)) # str1 = "abc" # str2 = "12345" # ret = zip(str1,str2) # print(tuple(ret)) # 现有两个元组(('a'),('b')),(('c'),('d')),请生成[{'a':'c'},{'b':'d'}格式。 tup1 = ('a','b') tup2 = ('c','d') # def func(x,y): # return {x:y} # ret = map(func,tup1,tup2) # print(list(ret)) # def func(tup): # return {tup[0]:tup[1]} # ret = zip(tup1,tup2) # # print(tuple(ret)) # ret2 = map(func,ret) # print(list(ret2)) ret = list(map(lambda tup:{tup[0]:tup[1]},zip(tup1,tup2))) print(ret)
# 测试多线程的效率 在单线程中数 8 千万个数和在两个线程中分别数 8 千万个数, # 哪个效率更高?速度更快? import threading import time def func1(): start = time.time() for i in range(140000000): i+=1 end = time.time() print("func1-->total_time:{}".format(end-start)) # if __name__ == '__main__': # t1 = threading.Thread(target=func1) # t1.start() #5.49 def func2(): start = time.time() for i in range(70000000): i+=1 end = time.time() print("func2-->total_time:{}".format(end-start)) def func3(): start = time.time() for i in range(70000000): i+=1 end = time.time() print("func3-->total_time:{}".format(end-start)) # if __name__ == '__main__': # t2 = threading.Thread(target=func2) # t3 = threading.Thread(target=func3) # t2.start() # t3.start() #5.51 #使用多进程数8千万个数 import multiprocessing if __name__ == '__main__': p1 = multiprocessing.Process(target=func2) p2 = multiprocessing.Process(target=func3) p1.start() p2.start()
# 重命名文件 os.rename(旧文件名,新文件名) import os # # os.rename("demo_02/1.txt","demo_02/111.txt") # os.rename("demo_02/2.txt","222.txt") # 2.删除文件 os.remove(文件名) #删除demo_02/3.txt # os.remove("demo_02/3.txt") # 3.创建单层目录 os.mkdir(目录名) #创建test1目录 # os.mkdir("test1") # 创建多级目录 os.makedirs(目录名) # os.makedirs("a/b/c/d") # 删除单层目录 os.rmdir(目录名) # os.rmdir("test1") # 删除多级目录 os.removedirs(目录名) # os.removedirs("a/b/c/d") # .获取当前所在目录 os.getcwd() # print(os.getcwd()) #获取的是绝对路径 # 6.获取目录列表 os.listdir(path) # print(os.listdir("E:\python0421\day13\code")) # 7.切换所在目录 os.chdir() # print(os.getcwd()) # os.chdir("a/b") # # print(os.getcwd()) # with open("222.txt","w")as file: # file.write("hello world") # 判断文件或文件夹是否存在 os.path.exists() # print(os.path.exists("222.txt")) # print(os.path.exists("a")) # 9.判断是否是文件 os.path.isfile() # print(os.path.isfile("222.txt")) # print(os.path.isfile("a")) # 10.判断是否是目录 os.path.isdir() # print(os.path.isdir("222.txt")) # print(os.path.isdir("a")) # #获取绝对路径 os.path.abspath() # print(os.path.abspath("222.txt")) # # # 获取路径中的最后部分 # print(os.path.basename("222.txt")) # print(os.path.basename(r"E:\python0421\day13\code\222.txt")) # # #判断是否是绝对路径 os.path.isabs() # print(os.path.isabs("222.txt")) # print(os.path.isabs(r"E:\python0421\day13\code\222.txt")) # # #获取文件所在目录,os.path.dirname # print(os.getcwd()) # print(os.path.dirname(r"E:\python0421\day13\code\a\b\11.txt")) # print(os.path.dirname(r"E:\python0421\day13\code\a\b")) #文件定位 tell() # with open("222.txt","r") as f: # with open("222.txt","a") as f: # print(f.tell()) #seek(offset,whence) offset偏移量,whence定位(0文件开头,1定位不变,2文件结尾) with open("222.txt","r") as f: print(f.tell()) f.seek(2,0) print(f.tell()) print(f.read())
class Shopping: instance = None #记录创建的对象,None说明是第一次创建对象 has_init = False #记录是否进行过初始化 def __new__(cls, *args, **kwargs): #第一次调用new方法,创建对象并记录 #第2-n次调用new方式时,不创建对象,而是直接放回记录的对象 #判断是否是第一次创建对象 if cls.instance==None: cls.instance = object.__new__(cls) return cls.instance def __init__(self): #单例模式只创建一个对象,所以初始化页应该只执行一次 if self.has_init==False: #没有进行过初始化 self.total_price = 31.8 self.has_init=True
# set1 = {3,2,6,4,1,3,6} # # set1 = {3,2,6,4,1,3,6,[2]} #集合中的元素只能是不可变类型 # print(set1) #去除列表中重复的元素 # lst = [1,2,2,3,3,5,6,3] # print(set(lst)) #集合增加 # set1 = {1,2} # # # set1.add(3) # # set2 = {2,3} # # set1.update(set2) # set1.clear() # print(set1) # print(dir(set1)) # lst = [1,2] # help(lst.remove) #集合数学运算 # set1 = {1,2,3,4,5} # set2 = {4,5,6,7,8} #取交集 # print(set1&set2) #{4, 5} # print(set1.intersection(set2)) #取并集 # print(set1|set2) # print(set1.union(set2)) #取差集 #取set1中有,但是set2中没有的元素 # print(set1-set2) # print(set1.difference(set2)) #反交集 # print(set1^set2) # print(set1.symmetric_difference(set2)) # set1 = {1,2,3,4,5} # set2 = {4,5} #判断是否是子集 # print(set1<set2) # print(set1.issubset(set2)) #判断是否是超集 # print(set1>set2) # print(set1.issuperset(set2))
# 函数的相互调用和嵌套. #相互调用 # def func1(): # print("--before func1--") # print("--after func1--") # # def func2(): # print("--before func2--") # func1() # print("--after func2--") # func2() #嵌套 # 在函数中又定义函数 def func1(): print("func1..") def func2(): print("func2...") func2() func1()
#下班太晚,和女朋友说一万次对不起 # print("对不起!") #相同或者相似的事情可以用循环解决 # num = 1 # while num<=10000: # print("对不起!-",num) # num+=1 #输出1-10之间的数字 # num = 1 # while num<=10: # print(num,end=' ') # num+=1 #售票:一个窗口一天售出10张票,卖完下班 # ticket = 10 # while ticket>0: # print("卖出一张票:",ticket,"号票") # ticket-=1 #循环从控制台输入5个数,输出最大值 # a, b, c, d, e = 1, 5, 3, 2, 4 # max_num = a # if max_num<b: # max_num = b # if max_num<c: # max_num = c # if max_num<d: # max_num = d # if max_num<e: # max_num = e # print(max_num) count = 1 max_num = False while count<=5: num = int(input("请输入数字:")) if count==1: #第一次输入 max_num = num else: if max_num<num: max_num=num count+=1 print(max_num)
#增加 lst = ["张伟强","刘江","徐伟明","刘伟超"] #在列表尾部增加 “梁国赞”append lst.append("梁国赞") # print(lst) #extend # lst2 = ["梁国赞","张威"] # lst.extend(lst2) # print(lst) # lst = ["张伟强","刘江","徐伟明","刘伟超"] #insert #将"梁国赞"插入到“刘江”的前面 # lst.insert(1,"梁国赞") # print(lst) #将"梁国赞"插入到“刘伟超”的前面 # lst.insert(-1,"梁国赞") # print(lst) #将"梁国赞"插入到“刘伟超”的后面 # lst.insert(5,"梁国赞") # print(lst) #删除 #pop() # lst = ["张伟强","刘江","徐伟明","刘伟超"] #删除 刘江 # lst.pop(1) # ret = lst.pop() # print(ret) # print(lst) # remove() # lst = ["张伟强","刘江","徐伟明","刘伟超","刘江"] #删除刘江 # lst.remove("刘江") # print(lst) #clear() # lst.clear() # print(lst) #del #删除列表 # del lst # print(lst) #删除刘江 # del lst[1] # print(lst) #修改 # lst = ["张伟强","刘江","徐伟明","刘伟超","刘江"] #将"张伟强"修改为"小张" # lst[0] = "小张" # print(lst) #reverse # lst.reverse() # print(lst) #sort # lst = [4,6,1,3,5] # lst.sort() # lst.sort(reverse=True) # #从大到小排序 # print(lst) # sorted() # lst2 = sorted(lst) # lst2 = sorted(lst,reverse=True) # print(lst) # print(lst2) #A:65,a:97 # lst = ['a','c','b'] # lst.sort() # print(lst) # lst = ['abc',"ABC","aBe"] #step1:先比较每个字符串的第一个字符的ascii码值 # "abc"-->"a" 97 # "ABC"-->"A" 65 # "aBe"-->"a" 97 #得出 "ABC"最小 #step1:再比较"abc"和"aBe"的第二个字符的ascii码值 # "abc"-->"b" 98 # "aBe"-->"B" 66 #得出"aBe"<"abc" #最终:"ABC"<"aBe"<"abc" # lst.sort() # print(lst) # lst = ['a','3','1','e','5','b'] # lst.sort() # print(lst) #查找 # lst = [1,2,3,7,2,6,2,3,2] # #查看2出现的次数 # # print(lst.count(2)) # #查看2的索引 # print(lst.index(2)) # print(lst.index(3)) #注意:列表不可以一边遍历,一边删除 # lst = [1,2,2,2,5,6,7,2,9] #将列表中的2全部删除 # for i in lst: # if i==2: # lst.remove(i) # print(lst) # new_lst = [] # for i in lst: # if i!=2: # new_lst.append(i) # print(new_lst) # lst_2 = [] #将所有的2存起来 # for i in lst: # if i==2: # lst_2.append(i) # for j in lst_2: # lst.remove(j) # print(lst) #列表嵌套 # lst = [[1,2,3],[4,5,6],[7,8,9]] #取出3 # print(lst[0][2]) #取出1,4,7 # for i in lst: # print(i[0]) #len()函数 # lst = [[1,2,3],[4,5,6],[7,8,9]] # print(len(lst)) #练习 #取出1,5,9 # lst = [[1,2,3],[4,5,6],[7,8,9]] # print(len(range(5))) # print(range(len(lst))) #列表的长度比最大索引大1 # for i in range(len(lst)): # print(lst[i][i]) #创建一个空列表,循环生成5个10以内的数字,添加到列表中 #查询列表中是否有元素3,如果有,删除该元素 import random lst = [] for i in range(5): ret = random.randint(0,3) if ret!=3: lst.append(ret) print(lst)
# 1.将字符串‘my name is zhangWeiqiang’中的每个单词输出一样,要求单词首字母大写效果如下 # content = "my name is zhangqeiqiang" #My Name Is Zhangweiqiang # content = "my name is zhangqeiqiang" # new_content = content.title() # print(new_content) # 2.判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 # num = input("请输入一个整数:") # if num.isdigit(): # if num==num[::-1]: # print("是回文数") # else: # print("不是回文数") # else: # print("不是回文数") # 3.键盘接收传入的字符串,统计大写字母的个数、小写字母的个数、数字的个数、其它字符的个数 # content = "I'm Zhang,18 years old" # upper_count = 0 # lower_count = 0 # digit_count = 0 # other_count = 0 # for i in content: # if i.isupper(): # upper_count+=1 # elif i.islower(): # lower_count+=1 # elif i.isdigit(): # digit_count+=1 # else: # other_count+=1 # print("大写字母:%d,小写字母:%d,数字:%d,其它字符:%d" # %(upper_count,lower_count,digit_count,other_count)) # 4.句子反转 # 给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, # 单词之间只有一个空格,前后没有空格。 # 比如: (1) “hello xiao mi”-> “mi xiao hello” # content = "hello xiao mi" # lst = content.split(' ') # lst.reverse() # print(lst) # string = "" # for i in lst: # string=string+i+' ' # print(string.strip()) #join()方法:可以将列表中的字符串拼接起来 # 格式: 拼接字符.join(列表) # lst = ["a","b","c"] # a*b*c # ret = "*".join(lst) # print(ret) content = "hello xiao mi" lst = content.split(" ")[::-1] ret = " ".join(lst) print(ret) # 5.完成学生管理系统 # 开头文档写出 普通用户、课程的保存方式 """ 学生选课系统 时间: 版本: 作者: """ # 管理员 事先设置好管理员账号密码 # 管理员功能: # 查看有哪些课程,Python,java,web,unity,UI # 增加或删除课程内容,增加 软件测试课程,删除UI课程 # 用户 # 注册 :用户名和密码注册,没有注册过用户的才可以注册成功 # 登录 :用户名和密码登录,登录成功进入选课界面 # 修改登录密码:输入旧密码,再输入新密码 # 查看:查看已选的课程 # 选课程:进行选课,选完课记录下来,下次查看可以看到 #保存课程内容 course_lst = ["Python","java","web","unity","UI"] #保存用户 user_dic = {"zhang":{"name":"zhang","pwd":"123","course":[]}} Administrator = {"name":"admin","pwd":"admin"} while True: print("欢迎学生选课主界面") print("~*" * 15) print(" 1.用户注册 ") print(" 2.用户登录 ") print(" 3.管理员登录 ") print(" 4.退出系统 ") print("~*" * 15) choose = input("请输入功能选项:") if choose=="1": print("欢迎来到注册界面!") name = input("请输入注册用户名:") pwd = input("请输入注册密码:") #判断用户名是否已存在,已存在则不允许注册 if name not in user_dic: #用户名不存在 user_dic[name] = {"name":name,"pwd":pwd,"course":[]} input("注册成功,按任意键继续。。。") else:#用户名已存在 input("用户名已存在,按任意键继续。。。") elif choose=="2": flag = 0 print("欢迎来到登录界面!") name: str = input("请输入登录用户名:") pwd = input("请输入登录密码:") if name in user_dic: #说明登录名在保存的user_dic中 #用户名和密码匹配 if name==user_dic[name]["name"] and pwd==user_dic[name]["pwd"]: print("登录成功") flag=1 else: print("密码错误") else: print("用户名不存在") #登录成功,走下面的代码 if flag: while True: print("欢迎来到选课界面!") print(" 1.查看选课 ") print(" 2.进入选课 ") print(" 3.修改密码 ") print(" 4.返回上一级 ") choose = input("请输入功能选项:") # 查看已有的选课 if choose == "1": if user_dic[name]["course"]: print("已选的课程:",user_dic[name]["course"]) input("按任意键继续。。。") else: input("没有选中任何课程,按任意键继续。。。") #进入选课 elif choose == "2": print("请选择课程:") for i,j in enumerate(course_lst,1): print("%s:%s"%(i,j)) choose = int(input("请输入课程编号:")) #用户输入编号在范围内 if 1<=choose<=len(course_lst): #取出课程 course = course_lst[choose-1] #如果已经选过此课程 if course in user_dic[name]["course"]: print("已选过此课程") input("按任意键继续。。。") else: user_dic[name]["course"].append(course) print("选课成功,您选择的课程是:%s"%course) input("按任意键继续。。。") else: print("编号不在范围内。。。") input("按任意键继续。。。") elif choose == "3": pwd_error = 0 while True: print("欢迎进入修改密码界面!") old_pwd = input("请输入旧密码:") #判断旧密码是否正确 if old_pwd==user_dic[name]["pwd"]: pwd = input("请输入新密码:") pwd2 = input("请确认新密码:") if pwd==pwd2: user_dic[name]["pwd"] = pwd input("修改成功,按任意键继续。。") break else: input("两次密码不一致,请重新输入,按任意键继续。。") else: if pwd_error >= 3: input("输入错误次数过多,已退出,按任意键继续") break input("密码有误,请重新输入,按任意键继续。。") pwd_error+=1 elif choose == "4": break else: input("输入有误,请重新输入,按任意键继续。。。") elif choose=="3": flag = 0 print("欢迎来到管理员界面") name = input("请输入管理员用户名:") pwd = input("请输入管理员密码:") if name==Administrator["name"] and pwd==Administrator["pwd"]: print("登录成功") flag = 1 if flag: while True: print("1.查看课程") print("2.增加课程") print("3.删除课程") print("4.返回上一级") choose = input("请输入功能选项:") if choose=="1": print("欢迎来到查看课程界面") print("目前有以下课程") for i in range(len(course_lst)): print("{} : {}".format(i+1,course_lst[i])) input("按任意键继续。。。。") elif choose=="2": print("欢迎来到增加课程界面") course_name = input("请输入要增加的课程名称:") if course_name in course_lst: input("课程已存在,请勿重复添加") else: course_lst.append(course_name) input("课程添加成功,按任意键继续") elif choose=="3": print("欢迎来到删除课程界面") print({i+1:course_lst[i] for i in range(len(course_lst))}) num = int(input("请输入要删除的课程编号:")) if 1<=num<=len(course_lst): ret = course_lst.pop(num-1) input("删除%s成功,按任意键继续"%ret) else: print("输入编号有误,无法删除,按任意键继续。。。") elif choose=="4": break elif choose=="4": print("已退出!") break else: input("输入有误,请重新输入,按任意键继续。。。")
# def func(): # a = 1 # print("内部a的值:",a) # func() # print("外部a的值:",a) # def func(): # a = 1 # print("内部a的值:",a) # return a # # # print(func()) # a = func() # print("外部a的值:",a) #可以返回多个数据 def func(): a = 1 b = 2 return a,b # print(func()) a,b = func() print(a,b)
# 注意:先完成课堂讲解案例,再尽量完成下列练习 # # 1.输入一个考试分数,判断考试结果是否为通过,如果分数>= 60,通过, # 否则,结果为不通过(使用双分支和三元条件表达式各做一遍) # score = int(input("请输入一个分数:")) # # if score>=60: # # print("通过") # # else: # # print("不通过") # ret = "通过" if score>=60 else "不通过" # print(ret) # 2.求1-100之间所有偶数的和 # num = 1 # sum_num = 0 # while num<=100: # if num%2==0: # sum_num+=num # num+=1 # print(sum_num) # num = 2 # sum_num = 0 # while num<=100: # sum_num+=num # num+=2 # print(sum_num) # 3.计算100到200范围内能被7或者9整除但不能同时被这两者整除的数的个数。 # num = 100 # count = 0 # while num<=200: # if (num%7==0 or num%9==0) and num%63!=0: # # print(num,end=' ') # count+=1 # num+=1 # print(count) # 4.50到70之间偶数的平均值 # num = 50 # count = 0 # sum_num = 0 # while num<=70: # sum_num+=num # count+=1 # num+=2 # print(sum_num/count) # 5.输出100-200范围内的所有质数 # num = 100 # while num<=200: # i = 2 # while i < num: # if num % i == 0: # break # i += 1 # else: # print(num,end=' ') # num+=1 # 6.2019年 中国GDP:15.54万亿美元 美国GDP:21.41万亿美元 # 假设未来一段时间中国GDP增长率6.1%,美国增长率2%,问在哪一年中国GDP超越美国? #100 #第二天增长10% #第二天的营业额:100*0.1+100 100*(1+0.1) #中国GDP增长:15.54*(1+0.061) #美国GDP增长:21.41*(1+0.02) # China_gdp = 15.54 # America_gdp = 21.41 # year = 2019 # while China_gdp<America_gdp: # China_gdp*=(1+0.061) # America_gdp*=(1+0.02) # year+=1 # print(year) # 7.一个球从100米高度自由落下,每次落地后弹回原来高度的一半, # 求它在第10次落地前,离地多高,第10次落地时共经过多少米? # 1 2 3 4 #h 100 50 25 12.5 #s 100 200 250 275 # h = 100 # s = 100 # count = 1 #第一次落地 # while count<100: # h /=2 # s = s+h*2 # count+=1 # print(h,s) # 8.输入一个整数,分解质因数,如输入8,输出 2 2 2 # 输入30 ,输出2 3 5 # n = 8 #将n除以2,如果可以整除,n = n/2,即8/2=4, 将4除以2,如果可以整除,n = n/2,即4/2=2.。。 #将30除以2,如果可以整除,n = n/2,即30/2=15, 将15除以2,不能整除,则除数自增变为2+1=3,将15除以3.。。 n = 6 i = 2 while n>1: if n%i==0: n/=i print(i,end=' ') else: i+=1 # 9.完善昨天最后一题,购物商城项目菜单跳转、商城项目内测用户登录 # 完善游戏的页面跳转和上下级菜单切换
# - L-->local(函数内部) 局部作用域 # - E-->Enclosing 嵌套作用域 # - G-->Global 全局作用域 # - B--built-in 內建作用域 # name = "张伟强" # def outter(): # name = "张威" # def inner(): # # name = "刘江" # print(name) # inner() # outter() #1.调用自己内部inner的name #2.注释掉name = "刘江",调用父函数中的name # 3.注释掉name = "张威",调用全局name, # - 模块(model),类(class),函数(def、lambda)会产生新的作用域 # - 条件语句(if...else...),循环语句(while....,for....) # for i in range(10): # num = 5 # print(num) # if 10>=5: # num=20 # print(num) # # def func(): # lst = [1,2] #产生新的作用域,出了函数就无法使用 # func() # print(lst) # - global 关键字可以将局部变量变成一个全局变量 格式: global 变量名称 # - nonlocal 关键字可以修改外层(非全局)变量 # name = "张伟强" # lst = [10] # def func(): # name = "刘江" # lst.append(20) # print("内部:",name) # func() # print("外部:",name) # print(lst) # name = "张伟强" # def func(): # global name #声明全局变量 # name = "刘江" # print("内部:",name) # func() # print("外部:",name) #修改嵌套中的name name = "徐伟明" def func1(): name = "张伟强" def func2(): #在func2中修改name = "张伟强" nonlocal name name = "刘江" func2() print("嵌套:",name) func1() print("全局:",name)
#向控制台输出3,2,1 def out_num(num): """功能:。。""" if num==0: return print(num) num-=1 out_num(num) out_num(3)
""" 综合案例:管理员管理课程 - 管理员,添加课程,查看课程 ,删除课程,修改课程 - 分析 - 数据类Date - 属性:课程数据courses_dict,以字典形式保存,类属性 - 用户类User - 属性:用户名,密码,昵称,邮箱,电话 - 管理员类Admin - 属性:继承用户类 - 方法:添加课程add_course,调用课程保存的方法 ​ 查看课程check_course,调用数据库类属性 ​ 修改课程update_course,调用课程修改的方法 ​ 删除课程delete_course,调用课程删除的方法 - 课程类Course: - 属性:名称,老师,人数限制,课时,学分,课程描述 - 方法:保存课程 ​ 修改课程 ​ 删除课程 ​ 打印课程信息 """ #数据类型 class Data: """数据类型""" courses_dict = {} #键:课程名称,值:课程对象 class User: """用户类型""" def __init__(self,username,password,nickname,email,phone): """初始化属性""" self.username = username self.password = password self.nickname = nickname self.email = email self.phone = phone class Admin(User): """管理员类""" def add_course(self): """添加课程""" name = input("请输入增加的课程名称:") if name in Data.courses_dict: print("课程已存在,请使用其他课程名称") return self.add_course() teacher = input("请输入授课老师:") limit = input("请输入人数:") times = input("请输入课程时长:") score = input("请输入分数:") des = input("请输入课程描述:") #创建课程对象 course = Course(name,teacher,limit,times,score,des) #保存课程数据 course.save() def check_course(self): """查看课程""" for name,course in Data.courses_dict.items(): print(f"课程名称:{name},老师:{course.teacher},课程描述:{course.des}") input("课程查看完成,按任意键继续") def update_course(self): """修改课程""" name = input("请输入需要修改的课程名称:") if name not in Data.courses_dict: print("课程不存在,请重新输入") return self.update_course() #课程存在,获取课程对象 course = Data.courses_dict[name] course.update() input("课程修改完成,按任意键继续。。") def delete_course(self): """删除课程""" name = input("请输入需要删除的课程名称:") if name not in Data.courses_dict: print("课程不存在,请重新输入") return self.delete_course() #获取课程对象 course = Data.courses_dict.get(name) course.delete_course() input("课程删除完成,按任意键继续。。") class Course: def __init__(self,name,teacher,limit,times,score,des): self.name = name self.teacher = teacher self.limit = limit self.times = times self.score = score self.des = des def save(self): """保存课程数据""" Data.courses_dict[self.name] = self def update(self): """修改课程""" self.teacher = input("请输入修改后的授课老师:") self.limit = input("请输入修改后的人数:") self.times = input("请输入修改后的课时:") self.score = input("请输入修改后的分数:") self.des = input("请输入修改后的课程描述:") self.save() def delete_course(self): """删除课程""" Data.courses_dict.pop(self.name) admin = Admin("韩老师","123","韩老师","[email protected]","12138") admin.add_course() admin.check_course() admin.update_course() admin.check_course() admin.delete_course() admin.check_course()
'''功能选项''' #登录前选项输入 def zhuce_xuanxiang(): while True: choose = input("请输入您的选项:") if choose == "1": pass elif choose == "2": pass elif choose == "3": pass else: print("您的输入有误!!!按任意键继续>>>") #商品分类 def fenlei_xuanxiang(): while True: choose = input("请输入您的选项:") if choose == "1": pass elif choose == "2": pass elif choose == "3": pass elif choose == "4": pass else: print("您的输入有误!!!按任意键继续>>>") #游戏选择 def youxi_xuanxiang(): while True: choose = input("请输入您的选项:") if choose == "1": pass elif choose == "2": pass elif choose == "3": pass else: print("您的输入有误!!!按任意键继续>>>") #美食选择 def meishi_xuanxiang(): while True: choose = input("请输入您的选项:") if choose == "1": pass elif choose == "2": pass elif choose == "3": pass else: print("您的输入有误!!!按任意键继续>>>") #登录后选项页 def denlu_xuanxiang(): while True: choose = input("请输入您的选项:") if choose == "1": pass elif choose == "2": pass elif choose == "3": pass elif choose == "4": pass elif choose == "5": pass else: print("您的输入有误!!!按任意键继续>>>")
# #定义人类:可以跳舞,可以玩,在玩的过程中跳舞 # #实现多态:老年人跳广场舞 # class Person: # """人的类型""" # # def dance(self): # print("跳舞") # # def play(self): # self.dance() # # class OldMan(Person): # """老年人类型""" # def dance(self): # print("跳广场舞") # # # per1 = Person() # # per1.play() # old = OldMan() # old.play() # - 网站类 # - 方法:注册方法,调用默认设备发送验证码 # - 设备类 # - 方法:生成验证码并发送 # class WebSite: # """网站类型""" # def register(self,device): # print("开始注册用户。。。") # #调用设备发送验证码的方法 # device.send("6666") # input("验证码已发送,请输入:") # print("注册成功") # # class Device: # """设备类型""" # def send(self,code): # print("默认发送验证码:",code) # # #用户注册 # ws = WebSite() # device = Device() # #发起注册 # ws.register(device) # 实现多态,用不同的设备注册网站,就使用相应的设备发送验证码 class WebSite: """网站类型""" def register(self,device): print("开始注册用户。。。") #调用设备发送验证码的方法 device.send("6666") input("验证码已发送,请输入:") print("注册成功") class Device: """设备类型""" def send(self,code): print("默认发送验证码:",code) class Phone(Device): """手机注册""" def send(self,code): print("通过手机发送验证码:",code) class Email: """邮箱注册""" def send(self, code): print("通过邮箱发送验证码:", code) #用户注册 ws = WebSite() # device = Device() phone = Phone() #发起注册 ws.register(phone)
#单分支 #判断一个人是否可以去网吧 #如果大于等于18岁,可以去 # age = 15 # if age>=18: # print("可以去网吧") # print("一天过去了!") #双分支 #判断一个人是否可以去网吧 #如果大于等于18岁,可以去,否则回家写作业 # age = 15 # if age>=18: # print("可以去网吧嗨皮!") # else: #else中不写条件语句 # print("回家写作业!") # print("一天过去了!") #判断一个人是否可以去网吧 #如果大于等于18岁,并且是男生,可以去,否则回家写作业 # age = 19 # gender = 0 # if age>=18 and gender==1: # print("可以去网吧嗨皮!") # else: # print("回家写作业!") # print("一天过去了!") # 案例操作:给贵妃熬粥的需求 #贵妃在一定条件下得分,另外一种条件被下毒 # import random #随机一定范围内的整数 # # # print(random.randint(1,10)) # score = 20 # x = random.randint(1,10) # print(x) # if x>6: # print("粥被人下毒了。。") # print("贵妃身亡") # else: # print("贵妃身体无恙,可以继续在宫中享受") # print("加5分") # score+=5 # print(score) #多分支 #需求:节日给女朋友送礼物 #情人节,送鲜花 #端午节:发红包 #国庆节:出去旅游 #其他:多喝热水 # holiday = input("请输入节日:") # if holiday=="情人节": # print("送鲜花") # elif holiday=="端午节": # print("发红包") # elif holiday=="国庆节": # print("出去旅游") # else: # print("多喝热水") # 分支嵌套 #需求:买火车票回家,如果有火车票,可以进站,没有不可以进站 #进站后检查行李,如果刀具长度小于18cm,可以上火车,否则不可以上火车 has_ticket = input("请问是否有火车票(有/1,没有/0)") if has_ticket=="0" or has_ticket=="1": if has_ticket=="1": print("可以进站!") knife = float(input("请输入刀具长度:")) if knife<18: print("可上火车!") else: print("刀太长,无法带上火车") else: print("没有票,无法进站") else: print("输入有误,终止操作!")
from cs50 import get_int def main(): # Get user input for height while True: h = get_int("Height: ") if 1 <= h <= 8: break # Print lines for i in range(h): space(h - i - 1) sign(i + 1) space(2) sign(i + 1) print() # Print spaces def space(n): for _ in range(n): print(" ", end="") return # Print spaces def sign(n): for _ in range(n): print("#", end="") return if __name__ == "__main__": main()
def hex_output(hex_humber): decimal_number = 0 for index, digit in enumerate(reversed(hex_humber)): decimal_number += int(digit, 16) * 16**index return decimal_number print(hex_output("123"))
# !/usr/bin/env python # encoding: utf-8 """ This is an implementation of Prim's algorithm, as found in: Skiena, Steven. The Algorithm Design Manual, 2nd ed. London: Springer-Verlag, 2008. -------------------------------------------- Prim's algorithm: Select an arbitrary vertex to start while (there are fringe vertices) select minimum-weight edge between tree and fringe add the selected edge and vertex to the tree update the cost to all affected fringe vertices -------------------------------------------- """ import numpy as np import argparse import sys import math def check_args(args=None): parser = argparse.ArgumentParser(description='Finds minimum spanning tree for adjacency matrix m') parser.add_argument('-m', '--matrix', help='adjacency matrix m', required=True) results = parser.parse_args(args) return results def neighbors(m, n): """ Returns a list of neighbors of node n in adjacency matrix m. """ return [x for x in range(len(m)) if m[n][x] != 0] def minimum_spanning_tree_prim(m): """ Given an adjacency matrix m, will return the MST. Args: m (numpy.ndarray) : adjacency matrix representation of the graph Returns: mst (list): List of edges in the MST """ cost = {x: math.inf for x in range(len(m))} parent = {x: None for x in range(len(m))} # Vertex 0 will be the root cost[0] = 0 unseen = list(range(len(m))) mst = [] while unseen: curr = min(unseen, key=cost.__getitem__) unseen.remove(curr) if parent[curr] is not None: mst.append((curr, parent[curr])) for nb in neighbors(m, curr): if nb in unseen and m[curr][nb] < cost[nb]: parent[nb] = curr cost[nb] = m[curr][nb] return mst if __name__ == '__main__': # Get command line arguments args = check_args(sys.argv[1:]) # Load adjacency matrix m = np.load(args.matrix) mst = minimum_spanning_tree_prim(m) cost = sum([m[x][y] for x, y in mst]) print('MST edges for matrix m: {}'.format([(x+1, y+1) for x,y in list(mst)])) print('cost: {}'.format(cost))
import numpy as np import matplotlib.pyplot as plt import util class Model: def __init__(self, layers, in_size, units, weight_init_range, bias_init_range=None, nonlins=None, loss="MSE", lr=0.001, decay_rate=0, normalization=None, name="Basic NN Model"): """ :param layers: number of layers in the network, not including input layer (must be at least one) :param in_size: number of inputs in the input layer :param units: np array of output units in each layer of the network, including input layer :param weight_init_range: support over which weights will be uniformly sampled from at initialization :param nonlins: (list of strings) list of non-linearities applied to each layer: 'linear', 'relu', 'sigmoid', 'tanh', 'softmax' :param loss: loss function, options: "MSE", "CrossEntropy" :param lr: (float) learning rate for gradient descent :param normalization: normalization for the loss: options "NSE" (normalized square error), None :param name: (string) name of model """ self.layers = layers self.units = units self.net = [] self.activations = [] self.deltas = [] self.in_size = in_size self.activation_in = np.zeros(in_size) # list of non-linearities for each layer other than the input layer # options: 'linear', 'sigmoid', 'tanh', 'relu', 'softmax' # defaults to linear layer self.nonlin_names = nonlins self.nonlins = [] self.nonlins_backward = [] self.loss_name = loss self.loss = util.lib_losses[loss] self.loss_backward = util.lib_losses_backward[loss] self.weight_init_range = weight_init_range self.lr = lr self.decay_rate = decay_rate self.weights = [] self.biases = [] self.bias_init_range = bias_init_range if bias_init_range is not None: self.have_bias = True else: self.have_bias = False self.train_loss = [] self.normalization = normalization self.name = name # initialize weights self.weights.append(np.random.rand(self.units[0], self.in_size) * (self.weight_init_range[1] - self.weight_init_range[0]) + self.weight_init_range[0]) for idx in range(1, layers): self.weights.append(np.random.rand(self.units[idx], self.units[idx - 1]) * (self.weight_init_range[1] - self.weight_init_range[0]) + self.weight_init_range[0]) # initialize biases # set biases to zero, even if not in use for idx in range(self.layers): self.biases.append(np.zeros(self.units[idx])) # set biases if in use if self.have_bias: for idx in range(self.layers): self.biases[idx] = np.random.rand(self.units[idx]) * \ (self.bias_init_range[1] - self.bias_init_range[0]) + self.bias_init_range[0] for idx in range(layers): self.net.append(np.zeros((self.units[idx], 1))) self.activations.append(np.zeros((self.units[idx], 1))) self.deltas.append(np.zeros((self.units[idx], 1))) if self.nonlin_names is None: self.nonlins.append(util.lib_nonlins['linear']) self.nonlins_backward.append(util.lib_nonlins_backward['linear']) else: self.nonlins.append(util.lib_nonlins[self.nonlin_names[idx]]) self.nonlins_backward.append(util.lib_nonlins_backward[self.nonlin_names[idx]]) # train steps taken self.steps = 0 # train batches taken self.batch_steps = 0 def forward(self, x): """ :param self: :param x: input as np array :return: feedforward output as np array all layer activations stored in self.activations """ # input layer self.activation_in = np.expand_dims(x, 1) # self.activation_in = x self.net[0] = np.matrix(self.weights[0]@self.activation_in + np.expand_dims(self.biases[0], 1)) self.activations[0] = np.matrix(self.nonlins[0](self.net[0])) # feedforward through hidden and output layers for idx in range(1, self.layers): self.net[idx] = self.weights[idx]@self.activations[idx-1] + np.expand_dims(self.biases[idx], 1) self.activations[idx] = np.matrix(self.nonlins[idx](self.net[idx])) return self.activations[-1] def get_grad(self, y, y_hat): grad = [np.zeros(self.weights[layer].shape) for layer in range(self.layers)] dL_dout = self.loss_backward(y, y_hat) if self.nonlin_names[-1] == "softmax": self.deltas[-1] = self.nonlins_backward[-1](self.activations[-1], dL_dout) else: self.deltas[-1] = np.matrix(np.asarray(dL_dout) * np.asarray(self.nonlins_backward[-1](self.activations[-1]))) grad[-1] = self.deltas[-1] @ self.activations[-2].T for idx in range(self.layers - 2, 0, -1): self.deltas[idx] = (self.weights[idx + 1].T @ self.deltas[idx + 1]) * self.nonlins_backward[idx](self.activations[idx]) grad[idx] = self.deltas[idx] @ self.activations[idx - 1].T self.deltas[0] = np.matrix(np.asarray(self.weights[1].T @ self.deltas[1]) * np.asarray(self.nonlins_backward[0](self.activations[0]))) grad[0] = self.deltas[0] @ self.activation_in.T # bias derivatives if self.have_bias: for idx in range(self.layers): grad.append(self.deltas[idx]) test1 = np.asarray(self.nonlins_backward[-1](self.activations[-1])) return grad def optimizer(self, grad): for idx in range(self.layers): self.weights[idx] += -self.lr * grad[idx] - self.decay_rate * self.weights[idx] # bias updates if self.have_bias: for idx in range(self.layers): self.biases[idx] += -self.lr * grad[idx + self.layers] - self.decay_rate * self.biases[idx] def train_step(self, x, y): """ training algorithm :param x: np array of training examples, first dimension is batch dimension for batch mode :param y: np array of training labels, first dimension is batch dimension for batch mode :return: """ batch_size = x.shape[0] self.train_loss.append(0) # include terms for biases grad = [np.zeros(self.weights[layer].shape) for layer in range(self.layers)] if self.have_bias: for idx in range(self.layers): grad.append(np.zeros(self.units[idx])) self.batch_steps += 1 for idx in range(batch_size): self.steps += 1 y_hat = self.forward(x[idx]) # print(y_hat) loss = self.loss(y[idx], y_hat) sample_grad = self.get_grad(y[idx], y_hat) for layer in range(self.layers): grad[layer] += sample_grad[layer] self.train_loss[-1] += loss if self.normalization == "NSE": self.train_loss[-1] /= self.NSE_normalization(y) else: self.train_loss[-1] /= batch_size for layer in range(self.layers): grad[layer] /= batch_size if self.have_bias: for idx in range(self.layers): grad[idx + self.layers] /= batch_size self.optimizer(grad) def reset(self, reinit=True): self.train_loss = [] for idx in range(self.layers): self.activations[idx] = np.zeros((self.units[idx], 1)) self.steps = 0 self.batch_steps = 0 if reinit: self.reinitialize() def reinitialize(self): self.weights[0] = np.random.rand(self.units[0], self.in_size) * \ (self.weight_init_range[1] - self.weight_init_range[0]) + self.weight_init_range[0] for idx in range(1, self.layers): self.weights[idx] = np.random.rand(self.units[idx], self.units[idx - 1]) * \ (self.weight_init_range[1] - self.weight_init_range[0]) + self.weight_init_range[0] if self.have_bias: for idx in range(self.layers): self.biases[idx] = np.random.rand(self.units[idx]) * \ (self.bias_init_range[1] - self.bias_init_range[0]) + self.bias_init_range[0] def NSE_normalization(self, labels): # normalized square error term label_sum = 0 label_means = np.mean(labels, 1) for t in range(len(labels)): label_sum += np.dot(labels[t], labels[t]) norm_factor = label_sum - np.dot(label_means, label_means) * labels.shape[0] return norm_factor def plot_train_loss(self): axis = plt.plot(self.train_loss) plt.yscale("log") plt.title("Training Loss") plt.xlabel("Samples") plt.ylabel("Loss") plt.show() def get_name(self): return self.name def set_name(self, name): self.name = name class LillicrapModel(Model): def __init__(self, layers, in_size, units, weight_init_range, nonlins=None, random_weights=False, randFB_init_range=None, lr=0.001, decay_rate=1e-06, normalization="NSE"): """ :param layers: number of layers in the network :param units: np array of output units in each layer of the network :param weight_init_range: support over which weights will be uniformly sampled from at initialization :param nonlins: list of non-linearities applied to each layer :param random_weights: whether the model will have random feedback weights (or will instead use basic GD) :param randFB_init_range: uniform sampling support for random feedback weights (if in use) """ super(LillicrapModel, self).__init__(layers=layers, in_size=in_size, units=units, weight_init_range=weight_init_range, nonlins=nonlins, lr=lr, decay_rate=decay_rate, normalization=normalization) self.random_weights = random_weights if self.random_weights is True: self.name = "Random Feedback Weights" else: self.name = "Backprop" self.B = [] if random_weights is True: self.randFB_init_range = randFB_init_range for idx in range(layers - 1): self.B.append(np.random.rand(units[idx], units[idx + 1]) * (randFB_init_range[1] - randFB_init_range[0]) + weight_init_range[0]) def loss(self, y, y_hat): e = np.expand_dims((y - y_hat).T, axis=1) return e, 0.5*np.dot(e.T, e) def get_grad(self, e, x): grad_W = [email protected]_dims(self.activations[1].T, 0) if self.random_weights is True: grad_W0 = -np.matrix(self.B[1])@[email protected](x.T) else: grad_W0 = -self.weights[2].T@[email protected](x.T) return grad_W0, grad_W def reinitialize(self): for idx in range(1, self.layers): self.weights[idx] = np.random.rand(self.units[idx], self.units[idx-1]) * \ (self.weight_init_range[1] - self.weight_init_range[0]) + self.weight_init_range[0] self.B = [] if self.random_weights is True: for idx in range(1, self.layers): self.B.append(np.random.rand(self.units[idx-1], self.units[idx]) * (self.randFB_init_range[1] - self.randFB_init_range[0]) + self.weight_init_range[0]) # model with learning rule based on BCM Hebbian learning rule as described in # "A synaptic basis for memory storage in the cerebral cortex" (Bear, 1996) # Thanks to Dr. McClelland for his thoughts in developing this project class BCMModel(Model): def __init__(self, layers, units, weight_init_range, nonlins=None, random_weights=False, randFB_init_range=None, lr=0.001, decay_rate=1e-06, normalization="NSE", BCM_decay_rate=0.9, BCM_sat_const=1): """ :param layers: number of layers in the network :param units: np array of output units in each layer of the network :param weight_init_range: support over which weights will be uniformly sampled from at initialization :param nonlins: list of non-linearities applied to each layer :param random_weights: whether the model will have random feedback weights (or will instead have set feedback weights) :param randFB_init_range: uniform sampling support for random feedback weights (if in use) :param BCM_rate_decay: rate of decay in exponential moving average of BCM modification threshold """ super(BCMModel, self).__init__(layers=layers, units=units, weight_init_range=weight_init_range, nonlins=nonlins, lr=lr, decay_rate=decay_rate, normalization=normalization, name='BCM') self.BCM_decay_rate = BCM_decay_rate self.random_weights = random_weights self.randFB_init_range = randFB_init_range self.BCM_sat_const = BCM_sat_const # BCM neural modification thresholds self.q = [] self.train_loss = [] for idx in range(layers-1): self.weights.append(np.random.rand(units[idx+1], units[idx]) * (weight_init_range[1] - weight_init_range[0]) + weight_init_range[0]) self.q.append(np.zeros((self.units[idx], 1))) for idx in range(layers): self.activations.append(np.zeros((self.units[idx], 1))) self.B = [] if random_weights is True: self.randFB_init_range = randFB_init_range for idx in range(layers - 1): self.B.append(np.random.rand(units[idx], units[idx + 1]) * (randFB_init_range[1] - randFB_init_range[0]) + weight_init_range[0]) def loss(self, y, y_hat): e = np.expand_dims((y - y_hat).T, axis=1) return e, 0.5*np.dot(e.T, e) def get_grad(self, e, x): grad_W = [email protected]_dims(self.activations[1].T, 0) if self.random_weights is True: grad_W0 = -np.matrix(self.B[1])@[email protected](x.T) del_hidden = self.B[1] @ e # del_hidden[del_hidden<0] = 0 post_syn_act = del_hidden # post_syn_act[post_syn_act<0] = 0 # post_syn_act = del_hidden + self.activations[1][:, np.newaxis] # del_hidden = self.weights[1].T @ e # BCM rule is applied to error signal input to neuron at distal apical dendritic compartment, # with the error signal in the GD framework corresponding to the gradient with respect to the activation self.q[0] = self.BCM_decay_rate * self.q[0] + (1 - self.BCM_decay_rate) * post_syn_act grad_W0 = -np.matrix(self.BCM_update_rule(post_syn_act, self.q[0])) @ np.matrix(x.T) # self.q[0] = self.BCM_decay_rate * self.q[0] + (1 - self.BCM_decay_rate) * post_syn_act else: grad_W0 = -self.weights[1].T@[email protected](x.T) return grad_W0, grad_W def BCM_update_rule(self, post_syn_act, threshold): # num = post_syn_act * (post_syn_act - threshold) num = post_syn_act - threshold # return num # return num/(self.BCM_sat_const + num) return num/(np.maximum(self.BCM_sat_const + num, np.full(num.shape, self.BCM_sat_const))) def reinitialize(self): self.q = [] for idx in range(1, self.layers): self.weights[idx] = np.random.rand(self.units[idx], self.units[idx-1]) * \ (self.weight_init_range[1] - self.weight_init_range[0]) + self.weight_init_range[0] self.q.append(np.zeros((self.units[idx], 1))) self.B = [] if self.random_weights is True: for idx in range(1, self.layers): self.B.append(np.random.rand(self.units[idx-1], self.units[idx]) * (self.randFB_init_range[1] - self.randFB_init_range[0]) + self.weight_init_range[0])