text
stringlengths
37
1.41M
# importing the required library from tkinter import * from tkinter.ttk import * from time import strftime root=Tk() #creating the tkinter object root.title('Harry_Clock') #setting title def time(): string=strftime('%H:%M:%S %p') #time format label.config(text=string) label.after(1000,time) label=Label(root,font=('ds-digital',80),background='black',foreground='white') #binding the labels label.pack(anchor='center') #packing the label in the center time() mainloop() # download the ds-digital font from here: https://www.dafont.com/ds-digital.font
from turtle import * state={'turn':0} # this will make the fidget to spin def spinner(): clear() angle=state['turn']/10 right(angle) #it will move the fidget to clockwise direction becuase our angle is right forward(100) dot(120,'red') back(100) right(120) #for anticlock direction we have to move to left angle forward(100) dot(120,'blue') #dot is circle here back(100) right(120) forward(100) dot(120,'yellow') back(100) right(120) update() # this will change its state def animate(): if state['turn']>0: state['turn']-=1 spinner() ontimer(animate,20) # this will control the speed of the fidget def flick(): state['turn']+=10 #speed of the circle on pressing space button # this will control the speed of the fidget # it is very slow tracer(False) width(20) onkey(flick,'space') #on pressing space key the spin will will move, the speed will increase on pressing space key listen() animate() done() # lets run it # now press the space key # keep pressing space key, its speed will increase on pressing # for 10 the speed will be slow
class Solution: def merge(self, nums1, m: int, nums2, n) -> None: """ Do not return anything, modify nums1 in-place instead. Brute Force: Time: O(n+m). Space: O(1) """ # nums1[m:] = nums2 # nums1.sort() curr = 0 for i in range(n): for j in range(curr, m+n): if nums1[j] > nums2[i]: nums1[j], nums1[j+1:] = nums2[i], nums1[j:m+n-1] break curr = j+1 else: nums1[i + m] = nums2[i] return nums1 sol = Solution() nums1 = [4,0,0,0,0,0] m = 1 nums2 = [1,2,3,5,6] n = 5 print(sol.merge(nums1, m, nums2, n))
class Solution: # T: O(n) S: O(n) def climbStairs(self, n: int) -> int: # 1 -> 1 | 2 -> 2 | 3 -> 3 | 4 -> 5 | 5 -> 8| 6 -> 13 | 7 -> 21 | 8 -> 34 | 9->55 # 1,1,1,1 1 1 1 1 1 # 2,1,1 1 1 1 2 # 1,2,1 1 1 2 1 # 1,1,2 1 2 1 1 # 2,2 2 1 1 1 # 2 2 1 # 2 1 2 # 1 2 1 if n <= 2: return n self.cache = {1: 1, 2: 2} return self.memoize(n) def memoize(self, n: int) -> int: if n in self.cache.keys(): return self.cache[n] self.cache[n] = self.memoize(n - 1) + self.memoize(n - 2) return self.memoize(n)
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype int Brute force TC: O(n) Binary Search TC: O(log n) """ # for i in range(len(nums)): # if target <= nums[i]: # return i # return len(nums) low = 0 high = len(nums) - 1 while low <= high: mid = (low + high) // 2 if target <= nums[mid]: high = mid - 1 else: low = mid + 1 # if high == low: # if target <= nums[low]: # return low # else: # return low + 1 return low nums = [1,3,5,6] target = 2 sol = Solution() res = sol.searchInsert(nums, target) print(res)
# Michelle Lally # Shunting Yard Algorithm def addconcat(infix): spec1 = ('+', '|', '?', '*', '.', '(') spec2 = ('+', '|', '?', '*', '.', ')') temp = "" for i, c in enumerate(infix): if c in ('+', '|', '?', '*', '.', '('): temp += c else: try: if infix[i+1] not in ('+', '|', '?', '*', '.', ')'): temp += c + "." else: temp += c except IndexError: temp += c break #print("temp", temp) return temp def shunt(infix): infix = addconcat(infix) specials = {'*': 50, '.': 40, '|': 30} pofix = "" stack = "" for c in infix: if c == '(': stack = stack + c elif c == ')': # Check the last character in the string while stack[-1] != '(': # Pushing the operators at the end of the stack to pofix as long as it's not the open bracket pofix = pofix + stack[-1] # Remove that operator from the stack stack = stack[:-1] # Remove the ( from the stack stack = stack[:-1] elif c in specials: # Check while theres something on the stack, and c's precedence is <= the precedence on the stack # specials.get(c , 0) means if c is in specials, get its value from the dictionary otherwise give it the value 0 # Then check if whats on top of the stack is in specials and get its value from the dictionary otherwise give it 0 while stack and specials.get(c, 0) <= specials.get(stack[-1], 0): # Remove the operator at the top of the stack and put it into pofix pofix, stack = pofix + stack[-1], stack[:-1] # Push c onto the stack stack = stack + c else: pofix = pofix + c while stack: # Pushing the operators at the end of the stack to pofix as long as it's not the open bracket pofix = pofix + stack[-1] # Remove that operator from the stack stack = stack[:-1] # Remove the ( from the stack return pofix # Plans for something you might create in memory # Can be reused # represents a state with 2 arrows labelled by label # use none for a label representing 'e' arrows class state: # Character label = None # In arrow edge1 = None # Out arrow edge2= None # an nfa class nfa: initial = None accept = None # Constructor in python starts and ends in 2 underscores # Every function must also has to have self as its first parameter def __init__(self, initial, accept): self.initial = initial self.accept = accept def compile(pofix): # Stack of NFA's nfastack = [] for c in pofix: # Catenation if c == '.': nfa2 = nfastack.pop() nfa1 = nfastack.pop() # take 1 of the edges of the accept state and let it # equal to the initial state in the second NFA nfa1.accept.edge1 = nfa2.initial newnfa = nfa(nfa1.initial, nfa2.accept) nfastack.append(newnfa) # Alternation elif c == '|': # pop 2 nfa's off the stack nfa2 = nfastack.pop() nfa1 = nfastack.pop() # creating an instance of state and connect it to # the initial states of the nfa's popped from the stack initial = state() # creating an instance of state and connect it to # the accept states of the nfa's popped from the stack accept = state() # join initial's in arrow to the inital state of nfa1 initial.edge1 = nfa1.initial # join initial's out arrow to the inital state of nfa2 initial.edge2 = nfa2.initial # nfa1 and nfa2 initial states are no longer # initial states because theyre pointing # nfa1 accept state to point at the new accept state nfa1.accept.edge1 = accept # nfa2 accept state to point at the new accept state nfa2.accept.edge1 = accept # push new nfa to the stack newnfa = nfa(initial, accept) nfastack.append(newnfa) # Zero or more elif c == '*': # pop single nfa from the stack nfa1 = nfastack.pop() # create new initial and accept states # creating an instance of state accept = state() # creating an instance of state initial = state() # join the new initial state to nfa1's initial state and the # new accept state initial.edge1 = nfa1.initial initial.edge2 = accept # join the old accept state to the new accept stare and nfa1's # initial state nfa1.accept.edge1 = nfa1.initial nfa1.accept.edge2 = accept # push new nfa to the stack newnfa = nfa(initial, accept) nfastack.append(newnfa) # Zero or one elif c == '?': # pop single nfa from the stack nfa1 = nfastack.pop() # create new initial and accept states # creating an instance of state accept = state() # creating an instance of state initial = state() initial.edge1 = nfa1.initial initial.edge2 = accept # join the old accept state to the new accept stare and nfa1's # initial state nfa1.accept.edge1 = accept # nfa1.accept.edge2 = accept # push new nfa to the stack newnfa = nfa(initial, accept) nfastack.append(newnfa) # One or more elif c == '+': # pop single nfa from the stack nfa1 = nfastack.pop() # create new initial and accept states # creating an instance of state accept = state() # creating an instance of state initial = state() # join the new initial state to nfa1's initial state and the # new accept state initial.edge1 = nfa1.initial # join the old accept state to the new accept stare and nfa1's # initial state nfa1.accept.edge1 = nfa1.initial nfa1.accept.edge2 = accept # push new nfa to the stack newnfa = nfa(initial, accept) nfastack.append(newnfa) else: # creating an instance of state accept = state() # creating an instance of state initial = state() # label of arrow coming out of the initial state is going to be c initial.label = c # edge1 points to the accept state initial.edge1 = accept # creates a new instance of the NFA class and set the initial state to the initial state just created and the same with accept nfastack.append(nfa(initial, accept)) # nfastack should only have a single nfa at the end return nfastack.pop() def followes(state): """ Return the set of states that can be reached from states following the e arrows """ # Create a new set, with state as its only member states = set() states.add(state) # check id the state that has arrows e from it if state.label is None: # check if edge1 is a state if state.edge1 is not None: # if theres an edge 1, follow it states |= followes(state.edge1) # check if edge2 is a state if state.edge2 is not None: # if theres an edge 2 follow it states |= followes(state.edge2) # Return the set of states return states def match(infix, string): """ Matches the string to the infix regular expression""" # shunt and compile the regular epxression # turn infix into postfix postfix = shunt(infix) # print("postfix: " ,postfix) # compile the postfix expression into an nfa nfa = compile(postfix) #the currrent states and the next states current = set() next = set() # Add the initial state to the current set current |= followes(nfa.initial) # loop through each character in the string for s in string: # loop through the current set of states for c in current: # check if that state is labelled s if c.label == s: # add the edg1 state to the next set next |= followes(c.edge1) #set current to next, and clear out next current = next next = set() #check is the accept state is in the currect states return (nfa.accept in current) inifixes = ["(abc)?","abc*", "a(b|d)c*", "(a(b|d))*", "a(b)c", "a|bc+"] strings = ["", "abc", 'bcc', "abbc", "daab", "abcc", "abd", "abbc"] #inifixes = ["a.b.+"] #strings = ["abbbb", "a", "bbb", "ab"] for i in inifixes: print('==================================================') print('\tExpression : ', i) for s in strings: print('{0}\t|| {1}\t||\t{2}'.format(match(i, s), i, s)) print('==================================================')
# Michelle Lally # Shunting Yard Algorithm def shunt(infix): specials = {'*': 50, '.': 40, '|': 30} pofix = "" stack = "" for c in infix: if c == '(': stack = stack + c print("stack 1: ", stack) elif c == ')': # Check the last character in the string while stack[-1] != '(': print("stack 2: ", stack) # Pushing the operators at the end of the stack to pofix as long as it's not the open bracket pofix = pofix + stack[-1] print("pofix 1: ", pofix) # Remove that operator from the stack stack = stack[:-1] print("stack 3: ", stack) # Remove the ( from the stack stack = stack[:-1] print("stack 4: ", stack) elif c in specials: # Check while theres something on the stack, and c's precedence is <= the precedence on the stack # specials.get(c , 0) means if c is in specials, get its value from the dictionary otherwise give it the value 0 # Then check if whats on top of the stack is in specials and get its value from the dictionary otherwise give it 0 while stack and specials.get(c, 0) <= specials.get(stack[-1], 0): print("stack 5: ", stack) # Remove the operator at the top of the stack and put it into pofix pofix, stack = pofix + stack[-1], stack[:-1] print("pofix 2: ", pofix) print("stack 6: ", stack) # Push c onto the stack stack = stack + c print("stack 7: ", stack) else: pofix = pofix + c print("pofix 3: ", pofix) while stack: # Pushing the operators at the end of the stack to pofix as long as it's not the open bracket pofix = pofix + stack[-1] print("pofix 4: ", pofix) # Remove that operator from the stack stack = stack[:-1] print("stack 8: ", stack) # Remove the ( from the stack return pofix print(shunt("a.(b|d).c*"))
import pygame,sys pygame.init() WHITE = [255,255,255] BLACK = [0,0,0] SCREEN_WIDTH = 1500 SCREEN_HEIGHT = 1000 CIRCLE_RADIUS = 25 PADDLE_WIDTH = 25 PADDLE_HEIGHT = 200 screen = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT]) class Paddle: def __init__(self, xp): self.pxpos = xp self.pypos = SCREEN_HEIGHT/2 class Ball: def __init__(self): self.bxpos = SCREEN_WIDTH/2 self.bypos = SCREEN_HEIGHT/2 self.bvely = 0.3 self.bvelx = 0.3 def movement(self): if self.bypos >= (SCREEN_HEIGHT - CIRCLE_RADIUS) or self.bypos <= CIRCLE_RADIUS: self.bvely *= -1 self.bypos += self.bvely self.bxpos += self.bvelx p1 = Paddle(SCREEN_WIDTH - 50) p2 = Paddle(50) ball = Ball() p1score = 0 p2score = 0 def collision(): if ball.bxpos + CIRCLE_RADIUS >= p1.pxpos: if (((p1.pypos + PADDLE_HEIGHT) >= (ball.bypos - CIRCLE_RADIUS) and (p1.pypos <= (ball.bypos + CIRCLE_RADIUS)))): ball.bvelx *= -1 if ball.bxpos - CIRCLE_RADIUS <= p2.pxpos + PADDLE_WIDTH: if ((p2.pypos + PADDLE_HEIGHT) >= (ball.bypos - CIRCLE_RADIUS) and (p2.pypos <= (ball.bypos + CIRCLE_RADIUS))): ball.bvelx *= -1 def reset(p1score, p2score): if ball.bxpos + CIRCLE_RADIUS > SCREEN_WIDTH: p2score += 1 ball.bxpos = SCREEN_WIDTH/2 ball.bypos = SCREEN_HEIGHT/2 print(p2score) if ball.bxpos - CIRCLE_RADIUS < 0: p1score += 1 ball.bxpos = SCREEN_WIDTH/2 ball.bypos = SCREEN_HEIGHT/2 print(p1score) return [p1score, p2score] font = pygame.font.SysFont(None, 50) while True: #Step 1: Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() break #Step 2: Calculations / Update variables / positions / etc keys = pygame.key.get_pressed() if keys[pygame.K_UP]: p1.pypos -= 1 if keys[pygame.K_DOWN]: p1.pypos += 1 if keys[pygame.K_w]: p2.pypos -= 1 if keys[pygame.K_s]: p2.pypos += 1 collision() ball.movement() p1score, p2score = reset(p1score, p2score) #Step 3: Fill the screen with background color (usually white) screen.fill(BLACK) #Step 4: Draw your stuff img = font.render(str(p1score), True, WHITE) screen.blit(img, (1450, 20)) img2 = font.render(str(p2score), True, WHITE) screen.blit(img2, (20, 20)) pygame.draw.circle(screen, WHITE, [ball.bxpos, ball.bypos], CIRCLE_RADIUS) pygame.draw.rect(screen, WHITE, [p1.pxpos, p1.pypos, PADDLE_WIDTH, PADDLE_HEIGHT]) pygame.draw.rect(screen, WHITE, [p2.pxpos, p2.pypos, PADDLE_WIDTH, PADDLE_HEIGHT]) #Step 5: Flip the screen pygame.display.flip()
list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for item in list: print(item)
a = 4 b = 3 if a > b: print("верно") a = 2 b = 3 if a < b: print("тоже верно") a = 2 b = 3 if a == b: print("не выводит инфу")
def traverse(data): if 'children' not in data.keys(): return 1 total_nodes = 0 for child in data['children']: total_nodes += traverse(child) return total_nodes
players = { "Messi": { "number": 10, "club": "Barcelona"}, "Ronaldo": { "number": 7, "club": "Juventus"} } # Length print(len(players)) # Check if item exists if "Messi" in players: print("Messi is in the dict") # Add item players["Salah"] = { "number": 11, "club": "Liverpool" } # Remove players.pop("Ronaldo") players.clear() print(players)
def calculate_amount(prices): amount = 0 for price in prices: amount += price return amount result = calculate_amount([50, 100, 150]) print(result)
fruits = ["🍌", "🍎", "🍍"] for fruit in fruits: if fruit == "🍎": continue print(fruit) print("end")
# Integer quantity = 4 # Float price = 2.5 # + - * / Operations with Integer and Float amount = quantity * price print(amount) # int to float print(float(quantity)) # int to string print(type(str(quantity))) # float to int print(int(price)) # float to string print(type(str(price)))
from sys import argv script, filename = argv # load the file contents into a variable txt = open(filename) print "Here's your file %r:" % filename # print the info out with the read method print txt.read() # we can do the same thing using a prompt rather than a command line argument print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read()
#!/usr/bin/env python """ Problem Definition : Fibonaci with Tabulation (Bottom Up) """ __author__ = 'vivek' def fib(n): fib_l = [0 for i in range(n+1)] fib_l[1] = 1 for j in range(2, n+1): fib_l[j] = fib_l[j-1] + fib_l[j-2] return fib_l[n] def main(): print(fib(10)) if __name__ == "__main__": main()
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right ### # Use a queue to store a list of nodes # Initially only root in the queue # As long as the queue is not empty, remove next node from the queue # Swap its children and add them to the queue # Eventually the queue is empty, all children swapped # class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if (root is None): return root queue = [] queue = queue + [root] while (len(queue) != 0): elem = queue[0] queue = queue[1:] tmp = elem.left elem.left = elem.right elem.right = tmp if (elem.left is not None): queue = queue + [elem.left] if (elem.right is not None): queue = queue + [elem.right ] return root
class Student: def __init__(self, name, sex, age): self.sex = sex self.name = name self.age = age def print(self): print("Hi, 我叫" + self.name, "性别:"+self.sex, "年龄:"+str(self.age))
""" *** *** *** """ for l in range(4): for c in range(6): if c % 2 == 1: print("#", end="") else: print("*", end="") print() print("\n") for l in range(4): for c in range(l + 1): print("*", end="") print() """ 升序排序 """ list01 = [3, 80, 45, 5, 80, 80] # 使用交换排序 for i in range(len(list01) - 1): for j in range(i + 1, len(list01)): if list01[i] > list01[j]: temp = list01[i] list01[i] = list01[j] list01[j] = temp print(list01) # 判断是否有两个相同元素,有则返回相同值 res = False for i in range(0, len(list01) - 1): for j in range(i + 1, len(list01)): if res: break if list01[i] == list01[j]: print(list01[i]) res = True break if res is False: print("nope") # 将二维列表的行变成列,列变成行 list02 = [ [1,2,3,4], [5,6,7,8], [9, 10, 11, 12], [13, 14, 15, 16] ] res = [] for c in range(4): res.append([]) for r in range(len(list02)): res[c].append(list02[r][c]) print(res)
""" 函数参数 实际参数 """ def fun01(a, b, c, d): print(a) print(b) print(c) print(d) # 位置实参:实参与实参的位置依次对应 fun01(1, 2, 3, 4) # 关键字实参:实参与形参 fun01(b=1, d=2, c=3, a=4) # 序列实参:星号将序列拆分后按位置与形参进行对应 list01 = ["a", "b", "c", "d"] fun01(*list01) print("字典实参:") # 字典实参:双星号将字典拆分后按名称与形参进行对应 dict01 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} fun01(**dict01) # 4.命名关键字形参(必须命名) def fun03(*, a, b): print(a) print(b) fun03(a="q", b="d") # 5.字典形参:数量无限的关键字实参 def fun06(**a): print(a) fun06(a=1, b=2) # 练习: # |位置|| 星号元组形参 || 命名关键字 || 双星号字典 | def fun07(a, b, *args, c, d, **kwargs): pass fun07(3, 4, 5, 6, c=7, d=8, e=9) # 位置实参无限 + 关键字实参无限 def fun08(*args, **kwargs): pass
#随机数小游戏 # 随机数工具 import random # 产生一个随机数 random_num = random.randint(1, 100) while True: num = int(input("enter a number: ")) if num<random_num: print("小了") elif num>random_num: print("大了") else: print("你猜对了!") break
""" 函数参数 形式参数 """ # 默认参数:如果实参不提供,可以使用默认值 def fun01(a=0, b=0, c=0, d=0): print(a) print(b) print(c) print(d) # 关键字实参+默认形参:可随意调用参数 # fun01(b=2, c=3) """ # """ def get_ss_by_hh_mm_ss(h=0, m=0, s=0): """ 练习:定义函数,根据时、分、秒计算总秒数 H, M, S --> S H --> s min --> s H, min --> s H, s --> s :param h: hour :param m: minute :param s: second :return: seconds in total """ ss = 0 if h != 0: ss += 3600 * h if m != 0: ss += 60 * m if s != 0: ss += s return ss print(get_ss_by_hh_mm_ss(h=1,s=40))
""" 练习:将随机列表中大于某个数的所有数字存入一个新的列表 并画出内存图 """ list01 = [54, 25, 12, 42, 35, 17] list02 = [] i = 0 for item in list01: if item > 30: list02.append(item) i += 1 print(list02[i-1])
# -*- coding: utf-8 -*- """ The formation of Transitive Memory System (TMS) This is based on the netlogo version of formation of TMS, except that the function "productivity_TMS" was added to test how productive the teams are. Author: Xiaoyi Yuan Date: 08/06/2016 OS: Mac 10.10.5 Python Version: 3.5 """ import random import statistics import networkx as nx import csv G = nx.DiGraph() """ 7 kinds of areas, each corresponds with a color in the list when connect with an expert, the edge becomes the corresponding color. """ colors = ['red', 'blue', 'green', 'yellow', 'white', 'cyan', 'pink'] class Agent(object): def __init__(self, expertise, tasks, waitlist, availability, tertius, steps): self.expertise = expertise self.tasks = tasks self.waitlist = waitlist self.availability = availability self.tertius = tertius self.steps = steps # First, create a team def create_TMS(nagents, nareas, ntasks): agents = [Agent(expertise=[statistics.median ([0, 1, random.normalvariate(0.5, 0.4)]) for i in range(nareas)], tasks=[random.randint(0, nareas - 1) for i in range(ntasks)], availability=False, waitlist=[], tertius=0, steps=0) for i in range(nagents)] G.add_nodes_from(agents) for agent in agents: others = [i for i in agents if i != agent] complete = 0 for task in agent.tasks: # if the agent is an expert him/herself, complete the task if agent.expertise[task] > 0.5: complete = complete + 1 else: # if there's an expert in the team that has helped him/her edge_colors = [G[agent][expert]['color'] for expert in G.successors(agent)] if colors[task] in edge_colors: complete = complete + 1 # if not connected to an expert else: # find an expert and build an edge experts = [expert for expert in others if agent.expertise[task] + expert.expertise[task] > 0.5] if experts != []: expert = random.choice(experts) G.add_edge(agent, expert, color=colors[task]) complete = complete + 1 # white nodes: completed all their tasks; black node: who didn't if complete == ntasks: nx.set_node_attributes(G, 'color', {agent: 'white'}) else: nx.set_node_attributes(G, 'color', {agent: 'black'}) # check if anyone in the network is in tertius position. # if it is, then agent.tertius= 1, otherwise, remain 0. for agent in agents: # check if all its outdegree neighbors are a transitive triad outdegree = [] for i in G.successors(agent): outdegree.append(i) if len(outdegree) > 1: for i in outdegree: for n in outdegree: if n != i and \ n in G.predecessors(i) or n in G.successors(i): agent.tertius = 1 return G, agents, nareas, nagents ''' Next, test TMS on its productivity: This step involves parallel activation. Every team member activates at the same time ''' def productivity_TMS(ntasks): # Assign them a new set of tasks to test their productivity for agent in team: agent.tasks = [random.randint(0, number_of_areas - 1) for i in range(ntasks)] agent.steps = 0 steps = 0 while steps <= 1000: for member in team: # I n each step, each person is available in the beginning # but only available for dealing with only one task member.availability = True if member.tasks == [] and member.steps == 0: member.steps = steps # if this member hasn't done with all the tasks, # if he can do it on his own, do it and then become unavailable if member.tasks != [] and member.expertise[member.tasks[0]] > 0.5: del member.tasks[0] member.availability = False # if he cannot do it on his own, add the task to expert's waitlist if member.tasks != [] and \ member.expertise[member.tasks[0]] <= 0.5: if any(G.successors(member)): for expert in G.successors(member): if G[member][expert]['color'] == \ colors[member.tasks[0]] and \ member not in expert.waitlist: expert.waitlist.append(member) # for those who cannot do his own tasks, check if he can help others for member in team: if member.tasks != [] and \ member.availability and \ any(member.waitlist): del member.waitlist[0].tasks[0] del member.waitlist[0] steps = steps + 1 with open("output.csv", 'w') as csvfile: writer = csv.writer(csvfile) for n in range(1000): G, team, number_of_areas, number_of_agents = create_TMS(10, 5, 10) productivity_TMS(10) for i in team: result = writer.writerow([i.tertius, i.steps]) ''' TMS triadic census ''' nx.triadic_census(G)
def read_file(name): return open(name).read().splitlines() def parse(lines): parsed = list(map(lambda line: int(line), lines)) parsed.sort() return parsed def differences(result): diffs = [result[0]] for pos in range(0, len(result) - 1): diffs.append(result[pos + 1] - result[pos]) diffs.append(3) return diffs def part1(filename="input"): adapters = parse(read_file(filename)) diffs = differences(adapters) ones = len(list(filter(lambda n: n == 1, diffs))) threes = len(list(filter(lambda n: n == 3, diffs))) print(ones * threes)
VOWELS = ["A", "E", "I", "O", "U"] def LongShout(word, multiplier): word = word.upper() count = 1 for vowel in VOWELS: long_vowels = vowel * multiplier * count word = word.replace(vowel, long_vowels) count = count + 1 #or count = count += 1 return word print LongShout('COOKIE', 4) print LongShout('cookie', 4) # groceries = {'eggs': 5, 'butter': 4, 'chocolate': 2} # for item in groceries: # #items: $(price) # print item + ": $" + str(groceries[item])
def words_count(filename): '''count the approximate number of words in a file''' try: with open(filename) as file_object: contents=file_object.read() except FileNotFoundError: msg='The file '+filename+"does't exist." print(msg) else: words=contents.split() num_words=len(words) print('The file '+filename+' has about '+str(num_words)+' words.') filenames=['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt'] for filename in filenames: words_count(filename)
x=int(input('please enter an integer:')) pwr=1 while pwr<6: factorize=False if x%pwr==0: root=x/pwr print(str(x)+' can be factor by '+str(pwr)+' and '+str(root)) factorize=True pwr=pwr+1 if factorize==False: print('no factors!')
namehandle=open('kids','w') namehandle.write('Micheal\n') namehandle.write('Mark\n') namehandle.close() namehandle=open('kids','r') for line in namehandle: print(line[:-1]) namehandle.close() namehandle=open('kids','a') namehandle.write('David\n') namehandle.write('Andrea\n') namehandle.close() namehandle=open('kids','r') for line in namehandle: print(line[:-1]) namehandle.close()
def findroot(x,power,epsilon): '''Assume x and epsilon int or float, power an int, epsilon>0 & power>=1 returns float y such that y**power is within epsilon of x. If such a float does not exist, it returns None.''' if x<0 and power%2==0: return None #Nagtive number has no even-powered roots low=min(-1,x) high=max(1,x) ans=(high+low)/2 while abs(ans**power-x)>=epsilon: if ans**power<x: low=ans else: high=ans ans=(high+low)/2.0 return ans def testfindroot(): epsilon=0.0001 for x in [0.25,-0.25,2,-2,8,-8]: for power in range(1,4): print('Testing x=',str(x),'and power=',power) result=findroot(x,power,epsilon) if result==None: print(' No root') else: print(' ', 'root is ', result, ' ', result**power, '~=',x) help(findroot) testfindroot()
x=int(input('Enter an integer:')) ans=0 while ans**3<abs(x): ans=ans+1 if ans**3!=abs(x): print(x,' is not a perfect cube') else: if x<0: ans=-ans print('Cube root of',x,' is',ans)
balance = 3329 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12.0 minimumMonthlyPayment = 10 newBalance = balance while(newBalance >= 0): newBalance = balance for i in range(0,12): monthlyUnpaidBalance = newBalance - minimumMonthlyPayment newBalance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) if newBalance > 0: minimumMonthlyPayment+=10 print "Lowest Payment: " + str(minimumMonthlyPayment)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 18 22:01:23 2020 @author: nikhildhamne Task The provided code stub reads two integers, a and b, from STDIN. Add logic to print two lines. The first line should contain the result of integer division, a//b. The second line should contain the result of float division, a/b. No rounding or formatting is necessary. Example a=3 b=5 - The result of the integer division 3//5=0. - The result of the float division is 3/5=0.6. Print: 0 0.6 Input Format The first line contains the first integer, a. The second line contains the second integer, b. Output Format Print the two lines as described above. """ if __name__ == '__main__': a = int(input()) b = int(input()) print(a//b) print(a/b)
def findNonDuplicate(A): uniqueElement='' low = 0 high = len(A) - 1 def spot_non_duplicate(given_list, low, high): if low > high: return None if low == high: return given_list[low] mid = int(low + (high - low) / 2) if mid % 2 == 0: #We can observe that if mid is even and its value if given_list[mid] == given_list[mid + 1]: #is equal to its next element mid+1, then the non duplicate return spot_non_duplicate(given_list, mid + 2, high) #element that we are looking for is on the right half, else: #else it's on the left half return spot_non_duplicate(given_list, low, mid) else: #If mid is odd, it's the opposite case from before. if given_list[mid] == given_list[mid - 1]: return spot_non_duplicate(given_list, mid + 1, high) else: #If mid is an odd number, it cannot be the return spot_non_duplicate(given_list, low, mid - 1) #non duplicate element. uniqueElement = spot_non_duplicate(A, low, high) return uniqueElement if __name__ == "__main__": assert findNonDuplicate(['c','c','d','d','f','f','z']) == 'z' assert findNonDuplicate(['a','a','b','b','c','d','d','e','e','r','r']) == 'c' F = ['c','c','d','d','g','g','i','i','k','y','y','z','z'] dublic_char = findNonDuplicate(F) print("The non dublicate character is:", dublic_char) G = [1, 1, 3, 3, 6, 6, 7, 7, 8, 9, 9] #It can work for inputs of both numbers and letters dublic_char = findNonDuplicate(G) #of the alphabet. We give examples of both cases print("The non duplicate character is:", dublic_char) #and we print the results.
# The following defined functions are used to assist in the output and calculations for data analysis. # Please use Python 3.8.5 and import library 'myfunctions' to use the functions shown below. from pathlib import Path import csv def import_csv_data(file_name, delimiter_separator): '''Reads data from a .csv file and creates a list of dictionaries with the data. The function accepts two attributes per row with the second attribute being an integer. Args: file_name (str): Name of data file (Example: "data.csv") delimiter_separator (str): Character(s) separating values in csv file Returns: A list of dictionaries with assigned values from csv file ''' # Initialize variables csvpath = "" temp_list = [] # Capture file path to be read csvpath = Path("./Resources/" + file_name) # Open data in specified path as csv_file with open(csvpath, 'r') as csv_file: # Read data from csv_file knowing the data is ',' delimited and assign to csvreader variable csvreader = csv.reader(csv_file, delimiter=delimiter_separator) # Store data header and go to next line header = next(csvreader) # Iterate through each line of csvreader for row in csvreader: # Assign each row to dictionary structure first_item = row[0] second_item = int(row[1]) # Assign dictionary data items to budget list # "pnl" represents Profit and Loss temp_list.append({header[0]: first_item, header[1]: second_item}) return temp_list def summary_output(number_of_months_in_budget, net_total_amount_of_profits_and_losses, average_of_profit_and_losses, greatest_increase_date, greatest_increase_number, greatest_decrease_date, greatest_decrease_number): """Accepts metric variables and prints a standard output to the screen along with a summary.txt file to the same location as the myfunctions libary. Args: number_of_months_in_budget (int): The number of months in the budget net_total_amount_of_profits_and_losses (int): The total amount of combined profits and losses. average_of_profit_and_losses (int): The average value of profits and losses. greatest_increase_date (str): The greatest increase date greatest_increase_number (int): The greatest increase number greatest_decrease_date (str): The greatest loss date greatest_decrease_number (int): The greatest loss number Output: Outputs summary message to screen and ./Output/summary.txt """ # Capture file path to be written output_path = Path("./summary.txt") # Open output path filewriter = open(output_path, 'w+') # Formatting individual rows for summary output and concatinates each string summary_message = "" summary_message += "Financial Analysis\n" summary_message += "----------------------------\n" summary_message += f"Total Months: {number_of_months_in_budget}\n" summary_message += f"Total: ${net_total_amount_of_profits_and_losses}\n" summary_message += f"Average Change: ${average_of_profit_and_losses}\n" summary_message += f"Greatest Increase in Profits: {greatest_increase_date} (${greatest_increase_number})\n" summary_message += f"Greatest Decrease in Profits: {greatest_decrease_date} (${greatest_decrease_number})\n" # Outputs summary message to screen print(summary_message) # Writes summary message to output path filewriter.write(summary_message) # Closes file filewriter.close() def greatest_increase_or_decrease_in_profits(change_in_profits_and_losses_list, increase_or_decrease, key_1, key_2): """Determine the greatest increase or decrease in profits (date and amount) over the entire period. Args: change_in_profits_and_losses_list (dict): Changes in profits and losses containing a 'Date' and 'Profit/Losses' key. increase_or_decrease (str): Indication to find the greatest "increase" in profits or the greatest "decrease" in profits. key_1 (str): Name of key 1. Usually a "Date" key_2 (str): name of key 2. Usually a "Profit/Losses" or "Value" Returns: A dictionary of the greatest change with a 'Date' and 'Profit/Losses' key """ # Value to assign initial greatest increase or decrease in profits or losses initial_assignment_performed = "no" # Stores 'Date' and 'PnL' in dictionary greatest_change_dictionary = {} # Loop through list of profits and losses for a_change_in_profits_and_losses_item in change_in_profits_and_losses_list: # Assignment of initial value to greatest increase from list if initial_assignment_performed == "no": # Assignment of dictionary values to variables date_value = a_change_in_profits_and_losses_item[key_1] pnl_value = a_change_in_profits_and_losses_item[key_2] # Initial assignment of values as the greatest change in dictionary greatest_change_dictionary[key_1] = date_value greatest_change_dictionary[key_2] = pnl_value # Initial assignment of greatest change incremented and no longer needs to be performed initial_assignment_performed = "yes" # Compare one change value to next value to find the greatest 'increase' in profits if greatest_change_dictionary[key_2] < a_change_in_profits_and_losses_item[key_2] and increase_or_decrease == "increase": # Assign profits and losses current item value and date to greatest change dictionary greatest_change_dictionary[key_1] = a_change_in_profits_and_losses_item[key_1] greatest_change_dictionary[key_2] = a_change_in_profits_and_losses_item[key_2] # Compare one change value to next value to find the greatest 'decrease' in losses elif greatest_change_dictionary[key_2] > a_change_in_profits_and_losses_item[key_2] and increase_or_decrease == "decrease": # Assign profits and losses current item value and date to greatest decrease of losses dictionary greatest_change_dictionary[key_1] = a_change_in_profits_and_losses_item[key_1] greatest_change_dictionary[key_2] = a_change_in_profits_and_losses_item[key_2] # Return greatest increase or decrease dictionary return greatest_change_dictionary def calculate_sum(list_of_dictionaries, key_name): """Accepts a list of dictionaries and loops through the list adding each key value. Args: list_of_dictionaries (list): A list of dictionaries key_name (str): The name of the key in the dictionaries to sum Returns: The sum of all the specified key values in the list. """ # Initialize variables sum = 0 # Loop through list for a_dictionary in list_of_dictionaries: # Add key values to sum variable sum += a_dictionary[key_name] return sum def largest_number(list_name): '''Takes in a list of integers and finds the largest number. Args: list_name (list): Name of list of numbers Returns: The largest value found in the list ''' # Assign initial greatest variable greatest_variable = 0 # Loop through list for current_item in list_name: # Compare if current item is greater than greatest variable if current_item > greatest_variable: # If true then assign current item to greatest variable greatest_variable = current_item # Return greatest variable return greatest_variable def smallest_number(list_name): '''Takes in a list of integers and finds the lowest number. Args: list_name (list): Name of list of numbers Returns: The lowest value found in the list ''' # Assign initial greatest variable lowest_variable = 0 # Loop through list for current_item in list_name: # Compare if current item is greater than greatest variable if current_item < lowest_variable: # If true then assign current item to greatest variable lowest_variable = current_item # Return greatest variable return lowest_variable
import csv speeding_cars = [] valid_number_plates = [] print ("Here is the list of speeding cars") for i,x in zip (speeding_cars,valid_number_plates): print(i,x) with open ("cars.csv","w")as f: f_csv = csv.writer(f) writer = csv.writer(f,delimiter = ",") writer.writerows(zip(speeding_cars,valid_number_plates)) f1 = ("data.csv", "r") f2 = ("cars.csv","r") f3 = ("results.csv","w") c1 = csv.reader(f1) c2 = csv.reader(f2) c3 = csv.writer(f3) if f1[3] == f2[2]: writer = csv.writer(f,delimiter = ",") writer.writerows(zip(f1 , f2))
# tworzenie obiektu - data elements + functions # T zazwyczaj oznacza new type # self oznacza every object class TActivity: def __init__(self, activityName, activityGrade): self.ActivityName = activityName self.ActivityGrade = activityGrade def showActivityState(self): print(" - " + self.ActivityName + " " + str(self.ActivityGrade)) def getActivityGrade(self): return self.ActivityGrade class TProcess: def __init__(self): self.ActivityList = [] self.noActivities = 0 def addActivity(self, arg): self.ActivityList.insert(self.noActivities, arg) self.noActivities = self.noActivities + 1 def showProcessState(self): print("Here is the list of my exams: ") for e in self.ActivityList: e.showActivityState() print("Mean grade of my exams = " + str(self.computeMeanValue())) def computeMeanValue(self): sumTemp = 0.0 for e in self.ActivityList: sumTemp = sumTemp + e.getActivityGrade() return round(sumTemp/self.noActivities, 2) def main(): myExams = TProcess() myExams.addActivity(TActivity("Statistical Methods", 5.0)) myExams.addActivity(TActivity("Python Programming", 4.5)) myExams.addActivity(TActivity("Big Data", 3.0)) myExams.showProcessState() if __name__ == "__main__": main()
#!/usr/bin/env python3 import unittest class Solution(object): def two_sum(self, nums, target): """ A solution to https://leetcode.com/problems/two-sum Given an array of integers, return two unique indicies of two numbers that add up to the supplied target. The same element may not be used twice. :type nums: List[int] :type target: int :rtype: List[int] """ for i, a in enumerate(nums): for j, b in enumerate(nums): if i == j: continue if a + b == target: return [i, j] return None class TestSolution(unittest.TestCase): def test_simple(self): s = Solution() self.assertEqual([0, 2], s.two_sum([1, 2, 3, 4], 4)) def test_no_reuse(self): s = Solution() self.assertEqual([1, 2], s.two_sum([3, 2, 4], 6)) if __name__ == '__main__': unittest.main()
class Guess: ''' The responsibility of guess is to track each players guess. Stereo type: information holder Attributes: _guess(integer): The players four digit guess ''' def __init__(self, guess): ''' The class constructor. Args: self (Guess): an instance of Guess. ''' self._guess = guess def get_guess(self): ''' Recieve the players four digit guess Args: self (Guess): an instance of Guess. Returns: Players guess ''' return self._guess
#!/bin/python3 import math import os import random import re import sys import fileinput # There is a new mobile game that starts with consecutively numbered clouds. # Some of the clouds are thunderheads and others are cumulus. # The player can jump on any cumulus cloud having a number that is equal to # the number of the current cloud plus 1 or 2. The player must avoid the thunderheads. # Determine the minimum number of jumps it will take to jump from the starting # postion to the last cloud. It is always possible to win the game. # # For each game, you will get an array of clouds numbered 0 # if they are safe or 1 if they must be avoided. # # Example # c = [0,1,0,0,0,1,0] # Index the array from 0...6. The number on each cloud is its index in the list # so the player must avoid the clouds at indices 1 and 5. They could follow these # two paths: 0>2>4>6 or 0>2>3>4>5. The first path takes 3 jumps while the second takes 4. # Return 3. # # Complete the 'jumpingOnClouds' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY c as parameter. # # c = [0,1,0,0,0,1,0] def jumpingOnClouds(c): jump = 0 converted = [str(c_int) for c_int in c] join_clouds = "".join(converted) end = False while not end: index = join_clouds.find('1') clouds = len(join_clouds[0:index]) if index < 0: end = True clouds = len(join_clouds[0:]) jump = jump + math.trunc(clouds / 2) + 1 join_clouds = join_clouds[index + 1:] return jump - 1 if __name__ == '__main__': for line in fileinput.input(): input = line.rstrip().split(" ") array_data = [numeric_string for numeric_string in input[0:]] result = jumpingOnClouds(array_data) print "result is {0}".format(result) # 28 > 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 # 3 > 0 0 0 1 0 0 # 4 > 0 0 1 0 0 1 0
#!/bin/python3 import math import os import random import re import sys import fileinput # A left rotation operation on an array shifts each of the array's elements 1 unit to the left. # For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would # become [3,4,5,1,2]. Note that the lowest index item moves to the highest index in a rotation. # This is called a circular array. # # Given an array 'a' of 'n' integers and a number, 'd', perform 'd' left rotations on the array. # Return the updated array to be printed as a single line of space-separated integers. # # Function Description # Complete the function rotLeft in the editor below. # rotLeft has the following parameter(s): # > int a[n]: the array to rotate # > int d: the number of rotations # # Returns # int a'[n]: the rotated array # # Complete the 'rotLeft' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER d # def rotLeft(a, d): if d > len(a): if d % len(a) == 0: return a else: d = d % len(a) result = a[d:] result = result + a[0:d] return result # Write your code here if __name__ == '__main__': for line in fileinput.input(): input = line.rstrip().split(" ") array_data = [int(numeric_string) for numeric_string in input[1:]] print "result is {0}".format(rotLeft(array_data, int(input[0]))) # 1999 1 2 3 4 5 6 7 > result is [5, 6, 7, 1, 2, 3, 4] # 4 1 2 3 4 5 > result is [5, 1, 2, 3, 4]
import numpy as np a = np.array([4, 10, 12, 23, -2, -1, 0, 0, 0, -6, 3, -7]) # 1. How many negative numbers are there? mask = a < 0 mask.sum() # 2. How many positive numbers are there? mask = a > 0 a[mask].sum() # 3. How many even positive numbers are there? a = a[a > 0] a = a[a % 2 == 0] a.size # 4. If you were to add 3 to each data point, # how many positive numbers would there be? a2 = a + 3 mask = a2 >0 mask.sum # 5. If you squared each number, # what would the new mean and standard deviation be? a3 = a**2 a3.mean() a3.std() # 6. A common statistical operation on a dataset is centering. # This means to adjust the data such that the center of the data is at 0. # This is done by subtracting the mean from each data point. # Center the data set. a.mean() a2 = (a - a.mean()) # 7 Calculate the z-score for each data point. a3 = a2 / a.std()
chinese_zodiac = "猴鸡狗猪鼠牛虎兔龙蛇马羊" zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座', u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', '射手座') zodiac_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22), (7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23)) cz_map = {} for i in chinese_zodiac: cz_map[i] = 0 zname_map = {} for i in zodiac_name: zname_map[i] = 0 while True: year = int(input("请输入年份: ")) month = int(input("请输入月份: ")) day = int(input("请输入日期: ")) n = 0 while zodiac_days[n] < (month, day): if month == 12 and day > 23: break n += 1 # 输出生肖和星座 print(zodiac_name[n]) print("%s 年的生肖是: %s" % (year, chinese_zodiac[year % 12])) cz_map[chinese_zodiac[year % 12]] += 1 zname_map[zodiac_name[n]] += 1 # 输出生肖和星座统计信息 for each_key in cz_map.keys(): print("生肖 %s 有 %d 个" % (each_key, cz_map[each_key])) for each_key in zname_map.keys(): print("星座 %s 有 %d 个" % (each_key, zname_map[each_key]))
from sys import argv script, filename = argv print filename print "file %r is going to be erased." %filename print "To cancel, hit CTRL-C (^C)." print "To proceed, hit RETURN." raw_input ("?") print "Opening the file ..." target = open(filename, 'w') print "Truncating the file. Adios!" target.truncate() print "Input the lyrics of the hit retro single 'What is love' by Haddaway:" line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") line4 = raw_input("line 4: ") print "Writing input to file." string = (line1 + '\n' + line2 + '\n' + line3 + '\n' + line4 ) target.write (string) target.close() print "Here is what you wrote:" print open(filename).read() print "And finally, we close it." target.close()
import random # 堆的向下调整 def heap_low(li, low, high, isLarge=True): temp = li[low] # 当low和high相等时,停止循环 while low < high: if isLarge: if low*2+2<=high and li[low*2+2]>li[low*2+1] and li[low*2+2]>temp: li[low] = li[low*2+2] low = low*2+2 # 左边孩子上位,并且排除上面情况 elif low*2+1<=high and li[low*2+1] > temp: li[low] = li[low*2+1] low = low*2+1 else: break else: if low*2+2<=high and li[low*2+2]<li[low*2+1] and li[low*2+2]<temp: li[low] = li[low*2+2] low = low*2+2 # 左边孩子上位,并且排除上面情况 elif low*2+1<=high and li[low*2+1] < temp: li[low] = li[low*2+1] low = low*2+1 else: break li[low] = temp # print(li) return li # 堆挨个出数 def heap_one_by_one(li, isLarge=True): low = 0 for high in range(len(li)-1, -1, -1): li[low], li[high] = li[high], li[low] li = heap_low(li, low, high-1, isLarge) return li # 建立堆,建立堆是从底部开始的 def heap_create(li, isLarge=True): n = len(li) - 1 # 循环所有根节点 for i in range((n-2+1)//2, -1, -1): li = heap_low(li, i, n, isLarge) return li # topk问题 def top_sort(li, k, isLarge=True): # 1、建立k个数的堆 li_topk = li[0: k] heap_create(li, isLarge) print(li_topk) # 2、遍历剩下的所有数 for i in range(k, len(li)-1): # 判断循环出的数和小根堆top的大小 if li[i] > li_topk[0]: li_topk[0] = li[i] heap_low(li_topk, 0, len(li_topk)-1, False) # print(li_topk) return li_topk # 堆排序 def heap_sort(li, isLarge=True): # 1、建立堆 heap_create(li, isLarge) print('create heap') print(li) # 2、挨个出数 heap_one_by_one(li, isLarge) # li = [3, 8, 7, 6, 5, 0, 1, 2, 4] # li = heap_low(li, 0, len(li)-1) # print(li) print('-----------------start------------------') li = [random.randint(0, 100) for i in range(10)] print(li) # heap_sort(li, False) print(top_sort(li, 5, False)) # print(li) print('--------------------end--------------')
import heapq # q:queue队列,优先队列 import random # 生成随机list,有两种方式 # 1、random.randint # li = [random.randint(0, 50) for i in range(20)] # 2、生成排序list后打乱 li = list(range(20)) random.shuffle(li) print(li) heapq.heapify(li) # 建堆(小根堆) print(li) for i in range(len(li)): # heapq.heappop每次会弹出一个最小的数 print(heapq.heappop(li), end=",") # 可以看到相对应的list会改变,不断减少一个最小值 print(li) # 与之相对的是heapq.heappush(heap, item),插入值
class Queue: def __init__(self, size=10): self.queue = [0 for i in range(size)] self.size = size self.front = 0 self.rear = 0 def isempty(self): return self.front == self.rear def isfull(self): return self.len() == self.size - 1 def len(self): if self.rear >= self.front: return self.rear - self.front else: return self.rear+self.size-self.front def push(self, element): ''' 入队列,首先判断queue是否满,不满的情况下: 1、next添加新元素 2、移动front到next ''' if self.isfull(): print('this queue is full') else: self.rear = (self.rear + 1) % self.size self.queue[self.rear] = element def pop(self): ''' 出队列,首先确认queue是不是空的,非空情况下: 1、移动rear,不需要其他操作 ''' if self.isempty(): print('this queue is empty') else: self.front = (self.front + 1) % self.size queue = Queue(5) for i in range(10): queue.push('sss') queue.pop() print(queue.len())
# -*- coding: utf-8 -*- """ Lunar Lander Parent Script By Jack Sandiford (SID: 4231908) Use the engine to stop the lunar lander from crashing! Created on Tue Oct 4 14:41:30 2016 @author: ppyjs8 """ """ Clearing any previous variables and clearing the console """ ### Remove all variables # %reset ### Clear the terminal # clear """ Import functions - via other python scripts """ import lunar_lander_main_menu as main_menu; import lunar_lander_game as game; """ Menu Screen: Select difficulty and read instructions """ difficulty = main_menu.start(); """ Run the lunar lander game """ game.start(difficulty); """ Features that could be added in the future: - Menu screen - Add instructions - Several difficulty modes - Bar colours change depending on bar height - Get lunar lander visual representation working - Tidy up code by adding all bars to a list - Add a status message that predicts the outcome - Add horizontal motion - Add key bindings / listeners - Add a quit button - Add a pause button - Add a reset button - Save final score to a file - Read score to check high score - Add sound effects - Add music - Add lunar lander sprite (visual representation) - Add engine effects (visual representation) - Add arrow keys that highlight when an arrow key press is detected - Add planet's ground (visual representation) - Planet's colour and features depend on difficulty (visual representation) - """ """ OTHER COMMENTS: Couldn't manage to get the several difficulty buttons to work! Will work on this in my own time. """
Used_For="App Development" Version=3.6 # Example 1: # Note: Call or Access a variable using curly braces {}, are used as placeholders. print(Used_For,id(Used_For),type(Used_For)) print("") print(Version,id(Version),type(Version)) print("") print('Python is used for {} and course is {}'.format(Used_For,Version)) # Example 2: # We can specify the order in which it is printed by using numbers (tuple index). phone='Ipone7' laptop="Mac Book Pro" print('I like {0} and {1}'.format('Ipone7','Mac Book Pro')) print('I like {1} and {0}'.format(phone,laptop)) # Example 3: # We can use keyword arguments to format the string: print('Hello {name}, {greeting}'.format(greeting='Goodmorning',name='John'))
from bs4 import BeautifulSoup from urllib.request import urlopen scrapingURL = "http://www.gregreda.com/2013/03/03/web-scraping-101-with-python/" def get_page_title(page_url): html = urlopen(page_url).read() soup = BeautifulSoup(html, "lxml") article_title = soup.find("h1", "article-title") return article_title.string def print_pretty_soup(page_url): html = urlopen(page_url).read() soup = BeautifulSoup(html, "lxml") article_title = soup.find("h1", "article-title") print(article_title.prettify()) # print(get_page_title(scrapingURL)) print_pretty_soup(scrapingURL)
''' Bai 34: Dinh nghia 1 ham co the tao dictionay, chua cac key la cac so tu 1 den 20 va cac gtri binh phuong cua chung. ham chi in ra cac gtri ''' def Dictionary(n): dictionary = {} for i in range(1, n + 1): dictionary[i] = i ** 2 print(dictionary.values()) Dictionary(20)
''' l = [1,2,3,4,5] # List len(l) # Chiều dài của list l[i] # Lấy ra phần tử trong list ở vị trí i l = l + l # Tăng gấp đôi danh sách list l = l * 2 # Tăng gấp đôi danh sách list l = l * 3 # Tăng gấp ba danh sách list l[i] = value # Cập nhật giá trị mới cho list l[start:end] # Lấy giá trị list từ vị trí start -> end ===== List Method ===== l.append(val) # Thêm 1 phần tử vào cuối list l.insert(index, val) # Thêm phần từ vào vtri index+1 l.pop(index) # Xoá phần tử ở vtri index l.count(val) # Đếm số lần xuất hiện của phần tử l.sort() # Sắp xếp list theo thứ tự tăng dần l.reverse() # Đảo ngược vtri phần tử del l[index] # Xoá phần tử tại vtri index del l[from:to] # Xoá phần tử từ vtri from -> to ''' l = [1,2,3,4,5] l = l + [5,6,7] # thêm 1 hoặc nhiều phâng tử phần tử l.append(9) # thêm 1 phần tử print(l) print(l.count(5))
''' Bai 46: Viet chuong trinh dung map() de tao list chua cac gtri binh phuong cua cac so trong [1,2,3,4,5,6,7,8,9,10] * Su dung map() de tao list * Su dung lamba() de dinh nghia ham chua biet ''' li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] squareNumners = list(map(lambda x: x ** 2, li)) print(squareNumners)
''' Bai 43: Viet chuong trinh de tao ra va in tuple chua cac so chan duoc lay tu tuple(1,2,3,4,5,6,7,8,9,10) ''' def MakeNewTuple(*data): data = tuple(data) l = [] for item in data: if item % 2 == 0: l.append(item) print(tuple(l)) MakeNewTuple(1,2,3,4,5,6,7,8,9,10)
''' Bai 22: Viet chuong trinh sap xep tuple(name,age,score) theo thu tu tang dan Tuple duoc nhap vao boi nguoi dung Tieu chi sap xep la: Name > Age > Score Note: Su dung itemgetter de chap nhan key sap xep ''' from operator import itemgetter l = [] s = input("Enter info (Name,Age,Score): ") while (len(s) != 0): l.append(tuple(s.split(','))) s = input("Enter info (Name,Age,Score): ") print(l.sort(key=itemgetter(0, 1, 2)))
''' Bai 29: Dinh nghia ham co the nhan 2 chuoi tu input Noi chung lai roi in ra man hinh ''' def StringAddString(str1,str2): str = str1 + str2 print(str) s1 = input("Nhap chuoi thu nhat: ") s2 = input("Nhap chuoi thu hai : ") StringAddString(s1,s2)
import random print("ROCK - PAPER - SCISSORS GAME") list = ["rock","paper","scissors"] again = True while again: y = input("Please enter your choice(Rock, Scissors, Paper) : ") # Players answer x = random.choice(list) # Computers Answer if x == y: print("Computer chose " + x.upper() + " you chose " + y.upper() + " so it's a tie you will get to choose again.") continue elif y == "rock": if x == "paper": print("Computer chose " + x.upper() + " you chose " + y.upper() + " so COMPUTER won.") else: print("Computer chose " + x.upper() + " you chose " + y.upper() + " so YOU won.") elif y == "paper": if x == "rock": print("Computer chose " + x.upper() + " you chose " + y.upper() + " so YOU won.") else: print("Computer chose " + x.upper() + " you chose " + y.upper() + " so COMPUTER won.") elif y == "scissors": if x == "rock": print("Computer chose " + x.upper() + " you chose " + y.upper() + " so COMPUTER won.") else: print("Computer chose " + x.upper() + " you chose " + y.upper() + " so YOU won.") play = input("Do you want to play again? > ") if play == "no": again = False
import pandas as pd import matplotlib.pyplot as plt # Get data and print a sample data = pd.read_csv("hubble_data.csv") # Reads CSV data file (automatically parses headers) print('Data sample:\n',data.head(), '\n') # Print the first 5 rows of data and their headers # Set the index of the data to the distance column data.set_index('distance', inplace=True) # Distance is our new x axis # Plot and show the data data.plot() # Data is already in the proper x v. y format plt.show()
#!/usr/bin/env python # -*- coding: utf8 -*- import warnings class RouteDict(dict): """ A hash-table dictionary of Routes. O(1) matching. """ def add(self, route): """ Adds route to the dictionary. If route is already in the dictionary, drops the route while issuing a warning. """ for path in route.paths(): if path in self: warnings.warn('Route collision: %s was dropped for %s' % (repr(route), repr(path))) else: self[path] = route def match(self, path): """ Returns the rotue which matches path. Returns False if no route matches. """ return self.get(path, False)
class AvailableMove: """ 'AvailableMove' objects are used in the Carcassonne.availableMoves() method to contain all the factors of a playable move into one object """ def __init__(self, TileIndex, X, Y, Rotation, MeepleInfo = None): self.TileIndex = TileIndex self.X = X self.Y = Y self.Rotation = Rotation self.MeepleInfo = MeepleInfo self.move = (TileIndex, X, Y, Rotation, MeepleInfo) self.moveString = f'({TileIndex}, {X}, {Y}, {Rotation}, {MeepleInfo})' def __repr__(self): if self.MeepleInfo is not None: Location = self.MeepleInfo[0] LocationIndex = self.MeepleInfo[1] if Location == 'C': FullLocation = "City" elif Location == 'R': FullLocation = "Road" elif Location == "G": FullLocation = "Farm" else: FullLocation = "Monastery" MeepleString = ", Meeple Location: " + FullLocation + ", Location Index: " + str(LocationIndex) else: MeepleString = "" String = "TileIndex: " + str(self.TileIndex) + ", (X,Y): (" + str(self.X) + "," + str(self.Y) + "), Rotation: " + str(self.Rotation) + MeepleString return String
#coding=utf-8 # 在要排序的一组数中,选出最小的一个数与第1个位置的数交换; # 然后在剩下的数当中再找最小的与第2个位置的数交换, # 依次类推,直到第n-1个元素和第n个元素(最后一个数)比较为止。 def select_sort(orgin_list): length = len(orgin_list) # 从list[0]开始遍历,进行外循环,list[i]作为基准位置比较数 for i in range(length-1): mi = i for j in range(i,length): # 找到最小的一个数的位置 if orgin_list[j] < orgin_list[mi]: mi = j orgin_list[mi],orgin_list[i] = orgin_list[i],orgin_list[mi] return orgin_list if __name__ == "__main__": orgin = [1, 3, 4, 2, 7, 4, 6, 8] print select_sort(orgin)
sum=0 for i in range(1,1001,1): sum=sum+i print("i=", i) print("sum=",sum) print("===========") sum=0 for i in range(2,1001,2): sum=sum+i print("sum2=", sum)
import csv, numpy def get_data1(): data = [['SN', 'Person', 'DOB'], ['1', 'John', '18/1/1997'], ['2', 'Marie', '19/2/1998'], ['3', 'Simon', '20/3/1999'], ['4', 'Erik', '21/4/2000'], ['5', 'Ana', '22/5/2001']] return data def get_data2(): data = [['name', 'sn', 'depth','height'], ['bl', 'LD001', 32, 24], ['jl', 'LD003', 33, 55]] return data def write_newcsv(fname,fdata): #write data (list of list) to file with deleleting everything already inside #'w'= new write, 'a'= append with open(fname, 'w') as fw: #with action will close the opened file automatically after loop ends csvWriter=csv.writer(fw) data=get_data2() for row in fdata: csvWriter.writerow(row) test_row=['al','LD005',33,56,57] csvWriter.writerow(test_row) def read_csv(fname): #with different delimiter: reader = csv.reader(f, delimiter="|") lines=[] with open(fname, 'r') as fr: csvReader=csv.reader(fr) for row in csvReader: print(row) for e in row: print(e) lines.append(row) return lines #========================================== #main fname='new_csv.csv' #write_newcsv(fname, get_data2()) cnt=read_csv(fname) print(cnt)
# python have few built_in operator: # range: range function allows us to quickly genarate a list of integers # if we want a list of 0 to 9 print(range(0, 10)) # it does not print the actual output # note range is a genarator function, a genarator is a special type of function that will genarate information. # and it not need to save to memory. # so if we want to get actual output we need to cast it with list() my_list = list(range(0, 10)) print(my_list) # try my_tuple = tuple(range(0, 10)) print(my_tuple) # step size: my_list = list(range(0, 10, 2)) print(my_list) # enumurate: enumurate is very handy with for loops: # imagine # index_count = 0 # for item in 'hello world': # print('at {} index letter is {}'.format(index_count, item)) # index_count += 1 # the commented example is the same of it. # it similar to the tuple unpacking. for index_count, item in enumerate('hello world'): print('at {} index letter is {}'.format(index_count, item))
# python dictionary is very flexible, its holds multiple datatype my_dict = {'k1': 'value1', 'k2': 'value2', 'k3': 123, 'k4': 0.000456, 'k5' :[1, 2, 3, 4, 5], 'k6': {'k7': 1234, 'k8': 0.09}, 'k9': (1, 2, 3, 4)} print(my_dict) # dictionary is the form of key value pair # dictionary basic operation=> # try #print(my_dict[0]) # its shows an error because dictionary can't support indexing # calling key value: print(my_dict['k5']) # now we can indexing the key value print(my_dict['k5'][3]) # we apply methods on that key values print(my_dict['k1'].upper()) # method to get all key values print(my_dict.keys()) # method to get all values print(my_dict.values()) # method to get all key and value's tuple print(my_dict.items()) # nesting dictionary print(my_dict['k6']) # its holds a dictionary on it # we can get values from nested dictionary print(my_dict['k6']['k7']) # optional operation # we can doing some stuff with dictionary print(my_dict['k3'] + 4) # we can also do subtraction/division/multiplication etc. # creating a new dictionary dictionary = {} dictionary['name'] = 'swarup' dictionary['age'] = 20 print(dictionary)
#!/usr/bin/python import pickle import numpy numpy.random.seed(42) # the words (features) and authors (labels), already largely processed words_file = "word_data_overfit.pkl" # like the file you made in the last mini-project authors_file = "email_authors_overfit.pkl" # this too word_data = pickle.load(open(words_file, "r")) authors = pickle.load(open(authors_file, "r")) # test_size is the percentage of events assigned to the test set (remainder go into training) from sklearn import cross_validation features_train, features_test, labels_train, labels_test = \ cross_validation.train_test_split(word_data, authors, test_size=0.1, random_state=42) from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english') features_train = vectorizer.fit_transform(features_train).toarray() features_test = vectorizer.transform(features_test).toarray() # a classic way to overfit is to use a small number # of data points and a large number of features # train on only 150 events to put ourselves in this regime features_train = features_train[:150] labels_train = labels_train[:150] # your code goes here # What is the accuracy of the decision tree you just made? from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier() clf.fit(features_train, labels_train) print "Accuracy:", clf.score(features_test, labels_test) # What is the importance of the most important feature? What is the number of this feature? import numpy as np importances = clf.feature_importances_ indices = np.argsort(importances)[::-1] print 'Feature Ranking: ' for i in range(10): print "{} feature no.{} ({})".format(i+1, indices[i], importances[indices[i]]) # feature no.33614 (0.764705882353) # What is the most powerful word when your decision tree is making its classification decisions? print vectorizer.get_feature_names()[33604] # 'sshacklensf'
def counter(a, b): # лічильник знайдених чисел num = 0 # перетворимо числа на рядки для зручності порозрядної роботи (так, мені просто подобається цей прийом) a_str = str(a) b_str = str(b) # а сюди будемо додавати вже знайдені числа (схоже на попереднє завдання) found = '' # тепер перебираємо всі розряди числа b for char_b in b_str: # якщо роряд наявний в числі a, але відсутній у знайдених, збільшити лічильник та додати розряд до знайдених цифр if a_str.find(char_b) != -1 and found.find(char_b) == -1: num = num + 1 found = found + char_b # повернути значення лічильника return num
import sys FlagError = True sum = 0 for count in sys.argv[1]: if count == '(': sum = sum + 1 else: sum = sum - 1 if sum < 0: FlagError = False if FlagError and sum == 0: print('YES') else: print('NO')
class Sphere(object): def __init__(self, r = 1, x = 0.0, y = 0.0, z = 0.0): self.r = r self.x = x self.y = y self.z = z def get_volume(self): import math return 4.0/3.0 * math.pi * self.r ** 3 def get_square(self): import math return 4 * math.pi * self.r ** 2 def get_radius(self): return self.r def get_center(self): return (self.x, self.y, self.z) def set_radius(self, radius): self.r = radius def set_center(self, x, y, z): self.x = x self.y = y self.z = z def is_point_inside(self, a, b, c): import math point = math.sqrt((self.x - a)**2 + (self.y - b)**2 + (self.z - c)**2) if self.r > point: return True return False s = Sphere() print(s.get_volume()) print(s.get_square()) print(s.get_radius()) print(s.get_center()) print(s.is_point_inside(3, 2, 3)) s.set_radius(5) s.set_center(3, 5, 6) print(s.get_volume()) print(s.get_square()) print(s.get_radius()) print(s.get_center()) print(s.is_point_inside(3, 2, 3))
class areaCircle: def areadelcirculo(self): print ("CALCULAR EL AREA DE UN CIRCULO") radio=input("CUAL ES EL RADIO: ") pi=3.1416 area=float (pi) * int (radio) ** 2.0 print("El área es: " + str (area)) area = areaCircle() area.areadelcirculo()
list1 = ['a','b','c','d','e','f','g','a'] ind1 = list1.index('a') ind2 = list1.index('d') ind3 = list1.index('a', 3) print(ind1) print(ind2) print(ind3)
str1 = 'hello' strlen1 = len(str1) print('str1의 길이는 %d이다.' %strlen1) str2 = input('문자열을 입력해주세요. ') strlen2 = len(str2) print('입력한 문자열의 길이는 %d이다.' %strlen2)
#图形界面库 from tkinter import * import tkinter.simpledialog as dl import tkinter.messagebox as mb ''' root = Tk() w = Label(root,text = "label title") w.pack() #信息框 mb.showinfo("Welcome","Welcome Message") #又弹一个新的对话框 guess = dl.askinteger("Number","Enter a number") output = 'This is output message' mb.showinfo("Output:",output) ''' root = Tk() #创建一个Label w = Label(root,text = "Guess Number Game") w.pack() #显示信息框 mb.showinfo("Welcome","Welcome to Guess Number Game") #定义一个数字 number = 59 #循环猜 while True: guess = dl.askinteger("Number","What's your guess ?") if guess == number: output = "Bingo! you guessed it right. but you do not win any prizes !" mb.showinfo("Hint:",output) break elif guess < number: output = "No,the number is a biger than that." mb.showinfo("Hint:",output) else: output = "No,the number is a lower than that." mb.showinfo("Hint:",output) print("Done")
# 참고) 리스트 내포(리스트 컴프리헨션) #append() 사용 num = [] for n in [1, 2, 3] : num.append(n*2) print('append 사용 : ', num) print() # 리스트 내포 사용 num2 = [n*2 for n in [1, 2, 3]] print('리스트 내포 사용 : ', num2) print() # append, if 사용 num3 = [] for n in [1, 2, 3, 4, 5] : if n % 2 == 1: # 홀수만 num3.append(n*2) print('append, if 사용 : ', num3) # 조건을 만족하는 데이터만 출력하는 리스트 내포 num4 = [n*2 for n in [1, 2, 3, 4, 5] if n%2==1] print('조건 리스트 내포 사용 : ', num4)
# p.g 107 my_list = [] n = int(input('정수를 입력하세요(종료는 0입니다.) >>> ')) while n != 0 : my_list.append(n) n = int(input('정수를 입력하세요(종료는 0입니다.) >>> ')) print(my_list) print() # TIP my_list = [] n = 1 # 0이 아닌 초기값 실행 -> while문 실 while n != 0 : n = int(input('정수를 입력하세요(종료는 0입니다.) >>> ')) my_list.append(n) # pop() : 리스트의 마지막 요소를 뽑은 후 제거 # pop(리스트 요소 위치) : 리스트 위치의 요소를 뽑은 후 제 my_list.pop() # my_list의 마지막 요소는 언제나 0이므로 제거 print(my_list) print() # 중첩 while문 day = 1 while day <= 5 : hour = 1 while hour <= 3: print('{}일차 {}교시 입니다.'.format(day, hour)) hour += 1 day += 1 # p.g 110 dan = 2 while dan <= 9: n = 1 while n <= 9: print('{} X {} = {}'.format(dan, n, dan*n)) n += 1 dan += 1
# p.g 160 # 01. rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple'] for index, color in enumerate(rainbow, start = 1): print(f'무지개의 {index}번째 색은 {color}입니다.') print() # 02. exam = [] print('점수를 입력하세요. 더 이상 입력할 점수가 없으면 음수를 아무거나 입력하세요.') while True : score = float(input('점수 입력 >>> ')) if score > 0: exam.append(score) continue else : break print('평균 = {}, 최대 = {}, 최소 = {}'.format(sum(exam)/len(exam), max(exam), min(exam))) print()
# 기본 연산자 # p.g 73 a = 7 b = 2 print('{} + {} = {}'.format(a,b,a+b)) print('{} - {} = {}'.format(a,b,a-b)) print('{} * {} = {}'.format(a,b,a*b)) print('{} ** {} = {}'.format(a,b,a**b)) print('{} / {} = {}'.format(a,b,a/b)) print('{} // {} = {}'.format(a,b,a//b)) print('{} % {} = {}'.format(a,b,a%b)) print() # 대입 연산자 # p.g 75 a,b = 10, 20 print('a = %d, b = %d' %(a, b)) a, b = b, a print('a = %d, b = %d' %(a, b)) print() # 복합 대입 연산자 # ex) a가 10에서 시작해서 코드가 진행될수록 값이 변하도록 해보기 a = 10 print('a의 값 :',a) a += 5 print('a의 값 :',a) a -= 5 print('a의 값 :',a) a *= 5 print('a의 값 :',a) a **= 5 print('a의 값 :',a) a /= 5 print('a의 값 :',a) a //= 5 print('a의 값 :',a) a %= 5 print('a의 값 :',a) print() # p.g 76 piggy_bank = 0 money = 10000 piggy_bank += money print('저금통에 용돈 {}원을 넣었습니다.'.format(money)) print('지금 저금통에는 {}원이 있습니다.'.format(piggy_bank)) snack = 2000 piggy_bank -= snack print('저금통에 스낵 구입비 {}원을 뺐습니다.'.format(snack)) print('지금 저금통에는 {}원이 있습니다.'.format(piggy_bank)) print() # 관계 연산자 : 자동으로 T/F 출력(bool) # p.g 78 a = 15 print('{}>10 : {}'.format(a, a>10)) print('{}<10 : {}'.format(a, a<10)) print('{}>=10 : {}'.format(a, a>=10)) print('{}<=10 : {}'.format(a, a<=10)) print('{}==10 : {}'.format(a, a==10)) print('{}!=10 : {}'.format(a, a!=10)) print() # 논리 연산자 # p.g 78 a = 10 b = 0 print('{}>0 and {}>0 : {}'.format(a, b, a>0 and b>0)) print('{}>0 or {}>0 : {}'.format(a, b, a>0 or b>0)) print('not {} : {}'.format(a, not a)) print('not {} : {}'.format(b, not b)) print() # 비트 연산자 : 2진수로 연산 # p.g 82 a = 10 # a = 0000 1010 -> 10 b = 70 # b = 0100 0110 -> 70 print('a & b : {}'.format(a&b)) # a&b = 0000 0010 -> 2 print('a | b : {}'.format(a|b)) # a|b = 0100 1110 -> 78 print('a ^ b : {}'.format(a^b)) # a^b = 0100 1100 -> 76 print('~a : {}'.format(~a)) # ~a = 1111 0101 -> -11 : 0이면 1, 1이면 0 print('a << 1 : {}'.format(a<<1)) # a << n = 0001 0100 -> 20 : 왼쪽으로 n 이동, 2^n만큼 곱셈 print('a >> 1 : {}'.format(a>>1)) # a >> n = 0000 0101 -> 5 : 오른쪽으로 n 이동, 2^n만큼 나눗셈 print() # 시퀀스 연산자 # p.g 83 tree = '#' space = ' ' print(space*4+tree*1) print(space*3+tree*3) print(space*2+tree*5) print(space*1+tree*7) print(space*0+tree*9) print() # 기타 연산자 # 1) 멤버쉽 연산자 (in 연산자) print('안녕'in'안녕하세요') # 포함되어있음 -> True 출력 print('잘가'in'안녕하세요') # 포함되어있지X -> False 출력 print('안녕'not in'안녕하세요') # 포함되어있음 -> False 출력 print('잘가'not in'안녕하세요') # 포함되어있지X -> True 출력 # 2) 삼항연산자 : 참if(조건식)else(거짓) # p.g 84 a = 10 b = 20 result = (a-b)if(a>=b)else(b-a) print('{}와 {}의 차이는 {}입니다.'.format(a,b,result)) print()
# p.g 180 # 01. num = input('전화번호를 입력하세요 >>> ') phone = num.split('-')[1] print(phone) print() # 02. num = input('사업자등록번호를 입력하세요(예: 123-45-67890) >>> ') n1 = num.split('-')[0] n2 = num.split('-')[1] n3 = num.split('-')[2] condition1 = len(num) == 12 condition2 = (num.find('-') == 3) condition3 = (num.find('-', 4) == 6) condition4 = (num.replace('-','').isdecimal) if condition1 and condition2 and condition3 and condition4: print('올바른 형식입니다.') else: print('올바른 형식이 아닙니다.') print() # p.g 181 # 03. student = '"김철수", 85' name = student.split(',')[0].strip('"') score = student.split(',')[1] print('이름은 {}이고, 점수는 {}입니다.'.format(name, score)) print()
# 세트(집합) : 순서X -> 인덱싱, 슬라이싱X. 중복 값 저장X -> 중복 제거용 s1 = {1, 2, 3} print('세트 s1 :', s1) # 요소 1개 추가 : add() s1.add(4) print('세트 s1 :', s1) # 요소 여러 개 추가 : update() s1.update([5, 6, 7]) # 리스트 형태로 삽입 print('세트 s1 :', s1) # 특정 요소 제거 : remove(), discard() s1.remove(3) print('세트 s1 :', s1) s1.discard(5) print('세트 s1 :', s1) s1.discard(0) print('세트 s1 :', s1) # remove() vs discard() ''' remove(a) : a가 없으면 오류 발생 discard(a) : a가 없어도 오류X '''
# 여러 개의 변수 a, b, c = 1, 2, 3 # 변수 값을 대입할 때 한 번에 순서대로 대입, 짝이 맞아야 함 print(a) print(b) print(c) a = b = c = 4 # 여러 개의 변수에 한 번에 같은 값 대입 가능 print(a) print(b) print(c) # 변수의 교환 a = 1 b = 2 print('변수 a :', a)
""" Find the max/min elements in a list. """ def max(a): max_elem = a[0] for element in a[1:]: if element > max_elem: max_elem = element return max_elem def min(a): minimum = a[0] for elem in a[1:]: if elem < minimum: minimum = elem return minimum
""" Compute the area of an arbitrary triangle Create a function area(vertices) that return the area of the triangle supplied. Test with a known triangle """ def area(vertices): xy1 = vertices[0] xy2 = vertices[1] xy3 = vertices[2] A = 0.5 * (xy2[0] * xy3[1] - xy3[0] * xy2[1] - xy1[0] * xy3[1] + xy3[0] * xy1[1] + xy1[0] * xy2[1] - xy2[0] * xy1[1]) return A triangle = [[0, 0], [2, 0], [2, 3]] print area(triangle) """ Running program Unix>python 2.17-area_triangle.py 3.0 """
import sys try: n = int(sys.argv[1]) # n dice i = int(sys.argv[2]) # i experiments except: print '''Usage: python %s n i n - number of dice i - number of experiments to run''' % sys.argv[0] def one6(n): return 1./6.*n - (n-1)/36. # Exact probability def throw_die(): import random return random.randint(1,6) j = 0 match = 0 while j < i: hit = False for k in range(n): die = throw_die() if die == 6: hit = True if hit: match +=1 j += 1 print "Probability for at least one six when throwing %g dice is %.f percent (%g throws)" % (n, float(match)/i*100, i) ''' Unix>python one6_2dice.py 2 100000 Probability for at least one six when throwing 2 dice is 31 percent (100000 throws) '''
""" Express a step function as a python function """ def H(x): if x < 0: return 0 elif x >= 0: return 1 print H(-0.5) print H(0) print H(10) """ Running program Unix>python 2.36-Heaviside.py 0 1 1 """
""" We need to give an input of a function and output: -extrema (max/min, local/absolute) -inc/dec intervals -concave up/down -points of inflection """ """ term = input("How many terms do you want in your function?") interval = input("What interval do you want us to analyze?" """ ''' Instructions: Hit "GO" and enter a function into the input box -Denote operations using the following symbols: '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), '^' exponent -Note that '-' denotes subtraction; use '_' as a negative sin (ex. _3*x represents -3x) -Only enter negative signs before numbers, not parentheses or trig functions (ex. write -(x+2) as _1*(x+2), write -sinx as _1*sinx) -Always enter the '*' sign - do NOT write numbers/variables/groups next to each other with no symbol to imply multiplication (ex. write 2*(x+1), NOT 2(x+1)) -Denote trig functions using their appropriate three-letter abbreviations (sin, cos, tan, csc, sec, cot) -Parentheses may be used (multiple sets may be used, but not concentric sets) -Use parentheses and the division symbol for rational functions -Pi and Euler's number may be denoted using p and e respectively ''' from math import sin, cos, tan, pi, e f_string = input("Please enter function ") #x_val = float(input("Please enter x value ")) n_test = ['0','1','2','3','4','5','6','7','8','9','10','.'] t_test = ['s','c','t'] fl_orig = [] #Defines fl_orig, which will contain items representing the various "pieces" (numbers, x, operations, etc.) of the function i = 0 while i < len(f_string): #Looks through string, examines each item, and adds it to list in the appropriate form if f_string[i] in n_test: #Adds multi-digit numbers (ex. 101) as list items num = '' while i < len(f_string) and f_string[i] in n_test: num += f_string[i] i += 1 fl_orig.append(float(num)) elif f_string[i] in t_test: #Adds three-letter representations of trig functions (ex. sin) as list items tf = '' for x in range(3): tf += f_string[i] i += 1 fl_orig.append(tf) elif f_string[i] == 'p': #Replaces letter p with decimal representation of pi, adds it to list fl_orig.append(pi) i += 1 elif f_string[i] == 'e': #Replaces letter e with decimal representation of Euler's number, adds it to list fl_orig.append(e) i += 1 else: #Adds items not in the above categories to list (includes 'x' and operation symbols) fl_orig.append(f_string[i]) i += 1 print(fl_orig) def f(x): #Defines function f global fl_orig f_list = fl_orig[:] #Creates f_list, a copy of fl_orig (This is done so that the original list remains "intact" and can be reused) i = 0 while i < len(f_list): #Replaces 'x' with numerical value of x if f_list[i] == 'x': f_list[i] = x i += 1 return evaluate(f_list) #Calls the evaluate function to calculate the result - returns this result def evaluate(f_list): #Defines evalute function, which can compute any list using proper order of operates while '_' in f_list: #Eliminates '_' and makes the number immediately after it negative i_neg = f_list.index('_') f_list = f_list[:i_neg]+[-1*f_list[i_neg+1]]+f_list[i_neg+2:] while '(' in f_list: #Searches for parentheses (loops until all parentheses have been eliminated) i_open = f_list.index('(') i_close = f_list.index(')') group = f_list[i_open+1:i_close] #Creates "group," which is a new list consisting of the contents of parentheses f_list = f_list[:i_open]+[evaluate(group)]+f_list[i_close+1:] #Calls the evaluate function for "group," and inserts the result into the list where the parentheses and their contents orginally were for tf in ['sin','cos','tan','csc','sec','cot']: while tf in f_list: #Looks for trig functions and evaluates all of them until none are left t_i = f_list.index(tf) if tf == 'sin': #Determines if function is sin - if so, evaluates the sin of the number following the function result = sin(f_list[t_i+1]) elif tf == 'cos': #Repeates for cos and other trig functions result = cos(f_list[t_i+1]) elif tf == 'tan': result = tan(f_list[t_i+1]) elif tf == 'csc': result = 1/sin(f_list[t_i+1]) elif tf == 'sec': result = 1/cos(f_list[t_i+1]) elif tf == 'cot': result = 1/tan(f_list[t_i+1]) f_list = f_list[:t_i]+[result]+f_list[t_i+2:] #Inserts result of trig calculate into list and eliminates original function and number while '^' in f_list: #Evaluates all exponents op_i = f_list.index('^') result = f_list[op_i-1]**f_list[op_i+1] f_list = f_list[:op_i-1]+[result]+f_list[op_i+2:] #Inserts calculated result and eliminates base, exponent symbol, and power while '/' in f_list: #Replaces division with multiplication by the recipricol i = f_list.index('/') f_list[i+1] = 1/f_list[i+1] f_list[i] = '*' while '*' in f_list: #Evaluates all multiplication (same method as exponents) op_i = f_list.index('*') result = f_list[op_i-1]*f_list[op_i+1] f_list = f_list[:op_i-1]+[result]+f_list[op_i+2:] while '-' in f_list: #Replaces subtraction with addition of the opposite i = f_list.index('-') f_list[i+1] *= -1 f_list[i] = '+' while '+' in f_list: #Evaluates all addition (same method as exponents and multiplication) op_i = f_list.index('+') result = f_list[op_i-1]+f_list[op_i+1] f_list = f_list[:op_i-1]+[result]+f_list[op_i+2:] return f_list[0] #List should now contain only one number, which represents the calculated result - function returns this number step = 100 calc_precision = 0.0001 x_values = [x/step for x in list(range(-3*step,3*step+1))] f_data = [] fp = lambda x: (f(x+calc_precision)-f(x-calc_precision))/(2*calc_precision) for x in x_values: f_data.append([x,f(x),fp(x),(fp(x+calc_precision)-fp(x-calc_precision))/(2*calc_precision)]) print(f_data) #print(f_list) """ EXTREMA for i in range(len(f_data)-2): if f_data[i][2] < 0 and f_data[i+1][2] <= 0 and f_data[i+2][2] > 0: print("Local min at x = "+str(f_data[i+1][0])) elif f_data[i][2] > 0 and f_data[i+1][2] >= 0 and f_data[i+2][2] < 0: print("Local max at x = "+str(f_data[i+1][0])) #else: # print("There are no local max's in the interval") INC/DEC INTERVALS CONCAvITY c_up = [] c_down = [] for i in range(len(f_data)): if f_data[i][3] > 0: c_up.append(f_data[i][0]) elif f_data[i][3] < 0: c_down.append(f_data[i][0]) print(c_up, c_down) POINTS OF INFLECTION for i in range(len(f_data)-2): if f_data[i][3] < 0 and f_data[i+1][3] <= 0 and f_data[i+2][3] > 0: print("Point of inflection at x = "+str(f_data[i+1][0])) elif f_data[i][3] > 0 and f_data[i+1][3] >= 0 and f_data[i+2][3] < 0: print("Point of inflection at x = "+str(f_data[i+1][0])) """
from typing import List def delete_duplicate_v1(numbers: List[int]) -> None: i = 0 j = 1 while j < len(numbers): if numbers[i] != numbers[j]: numbers[i+1] = numbers[j] i += 1 j += 1 numbers[:] = numbers[:i+1] def delete_duplicate_v1_by_sakai(numbers: List[int]) -> None: tmp = [] for n in numbers: if n not in tmp: tmp.append(n) numbers[:] = tmp def delete_duplicate_v2_by_sakai(numbers: List[int]) -> None: tmp = [numbers[0]] i, len_num = 0, len(numbers) - 1 while i < len_num: if numbers[i] != numbers[i+1]: tmp.append(numbers[i+1]) i += 1 numbers[:] = tmp def delete_duplicate_v3_by_sakai(numbers: List[int]) -> None: i = 0 while i < len(numbers) - 1: if numbers[i] == numbers[i+1]: numbers.remove(numbers[i]) i -= 1 i += 1 def delete_duplicate_v4_by_sakai(numbers: List[int]) -> None: i = len(numbers) - 1 while 0 < i: if numbers[i-1] == numbers[i]: numbers.pop(i) i -= 1 if __name__ == '__main__': numbers = [1, 3, 3, 5, 5, 7, 7, 7, 10, 12, 12, 15] print(list(set(numbers))) print(list(dict.fromkeys(numbers))) print([n for i, n in enumerate(numbers) if n not in numbers[:i]]) delete_duplicate_v4_by_sakai(numbers) print(numbers)
from typing import Any, Optional class Stack(object): def __init__(self) -> None: self.values = [] def push(self, value: Any) -> None: self.values.append(value) def pop(self) -> Optional[Any]: if self.values: return self.values.pop() if __name__ == '__main__': stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack.values) print(stack.pop()) print(stack.values) print(stack.pop()) print(stack.values) print(stack.pop()) print(stack.pop())
import string from typing import Generator def caesar_cipher(text: str, shift: int) -> str: ascii = None result = [] for t in text: if t.islower(): ascii = string.ascii_lowercase elif t.isupper(): ascii = string.ascii_uppercase else: result.append(t) continue index = (ascii.index(t) + shift) % len(ascii) result.append(ascii[index]) return ''.join(result) def caesar_cipher_by_sakai(text: str, shift: int) -> str: result = '' for char in text: if char.islower(): alphabet = string.ascii_lowercase elif char.isupper(): alphabet = string.ascii_uppercase else: result += char continue index = (alphabet.index(char) + shift) % len(alphabet) result += alphabet[index] return result def caesar_cipher_no_use_string(text: str, shift: int) -> str: result = '' len_alphabet = ord('Z') - ord('A') + 1 for char in text: if char.isupper(): result += chr(((ord(char) - ord('A') + shift) % len_alphabet) + ord('A')) elif char.islower(): result += chr(((ord(char) - ord('a') + shift) % len_alphabet) + ord('a')) else: result += char return result def caesar_cipher_hach(text: str) -> Generator[str, None, None]: len_alphabet = ord('Z') - ord('A') + 1 for shift in range(1, len_alphabet + 1): result = '' for char in text: if char.isupper(): result += chr((ord(char) - ord('A') - shift) % len_alphabet + ord('A')) elif char.islower(): result += chr((ord(char) - ord('a') - shift) % len_alphabet + ord('a')) else: result += char yield result if __name__ == '__main__': text = "ATTACK SILICON VALLY by engineer" t = caesar_cipher(text, 3) print(t) # t = caesar_cipher(t, -3) # print(t) # t = caesar_cipher_by_sakai(text, 3) # print(t) # t = caesar_cipher_by_sakai(t, -3) # print(t) for h in caesar_cipher_hach(t): print(h)
from typing import List def order_even_first_odd_last(numbers: List[int]) -> None: len_numbers = len(numbers) for i in range(len_numbers): if numbers[i] % 2: for j in range(i+1, len_numbers): if numbers[j] % 2 == 0: numbers[i], numbers[j] = numbers[j], numbers[i] break def order_even_first_odd_last_v2(numbers: List[int]) -> None: len_numbers = len(numbers) insert_index = len_numbers i = len_numbers - 1 while 0 <= i: if numbers[i] % 2: numbers.insert(insert_index, numbers[i]) numbers.pop(i) insert_index -= 1 i -= 1 def order_even_first_odd_last_by_sakai(numbers: List[int]) -> None: i, j = 0, len(numbers)-1 while i < j: if numbers[i] % 2: numbers[i], numbers[j] = numbers[j], numbers[i] j -= 1 else: i += 1 if __name__ == '__main__': numbers = [0, 1, 3, 4, 2, 4, 5, 1, 6, 9, 8] order_even_first_odd_last_by_sakai(numbers) print(numbers)
from typing import List, Generator import time def print_duration(func): def _wrapper(number: int) -> List[int]: start = time.time() result = func(number) print(f'duration={time.time() - start}') return result return _wrapper @print_duration def generate_primes_v1(number: int) -> List[int]: if number == 1: return [] if number == 2: return [2] primes = [2] for i in range(3, number+1, 2): for prime in primes: if i % prime == 0: break else: primes.append(i) return primes def generate_primes_v2(number: int) -> Generator[int, None, None]: if number == 1: return [] if number == 2: return [2] primes = [2] for i in range(3, number+1, 2): for prime in primes: if i % prime == 0: break else: yield i @print_duration def generate_primes_by_sakai_v1(number: int) -> List[int]: primes = [] for x in range(2, number+1): for y in range(2, x): if x % y == 0: break else: primes.append(x) return primes @print_duration def generate_primes_by_sakai_v2(number: int) -> List[int]: primes = [] cache = {} for x in range(2, number+1): is_prime = cache.get(x) if is_prime is False: continue primes.append(x) for y in range(x*2, number+1, x): cache[y] = False return primes def generate_primes_by_sakai_v3(number: int) -> Generator[int, None, None]: cache = {} for x in range(2, number+1): is_prime = cache.get(x) if is_prime is False: continue yield x for y in range(x*2, number+1, x): cache[y] = False if __name__ == '__main__': print(generate_primes_v1(1000)) print(generate_primes_by_sakai_v1(1000)) print(generate_primes_by_sakai_v2(1000)) start = time.time() for i in generate_primes_by_sakai_v3(10000): pass print(f'duration={time.time() - start}') start = time.time() for i in generate_primes_v2(10000): pass print(f'duration={time.time() - start}')
import unittest class RomanNUMERALConverter(object): def __init__(self, roman_numeral): self.roman_numeral = roman_numeral self.digit_map = { "M":1000, "D":500,"C":100,\ "L":50, "X":10, "V":5, "I":1 } def convert_to_decimal(self): val = 0 for char in self.roman_numeral: val += self.digit_map[char] return val class RomanNumeralConverterTest(unittest.TestCase): def test_parsing_millenia(self): value = RomanNUMERALConverter("M") self.assertEqual(1000, value.convert_to_decimal()) def test_parsing_century(self): value = RomanNUMERALConverter("C") self.assertEqual(100, value.convert_to_decimal()) def test_parsing_half_century(self): value = RomanNUMERALConverter("L") self.assertEqual(50, value.convert_to_decimal()) def test_parsin_decade(self): value = RomanNUMERALConverter("X") self.assertEqual(10,value.convert_to_decimal()) def test_parsing_half_decade(self): value= RomanNUMERALConverter("V") self.assertEqual(5, value.convert_to_decimal()) def test_parsin_one(self): value = RomanNUMERALConverter("I") self.assertEqual(1, value.convert_to_decimal()) def test_no_roman_numeral(self): value = RomanNUMERALConverter(None) self.assertRaises(TypeError, value.convert_to_decimal) if __name__=="__main__": unittest.main()
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print("Please enter only lowercase") entry=input("\nEnter a fruite name: ") if "apple" in thislist: print("The fruit apple is in our database") elif "banana" in thislist: print("The fruit banana is in our database") elif "cherry" in thislist: print("The fruit cherry is in our database") elif "orange" in thislist: print("The fruit orange is in our database") elif "kiwi" in thislist: print("The fruit kiwi is in our database") elif "melon" in thislist: print("The fruit melon is in our database") elif "mango" in thislist: print("The fruit mango is in our database") else: print("The fruit is not in our database")
a = input("please enter your name: ") b =int(input("enter a number: ")) print("You have entered %s and the number you enter %d !"% (a, b)) num1=float(input("\n\nplease enter a number: ")) op=input("ensure the operation on the number: ") num2=float(input("plese enter second number: ")) if op=="+": su=num1+num2 print("\n\nThe sum is", su) else : print("We are updating our app ") print("\n it will be come soon") print("\n\n\nyou were entered %d and %d" % (num1, num2))
#!/usr/bin/env python # -*- coding: utf-8 -*- # binary search. class BinarySearch(): def __init__(self): pass def bsearch(self, list, value): if list is None or len(list) == 0: return - 1; cs = 0 ce = len(list) - 1 if list[cs] == value: return cs if list[ce] == value: return ce while ce != cs: cm = (ce - cs + 1) / 2 # print 's:%s,m:%s,e:%s.' % (cs, cm, ce) if list[cm] == value: return cm elif list[cm] > value: ce = cm else: cs = cm if __name__ == '__main__': # search 3 l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] l2 = [2, 2.5, 3, 200, 9234] l3 = [3] l4 = [3, 5] l5 = [1, 3] bs = BinarySearch() print bs.bsearch(l1, 3); print bs.bsearch(l2, 3); print bs.bsearch(l3, 3); print bs.bsearch(l4, 3); print bs.bsearch(l5, 3);
# In[1]: import numpy as np import pandas as pd from sklearn.decomposition import NMF # 100 (features) x 200 (examples) = 100 x 5 by 5 x 200 n_features= 100 n_examples = 200 r = 5 # Low-rank basis (orthogonal columns) basis_w = np.dot(np.random.rand(n_features, r), np.random.rand(r, r)) # Random coefficients coefs_h = np.random.rand(r, n_examples) # Note here V has rows as features and columns as examples, # This is consitent as Lecture notations, so we use the same W and H interpretations as in the lecture slides. V = np.dot(basis_w, coefs_h) model = NMF(n_components=r, init='random', random_state=0) # Calling fit_transform will calculate the NMF decomposition and return the basis $\mathbf W$. # In[2]: W = model.fit_transform(V) print(W.shape) # To obtain the coefficients $\mathbf H$ # In[3]: H = model.components_ print(H.shape) # Let's check how accurately we can reconstruct the original data. # # Increasing number of components will increase accuracy of reconstruction. # In[4]: reco = np.dot(W, H) diff = V - reco print(np.linalg.norm(diff) / np.linalg.norm(V)) # Then we can compare the true basis matrix and estimated basis matrix. Note that they are very different! # In[5]: pd.DataFrame(basis_w).head() # Estimated basis matrix # In[6]: pd.DataFrame(W).head() # ## Market Movement Analysis # # One of the powerful applications of NNMF is clustering via the underlying generative process. # # This is in contrast to traditional clustering methods such as k-means. These traditional clustering methods rely on vector distance metrics. This usually leads to clustering of stocks that are of a similar price. # # However what we are usually more interested in is "which stocks move together?". # # By performing NNMF we can produce a set of basis vectors and coefficients. The basis vectors can be roughly interpreted as unknown factors that affect the stock price. The coefficients of each stock are then treated as a similarity. In other words if stocks have similar coefficient patterns then they will likely move together. # # So the process is to perform NNMF and then cluster stocks based on their coefficients. # # In this example we look at the 30 component stocks of the Dow Jones Industrial Average over 25 weeks. # In[9]: from sklearn.cluster import KMeans np.random.seed(0) dow_jones = pd.read_csv("dow_jones_index.data") V = dow_jones.pivot(index = "stock", columns = "date", values = "close") V = V.replace('[\$,]', '', regex=True).astype(float) # V transpose has columns as stocks (examples) and rows as dates (features) V= V.T V.head() # In[10]: import matplotlib.pyplot as plt # Plot individual stock prices fig1 = plt.figure() plt.plot(V.values) fig1 # In[17]: model = NMF(n_components=5, init='random', random_state=0, max_iter=10000) # In[18]: W = model.fit_transform(V) print(W.shape) # In[19]: H = model.components_ print(H.shape) # Group stocks by their cluster assignment for interpretation.Or cluster stocks based on their coefficients. # In[20]: # kmeans treats row as training example, so transpose H kmeans = KMeans(n_clusters=7, random_state=0).fit(H.T) # generate clustering labels for each training example labels = kmeans.labels_ groups = [list() for i in range(7)] for i in range(len(labels)): g = labels[i] groups[g].append(V.columns[i]) for i in range(len(groups)): print("Stock group {0}: ".format(i) + str(groups[i])) # ## Topic Modelling/Extraction # # Given a collection of documents we can use NMF to automatically find words (features) which are most relevant to each topic (basis vector). # # The number of topics is controlled by the number of basis vectors. # # In this example we will use the twenty newsgroup dataset to find 10 topics and the most important words in those topics. # In[21]: from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.datasets import fetch_20newsgroups n_samples = 2000 n_features = 1000 n_components = 10 dataset = fetch_20newsgroups(shuffle=True, random_state=1, remove=('headers', 'footers', 'quotes')) data_samples = dataset.data[:n_samples] # Build a tfidf representation that removes stop words and filters out words that occur in 95% of documents # In[22]: tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, max_features=n_features, stop_words='english') tfidf = tfidf_vectorizer.fit_transform(data_samples) # Transpose the data so that we have rows as features (1000) and columns as samples (2000) tfidf= tfidf.T print(tfidf.shape) # Each column of $\mathbf W$ represents one topic: 10 topics in total # In[24]: nmf = NMF(n_components=n_components, init='random', random_state=0, max_iter=10000) W = nmf.fit_transform(tfidf) W.shape # Display the top 15 words in each topic (10 topics in total) # In[25]: def print_top_words(model, feature_names, n_top_words): for topic_idx, topic in enumerate(W.T): message = "Topic #%d: " % topic_idx message += " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) print(message) n_top_words = 15 tfidf_feature_names = tfidf_vectorizer.get_feature_names() print_top_words(nmf, tfidf_feature_names, n_top_words) # ## Face Feature Extraction. # # This example is from the lecture. We can extract image features for applications such as compression and feature engineering. # In[26]: from sklearn.datasets import fetch_lfw_people lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) # Images in the LFW dataset are 50*37 pixels in size. # Therefore 1850 features in total. # n_samples is the number of images n_samples, a, b = lfw_people.images.shape V = lfw_people.data # Transpose the data so that we have rows as features (1850) and columns as samples (1288) V= V.T # Display an example face (1st face of the input). Note here each column represents one face image. # In[27]: fig = plt.figure() plt.imshow(V[:,1].reshape((a, b)), cmap=plt.cm.gray) fig # Let's do a NNMF decomposition with 50 basis vectors # In[28]: model = NMF(n_components=50, init='random', random_state=0) W = model.fit_transform(V) H = model.components_ # Visualise the basis vectors # In[29]: fig, axarr = plt.subplots(5, 10, figsize=(8, 6)) axarr_list = np.ravel(axarr) for i in range(50): # each coolumn of W represent one basis vector axarr_list[i].imshow(W[:,i].reshape((a, b)), cmap=plt.cm.gray) axarr_list[i].axis('off') fig # Check the approximation $\mathbf W$$\mathbf H$ (1st face of the approximation) # In[30]: V_Approx= np.dot(W, H) fig = plt.figure() plt.imshow(V_Approx[:, 1].reshape((a, b)), cmap=plt.cm.gray) fig # ## Singular Value Decomposition # # SVD is a central part of these algorithms and is often the bottleneck. Below we illustrate the various types of SVD and their pros/cons. # # There are four options: # - Full SVD # - Partial SVD (optional) # - Sparse SVD (optional) # - Approximate SVD (optional) # In[2]: import scipy.sparse.linalg as sparse import scipy as sp import numpy as np import time n = 1000 m = 900 r = 5 A = np.dot(np.random.randn(n, r), np.random.randn(r, m)) print(A.shape) print(np.linalg.matrix_rank(A)) # ### Full SVD # # Full SVD decomposition generates full size matrices for U, S and V. # # Full SVD, has approximately $O(n^3)$ time complexity and does not scale well to large matrices or matrices with large rank. # In[20]: tic = time.time() U, s, V = sp.linalg.svd(A, full_matrices=True) toc = time.time() print("U: " + str(U.shape)) print("s: " + str(s.shape)) print("V: " + str(V.shape)) S = np.zeros((1000, 900)) S[:900, :900] = np.diag(s) print("Running time: {0}s. Error: {1}".format(toc - tic, np.linalg.norm(U.dot(S).dot(V) - A))) # Impact of full_matrices parameter. When full_matrices=False, this is also called reduced SVD. Note the difference for the sizes of matrix $\mathbf U$ between full_matrices=True and full_matrices=False. # In[21]: tic = time.time() U, S, V = sp.linalg.svd(A, full_matrices=False) toc = time.time() print("U: " + str(U.shape)) print("S: " + str(S.shape)) print("V: " + str(V.shape)) print("Running time: {0}s. Error: {1}".format(toc - tic, np.linalg.norm(U.dot(np.diag(S)).dot(V) - A))) # ### Partial and Sparse SVD # # A partial SVD is performing an SVD on only the top $k$ singular values. Partial SVD is also known as truncated SVD or skinny SVD. # # A sparse SVD is performing an SVD on a sparse matrix. # # In scipy, the partial and sparse SVD function is shared. This function implements a different SVD solver that takes advantage of computing the SVD of a sparse input matrix OR computing a reduced number of singular values. # # Notice that computing a partial SVD is significantly quicker and the error is still relatively small. # In[24]: tic = time.time() U, S, V = sparse.svds(A, k=r) toc = time.time() print("U: " + str(U.shape)) print("S: " + str(S.shape)) print("V: " + str(V.shape)) print("Running time: {0}s. Error: {1}".format(toc - tic, np.linalg.norm(U.dot(np.diag(S)).dot(V) - A))) # ### Approximate SVD # # Approximate SVD is a technique that uses randomisation to quickly compute an approximate SVD result. # # More details are available here: # - https://arxiv.org/pdf/0909.4061.pdf # - https://amath.colorado.edu/faculty/martinss/Talks/2015_02_chicago.pdf # # Suffice to say that the approximate SVD scales nicely to huge matrices and results in a suprisingly accurate result. For massive scale machine learning it is the only solution. # In[23]: def random_svd(A, k): omega = np.random.randn( A.shape[1], r ) Y = np.dot(A, omega) Q = sp.linalg.orth(Y) B = np.dot(np.transpose(Q), A) Uhat, S, V = sp.linalg.svd(B, full_matrices=False) U = np.dot(Q, Uhat) return U, S, V tic = time.time() [U, S, V] = random_svd(A, k=5) toc = time.time() print("U: " + str(U.shape)) print("S: " + str(S.shape)) print("V: " + str(V.shape)) print("Running time: {0}s. Error: {1}".format(toc - tic, np.linalg.norm(U.dot(np.diag(S)).dot(V) - A)))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 17 17:17:16 2018 @author: Junbin Gao All Copyright """ from sklearn.feature_extraction.text import TfidfTransformer # Initiate the transformer transformer = TfidfTransformer(smooth_idf=False) # Check what it is transformer # Corpus with three different terms and their counts in a corpus of 6 documents counts = [[3, 0, 1], [2, 0, 0], [3, 0, 0], [4, 0, 0], [3, 2, 0], [3, 0, 2]] # Transform the corpus tfidf = transformer.fit_transform(counts) # This is the transformed feature matrix for 6 documents # This matrix can be pipelined into a machine learning algorithm # Each row is normalized to have unit Euclidean norm: X = tfidf.toarray() # If we are only given the entire corpus, rather than the counts, then we can # do the following way corpus = [ 'This is the first document.', 'This is the second second document.', 'And the third one.', 'Is this the first document?', ] from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer() X_tfidf = vectorizer.fit_transform(corpus) # You can check all the terms vectorizer.vocabulary_ # Check the extracted features X = X_tfidf.toarray() # Please explain the meaning of X[0] # A more complicated example import pandas as pd # This dataset from airbnb consists of texts hosters describe their hotels/rooms # As there are possible non-English words, we use ISO-8859-1 encoding to read csv descr = pd.read_csv('Room_Description.csv', encoding = "ISO-8859-1", engine='python') """ You cann set the number of features you wish to extract. For larger corpus, this number can be large, e.g., 3000 """ n_features = 1000 """ Let us define the tf-idf vecotorizer first. Here we set max_df = 0.99 means ignoring terms that appear in more than 99% of the documents. min_df = 3 means ignoring terms that appear in less than 2 documents. stop_words = 'english' means we will use a built-in list of words to be removed such as "a", "the" etc. """ tfidf_vectorizer = TfidfVectorizer(max_df = 0.99, min_df=3, max_features=n_features, stop_words='english') tfidf_vectorizer.fit(descr['description']) X_tfidf = tfidf_vectorizer.transform(descr['description']) X = pd.DataFrame(X_tfidf.toarray())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 29 18:04:50 2017 @author: steve """ word = "chair" n_unique_chars = len(set(word)) guess_state = ["_", "_", "_", "_", "_"] guessed_letters = set() guessed_correct = set() n_guesses = 10 running = True while running: uinput = input("Guess a letter: ") if uinput not in guessed_letters: guessed_letters.add(uinput) locs = [pos for pos, char in enumerate(word) if char == uinput] if len(locs) > 0: guessed_correct.add(uinput) for l in locs: guess_state[l] = uinput else: n_guesses = n_guesses - 1 if len(guessed_correct) < n_unique_chars: if (n_guesses <= 0): running = False print("No more guesses left") else: print("{0} guesses left".format(n_guesses)) print("Guessed letters: {0}".format(guessed_letters)) print(guess_state) else: running = False print("You win!") print(guess_state) else: print("You have already guessed {0}. Ignoring.".format(uinput)) print("Guessed letters: {0}".format(guessed_letters)) print("{0} guesses left".format(n_guesses)) print(guess_state)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 1 21:28:55 2018 @author: steve """ import pandas as pd # Read a CSV file, this returns a DataFrame object # A DataFrame is similar to a spreadsheet/table happiness_df = pd.read_csv('happiness_2016.csv') # A single column of a DataFrame is a Series country_series = happiness_df['Country'] # You can index into Dataframes and Series lots of ways # Multiple columns sub_dataframe = happiness_df[ ['Country', 'Region'] ] # By column number region_series = happiness_df.iloc[:, 1] # By row number row_10 = happiness_df.iloc[9, :] # Single Cell happy_score_sweden = happiness_df.iloc[9, 3] # We can query a dataframe very easily # Find all countries (rows) with a happiness score > 7.4 top_scorers = happiness_df[ happiness_df['Happiness Score'] > 7.4 ] # Find all countries in SEA with Freedom > .5 free_sea = happiness_df[ (happiness_df['Region'] == 'Southeastern Asia') & (happiness_df['Freedom'] > 0.5 ) ] # Check if there are any missing or corrupt values print("Contains missing values") if happiness_df.isnull().values.any() else print("No missing values") # Delete rows containing NaN values happiness_df.dropna(inplace=True) # Or you can replace them with a placeholder value happiness_df.fillna(value="PLACEHOLDER", inplace=True)
# -*- coding: utf-8 -*- """ Created on Fri May 11 11:23:43 2018 @author: Professor Junbin Gao Adopted from the program at http://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ """ import time import math import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential # We want to be able to repeat the experiment so we fix to a random seed np.random.seed(70) # Let us loading data data = pd.read_csv('international-airline-passengers.csv', usecols=[1]) data = data.dropna() # Drop all Nans data = data.values # Convert from DataFrame to Python Array # You need to make sure the data is type of float # you may use data = data.astype('float32') if your data are integers # Prepare data ..... """ Scaling ... Neural networks normally work well with scaled data, especially when we use the sigmoid or tanh activation function. It is a good practice to scale the data to the range of 0-to-1. This can be easily done by using scikit-learn's MinMaxScaler """ scaler = MinMaxScaler(feature_range=(0, 1)) data = scaler.fit_transform(data) """ Splitting ... We are going to use a time window of k = 3, so we will split the time series as x_1, x_2, x_3, x_4 [prediction] x_2, x_3, x_4, x_5 x_3, x_4, x_5, x_6 .... """ train_size = int(len(data)*0.67) # Use the first 2/3 data for training test_size = len(data) - train_size # the remaining for testing Dtrain, Dtest = data[0:train_size,:], data[train_size:len(data),:] # Both Xtrain and Xtest are in time series form, we need split them into sections # in time-window size 4 time_window = 15 Xtrain, Ytrain = [], [] for i in range(len(Dtrain) - time_window -1): Xtrain.append(Dtrain[i:(i+time_window), 0]) # pick up the section in time_window size Ytrain.append(Dtrain[i+time_window, 0]) # pick up the next one as the prediction Xtrain = np.array(Xtrain) # Convert them from list to array Ytrain = np.array(Ytrain) Xtest, Ytest = [], [] for i in range(len(Dtest) - time_window -1): Xtest.append(Dtest[i:(i+time_window), 0]) # pick up the section in time_window size Ytest.append(Dtest[i+time_window, 0]) # pick up the next one as the prediction Xtest = np.array(Xtest) # Convert them from list to array Ytest = np.array(Ytest) # We are going to use keras package, so we must reshape our data to the keras required format # (samples, time_window, features) we are almost there, but need to reshape into 3D array # For time series, the feature number is 1 (one scalar value at each time step) Xtrain = np.reshape(Xtrain, (Xtrain.shape[0], time_window, 1)) Xtest = np.reshape(Xtest, (Xtest.shape[0], time_window, 1)) # Define our model ..... model = Sequential() # Add a LSTM with output_dim (number of hidden neurons) = 100 # input_dim = 1 (for time series) #model.add(LSTM( # return_sequences=False, input_dim=1, # units = 100 #output_dim=100, # )) # Many-to-One model MyBatchSize = 1 model.add(LSTM(100, input_shape = (time_window,1), batch_size=MyBatchSize, return_sequences=False)) # Many-to-One model # It seems without using batch_size = 1 here causes some problems, a bug? model.add(Dropout(0.2)) # Impose sparsity as we have so many hidden neurons # As we will have 100 outputs from LSTM at each time step, we will use a linear # layer to map them to a single "prediction" output model.add(Dense( output_dim=1)) model.add(Activation("linear")) # Compiling model for use start = time.time() model.compile(loss="mse", optimizer="rmsprop") print("Compilation Time : ", time.time() - start) # Training model.fit( Xtrain, Ytrain, batch_size=MyBatchSize, nb_epoch=50, # You increase this number validation_split=0.05) # Predicting # make predictions trainPredict = model.predict(Xtrain,batch_size=MyBatchSize) testPredict = model.predict(Xtest,batch_size=MyBatchSize) # invert predictions due to scaling trainPredict = scaler.inverse_transform(trainPredict) Ytrain = scaler.inverse_transform(Ytrain[:,np.newaxis]) testPredict = scaler.inverse_transform(testPredict) Ytest = scaler.inverse_transform(Ytest[:,np.newaxis]) # calculate root mean squared error trainScore = math.sqrt(mean_squared_error(Ytrain, trainPredict[:,0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(Ytest, testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore)) # Plotting results # shift train predictions for plotting trainPredictPlot = np.empty_like(data) trainPredictPlot[:, :] = np.nan trainPredictPlot[time_window:len(trainPredict)+time_window, :] = trainPredict # shift test predictions for plotting testPredictPlot = np.empty_like(data) testPredictPlot[:, :] = np.nan testPredictPlot[len(trainPredict)+(time_window*2)+1:len(data)-1, :] = testPredict # plot baseline and predictions plt.plot(scaler.inverse_transform(data), label='True Data') plt.plot(trainPredictPlot, label='Train Prediction') plt.plot(testPredictPlot, label='Test Prediction') plt.legend() plt.show() # Overall Prediction with the train model Xall = [] for i in range(len(data) - time_window): Xall.append(data[i:(i+time_window), 0]) # pick up the section in time_window size Xall = np.array(Xall) # Convert them from list to array Xall = np.reshape(Xall, (Xall.shape[0], time_window, 1)) allPredict = model.predict(Xall,batch_size=MyBatchSize) allPredict = scaler.inverse_transform(allPredict) allPredictPlot = np.empty_like(data) allPredictPlot[:, :] = np.nan allPredictPlot[time_window:, :] = allPredict plt.figure() plt.plot(scaler.inverse_transform(data), label='True Data') plt.plot(allPredictPlot, label='One-Step Prediction') plt.legend() plt.show()