text
stringlengths
37
1.41M
def sayHello(): print('Hello World!') sayHello() def printMax(a = 2, b): if a > b: print(a) else: print(b) a = 4 b = 0 printMax(b)
import pygame class Circle: def __init__(self, rad): self.rad = rad print("Ball rad {} has been created!".format(self.rad)) def position(self, x, y): self.x = x self.y = y print("Ball with rad {} is in ({}, {}) position.".format(self.rad, self.x, self.y)) def direction(self, dx, dy): self.dx = dx self.dy = dy print("Ball with rad {} has ({}, {}) direction.".format(self.rad, self.dx, self.dy)) def __del__(self): print("Ball with rad {} has been deleted!".format(self.rad))
import random a=input("请输入您要猜的数:") print(type(a)) #数字范围是[1,1000] secret = random.randint(1, 1000) guess = 0 while guess != secret: guess = int(input("Guess a number: ")) if guess == 0: print("Sorry to see you go") break if guess > secret: print("too large") elif guess < secret: print("too small") else: print("Congratulation!")
class Employee: salary_raise = 1.04 def __init__(self, name, last, salary): self.name = name self.last = last self.salary = salary def __str__(self): return f"Name: {self.name} -- Last: {self.last}\nSalary: {self.salary}" def apply_raise(self): self.salary *= self.salary_raise @classmethod def set_salary_raise(cls, value): cls.salary_raise = value class Developer(Employee): salary_raise = 1.10 def __init__(self, name, last, salary, p_language): super().__init__(name, last, salary) self.p_language = p_language def __str__(self): return f"Name: {self.name} -- Last: {self.last}\nSalary: {self.salary}\nP_Language: {self.p_language}" user_employee = Employee("Bud", "Spencer", 10000) user_developer = Developer("Peter", "Griffin", 12500, "Python") print(user_employee) user_employee.apply_raise() print(user_employee.salary) user_employee.apply_raise() print(user_employee.salary) user_employee.apply_raise() print(user_employee.salary) print(user_developer) user_developer.apply_raise() print(user_developer.salary) user_developer.apply_raise() print(user_developer.salary) user_developer.apply_raise() print(user_developer.salary)
from tkinter import * from time import strftime class Clock: def __init__(self, root): self.root = root self.root.title("Clock") self.root.resizable(0, 0) self.root.iconbitmap("clock-icon.ico") # VARS self.time_var = StringVar() # Time Label self.time_label = Label(self.root, bg="black", fg="cyan", font=("ds-digital", 80, "bold"), textvariable=self.time_var) self.time_label.pack() self.Time() def Time(self): time = strftime("%I:%M:%S %p") self.time_var.set(time) self.time_label.after(1000, self.Time) if __name__ == '__main__': ROOT = Tk() clock = Clock(ROOT) ROOT.mainloop()
import numpy as np import math as math import cv2 as cv import Layer class ReLuLayer(Layer.Layer): """Actually a leaky ReLU in order to avoid dead neurons Has the form f(x) = max(0.1x, x) Has no learned parameters""" def __init__(self, input_dim): Layer.Layer.__init__(self, input_dim, input_dim) self.input = None self.filters = None self.x_grads = None self.output = np.zeros([input_dim['height'], input_dim['width'], input_dim['depth']]) def forward_pass(self, input): """Takes the input and passes a volume of the same size where the values are = f(x) = max(0.1x, x)""" self.input = input input_cpy = input.flatten().copy() for w in range(input_cpy.size): input_cpy[w] = input_cpy[w] if input_cpy[w] > 0 else 0 # input_cpy[w] * 0.1 self.output = input_cpy.reshape(self.input.shape).copy() return self.output def backward_pass(self, out_grads): """Backprops thorugh the leaky ReLU which has dz/dw = 1 if the input was greater than 0 else 0.1""" self.x_grads = out_grads.copy() x_grads_copy = self.x_grads.flatten().copy() for w in range(x_grads_copy.size): x_grads_copy[w] = x_grads_copy[w] if self.input.flatten()[w] > 0 else 0 # 0.1 * x_grads_copy[w] self.x_grads = x_grads_copy.reshape(self.input.shape) return self.x_grads
""" 给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​ 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票): 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。 示例: 输入: [1,2,3,0,2] 输出: 3 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出] """ class Solution: def maxProfit(self, prices) -> int: if len(prices) <= 1: return 0 buy, pre_buy, sell, pre_sell = -max(prices), 0, 0, 0 for price in prices: pre_buy = buy buy = max(pre_sell - price, pre_buy) pre_sell = sell sell = max(pre_buy + price, pre_sell) return sell
""" Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.   Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. 题目分析 平衡二叉树 (空树或者左右两个孩子高度差不超过1) 在涉及到二叉树的题目时,递归函数非常好用 1.左子树是否平衡 2.右子树是否平衡 3.左子树的高度 4.右子树的高度 整个递归过程按照同样的结构得到子树的信息(左子树和右子树分别是否平衡,以及它们的高度),整合子树的信息 ( ),加工出返回的信息(应该返回左右子树中,高度较大的那一个high+1) """ # 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 isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def get_height(root): if root is None: return 0 left_height, right_height = get_height(root.left), get_height(root.right) if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1: return -1 return max(left_height, right_height) + 1 return (get_height(root) >= 0) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: if root is None: return True left_height = self.getHeight(root.left) right_height = self.getHeight(root.right) if abs(left_height-right_height) > 1: return False return self.isBalanced(root.left) and self.isBalanced(root.right) def getHeight(self, root: TreeNode) -> int: if root is None: return 0 left_height = self.getHeight(root.left) right_height = self.getHeight(root.right) return max(left_height, right_height) + 1
""" 把两个树重叠,重叠部分求和,不重叠部分是两个树不空的节点 """ """ 题目大意 将两个二叉树进行merge操作。操作方式是把两个树进行重叠,如果重叠部分都有值,那么这个新节点是他们的值的和;如果重叠部分没有值,那么新的节点就是他们两个当中不为空的节点。 解题方法 递归 如果两个树都有节点的话就把两个相加,左右孩子为两者的左右孩子。 否则选不是空的节点当做子节点。 时间复杂度是O(N1+N2),空间复杂度O(N)。N = t1 的 t2交集。 """ class Solution: def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if t1 and t2: newT = TreeNode(t1.val + t2.val) newT.left = self.mergeTrees(t1.left, t2.left) newT.right = self.mergeTrees(t1.right, t2.right) return newT else: return t1 or t2 #也可以换一种写法,没有任何区别: class Solution: def mergeTrees(self, t1, t2): if not t2: return t1 if not t1: return t2 newT = TreeNode(t1.val + t2.val) newT.left = self.mergeTrees(t1.left, t2.left) newT.right = self.mergeTrees(t1.right, t2.right) return newT
#快排 O(N) O(1) """class Solution: def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int': return self.quick_sort(nums, k) def quick_sort(self, nums, k): k = len(nums) - k left = 0 right = len(nums) """ # 首先要明确,此题目求的是 第K个最大元素,就是说将数据进行从小到大排序,倒数第K个元素。 class Solution: def partition(self, nums, left, right): # 一次排序 temp = nums[left] while left < right: while (left < right) and (nums[right] >= temp): right -= 1 nums[left] = nums[right] while (left < right) and (nums[left] <= temp): left += 1 nums[right] = nums[left] nums[left] = temp return left # left左边的数字比left小 def findKthLargest(self, nums: List[int], k: int) -> int: return self.select(nums, 0, len(nums) - 1, k) def select(self, nums, left, right, k): p = self.partition(nums, left, right) m = right - p + 1 if m == k: return nums[p] if k > m: # 此元素在左边 return self.select(nums, left, p - 1, k - m) else: # 此元素在右边 return self.select(nums, p + 1, right, k) #堆排序 O(NLOGK) O(K) class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return self.heap_sort(nums, k) def heap_sort(self, nums, k): #maxheap for i in range(len(nums) // 2 - 1, -1, -1): self.heap_adjust(nums, i, len(nums)) cnt = 0 #交换堆顶元素,重新调整结构 for i in range(len(nums) - 1, 0, -1): self.heap_swap(nums, 0, i) cnt += 1 if cnt == k: return nums[i] self.heap_adjust(nums, 0, i) return nums[0] def heap_adjust(self, nums, start, length): tmp = nums[start] k = start * 2 + 1 while k < length: #对于完全二叉树,没有左节点一点没有右节点 #当前节点左节点符号 left = start * 2 + 1 #当前节点右节点符号 right = left + 1 if right < length and nums[right] > nums[left]: #如果右节点比较大 k = right if nums[k] > tmp: #如果子节点比父节点大,则将子节点复制给父节点 nums[start] = nums[k] start = k else: break k = k * 2+ 1 nums[start] = tmp def heap_swap(self, nums, i, j): nums[i], nums[j] = nums[j], nums[i] return nums
""" 给你两个二进制字符串,返回它们的和(用二进制表示)。 输入为 非空 字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101"   提示: 每个字符串仅由字符 '0' 或 '1' 组成。 1 <= a.length, b.length <= 10^4 字符串如果不是 "0" ,就都不含前导零。 """ class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ result, carry, val = "", 0, 0 for i in range(max(len(a), len(b))): val = carry if i < len(a): val += int(a[-(i+1)]) if i < len(b): val += int(b[-(i+1)]) carry, val = val // 2, val%2 result += str(val) if carry: result += str(1) return result[::-1]
ara=input("enter the string\n") reverse='' i=len(ara) while i>0: reverse=reverse+ara[i-1] i=i-1 print(reverse)
#Implement a program with functions, for finding the area of circle, triangle, square p=3.147 def area_of_circle(): x=int(input("enter the radius of circle:\n")) return (p*x*x) def area_of_triangle(): b=int(input("enter the base:\n")) h=int(input("enter the height:\n")) return(0.5*b*h) def area_of_square(): r=int(input("enter the radius of circle:\n")) return(r*r) def main(): print("area of circle",area_of_circle()) print("area of traingle",area_of_triangle()) print("area of square",area_of_square()) if __name__ == '__main__': main()
abc=input("enter the string\n") count=0 for b in abc: if (b=='a' or b=='e' or b=='i'or b=='o'or b=='u'): count=count+1 print("number of vowels in string is",count)
class User: """ a class that generates new instances of passwors """ user_list = [] def __init__(self,first_name,last_name,password): """ _init_ a method that helps to define properties for our objects. """ self.first_name = first_name self.last_name = last_name self.password = password def save_user(self): """ this method saves contact objects into user_list """ User.user_list.append(self) @classmethod def find_user_by_password(cls,password): """ this method takes in a password and returns a password that matches tha password. """ for user in cls.user_list: if user.password == password: return user def delete_user(self): """ this method deletes a user from the user_list """ User.user_list.remove(self) @classmethod def user_exists(cls,password): """ this method checks if a user exists fro the user_list """ for user in cls.user_list: if user.password == password: return True return False @classmethod def display_user(cls): """ this method returns the user list """ return cls.user_list class Credential: """ a class that generates new instances of credentials """ credential_list= [] def __init__(self,Account,username,password): """ _init_ a method that helps to define properties for our objects. """ self.Account = Account self.username = username self.password = password def save_credential(self): """ saves credentail objects into credential list """ Credential.credential_list.append(self) @classmethod def find_credential_by_username(cls,username): """ this method takes in username and returns a username that matches the username """ for credential in cls.credential_list: if credential.username == username: return credential def delete_credential(self): """ this method deletes a credential from the credentila_list """ Credential.credential_list.remove(self) @classmethod def credential_exists(cls,username): """ this method checks if a credential exists fro the credential_list """ for credential in cls.credential_list: if credential.username == username: return True return False @classmethod def display_credential(cls): """ this method returns the credential list """ return cls.credential_list
my_dict = dict() for i in range(0,3): key = input("Enter the name: ") value = input("Enter the usn: ") my_dict[key] = value print(my_dict)
import unittest import twothirds class TestGame(unittest.TestCase): def test_initialisation_from_other_than_list_gives_errors(self): data = 2 self.assertRaises(ValueError, twothirds.TwoThirdsGame, data) def test_initialisation_from_list(self): data = range(100) g = twothirds.TwoThirdsGame(data) self.assertEqual(data, g.data) def test_initialisation_from_dictionary(self): data = dict(zip(range(100), range(100))) g = twothirds.TwoThirdsGame(data) self.assertEqual(data, g.data) def test_calculation_for_list(self): data = range(100) g = twothirds.TwoThirdsGame(data) two_thirds = sum(data) * 2.0 / (3.0 * len(data)) self.assertAlmostEqual(two_thirds, g.two_thirds_of_the_average()) def test_calculation_for_dict(self): data = dict(zip(range(100), range(100))) g = twothirds.TwoThirdsGame(data) self.assertEqual(data, g.data) two_thirds = sum(data.values()) * 2.0 / (3.0 * len(data)) self.assertAlmostEqual(two_thirds, g.two_thirds_of_the_average()) def test_find_winner_for_list(self): data = range(100) g = twothirds.TwoThirdsGame(data) self.assertEqual(('Anonymous', 33), g.find_winner()) def test_find_winner_for_list_1(self): data = [5, 5, 10, 9, 1, 0] g = twothirds.TwoThirdsGame(data) self.assertEqual(('Anonymous', 5), g.find_winner()) def test_find_winner_for_list_2(self): data = [0, 0, 0, 0, 0, 0] g = twothirds.TwoThirdsGame(data) self.assertEqual(('Anonymous', 0), g.find_winner()) def test_find_winner_for_list_3(self): data = [100, 100, 100, 100, 100, 100] g = twothirds.TwoThirdsGame(data) self.assertEqual(('Anonymous', 100), g.find_winner()) def test_find_winner_for_dict(self): data = dict(zip(range(100), range(100))) g = twothirds.TwoThirdsGame(data) self.assertAlmostEqual((33, 33), g.find_winner()) def test_find_winner_for_dict_1(self): data = {'Vince' : 5, 'Zoe' : 5, 'David': 10, 'Elliot': 9, 'Kaity': 1, 'Ben': 0} g = twothirds.TwoThirdsGame(data) self.assertEqual(('Vince', 'Zoe', 5), g.find_winner()) def test_find_winner_for_dict_2(self): data = {'Vince' : 0, 'Zoe' : 0, 'David': 0, 'Elliot': 0, 'Kaity': 0, 'Ben': 0} g = twothirds.TwoThirdsGame(data) sorted_names = sorted(data.keys()) expected_result = tuple(sorted_names + [0]) self.assertEqual(expected_result, g.find_winner()) def test_find_winner_for_dict_3(self): data = {'Vince' : 100, 'Zoe' : 100, 'David': 100, 'Elliot': 100, 'Kaity': 100, 'Ben': 100} g = twothirds.TwoThirdsGame(data) sorted_names = sorted(data.keys()) expected_result = tuple(sorted_names + [100]) self.assertEqual(expected_result, g.find_winner()) def test_find_winner_for_dict_4(self): data = {'A': 1, 'B': 2, 'C': 3} g = twothirds.TwoThirdsGame(data) expected_result = ('A', 1) self.assertEqual(expected_result, g.find_winner())
x = int(raw_input("Dime un numero: ")) y = int(raw_input("Dime otro numero: ")) while x<=y: if x%2==0: print x x += 1
from nltk.corpus import stopwords from nltk.tokenize import word_tokenize X = input("Enter first string: ").lower() Y = input("Enter second string: ").lower() #X ="I love horror movies" #Y ="Lights out is a horror movie" # tokenization X_list = word_tokenize(X) Y_list = word_tokenize(Y) # sw contains the list of stopwords sw = stopwords.words('english') l1 =[];l2 =[] # remove stop words from the string X_set = {w for w in X_list if not w in sw} Y_set = {w for w in Y_list if not w in sw} # form a set containing keywords of both strings rvector = X_set.union(Y_set) for w in rvector: if w in X_set: l1.append(1) # create a vector else: l1.append(0) if w in Y_set: l2.append(1) else: l2.append(0) c = 0 # cosine formula for i in range(len(rvector)): c+= l1[i]*l2[i] cosine = c / float((sum(l1)*sum(l2))**0.5) print("similarity: ", cosine)
# A Dictionaries is a collection which is unordered, changeable and indexed. No duplicate members. #Note: Dictionaries are same as Objects in javascipt #Create dict person={ 'first_name' : 'theodore', 'last_name' : 'kimana', 'age': 24, } household={ 'dad': 'Theobare', 'mom' : 'Odette', 'dad_age': 54, 'mom_age': 40, } # Use Constractor person2= dict(first_name='Sara', last_name='james') # Get a Value in dict print(household['mom']) print(person.get('last_name')) # Add key/value person['phone']='200000' # Get dict keys print(person.keys()) # Get dict value print(person.values()) #print(person) # Get dict items print(person.items()) # Copy dict household=person.copy() household['city']= 'Boston' # Remove item del(household['city']) print(household) del (person['first_name']) print(person) # Clear person.clear() print(person) # Length in dictionaries print(len(household)) #person.pop('phone') print(person) #print(household) # Clear household.clear() print(household) #print(person2, type(person2)) # Create a list of dict people=[ {'name': 'james', 'age': '34'}, {'name': 'greg', 'age': '21'} ] print(people) # If you want to get the name in the list dict print(people[1]['name'])
import util class Obstacle: """ Classe représentant un obstacle ... Attributs ----- min_y : int Position en y pos_x : int Position en x largeur : int largeur de l'obstacle hauteur : int hauteur de l'obstacle Méthodes ----- avancer(v): Retranche v à la position en x de l'obstacle afficher(): Affiche l'obstacle en chaîne de caractères dans la console auteur : Benoît """ def __init__(self, min_y, pos_x, largeur=util.LARGEUR_OBSTACLE, hauteur=util.HAUTEUR_CHEMIN): """ Initialise un objet Obstacle, défini par sa position minimale en y (début du chemin), et sa position en x. Les propriétés largeur et hauteur sont initialisées avec les valeurs constantes d'util. ... Parametres : ----- min_y : int Position en y pos_x : int Position en x largeur : int largeur de l'obstacle hauteur : int hauteur de l'obstacle """ self.min_y = min_y self.pos_x = pos_x self.largeur = largeur self.hauteur = hauteur def avancer(self, v): """ Retranche v à la position en x de l'obstacle ... Parametres ----- v : int vitesse de déplacement """ self.pos_x -= v def afficher(self): """ Affiche l'obstacle en chaîne de caractères dans la console """ print(" L'obstacle est en x={}, y={}".format(self.pos_x, self.min_y))
#!/usr/bin/env python #-*-coding:utf-8 -*- # print 'hello, %s' % 'world' # print 'Hi, %s, you have $%.1f.' %('Michael', 33.111) # print '%02d - %03d' % (2,1) # print "growth rate: %d%%" % 7 # source1 = 72 # source2 = 85 # imp = ((85 - 72) / 72) * 100 # # print "improve: %.1f%%" % ((source2-source1)/source1)*100 # print 'improve: ' , imp ''' classmates = ['Michael','Bob','Tracy'] print classmates print len(classmates) classmates.append('Adam') print classmates classmates.insert(1,'Jack') print classmates classmates.pop(1) print classmates classmates[1] = 'Sarch' print classmates L = ['Apple',123, True] print L classmates_tuple = ('Michael','Bob','Tracy') print classmates_tuple t = (2,) print t ''' ''' d = {'Michael':95,'Bob':75 ,'Tracy': 85} print d d.pop('Bob') print d # s = set([1,2,3]) # print s s = {'No1':1,'(1,2,3)':(1,2,3)} print s['(1,2,3)'] ''' ''' def fact(n): if n == 1: return 1 return n * fact(n - 1) # print fact(5) def fact2(n): return fact_iter(n,1) def fact_iter(num, producter): if num == 1 : return producter # print "fact_iter(%d, %d)" % (num-1, num*producter) print "fact_iter(%d, %d)" % (num, producter) return fact_iter(num-1, num*producter) print fact2(5) ''' ''' L = ['Michael', 'Sarch', 'Tracy', 'Bob', 'Jack'] print L[:3] l = range(100) print l[::5] ''' ''' d = {'a':1, 'b':2, 'c':3} for key in d: print key , d[key] for value in d.itervalues(): print value ''' ''' from collections import Iterable print isinstance(1234, Iterable) for key, value in enumerate(('A','B','C')): print key, value for x,y,z in [(1,1,1),(2,4,8), (3,9,27)]: print x,y,z ''' ''' L = [] # print range(1,11) l = [x * x for x in range(1,11) if x % 2 ==0] print l b = [m + n for m in 'ABC' for n in 'XYZ'] print b l = ["Hello", 'World',18, 'Apple',None] aa = [word.lower() for word in l if isinstance(word,str)] bb = [word.lower() if isinstance(word,str) else word for word in l] print aa print bb ''' # g = (x * x for x in range(10)) # for n in g : # print n ''' def odd(): print 'step 1' yield 1 print 'step 2' yield 2 print 'step 3' yield 3 o = odd() o.next() o.next() o.next() o.next() ''' ''' f = abs def add(x, y, f): return f(x) + f(y) a = 2 b = 2 c=b print id(a) print id(b) print a is c ''' ''' a = [1,2,3,4,5,6,7,8,9] def f(x): return x*x print map(f,a) def fn (x,y): return x*10 + y print reduce(fn,[1,3,5,7,9]) ''' ''' bar = lambda:'begineman' print bar() def add(x, y):return x + y add2 = lambda x,y : x+y print add2(1,2) ''' ''' def str2int(s): def fn(x,y): return x*10+y def char2num(s): return {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}[s] return reduce(fn,map(char2num,'25689')) ''' ''' def is_add(n): return n % 2 == 1 print filter(is_add,[1,2,4,5,6,9,10,15]) ''' ''' numlist = range(1,101) def snum(num): count = 0 for i in range(1,num+1): if num %i == 0: count += 1 if count == 2: return True else: return False print filter(snum,numlist) def fn(x): n=2 while n < x: if x % n == 0: return False n = n + 1 return True print filter(fn,range(2,101)) ''' ''' def lazy_sum(*args): def calc_sum(): ax = 0 for n in args: ax = ax + n return ax return calc_sum f = lazy_sum(1,3,4,6,7,9) print f() ''' ''' def f(): print 'Call f() ...' def g(): print 'call g()...' return g x = f() x() ''' ''' def make_addr(addend): def adder(augend): return addend + augend return adder p = make_addr(23) q = make_addr(44) print p(100) print q(100) ''' ''' def hellocounter(name): count = [0] def counter(): count[0] += 1 print 'Hello, ', name, ',', str(count[0]) + ' access!' return counter hello = hellocounter('ma6714') hello() hello() hello() ''' ''' def count(): fs = [] for i in range(1,4): def f(j): def g(): return j * j return g fs.append(f(i)) return fs z1,z2,z3 = count() print z1() print z2() print z3() func = lambda i :lambda :i*i def count2(): fs = [] for i in range(1, 4): fs.append(func(i) ) return fs x1,x2,x3 = count2() print x1() print x2() print x3() ''' ''' def makebold(fn): def wrapped(): return '<b>' + fn() + "/b>" return wrapped def makeitalic(fn): def wrapped(): return '<i>' + fn() + '</i>' return wrapped @makebold @makeitalic def hello(): return "hello world" # print hello() aaa = makebold(makeitalic(hello)) print aaa() ''' ''' def now(): print '2013-12-25' f = now print f() print now.__name__ print f.__name__ ''' def log(func): def wrapper(*args, **kw): print 'call %s(): ' % func.__name__ return func(*args, **kw) return wrapper @log def now(): print '2013-12-25' # f = now # print f() # print now.__name__ # print f.__name__ now() ''''''
import numpy as np import matplotlib.pyplot as plt # Calculating the parameters based on formulas def best_fit(X, Y): a1 = ((X*Y).mean() - X.mean()*Y.mean())/((X**2).mean() - (X.mean()**2)) a0 = Y.mean() - a1*X.mean() return a0, a1 X = np.array([1, 2, 3, 4, 5, 6]) Y = np.array([1.5, 4, 4, 6, 7, 8]) plt.scatter(X, Y) a0, a1 = best_fit(X, Y) print(a0, a1) X1 = 0 pred1 = a0 + a1*X1 X2 = 10 pred2 = a0 + a1*X2 X_Line = (X1, X2) Y_Line = (pred1, pred2) # Plotting the line plt.plot(X_Line, Y_Line) plt.show()
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt from tqdm import tqdm import numpy as np class Classifier(object): """ Multi Class Classifier base class """ def __init__(self, input_size, n_classes): """ Initializes a matrix in which each column will be the Weights for a specific class. :param input_size: Number of features :param n_classes: Number of classes to classify the inputs """ self.parameters = np.zeros((input_size+1, n_classes)) # input_size +1 to include the Bias term def train(self, X, Y, devX, devY, epochs=20): """ This trains the perceptron over a certain number of epoch and records the accuracy in Train and Dev sets along each epoch. :param X: numpy array with size DxN where D is the number of training examples and N is the number of features. :param Y: numpy array with size D containing the correct labels for the training set :param devX (optional): same as X but for the dev set. :param devY (optional): same as Y but for the dev set. :param epochs (optional): number of epochs to run Note: This function will print a loading bar ate the terminal for each epoch. """ train_accuracy = [self.evaluate(X, Y)] dev_accuracy = [self.evaluate(devX, devY)] for epoch in range(epochs): for i in tqdm(range(X.shape[0])): self.update_weights(X[i, :], Y[i]) train_accuracy.append(self.evaluate(X, Y)) dev_accuracy.append(self.evaluate(devX, devY)) return train_accuracy, dev_accuracy def evaluate(self, X, Y): """ Evaluates the error in a given set of examples. :param X: numpy array with size DxN where D is the number of examples to evaluate and N is the number of features. :param Y: numpy array with size D containing the correct labels for the training set """ correct_predictions = 0 for i in range(X.shape[0]): y_pred = self.predict(X[i, :]) if Y[i] == y_pred: correct_predictions += 1 return correct_predictions/X.shape[0] def plot_train(self, train_accuracy, dev_accuracy, filename): """ Function to Plot the accuracy of the Training set and Dev set per epoch. :param train_accuracy: list containing the accuracies of the train set. :param dev_accuracy: list containing the accuracies of the dev set. """ x_axis = [epoch+1 for epoch in range(len(train_accuracy))] plt.plot(x_axis, train_accuracy, '-g', linewidth=1, label='Train') plt.xlabel("epochs") plt.ylabel("Accuracy") plt.plot(x_axis, dev_accuracy, 'b-', linewidth=1, label='Dev') plt.legend() plt.savefig("plots/"+filename) plt.gcf().clear() def update_weights(self, x, y): """ Function that will take an input example and the true prediction and will update the model parameters. :param x: Array of size N where N its the number of features that the model takes as input. :param y: The int corresponding to the correct label. TO DO - child classes must implement this function """ pass def predict(self, x): """ This function will add a Bias value to the received input, multiply the Weights corresponding to the different classes with the input vector and choose the class that maximizes that multiplication. :param x: numpy array with size 1xN where N = number of features. TO DO - child classes must implement this function """ pass
# -*- coding: utf-8 -*- from sklearn.externals import joblib from classifier import Classifier import matplotlib.pyplot as plt import numpy as np import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) class MultinomialLR(Classifier): """ Multinomial Logistic Regression """ def __init__(self, input_size, n_classes, lr=0.001, l2=None): """ Initializes a matrix in which each column will be the Weights for a specific class. :param input_size: Number of features :param n_classes: Number of classes to classify the inputs """ Classifier.__init__(self, input_size, n_classes) self.lr = lr self.l2 = l2 def predict(self, input): """ This function will add a Bias value to the received input, multiply the Weights corresponding to the different classes with the input vector, run a softmax function and choose the class that achieves an higher probability. :param x: numpy array with size 1xN where N = number of features. """ return np.argmax(self.softmax(np.dot(np.append(input, [1]), self.parameters))) def softmax(self, x): """ Compute softmax values for each sets of scores in x.""" return np.exp(x-np.max(x))/np.sum(np.exp(x-np.max(x)), axis=0) def update_weights(self, x, y): """ Function that will take an input example and the true prediction and will update the model parameters. :param x: Array of size N where N its the number of features that the model takes as input. :param y: The int corresponding to the correct label. """ linear = np.dot(np.append(x, [1]), self.parameters) predictions = self.softmax(linear) if self.l2 is not None: self.parameters = self.parameters - self.lr*(np.outer(predictions, np.append(x, [1])).T - self.l2*self.parameters) else: self.parameters = self.parameters - self.lr*(np.outer(predictions, np.append(x, [1])).T) self.parameters[:, y] = self.parameters[:, y] + self.lr*np.append(x, [1]) def main(): train_x, train_y = joblib.load("data/train.pkl") dev_x, dev_y = joblib.load("data/dev.pkl") test_x, test_y = joblib.load("data/test.pkl") logistic_reg = MultinomialLR(train_x.shape[1], np.unique(train_y).shape[0], l2=0.1) train_accuracy, dev_accuracy = logistic_reg.train(train_x, train_y, dev_x, dev_y) print ("Train Accuracy: {}".format(logistic_reg.evaluate(train_x, train_y))) print ("Dev Accuracy: {}".format(logistic_reg.evaluate(dev_x, dev_y))) print ("Test Accuracy: {}".format(logistic_reg.evaluate(test_x, test_y))) logistic_reg.plot_train(train_accuracy, dev_accuracy, "multinomial-lr-accuracy.png") if __name__ == '__main__': main()
from constants import * from math import fabs, sqrt class Matches: """creates group(field) of matches that can be drawn selectively""" def __init__(self, field_power, indent=INDENT_BETWEEN_MATCHES, indent_x=MATCH_INDENT_X, indent_y=MATCH_INDENT_Y): self.field_power = field_power self._create_cells(indent, indent_x, indent_y) self._create_matches() def draw_visible_matches(self, canvas, active_list: list, color="pink"): for i in range(len(self.matches)): if active_list[i]: self.matches[i].draw(canvas, color) def draw_invisible_matches(self, canvas, active_list: list, color): for i in range(len(self.matches)): if not active_list[i]: self.matches[i].draw(canvas, color) def _create_matches(self): """create field of matches (square-shape)""" self.matches = [] for i in range(len(self.cells)): try: if (i + 1) % (self.field_power + 1) != 0: self.matches.append(self.cells[i].connect_to(self.cells[i + 1])) if (i + 1) % (self.field_power + 1) != 0 and i + 1 < (self.field_power + 1) ** 2 - self.field_power: self.matches.append(self.cells[i].connect_to(self.cells[i + self.field_power + 2])) if i + 1 < (self.field_power + 1) ** 2 - self.field_power: self.matches.append(self.cells[i].connect_to(self.cells[i + self.field_power + 1])) if i + 1 < (self.field_power + 1) ** 2 - self.field_power and (i + 1) % (self.field_power + 1) != 1: self.matches.append(self.cells[i].connect_to(self.cells[i + self.field_power])) except IndexError: print("Cannot draw one of the matches") print(i) def _create_cells(self, indent, indent_x, indent_y): """create cells which later would connect to line(matches)""" self.cells = [] for i in range(self.field_power + 1): for j in range(self.field_power + 1): self.cells.append(Cell((j + 1) * indent + indent_x, (i + 1) * indent + indent_y)) print(len(self.cells)) @property def Length(self): return len(self.matches) def __getitem__(self, item): return self.matches[item] class Match: """creates match(line) between two cells you can draw in on the canvas and check if given point is within this match""" def __init__(self, coords: list): self.coords = [coords[0], coords[1], coords[2], coords[3]] def draw(self, canvas, color): canvas.create_line(self.coords, fill=color, width=MATCH_WIDTH) def inside_of_rectangle(self, point: list) -> bool: """check if point is within a rectangle by comparing scalar product of the vectors, created by rectangle vertices, that are calculated on the place and point coords""" px, py = point[0], point[1] x1, x2, x3, y1, y2, y3 = [1 for i in range(6)] if self.coords[0] == self.coords[2]: x1 = self.coords[0] + MATCH_WIDTH / 2 x2 = self.coords[0] - MATCH_WIDTH / 2 x3 = self.coords[2] - MATCH_WIDTH / 2 y1 = y2 = self.coords[1] y3 = self.coords[3] elif self.coords[1] == self.coords[3]: y1 = self.coords[1] + MATCH_WIDTH / 2 y2 = self.coords[1] - MATCH_WIDTH / 2 y3 = self.coords[3] - MATCH_WIDTH / 2 x1 = x2 = self.coords[0] x3 = self.coords[2] else: if self.coords[0] < self.coords[2]: x1 = self.coords[0] + MATCH_WIDTH / 2 x2 = self.coords[0] - MATCH_WIDTH / 2 x3 = self.coords[2] - MATCH_WIDTH / 2 y1 = self.coords[1] - MATCH_WIDTH / 2 y2 = self.coords[1] + MATCH_WIDTH / 2 y3 = self.coords[3] + MATCH_WIDTH / 2 elif self.coords[0] > self.coords[2]: x1 = self.coords[0] + MATCH_WIDTH / 2 x2 = self.coords[0] - MATCH_WIDTH / 2 x3 = self.coords[2] - MATCH_WIDTH / 2 y1 = self.coords[1] + MATCH_WIDTH / 2 y2 = self.coords[1] - MATCH_WIDTH / 2 y3 = self.coords[3] - MATCH_WIDTH / 2 first = 0 < self._scalar_product([x1 - x2, y1 - y2], [px - x2, py - y2]) < self._scalar_product( [x1 - x2, y1 - y2], [x1 - x2, y1 - y2]) second = 0 < self._scalar_product([x3 - x2, y3 - y2], [px - x2, py - y2]) < self._scalar_product( [x3 - x2, y3 - y2], [x3 - x2, y3 - y2]) return first and second def _line_length(self, point1, point2): x = fabs(point1[0] - point2[0]) y = fabs(point1[1] - point2[1]) return sqrt(x ** 2 + y ** 2) def _scalar_product(self, vector1, vector2): return vector1[0] * vector2[0] + vector1[1] * vector2[1] class Cell: """creates cell(point) on the screen that can be connected to another cell to make match""" def __init__(self, pos_x, pos_y): self.pos_x, self.pos_y = pos_x, pos_y def connect_to(self, other_cell): """ create new match that lay between 2 cells""" return Match([self.pos_x, self.pos_y, other_cell.X, other_cell.Y]) @property def X(self): return self.pos_x @property def Y(self): return self.pos_y
#枚举类 from enum import Enum Month=Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Aug','Sep','Oct','Nov','Dec')) for name,member in Month.__members__.items(): print(name,'=>',member,',',member.value) #type()函数既可以返回一个对象的类型,又可以创建出新的类型 class Hello(): def hello(self,name='world'): print('Hello %s .'% name) h=Hello() #h.hello() print(type(Hello)) #动态创建class def fn(self,name='dantyli'): #先定义函数 print('Hello %s'% name) Hello=type('Hello',(object,),dict(hello=fn))#创建Hello class h=Hello() h.hello() #错误处理,try...except跨越多层调用 try: print('try...') r=10/0 print('result',r) except ZeroDivisionError as e: print('except',e) else: print('finally...') def foo(s): return 10/int(s) def bar(s): return foo(s)*2 def main(): try: bar('0') except Exception as e: print('Error',e) #使用异常避免崩溃else print('Give me two numbers ,and i will divide them') print("enter 'q' to quit") while True: first_num=input('\n first number') if first_num=='q': break second_num=input('\n second number') try: answer=int(first_num)/int(second_num) except ZeroDivisionError: print('you can not divide by 0!') else: print(answer) #FileNotFoundError异常 filename='aice.txt' try: with open(filename) as file_object: contents=file_object.read() except FileNotFoundError: msg='sorry the file '+filename+' does not exist' print(msg) else: print(contents) #失败时一声不吭 def count_words(filename): try: with open(filename) as file_object: contents=file_object.read() except FileNotFoundError: pass #告诉python什么都不做 else: words=contents.split() num_words=len(words) print('this book has about '+str(num_words)+'words') #存储数据 import json numbers=['dantyli','lice','andy','tonny'] filename='numbers.json' with open(filename,'w') as f_obj: json.dump(numbers,f_obj) with open(filename) as f_obj: numbers=json.load(f_obj) print(numbers)
print('Welcome to input checker!') original = input("Enter a word:") if len(original) > 0: # Checks that something was inputted print(original) else: print("Your input is empty") print('Welcome to alphabetical input checker!') original = input("Enter a word:") if len(original) > 0 and original.isalpha(): # Checks that only alphabetical characters are inputted print(original) else: print("This is not a word")
# Return sorted sequence (by value order) c = {'a': 10, 'c': 22, 'b': 1} tmp = list() for k, v in c.items(): tmp.append((v,k)) print(tmp) tmp = sorted(tmp, reverse=True) print(tmp)
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) # find all lines starting with "From" and capture the email address in the list 'emails' emails = list() for line in handle: if line.startswith('From '): emails.append(line.split(' ')[1]) #print(emails) # from the list 'emails', capture the email and the number of times in the dictionary "email counts" email_counts = dict() for email in emails: email_counts[email] = email_counts.get(email, 0) + 1 #print(email_counts) # find the most times an email is seen big_email = None big_count = None for email,count in email_counts.items(): if big_email is None or count > big_count: big_email = email big_count = count print(big_email, big_count)
while True: operator = input("To multiply or divide, please select * or /: ") if operator == "/" or operator == "*": break else: print("That is an invalid operator, please try again\n") def math_function(num1, num2): if operator == "*": math_function = int(num1) * int(num2) return math_function elif operator == "/": math_function = int(num1) / int(num2) return math_function num1 = input("Please provide a whole number: ") num2 = input("And provide a second whole number: ") answer = math_function(num1, num2) print(num1, operator, num2, "is:", str(answer))
dct = {'chuck': 1, 'fred': 42, 'jan': 100} # print dictionary print(dct) # change dictionary keys into list print(list(dct)) # change dictionary keys into list with method print(dct.keys()) print(list(dct.keys())) # change dictionary values into list with method print(dct.values()) print(list(dct.values())) # change dictionary into tuple with method print(dct.items()) p_tuple = tuple(dct.items()) print(p_tuple) # change dictionary keys into sorted list for d in sorted(dct.keys()): print(d, '-', dct[d])
def product(nums): total = 0 print(nums) for n in nums: if total == 0: total = n else: total *= n print(total) return total product([4, 5, 5]) # ---------------------------# def product(nums): total = 1 print(nums) for n in nums: total *= n print(total) return total product([4, 5, 5]) # ---------------------------# def multiply(num1, num2): multiply = int(num1) * int(num2) return multiply num1 = input("Please provide a whole number: ") num2 = input("And provide a second whole number: ") answer = multiply(num1, num2) print(num1, "*", num2, "is:", str(answer))
# Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) count = 0 spam_total = 0.0 for line in fh: if not line.startswith("X-DSPAM-Confidence:"): continue count += 1 num = line.find(":") spam = float(line[num+1:]) spam_total = spam_total + spam confidence = spam_total / count print("Average spam confidence: {0: >1.12f}".format(float(confidence)))
def reverse(x): drow = '' for i in range(len(x) -1, -1, -1): drow += x[i] i -= 1 # print(drow) return drow print(reverse('abcd')) # ---------------------------------------- # to_one_hundred = list(range(101)) # print(to_one_hundred) backwards_by_tens = to_one_hundred[::-10] print(backwards_by_tens)
class Students: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def avg(self): return sum(self.marks) / len(self.marks) def go_to_school(self): print("{} is going to {}.".format(self.name, self.school)) anna = Students("Anna", "MIT") anna.marks.append(56) anna.marks.append(90) anna.marks.append(78) print(anna.name) print(anna.school) print(anna.marks) print(anna.avg()) anna.go_to_school()
#!/usr/bin/python #coding:utf8 ''' first step:pip install pyramid-arima ''' import pandas as pd import numpy as np from pyramid.arima import auto_arima print("load dataset...") data = pd.read_csv('international-airline-passengers.csv') #divide into train and validation set train = data[:int(0.7*(len(data)))] valid = data[int(0.7*(len(data))):] #preprocessing (since arima takes univariate series as input) train.drop('Month',axis=1,inplace=True) valid.drop('Month',axis=1,inplace=True) #plotting the data #train['International airline passengers'].plot() #valid['International airline passengers'].plot() print("train the model") model = auto_arima(train, trace=True, error_action='ignore', suppress_warnings=True) model.fit(train) forecast = model.predict(n_periods=len(valid)) forecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction']) #plot the predictions for validation set #plt.plot(train, label='Train') #plt.plot(valid, label='Valid') #plt.plot(forecast, label='Prediction') #plt.show() print("evalute the prediction...") #calculate rmse from math import sqrt from sklearn.metrics import mean_squared_error rms = sqrt(mean_squared_error(valid,forecast)) print(rms)
# Quiz 1: Create Usernames #Write a for loop that iterates over the names list to create a usernames list. #To create a username for each name, make everything lowercase and replace #spaces with underscores. Running your for loop over the list. names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] usernames = [] for name in names: name = name.lower() name = name.replace(' ', '_') usernames.append(name) # or shorter variant: # usernames.append(name.lower().replace(' ', '_')) print(usernames) # Quiz 2: Modify Usernames with Range # Write a for loop that uses range() to iterate over the positions in usernames # to modify the list. Like you did in the previous quiz, change each name to be # lowercase and replace spaces with underscores. usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] for index in range(len(usernames)): usernames[index] = usernames[index].lower().replace(' ', '_') print(usernames) # Quiz 3: Tag Counter # Write a for loop that iterates over a list of strings, tokens, and counts how # many of them are XML tags. XML is a data language similar to HTML. You can # tell if a string is an XML tag if it begins with a left angle bracket "<" and # ends with a right angle bracket ">". Keep track of the number of tags using # the variable count. tokens = ['<greeting>', 'Hello World!', '</greeting>'] count = 0 for token in tokens: if token[0] == '<' and token[-1] == '>': count = count + 1 print(count) # Quiz 4: Create an HTML List # Write some code, including a for loop, that iterates over a list of strings # and creates a single string, html_str, which is an HTML list. For example, # should output: # <ul> # <li>first string</li> # <li>second string</li> # </ul> items = ['first string', 'second string'] html_str = "<ul>\n" # "\ n" is the character that marks the end of the line, # it does the characters that are after it in html_str # are on the next line for item in items: html_str = html_str + "<li>" + str(item) + "</li>" "\n" html_str = html_str + "</ul>" print(html_str) # Quiz 5: Lower # If you want to create a new list called lower_colors, where each color # in colors is lower cased, which code would do this? colors = ['Red', 'Blue', 'Green', 'Purple'] lower_colors = [] for color in colors: lower_colors.append(color.lower()) print(lower_colors) # Quizzes: Iterating Through Dictionaries # Quiz 1: Fruit Basket - Task 1 """ You would like to count the number of fruits in your basket. In order to do this, you have the following dictionary and list of fruits. Use the dictionary and list to count the total number of fruits, but you do not want to count the other items in your basket. """ result = 0 basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] #Iterate through the dictionary for key, value in basket_items.items(): for item in fruits: #if the key is in the list of fruits, add the value (number of fruits) #to result if item == key: result = result + value print(result) # Quiz: Fruit Basket - Task 2 """ If your solution is robust, you should be able to use it with any dictionary of items to count the number of fruits in the basket. Try the loop for each of the dictionaries below to make sure it always works. """ #Example 1 result = 0 basket_items = {'pears': 5, 'grapes': 19, 'kites': 3, 'sandwiches': 8, 'bananas': 4} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] # Your previous solution here for key, value in basket_items.items(): for item in fruits: #if the key is in the list of fruits, add the value (number of fruits) #to result if item == key: result = result + value print(result) #Example 2 result = 0 basket_items = {'peaches': 5, 'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] # Your previous solution here for key, value in basket_items.items(): for item in fruits: #if the key is in the list of fruits, add the value (number of fruits) #to result if item == key: result = result + value print(result) #Example 3 result = 0 basket_items = {'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4, 'bears': 10} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] # Your previous solution here for key, value in basket_items.items(): for item in fruits: #if the key is in the list of fruits, add the value (number of fruits) #to result if item == key: result = result + value print("I count {} fruits in the busket".format(result) # Quiz: Fruit Basket - Task 3 # You would like to count the number of fruits in your basket. # In order to do this, you have the following dictionary and list of # fruits. Use the dictionary and list to count the total number # of fruits and not_fruits. fruit_count, not_fruit_count = 0, 0 basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8} fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas'] #Iterate through the dictionary for key, value in basket_items.items(): #if the key is in the list of fruits, add to fruit_count. if key in fruits: fruit_count = fruit_count + value #if the key is not in the list, then add to the not_fruit_count else: not_fruit_count = not_fruit_count + value print("There are {} fruits and {} not fruits".format(fruit_count, not_fruit_count)) # Quiz: Break the String # # Write a loop with a break statement to create a string, news_ticker, that # is exactly 140 characters long. You should create the news ticker by adding # headlines from the headlines list, inserting a space in between each headline. headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok Review: Totally Triffic"] news_ticker = "" headlines = " ".join(headlines) for letter in headlines: news_ticker = news_ticker + letter if len(news_ticker) == 140: break print(news_ticker) # Udacity solution headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok Review: Totally Triffic"] news_ticker = "" for headline in headlines: news_ticker += headline + " " if len(news_ticker) >= 140: news_ticker = news_ticker[:140] break print(news_ticker) # Quiz 1: zip() and enumerate() # # Zip Coordinates x_coord = [23, 53, 2, -12, 95, 103, 14, -5] y_coord = [677, 233, 405, 433, 905, 376, 432, 445] z_coord = [4, 16, -6, -42, 3, -6, 23, -1] labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"] points = [] for num_x, num_y, num_z, letter in zip(x_coord, y_coord, z_coord, labels): points.append("{}: {}, {}, {}".format(letter, num_x, num_y, num_z)) print(points) # Udacity solution: x_coord = [23, 53, 2, -12, 95, 103, 14, -5] y_coord = [677, 233, 405, 433, 905, 376, 432, 445] z_coord = [4, 16, -6, -42, 3, -6, 23, -1] labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"] points = [] for point in zip(labels, x_coord, y_coord, z_coord): points.append("{}: {}, {}, {}".format(*point)) for point in points: print(point) # Quiz 2: zip() and enumerate() # # Zip Lists to a Dictionary cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"] cast_heights = [72, 68, 72, 66, 76] cast = dict(zip(cast_names, cast_heights)) print(cast) # Quiz 3: unzip # # Unzip the cast tuple into two names and heights tuples. cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76)) # define names and heights here names, heights = zip(*cast) print(names) print(heights) # Quiz 4: zip() and enumerate() # # Quiz: Transpose with Zip # Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)) data_transpose = tuple(zip(*data)) print(data_transpose) # Quiz 5: Quiz: Enumerate # # Use enumerate to modify the cast list so that each element contains the name # followed by the character's corresponding height. For example, the first # element of cast should change from "Barney Stinson" to "Barney Stinson 72". cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"] heights = [72, 68, 72, 66, 76] for index, height in enumerate(heights): s = "{} {}".format(cast[index], height) cast[index] = s print(cast)
""" This neural network is to be used to compare to our k-means model. We hope that this model is a good comparison. The code is made by following the implemention by http://neuralnetworksanddeeplearning.com/chap1.html """ # Useful libraries import numpy as np import random # Our Defined Libraries import Sigmoid ################################################################################ # Neural Network Class # ################################################################################ class NeuralNetwork(): # In the initialization of the Neural Network we need a list describing the # neural network, each item represents number of neurons in that level def __init__ (self, n_settings): # Neural network settings self.n_settings = n_settings self.layer_count = len(n_settings) # Weights and Biases are assigned randomly, can improve later! self.biases = [np.random.randn(b, 1) for b in n_settings[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(n_settings[:-1], n_settings[1:])] def processinputs(self, iput): ''' returns outputs in iput is an input ''' for bias, weight in zip(self.biases, self.weights): iput = Sigmoid.sigmoid_vec(np.dot(weight, iput) + bias) return iput # The way that learning occurs is that we have to use a stochastic gradient # descent def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): """Train the neural network using mini-batch stochastic gradient descent. The "training_data" is a list of tuples "(x, y)" representing the training inputs and the desired outputs. The other non-optional parameters are self-explanatory. If "test_data" is provided then the network will be evaluated against the test data after each epoch, and partial progress printed out. This is useful for tracking progress, but slows things down substantially.""" if test_data: n_test = len(test_data) n = len(training_data) for j in xrange(epochs): # For each of the epoch we shuffle data random.shuffle(training_data) # We then take the shuffled data and split the # data into subsets of data mini_batches = [training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size)] # now apply the a setp of gradient descent for mini_batch in mini_batches: #update baches self.update_mini_batch(mini_batch, eta) if test_data: print "Epoch {0}: {1} / {2}".format(j, self.evaluate(test_data), n_test) else: print "Epoch {0} complete".format(j) def update_mini_batch(self, mini_batch, eta): """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The "mini_batch" is a list of tuples "(x, y)", and "eta" is the learning rate.""" nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] self.weights = [w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] def backprop(self, x, y): """Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``.""" nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # process inputs activation = x # list to store all the activations, layer by layer activations = [x] # list to store all the z vectors, layer by layer zs = [] for b, w in zip(self.biases, self.weights): z = np.dot(w, activation) + b zs.append(z) activation = Sigmoid.sigmoid_vec(z) activations.append(activation) # backward pass delta = self.cost_derivative(activations[-1], y) * \ Sigmoid.sigmoid_prime_vec(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) # Here we iterate from the lowest neural layer (layer = 1 is lowest) # all the way up to the highest neural layer for layer in xrange(2, self.layer_count): z = zs[-layer] spv = Sigmoid.sigmoid_prime_vec(z) delta = np.dot(self.weights[-layer+1].transpose(), delta) * spv nabla_b[-layer] = delta nabla_w[-layer] = np.dot(delta, activations[-layer-1].transpose()) return (nabla_b, nabla_w) def evaluate(self, test_data): """ Return the number of test inputs for which the neural network outputs the correct result. The neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation. """ test_results = [(np.argmax(self.processinputs(x)), y) for (x, y) in test_data] return sum(int(x == y) for (x, y) in test_results) def cost_derivative(self, output_activations, y): """Return the vector of partial derivatives \partial C_x / \partial a for the output activations.""" return (output_activations-y)
from Exceptions.Numbers import Numbers n = Numbers() try: num1, num2 = input("Introduce dos numeros separados por comas:") except NameError as ex: print("Exception:", ex) except TypeError: print("No se indicaron los numeros separados por comas") else: print("Solo se ejecuta cuando no entra a nigun except") finally: print("Siempre se ejecuta finally") print(n.sum(num1, num2))
import numpy as np # 损失函数梯度 def DJ(X_b, y, theta): """ :param X_b: 处理之后的矩阵 :param y: y值 :param theta: θ :return res: 梯度向量 """ res = np.empty(len(theta)) res[0] = np.sum((X_b.dot(theta) - y)) for i in range(1, len(theta)): res[i] = np.sum((X_b.dot(theta) - y).dot(X_b[:, i])) return res * 2 / len(X_b) def J(X_b, y, theta): """ :param X_b: :param y: :param theta: :return: 损失函数 """ try: print(np.sum((y - X_b.dot(theta)) ** 2) / len(X_b)) return np.sum((y - X_b.dot(theta)) ** 2) / len(X_b) except: return float('inf') def gradient_descent(X_b, y, init_theta, eta, n_iters=10, eplison=1e-8): """ :param init_theta: theta初始值 :param eta: 系数eta :param eplison: 迭代的临界值 :param n_iters: 拟合的次数上限值 :return theta: 拟合求得得theta向量 """ theta = init_theta # 设定最大的学习次数 n = 0 while n < n_iters: gradient = DJ(X_b, y, theta) last_theta = theta theta = theta - eta * gradient # print("in") print(theta) if (abs(J(x_b, y, theta) - J(X_b, y, last_theta)) < eplison): break n = n + 1 # print(theta) print(n) return theta if __name__ == "__main__": # 创建一个线性相关得矩阵,元素个数100 x = 2 * np.random.random(size=(1000, 1)) y = 3 * x + 4 + np.random.normal(size=(1000, 1)) # 给矩阵加一列常量为1的列 x_b = np.hstack([np.ones((len(x), 1)), x]) init_theta = np.zeros(x_b.shape[1]) eta = 0.01 # print(x_b) # print(J(x_b, y, init_theta)) print(gradient_descent(x_b, y, init_theta, eta))
strHours = input('Enter Hours: ') strRate = input('Enter Rate: ') floatHours = float(strHours) floatRate = float(strRate) if floatHours > 40 : overtimeHours = floatHours - 40 overtimeRate = floatRate * 1.5 # print('') # print('Overtime hours: ' + str(overtimeHours)) # print('Overtime rate: ' + str(overtimeRate)) xp = (40 * floatRate) + (overtimeHours * overtimeRate) else : # print('Regular') xp = floatHours * floatRate print('Pay:', xp)
print("Hello World double quote") print('Hello World single quote') print('O----') print(' !|') print('*' * 10) price = 10 price = 25 print(type(price), price) rate = 2.5 print(type(rate), rate) name = "Naveen" print(type(name), name) isHappy = True print(type(isHappy), isHappy)
import random import string for i in range(3): print(random.random()) print(random.randint(10, 50)) alphabets = string.ascii_lowercase[:26] print("random", random.choice(alphabets)) class Dice: def roll(self): f = random.randint(1, 6) s = random.randint(1, 6) return f, s dice = Dice() print(dice.roll())
#coding=utf-8 import sys """ 掌握内容 1、迭代器有两个基本的方法:iter() 和 next() 2、生成器的yield函数 3、str.strip()把字符串(str)的头和尾的空格,以及位于头尾的\n \t之类给删掉, """ #使用生成器处理文件,用户指定要查找的内容,将文件中匹配到的行输出到屏幕 def read_file(filename,test): with open(filename) as file: for line in file: if test in line: yield line RR = read_file('asd.txt','ds') for readli in RR: print (readli.strip()) #使用生成器,从文件中读取内容,在每一行前加上指定str def modify_file(filename,str): with open(filename) as file: for line in file: yield str + line MM = modify_file('asd.txt','#####') for modifyli in MM: print (modifyli.strip()) #用生成器实现裴波那契数列 def fibonacci(n): # 生成器函数 - 斐波那契 a = 0 b = 1 counter = 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print(next(f), end=" ") except StopIteration: sys.exit()
__author__ = 'jonathan' from collections import OrderedDict # following code inspired from: # http://stackoverflow.com/questions/2437617/limiting-the-size-of-a-python-dictionary class DictionaryWithLimitedSize(OrderedDict): """A python dictionary that has a limited size.""" def __init__(self, *args, **kwds): self.size_limit = kwds.pop("size_limit", None) OrderedDict.__init__(self, *args, **kwds) self._remove_old_items() def __setitem__(self, key, value): """ Set a key/value pair in the dict. At the end, this function will check if old objects should be removed. :param key: a string key :param value: a value """ OrderedDict.__setitem__(self, key, value) self._remove_old_items() def _remove_old_items(self): """ Remove the items that are old. """ if self.size_limit is not None: while len(self) > self.size_limit: self.popitem(last=False)
# -*- coding: utf-8 -*- """ Created on Sun May 19 11:23:37 2019 @author: user """ #create a Node class ListNode: def __init__(self,x): self.val = x self.next = None class Solution: def printListFromTailToHead(self,listNode): alist = [] while listNode: alist.append(listNode.val) listNode = listNode.next return alist[::-1]
# load up the libraries we will need import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn import metrics # load the dataset from the csv file dataset = pd.read_csv('house-prices.csv') # print the first few lines of the data print(dataset.head()) # shows you the dimensionality of the data (rows, columns) print(dataset.shape) # spits out some interesting details about the data print(dataset.describe()) # we always call the independent variables as X # these are our features X = dataset[['Bedrooms', 'Bathrooms', 'Land size sqm']] # the dependent variable is called y y = dataset['Above1.5m'] # lets split our data into training and test sets # the size is mentioned in a number between 0 to 1 # here we have reserved 0.2 (20%) for our test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # instantiate the model (using the default parameters) regressor = LogisticRegression(solver='lbfgs') # fit the model with data regressor.fit(X_train, y_train) # lets make some predictions y_pred = regressor.predict(X_test) # show me the confusion matrix, takes the format # (TrueNegative, FalsePositive, FalseNegative, TruePositive) confusion_matrix = metrics.confusion_matrix(y_test, y_pred).ravel() print(confusion_matrix) # print out some metrics # how often is the prediction correct? print('Accuracy [ (TP + TN)/Total ] :', metrics.accuracy_score(y_test, y_pred)) # whats the ratio of true positives to the all the positives returned print('Precision [ TP/(TP + FP) ] :', metrics.precision_score(y_test, y_pred)) # true positives ratio to how many should have been true postives print('Recall [ TP/(TP + FN) ]:', metrics.recall_score(y_test, y_pred)) # find and show me area under the curve - AUC - ROC y_pred_proba = regressor.predict_proba(X_test)[::,1] false_positive_rate, true_positive_rate, _ = metrics.roc_curve(y_test, y_pred_proba) auc = metrics.roc_auc_score(y_test, y_pred_proba) plt.plot(false_positive_rate, true_positive_rate, label='auc=' + str(auc)) plt.legend(loc=4) plt.show()
list=[1,2,3,4,5] for i in range(len(list)): print(list[i])
def add(a,b): """ this method is to get the sum of two numbers a:number b:number """ s = a+b return s sum = add(10,20)#s print(sum)
name_list = ["david","xavier","jim","alan","jim"] def clearAll(name_list): """ this method is to clear all the elements in a list name_list:list """ name_list.clear() return(name_list)
str1=input('plz input ur str') str2=input('plz input ur str') new_str=str1[:2] print(new_str) str1=str1.replace(str1[:2],str2[:2]) print(str1) str2=str2.replace(str2[:2],new_str) print(str2) new_str=str1+' '+str2 print(new_str)
#insert sort model:队伍的壮大 list=[3,5,6,0,1,2] for i in range(1,len(list)): for j in range(i,0,-1): if list[j-1]>list[j]: num=list[j] list[j]=list[j-1] list[j-1]=num print(list)
#1.准备任务 import threading import time def coding(): print("coding_thread:",threading.current_thread()) for i in range(10): print("coding...") time.sleep(0.3) def debugging(): print("debugging_thread:",threading.current_thread()) for i in range(10): print("debugging...") time.sleep(0.3) if __name__=='__main__': #2.创建进程 coding_thread=threading.Thread(target=coding) debugging_thread=threading.Thread(target=debugging) #Process([group [,target[,name]]) #3.启动进程 coding_thread.start() debugging_thread.start()
age=int(input("plz input your age:"))#str def ifBasic(age): """ this method is to judge if user's inputted age greater than 16. age:age """ if age>=16:#if filter int float return "adult,you can enjoy your happy hour!" print(ifBasic(age))
# 3.2 应用二:计算1-100偶数累加和 def even(): """ this method is to get the sum of all the even numbers from 1-100 """ sum = 0 num=1#初始条件 while num<=100:#判断条件 if num%2==0: sum = sum+num num+=1#while的步进 return(sum)
import random num=random.randint(0,100) uI = int(input("plz enter your input:")) while uI!=num: if uI<num: print('smaller') elif uI>num: print('bigger') uI = int(input("plz enter your input:")) print('bingo')
name_list=['david','xavier','alan','jim'] print(name_list) #del:删除指定元素 del name_list[0] print(name_list) #pop():从list中弹出指定元素 name=name_list.pop(0) print(name_list,name) #remove():删除列表中指定元素(第一个匹配的) name_list.remove('alan') print(name_list) #clear:清空list name_list.clear() print(name_list)
def sorry(): """ this method is to say sorry to your girlfriend though you don't have one """ i = 1 while i <= 5: if i == 3: print('so sick') i += 1 continue print('sorry') i += 1 else: return 'thank you for your forgiveness'
str=input('your sentence?') if str.find('not')!=1 and str.find('poor')!=-1: begin=str.index('not') end=str.index('poor') print(str.replace(str[begin:end+len('poor')],'good',100)) elif str.find('poor')!=-1: print(str)
num_list = [3,5,6,0,1,2] #res_list[] #假设min=3 min=0 #num_list = [3,5,6,1,2] def BubbleSort(num_list): """ this method is to sort the elements form smallest to greatest num_list:array which contains elements """ num = len(num_list)-1 while num>0: for j in range(num): if num_list[j]>num_list[j+1]: temp = num_list[j] num_list[j]=num_list[j+1] num_list[j+1] = temp num-=1#1已经排好序的数 return num_list print(BubbleSort(num_list))
# str="hello" \ # "world" # print(str) def enter(): """ this method is to print a string in a new line """ str=""" hello world """ return(str)
list=[1,2,3,4] # list.append(5) # print(list) # list=["byte","tube"] # list.extend("dal") # print(list) def removeEle(list): """ this method is to remove 1 element in the list and show the length of the list list:list """ list.remove(11,100) return len(list)
class Student(object): def __init__(self,name,gender,grade): self.name=name self.gender=gender self.grade=grade def __str__(self): return f'{self.name},{self.gender},{self.grade}'
integer=100 res=0 while integer>=1: if integer%2==0: if integer==66: integer-=1 continue res+=integer integer-=1 else: print(res)
""" Given a sorted array of integers, return the two numbers that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. """ arr = [-2, 1, 2, 4, 7, 11] target = 13 # Brute Force: # Time complexity: O(n^2) # Space complexity: O(1) def two_sum_brute_force(arr, target): for i in range(len(arr) - 1): for j in range(i + 1, len(arr)): if arr[i] + arr[j] == target: print(arr[i], arr[j]) return True return False # print(two_sum_brute_force(arr, target)) # Hash Tabel: # Time complexity: O(n) # Space complexity O(n) def two_sum_hash_table(arr, target): ht = dict() for i in range(len(arr)): if arr[i] in ht: print(ht[arr[i]], arr[i]) return True else: ht[target - arr[i]] = arr[i] return False # print(two_sum_hash_table(arr, target)) # Time complexity O(n) # Space complexity O(1) def two_sum(arr, target): # Takes advantage of the sorted array i = 0 # pointer at the beginning j = len(arr) -1 # pointer at the end while i <= j: if arr[i] + arr[j] == target: print(arr[i], arr[j]) return True elif arr[i] + arr[j] < target: i += 1 else: # arr[i] + arr[j] < target j -= 1 return False print(two_sum(arr, target))
""" Problem: write a function that takes an array of sorted integers and a key and returns the index of the first occurrence of that key from the array. For example, for the array: [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] with target = 108, the algorithm would return 3, as the first occurrence of 108 in the above array is located at index 3 """ arr = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] target = 108 # Time complexity O(n) def find_target(arr, target): return arr.index(target) print(find_target(arr, target)) # Time complexity O(log n) def find(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] < target: low = mid + 1 elif arr[mid] > target: high = mid - 1 else: if mid - 1 < 0: return mid if arr[mid - 1] != target: return mid high = mid - 1 return None print(find(arr, target))
""" Problem: Given two numbers, find their product using recursion. """ x = 5 y = 3 def product_recursive(num1, num2): # Cutting down in on the number of recursive calls if x < y: return product_recursive(y, x) if num2 == 0: return 0 return num1 + product_recursive(num1, num2 - 1) print(product_recursive(x, y))
""" Problem: Implement an algorithm to determine if a string has all unique characters. """ def unique_char(word): letters = dict() for char in word: if char not in letters: letters[char] = 1 else: letters[char] += 1 unique = "" for k, v in letters.items(): if v > 1: unique += k return len(unique) == 0 # print(unique_char("unique")) # print(unique_char("bear")) def is_unique(s): return len(set(s)) == len(s) # print(is_unique("unique")) # print(is_unique("bear")) """ Problem: Given two strings, write a function to decide if one is a permutation of the other. """ def permutation(s1, s2): arr1 = list(s1) arr2 = list(s2) return sorted(arr2) == sorted(arr1) # print(permutation("driving", "drivign")) # print(permutation("driving", "ddriving")) # print(permutation("the cow jumps over the moon.", "the moon jumps over the cow.")) def is_permutation(str_1, str_2): # remove white space str_1 = str_1.replace(" ", "") str_2 = str_2.replace(" ", "") # Check the lengths if len(str_1) != len(str_2): return False for char in str_1: if char in str_2: str_2 = str_2.replace(char, "") return len(str_2) == 0 # print(is_permutation("driving", "drivign")) # print(is_permutation("driving", "ddriving")) # print(is_permutation("the cow jumps over the moon.", "the moon jumps over the cow.")) """ Problem: Given a string, write a function to decide if it is a palindrome. """ def palindrome(string): # arr1 = list(string) # arr2 = arr1[::-1] # return arr1 == arr2 string = string.replace(" ", "") return string == string[::-1] # print(palindrome("madam")) # print(palindrome("nurses run")) import string def is_palindrome(s): s = s.lower() # remove the punctuation s = s.translate(str.maketrans("", "", string.punctuation)) s = s.replace(" ", "") return s == s[::-1] # print(is_palindrome("madam")) # print(is_palindrome("nurses run")) # print(is_palindrome("computer")) """ Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. """ arr1 = [1, 3, 11, 2, 7] def two_sum1(arr, target): # Nested for loops for i in range(len(arr) - 1): for j in range(i + 1, len(arr)): if arr[i] + arr[j] == target: return i, j # print(two_sum1(arr1, 9)) def two_sum2(arr, target): if len(arr) <= 1: return False nums = dict() for i in range(len(arr)): if arr[i] in nums: print(nums[arr[i]], i) return True else: nums[target - arr[i]] = i return False # print(two_sum2(arr1, 9)) """ Problem: Given an array of integers, every element appears twice except for one. Find that single one. Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ arr2 = [1, 3, 11, 2, 7, 1, 3, 2, 7] def single(arr): nums = dict() for i in arr: if i in nums: nums[i] += 1 else: nums[i] = 1 for k, v in nums.items(): if v == 1: return k # print(single(arr2)) def single2(arr): for i in arr: if arr.count(i) == 1: return i # print(single2(arr2)) def single3(arr): # Using the XOR (^) ans = 0 for i in range(len(arr)): ans ^= arr[i] return ans # print(single3(arr2)) """ Problem: FizzBuzz """ def fizzbuzz(n): arr = list() for i in range(1, n + 1): if i % 3 == 0 and i % 5 == 0: arr.append("FizzBuzz") elif i % 3 == 0: arr.append("Fizz") elif i % 5 == 0: arr.append("Buzz") else: arr.append(i) return arr # print(fizzbuzz(100)) """ Problem: Write an iterative and recursive function that implements the factorial of a number """ def factorial_iterative1(n): if n <= 1: return 1 ans = 1 for i in range(1, n + 1): ans *= i return ans # print(factorial_iterative1(5)) def factorial_recursive1(n): if n <= 1: return 1 return n * factorial_recursive1(n - 1) # print(factorial_recursive1(5)) def factorial_iterative(n): x = 1 for i in range(n, 1, -1): x *= i return x # print(factorial_iterative(5)) """ Problem: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters and that you are given the "true" length of the string. """ def urlify(string): string = string.replace(" ", '%20') return string # print(urlify("Mr. Tony Stark")) """ Problem: Given two strings, check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “act” and “tac” are an anagram of each other. """ def anagram1(s1, s2): letters = dict() for i in s1: if i in letters: letters[i] += 1 else: letters[i] = 1 for i in s2: if i in letters: letters[i] -= 1 else: return False return True # print(anagram1("act", "tac")) # print(anagram1("madam", "nadam")) # print(anagram1("practice makes perfect", "perfect makes practice")) # print(anagram1("allergy", "allergic")) def is_anagram(str_1, str_2): str_1 = str_1.replace(" ", "") str_2 = str_2.replace(" ", "") if len(str_1) != len(str_2): return False str_1 = str_1.lower() str_2 = str_2.lower() alphabet = "abcdefghijklmnopqrstuvwxyz" dict1 = dict.fromkeys(list(alphabet), 0) dict2 = dict.fromkeys(list(alphabet), 0) for i in range(len(str_1)): dict1[str_1[i]] += 1 dict2[str_2[i]] += 1 return dict1 == dict2 # print(is_anagram("act", "tac")) # print(is_anagram("madam", "nadam")) # print(is_anagram("practice makes perfect", "perfect makes practice")) # print(is_anagram("allergy", "allergic")) """ Problem: Given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd. """ matrix = [ [1, 3, 5], [2, 6, 9], [3, 6, 9] ] def matrix_median(matrix): arr = list() for i in matrix: arr.extend(i) arr = sorted(arr) middle = len(arr) // 2 return arr[middle] # print(matrix_median(matrix)) def median_matrix(arr): if len(arr) == 1: vec = arr[0] return vec[len(vec) // 2] else: new_list = [] for row in range(len(arr)): new_list.extend(arr[row]) new_list = sorted(new_list) return new_list[len(new_list) // 2] # print(median_matrix(matrix)) """ Problem: String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string "aabcccccaaa" would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a-z). """ def compression(s): comp_str = "" count = 1 for i in range(len(s) - 1): if s[i] == s[i + 1]: count += 1 else: comp_str += s[i] + str(count) count = 1 comp_str += s[i] + str(count) if len(comp_str) >= len(s): return s else: return comp_str # print(compression("aabcccccaaa")) """ Problem: String Rotation: Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 (e.g. "waterbottle" is a rotation of "erbottlewat"). """ def rotation(s1, s2): arr1 = list(s1) arr2 = list(s2) return sorted(arr1) == sorted(arr2) print(rotation("waterbottle", "erbottlewat")) import string def is_string_rotation1(str_1, str_2): if len(str_1) != len(str_2): return False str_1 = str_1.lower() str_2 = str_2.lower() letters = dict() for i in str_1: if i in letters: letters[i] += 1 else: letters[i] = 1 for i in str_2: if i in letters: letters[i] -= 1 else: return False return True print(is_string_rotation1("waterbottle", "erbottlewat")) print(is_string_rotation1("watertables", "erbottlewat")) def is_string_rotation(str_1, str_2): if len(str_1) != len(str_2): return False str_1 = str_1.lower() str_2 = str_2.lower() dict_1 = dict.fromkeys(list(string.ascii_lowercase), 0) dict_2 = dict.fromkeys(list(string.ascii_lowercase), 0) for i in range(len(str_1)): dict_1[str_1[i]] += 1 dict_2[str_2[i]] += 1 return dict_1 == dict_2 # # print(is_string_rotation("waterbottle", "erbottlewat")) # print(is_string_rotation("watertables", "erbottlewat")) """ Problem: Find the number of 1s in the binary representation of a number. For example: num_ones(2) = 1 -- since "10" is the binary representation of the number "2". num_ones(5) = 2 -- since "101" is the binary representation of the number "5" num_ones(11) = 3 -- since "1011" is the binary representation of the number "11" """ def num_of_ones(num): binary = "{0:b}".format(num) # or could use bin(num) return binary.count("1") print(num_of_ones(2)) print(num_of_ones(5)) print(num_of_ones(11)) # Approach 1: using bin() def num_ones(num): one_sum = 0 bin_rep = bin(num)[2:] for i in bin_rep: one_sum += int(i) return one_sum print(num_ones(2)) print(num_ones(5)) print(num_ones(11)) # Approach 2: without bin() def ones_count(num): one_sum = 0 while num: one_sum += num & 1 num >>= 1 return one_sum print(ones_count(2)) print(ones_count(5)) print(ones_count(11))
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): cur_node = self.head while cur_node: print(cur_node.data) cur_node = cur_node.next def append(self, data): new_node = Node(data) if self.head is None: self.head = new_node return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node class CircularLinkedList: def __init__(self): self.head = None def prepend(self, data): new_node = Node(data) cur_node = self.head new_node.next = self.head if not self.head: new_node.next = new_node else: while cur_node.next != self.head: cur_node = cur_node.next cur_node.next = new_node self.head = new_node def append(self, data): if not self.head: self.head = Node(data) self.head.next = self.head else: new_node = Node(data) cur_node = self.head while cur_node.next != self.head: cur_node = cur_node.next cur_node.next = new_node new_node.next = self.head def print_list(self): cur_node = self.head while cur_node: print(cur_node.data) cur_node = cur_node.next if cur_node == self.head: break def remove_node(self, node): if self.head == node: cur_node = self.head while cur_node.next != self.head: cur_node = cur_node.next cur_node.next = self.head.next self.head = self.head.next else: cur_node = self.head prev = None while cur_node.next != self.head: prev = cur_node cur_node = cur_node.next if cur_node == node: prev.next = cur_node.next cur_node = cur_node.next def __len__(self): count = 0 cur_node = self.head while cur_node: count += 1 cur_node = cur_node.next if cur_node == self.head: break return count def split_list(self): size = len(self) if size == 0: return None if size == 1: return self.head mid = size // 2 count = 0 prev = None cur_node = self.head while cur_node and count < mid: count += 1 prev = cur_node cur_node = cur_node.next prev.next = self.head split_cllist = CircularLinkedList() while cur_node.next != self.head: split_cllist.append(cur_node.data) cur_node = cur_node.next split_cllist.append(cur_node.data) self.print_list() split_cllist.print_list() def is_circular_linked_list(self, input_list): cur = input_list.head while cur.next: cur = cur.next if cur.next == input_list.head: return True return False cllist = CircularLinkedList() cllist.append(1) cllist.append(2) cllist.append(3) cllist.append(4) cllist.print_list() print("~~~~~~~~~~~~~~~~~~~~~~~~~") llist = LinkedList() llist.append(1) llist.append(2) llist.append(3) llist.append(4) llist.print_list() print("^^^^^^^^^^^^^^^^^^^^^^^^^^^") print(cllist.is_circular_linked_list(cllist)) print(cllist.is_circular_linked_list(llist))
size = int(input()) array_input = [] for x in range(size): array_input.append([int(y) for y in input().split()]) print(array_input) for i in array_input: for j in i: print(j, end=" ") print()
""" Walrus Operator ":=" """ def func(x): return x + 1 if (x := func(4)) >= 5: print(x) (walrus := func(2)) # print(walrus) """ String Intern => Mutability of Objects Intern: A method of storing only one copy of each distinct string value, which must be immutable. """ a = "".join(['o', 'k', 'a', 'y']) b = 'o' + 'k' + 'a' + 'y' # b and c are pointing to the same object c = "okay" # b and c are pointing to the same object # print(a is b) # the interpreter doesn't know what will the value of a is going to be. Thus, stored as a separate object. # print(a is c) # print(b is c) """ 'is' is not the same as '==' . '==' compares the equivalence of objects. 'is' checks the id of the objects, same objects """ # print(a == b) # print(a == c) # print(b == c) """ Chained Operations 1 AND True are the same """ # print((1 == 1) in [1]) # # print(1 == (1 in [1])) # # print(1 < (0 < 1)) # # print(1 < 0 < 1) # this valued as => 1 < 0 and 0 < 1 """ Dictionary Key Hashing """ d = {} d[1] = "hi" d[1.0] = "hello" d[2 - 1] = "yo" # print(d) # x = hash(1) # y = hash(2 - 1) # z = hash(1.0) # print(x == y) # print(x == z) """ all() function: Takes an iterable object and tells me if all the values in it are equal to True """ # print(all([1, 2, 3, False])) # print(all([1, 2, 3])) # an empty nested list == False # print(all([[]])) # print(all([[1]])) """ Not: has a lower precedent to the '==' """ x = True y = False print(not x == y) # this is evaluated as (not (x == y)) # print(x == not y) print(x == (not y)) """ Guess the output """ a, b = a[b] = {}, 5 print(a, b) """ {...} => AKA circular reference: this data structure is the same as the data structure inside of it """
from numpy import * from matplotlib.pyplot import * # Create 100 equidistant points between 0 and 2*pi xs = linspace(0, 2.*pi, 100) # Create a title for the plot title("How to make plots") # Create labels for the axes # Note that in the label, you can use TeX-strings! xlabel("$x$") ylabel("$f(x)$") # Now create two plots of different functions in a single figure plot(xs, sin(xs), 'o-', label="$f(x)=\sin(x)$") plot(xs, sin(xs)**2, '*:', label="$f(x)=\sin^2(x)$") # Now create the legend box legend() # Create a second plot in loglog scale figure() title("A second plot, this time in loglog scale") loglog(xs, xs**2, 'o-', label="$f(x)=x^2$") loglog(xs, xs**0.5, '*:', label="$f(x)=\sqrt{x}$") legend() # Create a third plot with four subplots figure("A title for the window") # Select a subplot # '221' describes the number of subplots in the figure and which subplot to select # '22' tells to make a grid of 2 by 2 subplots # '1' tells to select the first plot subplot(221, title="$\sin(x)$") plot(xs, sin(xs)) subplot(222, title="$\cos(x)$") plot(xs, cos(xs)) subplot(223, title="$\sin^2(x)$") plot(xs, sin(xs)**2) subplot(224, title="$\cos^2(x)$") plot(xs, cos(xs)**2) show()
import random import time import sys import os class TicTacToe: board = ['_', '|', '_', '|', '_', '_', '|', '_', '|', '_', ' ', '|', ' ', '|', ' '] remaining_choices = ['1', ' ', '2', ' ', '3', ' ', '4', ' ', '5', ' ', '6', ' ', '7', ' ', '8', ' ', '9'] player_game_piece = str comp_game_piece = str valid_board_choices = {1:0, 2:2, 3:4, 4:5, 5:7, 6:9, 7:10, 8:12, 9:14} valid_remaining_choices = {1:0, 2:2, 3:4, 4:6, 5:8, 6:10, 7:12, 8:14, 9:16} won_game = False players = int coin_toss = int def number_of_players(self): """ Choose number of players. If only 1 player is selected, pc_choice is called to be opponent. """ self.players = int(input("1 or 2 players? ")) while self.players != 1 and self.players != 2: self.players = int(input("Please select 1 or 2 players: ")) if self.players == 1: self.player_game_piece = input("Would you like to be X or O? ").upper() if self.player_game_piece == "X": self.comp_game_piece = "O" else: self.comp_game_piece = "X" elif self.players == 2: self.player_game_piece = input("Which piece would Player_1 like to be? X or O ").upper() if self.player_game_piece == "X": self.comp_game_piece = "O" else: self.comp_game_piece = "X" while self.player_game_piece.upper() != "X" and self.player_game_piece.upper() != "O": self.player_game_piece = input("Please choose between X or O ").upper() return self.players, self.player_game_piece def draw_board(self): """ Draws the actual board, but also the remaining valid choices in a quantitative format so that it's a bit easier to know what your options are. """ print("".join(self.board[:5]), end=" ") print("".join(self.remaining_choices[:6])) print("".join(self.board[5:10]), end=" ") print("".join(self.remaining_choices[6:12])) print("".join(self.board[10:15]), end=" ") print("".join(self.remaining_choices[12:])) def player_choice(self, game_piece): """ Asks player for an input from 1 to 9 (possible locations where a piece can be put are in self.valid_choices defined in __init__ method) and then removes that choice from self.remaining_choices. """ self.draw_board() choice = int(input("Please select a number from 1 to 9 ")) print() while choice not in [1, 2, 3, 4, 5, 6, 7, 8, 9]: choice = int(input("Please select a number from 1 to 9 ")) print() if self.board[self.valid_board_choices[choice]] == game_piece or self.board[self.valid_board_choices[choice]] == self.comp_game_piece: choice = int(input("That space is already occupied,\n please select another number 1 to 9 ")) print() else: self.remaining_choices.remove(str(choice)) self.board[self.valid_board_choices[choice]] = game_piece self.remaining_choices.insert(self.valid_remaining_choices[choice], game_piece) return choice def pc_choice(self): """ Method called if only one player is selected. pc_choice randomly selects one of the available locations from self.valid_remaining_choices """ choice = random.randrange(1,10) if self.board[self.valid_board_choices[choice]] == " " or self.board[self.valid_board_choices[choice]] == "_": self.board[self.valid_board_choices[choice]] = self.comp_game_piece self.remaining_choices.remove(str(choice)) self.remaining_choices.insert(self.valid_remaining_choices[choice], self.comp_game_piece) else: while self.board[self.valid_board_choices[choice]] != " " and self.board[self.valid_board_choices[choice]] != "_": choice = random.randrange(1, 10) self.board[self.valid_board_choices[choice]] = self.comp_game_piece self.remaining_choices.remove(str(choice)) self.remaining_choices.insert(self.valid_remaining_choices[choice], self.comp_game_piece) return choice def game_over(self): """ Checks self.board to see if a win condition (3 game pieces in a row) has been met. """ if self.remaining_choices[0:5:2] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[0:5:2] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[5:10:2] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[5:10:2] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[10::2] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[10::2] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[0:13:6] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[0:13:6] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[2:14:6] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[2:14:6] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[4::6] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[4::6] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[0::8] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[0::8] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[4:13:4] == [self.player_game_piece] * 3: print("Player_1 Wins!") self.draw_board() self.won_game = True elif self.remaining_choices[4:13:4] == [self.comp_game_piece] * 3: print("Player_2 Wins!") self.draw_board() self.won_game = True def play_game(self): """ Flips coin to decide who goes first. Will continue loop until self.won_game = True """ self.number_of_players() self.coin_toss = random.randint(1,2) ## Loop for if there is 1 player. if self.players == 1: if self.coin_toss == 1: print("Player_1 goes first.") time.sleep(2) while not self.won_game: self.player_choice(self.player_game_piece) self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": os.system("cls") start_game = TicTacToe() start_game.play_game() else: sys.exit() self.pc_choice() self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": start_game = TicTacToe() start_game.play_game() else: sys.exit() else: print("Player_2 goes first.") time.sleep(2) while not self.won_game: self.pc_choice() self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": os.system("cls") start_game = TicTacToe() start_game.play_game() else: sys.exit() else: pass self.player_choice(self.player_game_piece) self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": os.system("cls") start_game = TicTacToe() start_game.play_game() else: sys.exit() else: pass ## Loop for if there are 2 players. elif self.players == 2: if self.coin_toss == 1: print("Player_1 goes first") while not self.won_game: self.player_choice(self.player_game_piece) self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": os.system("cls") start_game = TicTacToe() start_game.play_game() else: sys.exit() print("Player_2's turn.") self.player_choice(self.comp_game_piece) self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": os.system("cls") start_game = TicTacToe() start_game.play_game() else: sys.exit() print("Player_1's turn.") elif self.coin_toss == 2: print("Player_2 goes first") while not self.won_game: self.player_choice(self.comp_game_piece) self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": os.system("cls") start_game = TicTacToe() start_game.play_game() else: sys.exit() print("Player_1's turn.") self.player_choice(self.player_game_piece) self.game_over() if self.won_game: play_again = input("Would you like to play again? (Y/N) ").upper() if play_again == "Y": os.system("cls") start_game = TicTacToe() start_game.play_game() else: sys.exit() print("Player_2's turn.") if __name__ == "__main__": start_game = TicTacToe() start_game.play_game()
import urllib import urllib2 import requests # Test URL url = "http://rfunction.com/code/1202/120202.R" # 1. Using urllib module print "Begin download with urllib" urllib.urlretrieve(url, "code1.R") # 2. Using urllib2 module print "Begin download with urllib2" f = urlllib2.urlopen(url) with open("code2.R", "wb") as code : code.write(f.read()) # 3. Using requests print "Begin download with requests" r = requests.get(url) with open("code3.R", "wb") as code : code.write(r.content)
#!/usr/bin/python # -*- coding: UTF-8 -*- a = 21 b = 10 c = 0 if ( a == b ): print ("1 - a=b") else: print ("1 - a!=b") if ( a != b ): print ("2 - a!=b") else: print ("2 - a=b") if ( a <> b ): print ("3 - a!=b") else: print ("3 - a=b") if ( a < b ): print ("4 - a<b" ) else: print ("4-a>=b") if ( a > b ): print "5 - a>b" else: print "5 - a<=b" # 修改变量 a 和 b 的值 a = 5; b = 20; if ( a <= b ): print "6 - a<=b" else: print "6 - a>b" if ( b >= a ): print "7 - b>=b" else: print "7 - b<b"
#!/usr/bin/python # -*- coding: UTF-8 -*- list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # 输出完整列表 print list[0] # 输出列表的第一个元素 print list[1:3] # 输出第二个至第三个的元素 print list[2:] # 输出从第三个开始至列表末尾的所有元素 print tinylist * 2 # 输出列表两次 print list + tinylist # 打印组合的列表 ''' 非法,不能重新赋值 list[1]=20 print list '''
#!/usr/bin/python # -*- coding: UTF-8 -*- # 可写函数说明 def changeme(mylist): u"修改传入的列表" mylist.append([1,2,3,4]); print u"函数内取值: ", mylist return # 调用changeme函数 mylist = [10,20,30]; changeme(mylist); print u"函数外取值: ", mylist
import numpy as np import matplotlib.pyplot as plt x=np.arange(-5,5,0.01) y=x**3 plt.axis([-6,6,-10,10]) #plt.ylim() plt.plot(x,y) plt.show() plt.grid(True)
def Print(msg): print msg def Add(x, y): z = x + y ret = Print("Hello, python!") print "ret: ", ret ret = Add(3, "2") print "ret: ", ret
import numpy as np import matplotlib.pyplot as plt # arange is similar to function range, but returns NumPy array of floats x = np.arange(-2 * np.pi, 2 * np.pi, 0.1) # NumPy functions return NumPy arrays cos_x = np.cos(x) sin_x = np.sin(x) # Demonstrate PyPlot interface to matplotlib plt.figure() plt.plot(x, cos_x, label='cos(x)', linewidth=2) plt.plot(x, sin_x, label='sin(x)', linewidth=2) plt.xlabel('x') plt.ylabel('y') # Display the legend, which is automatically built from line labels plt.legend() # Figure won't appear until we call show() plt.show()
"""Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. """ from itertools import count # Собираем числа от 1 до n и сразу считаем их сумму n = 4 nums = [] nums_sum = 0 for el in count(1): if el > n: break else: nums_sum += el nums.append(str(el)) # Записываем в виде строки и выводим сумму на экран with open(f'5-05-nums.txt', 'w') as file: file.write(' '.join(nums)) print(f'Your data saved in \'5-05-nums.txt\' file\nTotal sum: {nums_sum}')
""" Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. """ class MyZeroDiv(Exception): def __str__(self): return 'You trying to division on zero' try: x = int(input('Insert first number: ')) y = int(input('Insert second number: ')) if y == 0: raise MyZeroDiv print(x / y) except ValueError: print('Use numbers only') except MyZeroDiv: print('You trying to division on zero')
"""Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке.""" with open('5-02-text.txt') as file: i = 1 words_len = {} # Собираем пары "номер строки: количество слов" for line in file: words_len.update({i: len(line.strip().split(' '))}) i += 1 # Считаем количество строк и выводим lines_len = len(words_len) print(f'{lines_len} lines total \n') # Выводим пары из словаря words_len for k, v in words_len.items(): print(f'line {k}: {v} word(s)')
number = int(input("Введите число ")) degree2 = '{}{}'.format(number, number) degree3 = '{}{}'.format(degree2, number) sum = number + int(degree2) + int(degree3) print(sum)
input_month = int(input("Введи порядковый номер месяца - ")) #Решение с dict seasons_dict = {'Зима':{11,12,1},'Весна':{2,3,4}, 'Лето':{5,6,7}, 'Осень':{8,9,10}} for key,val in seasons_dict.items(): if input_month in val: print(key) #Решение с list seasons_month = [ [11, 12, 1], [2, 3, 4], [5, 6, 7], [8, 9, 10] ] seasons_list = ['Зима', 'Весна', 'Лето', 'Осень'] for i,value in enumerate(seasons_month): if input_month in value: print(seasons_list[i])
import numpy as np import matplotlib.pylab as plt %matplotlib inline def f(X): return (X[0]**2 + X[1] - 11)**2 + (X[0] + X[1]**2 - 7)**2 # Аналитический способ вычисления производных def theory_df(X): derivative_x1 = 2 * (-7 + X[0] + X[1] ** 2 + 2 * X[0] * (-11 + X[0]**2 + X[1])) derivative_x2 = 2 * (-11 + X[0]**2 + X[1] + 2 * X[1] * (-7 + X[0] + X[1] ** 2)) return np.array([derivative_x1, derivative_x2]) def theory_ddf(X): derivative_x1_x1 = -42 + 12 * X[0]**2 + 4 * X[1] derivative_x2_x2 = -26 + 4 * X[0] + 12 * X[1]**2 derivative_x1_x2 = 4 * (X[0] + X[1]) return np.array([[derivative_x1_x1, derivative_x1_x2], [derivative_x1_x2, derivative_x2_x2]]) # Численный способ вычисления производных # Метод конечных разностей def numerical_df(X, dx = 1e-6): derivative_x1 = (f([X[0] + dx, X[1]]) - f([X[0] - dx, X[1]])) / (2*dx) derivative_x2 = (f([X[0], X[1] + dx]) - f([X[0], X[1] - dx])) / (2*dx) return np.array([derivative_x1, derivative_x2]) def numerical_ddf(X, dx = 1e-3): derivative_x1_x1 = (f([X[0] + dx, X[1]]) - 2 * f([X[0], X[1]]) + f([X[0] - dx, X[1]])) / (dx**2) derivative_x2_x2 = (f([X[0], X[1] + dx]) - 2 * f([X[0], X[1]]) + f([X[0], X[1] - dx])) / (dx**2) derivative_x1_x2 = (f([X[0] + dx, X[1] + dx]) - f([X[0], X[1] - dx]) - f([X[0] - dx, X[1]]) + f([X[0] + dx, X[1] + dx])) / (4 * dx**2) return np.array([[derivative_x1_x1, derivative_x1_x2], [derivative_x1_x2, derivative_x2_x2]]) # Метод from numpy import linalg def newton(X0, df, ddf, e): X_k = X0 while linalg.norm(df(X_k)) > e: X_k = X_k - np.dot(linalg.inv(ddf(X_k)), df(X_k)) return X_k # newton([4, 3], theory_df, theory_ddf, 0.0001) newton([4, 3], numerical_df, numerical_ddf, 0.0001) array([3.3851536 , 0.07385336]) [[None, None], [None, None]]
# Inspired by "12 Beginner Python Projects - Coding Course" from FreeCodeCamp. # Added input validation, games keeps replaying untill user types 'exit' (loop) & # displays computer's pick to the player. import random import pyinputplus as pyip def play(): global user global computer print("Make your choice: 'r' for rock, 'p' for paper and 's' for scissors:") user = pyip.inputRegex(r'(r|p|s|exit)') computer = random.choice(['r','p','s']) if user == "exit": return "Thank you so much for playing!" if user == computer: return "It's a tie!" if is_win(user, computer): return "You Won!" return "You lost!" def is_win(player,opponent): # return true if player wins # r > s, s > p, p > r if (player == "r" and opponent == "s") or (player == "s" and opponent == "p") \ or (player == "p" and opponent == "r"): return True print("Welcome to 'Rock, Paper, Scissors!'") print("You can quit anytime by typing 'exit'.\n") user = "" while True: print(play()) if user == "exit": break if computer == 'r': print("The computer picked 'rock'.") if computer == 'p': print("The computer picked paper.") if computer == 's': print("The computer picked 'scissors'.")
# Guess The Number Game # Challenge 3, chapter 3 python for the absolute beginner # The player has to guess the number (between 1 and 30). # The player has 5 chances to guess, otherwise he gets a chastising message. import random print("\t\t\t\t\t\tGuess the right number!") print("\nChoose a number between 1 and 30.") print("You have 5 chances to get it right.\n") # Initial values number = random.randint(1, 30) guess = "" tries = 0 while guess != number: guess = int(input("Guess the number: ")) tries += 1 if tries > 5: print("\nYou didn't guess the right number in time, you loser!") break elif guess > number: print("Lower...") elif guess < number: print("Higher...") if guess == number: print("\nYou won!") print(f"\nIt took you {tries} tries.") print(f"The correct number was: {number}") input("\nPress enter to exit the program.")
#! python3 # 2048.py - my solution to practice project "2048" # from "Automate The Boring Stuff". # 2048 is a game where you combine tiles by sliding them using the arrow keys. from selenium import webdriver from selenium.webdriver.common.keys import Keys import time browser = webdriver.Firefox() browser.get('https://play2048.co') htmlElem = browser.find_element_by_tag_name('html') # You can get a fairly high score by repeatedly sliding in an up, right, # down and left pattern over and over again. # Using time.sleep() to slow down the movements so you can actually see # the gameplay. while True: htmlElem.send_keys(Keys.UP) time.sleep(0.3) htmlElem.send_keys(Keys.RIGHT) time.sleep(0.3) htmlElem.send_keys(Keys.DOWN) time.sleep(0.3) htmlElem.send_keys(Keys.LEFT) time.sleep(0.3) # Game over? Simply click "Try again" to let the program continue.
# Задание 2 from random import randint list = [] for i in range(15): # создание списка a = randint(0, 100) a = int(a) list.append(a) print(list) print([list[i] for i in range(len(list)) if list[i] > list[i - 1]]) # вывод значений #
# Задание 4 #без генератора my_list = [1, 2, 1, 2, 5, 6, 13, 2] my_set = set(my_list) #print(my_set) - тестовая строка new_list = list(my_set) print(new_list) #с генератором from random import randint my_list = [] for i in range(15): # создание списка a = randint(0, 10) a = int(a) my_list.append(a) print(my_list) my_set = set(my_list) #print(my_set) - тестовая строка new_list = list(my_set) print(new_list)
# raise案例-2 # 自己定义异常 # 需要注意: 自定义异常必须是系统异常的子类 class DanaValueError(ValueError): pass try: print("我爱王晓静") print(3.1415926) # 手动引发一个异常 # 注意语法:raise ErrorClassName raise DanaValueError print("还没完呀") except NameError as e: print("NameError") except DanaValueError as e: print('DanaValueError') except ValueError as e: print("ValueError") except Exception as e: print("有异常") finally: print("我肯定会被执行的")
from tkinter import messagebox from tkinter import * import numpy as np b = [] h = [] j = [] k = [] root = Tk() root.title(" Solving simultaneous linear equations ") root.geometry('650x1900') root.configure(bg='teal') dg = Label(root, text='enter names of variables in the equations ') dg.grid(column=0, row=0, columnspan=3, padx=20, pady=20) gg = Entry(root, width=35, borderwidth=5) gg.grid(column=0, row=1, columnspan=2, padx=20, pady=20) dd = Label(root, text="considering the equations in general form, like for a 3 variable linear equation ax+by+cz=d \n" "enter the values of co efficient of each variable in order ") dd.grid(column=0, row=2, columnspan=3, padx=20, pady=30) e = Entry(root, width=35, borderwidth=5) e.grid(column=0, row=3, columnspan=2, padx=20, pady=30) con = Label(root, text=" similarly enter the constants in order ") con.grid(column=0, row=5, columnspan=3, padx=20, pady=30) cons = Entry(root, width=35, borderwidth=5) cons.grid(column=0, row=6, columnspan=2, padx=20, pady=30) def enter1(): f_m = gg.get() if f_m not in k: if f_m.isalpha(): k.append(f_m) else: messagebox.showerror( 'INVALID ENTRY', 'YOU HAVE ENTERED NOTHING OR A NUMBER. PLEASE INSERT A VARIABLE NAME') global ll ll = Listbox(root, height=8, width=15) for i in k: ll.insert(END, i) ll.grid(row=1, column=3, columnspan=3, padx=3, pady=3) gg.delete(0, END) else: messagebox.showerror( 'INVALID ENTRY', 'YOU HAVE ENTERED THE SAME NAME OF VARIABLE AGAIN. PLEASE ENTER PROPER NAME OF VARIABLE') def enter2(): f_m = e.get() u = f_m.split() if f_m.isnumeric() and (len(k) == 0 or len(k) == 1): f_n = float(f_m) b.append(f_n) else: try: f_n = float(f_m) except: messagebox.showerror( 'INVALID ENTRY', 'YOU HAVE ENTERED NOTHING OR A STRING. PLEASE ENTER A NUMBER') else: b.append(f_n) global lb lb = Listbox(root, height=9, width=15) for i in b: lb.insert(END, i) lb.grid(row=3, column=3, columnspan=3, padx=3, pady=2) e.delete(0, END) def enter3(): f_m = cons.get() if f_m.isnumeric() and (len(k) == 0 or len(k) == 1): f_n = float(f_m) h.append(f_n) else: try: f_n = float(f_m) except: messagebox.showerror( 'INVALID ENTRY', 'YOU HAVE ENTERED NOTHING OR A STRING. PLEASE ENTER A NUMBER') else: h.append(f_n) global ld ld = Listbox(root, height=4) for i in h: ld.insert(0, i) ld.grid(row=6, column=3, columnspan=3) cons.delete(0, END) def clear(): gg.delete(0, END) e.delete(0, END) cons.delete(0, END) def done(): root.destroy() btenter1 = Button(root, text='Enter', padx=40, pady=20, command=enter1) btenter2 = Button(root, text='Enter', padx=40, pady=20, command=enter2) btenter3 = Button(root, text='Enter', padx=40, pady=20, command=enter3) btdone = Button(root, text='Done', padx=40, pady=20, command=done) btclear = Button(root, text='clear', padx=40, pady=20, command=clear) btenter1.grid(row=1, column=2) btenter2.grid(row=3, column=2) btenter3.grid(row=6, column=2) btdone.grid(row=7, column=2) btclear.grid(row=7, column=1) root.mainloop() n = len(k) if n == 0: messagebox.showerror('INSUFFICIENT ENTRY', 'PLEASE ENTER THE REQUIRED INPUT') messagebox.showinfo('YOU HAVE ENCOUNTERED A ERROR', 'INSUFFICIENT INPUT PROVIDED. PLEASE RUN THE PROGRAM AGAIN') else: if len(b) != n**2: messagebox.showerror( 'INSUFFICIENT ENTRY', 'YOU HAVE NOT ENTERED ALL THE VALUES IN COEFFICIENT MATRIX') messagebox.showinfo('YOU HAVE ENCOUNTERED A ERROR', 'THE COEFFICIENT MATRIX IS INCOMPLETE. PLEASE RUN THE PROGRAM PROGRAM') elif len(h) != n: messagebox.showerror( 'INSUFFICIENT ENTRY', 'YOU HAVE NOT ENTERED ALL THE VALUES IN CONSTANT MATRIX') messagebox.showinfo('YOU HAVE ENCOUNTERED A ERROR', 'THE CONSTANT MATRIX IS INCOMPLETE. PLEASE RUN THE PROGRAM AGAIN') else: z = 0 c = [[0 for i in range(n)]for j in range(n)] for i in range(n): # taking the value of matrix A for j in range(n): c[i][j] = b[z] z = z+1 if h == [0 for i in range(n)]: global det det = np.linalg.det(c) if det == 0: root1 = Tk() root1.title(" Solving simultaneous linear equations ") root1.geometry('100x100') p = Label(text='the system has infinitely many solutions ').grid( row=0, column=0, columnspan=3) root1.mainloop() else: root2 = Tk() root2.title(" Solving simultaneous linear equations ") root2.geometry('100x100') q = Label(text=" the system has trivial solution that is X ").grid( row=0, column=0, columnspan=3) root2.mainloop() else: if np.linalg.det(c) == 0: jk = Tk() jk.title("Solving simultaneous linear equations ") jk.geometry('100x100') jk.config(bg='teal') w = Label(text='the system of equation given has no solutions').grid( row=0, column=0, columnspan=3) jk.mainloop() else: j = np.linalg.solve(c, h) d = list(zip(k, j)) lol = Tk() lol.title(" Solving simultaneous linear equations ") lol.geometry('550x500') lol.config(bg='teal') ha = Label(lol, text=" the solution for the given linear equation is").grid( row=0, column=0, columnspan=3) hh = Listbox(lol, width=40) for i in range(n): hh.insert(0, d[i]) hh.grid(row=1, column=0, columnspan=3) lol.mainloop()
Number = input("Enter a number") Number = int(Number) if Number > 10: print(str(Number) + " is greater than 10") elif Number == 10: print(str(Number) + " is 10") elif Number < 10: print(str(Number) + " is less than 10")
formula = input() splited_by_minus = formula.split("-") sum = 0 for num in splited_by_minus[0].split("+"): sum += int(num) for i in range(1, len(splited_by_minus)): for num in splited_by_minus[i].split("+"): sum -= int(num) print(sum)
import arcade from .game import GameObject UP = "up" DOWN = "down" RIGHT = "right" LEFT = "left" POSITIVE_DIRECTION = 1 NEGATIVE_DIRECTION = -1 NEUTRAL_DIRECTION = 0 START_DIRECTION_X = POSITIVE_DIRECTION START_DIRECTION_Y = NEUTRAL_DIRECTION class SnakeTurningPoint(GameObject): """ Holds the data that represent where in the game's Cartesian plane a `SnakeBodySegment` should change its direction. """ BODY_WIDTH = 10 BODY_HEIGHT = 10 def __init__(self, x, y, direction): super().__init__(x, y, self.BODY_WIDTH, self.BODY_HEIGHT) self.direction = direction @property def data(self): return self.x, self.y, self.direction def draw(self): arcade.create_rectangle_filled( center_x=self.x, center_y=self.y, width=self.width, height=self.height, color=arcade.color.WHITE, ).draw() class SnakeBodySegment(GameObject): """ Represents a node in the `Snake`'s doubly linked list body so that every `SnakeBodySegment` stores a reference to its previous and next neighbours. That makes it easier to check and propagate turning points in the snake's body. """ BODY_WIDTH = 10 BODY_HEIGHT = 10 def __init__(self, x, y, direction_x, direction_y, speed): super().__init__(x, y, self.BODY_WIDTH, self.BODY_HEIGHT) self.direction_x = direction_x self.direction_y = direction_y self.speed = speed self.turning_point = None self.previous = None self.next = None @property def is_moving_up(self): return ( self.direction_x == NEUTRAL_DIRECTION and self.direction_y == POSITIVE_DIRECTION ) @property def is_moving_down(self): return ( self.direction_x == NEUTRAL_DIRECTION and self.direction_y == NEGATIVE_DIRECTION ) @property def is_moving_left(self): return ( self.direction_x == NEGATIVE_DIRECTION and self.direction_y == NEUTRAL_DIRECTION ) @property def is_moving_right(self): return ( self.direction_x == POSITIVE_DIRECTION and self.direction_y == NEUTRAL_DIRECTION ) @property def is_moving_vertically(self): return self.direction_x == NEUTRAL_DIRECTION @property def is_moving_horizontally(self): return self.direction_y == NEUTRAL_DIRECTION @property def can_turn_direction(self): return not self.next or not self.next.turning_point def move(self): self.x += self.direction_x * self.speed self.y += self.direction_y * self.speed self.check_turning_point() def turn_up(self): self.turn(UP) def turn_down(self): self.turn(DOWN) def turn_left(self): self.turn(LEFT) def turn_right(self): self.turn(RIGHT) def turn(self, direction, propagate_turning_point=True): if direction not in (UP, DOWN, LEFT, RIGHT) or not self.can_turn_direction: return turned = False if direction == UP and self.is_moving_horizontally: self.direction_x = NEUTRAL_DIRECTION self.direction_y = POSITIVE_DIRECTION turned = True elif direction == DOWN and self.is_moving_horizontally: self.direction_x = NEUTRAL_DIRECTION self.direction_y = NEGATIVE_DIRECTION turned = True elif direction == LEFT and self.is_moving_vertically: self.direction_x = NEGATIVE_DIRECTION self.direction_y = NEUTRAL_DIRECTION turned = True elif direction == RIGHT and self.is_moving_vertically: self.direction_x = POSITIVE_DIRECTION self.direction_y = NEUTRAL_DIRECTION turned = True if turned and propagate_turning_point: self.propagate_turning_point(direction) def grow(self): self.next = SnakeBodySegment( x=self.x, y=self.y, direction_x=self.direction_x, direction_y=self.direction_y, speed=self.speed, ) self.next.previous = self self.next.fix_segment_positions(self.x, self.y) def propagate_turning_point(self, direction, x=None, y=None): """ Set to next body segment a Cartensian coordinate where it will turn to given `direction`. """ if not self.next: return x = x or self.x y = y or self.y self.next.turning_point = SnakeTurningPoint(x, y, direction) def check_turning_point(self): """ Make sure to change a body segment's direction if it has reached a turning point. """ if self.turning_point is None: return target_x, target_y, target_direction = self.turning_point.data reached_x = self._has_reached_target_x reached_y = self._has_reached_target_y reached = reached_x(target_x, target_direction) or reached_y( target_y, target_direction ) if not reached: return self.fix_segment_positions(target_x, target_y) self.turn(target_direction, propagate_turning_point=False) self.propagate_turning_point(target_direction, target_x, target_y) self.turning_point = None def fix_segment_positions(self, target_x, target_y): """ Make sure to align segments when they reach a turning point. """ if self.previous is None: return elif self.previous.is_moving_horizontally: direction = -1 * self.previous.direction_x self.x = self.previous.x + direction * self.BODY_WIDTH self.y = target_y else: direction = -1 * self.previous.direction_y self.y = self.previous.y + direction * self.BODY_HEIGHT self.x = target_x def draw(self): """ Draw the snake segment and the turning point if there's one, because that makes the snake's movement animation smoothier). """ arcade.create_rectangle_filled( center_x=self.x, center_y=self.y, width=self.width, height=self.height, color=arcade.color.WHITE, ).draw() if self.turning_point: self.turning_point.draw() def _has_reached_target_y(self, target_y, target_direction): return ( target_direction in (LEFT, RIGHT) and self.is_moving_up and self.y >= target_y or self.is_moving_down and self.y <= target_y ) def _has_reached_target_x(self, target_x, target_direction): return ( target_direction in (UP, DOWN) and self.is_moving_right and self.x >= target_x or self.is_moving_left and self.x <= target_x ) class Snake: """ Linked list of `SnakeBodySegment` that represents the entire snake character in the game. """ START_SPEED = 3 START_X = 400 START_Y = 300 def __init__(self): self.head = SnakeBodySegment( x=self.START_X, y=self.START_Y, speed=self.START_SPEED, direction_x=START_DIRECTION_X, direction_y=START_DIRECTION_Y, ) self.tail = self.head self.segments = [] self.grow() def grow(self): self.tail.grow() self.tail = self.tail.next self.segments.append(self.tail) def move(self): segment = self.head while segment: segment.move() segment = segment.next def turn_up(self): self.head.turn_up() def turn_down(self): self.head.turn_down() def turn_left(self): self.head.turn_left() def turn_right(self): self.head.turn_right() def draw(self): segment = self.head while segment: segment.draw() segment = segment.next
import csv def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='\r') # Print New Line on Complete if iteration == total: print() if __name__ == '__main__': setIntance = set() setIntance2 = set() with open('files/temp_datalab_records_job_listings.csv', newline='') as csvfile: csv_reader = csv.reader(csvfile) count = 0 for row in csv_reader: # 68460125 # printProgressBar(count+1, 100000, prefix='Progress:', # suffix = 'Complete('+str(count)+")", length = 50) count = count+1 print(row[4]) setIntance.add(row[6]) setIntance2.add(row[4]) if(count == 100000): break print("Category: "+str(len(setIntance))) print("Job-Position: "+str(len(setIntance2)))
#!/usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Tsou" # Email:625139905@qq.com """ 1.函数 在python中,函数通过def关键字、函数名和可选的参数列表定义。 通过return关键字返回值。 """ # def foo(): # return 1 # print(foo()) """ 方法体是必须的,通过缩进来表示, 在方法名的后面加上双括号()就能调用函数 """ """ 2.作用域 在python中,函数会创建一个新的作用域。 python开发者可能会说函数有自己的命名空间,差不多一个意思。 这意味着在函数内部碰到一个变量的时候, 函数会优先在自己的命名空间里面去寻找。 """ # a_string = "This is a global variable" # def foo(): # print(locals()) # print(globals()) # doctest: +ELLIPSIS # foo() # 2 """ 内置的函数globals返回一个包含所有python解释器知道的变量名称的字典。 在#2我调用了函数foo把函数内部本地作用域里面的内容打印出来。 我们能够看到,函数foo有自己独立的命名空间, 虽然暂时命名空间里面什么都还没有。 """ """ 3.变量解析规则 当然这不是说我们在函数里面就不能访问外面的全局变量。 在Python的作用域规则里面,创建变量一定会在当前作用域里创建一个变量, 但是访问或者修改变量时会先在当前作用域查找变量, 没有找匹配变量的话会依次向上在闭合的作用域里面进行查找。 所有如果我们修改函数foo的实现让它打印全局的作用域里面的变量也是可以的 """ # a_string = "This is a global variable" # def foo(): # print(a_string) # 1 # foo() """ 在#1处,pytohn解释器会尝试查找变量a_string, 当然在函数的本地作用域里面是找不到的, 所以接着会去上层的作用域里面去查找。 但是另一方面,假如我们在函数内部给全局变量赋值,结果却和我们想的不一样: """ # a_string = "This is a global variable" # def foo(): # a_string = "test" # 1 # print(locals()) # foo() # print(a_string) # 2 """ 我们能够看到,全局变量能够被访问到(如果是可变数据类型(像list,dict这些)甚至能够被更改)但是赋值不行。 在函数内部的#1处,我们实际上创建了一个局部变量, 隐藏全局作用域中的同名变量。 我们可以通过打印出局部命名空间中的内容得出这个结论。 我们也能看到在#2处打印出来的变量a_string的值并没有改变。 """ """ 4.变量生存周期 值得注意的一个点是,变量不仅是生存在一个个的命名空间内, 他们都有自己的生存周期 """ # def foo(): # x = 1 # print(foo()) # print(x) # 1 """ #1处发生的错误不仅仅是因为作用域规则导致的(尽管这是抛出了NameError错误的原因) 它还和python以及其他很多编程语言中函数调用实现的机制有关。 在这个地方这个执行时间点并没有什么有效的语法让我们能够获取变量x的值, 因为它这个时候压根不存在!函数foo的命名空间随着函数调用开始而开始, 结束而销毁。 """ """ 5.函数参数 python允许我们向函数传递参数,参数会变成本地变量存在于函数内部。 """ # def foo(x): # print(locals()) # foo(1) """ 在python里有很多的方式来定义和传递参数, 完整版可以查看python官方文档。 我们在这里简略的说明一下: 函数的参数可以是必须的位置参数或者是可选的命名,默认参数。 """ # def foo(x, y=0): # 1 # return x - y # print(foo(3, 1)) # 2 # print(foo(3)) # 3 # print(foo()) # 4 # print(foo(y = 1, x = 3)) # 5 """ 在#1处我们定义了函数foo,它有一个位置参数x和一个命名参数y。 在#2处我们能够通过常规的方式来调用函数, 尽管有一个命名参数,但参数依然可以通过位置传递给函数。 在调用函数的时候,对于命名参数y我们也可以完全不管就像#3处所示的一样。 如果命名参数没有接收到任何值的话,python会自动使用声明的默认值也就是0。 需要注意的是我们不能省略第一个位置参数x,否则的话就会像#4处所示发生错误。 python支持函数调用时的命名参数(个人觉得应该是命名实参)。 看看#5处的函数调用,我们传递的是两个命名实参,这个时候因为有名称标识, 参数传递的顺序也就不用在意了。 当然相反的情况也是正确的:函数的第二个形参是y, 但是我们通过位置的方式传递值给它。在#2处的函数调用foo(3,1), 我们把3传递给了第一个参数,把1传递给了第二个参数, 尽管第二个参数是一个命名参数。 总结:函数的参数可以有名称和位置。 这意味着在函数的定义和调用的时候会稍稍在理解上有点不同。 我们可以给只定义了位置参数的函数传递命名参数(实参),反之亦然! """ """ 6.嵌套函数 python允许创建嵌套函数。 这意味着我们可以在函数里定义函数而且现有的作用域和变量生存周期依旧适用。 """ # def outer(): # x = 1 # def inner(): # print(x) # 1 # inner() # 2 # outer() """ #1发生了什么:python解释器需要找到一个叫x的本地变量, 查找失败之后会继续在上层的作用域里面寻找, 这个上层的作用域定义在另外一个函数里面。 对含糊outer来说,变量x是一个本地变量,但是如先前提到的一样, 函数inner可以访问封闭的作用域(至少可以读和修改)。 在#2处,我们调用函数inner,非常重要的一点是, inner也仅仅是一个遵循python变量解析规则的变量名, python解释器会优先在outer的作用域里面对变量名inner查找匹配的变量。 """ """ 7.函数是python世界里的一级类对象 显而易见,在python里函数和其他东西一样是对象。 """ # print(issubclass(int, object)) # all objects in Python inherit from a common baseclass # def foo(): # pass # print(foo.__class__) # print(issubclass(foo.__class__, object)) """ 函数在python里面就是对象,和其他的东西一样。 这就是说你可以把函数像参数一样传递给其他的函数或者从函数里面返回函数。 """ # def add(x, y): # return x + y # def sub(x, y): # return x - y # def apply(func, x, y): # 1 # return func(x, y) # 2 # print(apply(add, 2, 1)) # 3 # print(apply(sub, 2, 1)) """ add和sub是非常普通的两个python函数,接收两个值,返回一个计算后的结果。 在#1处你们能看到准备接收一个函数的变量只是一个普通的变量而已, 和其他变量一样。在#2处我们调用传进来的函数:()代表着调用的操作并且调用变量包含的值。 在#3处,你们也能看到传递函数并没有什么特殊的语法。 函数的名称只是和其他变量一样的标识符而已。 python把频繁要用的操作变成函数作为参数进行使用, 像通过传递一个函数给内置排序函数的key参数从而来定义排序规则。 """ # def outer(): # def inner(): # print("Inside inner") # return inner # 1 # foo = outer() # 2 # print(foo) # foo() """ 在#1处我把恰好是函数标识符的变量inner作为返回值返回出来。 这并没有什么特殊的语法:“把函数inner返回出来,否则它根本不可能会被调用到。” 每次函数outer被调用的时候,函数inner都会被重新定义, 如果它不被当作变量返回的话,每次执行过后它将不复存在。 在#2处我们捕获返回值-函数inner,将它存在一个新的变量foo里。 我们能够看到,当对变量foo进行求值,它确实包含函数inner, 而且我们能够对他进行调用。 """ """ 8.闭包 #定义:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure) 分解来说,包含下面3个条件: 1) 需要函数嵌套, 就是一个函数里面再写一个函数. 2) 外部函数需要返回一个内部函数的引用 3) 外部函数中有一些局部变量, 并且, 这些局部变量在内部函数中有使用 一些概念: 1)自由变量: 外部函数中定义的局部变量, 并且在内部函数中被使用 2) 闭包: 那个使用了自由变量并被返回的内部函数就称为闭包 #支持闭包的语言有这样的特性: 1)函数是一阶值(First-class value),即函数可以作为另一个函数的返回值或参数,还可以作为一个变量的值 2)函数可以嵌套定义,即在一个函数内部可以定义另一个函数 """ # def outer(): # x = 1 # def inner(): # print(x) # 1 # return inner # 加括号返回的是函数执行过程是NoType类型,不加括号返回的是函数内存地址,即函数本身 # foo = outer() # print(foo.__closure__) # __closure__里包含了一个元组(tuple)。这个元组中的每个元素是cell类型的对象。 """ 在上一个例子中我们了解到,inner作为一个函数被outer返回, 保存在一个变量foo,并且我们能够对它进行调用foo()。 我们先看看作用域规则,所有的东西都在python的作用域规则下进行工作: x是函数outer里的一个局部变量。当函数inner在#1处打印x的时候, python解释器会在inner内部查找相应的变量,当然会找不到, 所以接着会到封闭作用域里面查找,并且会找到匹配。 但是从变量的生存周期来看,变量x是函数outer的一个本地变量, 这意味着只用当函数outer正在运行的时候才会存在。 根据我们已知的python运行模式,我们没法在函数outer返回之后继续调用函数inner, 在函数inner被调用的时候,变量x早已不复存在,可能会发生一个运行时错误。 但是,返回的函数inner居然能够正常工作。 Python支持一个叫函数闭包的特性,简而言之, 嵌套定义在非全局作用域里面的函数能够记住它在被定义的时候所处的封闭命名空间。 这能够通过查看函数的__closure__属性得出结论, 这个属性里面包含封闭作用域里面的值(只会包含被捕捉到的值,比如x, 如果在outer里面还定义了其他的值,封闭作用域里面是不会有的) 记住,每次函数outer被调用的时候,函数inner都会被重新定义。 现在变量x的值不会变化,所以每次返回的函数inner会是同样的逻辑。 """ # 这是一个另外的例子: # def line_conf(a, b): # def line(x): # return a*x + b # return line # # line1 = line_conf(1, 1) # line2 = line_conf(4, 5) # print(line1(5), line2(5)) """ 这个例子中,函数line与环境变量a,b构成闭包。 在创建闭包的时候,我们通过line_conf的参数a,b说明了这两个环境变量的取值, 这样,我们就确定了函数的最终形式(y = x + 1和y = 4x + 5)。 我们只需要变换参数a,b,就可以获得不同的直线表达函数。 由此,我们可以看到,闭包也具有提高代码可复用性的作用。 如果没有闭包,我们需要每次创建直线函数的时候同时说明a,b,x。 这样,我们就需要更多的参数传递,也减少了代码的可移植性。 利用闭包,我们实际上创建了泛函数。 line函数定义一种广泛意义的函数。这个函数的一些方面已经确定(必须是直线), 但另一些方面(比如a和b参数待定)。 随后,我们根据line_conf传递来的参数,通过闭包的形式, 将最终函数确定下来。 """ """ 闭包与并行运算 闭包有效的减少了函数所需定义的参数数目。 这对于并行运算来说有重要的意义。 在并行运算的环境下,我们可以让每台电脑负责一个函数, 然后将一台电脑的输出和下一台电脑的输入串联起来。 最终,我们像流水线一样工作,从串联的电脑集群一端输入数据, 从另一端输出数据。这样的情境最适合只有一个参数输入的函数。 闭包就可以实现这一目的。 并行运算正称为一个热点。这也是函数式编程又热起来的一个重要原因。 函数式编程早在1950年代就已经存在,但应用并不广泛。 然而,我们上面描述的流水线式的工作并行集群过程,正适合函数式编程。 由于函数式编程这一天然优势, 越来越多的语言也开始加入对函数式编程范式的支持。 """ # def outer(x): # def inner(): # print(x) # 1 # return inner # print1 = outer(1) # print2 = outer(2) # print1() # print2() """ 从这个例子中能看到闭包-被函数记住的封闭作用域-能够被用来创建自定义的函数, 本质上来说是一个硬编码的参数。事实上我们并不是传递参数1或者2给函数inner, 实际上是创建了能够打印各种数字的各种自定义版本。 闭包单独拿出来就是一个非常强大的功能, 在某些方面,也许会把它当作一个类似于面向对象的技术: outer像是给inner服务的构造器,x像一个私有变量。使用闭包的方式也有很多: 如果熟悉python内置排序方法的参数key, 说不定已经写过一个lambda方法在排序一个列表的时候基于第二个元素而不是第一个。 现在说不定也可以写一个itemgetter方法,接收一个索引值来返回一个完美的函数, 传递给排序函数的参数key """ """ 9.装饰器 装饰器其实就是一个闭包,把一个函数当作参数然后返回一个替代版函数。 """ # def outer(some_func): # def inner(): # print("before some_func") # ret = some_func() # 1 # return ret + 1 # return inner # def foo(): # return 1 # decorated = outer(foo) # 2 # print(decorated()) """ 定义了一个函数outer,它只有一个some_func的参数, 在它里面我们定义了一个嵌套的函数inner。inner会打印一串字符串, 然后调用some_func,在#1处得到它的返回值。 在outer每次调用的时候,some_func的值可能会不一样, 但是不管some_func的值如何,我们都会调用它。最后, inner返回some_func() + 1的值-我们通过调用在#2处存储在变量decorated里面的函数能够看到被打印出来的字符串以及返回值2, 而不是期望中调用函数foo得到的返回值1。 我们可以认为变量decorated是函数foo的一个装饰版本,一个加强版本。 事实上如果打算写一个有用的装饰器的话,我们可能会愿意用装饰版本完全取代原先的函数foo, 这样我们总是会得到我们的“加强版”foo。想要达到这个效果, 完全不需要学习新的语法,简单的赋值给变量foo就行 """ # foo = outer(foo) # print(foo()) """ 现在,无论怎么调用都不会牵扯到原先的函数foo,都会得到新的装饰版本的foo。 现在写一个有用的装饰器。想象一个库,这个库能够提供类似坐标的对象, 也许仅仅是一些x和y的坐标对。不过可惜的是这些坐标对象不支持数学运算符, 而且我们也不能对源代码进行修改,因此也就不能直接加入运算符的支持。 我们将会做一系列的数学运算, 所以我们想要能够对两个坐标对象进行合适加减运算的函数。 """ # class Coordinate(object): # def __init__(self, x, y): # self.x = x # self.y = y # def __repr__(self): # return "Coord:" + str(self.__dict__) # def add(a, b): # return Coordinate(a.x + b.x, a.y + b.y) # def sub(a, b): # return Coordinate(a.x - b.x, a.y - b.y) # one = Coordinate(100, 200) # two = Coordinate(300, 200) # print(add(one, two)) """ 如果我们的加减函数同时也需要一些边界检查的行为该怎么办? 例如只能对正的坐标对象进行加减操作,任何返回的值也都应该是正的坐标。 现在是这样: one = Coordinate(100, 200) two = Coordinate(300, 200) three = Coordinate(-100, -100) sub(one, two) Coord: {'y': 0, 'x': -200} add(one, three) Coord: {'y': 100, 'x': 0} 我们期望在不更改坐标对象one,two,three的前提下one减去two的值是{x:0,y:0}, one加上three的值是{x:100,y:200}。 与其给每个方法都加上参数和返回值边界检查的逻辑,来写一个边界检查的装饰器 """ # three = Coordinate(-100, -100) # def wrapper(func): # def checker(a, b): # 1 # if a.x < 0 or b.y < 0: # a = Coordinate(a.x if a.x > 0 else 0, a.y if a.y > 0 else 0) # if b.x < 0 or b.y < 0: # b = Coordinate(b.x if b.x > 0 else 0, b.y if b.y > 0 else 0) # ret = func(a, b) # if ret.x < 0 or ret.y < 0: # ret = Coordinate(ret.x if ret.x > 0 else 0, ret.y if ret.y > 0 else 0) # return ret # return checker # add = wrapper(add) # sub = wrapper(sub) # print(sub(one, two)) # print(add(one, three)) """ 这个装饰器能像先前的装饰器一样进行工作,返回一个经过修改的函数, 但是在这个例子中,它能够对函数的输入参数和返回值做一些非常有用的检查和格式化工作, 将负值的x和y替换成0。 显而易见,通过这样的方式,我们的代码变得更加简洁: 将边界检查的逻辑隔离到单独的方法中,然后通过装饰器包装的方式应用到我们需要进行检查的地方。 另外一种方式通过在计算方法的开始处和返回值之前调用边界检查的方法也能够达到同样的目的。 但是不置可否的是,使用装饰器能够让我们以最小的代码量达到坐标边界检查的目的。 事实上,如果我们是在装饰自己定义的方法的话,我们能够让装饰器应用的更加有逼格。 """ """ 10.使用@标识符将装饰器应用到函数 Python2.4支持使用标识符@将装饰器应用在函数上,只需要在函数的定义前加上@和装饰器的名称。 在上一节的例子里我们是将原本的方法用装饰的方法代替: add = wrapper(add) 这种方式能够在任何时候对任意方法进行包装。但是如果我们自定义一个方法, 我们可以使用@进行装饰 @wrapper def add(a,b): return Coordinate(a.x + b.x, a.y + b.y) 需要明白的是,这样的做法和先前简单的用包装方法替代原有方法上是一样的, python只是加了一些语法糖让装饰的行为更加的直接明确和优雅一点。 """ # def log(func): # def wrapper(*args, **kw): # print("call %s()" % func.__name__) # return func(*args, **kw) # return wrapper # @log # 必须在被修饰函数的前一行,不能修饰类 # def now(): # print('2017-06-19') # now() """ 11.*args and **kwargs 我们已经完成了一个有用的装饰器,但是由于硬编码的原因它只能应用在一类具体的方法上, 这类方法接收两个参数,传递给闭包捕获的函数。 如果我们想实现一个能够应用在任何方法上的装饰器要怎么做呢? 再比如,如果我们要实现一个能应用在任何方法上的类似于计数器的装饰器, 不需要改变原有方法的任何逻辑。 这意味着装饰器能够接受拥有任何签名的函数作为自己的被装饰方法, 同时能够用传递给它的参数对被装饰的方法进行调用。 Python正好有支持这个特性的语法。可以阅读Python Tutorail获取更多的细节。 当定义函数的使用了*,意味着那些通过位置传递的参数将会被放在带有*前缀的变量中。 """ # def one(*args): # print(args) # 1 # one() # one(1,2,3) # def two(x,y, *args): # 2 # print(x, y, args) # two('a','b','c') """ 第一个函数one只是简单的将任何传递过来的位置参数全部打印出来而已, 能够看到,在代码#1处我们只是引用了函数内的变量args, *args仅仅只是用在函数定义的时候用来表示位置参数应该存储在变量args里面。 Python允许我们制定一些参数并且通过args捕获其他所有剩余的未被捕获的位置参数, 就像#2处所示的那样。*操作符在函数被调用的使用也能使用。 意义基本是一样的。当调用一个函数的时候, 一个用*标志的变量意思是变量里面的内容需要被提取出来然后当做位置参数被使用。 """ # def add(x,y): # return x + y # lst = [1,2] # print(add(lst[0], lst[1])) # 1 # print(add(*lst)) # 2 """ #1处的代码和#2处的代码所做的事情其实是一样的, 在#2处,python为我们所做的事其实也可以手动完成。 *args要么是表示调用方法的时候额外的参数可以从一个可迭代列表中取得, 要么就是定义方法的时候标志这个方法能够接受任意的位置参数。 **代表着键值对的参数字典,和*所代表的意义相差无几。 """ # def foo(**kwargs): # print(kwargs) # foo() # foo(x = 1, y = 2) """ 当我们定义一个函数的时候,我们能够用**kwargs来表明所有未被捕获的关键字参数都应该存储在kwargs的字典中。 args和kwargs并不是python语法的一部分,但是在定义函数的时候,使用这样的变量名算是一个不成文的约定。 和*一样,我们同样可以在定义或者调用函数的时候使用**。 """ # dct = {'x':1 , 'y':2} # def bar(x,y): # return x+y # print(bar(**dct)) """ 12.更通用的装饰器 写一个能够记录下传递给函数参数的装饰器。 """ def logger(func): def inner(*args, **kwargs): # 1 print("Arguments were: %s, %s" % (args, kwargs)) return func(*args, **kwargs) # 2 return inner """ 请注意函数inner,它能够接受任意数量和类型的参数并把它们传递给被包装的方法。 """ @logger def foo1(x, y=1): return x*y @logger def foo2(): return 2 print(foo1(5,4)) print(foo1(1)) print(foo2()) """ 随便调用定义的哪个方法,相应的日志也会打印到输出窗口。 """
temp_C = input("enter temperature in degC: ") temp_F = float(temp_C)*9/5+32 print("The temperature in {} degF".format(temp_F))