text
stringlengths
37
1.41M
if __name__ == '__main__': x = eval(input("x = ")) if x >= 20: print(0) elif x >= 10: print(0.5 * x - 2) elif x >= 5: print(3 * x - 5) elif x >= 0: print(x) else: print(0)
class Node: left = right = None def __init__(self, data=None): self.data = data def insert(self, data): '''Insert new data to this BST''' if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data >= self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data def in_order_traversal(node): '''Visit the nodes using in order traversal''' if node: yield from in_order_traversal(node.left) yield node.data yield from in_order_traversal(node.right) # CASE 1 # Constructing BST A bst_1a = Node() for i in [10, 5, 20, 15, 30]: bst_1a.insert(i) # Constructing BST B bst_1b = Node() for i in [10, 20, 15, 30, 5]: bst_1b.insert(i) # InOrder Traversing of CASE 1 BSTs bst_1a_iot = list(in_order_traversal(bst_1a)) bst_1b_iot = list(in_order_traversal(bst_1b)) # Comparing CASE 1 BSTs to check if they are same print(bst_1a_iot, '==', bst_1b_iot, '\t--->', bst_1a_iot == bst_1b_iot) # [5, 10, 15, 20, 30] == [5, 10, 15, 20, 30] ---> True # CASE 2 # Constructing BST A bst_2a = Node() for i in [10, 5, 20, 15, 30]: bst_2a.insert(i) # Constructing BST B bst_2b = Node() for i in [10, 5, 30, 20, 5]: bst_2b.insert(i) # InOrder Traversing of CASE 2 BSTs bst_2a_iot = list(in_order_traversal(bst_2a)) bst_2b_iot = list(in_order_traversal(bst_2b)) # Comparing CASE 2 BSTs to check if they are same print(bst_2a_iot, '==', bst_2b_iot, '\t--->', bst_2a_iot == bst_2b_iot) # [5, 10, 15, 20, 30] == [5, 5, 10, 20, 30] ---> False
#!/usr/bin/env python # coding: utf-8 # In[1]: print('ใ“ใ‚ŒใŒGitHubใฎไบŒ็•ชใ‚ใฎใƒ•ใ‚กใ‚คใƒซ') # In[2]: n = int(input('n = ')) # In[3]: for i in range(n):print(i) # In[ ]:
#!/usr/bin/env python3 import sys class Marble: def __init__(self, value): self.value = value self.cw = None self.ccw = None def place(self, other): '''Inserts a new marble in the circle according to the stupid elven rules. Returns the new current marble. ''' before = self.cw after = self.cw.cw # print("before {}, after {}".format(before.value, after.value)) other.ccw = before other.cw = after before.cw = other after.ccw = other return other def remove(self): '''Remove the marble 7 marbles ccw from this. Returns tuple of (new current marble, value of removed) ''' removed = self for _ in range(7): removed = removed.ccw before = removed.ccw after = removed.cw before.cw = after after.ccw = before return (after, removed.value) def main(): try: num_players = int(sys.argv[1]) num_marbles = int(sys.argv[2]) except (IndexError, ValueError): print("Usage: {} NUM_PLAYERS NUM_MARBLES".format(sys.argv[0]), file=sys.stderr) return scores = [0] * num_players m = Marble(0) m.cw = m m.ccw = m player = 0 for value in range(1, num_marbles + 1): if value % 23 != 0: m = m.place(Marble(value)) else: (m, removed) = m.remove() scores[player] += value + removed player = (player + 1) % num_players print("High score: {}".format(max(scores))) if __name__ == '__main__': main()
#!/usr/bin/env python3 import sys import itertools def main(): fname = sys.argv[1] with open(fname) as f: numbers = (int(line.rstrip()) for line in f if line != '\n') freq = 0 encountered = set() for num in itertools.cycle(numbers): freq += num if freq in encountered: print(freq) break encountered.add(freq) if __name__ == '__main__': main()
#import turtle fib_x=1 fib_next=1 n=input() n=int(n) if n<=2: fib_n=1 else: print(fib_x) print(fib_next) #turtle.circle(fib_x,180) #turtle.circle(fib_x,180) i=3 count=0 while i<=n: i+=1 count+=1 fib_temp=fib_x+fib_next fib_x=fib_next fib_next=fib_temp #turtle.circle(fib_next,180) print(fib_next) fib_n=fib_next print('Total count:', count) #print(fib_n)
str=input("please enter any sentence: ") for i in str: print(i)
def number_sum(numbers): result=0 for number in numbers: result+=number average=result/len(numbers) return average avg=number_sum([1,2,30,4,5,9]) print(avg)
print('Enter the name of cat 1:') catName1=input() print('Enter the name of cat 2:') catName2=input() print('Enter the name of cat 3:') catName3=input() print('Enter the name of cat 4:') catName4=input() print('Enter the name of cat 5:') catName5=input() print('Enter the name of cat 5:') catName6=input() print('The cat name are:') print(catName1+''+catName2+''+catName3+''+catName4+''+catName5+''+catName6)
import pygame import os import random import math # ๋ฒ„๋ธ” ํด๋ž˜์Šค ์ƒ์„ฑ class Bubble(pygame.sprite.Sprite): def __init__(self, image , color, position=(0,0) ,row_idx=-1, col_idx=-1): super().__init__() self.image = image self.color = color self.rect = image.get_rect(center=position) self.radius = 9 self.row_idx = row_idx self.col_idx = col_idx #๋ฒ„๋ธ”์˜ ์œ„์น˜ ์„ธํŒ…ํ•ด์ฃผ๋Š” setter def set_rect(self, position): self.rect = self.image.get_rect(center=position) #๋ฒ„๋ธ”์„ ๊ทธ๋ฆฐ๋‹ค def draw(self, screen, to_x=None): if to_x: screen.blit(self.image, (self.rect.x + to_x, self.rect.y)) #to_x๋งŒํผ ๋” ํ•ด์ค˜์„œ ํ”๋“ค๋ฆฌ๋Š” ๊ฒƒ ์ฒ˜๋Ÿผ ๋ณด์ด๊ฒŒ else: screen.blit(self.image, self.rect) #๊ฐ๋„๋ฅผ setํ•œ๋‹ค. input:๊ฐ๋„, output:๋ผ๋””์•ˆ def set_angle(self, angle): self.angle = angle self.rad_angle = math.radians(self.angle) #๊ฐ๋„๋ฅผ ๋ผ๋””์•ˆ์ˆ˜์น˜๋กœ ๋ณ€๊ฒฝ #๋ฒ„๋ธ”์„ ์ด๋™์‹œํ‚จ๋‹ค def move(self): to_x = self.radius * math.cos(self.rad_angle) to_y = self.radius * math.sin(self.rad_angle) * -1 #๋ฒ„๋ธ”์˜ ์ด๋™ ์ฒ˜๋ฆฌ self.rect.x += to_x self.rect.y += to_y #๋ฒฝ์— ์ถฉ๋Œ ์ฒ˜๋ฆฌ (์ขŒ์ธก์„ ๋ฒ—์–ด๋‚˜๊ฑฐ๋‚˜ or ์šฐ์ธก์„ ๋ฒ—์–ด๋‚œ๊ฒฝ์šฐ) if self.rect.left <0 or self.rect.right > screen_width: self.set_angle(180 - self.angle) #๋ฒฝ์— ๋ถ€๋”ชํžˆ๋ฉด ํŠ•๊ธฐ๊ฒŒ #๋ฒ„๋ธ”์˜ xํ–‰๊ณผ yํ–‰ ๊ฐ’์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค def set_map_index(self, row_idx, col_idx): self.row_idx = row_idx self.col_idx = col_idx #๋ฒ„๋ธ”์„ height๋งŒํผ ์•„๋ž˜๋กœ ๋–จ์–ด๋œจ๋ฆฐ๋‹ค def drop_downward(self, height): self.rect = self.image.get_rect(center=(self.rect.centerx, self.rect.centery + height)) # ๋ฐœ์‚ฌ๋Œ€ ํด๋ž˜์Šค ์ƒ์„ฑ class LaunchPad(pygame.sprite.Sprite): def __init__(self, image, position,angle): super().__init__() self.image = image #์›€์ง์—ฌ์ง„ ๊ฐ๋„์˜ ์ด๋ฏธ์ง€ self.position = position self.rect = image.get_rect(center=position) self.angle = angle self.original_image = image #0๋„์˜ ์ด๋ฏธ์ง€ #draw ํ•จ์ˆ˜ ์ •์˜ #sprite.Group()์€ drawํ•จ์ˆ˜๊ฐ€ ์žˆ์œผ๋‚˜, sprite๋Š” draw ํ•จ์ˆ˜๊ฐ€ ์—†์œผ๋ฏ€๋กœ ์—ฌ๊ธฐ์„œ ์ •์˜ํ•œ๋‹ค def draw(self, screen): screen.blit(self.image,self.rect) #screen์— image๋ฅผ rect์— ๋งž์ถ”์„œ ํ‘œ์‹œํ•ด์ค€๋‹ค. # ํšŒ์ „ def rotate(self, angle): self.angle += angle if self.angle > 170: self.angle =170 elif self.angle <10: self.angle = 10 #์›๋ณธ์ด๋ฏธ์ง€์˜ ๊ฐ๋„ ๋ณ€ํ™” ์‹œ์ผœ์„œ ์—…๋ฐ์ดํŠธ ์‹œํ‚ค๋„๋ก ํ•˜์ž #self.original_image๋ฅผ self.angle ๊ฐ๋„ ๋งŒํผ ๋ณ€ํ™”์‹œ์ผœ์„œ self.image์— ์ค€๋‹ค. #1์€ ๋ช‡๋ฐฐ๋กœ ํ™•๋Œ€ํ•˜๋А๋ƒ๋ฅผ ์˜๋ฏธํ•˜๋Š” ๋ณ€์ˆ˜ self.image = pygame.transform.rotozoom(self.original_image,self.angle,1) #rect๋Š” ๊ฒŒ์ž„ ์‹œ์ž‘์‹œ position์„ ๊ธฐ์ค€์œผ๋กœ ๋”ํ•ด์ง„ ๊ฐ๋„๋กœ self.rect = self.image.get_rect(center=self.position) #๊ฒŒ์ž„๋งต๊ธฐ def setup(): global map # lv1 map = [ list("RRYYBBGG"), list("RRYYBBG/"), # '/' ๋กœ ํ‘œํ˜„ํ•œ ๊ฒƒ์€ ๋ฒ„๋ธ”์ด ์œ„์น˜ํ•  ์ˆ˜ ์—†๋Š” ๊ณณ์ž„์„ ์˜๋ฏธ list("BBGGRRYY"), list("BGGRRYY/"), list("........"), # '.' ๋กœ ํ‘œํ˜„ํ•œ ๊ฒƒ์€ ๋น„์–ด์žˆ๋Š” ๊ณต๊ฐ„์ž„์„ ์˜๋ฏธ list("......./"), list("........"), list("......./"), list("........"), list("......./"), list("........") ] # # lv2 # map = [ # list("...YY..."), # list("...G.../"), # list("...R...."), # list("...B.../"), # list("...R...."), # list("...G.../"), # list("...P...."), # list("...P.../"), # list("........"), # list("......./"), # list("........") # ] # # lv3 # map = [ # list("G......G"), # list("RGBYRGB/"), # list("Y......Y"), # list("BYRGBYR/"), # list("...R...."), # list("...G.../"), # list("...R...."), # list("......./"), # list("........"), # list("......./"), # list("........") # ] for row_idx, row in enumerate(map): for col_idx, col in enumerate(row): if col in [".","/"]: continue pos = get_bubble_position(row_idx,col_idx) # ๋ฒ„๋ธ” ํ‘œ์‹œํ•  ์ขŒํ‘œ ์ฐพ๊ธฐ image = get_bubble_image(col) # ๋ฒ„๋ธ”์˜ ์ด๋ฏธ์ง€ ์ฐพ๊ธฐ bubble_group.add(Bubble(image,col,pos,row_idx,col_idx)) # ๋ฒ„๋ธ”๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์„œ ์ •๋ณด๋ฅผ ๋‹ด์•„์„œ bubble_group์— ์‚ฝ์ž… #๋ฒ„๋ธ”์„ ํ‘œ์‹œํ•ด์•ผ ํ•  ์ขŒํ‘œ๋ฅผ ์ฐพ๋Š”๋‹ค def get_bubble_position(row_idx, col_idx): pos_x= col_idx * CELL_SIZE + (BUBBLE_WIDTH //2) # ->ํŒŒ์ด์ฌ์—์„œ /์“ฐ๋ฉด ์‹ค์ˆ˜๋กœ ๋‚˜์˜ค๋‹ˆ ๋‚˜๋จธ์ง€ ๋ฒ„๋ฆฌ๊ณ  ์ •์ˆ˜๋งŒ ์–ป๊ณ  ์‹ถ์„๋•Œ ์‚ฌ์šฉ pos_y= row_idx * CELL_SIZE + (BUBBLE_HEIGHT //2) + WALL_HEIGHT if row_idx %2==1 : pos_x += CELL_SIZE //2 #ํ™€์ˆ˜ ํ–‰์ผ๋•Œ๋Š” ๋ฒ„๋ธ”์˜ ๋ฐ˜์นธ ๋งŒํผ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๋ฐ€๋ ค์žˆ์–ด์•ผ ํ•˜๋ฏ€๋กœ return pos_x, pos_y #๋ฒ„๋ธ”์„ ํ‘œ์‹œํ•  ์ด๋ฏธ์ง€๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค def get_bubble_image(color): if color == "R": return bubble_images[0] elif color == "Y": return bubble_images[1] elif color == "B": return bubble_images[2] elif color == "G": return bubble_images[3] elif color == "P": return bubble_images[4] else: return bubble_images[5] #๋‹ค์Œ๋ฒˆ์— ๋ฐœ์‚ฌํ•  ๋ฒ„๋ธ”์„ ์ค€๋น„ํ•œ๋‹ค def prepare_bubbles(): global CURR_BUBBLE, NEXT_BUBBLE #๋‹ค์Œ์— ์  ๋ฒ„๋ธ”์ด ์žˆ๋‹ค๋ฉด, ํ˜„์žฌ ๋ฒ„๋ธ”์— ๋‹ค์Œ ๋ฒ„๋ธ”์„ ๋„ฃ๋Š”๋‹ค. if NEXT_BUBBLE: CURR_BUBBLE = NEXT_BUBBLE #๋‹ค์Œ์— ์  ๋ฒ„๋ธ”์ด ์—†๋‹ค๋ฉด, ๋ฒ„๋ธ”์„ ์ƒˆ๋กœ ๋งŒ๋“ ๋‹ค. else: CURR_BUBBLE = create_bubble() #์ƒˆ ๋ฒ„๋ธ” ๋งŒ๋“ค๊ธฐ CURR_BUBBLE.set_rect((screen_width// 2, 624)) #๋ฒ„๋ธ”์˜ ์œ„์น˜๋ฅผ ๋ฐœ์‚ฌ๋Œ€ ์œ„์น˜๋กœ ์ •ํ•ด์ค€๋‹ค. NEXT_BUBBLE = create_bubble() NEXT_BUBBLE.set_rect((screen_width // 4 , 688)) #๋ฒ„๋ธ”์˜ ์œ„์น˜๋ฅผ ๋‹ค์Œ์— ์  ์œ„์น˜๋กœ ์ •ํ•ด์ค€๋‹ค. #๋ฒ„๋ธ”์„ ๋งŒ๋“ ๋‹ค def create_bubble(): color = get_random_bubble_color() image = get_bubble_image(color) return Bubble(image,color) #์šฐ์„  ๋ฒ„๋ธ”์˜ ์œ„์น˜๋Š” ์ •ํ•˜์ง€ ์•Š๊ณ , ๊ฐ์ฒด๋งŒ ์ƒ์„ฑ #๋žœ๋ค์œผ๋กœ ๋ฒ„๋ธ” ์ƒ‰๊น”์„ ์ •ํ•œ๋‹ค def get_random_bubble_color(): colors = [] #์ƒ‰๊น”์˜ ํ›„๋ณด๊ฐ€ ๋  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ๋“ค for row in map: for col in row: # ๋น„์–ด์žˆ๊ฑฐ๋‚˜ || .์ด๊ฑฐ๋‚˜ || / ์•„๋‹Œ ๊ฒฝ์šฐ col์„ ํ•˜๋‚˜ ์ถ”๊ฐ€ํ•œ๋‹ค if col not in colors and col not in [".","/"]: colors.append(col) return random.choice(colors) def process_collision(): global CURR_BUBBLE, FIRE,CURR_FIRE_COUNT #์ถฉ๋Œํ•œ ๋ฒ„๋ธ” hit_bubble = pygame.sprite.spritecollideany(CURR_BUBBLE, bubble_group, pygame.sprite.collide_mask) #๋ฒ„๋ธ”๋ผ๋ฆฌ ์ถฉ๋Œ or ์ฒœ์žฅ์— ๋ถ€๋”ชํžŒ๊ฒฝ์šฐ if hit_bubble or CURR_BUBBLE.rect.top <= WALL_HEIGHT: #(* ใ…ใ…) ์ ์œผ๋ฉด ํŠœํ”Œํ˜•ํƒœ๋ฅผ (ใ…‡,ใ…‡)ํ˜•ํƒœ๋กœ ๋ถ„๋ฆฌํ•ด์„œ ์ „๋‹ฌ row_idx, col_idx = get_map_index(*CURR_BUBBLE.rect.center) place_bubble(CURR_BUBBLE, row_idx, col_idx) remove_adjacent_bubbles(row_idx, col_idx, CURR_BUBBLE.color) #๋™์ผ ์ƒ‰๊น” ๋ฒ„๋ธ” 3๊ฐœ๊ฐ€ ๋ชจ์ด๋ฉด ํ„ฐ๋œจ๋ฆฐ๋‹ค CURR_BUBBLE = None FIRE = False CURR_FIRE_COUNT -= 1 #๋ฐœ์‚ฌํ• ๋•Œ๋งˆ๋‹ค ๋ฐœ์‚ฌ๊ธฐํšŒ -1์‹œํ‚จ๋‹ค. def get_map_index(x, y): row_idx = (y - WALL_HEIGHT) // CELL_SIZE col_idx = x // CELL_SIZE if row_idx %2 ==1: col_idx = (x - (CELL_SIZE //2)) // CELL_SIZE if col_idx < 0 : col_idx = 0 if col_idx > MAP_ROW_COUNT - 2 : col_idx = MAP_ROW_COUNT - 2 return row_idx, col_idx #๋ฒ„๋ธ”์„ ํŠน์ • ์œ„์น˜์— ๋ถ™์ธ๋‹ค(์ถฉ๋Œ์‹œ ๋ถ™์ด๊ธฐ ์œ„ํ•ด์„œ) def place_bubble(bubble, row_idx, col_idx): map[row_idx][col_idx] = bubble.color position = get_bubble_position(row_idx, col_idx) bubble.set_rect(position) bubble.set_map_index(row_idx,col_idx) bubble_group.add(bubble) #๋™์ผ ์ƒ‰๊น” ๋ฒ„๋ธ” 3๊ฐœ๊ฐ€ ๋ชจ์ด๋ฉด ํ„ฐ๋œจ๋ฆฐ๋‹ค(DFS ๋กœ์ง ์ด์šฉ) def remove_adjacent_bubbles(row_idx, col_idx, color): visited.clear() #์ดˆ๊ธฐํ™” visit(row_idx, col_idx, color) if len(visited) >= 3: remove_visited_bubbles() #๊ฐ™์€ ์ƒ‰์ด 3๊ฐœ ์ด์ƒ์ด๋ฉด ํ„ฐ๋œจ๋ฆฐ๋‹ค remove_haning_bubbles() #๊ทธ ์ดํ›„ ์ฒœ์žฅ์— ๋ถ™์–ด์žˆ์ง€ ์•Š๊ณ  ๋–  ์žˆ๋Š” ๊ฒƒ์ด ์žˆ์œผ๋ฉด ์—†์•ค๋‹ค #DFS๋ฅผ ์œ„ํ•œ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ def visit(row_idx, col_idx, color=None): #๋งต์˜ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด return ์ฒ˜๋ฆฌ if row_idx < 0 or row_idx >= MAP_ROW_COUNT or col_idx < 0 or col_idx >= MAP_COLUMN_COUNT: return #ํ˜„์žฌ ๋ฐฉ๋ฌธํ•˜๋ ค๋Š” ๊ณณ์˜ ์ƒ‰์ƒ์ด ๋™์ผํ•œ์ง€ ํ™•์ธํ•˜๊ณ  ๋‹ค๋ฅด๋ฉด return if color != None: if map[row_idx][col_idx] != color: return #๋นˆ ๊ณต๊ฐ„์ด๊ฑฐ๋‚˜, ๋ฒ„๋ธ”์ด ์กด์žฌํ•  ์ˆ˜ ์—†๋Š” ์œ„์น˜๋ผ๋ฉด return if map[row_idx][col_idx] in [".","/"]: return #์ด๋ฏธ ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ  ๋ฐฉ๋ฌธํ–ˆ์—ˆ๋‹ค๋ฉด return if (row_idx, col_idx) in visited: return #๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ visited.append((row_idx,col_idx)) #ํ–‰์˜ ์œ„์น˜๊ฐ€ ์ง์ˆ˜์ธ ๊ฒฝ์šฐ ์ด๋™ ๊ฐ€๋Šฅ ๋ฐฉํ–ฅ rows = [0, -1,-1, 0, 1, 1] cols = [-1, -1, 0, 1, 0, -1] #ํ–‰์˜ ์œ„์น˜๊ฐ€ ํ™€์ˆ˜์ธ ๊ฒฝ์šฐ ์ด๋™ ๊ฐ€๋Šฅ ๋ฐฉํ–ฅ if row_idx % 2 == 1: rows=[0, -1, -1, 0, 1, 1] cols=[-1, 0, 1, 1, 1, 0 ] #DFS์ฒ˜๋ฆฌ for i in range(len(rows)): visit(row_idx + rows[i], col_idx + cols[i], color) def remove_visited_bubbles(): #๋ฐฉ๋ฌธํ•œ ๋ฒ„๋ธ” ์ฐพ๊ธฐ bubbles_to_remove = [b for b in bubble_group if (b.row_idx, b.col_idx) in visited] for bubble in bubbles_to_remove: map[bubble.row_idx][bubble.col_idx] = "." # ๋งต์˜ ํ•ด๋‹น์ขŒํ‘œ๋ฅผ ๋นˆ ์ƒํƒœ๋กœ ๋งŒ๋“ ๋‹ค bubble_group.remove(bubble) def remove_not_visited_bubbles(): #๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋ฒ„๋ธ”์ฐพ๊ธฐ -> ๋ฐฉ๋ฌธ์„ ์•ˆํ–ˆ๋‹ค๋ฉด, ์ฒœ์žฅ์— ์ด์–ด์ ธ์žˆ์ง€ ์•Š์€ ๋ฒ„๋ธ”์ด๋‹ค bubbles_to_remove = [b for b in bubble_group if (b.row_idx, b.col_idx) not in visited] for bubble in bubbles_to_remove: map[bubble.row_idx][bubble.col_idx] = "." # ๋งต์„ ์ดˆ๊ธฐํ™” ์‹œํ‚จ๋‹ค bubble_group.remove(bubble) def remove_haning_bubbles(): visited.clear() for col_idx in range(MAP_COLUMN_COUNT): if map[0][col_idx] != ".": visit(0,col_idx,color=None) remove_not_visited_bubbles() #๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณณ์„ ํ„ฐ๋œจ๋ฆฐ๋‹ค -> ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณณ์€ ์ฒœ์žฅ์— ๋ถ™์–ด์žˆ์ง€ ์•Š์€ ๋ฒ„๋ธ”์ด๋ฏ€๋กœ def draw_bubbles(): #ํ”๋“ค๋ฆฌ๋Š” ํšจ๊ณผ๋ฅผ ๋‚ด๊ธฐ์œ„ํ•ด์„œ x์ขŒํ‘œ๋ฅผ ๋” ํ•ด์ค€๋‹ค to_x = None if CURR_FIRE_COUNT == 2: to_x = random.randint(-1,1) -1 # -1 ~ 1์˜ ๊ฐ’์„ ๋‚œ์ˆ˜๋กœ ๊ฐ€์ง„๋‹ค elif CURR_FIRE_COUNT == 1: to_x = random.randint(-4,4) -1 # -4 ~ 4์˜ ๊ฐ’์„ ๋‚œ์ˆ˜๋กœ ๊ฐ€์ง„๋‹ค #๋ฒ„๋ธ”์„ ๊ทธ๋ฆฐ๋‹ค. for bubble in bubble_group: bubble.draw(screen, to_x) #๋ฒฝ์„ ์•„๋ž˜๋กœ ๋‚ด๋ฆฐ๋‹ค. def drop_wall(): global WALL_HEIGHT,CURR_FIRE_COUNT #๋ฒฝ์ด ๋‚ด๋ ค์˜จ ๋งŒํผ ๋ชจ๋‘ ๋ฐ‘์œผ๋กœ ๋‚ด๋ฆฐ๋‹ค WALL_HEIGHT += CELL_SIZE for bubble in bubble_group: bubble.drop_downward(CELL_SIZE) CURR_FIRE_COUNT = FIRE_COUNT #ํ˜„์žฌ ํ™”๋ฉด์˜ ๋ฒ„๋ธ”๋“ค ์ค‘์—์„œ ๊ฐ€์žฅ ๋ฐ‘์— ์žˆ๋Š” ๋ฒ„๋ธ”์˜ bottom๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค. def get_lowest_bubble_bottom(): bubble_bottoms = [bubble.rect.bottom for bubble in bubble_group] #bubble_group์˜ ๋ฒ„๋ธ”๋“ค์˜ bottom ๊ฐ’์„ ๊ฐ€์ ธ์˜จ๋‹ค. return max(bubble_bottoms) #game over์‹œ ๋ฒ„๋ธ”์„ ๋ชจ๋‘ ๊ฒ€์€์ƒ‰์œผ๋กœ ๋ฐ”๊พผ๋‹ค def change_bubble_image(image): for bubble in bubble_group: bubble.image = image #game over ์ฒ˜๋ฆฌ ํ•จ์ˆ˜ def display_game_over(): txt_game_over = GAME_FONT.render(GAME_RESULT, True, WHITE) rect_game_over = txt_game_over.get_rect(center=(screen_width // 2, screen_height // 2)) screen.blit(txt_game_over, rect_game_over) pygame.init() screen_width = 448 screen_height = 720 screen = pygame.display.set_mode((screen_width,screen_height)) # ํ™”๋ฉด ํฌ๊ธฐ ์„ค์ • pygame.display.set_caption("Puzzle Bobble") # ๊ฒŒ์ž„๋ช… ์„ค์ • clock = pygame.time.Clock() # ๋ฐฐ๊ฒฝ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ current_path = os.path.dirname(__file__) #์‹คํ–‰ํ•˜๋Š” py๊ฒฝ๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ background = pygame.image.load(os.path.join(current_path, "background.png")) #๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ wall = pygame.image.load(os.path.join(current_path, "wall.png")) #๋ฒฝ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ # ๋ฒ„๋ธ” ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ bubble_images = [ pygame.image.load(os.path.join(current_path, "red.png")).convert_alpha() #๋นจ๊ฐ• ๊ณต ,pygame.image.load(os.path.join(current_path, "yellow.png")).convert_alpha() #๋…ธ๋ž‘ ๊ณต ,pygame.image.load(os.path.join(current_path, "blue.png")).convert_alpha() #ํŒŒ๋ž‘ ๊ณต ,pygame.image.load(os.path.join(current_path, "green.png")).convert_alpha() #์ดˆ๋ก ๊ณต ,pygame.image.load(os.path.join(current_path, "purple.png")).convert_alpha() #๋ณด๋ผ ๊ณต ,pygame.image.load(os.path.join(current_path, "black.png")).convert_alpha() #๊ฒ€์ • ๊ณต ] #๋ฐœ์‚ฌ๋Œ€ ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ launchPad_image = pygame.image.load(os.path.join(current_path, "launchPad.png")) launchPad = LaunchPad(launchPad_image,( screen_width //2, 624),90) #๋ฐœ์‚ฌ๋Œ€ ์œ„์น˜ ์„ธํŒ… #๊ฒŒ์ž„ ๊ด€๋ จ ๋ณ€์ˆ˜ CELL_SIZE = 56 BUBBLE_WIDTH = 56 BUBBLE_HEIGHT = 62 MAP_ROW_COUNT = 11 #๋งต์˜ ํ–‰ ๊ฐฏ์ˆ˜ MAP_COLUMN_COUNT=8 #๋งต์˜ ์—ด ๊ฐฏ์ˆ˜ FIRE_COUNT = 7 # ์ด๋ฒˆ ๊ฒŒ์ž„์˜ ์ด ๋ฐœ์‚ฌ๊ธฐํšŒ CURR_FIRE_COUNT = FIRE_COUNT # ๋‚จ์€ ๋ฐœ์‚ฌ๊ธฐํšŒ WALL_HEIGHT = 0 # ํ™”๋ฉด์— ๋ณด์—ฌ์ง€๋Š” ๋ฒฝ์˜ ๋†’์ด #๊ฒŒ์ž„ ์ข…๋ฃŒ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ๋ณ€์ˆ˜ IS_GAME_OVER = False GAME_FONT = pygame.font.SysFont("arialrounded", 40) GAME_RESULT = None WHITE = (255,255,255) #๋ฒ„๋ธ” ๋ฐœ์‚ฌ๋ฅผ ์œ„ํ•œ ๋ณ€์ˆ˜ CURR_BUBBLE = None #์ด๋ฒˆ์— ์  ๋ฒ„๋ธ” NEXT_BUBBLE = None #๋‹ค์Œ์— ์  ๋ฒ„๋ธ” FIRE = False #๋ฐœ์‚ฌ์ค‘์ธ์ง€ ์—ฌ๋ถ€ #๋ฐœ์‚ฌ๋Œ€ ๊ด€๋ จ ๋ณ€์ˆ˜ TO_ANGLE_LEFT = 0 # ์ขŒ๋กœ ์›€์ง์ธ ๊ฐ๋„์˜ ์ •๋ณด TO_ANGLE_RIGHT = 0 # ์šฐ๋กœ ์›€์ง์ธ ๊ฐ๋„์˜ ์ •๋ณด ANGLE_SPEED = 1.5 # ์›€์ง์ผ ์†๋„(1.5๋„์”ฉ ์›€์ง์ด๊ฒŒ ๋จ) map = [] #๋งต visited = [] #๋ฐฉ๋ฌธ๊ธฐ๋ก bubble_group = pygame.sprite.Group() # ๋ฒ„๋ธ”์„ ์ƒ์„ฑํ•ด์„œ ๊ด€๋ฆฌํ•  ๊ณต๊ฐ„ setup() running = True while running: clock.tick(60) #FPS๋ฅผ 60์œผ๋กœ ์„ค์ • for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #๋ฐ˜๋ณต๋ฌธ ํƒˆ์ถœํ•˜๋„๋ก running๋ณ€์ˆ˜ ๋ณ€๊ฒฝ # ํ‚ค๋ณด๋“œ์˜ ์•„๋ž˜ํ™”์‚ดํ‘œ๊ฐ€ ๋ˆŒ๋ ค์กŒ์„๋•Œ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: TO_ANGLE_LEFT += ANGLE_SPEED elif event.key == pygame.K_RIGHT: TO_ANGLE_RIGHT -= ANGLE_SPEED #์ŠคํŽ˜์ด์Šค๋ฐ”๊ฐ€ ๋ˆŒ๋ ค์ง€๊ณ  && CURR_BUBBLE ๋งŒ๋“ค์–ด์ ธ ์žˆ์œผ๋ฉฐ && ๋ฐœ์‚ฌ์ค‘์ธ์ƒํƒœ๊ฐ€ ์•„๋‹๋•Œ <๋ฐœ์‚ฌ!> elif event.key == pygame.K_SPACE: if CURR_BUBBLE and not FIRE : FIRE = True CURR_BUBBLE.set_angle(launchPad.angle) # ํ‚ค๋ณด๋“œ์˜ ์•„๋ž˜ํ™”์‚ดํ‘œ๊ฐ€ ๋–ผ์–ด์กŒ์„๋•Œ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: TO_ANGLE_LEFT = 0 elif event.key == pygame.K_RIGHT: TO_ANGLE_RIGHT = 0 if not CURR_BUBBLE: prepare_bubbles() if FIRE: process_collision() #์ถฉ๋Œ์ฒ˜๋ฆฌ # ๋ฐœ์‚ฌ๊ธฐํšŒ๋ฅผ ๋ชจ๋‘ ์‚ฌ์šฉํ–ˆ์„๋•Œ, ๋ฒฝ์„ ๋‚ด๋ฆฐ๋‹ค. if CURR_FIRE_COUNT == 0: drop_wall() #๊ฒŒ์ž„ ์ข…๋ฃŒ ์ฒ˜๋ฆฌ ###์„ฑ๊ณต### if not bubble_group: GAME_RESULT = "Mission Complete" IS_GAME_OVER = True ###์‹คํŒจ### elif get_lowest_bubble_bottom() > len(map) * CELL_SIZE: GAME_RESULT = "Game Over" IS_GAME_OVER = True change_bubble_image(bubble_images[5]) screen.blit(background, (0,0)) #(0,0) background ํ‘œ์‹œํ•˜๊ธฐ screen.blit(wall,(0, WALL_HEIGHT - screen_height)) #๊ฒŒ์ž„ over์‹œ ๋ฒฝ ํ‘œ์‹œํ•˜๊ธฐ draw_bubbles() #๋ฒ„๋ธ” ํ‘œ์‹œํ•˜๊ธฐ launchPad.rotate(TO_ANGLE_LEFT+TO_ANGLE_RIGHT) #๋ฐœ์‚ฌ๋Œ€ ์ด๋ฏธ์ง€ ๊ฐ๋„ ํ‘œํ˜„ํ•˜๊ธฐ launchPad.draw(screen) #๋ฐœ์‚ฌ๋Œ€ ํ‘œ์‹œํ•˜๊ธฐ #๋ฐœ์‚ฌํ•  ๋ฒ„๋ธ”์„ ํ‘œ์‹œํ•˜๊ธฐ if CURR_BUBBLE: #๋ฐœ์‚ฌ์ค‘์ด๋ผ๋ฉด if FIRE: CURR_BUBBLE.move() CURR_BUBBLE.draw(screen) #๋‹ค์Œ์— ๋ฐœ์‚ฌํ•  ๋ฒ„๋ธ”์„ ํ‘œ์‹œํ•˜๊ธฐ if NEXT_BUBBLE: NEXT_BUBBLE.draw(screen) #game over ์ถœ๋ ฅ if IS_GAME_OVER: display_game_over() running = False pygame.display.update() pygame.time.delay(3000) #๊ฒŒ์ž„ over์‹œ 3์ดˆ ๋Œ€๊ธฐํ›„ ์ข…๋ฃŒ pygame.quit()
class Pilha(object): def __init__(self): self.dados = [] #self.est = [] #self.parent = -1 def empilha(self, elemento): self.dados.append(elemento) #self.est.append(num) #self.parent = num def desempilha(self,tam): for i in range(0,tam): self.dados.pop(-1) def tam(self): return len(self.dados) def topo(self): return self.dados[-1]
def proper_divisors_list(n): divisors = [[] for _ in range(n)] for i in range(1, n): k = i * 2 while k < n: divisors[k].append(i) k += i return divisors def find_amicable_total(divisors): n = len(divisors) sum_divisor = [sum(divisors[i]) for i in range(n)] total = 0 for i in range(n): j = sum_divisor[i] if j != i and j < n and sum_divisor[j] == i: total += i return total if __name__ == '__main__': print(find_amicable_total(proper_divisors_list(10000)))
def factorials_list(n): if n == 0: return [1] else: factorials = [1] for i in range(1, n): factorials.append(factorials[-1]*i) return factorials def lex_permutations(n): """ Find the nth permutation of the basic 10 digits in lexicographic order """ fatorials = factorials_list(10) permu = "" for i in fatorials[::-1]: num = n // i if __name__ == '__main__': print(factorials_list(10))
"""" MongoDB database model for Lesson 7 """ import os from datetime import datetime from pymongo import MongoClient program_start = datetime.now() class MongoDBConnection(object): """ MongoDB Connection for content manager """ def __init__(self, host='127.0.0.1', port=27017): """ Use the ip address and specific port for local windows """ self.host = host self.port = port self.connection = None def __enter__(self): self.connection = MongoClient(self.host, self.port) return self def __exit__(self, exc_type, exc_val, exc_tb): self.connection.close() def count_mdb_collection(collection_name): """ Count the particular MongoDB database collection records """ collection_count = 0 mongo = MongoDBConnection() with mongo: # mongodb database defined db = mongo.connection.media # collections in the MongoDB database products = db["products"] customers = db["customers"] rentals = db["rentals"] for doc in collection_name.find(): collection_count += 1 return collection_count def import_products_data(data_dir, products_file): """ Load MongoDB database products collection from .csv file """ mongo = MongoDBConnection() with mongo: # mongodb database defined db = mongo.connection.media # Products collection in the MongoDB database products = db["products"] # Insert Products file records prod_start = datetime.now() add_prod = 0 err_prod = 0 try: with open(data_dir + "\\" + products_file, 'r') as csv_file: csv_header = csv_file.readline() while csv_header: csv_line = csv_file.readline() if not csv_line: break data_in = dict(zip(csv_header.strip().split(','), csv_line.strip().split(','))) try: products.insert_one(data_in) add_prod += 1 except: print(f'failed to insert: {data_in}\n') err_prod += 1 csv_file.close() except FileNotFoundError: print('File not found: ', data_dir + "\\" + products_file) prod_finish = datetime.now() # Gather up the statistics to be returned added = (add_prod) errors = (err_prod) elapsed = (prod_finish - prod_start).total_seconds() return added, errors, elapsed def import_customers_data(data_dir, customers_file): """ Load MongoDB database customers collection from .csv file """ mongo = MongoDBConnection() with mongo: # mongodb database defined db = mongo.connection.media # Customers collection in the MongoDB database customers = db["customers"] # Insert Customers file records cust_start = datetime.now() add_cust = 0 err_cust = 0 try: with open(data_dir + "\\" + customers_file, 'r') as csv_file: csv_header = csv_file.readline() while csv_header: csv_line = csv_file.readline() if not csv_line: break data_in = dict(zip(csv_header.strip().split(','), csv_line.strip().split(','))) try: customers.insert_one(data_in) add_cust += 1 except: print(f'failed to insert: {data_in}\n') err_cust += 1 csv_file.close() except FileNotFoundError: print('File not found: ', data_dir + "\\" + customers_file) cust_finish = datetime.now() # Gather up the statistics to be returned added = (add_cust) errors = (err_cust) elapsed = (cust_finish - cust_start).total_seconds() return added, errors, elapsed def import_rentals_data(data_dir, rentals_file): """ Load MongoDB database rentals collection from .csv file """ mongo = MongoDBConnection() with mongo: # mongodb database defined db = mongo.connection.media # Rentals collection in the MongoDB database rentals = db["rentals"] # Insert Rentals file records rent_start = datetime.now() add_rent = 0 err_rent = 0 try: with open(data_dir + "\\" + rentals_file, 'r') as csv_file: csv_header = csv_file.readline() while csv_header: csv_line = csv_file.readline() if not csv_line: break data_in = dict(zip(csv_header.strip().split(','), csv_line.strip().split(','))) try: rentals.insert_one(data_in) add_rent += 1 except: print(f'failed to insert: {data_in}\n') err_rent += 1 csv_file.close() except FileNotFoundError: print('File not found: ', data_dir + "\\" + rentals_file) rent_finish = datetime.now() # Gather up the statistics to be returned added = (add_rent) errors = (err_rent) elapsed = (rent_finish - rent_start).total_seconds() return added, errors, elapsed def drop_data(): """ Drop entire MongoDB database collection """ mongo = MongoDBConnection() with mongo: # mongodb database defined db = mongo.connection.media # collections in the MongoDB database products = db["products"] customers = db["customers"] rentals = db["rentals"] products.drop() customers.drop() rentals.drop() def main(): """ Extra testing scenarios...also works with pytest 'test_gradel07.py' """ import_elapsed = 0 mongo = MongoDBConnection() with mongo: # mongodb database defined db = mongo.connection.media # collections in the MongoDB database products = db["products"] customers = db["customers"] rentals = db["rentals"] print(f'Products count: {count_mdb_collection(products)}') print(f'Customers count: {count_mdb_collection(customers)}') print(f'Rentals count: {count_mdb_collection(rentals)}\n') data_dir = os.path.dirname(os.path.abspath(__file__)) added, errors, elapsed = import_products_data(data_dir, "products.csv") import_elapsed += elapsed print(f'Added Products records: {added}') print(f'Error Products records: {errors}') print(f'Elapsed Products time: {elapsed}\n') added, errors, elapsed = import_customers_data(data_dir, "customers.csv") import_elapsed += elapsed print(f'Added Customers records: {added}') print(f'Error Customers records: {errors}') print(f'Elapsed Customers time: {elapsed}\n') added, errors, elapsed = import_rentals_data(data_dir, "rentals.csv") import_elapsed += elapsed print(f'Added Rentals records: {added}') print(f'Error Rentals records: {errors}') print(f'Elapsed Rentals time: {elapsed}\n') print(f'Products count: {count_mdb_collection(products)}') print(f'Customers count: {count_mdb_collection(customers)}') print(f'Rentals count: {count_mdb_collection(rentals)}\n') program_finish = datetime.now() program_elapsed = (program_finish - program_start).total_seconds() print(f'Elapsed program time: {program_elapsed}') print(f'Elapsed import time: {import_elapsed}') print(f'Elapsed overhead time: {(program_elapsed - import_elapsed)}\n') # Option to drop data from collections yorn = input("Drop data?") if yorn.upper() == 'Y': drop_data() if __name__ == "__main__": main()
# Student: Bradnon Nguyen # Class: Advance Python 220 - Jan2019 # Lesson04 - Refactor - basic_operations.py. """ Importing customer_db_model.py this file has the following function: - add_customer. -search_customer. -delete_customer. -update_customer_credit. -list_active_customers. """ import logging import datetime import codecs import csv from peewee import * from lesson03.assignment.customer_db_model import * # logging.basicConfig(level=logging.INFO,) # LOGGER.info('Starting program action.') # LOGGING SETTING START LOG_FORMAT = "%(asctime)s %(filename)s:%(funcName)s:%(lineno)-3d %(levelname)s %(message)s" LOG_FILE = datetime.datetime.now().strftime("%Y-%m-%d")+'db.log' FORMATTER = logging.Formatter(LOG_FORMAT) DICT_LEVEL = {'0': 'disabled', '1': 'ERROR', '2': 'WARNING', '3': 'DEBUG'} # Log setting for writing to file FILE_HANDLER = logging.FileHandler(LOG_FILE) FILE_HANDLER.setLevel(logging.WARNING) # Saving to log file via level FILE_HANDLER.setFormatter(FORMATTER) # Log setting for display to standout. CONSOLE_HANDLER = logging.StreamHandler() CONSOLE_HANDLER.setLevel(logging.DEBUG) # Send log to console: DEBUG level CONSOLE_HANDLER.setFormatter(FORMATTER) LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) LOGGER.addHandler(FILE_HANDLER) LOGGER.addHandler(CONSOLE_HANDLER) # LOGGING SETTING END! def initialize_db(tablename): """ Create DB to meet requirement # 6. Ensure you application will create an empty database if one doesnโ€™t exist when the app is first run. Call it customers.db """ try: LOGGER.info('Creating Database..') DB.connect() DB.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite only tablename.create_table() LOGGER.info('CREATE: Tablename = has been created.') except Exception as errs: LOGGER.warning(f'Creating DB issue. {errs}') DB.close() # Creating the database with table Customer First! initialize_db(Customer) def db_initial_steps(): """basic method to reuse sqlite3 connection strings""" DB.connect(reuse_if_open=True) DB.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite only LOGGER.info("DB-connection") def process_csv(csv_file_in): """ Read in csv file and return a list of rows. Param: csv file name. """ data = [] with open(csv_file_in, 'r', newline='') as csvfile: has_header = csv.Sniffer().has_header(csvfile.read(1024)) # 1024=read 2 lines csvfile.seek(0) # Rewind. reader = csv.reader(csvfile) if has_header: # True False next(reader) # Skip header row. try: for row in reader: LOGGER.info(f'CSV: processing the the next row: {row}.') yield row data.append(row) # adding the data row into list data except csv.Error as errs: LOGGER.error(f"Some sort of data process issue: {row}") LOGGER.error(errs) return data def add_customer(customer_id, name, lastname, home_address, phone_number, email_address, status, credit_limit): """ This function will add a new customer to the sqlite3 database. Parameters:customer_id, name, lastname, home_address, phone_number, email_address, status, credit_limit. """ try: db_initial_steps() with DB.transaction(): new_customer = Customer.create( customer_id=customer_id, name=name, lastname=lastname, home_address=home_address, phone_number=phone_number, email=email_address, status=status, credit_limit=credit_limit ) new_customer.save() LOGGER.warning(f'ADD: Customer with id: {customer_id} has been saved.') except Exception as errs: LOGGER.error(f"ADDFAIL: Failed DATA save on input record id: {customer_id}.") LOGGER.error(errs) finally: DB.close() LOGGER.info(f"ADD: DB closed.") def add_customers(list_in): """ This function is used to add more than 1 customers to the db from a list. Param: a list. Although the intend of usage here would be add_customers(process_csv(file_name_csv)). """ try: for customer in list_in: add_customer(customer[0], customer[1], customer[2], customer[3], customer[4], customer[5], customer[6], customer[7] ) except Exception as eerrs: LOGGER.error(f'ADDFAIL: Something went wrong with saving dat from a list: {list_in}.') LOGGER.error(eerrs) def search_customer(customer_id_in): """ This function will return a dictionary object with name, lastname, email address and phone number of a customer or an empty dictionary object if no customer was found. Param: customer_id_in. """ LOGGER.info('Entered search customer.') dict_customer = {} # To hold return values. try: db_initial_steps() searched_customer = Customer.get(Customer.customer_id == customer_id_in) LOGGER.info(f'FIND: Customer object with id: {customer_id_in} has been return.') dict_customer = {"name": searched_customer.name, "lastname": searched_customer.lastname, "email": searched_customer.email, "phone_number": searched_customer.phone_number } except Exception as errs: LOGGER.error(f'FINDFAIL: Unable to find user: {customer_id_in}.') LOGGER.error(errs) finally: DB.close() LOGGER.info(f"FIND:DB closed connection.") return dict_customer # finally we will return value either empty or with data def delete_customer(customer_id_in): """ This function will delete a customer from the sqlite3 database. Param: customer_id """ LOGGER.info('Entered find and delete.') try: db_initial_steps() customer_tb_deleted = Customer.get(Customer.customer_id == customer_id_in) customer_tb_deleted.delete_instance() LOGGER.warning(f'DELETE: Found and removed customer with id: {customer_id_in}.') except Exception as errs: LOGGER.error(f"DELETE:Something wrong in deleting {customer_id_in}.") LOGGER.error(errs) finally: DB.close() LOGGER.info(f"DELETE: DB closed.") def update_customer_credit(customer_id_in, credit_limit_update): """ This function will search an existing customer by customer_id and update their credit limit or raise a ValueError exception if the customer does not exist. Parameters: customer_id_in, credit_limit_update. """ LOGGER.info("Entered customer update credit.") try: db_initial_steps() with DB.transaction(): customer_tb_updated = Customer.get(Customer.customer_id == customer_id_in) customer_tb_updated.credit_limit = credit_limit_update customer_tb_updated.save() LOGGER.warning(f"UPDATE: Update done for customer with id: {customer_id_in}.") except Exception as errs: LOGGER.error(f"UPDATE: Unable to update customer with id: {customer_id_in}.") LOGGER.error(errs) raise ValueError("NoCustomer") finally: DB.close() LOGGER.info("UPDATE:Closed DB connection") def list_active_customers(): """ This function will return an integer with the number (count) of customers, whose status is currently "active". """ LOGGER.info(f"LISTACTIVE:Entered function.") try: db_initial_steps() count_active_customer = Customer.select().where(Customer.status == 'active').count() LOGGER.info(f'LISTACTIVE: The number of {count_active_customer}') except Exception as errs: LOGGER.error(f'LISTFAIL: DBMS issue: {errs}.') finally: DB.close() LOGGER.info("LISTACTIVE: Closed connection.") return count_active_customer def delete_all_customers(table_name): """ This function is used to delete all records in Customer model. Param: Model or Table name. """ LOGGER.info(f"DELETEALL:Entered active customer count.") try: db_initial_steps() table_name.delete() # delete all LOGGER.warning(f'DELETEALL: all customers in {table_name} have been removed.') except Exception as errs: LOGGER.error(f'DELETEALLFAIL: Something wrong with truncate table {table_name}.') LOGGER.error(errs) finally: DB.close() LOGGER.info(f'DELETEALL: DB Closed')
# Furniture class # pylint: disable=too-few-public-methods # pylint: disable=too-many-arguments """ Module to define furniture class """ from inventory_management.inventory_class import Inventory class Furniture(Inventory): """ This class inherets from Inventory class and adds furniture attributes to a dictionary """ def __init__(self, product_code, description, market_price, rental_price, material, size): Inventory.__init__(self, product_code, description, market_price, rental_price) # Creates common instance variables from the parent class self.material = material self.size = size def return_as_dictionary(self): """ Function to add furniture attributes to a dictionary """ output_dict = {} output_dict['product_code'] = self.product_code output_dict['description'] = self.description output_dict['market_price'] = self.market_price output_dict['rental_price'] = self.rental_price output_dict['material'] = self.material output_dict['size'] = self.size return output_dict
# Student: Bradnon Nguyen # Class: Advance Python 220 - Jan2019 # Lesson03 - customer_db_model.py """ This will create a customer model and database that can be used at HP Norton with the following data: Customer ID. Name. Lastname. Home address. Phone number. Email address. Status (active or inactive customer). Credit limit. """ from peewee import * DB = SqliteDatabase('customers.db') class BaseModel(Model): """ base Model peewee Object Relational Mapping - ORM """ class Meta: # database = SqliteDatabase('HPCustomer.db') # Why not here? database = DB class Customer(BaseModel): """ This class defines a customer model in HP HP Norton, which maintains details of someone to support: Saleperson, Accountant, Manager. Fields: customer_id, name, last_name, home_address, phone_number, email status, credit_limit. """ # Customer ID, Name, Lastname, Home address, Phone number, Email address, Status (active or inactive customer), Credit limit. customer_id = CharField(primary_key=True, max_length=20) name = CharField(null=True) lastname = CharField(null=True) home_address = CharField(null=True, max_length=255) phone_number = CharField(null=True, max_length=20) email = CharField(null=True, max_length=254) # RFC xxyy status = CharField(null=True, max_length=8) credit_limit = CharField(null=True) class CustomerA(BaseModel): """This class is similar to Customer except that this one has constraints""" customer_id = CharField(primary_key=True, max_length=20) name = CharField(null=True) lastname = CharField(null=True) home_address = CharField(null=True, max_length=255) phone_number = CharField(null=True, max_length=20) email = CharField(null=True, max_length=254) # RFC xxyy # These will fail some Andy's tests if in Customer status = CharField(null=True, constraints=[Check("status == 'active' or status == 'inactive'")]) credit_limit = IntegerField(null=True, constraints=[Check('credit_limit >= 0')])
""" Unit tests for assignment01 """ from unittest import TestCase # from unittest.mock import MagicMock from inventory_management.inventory_class import Inventory from inventory_management.furniture_class import Furniture from inventory_management.electric_appliances_class import ElectricAppliances from inventory_management.market_prices import get_latest_price from inventory_management.main import add_appliance from inventory_management.main import add_furniture from inventory_management.main import add_inventory from inventory_management.main import get_item class InventoryTest(TestCase): """ Inventory class tests """ def test_inventory_class(self): """ Inventory class test """ product_code = 1234 description = 'test inventory article' market_price = 1234.56 rental_price = 12.34 test_article = Inventory(product_code, description, market_price, rental_price) test_dict = test_article.return_as_dictionary() self.assertEqual(test_dict['product_code'], product_code) self.assertEqual(test_dict['description'], description) self.assertEqual(test_dict['market_price'], market_price) self.assertEqual(test_dict['rental_price'], rental_price) class FurnitureTest(TestCase): """ Furniture class tests """ def test_furniture_class(self): """ Furniture class test """ product_code = 5678 description = 'test furniture article' market_price = 5678.90 rental_price = 56.78 material = 'cloth' size = 'large' test_article = Furniture(product_code, description, market_price, rental_price, material, size) test_dict = test_article.return_as_dictionary() self.assertEqual(test_dict['product_code'], product_code) self.assertEqual(test_dict['description'], description) self.assertEqual(test_dict['market_price'], market_price) self.assertEqual(test_dict['rental_price'], rental_price) self.assertEqual(test_dict['material'], material) self.assertEqual(test_dict['size'], size) class ElectricApplianceTest(TestCase): """ Appliance class tests """ def test_electric_appliance_class(self): """ Appliance class test """ product_code = 5678 description = 'test furniture article' market_price = 5678.90 rental_price = 56.78 brand = 'General Electric' voltage = 220 test_article = ElectricAppliances(product_code, description, market_price, rental_price, brand, voltage) test_dict = test_article.return_as_dictionary() self.assertEqual(test_dict['product_code'], product_code) self.assertEqual(test_dict['description'], description) self.assertEqual(test_dict['market_price'], market_price) self.assertEqual(test_dict['rental_price'], rental_price) self.assertEqual(test_dict['brand'], brand) self.assertEqual(test_dict['voltage'], voltage) class MarketPriceTest(TestCase): """market price test""" def test_market_price(self): """market price test""" magic_num = 24 item_code = 42 mkt_price = get_latest_price(item_code) self.assertEqual(mkt_price, magic_num) class MainTest(TestCase): """Main test""" def test_add_furniture(self): """ Test adding a furniture item """ item_code = 123 item_description = 'sofa' item_price = 42 item_rental_price = 24 item_material = 'cloth' item_size = 'large' actual_dict = None test_dict = { 'product_code' : item_code, 'description' : item_description, 'market_price' : item_price, 'rental_price' : item_rental_price, 'material' : item_material, 'size' : item_size } add_furniture(item_code, item_description, item_price, item_rental_price, item_material, item_size) actual_dict = get_item(item_code) self.assertNotEqual(actual_dict, None) if actual_dict is None: return for key in actual_dict: self.assertEqual(test_dict[key], actual_dict[key]) def test_add_appliance(self): """ test adding an Electric Appliance item """ item_code = 456 item_description = 'dishwasher' item_price = 420 item_rental_price = 240 item_brand = 'GE' item_voltage = 220 actual_dict = None test_dict = { 'product_code' : item_code, 'description' : item_description, 'market_price' : item_price, 'rental_price' : item_rental_price, 'brand' : item_brand, 'voltage' : item_voltage } add_appliance(item_code, item_description, item_price, item_rental_price, item_brand, item_voltage) actual_dict = get_item(item_code) self.assertNotEqual(actual_dict, None) if actual_dict is None: return for key in actual_dict: self.assertEqual(test_dict[key], actual_dict[key]) def test_add_inventory(self): """ Test adding an inventory item """ item_code = 789 item_description = 'pencil' item_price = 4 item_rental_price = 2 actual_dict = None test_dict = { 'product_code' : item_code, 'description' : item_description, 'market_price' : item_price, 'rental_price' : item_rental_price, } add_inventory(item_code, item_description, item_price, item_rental_price) actual_dict = get_item(item_code) self.assertNotEqual(actual_dict, None) if actual_dict is None: return for key in actual_dict: self.assertEqual(test_dict[key], actual_dict[key])
def counter(start=0): count = start def increment(): nonlocal count count += 1 return count return increment def make_multipler(n): def multiply(x): return x * n return multiply mycounter = counter() print('1st mycounter():', mycounter()) print('2nd mycounter():', mycounter()) print('3rd mycounter():', mycounter()) print() mycounter99 = counter(99) print('1st mycounter99():', mycounter99()) print('2nd mycounter99():', mycounter99()) print('3rd mycounter99():', mycounter99()) print() mymult3 = make_multipler(3) print('mymult3(4):', mymult3(4)) print() mymult5 = make_multipler(5) print('mymult5(4):', mymult5(4))
# Create Database # pylint: disable=unused-wildcard-import # pylint: disable=wildcard-import """ Module to create a database and define the Customer model """ from peewee import * TABLE_NAME = 'customers' DATABASE = SqliteDatabase(TABLE_NAME + '.db') def main(): """ This fucntions initiates the database connect and creates a table """ DATABASE.connect() DATABASE.execute_sql('PRAGMA foreign_keys = ON;') if Customer.table_exists() is False: Customer.create_table() print(f"{TABLE_NAME} table created successfully") else: print(f"{TABLE_NAME} table already exists") DATABASE.close() class BaseModel(Model): """ This class defines BaseModel """ class Meta: """ This class defines the database """ database = DATABASE class Customer(BaseModel): """ This class defines Customer, which maintains details of someone who has made a purchase """ customer_id = CharField(primary_key=True, max_length=7) name = CharField(max_length=20) lastname = CharField(max_length=20, null=True) address = CharField(max_length=40, null=True) phone_number = CharField(max_length=40, null=True) email = CharField(max_length=40, null=True) status = CharField(max_length=8, null=True) credit_limit = IntegerField(null=True)
""" Module:calculator with basic methods. """ from .exceptions import InsufficientOperands #class Calculator(object): class Calculator: """ Class: Calculator """ def __init__(self, adder, subtracter, multiplier, divider): self.adder = adder self.subtracter = subtracter self.multiplier = multiplier self.divider = divider self.stack = [] def enter_number(self, number): """ Method: To enter number. """ self.stack.insert(0, number) def _do_calc(self, operator): """ Method: To do calculation. """ try: #result = operator.calc(self.stack[0], self.stack[1]) #ORG result = operator.calc(self.stack[1], self.stack[0]) # Integration test to pass except IndexError: raise InsufficientOperands self.stack = [result] return result def add(self): """ Method: To add 2 number. """ return self._do_calc(self.adder) def subtract(self): """ Method: To substract 2 numbers. """ return self._do_calc(self.subtracter) def multiply(self): """ Method: To substract 2 numbers. """ return self._do_calc(self.multiplier) def divide(self): """ Method: To divide 2 numbers. """ return self._do_calc(self.divider)
""" Class object to handle inventory dictionary """ class Fullinventory: """ Inventory Dictionary Utiltiy""" def __init__(self): self.full_inventory_dict = {} def add_inventory(self, item_code, item_dict): """ Add an item to the inventory dictionary """ self.full_inventory_dict[item_code] = item_dict def get_inventory(self): """ Print the inventory dictionary """ return self.full_inventory_dict def get_inventory_item(self, item_code): """ Get inventory item """ if item_code in self.full_inventory_dict: return self.full_inventory_dict[item_code] return None
def most_common(filename): fd = open(filename) letters = "abcdefghijklmnopqrstuvwxyz" dic = {} for line in fd: for letter in line: if letter in letters: if letter in dic: dic[letter] += 1 else: dic[letter] = 1 list_values = list(dic.values()) list_values.sort(reverse=True) fd.close() print("the two most common letters appear", list_values[0] + list_values[1], "times") most_common("short.txt")
#!/usr/bin/env python #coding:utf -8 # l = [1,2,3,4,5,6,7,2,3,4] # t = {"a":4, "b":2,"c":5,"e":3,"d":2} # n = sorted(t.items(),key=lambda x:x[1],reverse=True)#1ไปฃ่กจvalue็š„ๅ€ผ็”ฑๅฐๅˆฐๅคง,reverseไปฃ่กจๅ€’่ฝฌ # m = sorted(t.items(),key=lambda x:x[0])#0ไปฃ่กจkey็š„โ€œaโ€ๅˆฐโ€œeโ€ # print l[2:] # print l[2:5] # print l[2:5:2] # print l[2:5:3] # print n # print n[0:3]#ๅฐ†ๅญ—ๅ…ธๅ†…็š„ๅ‡บ็Žฐ้ข‘็އๆœ€้ซ˜ไธ‰ไธชๅˆ—ๅ‡บ # print m # print 'hello' # print 'hello\n\n' # print r'hello\n\n' # n = 'abc' # print n.join("1") # print n.join("11") # print n.join('111') # def changename(a,b): # print a # return a # changename(1,2) # l = ['a','a','a','b','b','c'] # print l # t = {"a":4, "b":2,"c":5,"e":3,"d":2} # print t.get("g") # t = {} # for i in l: # print # def a(b,**c): # print b # print c # print '-'*20 # return 1,2,3,4 # t=a(1,x=2,y=3,z=4) # print t # from time import ctime,sleep # from time import # def timefun_arg(pre="hello"): # def timefun(func):#ๅฎšไน‰่ฃ…้ฅฐๅ™จ # def warppedfunc():#ๅฎšไน‰ไธ€ไธชๅ†…้ƒจๅ‡ฝๆ•ฐ # print "%s called at %s" %(func.__name__,ctime())#ๅ…ˆๆ‰ง่กŒๅ‡ฝๆ•ฐ็š„ๅ†…ๅฎน # return func()#ๅ†ๆ‰ง่กŒๅฆไธ€ไธชๅ‡ฝๆ•ฐ็š„ๅ†…ๅฎน๏ผˆ่ฟ™้‡Œไผ ๅ…ฅ็š„ๆ˜ฏfooๅ‡ฝๆ•ฐ๏ผ‰ # return warppedfunc#่ฟ™ไธช่ฎฉfoo(1,2)ๆ‰ง่กŒไธๆŠฅ้”™,ๅฎƒ็š„ๆ„ไน‰ๅฏ่ƒฝๆ˜ฏๆ‰ง่กŒไธŠไธ€่กŒ็š„ไปฃ็  # return timefun # @timefun_arg("wind")#ๅœจfooๆ‰ง่กŒไน‹ๅ‰๏ผŒๅ…ˆๅˆฉ็”จfoo่ฐƒ็”จ่ฃ…้ฅฐๅ™จๅ‡ฝๆ•ฐ๏ผŒ่ฟ›ๅ…ฅๅˆฐ่ฟ™ไธชๅ‡ฝๆ•ฐ็„ถๅŽๅ†timefun๏ผˆfoo๏ผ‰ # def foo(): # print "-"*30 # return "haha" # @timefun_arg("kid") # def too(): # print "-"*30 # return "wawa" # foo() # sleep(2) # print foo() # too() # sleep(2) # print too() # from time import time,sleep # def logged(when): # def log(f,*args,**kargs): # print "fun:%s args:%r kargs:%r" %(f,args,kargs) # #%rๅญ—็ฌฆไธฒ็š„ๅŒๆ—ถ๏ผŒๆ˜พ็คบๅŽŸๆœ‰ๅฏน่ฑก็ฑปๅž‹ # def pre_logged(f):#ๅ…ˆๅฃฐๆ˜Ž๏ผŒๅฆๅˆ™ๆœ€ไธ‹้ข็š„try่ฏญๅฅไธญ็š„pre_loggedไผšไธๅญ˜ๅœจ # def warpper(*args,**kargs): # log(f,*args,**kargs) #ๅ…ˆๆ‰ง่กŒlog(fun,"wind",x=1,y=2) # return f(*args,**kargs) #ๅŽๆ‰ง่กŒfunๅ‡ฝๆ•ฐๅ†…ๅฎน # return warpper # def post_logged(f):#ๅŒ็† # def warpper(*args,**kargs): # now=time() # try: # return f(*args,**kargs) #ๅ…ˆๆ‰ง่กŒtooๅ‡ฝๆ•ฐๅ†…ๅฎน # finally:#finally่กจ็คบๆ‰ง่กŒ็Žฉtry่ฏญๅฅๅŽ๏ผŒไธ€ๅฎšๆœ€ๅŽๅ†ๆ‰ง่กŒๅ…ถๅ†…ๅฎน # log(f,*args,**kargs) #ๅŽๆ‰ง่กŒlog(too,"kid") # sleep(2) # print "time delta: %s"%(time()-now) # return warpper # try:#ๅ…ˆๆ‰ง่กŒๅ‡ฝๆ•ฐ็š„ๅ†…ๅฎน๏ผˆ็ฌฌไธ€ๆญฅ๏ผ‰ # #่‹ฅwhen็ญ‰ไบŽpre่ฟ”ๅ›žpre_logged,ๅณๆ‰ง่กŒไธŠ้ข็š„pre_loggedๅ‡ฝๆ•ฐ # return {"pre":pre_logged,"post":post_logged}[when] # except KeyError ,e: # raise ValueError(e),'must be "pre" or "post"' # @logged("pre") # def fun(name,x,y): # print "hello,",name # fun("wind",x=1,y=2) # print "-"*30 # @logged("post") # def too(name): # print "hi,",name # too("kid") # import json # class Employee: # a="123" # def __init__(self,name,pay): # self.name=name # self.pay=pay # def hello(self): # print self.name # print "hello" # worker=Employee("wind",100) # worker.hello() # print getattr(worker,'a') # print hasattr(worker,'a') # setattr(worker,'name',"kid") # worker.hello() # print "-"*30 # print Employee.__name__ # print "-"*30 # print Employee.__dict__ # print "-"*30 # print Employee.__doc__ # print "-"*30 # print Employee.__module__ # print "-"*30 # print Employee.__bases__ # class Parent: # a = 100 # def __init__(self): # print "่ฐƒ็”จ็ˆถ็ฑปๆž„้€ ๅ‡ฝๆ•ฐ" # def parentMethod(self): # print "่ฐƒ็”จ็ˆถ็ฑปๆ–นๆณ•" # def setAttr(self,attr): # Parent.a = attr # def getAttr(self): # print "็ˆถ็ฑปๅฑžๆ€ง :",Parent.a # def sayhello(self): # print "i am Parent" # class child(Parent): # def __init__(self):#ๅญ็ฑปไธไผšไธปๅŠจ่ฐƒ็”จ็ˆถ็ฑปๆž„้€ ๆ–นๆณ• # print "่ฐƒ็”จๅญ็ฑปๆž„้€ ๆ–นๆณ•" # def childMethod(self): # print "่ฐƒ็”จๅญ็ฑปๆ–นๆณ•" # def sayhello(self):#ไธŽ็ˆถ็ฑป็š„ๅ‡ฝๆ•ฐ้‡ๅ๏ผŒไผš่ฆ†็›–็ˆถ็ฑป็š„ๅ†…ๅฎน # print "i am child" # c = child() # c.childMethod() # c.parentMethod() # c.sayhello() # c.getAttr() # print "-"*30 # c.setAttr(200) # c.getAttr() # class Animal(object): # def run(self): # print('Animal is running...') # class Dog(Animal): # def run(self): # print('Dog is running...') # def run_twice(animal): # animal.run() # animal.run() # run_twice(Dog()) # class Parent: # __a = 100 # b = 20 # def print_a(self): # print self.__a # @parentmethod # def changeB(cls,newB): # cls.b = newB # p = Parent() # p.print_a() # print p._Parent__a # sum =100 # def fun(): # s1=200 # res=locals() #่ฟ”ๅ›ž่ฟ™ไธชๅ‡ฝๆ•ฐไธญ็š„่Žทๅ–ๅˆฐ็š„ๅฑ€้ƒจๅ˜้‡ # print res # res1 = globals()#่ฟ”ๅ›žๅ…จๅฑ€็š„ๅ˜้‡ # print res1 # fun() # f = open("hello.txt","r+") # #r ๅช่ฏป # #w ๅชๅ†™๏ผŒๆ–‡ไปถๅญ˜ๅœจ๏ผŒๅˆ™่ฆ†็›–ๅ†…ๅฎน๏ผŒๆ–‡ไปถไธๅญ˜๏ผŒๅˆ™ๆ–ฐๅปบ๏ผˆๆœ€ๅฅฝไธ่ฆ็”จw๏ผ‰ # #a ่ฟฝๅŠ ๅ†™ # #r+ ่ฏปๅ†™ๆ–นๅผๆ‰“ๅผ€ๆ–‡ไปถ # #w+ ๅฏ่ฏปๅฏๅ†™ๆ–‡ไปถ๏ผŒๆ–‡ไปถๅญ˜ๅœจ๏ผŒๅˆ™่ฆ†็›–ๅ†…ๅฎน๏ผŒๆ–‡ไปถไธๅญ˜๏ผŒๅˆ™ๆ–ฐๅปบ # #a+ ่ฟฝๅŠ ๆ‰“ๅผ€ๆ–‡ไปถ๏ผŒๅฏ่ฏปๅฏๅ†™๏ผŒๅฆ‚ๆžœๆ–‡ไปถไธๅญ˜ๅœจ๏ผŒๅˆ™ๅˆ›ๅปบ # print f.mode # print f.name # print f.closed#ๅˆคๆ–ญๆ–‡ไปถๆ˜ฏๅฆๅ…ณ้—ญไบ† # print '-'*30 # f.close() # print f.closed # myPath = "./" # fontPath = "./" # inputFile = "test.JPG" # outputFil = "output.jpg" # from PIL import Image,ImageFont,ImageDraw # im = Image.open(myPath + inputFile)#ๆ‰“ๅผ€ๅ›พ็‰‡ # draw = ImageDraw.Draw(im)#็”ปๅ‡บๅ›พ็‰‡ # fontsize = min(im.size)/4 # print im # print im.size # print im.size[0] # print fontsize # font = ImageFont.truetype(fontPath + "GasinamuNew.ttf", fontsize)#.ttfๆ˜ฏๅญ—ไฝ“ๅบ“็š„ไธœ่ฅฟ๏ผŒ้œ€่ฆๅฆๅค–ๆ‰พ็š„ # draw.text((im.size[0]-fontsize,0), '8',font = font ,fill = (256,256,0))#8ไปฃ่กจๆ˜พ็คบ็š„ๆ•ฐๅญ—๏ผŒfill้ขœ่‰ฒ๏ผŒ็ฌฌไธ€ไธชๅ‚ๆ•ฐๆ˜ฏไฝ็ฝฎ # im.save(myPath + outputFil,"jpeg") # import string, random # filed = string.letters + string.digits#ๅญ—ๆฏๅŠ ๆ•ฐๅญ— # def getRandom():#่Žทๅพ—ๅ››็ป„ๅญ—ๆฏๅ’Œๆ•ฐๅญ—็š„้šๆœบ็ป„ๅˆ # return "".join(random.sample(filed,3)) # def concatenate(group):#็”Ÿๆˆ็š„ๆฏไธชๆฟ€ๆดป็ ไธญๆœ‰ๅ‡ ็ป„ # return "-".join([getRandom() for i in range(group)]) # def generate(n):#็”Ÿๆˆn็ป„ๆฟ€ๆดป็  # return [concatenate(4) for i in range(n)] # if __name__ == '__main__':#ๅ•็‹ฌๆ‰ง่กŒๆ‰ไผš่ฟ่กŒprint๏ผŒๅฆๅˆ™ไธไผš่ฟ่กŒ # print generate(5) # import re,os # from collections import Counter # # FileSource = "./music.txt" # File_Path = "./again" # def getCounter(articlefilesource): # pattern = r'''[A-Za-z]+|\$?\d+%?$'''#ๅญ—ๆฏๆ ผๅผ๏ผŒ # with open(articlefilesource) as f: # r = re.findall(pattern,f.read()) # return Counter(r) # #่ฟ‡ๆปค่ฏ # stop_word = ['the','in','of','and','to','has','that','s','is','are','a','with','as','an'] # def run(File_Path): # os.chdir(File_Path)#ๅˆ‡ๆขๅˆฐ็›ฎๆ ‡ๆ–‡ไปถๆ‰€ๅœจ็›ฎๅฝ• # total_counter = Counter()#้ๅކ่ฏฅ็›ฎๅฝ•ไธ‹็š„txtๆ–‡ไปถ # for i in os.listdir(os.getcwd()): # print os.path.splitext(i) # if os.path.splitext(i)[1] == '.txt': # total_counter += getCounter(i) # #ๆŽ’้™คstopword็š„ๅฝฑๅ“ # for i in stop_word: # total_counter[i]=0 # print total_counter.most_common() # print total_counter.most_common()[0:3] # if __name__ == '__main__': # run(File_Path) # import os # from PIL import Image # myPath = "./" # outPath= "./photo/" # def processImage(filesource,destsource,name,imgtype): # imgtype = 'jpeg' if imgtype == ".jpg" else 'png' # im = Image.open(filesource + name) # rate = max(im.size[0]/640 if im.size[0] > 640 else 0,im.size[1]/1130 if im.size[1] > 1130 else 0) # print rate#็ผฉๆ”พๆฏ”ไพ‹ # if rate: # im.thumbnail((im.size[0]/rate,im.size[1]/rate)) # im.save(destsource + name,imgtype) # def run(): # os.chdir(myPath) # for i in os.listdir(os.getcwd()): # postfix = os.path.splitext(i)[1]#ๆฃ€ๆŸฅๅŽ็ผ€ # if postfix == '.jpg' or postfix == '.png': # processImage(myPath,outPath,i,postfix) # if __name__ == '__main__': # run() # import os,re # File_Path = "./" # def analyze_code(codefilesource): # total_line = 0 # comment_line = 0 # blank_line = 0 # with open(codefilesource) as f: #็›ธๅฝ“ไบŽf = open(codefilesource) # lines = f.readlines() # total_line = len(lines) # line_index = 0 # while line_index < total_line:#้ๅކๆฏไธ€่กŒ # line = lines[line_index] # if line.startswith("#"):#ๆณจ้‡Š่กŒๆ•ฐ # comment_line += 1 # elif re.match("\s*'''",line) is not None: # comment_line += 1 # while re.match(".*'$'''",line) is None: # line = lines[line_index] # comment_line += 1 # line_index += 1 # elif line == "\n":#็ฉบ่กŒ # blank_line +=1 # line_index +=1 # print "ๅœจ%sไธญ:"%codefilesource # print "ไปฃ็ ่กŒๆ•ฐ:",total_line # print "ๆณจ้‡Š่กŒๆ•ฐ:",comment_line,"ๅ %0.2f%%"%(comment_line*100.0/total_line) # print "็ฉบ่กŒๆ•ฐ:",blank_line,"ๅ %0.2f%%"%(blank_line*100.0/total_line) # return [total_line,comment_line,blank_line] # def run(File_Path): # os.chdir(File_Path) # total_lines = 0 # total_comment_lines = 0 # total_blank_lines = 0 # for i in os.listdir(os.getcwd()): # if os.path.splitext(i)[1] == '.py': # line = analyze_code(i) # total_lines,total_comment_lines,total_blank_lines = total_lines + line[0],total_comment_lines+line[1],total_blank_lines+line[2] # print "ๆ€ปไปฃ็ ่กŒๆ•ฐ:",total_lines # print "ๆ€ปๆณจ้‡Šๆ•ฐ:",total_comment_lines,"ๅ %0.2f%%"%(total_comment_lines*100.0/total_lines) # print "ๆ€ป็ฉบ่กŒๆ•ฐ:",total_blank_lines,"ๅ %0.2f%%"%(total_blank_lines*100.0/total_lines) # if __name__ == '__main__': # run(File_Path) from goose import Goose from goose.text import StopWordsChinese import sys reload(sys) sys.setdefaultencoding("utf-8") url ='https://linux.cn/article-6717-1.html' def extract(url): g= Goose({'stopwords_class':StopWordsChinese}) article = g.extract(url=url) return article.cleaned_text if __name__ == '__main__': print extract(url) from PIL import Image,ImageDraw,ImageFont,ImageFilter import string,random fontPath = "./" def getRandomChar():#่Žทๅพ—้šๆœบๅ››ไธชๅญ—ๆฏ+ๆ•ฐๅญ— return [random.choice(string.letters + string.digits) for _ in range(4)] def getRandomColor():#่Žทๅพ—้ขœ่‰ฒ return (random.randint(30,100),random.randint(30,100),random.randint(30,100)) def getCodePicture():#่Žทๅ–้ชŒ่ฏ็ ๅ›พ็‰‡ width = 240 height= 60 #ๅˆ›ๅปบ็”ปๅธƒ image = Image.new('RGB',(width,height),(180,180,180)) font = ImageFont.truetype(fontPath + "GasinamuNew.ttf",40) draw = ImageDraw.Draw(image) #ๅˆ›ๅปบ้ชŒ่ฏ็ ๅฏน่ฑก code = getRandomChar() for t in range(4): draw.text((60*t +10,0),code[t],font=font,fill=getRandomColor()) #ๅกซๅ……ๅ™ช็‚น for _ in range(random.randint(1500,3000)): draw.point((random.randint(0,width),random.randint(0,height)),fill=getRandomColor()) #ๆจก็ณŠๅค„็† image = image.filter(ImageFilter.BLUR) #ไฟๅญ˜ๆ–‡ไปถ image.save("./photo/"+"".join(code)+'.jpg','jpeg') if __name__ == '__main__': getCodePicture() import requests import re url = r'http://www.renren.com/ajaxLogin/login' user = {'email':'username','password':'passwd'}#ๆณจๅ†Œไธ€ไธช่ดฆๅท๏ผŒๆ‰ไผšๆœ‰ๆ•ฐๆฎๆ˜พ็คบ s = requests.Session() r = s.post(url,data=user) html = r.text visit = [] first = re.compile(r'</span><span class="time-tip first-tip"><span class="tip-content">(.*?)</span>') second = re.compile(r'</span><span class="time-tip"><span class="tip-content">(.*?)</span>') third = re.compile(r'</span><span class="time-tip last-second-tip"><span class="tip-content">(.*?)</span>') last = re.compile(r'</span><span class="time-tip last-tip"><span class="tip-content">(.*?)</span>') visit.extend(first.findall(html)) visit.extend(second.findall(html)) visit.extend(third.findall(html)) visit.extend(last.findall(html)) for i in visit: print i print "ไปฅไธ‹ๆ˜ฏๆ›ดๅคš็š„ๆœ€่ฟ‘้‡‡่ฎฟ" vm = s.get('http://www.renren.com/myfoot/whoSeenMe') fm = re.compile(r'"name":"(.*?)"') visitmore = fm.findall(vm.text) for i in visitmore: print i # files = {'file':open('1.jpg','rb')}#rbไบŒ่ฟ›ๅˆถ # r = requests.post("http://httpbin.org/post",files = files) # print r.url # print r.text # import json # mydata = {'name':'wind','age':'24'} # r = requests.post("http://httpbin.org/post",data = json.dumps(mydata)) # print r.url # print r.text # { # "args":{}, # "data":"{\"name\":\"wind\",\"age\":\"24\"}", # "files":{},#ไธŠไผ ๆ–‡ไปถ # "from":{}, # "headers":{ # "Accept":"*/*", # "Accept-Encoding":"gzip,deflate,compress", # "Content-Length":"30", # "Content-Type":"application/x-www-form-urlencoded", # "Host":"httpbin.org", # "User-Agent":"python-requests/2.2.1 CPython/2.7.6 Linux/3.16.0-30-generic" #ไฝฟ็”จ็š„ๅ‘ฝไปค # }, # "json":{ # "name":"wind", # "age":"24" # }, # "origin":"61.148.201.2", # "url":"http://httpbin.org/post" # } # myparams= {"name":"wind"} # r = requests.get('https://www.baidu.com',params=myparams)#ๅ‰้ข้‚ฃไธชๅบ”่ฏฅๆ˜ฏ็ฝ‘ๅ€ๅคด # print r.url # print r.content # r = requests.get('http://httpbin.org/get') # r = requests.get('http://c.itcast.cn') # print r.text#ๅ‘ๅ‡บๅŽป็š„ๅ†…ๅฎน # print r.content #ๆ”ถๅˆฐ็š„ๅ†…ๅฎน # print r.url # { # "args":{}, # "headers":{ # "Accept":"*/*", # "Accept-Encoding":"gzip,deflate,compress", # "Host":"httpbin.org", # "User-Agent":"python-requests/2.2.1 CPython/2.7.6 Linux/3.16.0-30-generic" #ไฝฟ็”จ็š„ๅ‘ฝไปค # }, # "origin":"61.148.201.2", # "url":"http://httpbin.org/get" # }
import gc class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head temp=self.head if self.head is not None: while(temp.next!=self.head): temp=temp.next temp.next = new_node else: new_node.next = new_node self.head = new_node def delete(self, key): temp = self.head if temp is None: return if(temp.data == key): while(temp.next != self.head): temp=temp.next temp.next = self.head.next self.head = self.head.next return while(temp is not None): if(temp.next.data == key): break temp = temp.next next = temp.next.next temp.next = next gc.collect() def printlist(self): temp = self.head while(self.head is not None): print(temp.data) temp = temp.next if(temp == self.head): break cll = CircularLinkedList() cll.push(4) cll.push(3) cll.push(2) cll.push(1) print("created linked list is:") cll.printlist() cll.delete(3) print("modified linked list is:") cll.printlist()
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self,new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insertAfter(self,prev_node,new_data): if prev_node is None: print("the given previous node is not in given linkedlist") return new_node = Node(new_data) new_node.next = prev_node.next prev_node.next = new_node def append(self,new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last=self.head while(last.next): last = last.next last.next = new_node def printlist(self): temp = self.head while(temp): print(temp.data,end=' ') temp = temp.next print() def pairWiseSwap(head): # code here if head is None: return temp = head while temp and temp.next: first = temp.data second = temp.next.data temp.data = second temp.next.data = first temp = temp.next.next # return head if __name__=='__main__': llist = LinkedList() llist.append(6) llist.push(7) llist.push(1) llist.append(4) llist.insertAfter(llist.head.next, 8) n = 5 print("Original linked list is: ") llist.printlist() pairWiseSwap(llist.head) print('new linked list is: ') llist.printlist()
#print("hello world") --------------------------------------------------------------- #my_message = "Hello Aabhar" #print(my_message) --------------------------------------------------------------- #message = "hello Aabhar" #print(message[0:5]) #print string from 0 to 4th index (but not 5th index) #print(message[:5]) #print from starting to 4th index #print(message[6:]) #print string from 6th index to end --------------------------------------------------------------- #message = "Hello World" #print(message.lower()) #print(message.upper()) #print(message.count('l')) #print(message.find('Universe')) #finding from which index this word is starting {if its -1 then it doesnt exist} -------------------------------------------------------------- #message = "Hello World" #new_message = message.replace('World', 'Aabhar') #print(message) #print(new_message) --------------------------------------------------------------- #greeting = 'Hello' #name = 'Aabhar' #message = greeting + ', ' + name + '. Welcome!' #message = f'{greeting}, {name.upper()} Welcome!' #print(message) --------------------------------------------------------------- greeting = 'Hello' name = 'Aabhar' print(help(str.lower)) #print(dir(name))
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Add Digits https://leetcode.com/problems/add-digits/ Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. ''' # Solution1: loop def turnNumAsList(num): tmpStr = str(num) i = 0 retList = [] for i in range(0,len(tmpStr)): retList.append(int(tmpStr[i])) i += 1 return retList def addDigitLoop(num): tmpNum = num while tmpNum >= 9: tmpNum = sum(turnNumAsList(tmpNum)) return tmpNum # Solution2: recursive def addDigitRecursive(num): if num <= 9: return num tmpList = turnNumAsList(num) return addDigitRecursive(sum(tmpList)) # Solution: O(1) def addDigit(num): return num if num <=9 else num % 9 # if num <= 9: # return num # else: # return num % 9 # print "8:", addDigitLoop(8) print "38:", addDigitLoop(38) print "138:", addDigitLoop(138) print "8:", addDigitRecursive(8) print "38:", addDigitRecursive(38) print "138:", addDigitRecursive(138) print "8:", addDigit(8) print "38:", addDigit(38) print "138:", addDigit(138)
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Two Sum: https://leetcode.com/problems/two-sum/ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. ''' class Solution_first(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: break if nums[i] + nums[j] == target: break return [i,j] class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): try: for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: raise StopIteration except StopIteration: break return [i,j] mySolution = Solution() import unittest class TestSolution_twoSum(unittest.TestCase): def test_twoSum(self): self.assertEqual(mySolution.twoSum([3,2,4],6), [1,2]) self.assertEqual(mySolution.twoSum([3,2,4],7), [0,2]) suite = unittest.TestLoader().loadTestsFromTestCase(TestSolution_twoSum) unittest.TextTestRunner(verbosity=2).run(suite)
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 67. Add Binary https://leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". ''' class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ if len(a) > len(b): b = '0' *(max(len(a),len(b)) - min(len(a),len(b))) + b else: a = '0' *(max(len(a),len(b)) - min(len(a),len(b))) + a aList, bList = list(a), list(b) carryBit, rList = 0, [] posBit = -1 while abs(posBit) <= len(aList): bitSum = int(aList[posBit]) + int(bList[posBit]) + carryBit if bitSum == 3: rList.append('1') carryBit = 1 elif bitSum == 2: rList.append('0') carryBit = 1 elif bitSum == 1: rList.append('1') carryBit = 0 elif bitSum == 0: rList.append('0') carryBit = 0 posBit = posBit - 1 if carryBit == 1: rList.append('1') rList.reverse() rStr = '' for i in rList: rStr += i return rStr def myUnitTest(self, a, b): return Solution.addBinary(self, a, b) mySolution = Solution() mySolution.myUnitTest("11","1") import unittest class Test_Solution_myUnitTest(unittest.TestCase): def test_myUnitTest(self): self.assertEqual(mySolution.myUnitTest("11","1"), "100") self.assertEqual(mySolution.myUnitTest("11","11"), "110") self.assertEqual(mySolution.myUnitTest("100","10"), "110") suite = unittest.TestLoader().loadTestsFromTestCase(Test_Solution_myUnitTest) unittest.TextTestRunner(verbosity=2).run(suite)
""" This script is meant to find duplicate files in a directory and subdirectories via md5 checksums Any collisions found are listed. Collisions are any two files with the same md5 hash value. """ from hashlib import md5 import os rootDir="/home/user/Music/" renamedCount = 0 fileDict = {} collisions=0 targetPercent=10 #returns an md5 hash of a file - found at https://gist.github.com/Jalkhov def getMD5Hash(fname): hashObj = md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hashObj.update(chunk) return hashObj.hexdigest() #returns a string list of file paths for all files in a directory and its subdirectories - refer to os.walk(dir) def get_filepaths(directory): file_paths = [] # List which will store all of the full filepaths. # Walk the tree. for root, _, files in os.walk(directory): for filename in files: # Join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) file_paths.append(filepath) # Add it to the list. return file_paths filePaths = get_filepaths(rootDir) #root directory to search #exit if 1 or 0 files exist in directory if len(filePaths)>1: print("%i files found in %s\nPopulating dictionary. This may take a while."%(len(filePaths),rootDir)) else: print("Too few files in directory") exit() #iterate over the string list of file paths and populates a hashtable for i,filepath in enumerate(filePaths): #add some visual feedback percent = int(100*float(i)/len(filePaths)) if percent>=targetPercent: targetPercent+=10 print("%s%% processed"%percent) #populate hash table key = getMD5Hash(filepath) if key in fileDict.keys(): #add to a pre-existing list fileDict[key].append(filepath) collisions+=1 else: #create a new list under the key fileDict[key]=[filepath] #list collisions if any (collisions will be any list in our hashtable greater than size 1) print("%i collisions found:"%collisions) if collisions>1: collisions=0 #recycle this variable for fList in fileDict.values(): if len(fList)>1: collisions+=1 print(collisions) for duplicate in fList: print("\t"+duplicate) print("Finished.")
\Lists: Complexity Operation | Example | Class | Notes --------------+--------------+---------------+------------------------------- 'Index' | l[i] | O(1) | 'Store' | l[i] = 0 | O(1) | 'Length' | len(l) | O(1) | 'Append' | l.append(5) | O(1) | 'Pop' | l.pop() | O(1) | same as l.pop(-1), popping at end 'Clear' | l.clear() | O(1) | similar to l = [] 'Slice' | l[a:b] | O(b-a) | l[1:5]:O(l)/l[:]:O(len(l)-0)=O(N) 'Extend' | l.extend(...)| O(len(...)) | depends only on len of extension 'Construction' | list(...) | O(len(...)) | depends on length of ... 'check ==, !=' | l1 == l2 | O(N) | 'Insert' | l[a:b] = ... | O(N) | 'Delete' | del l[i] | O(N) | 'Remove' | l.remove(...)| O(N) | 'Containment' | x in/not in l| O(N) | searches list 'Copy' | l.copy() | O(N) | Same as l[:] which is O(N) 'Pop' | l.pop(i) | O(N) | O(N-i): l.pop(0):O(N) (see above) 'Extreme value' | min(l)/max(l)| O(N) | searches list 'Reverse' | l.reverse() | O(N) | 'Iteration' | for v in l: | O(N) | 'Sort' | l.sort() | O(N Log N) | key/reverse mostly doesn't change 'Multiply' | k*l | O(k N) | 5*l is O(N): len(l)*l is O(N**2) \Sets: Complexity Operation | Example | Class | Notes --------------+--------------+---------------+------------------------------- 'Length' | len(s) | O(1) | 'Add' | s.add(5) | O(1) | 'Containment' | x in/not in s| O(1) | compare to list/tuple - O(N) 'Remove' | s.remove(5) | O(1) | compare to list/tuple - O(N) 'Discard' | s.discard(5) | O(1) | 'Pop' | s.pop(i) | O(1) | compare to list - O(N) 'Clear' | s.clear() | O(1) | similar to s = set() \Dictionaries: dict and defaultdict Complexity Operation | Example | Class | Notes --------------+--------------+---------------+------------------------------- 'Index' | d[k] | O(1) | 'Store' | d[k] = v | O(1) | 'Length' | len(d) | O(1) | 'Delete' | del d[k] | O(1) | 'get/setdefault'| d.method | O(1) | 'Pop' | d.pop(k) | O(1) | 'Pop item' | d.popitem() | O(1) | 'Clear' | d.clear() | O(1) | similar to s = {} or = dict() 'Views' | d.keys() | O(1) |
def getFactors (n): result = [] temp = [] getResult(n, 2, temp, result) return result def getResult(num, start, currentResult, finalResult): import copy if (num == 1): if (len(currentResult) > 1): # x= copy.deepcopy() finalResult.append(currentResult[:]) #<------- importatn for deep copy !! return for i in range(start, num+1): if (num%i == 0): currentResult.append(i) getResult(num//i, i, currentResult, finalResult) currentResult.pop() print(getFactors(12))
class LinkedList: def __init__(self, val= None, next = None): self.val = val self.next = next def print_list(self): node = self r='' while node: r+= str(node.val) node = node.next if node: r += "-->" print(r) def remove_elements_greater_than_k(self, k): node = self prev = None while node: print(node.val, prev.val) if node.val > k: prev.next = node.next else: prev = node node = node.next if __name__=="__main__": # t e s t c a s e I # 1-->2-->3-->4-->5 k = 3 l6 = LinkedList(6) l5 = LinkedList(5,l6) l4 = LinkedList(4,l5) l3 = LinkedList(3, l4) l2 = LinkedList(2,l3) l1 = LinkedList(1,l2) l1.print_list() l1.remove_elements_greater_than_k(3) l1.print_list() # t e s t c a s e II # #10-->2-->32-->4-->5 k = 5 # # l1 = LinkedList(10,LinkedList(2,LinkedList(32,LinkedList(4,LinkedList(5))))) # l1.print_list() # l1.remove_elements_greater_than_k(5) # l1.print_list()
p = [0,1,2,3,4,5,6,7] def findCelebrity(self, n): x = 0 for i in xrange(n): if knows(x, i): x = i if any(knows(x, i) for i in xrange(x)): return -1 if any(not knows(i, x) for i in xrange(n)): return -1 return x ''' The first loop is to exclude n - 1 labels that are not possible to be a celebrity. After the first loop, x is the only candidate The second and third loop is to verify x is actually a celebrity by definition. The key part is the first loop. To understand this you can think the knows(a,b) as a a < b comparison, if a knows b then a < b, if a does not know b, a > b. Then if there is a celebrity, he/she must be the "maximum" of the n people. ''' int x = 0 for (int i = 0; i < n; ++i) if (knows(x, i)) x = i; for (int i = 0; i < x; ++i) if (knows(x, i)) return -1; for (int i = 0; i < n; ++i) if (!knows(i, x)) return -1; return x
# dfs + stack # def binaryTreePaths1(self, root): # if not root: # return [] # res, stack = [], [(root, "")] # while stack: # node, ls = stack.pop() # if not node.left and not node.right: # res.append(ls+str(node.val)) # if node.right: # stack.append((node.right, ls+str(node.val)+"->")) # if node.left: # stack.append((node.left, ls+str(node.val)+"->")) # return res # # nums = [2, 7, 11, 15] # target = 9 # # diff_map = {} # # for i in range(len(nums)): # diff = target - nums[i] # if diff in diff_map: # print("!")3[diff_map[diff],i]) # else: # diff_map[diff] = i # # print(diff_map)
import collections class simple_graph: def __init__(self): self.edges = {} def neighbours(self, vertex): return self.edges[vertex] class Queue: def __init__(self): self.elements = collections.deque() def empty(self): return len(self.elements)==0 def put(self, x): self.elements.append(x) def get(self): return self.elements.popleft() def dump(self): print(self.elements) def BFS(graph, start, goal=None): frontier = Queue() frontier.put(start) visited = {} visited[start] = True while not frontier.empty(): frontier.dump() #1 pop from queuee current = frontier.get() print("Visiting " + current) if current == goal: break for next in graph.neighbours(current): if next not in visited: frontier.put(next) visited[next] = True print("------------------") if __name__=="__main__": g = simple_graph() g.edges = { 'A' : ['B'], 'B' : ['A', 'C', 'D'], 'C' : ['A'], 'D' : ['E', 'A'], 'E' : ['B'] } BFS(g, 'A') #without target print("\n\n\n") BFS(g, 'A' , 'C') #with target
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } survey = ['jen','sarah','ellen','phil'] for person in favorite_languages: if person in survey: print('Thank you for accepting my survey, '+person.title()+'!') else: print('Would you like to take my survey, '+ person.title()+'?')
import numpy as np import matplotlib.pyplot as plt import random from math import exp from sys import exit def main(): numberOfIteration = int(input("How many iteration do you want?")) learningRate = float(input("What learning rate do you want?")) #I shuffled the data x = np.loadtxt('dataTrain.csv', delimiter=',',skiprows=1, dtype=int) np.random.shuffle(x) #64 features and label matrixes dataset = x[:,:64] labels = x[:,64:65] inputNumber = len(dataset[0]) outputNumber = len(labels) #Initialize the multilayer model, hidden layer number is 10 network = initialize_network(inputNumber, 10, 10) #Train network with 0.1 learning rate and 20 loops train_network(network, x, learningRate, numberOfIteration, 10) true = 0 false = 0 for row in x: prediction = predict(network, row) if row[-1] == prediction: true+=1 else: false += 1 print("Accuracy = ", true*100/(true+false) ,"%") def initialize_network(n_inputs, n_hidden, n_outputs): #Create dictionary network = list() # For hidden layer weights add realy small weights hidden = [{'w':[random.uniform(-0.1, 0.1) for i in range(n_inputs + 1)]} for i in range(n_hidden)] network.append(hidden) # For output layer weights add realy small weights output = [{'w':[random.uniform(-0.1, 0.1) for i in range(n_hidden + 1)]} for i in range(n_outputs)] network.append(output) return network def predict(network, test): outputs = forward(network, test) return outputs.index(max(outputs)) #Predict as it belongs class with biggest probability # Sigmoid function for activation of the neuron def sigmoid(x): if x<0: a = exp(x) return a / (1 + a) else: return 1 / (1 + exp(-x)) #Derivation of the sigmoid function def sigmoid_derivative(x): return x * (1.0 - x) # Calculate sum of activations of the neurons by using weights def activation(weights, data): sumOfProduct = weights[-1] #Last weight for i in range(len(weights)-1): sumOfProduct += weights[i] * data[i] # weight*data return sumOfProduct # Calculate the outputs of the each neurons with new weights def forward(network, row): inputs = row for i in network: modifiedVals = [] for j in i: j['out'] = sigmoid (activation(j['w'], inputs)) modifiedVals.append(j['out']) inputs = modifiedVals return inputs def backward_propagate_error(network, expected): for i in reversed(range(len(network))): layer = network[i] errors = list() #len deฤŸeri printle if i != len(network)-1: for j in range(len(layer)): error = 0.0 for neuron in network[i + 1]: error += (neuron['w'][j] * neuron['deltaw']) errors.append(error) #Error of neuron else: for j in range(len(layer)): neuron = layer[j] errors.append(expected[j] - neuron['out']) for j in range(len(layer)): neuron = layer[j] neuron['deltaw'] = errors[j] * sigmoid_derivative(neuron['out']) # Error that multiplied by sigmoid derivative # Update network weights with error # It doesn't return anything since it directly updates the dictionary def update_weights(network, row, l_rate): for i in range(len(network)): inputs = row[:-1] if i != 0: inputs = [j['out'] for j in network[i - 1]] for j in network[i]: for k in range(len(inputs)): j['w'][k] += l_rate * j['deltaw'] * inputs[k] j['w'][-1]+= l_rate * j['deltaw'] def train_network(network, train, l_rate, iterations, n_outputs): for iteration in range(iterations): # For number of iterations that user want sum_error = 0 for row in train: outputs = forward(network, row) expected = [0 for i in range(n_outputs)] expected[row[-1]] = 1 # Make bias unit as 1 sum_error -= sum([ expected[i]*np.log(outputs[i]) for i in range(n_outputs)]) # Cross entropy for error backward_propagate_error(network, expected) # According to the error update_weights(network, row, l_rate) if iteration <= 9 or iteration == 49 or iteration==99 or iteration == 199 : print("Iteration", iteration+1 , "Cross entropy error : " , sum_error) main()
## Training using the Perceptron implementation in scikit-learn, as described ## in Python Machine Learning (pg 50), by Sebastian Raschka. from moldata import * ## Data prep. trainset1 = Molset(100, 'C', 20) print(trainset1.X) print(trainset1.y) print([(len(trainset1.X), len(trainset1.X[0])), len(trainset1.y)]) ## Training. # Split the data. from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( trainset1.X, trainset1.y, test_size=0.3, random_state=0) # Standardize the data to a normal distribution. from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) # Train on the standardized data. from sklearn.linear_model import Perceptron ppn = Perceptron(n_iter=40, eta0=0.1, random_state=0) ppn.fit(X_train_std, y_train) # Apply the trained network to the standardized test data and print metrics. y_pred = ppn.predict(X_test_std) print('Misclassified samples: %d' % (y_test != y_pred).sum()) from sklearn.metrics import accuracy_score print('Accuracy: %.3f' % accuracy_score(y_test, y_pred)) ## Plotting import matplotlib.pyplot as plt
# P3.40 # get cost input cost = int(input("Please enter the cost of your groceries: $")) if(10 <= cost <= 60): coupon = 8 elif(60 < cost <= 150): coupon = 10 elif(150 < cost <= 210): coupon = 12 elif(210 < cost): coupon = 14 else: coupon = 0 if(coupon == 0): print("You do not win a coupon.") else: discount = str(round(cost * (coupon * 0.01), 2)) print("You win a discount coupon of $" + discount + " (" + str(coupon) + "% of your purchase)")
# # Python File Write # # To write to an existing file, you must add a parameter to the open() function: # # 1. "a" - Append - will append to the end of the file # # 2. "w" - Write - will overwrite any existing content (That means will delete the previous content and add new lines. a = "Open the file Hello.txt and append content to the file\n" print(a) # # open and write to the file. f = open("C://Users/DOLPHIN-PC/PycharmProjects/Python_Learning/Sample/Hello1.txt", "a") f.write("\nNew line added\n") f.close() # #open and read the file f = open("C://Users/DOLPHIN-PC/PycharmProjects/Python_Learning/Sample/Hello1.txt") print(f.read()) b = "\nOpen the file Hello.txt and overwrite the content:\n" print(b) # Open and write f = open("C://Users/DOLPHIN-PC/PycharmProjects/Python_Learning/Sample/Hello1.txt", "w") f.write("Oops, deleted all previous content mistakenly.") f.close() # # open and read f = open("C://Users/DOLPHIN-PC/PycharmProjects/Python_Learning/Sample/Hello1.txt") print(f.read())
'''Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.''' x= 5 y = "Jhon" print(x) print(y) '''Casting If you want to specify the data type of a variable, this can be done with casting.''' x = str(3) y = int(3) z = float(3) print(x) print(y) print(z) '''Get the Type You can get the data type of a variable with the type() function.''' x = 5 y = "Jhon" z = 3.45 print(type(x)) print(type(y)) print(type(z)) '''Variables name can only be (A-z, 0-9, and _ )''' myvar = "My " my_var = "name " myvar1 = "is " _my_var = "Grace " MYVAR = "Joydhar." print(myvar + my_var + myvar1 + _my_var + MYVAR) '''Multiple Values: Must use comma(,) in between values''' x,y,z = "Banana", "Orange", "Apple" print(x) print(y) print(z) #One value to multiple variables x = y = z = "Orange" print(x) print(y) print(z) #Unpack Collections fruits = ["apple", "orange", "banana"] x, y, z = fruits print(x) print(y) print(z) #Output Variables: We need to add + before the varriable x= "awesome" print("python is " +x) #Also we can add two variables using + x = "Python is " y = "Awesome." z = x+y print(z) #Local and Global Variables: Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. But if we write global with a variable, that will be used in anywhere in your code and it will remain same. #Local Variable outside a function x = "Lovely" def myfunction(): print("python is " +x) myfunction() #Local Variable inside a function def myfunc(): x = "Beauty" print("Python is " +x) myfunc() #Local variable inside and outside a function y= "do work" def myfunc1(): y = "think" print("People love to " + y) myfunc1() print("People love to " + y) #Global Variable def myfunc2(): global x x= "Love" print("Bangladesh is a place of " + x) myfunc2() print("Bangladesh is a place of " + x) '''Also, use the global keyword if you want to change a global variable inside a function.''' x = "Awesome" def myfunc3(): global x x = "beautiful" myfunc3() print("Bangladesh is " + x)
a = 5 b = 10 a,b = b,a '''temp = a a = b b = temp''' print(a) print(b) '''a = int(input("Enter a value: ")) b = int(input("Enter a value: ")) temp = a a = str(b) #10 b = str(temp) #5 print("A is: " + a) print("B is: " + b)'''
import sys a = "Tuple is a collection which is odered but unchangeable.\nThat means there is no option to add or remove data directly from the array. But we can put duplicate values" print(a) tuple = (1, (2,3,4),5, 6,7) print('tuple', sys.getsizeof(tuple)) #Memory requirement low print(tuple) '''del tuple #For Delete the array. print(tuple)''' list = [1, [2,3,4],5, 6,7] print('list', sys.getsizeof(list)) #Memory requirement high print(list)
from numpy import * a= "2D array:" print(a) arr1 = array([ [1, 2, 3, 4, 9, 2], [5, 6, 7, 8, 4, 1] ]) print("Array 1 is: ", arr1) print("Datatype of Array1: ", arr1.dtype) print("Dimension of Array1 :", arr1.ndim) print("Shape of Array1 : ", arr1.shape) b = "\n2D to 1D Array" print(b) arr2 = arr1.flatten() print(arr2) print("Datatype of Array2: ", arr2.dtype) print("Dimension of Array2 :", arr2.ndim) print("Shape of Array2 : ", arr2.shape) c = "\n1D to 2D Array" print(c) arr3 = arr2.reshape(3, 4) print(arr3) print("Datatype of Array3: ", arr3.dtype) print("Dimension of Array3 :", arr3.ndim) print("Shape of Array3 : ", arr3.shape) d = "\n2D to 3D Array" print(d) arr4 = arr1.reshape(3, 2, 2) print(arr4) print("Datatype of Array4: ", arr4.dtype) print("Dimension of Array4 :", arr4.ndim) print("Shape of Array4 : ", arr4.shape) e = "\n2D to 3D Array - Practice" print(e) arr5 = array([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]) arr6 = arr5.reshape(3, 2, 3) print(arr6)
from string import ascii_lowercase, ascii_uppercase def rotate(text, offset): new_lowercase = ascii_lowercase[offset:] + ascii_lowercase[:offset] new_uppercase = ascii_uppercase[offset:] + ascii_uppercase[:offset] translation = str.maketrans(ascii_lowercase + ascii_uppercase, new_lowercase + new_uppercase) return text.translate(translation)
def verify(isbn): count = 0 total = 0 for ch in isbn: if count <= 9 and ch.isdigit(): total += int(ch) * (10 - count) count += 1 elif count == 9 and ch == 'X': total += 10 count += 1 elif ch == '-': pass else: return False return count == 10 and not total % 11
from random import choice from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if key == None: self.key = ''.join(choice(ascii_lowercase) for _ in range(100)) elif key.isalpha() and key.islower(): self.key = key else: raise ValueError def encode(self, msg): ciphertext = '' for i, c in enumerate(msg.lower()): if c.isalpha(): new_ord = ord(c) + ord(self.key[i % len(self.key)]) - ord('a') ciphertext += chr(new_ord - 26 if new_ord > ord('z') else new_ord) return ciphertext def decode(self, msg): plaintext = '' for i, c in enumerate(msg): new_ord = ord(c) - ord(self.key[i % len(self.key)]) + ord('a') plaintext += chr(new_ord + 26 if new_ord < ord('a') else new_ord) return plaintext class Caesar(Cipher): def __init__(self): super().__init__('d')
#Gabriel Abraham #notesonartificialintelligence #printing out the value in a range, this time with a set increment even_numbers = list(range(2,11,2)) print(even_numbers) #A list will be created with value between 2 and 10. The third argument in range is the value of the increment to be followed. #The program will go though the value of 2 to 10 in increments of 2
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 9 #Write a class admin that inherits from the user class. from users import Users from privileges import Privileges class Admin(Users): """A simple admin class""" def __init__(self, first_name, last_name, age): """Initialise attributes of the parent class.""" super().__init__(first_name, last_name, age) #Add attribute privileges, that stores a list of string like: 'can add post'... #Add a function that will list the administrators set of privileges. self.privileges = Privileges()
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 6 #A list in a dictionary #Store information about a pizza being ordered. pizza = { 'crust' : 'thick', 'toppings' : ['mushroom', 'entra cheese'], } #Summarise the order. print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings:") for topping in pizza['toppings']: print("\t" + topping.title())
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 7 #Write a loop which will ask users for their age, and then tell them the sode of their movie ticket. prompt = "Welcome to the ticket machine. Enter your age: " prompt += "\nType 'Quit' to end program\n" age = "" while age.lower() != 'quit': age = input(prompt) #Casting the text into a string #age = int(age) if int(age) < 3: print('Your ticket will be free, enjoy') elif int(age) < 12: print('Your ticket will be $10.') elif int(age) >= 12: print('Your ticket will be $15')
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 9 class Restaurant: def __init__(self, name, type): restaurant_name = self.name cusine_type = self.type def open_restaurant(): """Display a message""" print(f"The restaurant {restaurant.name} is now open") def describe_restaurant(): """Print out the attributes of the class""" print(f"The restaurant in question is named: {restaurant_name.title()}.") print(f"The cusine of {restaurant_name.title()} is {cusine_type.title()}") new_restaurant = Restaurant('Rannaghor', 'indian') new_restaurant.open_restaurant() new_restaurant.describe_restaurant()
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 9 #Modify the class below. class Users: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age #Add an attribute login_attempts self.login_attempts = 0 def describe_user(self): """Prints a summary of the user's information""" print(f"The name of the user in question is:{self.first_name}{self.last_name}.") print(f"the user in question is {self.age} years old.\n") def greet_user(self): """A function to greet the user""" print(f"Hello, {self.first_name}\last_name") #Create a new funtion that increments the login attempts def increment_login_attempts(self): """Increment the attribute login_attempts""" self.login_attempts += 1 #Create a function that resets the number of login attempts def reset_login_attempts(self): """Reset the number of login attempts""" self.login_attempts = 0 reset_output = f"The login attampts have been reset,\n" reset_output += f"the value is now {self.login_attempts}.\n" return reset_output gabriel = Users('gabriel','abraham', 24) gabriel.describe_user() gabriel.greet_user() #For loop to increase the login attempts for value in range(5): gabriel.increment_login_attempts() print(gabriel.login_attempts) print(gabriel.reset_login_attempts()) james = Users('James', 'Adam', 35) james.describe_user() james.greet_user() charles = Users('charles', 'time', 23) charles.describe_user() charles.greet_user()
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 5 #Turn the example from eariler into an if_elif_else chain alien_color = 'purple' if alien_color.lower() == "green": print("You've just earned 5 points") elif alien_color.lower() == 'yellow': print("You've just earned 10 points") else: print("You've just earned 15 points")
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 5 #Choose a color for an alien as was done in the eariler expamle, and then write an if-else chain. alien_color = "yellow" if alien_color.lower() == "green": print("you've just earned 5 points") else: print("You've just earned 10 points") if alien_color.lower() == "yellow": print("you've just earned 5 points") else: print("You've just earned 10 points")
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 5 #Write an if statement that determines a person's stage at life. Set a value for the variable age, and then: age = 46 if age < 2: print("The person in question is a baby.") elif age < 4: print("the person is question is a toddler") elif age < 13: print("The person in question is still a child") elif age < 20: print("The person in quesiton is a teenager.") elif age < 65: print("The person in question if an adult.") else: print("The person in question is an elder.")
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 9 #The attributes will be information #The classes will be behaviours class Dog: """A simple attempt to model a god.""" def __init__(self, name,age): """Initialise name and age atrributes.""" self.name = name self.age = age def sit(self): """SImulate a dog sitting in response to a connant.""" print(f"{self.name} is now sitting.") def roll_over(self): """Simulate rolling over in sesponse to a command.""" print(f"{self.name} rolled over!") my_dog = Dog('Willie', 6) your_dog = Dog("Lucy", 3) print(f"My dog's name is {my_dog.name}.") print(f"My dog is {my_dog.age} years old.") my_dog.sit() print(f"\nYour dog's name is {your_dog.name}.") print(f"\nYour dog is {your_dog.age} years old.") your_dog.sit()
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 11 #Testing a function. def get_formatted_name(first, last, middle = ""): """Generate a neatly formatted full name.""" if middle: full_name = f"{first} {middle} {last}" else: full_name = f"{first} {last}" return full_name.title() #To test this function lets create a new program names.py
#Gabriel Abraham #notesonartificialintelligence #Python Crash Course - Chapter 11 import unittest from city_country import city_country class CityTestCase(unittest.TestCase): """Test the city country function.""" def test_city_country(self): """Will the function work?""" output = city_country('santiago', 'chile') #Test if the result of city_country (output) is the same as 'Santiago, Chile' self.assertEqual(output,'Santiago, Chile') if __name__ == '__main__': unittest.main()
# Assign a message to a variable, and print that message. # Them change the value of the variable to a new message, and print the new message. message = "This is the first message" print(message) message = "This is will be the new message with the latest variable" print(message)
#Gabriel Abraham #notesonartificialintelligence #Make a copy of the "pizza list", and then do the following: minerals = ["Selenium", "Calcium","Magnesium"] #Creating a copy of minerals list. friend_minerals = minerals[:] #Add a different pizza to the friend_mineral friend_minerals.append("Cobalt") #Prove that the lists have are indeed to separate lists print("My favorite minerals are: ") for mineral in minerals: print(mineral) #Then use another foor loop to print the other list. print("My friends favorite minerals are: ") for friend_mineral in friend_minerals: print(friend_mineral)
#Gabriel Abraham #notesinartificialintelligence #Python Crash Course - Chapter 8 def make_album(artist_name, album_title, number_of_songs = ''): """Music Album Dictionary""" music_album = {'Name' : artist_name, 'Album Name' : album_title} if number_of_songs: music_album['Number Of Songs'] = number_of_songs return (music_album) album = make_album('Pink Floyd', 'Dark Side of the Moon') print(album) album = make_album('The Beatles', "Sgt. Pepper's Lonely Hearts Club Band", "16") print(album) album = make_album('The Beatles', 'Abbey Road') print(album)
#Gabriel Abraham #notesofartificialintelligence #Python Crash Course - Chapter 8 def show_messages(message_list): """Print elements from a list""" for message in message_list: print(message) messages = ['Mental peace and Clarity', 'Abundance and Love', 'Radient energy and God form'] #I'll pass it a cpoy and not the original list. show_messages(messages[:])
"""" Write a python program which accepts the radius of a circle from the user and compute the area (area of circle=pi*radius)""" radius = int(input("Enter the radius")) pi = 3.14 area = radius*pi print("The area of the circle is", area)
from __future__ import print_function import pandas as pd import numpy as np import matplotlib.pyplot as plt from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential # define a function to convert a vector of time series into a 2D matrix def convertSeriesToMatrix(vectorSeries, sequence_length): matrix=[] for i in range(len(vectorSeries)-sequence_length+1): matrix.append(vectorSeries[i:i+sequence_length]) return matrix # random seed np.random.seed(1234) # load raw data df_raw = pd.read_csv('C:\data\hourly_load_2016.csv', header=None) # numpy array df_raw_array = df_raw.values # daily load list_daily_load = [df_raw_array[i,:] for i in range(0, len(df_raw)) if i % 24 == 0] # hourly load (23 loads for each day) list_hourly_load = [df_raw_array[i,1]/100000 for i in range(0, len(df_raw)) if i % 24 != 0] # the length of the sequnce for predicting the future value sequence_length = 23 # convert the vector to a 2D matrix matrix_load = convertSeriesToMatrix(list_hourly_load, sequence_length) # shift all data by mean matrix_load = np.array(matrix_load) shifted_value = matrix_load.mean() matrix_load -= shifted_value print ("data_load_forecast shape: ", matrix_load.shape) # split dataset: 90% for training and 10% for testing train_row = int(round(0.9 * matrix_load.shape[0])) train_set = matrix_load[:train_row, :] # shuffle the training set (but do not shuffle the test set) np.random.shuffle(train_set) # the training set X_train = train_set[:, :-1] # the last column is the true value to compute the mean-squared-error loss y_train = train_set[:, -1] # the test set X_test = matrix_load[train_row:, :-1] y_test = matrix_load[train_row:, -1] # the input to LSTM layer needs to have the shape of (number of samples, the dimension of each element) X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) # build the model model = Sequential() # layer 1: LSTM model.add(LSTM( input_dim=1, output_dim=50, return_sequences=True)) model.add(Dropout(0.2)) # layer 2: LSTM model.add(LSTM(output_dim=100, return_sequences=False)) model.add(Dropout(0.2)) # layer 3: dense # linear activation: a(x) = x model.add(Dense(output_dim=1, activation='linear')) # compile the model model.compile(loss="mse", optimizer="rmsprop") # train the model model.fit(X_train, y_train, batch_size=512, nb_epoch=50, validation_split=0.05, verbose=1) # evaluate the result test_mse = model.evaluate(X_test, y_test, verbose=1) print ('\nThe mean squared error (MSE) on the test data set is %.3f over %d test samples.' % (test_mse, len(y_test))) # get the predicted values predicted_values = model.predict(X_test) num_test_samples = len(predicted_values) predicted_values = np.reshape(predicted_values, (num_test_samples,1)) # plot the results fig = plt.figure() plt.plot(y_test + shifted_value) plt.plot(predicted_values + shifted_value) plt.xlabel('Hour') plt.ylabel('Electricity load (*1e5)') plt.show() fig.savefig('output_load_forecasting.jpg', bbox_inches='tight') # save the result into txt file test_result = np.vstack((predicted_values, y_test)) + shifted_value np.savetxt('output_load_forecasting_result.txt', test_result)
def add_time(start, duration, day_of_week=''): ## Parse inputs start_hour = int(start.split()[0].split(':')[0]) start_minute = int(start.split()[0].split(':')[1]) am_pm = start.split()[1] duration_hour = int(duration.split(':')[0]) duration_minute = int(duration.split(':')[1]) ## Days of the week week = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] if day_of_week: start_day_index = week.index(day_of_week.lower()) ## Add times total_days = 0 end_hour = start_hour + duration_hour end_minute = start_minute + duration_minute while end_hour >= 11 or end_minute >= 60: if end_minute >= 60: end_hour += 1 end_minute -= 60 if end_hour >= 11: if am_pm == 'AM': am_pm = 'PM' else: am_pm = 'AM' total_days += 1 if end_hour == 12: break if end_hour > 12: end_hour -= 12 ## Display results new_time = f'{end_hour}:{str(end_minute).zfill(2)} {am_pm}' if day_of_week: new_time += ', ' + week[(start_day_index + total_days) % 7].capitalize() if total_days == 1: new_time += ' (next day)' if total_days > 1: new_time += f' ({total_days} days later)' return new_time
class Stack: num_of_stacks = 0 class Node: def __init__(self,data): self.data = data self.next_node = None def __init__(self): self.top = None self.stack_size = 0 Stack.num_of_stacks += 1 # isEmpty def is_empty(self): return self.top == None # peek def peek(self): try: return self.top.data except: return None # push def push(self, data): node = self.Node(data) node.next_node = self.top self.top = node self.stack_size += 1 # pop def pop(self): if self.top != None: self.stack_size -= 1 data = self.top.data self.top = self.top.next_node return data # string representation def __str__(self): return f"its top is {self.peek()}, and stack size is {self.stack_size} " def main(): s = Stack() b = Stack() s.pop() s.push(12) s.push(24) s.push(36) s.push(48) print(s.pop()) print(s) if __name__ == "__main__": main()
import datetime from src.handlers.code_handler import * months = { "jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12, "january": 1, "february": 2, "march": 3, "april": 4, "june": 6, "july": 5, "august": 8, "september": 9, "october": 10, "november": 11, "december": 12 } def get_year(year_str: str) -> int: sys_year = datetime.datetime.today().year # return if year valid, if not return ridiculous time if year_str.isnumeric(): if len(year_str) == 2: if int(str(sys_year)[2:]) <= int(year_str): year_str = '20' + year_str else: year_str = '19' + year_str year = int(year_str) else: year = 9999 return year def get_month(month_str: str) -> int: sys_month = datetime.datetime.today().month # return if month valid, if not return ridiculous time if month_str.isnumeric(): month = int(month_str) if int(month_str) <= 12 else 12 else: month = months[month_str.lower()] \ if month_str.lower() in months else 12 return month def get_date(date_str: str) -> int: sys_month = datetime.datetime.today().month # return if month valid, if not return ridiculous time if date_str.isnumeric(): date = int(date_str) if int(date_str) <= 31 else 31 else: date = 31 return date def date_formatter(date_str, date_format): code = '' req_code = date_format req_format = '%d-%d-%d' str_list = [] specials = '/.-_, ' start = -1 # Ensure date_str is string date_str = str(date_str) for i in range(len(date_str)): if start == -1: start = i if date_str[i] in specials or i == len(date_str)-1: if i == len(date_str)-1: str_list.append(date_str[start:i+1]) else: str_list.append(date_str[start:i]) start = -1 for i in range(len(str_list)): code += str(len(str_list[i])) if str_list[i].isnumeric(): code += 'N' else: code += 'S' if code == req_code: date = code_handler( req_code, get_date(str_list[2]), get_month(str_list[1]), get_year(str_list[0]) ) elif code == '2N2N4N': if int(str_list[1]) > 12: date = code_handler( req_code, get_date(str_list[1]), get_month(str_list[0]), get_year(str_list[2]) ) else: date = code_handler( req_code, get_date(str_list[0]), get_month(str_list[1]), get_year(str_list[2]) ) elif code == '4N2N2N': if int(str_list[2]) > 12: date = code_handler( req_code, get_date(str_list[2]), get_month(str_list[1]), get_year(str_list[0]) ) else: date = code_handler( req_code, get_date(str_list[1]), get_month(str_list[2]), get_year(str_list[0]) ) else: date = date_str return date
from sympy import ( Circle, Point, ) def get_location(list_of_positions_and_distance): """ This method receive a list with all postions and the distance to the emisor. To to get the origin this method create three circles and get the intersection point between this circles >>> get_location([(-1, 0, 1), (0, -2, 2), (3, 0, 3)]) (0, 0) """ circle_one = Circle( Point(list_of_positions_and_distance[0][0],list_of_positions_and_distance[0][1]), list_of_positions_and_distance[0][2] ) circle_two = Circle( Point(list_of_positions_and_distance[1][0],list_of_positions_and_distance[1][1]), list_of_positions_and_distance[1][2] ) circle_three = Circle( Point(list_of_positions_and_distance[2][0],list_of_positions_and_distance[2][1]), list_of_positions_and_distance[2][2] ) intersection_point_set = ( set(circle_one.intersection(circle_two)) & set(circle_one.intersection(circle_three)) & set(circle_two.intersection(circle_three)) ) if len(intersection_point_set) != 1: # None or more than 1 point where found raise Exception intersection_point = intersection_point_set.pop() return intersection_point.x, intersection_point.y
n=int(input()) flag=0 for i in range(2,n,-1): if n%1==0: flag=1 break if flag==0: print("prime") else: print("not")# your code goes here
s=input() if s.isalpha(): print("Alphabest") elif s.isnumeric(): print("Number") else: print("Special char")
def nth(n): n = int(n) if (n==1): return str(n) + "st" elif (n==2): return str(n) + "nd" elif (n==3): return str(n) + "rd" else: return str(n) + "th"
""" Consider a singly linked list whose nodes are numbered starting at 0. Define the even-odd merge of the list to be the list consisting of the even-numbered nodes followed by the odd-numbered nodes. Write a program that computes the even-odd merge. Example: Input: L0 -> L1 -> L2 -> L3 -> L4 Output: L0 -> L2 -> L4 -> L1 -> L3 """ # Define objects class LinkedList: def __init__(self, head=None): self.head = head def __repr__(self): node = self.head nodes = [] while node is not None: nodes.append(str(node.data)) node = node.next_ nodes.append('None') return ' -> '.join(nodes) class Node: def __init__(self, data=None, next_=None): self.data = data self.next_ = next_ # Make input linked list l4 = Node(4) l3 = Node(3, next_=l4) l2 = Node(2, next_=l3) l1 = Node(1, next_=l2) l0 = Node(0, next_=l1) input_llist = LinkedList(head=l0) def even_odd_merge(llist): return llist print(even_odd_merge(input_llist)) # assert even_odd_merge(llist).__repr__() == '0 -> 2 -> 4 -> 1 -> 3 -> None'
def max_unique_split(s: str) -> int: # Container to track already used substrings used_substrings = set() current_substring = '' for i, char in enumerate(s): # Add the character to the current substring current_substring += char # If it's a new unique substring, append to the set and reinitialize the current substring if current_substring not in used_substrings: used_substrings.add(current_substring) current_substring = '' # Return the number of substrings return len(used_substrings) # --- Test Cases --- # assert max_unique_split("ababccc") == 5 assert max_unique_split("aba") == 2 assert max_unique_split("aa") == 1
n=int(input("Enter the number of fibonacci numbers you want: - ")) a,b=0,1 print("\n{}\t{}".format(a,b),end=" ") for i in range(n-2): c=a+b print("\t{}".format(c),end=" ") a=b b=c
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Sep 24 11:34:34 2017 @author: dldien """ import numpy as np X = np.matrix([[1, 1, 1, 1, 1], [0, 0.5, 1.2, 2.5, 3]]).T y = np.matrix([1, 2.5, 3.5, 4, 5.5]).T theta = np.matrix([0, 0.5]).T alpha = 0.03 it = 10 for i in range(0, it): h = X * theta; derivative = np.matrix([0, 0]).T derivative[0] = np.sum(h - y) derivative[1] = np.sum(np.multiply((h - y), (X[:, 1]))) theta = theta - alpha * derivative; print theta theta = np.array(theta) import matplotlib.pyplot as plt plt.plot(X[:, 1], y, "ro") x0 = [0, 4] y0 = theta[0] + theta[1] * x0 plt.plot(x0, y0, color="blue") plt.show()
import numpy as np A = np.array([2,5,3,6,7,8]) B = np.array(range(1,200+1)) C = np.linspace(0, 1000, 1001) C = C[C % 2 == 0] A5 = A + 5 B3 = B * 3 A_sort = np.sort(A) Dict = {'Name' : 'Duong Lu Dien', 'Age' : 21, 'Course' : 'Nguyen Ly May Hoc'} Dict['Course'] = 'Tri Tue Nhan Tao' def hello(): name = input('Enter your name: ') print 'Hello %s' %name # hello() def squareEquationSolver(a, b, c): from math import sqrt delta = b * b - 4 * a * c if delta < 0: print 'No solution for this equation' elif delta == 0: x = -b / (2*a) print 'Solution: x = %f' %x else: x1 = (-b + sqrt(delta)) / (2*a) x2 = (-b - sqrt(delta)) / (2*a) print 'Solution: x1 = %f and x2 = %f' %(x1,x2) # a = input('Enter a: ') # b = input('Enter b: ') # c = input('Enter c: ') # squareEquationSolver(a, b, c) def findMaximum(): a = input('Enter a number: ') b = input('Enter another one: ') c = input('Enter another one: ') max = a if b > max: max = b if c > max: max = c print 'So lon nhat trong 3 so nhap vao la %d' %max # findMaximum() X = np.matrix([ [1,2,3], [4,5,6], [7,8,9] ]) Y = np.matrix([ [11,22,33,44], [55,66,77,88], [99,111,222,333] ]) Z = X * Y import matplotlib.pyplot as plt x = np.linspace(-10, 10, 100) y = np.sin(x) plt.plot(x,y) plt.show() x2 = np.linspace(-5, 5, 100) y2 = x2**3 - 2*x2*x2 + x2 + 5 plt.plot(x2, y2) plt.show()
def strStr(haystack: str, needle: str) -> int: if needle == '': return 0 if needle in haystack: print(haystack.index(needle)) else: print(-1) if __name__ == '__main__': strStr("hello", "ll")
def smallerNumbersThanCurrent(nums): small = [] for i in range(len(nums)): count = 0 for a in range(len(nums)): if nums[i] > nums[a]: count += 1 small.append(count) print(small) if __name__ == '__main__': smallerNumbersThanCurrent([7, 7, 7, 7])
""" This program analyzes bikeshare data for several cities and interactively displays important summary statistics for each city. Author Gregory Rowe """ import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs print('Would you like to see data for Chicago, New York City , or Washington?') def cityname(): city = str(input('Type city name :')).lower() if city not in citynames: print('Please select city from chicago, new york city, or washington.') city = cityname() return city city = cityname() # TO DO: get user input for month (all, january, february, ... , june) print('Select a month from january, february, march, april, may, june, or all .') def monthname(): month = str(input('Type month :')).lower() if month not in months: print('Please select month january, february, march, april, may, june, or all .') month = monthname() return month month = monthname() # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) print('Select a day monday, tuesady, wednesday, thursday, friday, saturday, sunday, or all .') def dayname(): day = str(input('Type day :')).lower() if day not in days: print('Please select day from monday, tuesday, wednesday, thursday, friday, saturday, sunday, or all .').lower() day = dayname() return day day = dayname() print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month original_df['Month'] = pd.DatetimeIndex(original_df['Start_Time']).month months_count = original_df['month'].value_counts() maxMonth = months_count.idxmax() months = ['january', 'february', 'march', 'april', 'may', 'june'] print('The most common month is {} and count is {}.'.format((months[maxMonth-1]).title(),month_count.max())) # TO DO: display the most common day of week original_df['Week Day'] = pd.DatetimeIndex(original_df['Start_Time']).weekday_name days_count = original_df['week day'].value_counts() maxDay = days_count.idxmax() days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] print('The most common day of week is {} and count is {}.'.format(maxDay.title(),days_count.max())) # TO DO: display the most common start hour original_df['Hours'] = pd.DatetimeIndex(original_df['Start_Time']).hour hours_count = original_df['hours'].value_counts() print('The most common hour is {} and count : {}'.format(hours_count.idmax(),hours_count.max())) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station Start_Station_counts = df['Start Station'].value_counts() print('The most commonly used start station is "{}" and count: {}'.format(Start_Station_counts.idmax(),Start_Station_counts.max())) # TO DO: display most commonly used end station End_Station_counts = df['End Station'].value_counts() print('The most commonly used end station is "{}" and count: {}'.format(End_Station_counts.idmax(),End_Station_counts.max())) # TO DO: display most frequent combination of start station and end station trip df['Start End stations'] = df['Start Station'] + df['End Station'] Start_End_Station = df['Start End Station'].value_counts() print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # TO DO: display total travel time total_time_sum = df['Trip Duration'].sum() print('Total travel time {}.'.format(total_time_sum)) # TO DO: display mean travel time total_time_mean = df['Trip Duration'].mean() print('Total traveling mean time {}.'.format(total_time_mean)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types count_user = df['User Type'].value_counts() print('Total count of user types {}.'.format(count_user)) # TO DO: Display counts of gender except for washington df['Gender'].fillna('Not given',inplace=True) count_user_gender = df['Gender'].value_counts() if city == 'washington': print('Gender is not availble for this city {}.'.format(city)) if city == 'chicago' or city == 'new york': print('Total Counts of user Gender type are {}.'.format(count_user_gender)) # TO DO: Display earliest, most recent, and most common year of birth birth_year = df['Birth Year'].value_counts() if city == 'washington': print('Birth year is not availble for this city {}.'.format(city)) if city == 'chicago' or city == 'new york': print('Earliest, most recent, and most common year of birth are "{}", "{}", and "{}" of"{}".'.format(birth_year.idmin(),df['Birth Year'].iloc[0],birth_year.idmax(),city)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) <<<<<<< HEAD #allows the user the option of seeing 5 lines raw data when the user asks next 5 lines print ======= #allows the user the option of seeing 5 lines of raw data >>>>>>> 34ac815402a44668ea8baba1a6799097733466c9 show_data = input ('\nWould you like to see five lines of raw data? Enter yes or no\n') count = 1 while show_data.lower() != 'no': print(df.iloc[[count, count + 1, count + 2, count + 3, count + 4]] ) show_data = input ('\nWould you like to see five lines of raw data? Enter yes or no\n') count += 5 def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
# ------ # Robot.py class # This runs the robot. # Copyright 2015. Pioneers in Engineering. # ------ import Motors class Robot: # Constructor for a generic robot program def __init__(self): self.motors = [] for addr in Motor.addrs: motor = Motor(addr) self.motors.append(motor) # Takes in a list of speeds in the order of # which motors are assigned in the array. # Note: This method does not fix motors being # backwards or anything, so YOU have to look at that yourself. def drive(self, *args): for index in range(len(args)): motor[index].set_speed(args[index]) # This method will ensure that everything is multiplied by 100 # But nothing else. def drive_from_controller(self, *args): for index in range(len(args)): args[index] *= 100 self.drive(args) # Used for emergency stop def stop(self): for motor in self.motors: motor.reset_motor()
#!/usr/bin/env python3 # HW05_ex09_01.py # Write a program that reads words.txt and prints only the # words with more than 20 characters (not counting whitespace). ############################################################################## # Imports # Body def print_large_words(): try: with open("words.txt", "r") as file_object: contents = file_object.read() contents = contents.split("\n") for word in contents: if len(word) > 20: print(word) except: print("Sorry, problem with reading the file. Check if file is present in your working directory.") ############################################################################## def main(): print_large_words() if __name__ == '__main__': main()
import tkinter as tk from tkinter import ttk class HelloView(tk.Frame): def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.name = tk.StringVar() self.hello_string = tk.StringVar() self.hello_string.set("Hello World") name_label = ttk.Label(self, text="Name:") name_entry = ttk.Entry(self, textvariable=self.name) ch_button = ttk.Button( self, text="Change", command=self.on_change ) hello_label = ttk.Label( self, textvariable=self.hello_string, font=("TkDefaultFont", 64), wraplength=600 ) name_label.grid(row=0, column=0, sticky=tk.W) name_entry.grid(row=0, column=1, sticky=(tk.W + tk.E)) ch_button.grid(row=0, column=2, sticky=tk.E) hello_label.grid(row=1, column=0, columnspan=3) self.columnconfigure(1, weight=1) def on_change(self): if self.name.get().strip(): self.hello_string.set("Hello " + self.name.get()) else: self.hello_string.set("Hello World")
import tkinter as tk from tkinter import ttk from tkinter.simpledialog import askstring def ask_string_dialog(title="Enter a string input dialog", prompt="Please enter a value") -> str: root = tk.Tk() string = askstring( parent=root, title=title, prompt=prompt ) root.destroy() return string class AskStringDialog(tk.Tk): def __init__(self, title="Select a value"): super().__init__() # create the root window self.geometry('200x100') self.resizable(False, False) self.title = title self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) ask_button = ttk.Button( self, text='Enter a value', command=self.ask ) ask_button.pack(expand=True) close_button = ttk.Button( self, text='Quit Dialog', command=self.destroy ) close_button.pack(expand=True) self.mainloop() # self.destroy() def ask(self): name = askstring( parent=self, title="test", prompt="Which name do you want to give to your simulation ?" ) print("###########################################") print(name) print("###########################################") type(self).result = name def run(): """ Encapsulate GUI """ main() def main(): AskStringDialog("Please, Enter a value") return(AskStringDialog.result) if __name__ == "__main__": main()
from enum import Enum def is_station(station): try: names = set([member.name for member in Station]) if station.name in names: return True else: return False except AttributeError: print("Station does not exist") class DateFormat(Enum): """ Enum for date formats""" DMY = 1 YMD = 2 class Station(Enum): """ Enum for stations""" BARB = 1 CUBA = 2 KARU = 3 MADA = 4 PUER = 5 SMAR = 6 def __str__(self): return str(self.name.lower()) class EmptyFolderError(Exception): pass
#!/usr/bin/env python3 # Calculator V2 - ACG Intro to Python Scripting Chapter 5 def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): if num2 == 0: print("Can't divide by 0") return else: return num1 / num2 operation = -1 while operation != 0: print("CALCULATOR PROGRAM") print("Select operation:") print("0 - quit, 1 - add, 2 - subtract, 3 - multiply, 4 - divide") operation = int(input("What operation do you want to perform? ")) if operation == 0: print("Ending program..") else: num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) if operation == 1: result = add(num1, num2) print(result) elif operation == 2: result = subtract(num1, num2) print(result) elif operation == 3: result = multiply(num1, num2) print(result) elif operation == 4: if num2 == 0: print("Can't divide by 0") else: result = divide(num1, num2) print(result) else: print("Operation not recognized...")
from collections import deque g = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 4], 3: [2, 4], 4: [2, 3] } q = deque() def bfs(g, node, q): visited = [False for k in g.keys()] inqueue = [False for k in g.keys()] q.appendleft(node) inqueue[node] = True combs = [] combs2 =[] i = 1 while not (len(q) == 0): c = q.pop() inqueue[c] = False visited[c] = True print("Visiting", c) i += 1 for v in g[c]: if v > c: combs2.append((c,v)) print("combs2",combs2) else: print("nothing") if not visited[v] and not inqueue[v]: print("test", c, v) combs.append((c, v)) print("combs",combs) q.appendleft(v) inqueue[v] = True bfs(g, 0, q)
''' ***Logistic Regression*** With Gradient Descent Author : Pranath Reddy 2016B5A30572H ''' import math import numpy as np import pandas as pd from sklearn.model_selection import train_test_split # A function to return the column at specified index def getcol(data,c): col = [] for i in range(len(data)): col.append(data[i][c]) return col def set(y): for i in range(len(y)): if(y[i]>0.5): y[i] = 1 if(y[i]<0.5): y[i] = 0 return y def sigmoid(x): return 1 / (1 + math.exp(-x)) # A function to return the updated values of m,c after one iteration of gradient descent def wtupdate(m1,m2,m3,m4,c,x,y): sumvm1 = 0 sumvm2 = 0 sumvm3 = 0 sumvm4 = 0 sumvc = 0 yp = [0 for i in range(len(x))] for i in range(len(x)): yp[i] = (m1*x[i,0]) + (m2*x[i,1]) + (m3*x[i,2]) + (m4*x[i,3]) + c yp[i] = sigmoid(yp[i]) sumvm1 = sumvm1 - (y[i]-yp[i])*x[i,0] sumvm2 = sumvm2 - (y[i]-yp[i])*x[i,1] sumvm3 = sumvm3 - (y[i]-yp[i])*x[i,2] sumvm4 = sumvm4 - (y[i]-yp[i])*x[i,3] sumvc = sumvc - (y[i]-yp[i]) m1 = m1 - 0.05*sumvm1 m2 = m2 - 0.05*sumvm2 m3 = m3 - 0.05*sumvm3 m4 = m4 - 0.05*sumvm4 c = c - 0.05*sumvc return m1,m2,m3,m4,c # A function to return the slope and intercept of y^ def linreg(x,y): m1 = 0 m2 = 0 m3 = 0 m4 = 0 c = 0 iters = 1000 i = 0 while(i<iters): m1,m2,m3,m4,c = wtupdate(m1,m2,m3,m4,c,x,y) i = i+1 return m1,m2,m3,m4,c # A function to implement min-max normalization def norm(data): ndata = data for i in range(5): maxval = max(getcol(data,i)) minval = min(getcol(data,i)) for j in range(len(data)): ndata[j][i] = (data[j][i]-minval)/((maxval-minval)+0.05) return ndata # import the data data = pd.read_excel('data3.xlsx',header=None) # normalize the data data = np.asarray(data) data = norm(data) # split into dependent and independent variables x = data[:,:-1] y = data[:,-1] # split into testing and training sets x_tr, x_ts, y_tr, y_ts = train_test_split(x, y, test_size=0.4) m1,m2,m3,m4, c = linreg(x_tr,y_tr) x = x_ts yp = [0 for i in range(len(x))] for i in range(len(x)): yp[i] = (m1*x[i,0]) + (m2*x[i,1]) + (m3*x[i,2]) + (m4*x[i,3]) + c yp[i] = sigmoid(yp[i]) y_ts = set(y_ts) yp = set(yp) y_actual = pd.Series(y_ts, name='Actual') y_pred = pd.Series(yp, name='Predicted') confmat = pd.crosstab(y_actual, y_pred) print(confmat) confmat = np.asarray(confmat) tp = confmat[1][1] tn = confmat[0][0] fp = confmat[0][1] fn = confmat[1][0] Acc = (tp+tn)/(tp+tn+fp+fn) SE = tp/(tp+fn) SP = tn/(tn+fp) print('Accuracy : ' + str(Acc)) print('sensitivity : ' + str(SE)) print('specificity : ' + str(SP))
import threading import time class multithreading (threading.Thread): def __init__(self, threadID, nome): threading.Thread.__init__(self) self.threadID = threadID self.nome = nome def run(self): print ("Initializing " + self.name) string = 'testetestetestetestetestetestetestetestetestetestetestetestetestetestetesteteste' for i in range(0, len(string)): if string[i].islower(): aux_string = string[i].upper() string = string[:i] + aux_string + string[i+1:] print(string) # Creating 30 threads for i in range(30): thread = multithreading(i, "Thread") thread.start() threads = [] threads.append(thread) for t in threads: for i in range (0, 30): t.join() print ("Finishing multithreading program")
class Person(object): count=0 name1='vs' def __init__(self,a,b,c): self.name=a self.sex=b self.classroom=c Person.count+=1 p1 = Person('Bob', 'boy',423) p2 = Person('Boq', 'girl',403) print(p1.classroom) print(Person.count) p1.name1='afa' #Person.name1='afa' print(p1.name1) print(p2.name1) print(Person.name1)
print("Welcome to the Temperature Conversion Program") tmp = float(input("What is the given temperature in degree fahrenheit?")) cs = ((tmp - 32) * 5) / 9 kv = ((tmp + 459.67) * 5) / 9 print("Degrees Fahrenheit:", tmp) print("Degrees Celsius:", round(cs,4)) print("Degrees Kelvin:", round(kv, 4))
print("Welcome to the Multiplication/Exponent Table app") name = input("Hello, what is your name:") num = float(input("What number would you like to work with?")) print("Multiplication table for %s", num) for i in range(1,10): mult = i*num print("{} * {} = {}".format(i,num,round(mult,2))) for i in range(1,10): exp = num**i print("{} ** {} = {}".format(num,i,round(exp,4)))
# -*- coding: utf-8 -*- #LeetCode - 392_Is_Subsequence.py #192ms 74.79% ''' Instruction: LeetCode 392 - Is Subsequence - [M] Developer: lrushx Process Time: Apr 13, 2017 ''' ''' Total Accepted: 28263 Total Submissions: 63778 Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not). Example 1: s = "abc", t = "ahbgdc" Return true. Example 2: s = "axc", t = "ahbgdc" Return false. Follow up: If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? ''' #ๅˆคๆ–ญsๆ˜ฏๅฆไธบt็š„ๅญไธฒ๏ผŒๅฏไปฅไธ่ฟž็ปญ #2ไธชไฝ็ฝฎๅ‘ๅŽๅˆคๆ–ญ๏ผŒๅคๆ‚ๅบฆO(mn)๏ผŒrangeๆ”นๆˆxrange๏ผŒๆ—ถ้—ดไปŽ682msๅˆฐ192ms class Solution(object): def isSubsequence(s, t): l1,l2 = len(s),len(t) if l1>l2: return False pos = 0 for i in xrange(l1): flag = False for j in xrange(pos,l2): if s[i] == t[j]: flag = True pos = j+1 break if not flag: return False return True ''' s = "abc" t = "ahbgdc" s = "axc" t = "ahbgdc" ''' s = "acb" t = "ahbgdc" print(isSubsequence(s,t))
## 141_Linked_List_Cycle.py ## 82ms 50% ''' Total Accepted:233.8K Total Submissions: Instruction: LeetCode 141 - Linked List Cycle [E] Developer: lrushx Process Time: Feb 23, 2018 ''' ''' Given a linked list, determine if it has a cycle in it. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head is None: return False fast, slow = head.next, head while fast != slow: for _ in range(2): if fast is None: return False fast = fast.next slow = slow.next return True
#!/bin/python3 ''' Instruction: HackerRank - The Full Counting Sort - [M] Success Rate: 83.41% Max Score: 40 Difficulty: Medium Submitted 20512 times Developer: lrushx Process Time: Mar 29, 2018 https://www.hackerrank.com/challenges/countingsort4/problem ''' import sys from collections import defaultdict def countingsort(arr): dic = defaultdict(list) half = (len(arr)-1) // 2 for i,(n,s) in enumerate(arr): if i <= half: dic[n].append((s,-1)) else: dic[n].append((s,1)) res = [] for n in range(100): for s,flag in dic[n]: if flag > 0: res.append(s) else: res.append('-') return ' '.join(res) if __name__ == "__main__": n = int(input().strip()) arr = [] for a0 in range(n): x, s = input().strip().split(' ') x, s = [int(x), str(s)] arr.append((x,s)) res = countingsort(arr) print(res)
# -*- coding:utf-8 -*- ''' Challenge: duplicate Total Acceptence: 27.35% Developer: lrushx Process Time: Apr 08, 2018 https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=3&rp=3&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking ''' class Solution: # ่ฟ™้‡Œ่ฆ็‰นๅˆซๆณจๆ„~ๆ‰พๅˆฐไปปๆ„้‡ๅค็š„ไธ€ไธชๅ€ผๅนถ่ต‹ๅ€ผๅˆฐduplication[0] # ๅ‡ฝๆ•ฐ่ฟ”ๅ›žTrue/False def duplicate(self, numbers, duplication): if len(numbers) == 0: return False ''' s = set() for x in numbers: if x in s: duplication[0] = x return True s.add(x) return False ''' n = len(numbers) for i in range(n): while numbers[numbers[i]]!=numbers[i]: j = numbers[i] numbers[i], numbers[j] = numbers[j], numbers[i] for i,x in enumerate(numbers): if i != x: duplication[0] = x return True return False #l = [2,3,1,0,2,5,3] l = [2,1,3,1,4] s = Solution() du = [-10] if s.duplicate(l,du): print(du[0])
## 815_Bus_Routes\[H\].py ## 512ms % ''' Total Accepted: 1.7K Total Submissions: 5.4K Developer: lrushx Process Time: Apr 11, 2018 https://leetcode.com/problems/bus-routes/description/ ''' ''' We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever. We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible. Example: Input: routes = [[1, 2, 7], [3, 6, 7]] S = 1 T = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. Note: 1 <= routes.length <= 500. 1 <= routes[i].length <= 500. 0 <= routes[i][j] < 10 ^ 6. ''' ## ็ป™ไธ€ไบ›bus่ทฏ็บฟ๏ผŒๆฏไธช่ทฏ็บฟ้ƒฝๆ˜ฏไธชlist๏ผŒๅŒ…ๅซ่ฏฅbusๅฏไปฅๅˆฐstop๏ผŒๅนถไธ”ๅฏไปฅๅพช็Žฏ่ตฐใ€‚ๅŒไธชstopๅฏไปฅๆขไน˜ใ€‚้—ฎไปŽSๅˆฐTๆœ€ๅฐ‘้œ€่ฆๅๅ‡ ่ถŸbus๏ผŸ ## ๆŠŠๅŽŸ้—ฎ้ข˜induceๆˆไปฅbusไธบ่Š‚็‚น็š„ๆ— ๅ‘ๅ›พ๏ผŒๅช่ฆ่ทฏ็บฟๆœ‰ๅ…ฌๅ…ฑstop็š„ไธค่ถŸbus๏ผŒๅฏนๅบ”่Š‚็‚นไน‹้—ดๅฐฑๆœ‰่พน๏ผŒๅนถไธ”่พน้•ฟไธบ1ใ€‚ ## ๅฆ‚ๆญคๅฐฑๆ˜ฏไธ€ไธชๅœจไปฅbus็ผ–ๅทไธบ่Š‚็‚น็š„ๆ— ๅ‘ๅ›พไธญๆ‰พไปŽๅŒ…ๅซS็š„ไผ—่Š‚็‚นๅˆฐๅŒ…ๅซT็š„ไผ—่Š‚็‚น็š„ๆœ€็Ÿญ่ทฏๅพ„๏ผŒBFSๅณๅฏใ€‚ ## ่‹ฅinduced graph็š„่พน้•ฟ้ž1๏ผŒๅˆ™้œ€่ฆ็”จDijkstra class Solution: def numBusesToDestination(self, routes, S, T): """ :type routes: List[List[int]] :type S: int :type T: int :rtype: int """ if S == T: return 0 n = len(routes) edges = defaultdict(set) sets = [set(r) for r in routes] queue = [(i,1) for i,x in enumerate(sets) if S in x] target = [i for i,x in enumerate(sets) if T in x] if not target or not queue: return -1 # S or T not in any routes for i,x in enumerate(sets): for j in range(i+1,n): if x & sets[j]: edges[i].add(j) edges[j].add(i) # now we have a list of source, a list of target, and edges, it's a shortest path problem # and edge cost is 1, both BFS and Dijkstra available # of edge cost is non-negative, then only Dijkstra available i = 0 visited = {x[0] for x in queue} while i < len(queue): u, step = queue[i] i += 1 if u in target: return step for v in edges[u]: if not v in visited: queue.append((v, step+1)) visited.add(v) return -1
## 796_Rotate_String.py ## 36ms 95.95% ''' Total Accepted: 7.4K Total Submissions: 11.4K Instruction: LeetCode 796 - Rotate String [M] Developer: lrushx Process Time: Mar 18, 2018 ''' ''' We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. Example 1: Input: A = 'abcde', B = 'cdeab' Output: true Example 2: Input: A = 'abcde', B = 'abced' Output: false ''' class Solution: def rotateString(self, A, B): if len(A) != len(B): return False if A == B: return True a = A[1:]+A[0] for _ in range(len(A)-1): if a == B: return True a = a[1:]+a[0] return False ''' class Solution: def check(self, A, B, i, l): for j in range(1,l-i): if A[i+j] != B[j]: return False for j in range(1,i): if A[j] != B[l-i+j]: return False return True def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ if len(A) != len(B): return False l = len(A) if self.check(A,B,0,l): return True for i in range(1,l): if A[i] == B[0] and A[0] == B[l-i]: if self.check(A,B,i,l): return True return False '''