text
stringlengths
37
1.41M
"""" 给定一个二叉树,返回它的 后序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? """ # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: result = [] def travel(node): if node: travel(node.left) travel(node.right) result.append(node.val) travel(root) return result
import pygame # Game config WIDTH = 600 HEIGHT = 600 FPS = 1 SCORE = 0 clock = pygame.time.Clock() red = (161, 40, 48) lime = (0, 255, 0) snake_body = [] x_back = 30 y_back = 30 intro_screen = False class Player: def __init__(self, x, y, width, height, direction): self.x = x self.y = y self.width = width self.height = height self.direction = direction self.speed = 30 self.body_parts = [pygame.Rect(self.x, self.y, self.width, self.height)] def player_movement(self): # change direction on input if self.direction == "right": self.x += self.speed if self.direction == "down": self.y += self.speed if self.direction == "up": self.y -= self.speed if self.direction == "left": self.x -= self.speed # prevent player from exiting screen if self.x + self.width/2 < 0: self.x = WIDTH if self.x > WIDTH: self.x = 0 if self.y + self.height/2 < 0: self.y = HEIGHT if self.y > HEIGHT: self.y = 0 def get_rect(self): box = pygame.Rect(self.x, self.y, self.width, self.height) return box def draw(self, window): for body_part in self.body_parts: pygame.draw.rect(window, red, body_part) print(body_part.x) def update(self): self.player_movement() self.body_parts.insert(0, pygame.Rect(self.x, self.y, self.width, self.height)) self.body_parts.pop()
#!/usr/bin/env python '''Re-encryption demonstration This little program shows how to re-encrypt crypto from versions older than 2.0. Those versions were inherently insecure, and version 2.0 solves those insecurities. This did result in a different crypto format, so it's not backward compatible. Use this program as a demonstration on how to re-encrypt your files/passwords/whatevers into the new format. ''' import sys import rsa from rsa import _version133 as insecure (pub, priv) = rsa.newkeys(64) # Construct the encrypted content. You'd typically read an encrypted file or # stream here. cleartext = 'Give me more cowbell' old_crypto = insecure.encrypt(cleartext, pub) print 'Old crypto:', old_crypto print # Decrypt and re-encrypt the contents to make it compatible with the new RSA # module. decrypted = insecure.decrypt(old_crypto, priv) new_crypto = rsa.encrypt(decrypted, pub) print 'New crypto:', new_crypto print
# import json # alltweets = [] # def get_all_tweets(name, screen_name): # #Twitter only allows access to a users most recent 3240 tweets with this method # #authorize twitter, initialize tweepy # # auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # # auth.set_access_token(access_key, access_secret) # # api = tweepy.API(auth) # #initialize a list to hold all the tweepy Tweets # alltweets[name] = [] # #make initial request for most recent tweets (200 is the maximum allowed count) # new_tweets = api.GetUserTimeline(screen_name = screen_name,count=200) # #save most recent tweets # alltweets.extend(new_tweets) # #save the id of the oldest tweet less one # oldest = alltweets[-1].id - 1 # #keep grabbing tweets until there are no tweets left to grab # while len(new_tweets) > 0: # print ("getting tweets before %s" % (oldest)) # #all subsiquent requests use the max_id param to prevent duplicates # new_tweets = api.GetUserTimeline(screen_name = screen_name,count=200,max_id=oldest) # #save most recent tweets # alltweets.extend(new_tweets) # #update the id of the oldest tweet less one # oldest = alltweets[-1].id - 1 # print ("...%s tweets downloaded so far" % (len(alltweets))) # #transform the tweepy tweets into a 2D array that will populate the csv # outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets] # #write the csv # # with open('%s_tweets.csv' % screen_name, 'wb') as f: # # writer = csv.writer(f) # # writer.writerow(["id","created_at","text"]) # # writer.writerows(outtweets) # pass # NEW TRY def get_all_tweets(name, screen_name): alltweets = [] new_tweets = api.GetUserTimeline(screen_name = screen_name,count=200) #save most recent tweets alltweets.extend(new_tweets) #save the id of the oldest tweet less one oldest = alltweets[-1].id - 1 #keep grabbing tweets until there are no tweets left to grab while len(new_tweets) > 0: print ("getting tweets before %s" % (oldest)) #all subsiquent requests use the max_id param to prevent duplicates new_tweets = api.GetUserTimeline(screen_name = screen_name,count=200,max_id=oldest) #save most recent tweets alltweets.extend(new_tweets) #update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print ("...%s tweets downloaded so far" % (len(alltweets))) return alltweets import json def jsonify(name, tweets): data = {} data[name] = [] for stat in tweets: data[name].append(stat.AsJsonString()) return data def jsonify_tweets(name, tweets): data = {} data[name] = [] for stat in tweets: data[name].append(stat.AsJsonString()) return data # SAVING THE JSON TWEETS #EXTRACTING IMAGES AND TEXT AS DICT FROM IMAGE CATG RESULT PAGE def txt_img_extract(res_page): txt_img_dic = {} try: res_pg = requests.get(res_page) except requests.ConnectionError: print('Connection Error(s) occured. :( : ' + requests.ConnectionError) res_page_soup = BeautifulSoup(res_pg.content, 'html5lib') img_box = res_page_soup.findAll('div', {'class':'m-brick grid-item boxy bqQt'}) for itm in img_box: try: img_t = itm.find('img')['alt'] img_l = 'https://www.brainyquote.com' + itm.find('img')['src'].replace('.jpg', '-2x.jpg') txt_img_dic[img_t] = img_l except: pass return txt_img_dic #CONVERT THE CRAPPED DIC TO LIST def txt_img_d2l(dict_t_i): img_lst = [] for i in range(len(dict_t_i)): img_lst.append([list(f.keys())[i], list(f.values())[i]]) return img_lst #GETTING COMPLETE LIST def complete_img_l(img_lst): for i in range(len(img_lst)): frm_2 = img_lst[i][1].replace('1-2x.jpg', '2-2x.jpg') frm_3 = img_lst[i][1].replace('1-2x.jpg', '3-2x.jpg') frm_4 = img_lst[i][1].replace('1-2x.jpg', '4-2x.jpg') frm_5 = img_lst[i][1].replace('1-2x.jpg', '5-2x.jpg') img_lst[i].append(frm_2) img_lst[i].append(frm_3) img_lst[i].append(frm_4) img_lst[i].append(frm_5) return img_lst import pickle def picklify_lst(lst, fn): with open(fn+".txt", "wb") as fp: #Pickling pickle.dump(lst, fp) print('Completed Picklifying.\n\n') def picklify(lst, fn): with open(fn+".txt", "wb") as fp: #Pickling pickle.dump(lst, fp) print('Completed Picklifying.\n\n') def pickle_loader(fn): with open(fn, "rb") as fp: # Unpickling b = pickle.load(fp) print('Completed Loading.\n\n') return b import requests import os def tweet_post(message, url=None): if (url): filename = 'temp.jpg' request = requests.get(url, stream=True) if request.status_code == 200: with open(filename, 'wb') as image: for chunk in request: image.write(chunk) api.PostUpdate(media=filename, status=message) os.remove(filename) print("Done.") else: print("Unable to download image.") else: api.PostUpdate(status=message) print("Done.")
""" Links the values of array in "x", "y" or "z" direction. Example: Arrays sent: |---o---|---o---|---o---|---o---|---o---|---o---| 0 1 2 3 4 5 Returnig: |---o---|---o---|---o---|---o---|---o---|---o---| (0+5)/2 1 2 3 4 (0+5)/2 First and last value in the returning array will be the average of themselves. """ # ============================================================================= def link_avg_x(a): # ----------------------------------------------------------------------------- """ Args: a: matrix for linking. Returns: None, but input arguments are changed. """ a[ :1,:,:] = (a[ :1,:,:] + a[-1:,:,:]) * 0.5 a[-1:,:,:] = a[ :1,:,:] return # end of function # ============================================================================= def link_avg_y(a): # ----------------------------------------------------------------------------- """ Args: a: matrix for linking. Returns: None, but input arguments are changed. """ a[:, :1,:] = (a[:, :1,:] + a[:,-1:,:]) * 0.5 a[:,-1:,:] = a[:, :1,:] return # end of function # ============================================================================= def link_avg_z(a): # ----------------------------------------------------------------------------- """ Args: a: matrix for linking. Returns: None, but input arguments are changed. """ a[:,:, :1] = (a[:,:, :1] + a[:,:,-1:]) * 0.5 a[:,:,-1:] = a[:,:, :1] return # end of function
# Реализовать структуру «Рейтинг», представляющую собой убывающий набор натуральных чисел. # У пользователя необходимо запрашивать новый элемент рейтинга. # Если в рейтинге существуют элементы с одинаковыми значениями, # то новый элемент с тем же значением должен разместиться после них. # Подсказка. Например, набор натуральных чисел: 7, 5, 3, 3, 2. # Пользователь ввел число 3. Результат: 7, 5, 3, 3, 3, 2. # Пользователь ввел число 8. Результат: 8, 7, 5, 3, 3, 2. # Пользователь ввел число 1. Результат: 7, 5, 3, 3, 2, 1. # Набор натуральных чисел можно задать непосредственно в коде, например, my_list = [7, 5, 3, 3, 2]. # el = int(input("Insert value - ")) # rating = [7, 5, 3, 3, 2] # rating.insert() # print(sorted(rating)) list = [7, 5, 3, 3, 2] new_number = int(input('Insert new element -')) i = 0 for n in list: if new_number <= n: i += 1 list.insert(i, float(new_number)) print(list )
# Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, # но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. def int_func(a): return str.title(a) print(int_func(a = input('Insert lowercase text -> ')))
def f(n): if n == 1: return 1 return n * f(n-1) r = f(7) print(r) # 1 1 2 3 5 8 13 21 34 def fibonacci(n): if n == 2: return 2 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) k = fibonacci(10) print(k)
import random import math class Array(): def __init__(self, n): self.n = n self.arr = self.generate_arr() def generate_arr(self): arr = [] n = self.n for i in range(n): a = random.randint(10, 100) arr.append(a) return arr def ex231(self): s = 0 n = self.arr for i in range(len(n)): # print(n) if n[i] % 2 == 0: s += n[i]**2 return s def ex233(self): s = 1 t = 0 k = self.arr for i in range(len(k)): # print(k) if k[i] % 2 == 0: s *= k[i] t += k[i] return s, t def ex234(self): s = 0 t = 0 n = self.arr for i in range(len(n)): # print(n) if n[i] % 2 == 1: s += n[i]**2 t += 1 l = math.sqrt(s/t) return l def ex236(self): s = 1 t = 0 k = self.arr for i in range(len(k)): if k[i] % 2 == 1: s *= k[i] t += 1 return s, t def ex242(self, m): s = 1 arr = self.arr for i in range(len(arr)): # print(arr) if arr[i] % m == 0: s *= arr[i] return s def ex245(self): s = 0 n = self.arr for i in range(len(n)): if (n[i] + i) % 3 == 0: s += n[i]**2 return s def ex246(self): m = 0 n = 0 arr = self.arr for i in range(len(arr)): k = math.sqrt(arr[i]) if int(k) == k: print(k) m += arr[i] n += 1 q = m/n return q def ex248(self, k): s = 0 arr = self.arr for i in range(len(arr)): # print(arr) if (arr[i]+i) ** 2 % k == 0: s += arr[i] return s def ex249(self, k): s = 1 n = self.arr for i in range(len(n)): if abs(n[i]-i) > k: s *= n[i]**2 return s def ex256(self): s = 0 arr = self.arr mn = arr[0] for i in range(len(arr)): # print(arr) if arr[i] < mn: mn = arr[i] k = i s = mn +k return s a = Array(5) print(a.generate_arr()) print(a.ex231()) print(a.ex233()) print(a.ex234()) print(a.ex236()) print(a.ex242(5)) print(a.ex245()) # print(a.ex246()) print(a.ex248(5)) print(a.ex249(70)) print(a.ex256())
def replace_words(text, word_dic): """ replace words in text via a dictionary >>> text = 'A Colorful day in city Center.' >>> word_dic = {'Color': 'color', 'Center': 'sub'} >>> replace_words(text, word_dic) 'A colorful day in city sub.' """ import re yo = re.compile('|'.join(map(re.escape, word_dic))) def translate(mat): return word_dic[mat.group(0)] return yo.sub(translate, text)
from tkinter import * from tkinter import ttk root = Tk() lbl = ttk.Label(root, text="Starting...") lbl.grid() lbl.bind('<Enter>', lambda e: lbl.configure(text='Moved mouse inside')) lbl.bind('<Leave>', lambda e: lbl.configure(text='Moved mouse outside')) lbl.bind('<1>', lambda e: lbl.configure(text='Clicked left mouse button')) lbl.bind('<Double-1>', lambda e: lbl.configure(text='Double clicked')) lbl.bind('<B3-Motion>', lambda e: lbl.configure(text='right button drag to %d,%d' % (e.x, e.y))) root.mainloop()
from tkinter import * from tkinter import ttk # to use jpg image from PIL import Image, ImageTk root = Tk() # Frame frame = ttk.Frame(root) frame.grid() frame['padding'] = (5,10) frame['borderwidth'] = 2 frame['relief'] = 'raised' # 'sunken' # Label label = ttk.Label(frame, text="full name:") label.grid() resultsContents = StringVar() label['textvariable'] = resultsContents resultsContents.set('New value to display') gif = PhotoImage(file='image.gif') label['image'] = gif jpg_image = Image.open("small.jpg") jpg_photo = ImageTk.PhotoImage(jpg_image) label['image'] = jpg_photo label.image = jpg_photo # mainloop root.mainloop()
from math import sqrt from data import * class Vector2: def __init__(self, x, y): self.x = x self.y = y def tuple(self): return self.x, self.y def normalized(self): return Vector2(self.x / self.distance(), self.y/self.distance()) def __iter__(self): return self def __add__(self, other): if isinstance(other, Vector2): return Vector2(self.x + other.x, self.y + other.y) elif isinstance(other, int): return Vector2(self.x + other, self.y + other) def __sub__(self, other): if isinstance(other, Vector2): return Vector2(self.x - other.x, self.y - other.y) elif isinstance(other, int): return Vector2(self.x - other, self.y - other) def __mul__(self, other): if isinstance(other, Vector2): return Vector2(self.x * other.x, self.y * other.y) elif isinstance(other, int) or isinstance(other, float): return Vector2(self.x * other, self.y * other) def __truediv__(self, other): if isinstance(other, Vector2): return Vector2(self.x / other.x, self.y / other.y) elif isinstance(other, int) or isinstance(other, float): return Vector2(self.x / other, self.y / other) def distance(self): return sqrt(self.x**2 + self.y**2) def distance_between(vect1, vect2): return sqrt((vect1.x - vect2.x)**2 + (vect1.y - vect2.y)**2) class Node: def __init__(self, pos, weight=1, locked=False, radius=1): self.position = pos self.last_pos = pos self.weight = weight self.locked = locked self.radius = radius def move(self, dt, external_forces = Vector2(0, 0)): if not self.locked: next_pos = self.position + (self.position - self.last_pos) self.last_pos = self.position self.position = next_pos gravity_vector = Vector2(0, -gravity) self.position += (gravity_vector * (dt / 1000)) self.position += (external_forces * (dt / 1000)) def __iter__(self): return self class Line: def __init__(self, parents, stretch=0): self.parents = parents self.stretch = stretch self.length = Vector2.distance_between(parents[0].position, parents[1].position) def work(self, dt): first_node = self.parents[0] second_node = self.parents[1] current_distance = Vector2.distance_between(first_node.position, second_node.position) if current_distance > self.length: move_distance = (current_distance - self.length) / 2 if not first_node.locked: move = (second_node.position - first_node.position).normalized() * move_distance first_node.position += move if not second_node.locked: move = (first_node.position - second_node.position).normalized() * move_distance second_node.position += move def __iter__(self): return self class Camera: def __init__(self, position, zoom=10): self.position = position self.zoom = 1/zoom self.center_offset = (Vector2(screen_size[0], screen_size[1]) / 2) / unit * zoom def world_to_screen_pos(self, vector2): return (vector2 - self.position + self.center_offset) * unit * self.zoom def world_to_screen_unit(self, value): return value * unit * self.zoom def screen_to_world_unit(self, value): return value / (unit * self.zoom) def screen_to_world_pos(self, position): if isinstance(position, tuple): x = position[0] y = position[1] elif isinstance(position, Vector2): x = position.x y = position.y vector = Vector2(x, y) screen_size_vector = Vector2(screen_size[0], screen_size[1]) vector = (vector - (screen_size_vector / 2) + self.world_to_screen_unit(self.position)) / (self.zoom * unit) return vector
# Zachary Tarell - zjt170000 # Homework 1: Search Algorithms - 8 puzzle # CS 4365.501 Artificial Intelligence import sys from collections import deque from heapq import heappush, heappop, heapify class State: def __init__(self, state, parent, move, depth, cost, key): self.state = state self.parent = parent self.move = move self.depth = depth self.cost = cost self.key = key if self.state: self.map = ''.join(str(e) for e in self.state) def __eq__(self, other): return self.map == other.map def __lt__(self, other): return self.map < other.map goal_state = [1, 2, 3, 4, 5, 6, 7, 8, 0] goal_node = State initial_state = list() board_len = 9 # set as 9 (total spaces) a global because it's known 8-puzzle board_side = 3 # set as 3 (sqrt of total spaces) a global because it's known 8-puzzle nodes_expanded = 0 max_search_depth = 10 enqueued_states = 0 moves = list() costs = set() # Breadth-First Search def bfs(start_state): global enqueued_states, goal_node, max_search_depth explored, queue = set(), deque([State(start_state, None, None, 0, 0, 0)]) while queue: node = queue.popleft() explored.add(node.map) if node.state == goal_state: goal_node = node return queue neighbors = expand(node) for neighbor in neighbors: if neighbor.map not in explored: queue.append(neighbor) explored.add(neighbor.map) if neighbor.depth > max_search_depth: print('Goal Depth was not reached before 11 moves') quit(0) if len(queue) > enqueued_states: enqueued_states = len(queue) # Iterative Deepening Search def ids(start_state): global costs threshold = h_one(start_state) while 1: response = dls_mod(start_state, threshold) if type(response) is list: return response break threshold = response costs = set() # Depth-First Search that is passed to ids def dls_mod(start_state, threshold): global enqueued_states, goal_node, max_search_depth, costs explored, stack = set(), list([State(start_state, None, None, 0, 0, threshold)]) while stack: node = stack.pop() explored.add(node.map) if node.state == goal_state: goal_node = node return stack if node.key > threshold: costs.add(node.key) if node.depth < threshold: neighbors = reversed(expand(node)) for neighbor in neighbors: if neighbor.map not in explored: neighbor.key = neighbor.cost + h_one(neighbor.state) stack.append(neighbor) explored.add(neighbor.map) if neighbor.depth > max_search_depth: print('Goal Depth was not reached before 11 moves') quit(0) if len(stack) > enqueued_states: enqueued_states = len(stack) return min(costs) # Manhattan Distance Heuristic def h_one(state): return sum(abs(b % board_side - g % board_side) + abs(b // board_side - g // board_side) for b, g in ((state.index(i), goal_state.index(i)) for i in range(1, board_len))) # A* Search with Manhattan Distance as heuristic 1 def astar1(start_state): global enqueued_states, goal_node, max_search_depth explored, heap, heap_entry = set(), list(), {} key = h_one(start_state) root = State(start_state, None, None, 0, 0, key) entry = (key, 0, root) heappush(heap, entry) heap_entry[root.map] = entry while heap: node = heappop(heap) explored.add(node[2].map) if node[2].state == goal_state: goal_node = node[2] return heap neighbors = expand(node[2]) for neighbor in neighbors: neighbor.key = neighbor.cost + h_one(neighbor.state) entry = (neighbor.key, neighbor.move, neighbor) if neighbor.map not in explored: heappush(heap, entry) explored.add(neighbor.map) heap_entry[neighbor.map] = entry if neighbor.depth > max_search_depth: print('Goal Depth was not reached before 11 moves') quit(0) elif neighbor.map in heap_entry and neighbor.key < heap_entry[neighbor.map][2].key: hindex = heap.index((heap_entry[neighbor.map][2].key, heap_entry[neighbor.map][2].move, heap_entry[neighbor.map][2])) heap[int(hindex)] = entry heap_entry[neighbor.map] = entry heapify(heap) if len(heap) > enqueued_states: enqueued_states = len(heap) # Misplaced Tiles Heuristic def h_two(state): count = 0 for i in range(1, board_len): if state[i] != goal_state[i]: count += 1 return count # A* Search with Misplaced Tiles as heuristic 2 def astar2(start_state): global enqueued_states, goal_node, max_search_depth explored, heap, heap_entry = set(), list(), {} key = h_two(start_state) root = State(start_state, None, None, 0, 0, key) entry = (key, 0, root) heappush(heap, entry) heap_entry[root.map] = entry while heap: node = heappop(heap) explored.add(node[2].map) if node[2].state == goal_state: goal_node = node[2] return heap neighbors = expand(node[2]) for neighbor in neighbors: neighbor.key = neighbor.cost + h_two(neighbor.state) entry = (neighbor.key, neighbor.move, neighbor) if neighbor.map not in explored: heappush(heap, entry) explored.add(neighbor.map) heap_entry[neighbor.map] = entry if neighbor.depth > max_search_depth: print('Goal Depth was not reached before 11 moves') quit(0) elif neighbor.map in heap_entry and neighbor.key < heap_entry[neighbor.map][2].key: hindex = heap.index((heap_entry[neighbor.map][2].key, heap_entry[neighbor.map][2].move, heap_entry[neighbor.map][2])) heap[int(hindex)] = entry heap_entry[neighbor.map] = entry heapify(heap) if len(heap) > enqueued_states: enqueued_states = len(heap) # Expanding the nodes def expand(node): global nodes_expanded nodes_expanded += 1 neighbors = list() neighbors.append(State(move(node.state, 1), node, 1, node.depth + 1, node.cost + 1, 0)) neighbors.append(State(move(node.state, 2), node, 2, node.depth + 1, node.cost + 1, 0)) neighbors.append(State(move(node.state, 3), node, 3, node.depth + 1, node.cost + 1, 0)) neighbors.append(State(move(node.state, 4), node, 4, node.depth + 1, node.cost + 1, 0)) nodes = [neighbor for neighbor in neighbors if neighbor.state] return nodes # moving each index to new empty state def move(state, position): new_state = state[:] index = new_state.index(0) if position == 1: # Up if index not in range(0, board_side): temp = new_state[index - board_side] new_state[index - board_side] = new_state[index] new_state[index] = temp return new_state else: return None if position == 2: # Down if index not in range(board_len - board_side, board_len): temp = new_state[index + board_side] new_state[index + board_side] = new_state[index] new_state[index] = temp return new_state else: return None if position == 3: # Left if index not in range(0, board_len, board_side): temp = new_state[index - 1] new_state[index - 1] = new_state[index] new_state[index] = temp return new_state else: return None if position == 4: # Right if index not in range(board_side - 1, board_len, board_side): temp = new_state[index + 1] new_state[index + 1] = new_state[index] new_state[index] = temp return new_state else: return None # Back tracing to keep track of parent nodes def backtrace(): current_node = goal_node while initial_state != current_node.state: if current_node.move == 1: movement = 'Up' elif current_node.move == 2: movement = 'Down' elif current_node.move == 3: movement = 'Left' else: movement = 'Right' print("Movement:", movement) print(current_node.state[0], current_node.state[1], current_node.state[2]) print(current_node.state[3], current_node.state[4], current_node.state[5]) print(current_node.state[6], current_node.state[7], current_node.state[8], "\n") moves.insert(0, movement) current_node = current_node.parent return moves # Export moves for outputting proper game states, moves, and total enqueued def export(): global moves moves = backtrace() for i in range(len(initial_state)): if initial_state[i] == 0: initial_state[i] = "*" print(initial_state[0], initial_state[1], initial_state[2], "(Initial input state)") print(initial_state[3], initial_state[4], initial_state[5]) print(initial_state[6], initial_state[7], initial_state[8], "\n") print("Number of moves: " + str(len(moves))) print("Number of states enqueued: " + str(enqueued_states)) # read in inputs def read(configuration): global board_len, board_side data = configuration.split(" ") for element in data: if element == "*": element = element.replace("*", "0") initial_state.append(int(element)) def main(): if len(sys.argv) > 1: algorithm = sys.argv[1] board = sys.argv[2] read(board) function = function_map[algorithm] function(initial_state) export() function_map = { 'bfs': bfs, 'ids': ids, 'astar1': astar1, 'astar2': astar2 } if __name__ == '__main__': main()
#!/usr/bin/python3 def no_c(my_string): new_string = "" for i in my_string: if i is "c" or i is "C": continue new_string = new_string + i return new_string
"""Unittest for class Square """ import unittest import sys import io from models.base import Base from models.rectangle import Rectangle from models.square import Square class TestSquareClass(unittest.TestCase): def test_is_subclass(self): """test Square is subclass of Base or not""" r = Square(1, 1) self.assertIsInstance(r, Base) self.assertIsNot(r, Base) def test_id_no_input(self): """test id with no input""" Base._Base__nb_objects = 0 b1 = Square(1, 1, 1) self.assertEqual(b1.id, 1) self.assertEqual(b1.id, Square._Base__nb_objects) b2 = Square(1, 1, 1) self.assertEqual(b2.id, 2) self.assertEqual(b2.id, Square._Base__nb_objects) def test_id_datatype(self): """test id with different data type""" Base._Base__nb_objects = 0 b3 = Square(1, 1, 1, 12) self.assertEqual(b3.id, 12) b4 = Square(1, 1, 1, "string") self.assertEqual(b4.id, "string") b5 = Square(1, 1, 1, {id: 1}) self.assertEqual(b5.id, {id: 1}) b7 = Square(1, 1, 1, [1]) self.assertEqual(b7.id, [1]) b8 = Square(1, 1, 1, 2.4) self.assertEqual(b8.id, 2.4) b9 = Square(1, 1, 1, (1, 2)) self.assertEqual(b9.id, (1, 2)) b10 = Square(1, 1, 1, {1, 2}) self.assertEqual(b10.id, {1, 2}) b11 = Square(1, 1, 1, True) self.assertEqual(b11.id, True) b12 = Square(1, 1, 1, False) self.assertEqual(b12.id, False) bN = Square(1, 1, 1, None) self.assertEqual(bN.id, 1) self.assertEqual(bN.id, Square._Base__nb_objects) def test_id_special_case(self): """test id with special cases""" b6 = Square(1, 1, 1, float('nan')) self.assertNotEqual(b6.id, b6.id) b6 = Square(1, 1, 1, float('inf')) self.assertEqual(b6.id, float('inf')) def test_size_int_success(self): """test size with integer that is greater than 0""" b1 = Square(2) self.assertEqual(b1.size, 2) self.assertEqual(b1.width, 2) self.assertEqual(b1.height, 2) b2 = Square(4, 1, 1) self.assertEqual(b2.size, 4) self.assertEqual(b2.width, 4) self.assertEqual(b2.height, 4) b3 = Square(23, 1, 12) self.assertEqual(b3.size, 23) self.assertEqual(b3.width, 23) self.assertEqual(b3.height, 23) def test_size_int_fail(self): """test width and height with integer that is equal or less than 0 """ with self.assertRaisesRegex(ValueError, "width must be > 0"): Square(-1, 1) with self.assertRaisesRegex(ValueError, "width must be > 0"): Square(0, -1) with self.assertRaisesRegex(ValueError, "width must be > 0"): Square(size=-1) with self.assertRaisesRegex(ValueError, "width must be > 0"): Square(size=0) def test_size_special_case(self): """test width and height with special cases""" with self.assertRaisesRegex(TypeError, "width must be an integer"): Square(float('nan'), 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square(float('inf'), 1) def test_size_isInt(self): """test size with non int data type""" with self.assertRaisesRegex(TypeError, "width must be an integer"): Square("a", 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square({1}, 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square([1], 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square({1: 2}, 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square((1, 2), 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square(True, 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square(False, 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square(None, 1) with self.assertRaisesRegex(TypeError, "width must be an integer"): Square("a", "b") with self.assertRaisesRegex(TypeError, "width must be an integer"): Square(1.5, 2) def test_x_y_int_success(self): """test x and y with integer that is greater or equal 0""" b1 = Square(2, 2, 2) self.assertEqual(b1.x, 2) self.assertEqual(b1.y, 2) b2 = Square(4, 3, 4) self.assertEqual(b2.x, 3) self.assertEqual(b2.y, 4) b3 = Square(40, 23, 40, 12) self.assertEqual(b3.x, 23) self.assertEqual(b3.y, 40) b4 = Square(40, 0, 0, 0) self.assertEqual(b4.x, 0) self.assertEqual(b4.y, 0) def test_x_y_int_fail(self): """test x and y with integer that is less than 0 """ with self.assertRaisesRegex(ValueError, "x must be >= 0"): Square(1, -2) with self.assertRaisesRegex(ValueError, "y must be >= 0"): Square(1, 1, -2) with self.assertRaisesRegex(ValueError, "x must be >= 0"): Square(1, -1, -1) def test_x_y_special_case(self): """test x and y with special cases""" with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, float('nan'), 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, float('inf'), 1) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, float('nan'), 1) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, float('inf'), 1) def test_x_isInt(self): """test x with non int data type""" with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, "a", 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, {1}, 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, [1], 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, {1: 2}, 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, (1, 2), 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, True, 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, False, 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, None, 1) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, "a", "b") with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, 1.5, 2) def test_y_isInt(self): """test y with non int data type""" with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, "a") with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, {1, 2}) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, [1, 2]) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, {1: 2}) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, (1, 2)) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, True) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, False) with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, None) with self.assertRaisesRegex(TypeError, "x must be an integer"): Square(1, "a", "b") with self.assertRaisesRegex(TypeError, "y must be an integer"): Square(1, 1, 2.4) def test_area(self): """test area of Square""" self.assertEqual(Square(3).area(), 9) self.assertEqual(Square(2, 0).area(), 4) self.assertEqual(Square(2, 2, 0, 0).area(), 4) def test_display(self): """test display method""" out = io.StringIO() sys.stdout = out Square(2).display() output = out.getvalue() self.assertEqual(output, "##\n##\n") out = io.StringIO() sys.stdout = out Square(3).display() output = out.getvalue() self.assertEqual(output, "###\n###\n###\n") out = io.StringIO() sys.stdout = out Square(3, 1, 1).display() output = out.getvalue() self.assertEqual(output, "\n ###\n ###\n ###\n") out = io.StringIO() sys.stdout = out Square(3, 2, 3).display() output = out.getvalue() self.assertEqual(output, "\n\n\n ###\n ###\n ###\n") out = io.StringIO() sys.stdout = out Square(3, 0, 0).display() output = out.getvalue() self.assertEqual(output, "###\n###\n###\n") def test_str(self): """test str method""" Base._Base__nb_objects = 0 r1 = Square(6, 2, 1, 12) self.assertEqual(str(r1), "[Square] (12) 2/1 - 6") r2 = Square(5, 1) self.assertEqual(str(r2), "[Square] (1) 1/0 - 5") r3 = Square(1, 2, 4) self.assertEqual(str(r3), "[Square] (2) 2/4 - 1") def test_update_int_success(self): """test update method""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") r1.update(89) self.assertEqual(str(r1), "[Square] (89) 10/10 - 10") r1.update(89, 2) self.assertEqual(str(r1), "[Square] (89) 10/10 - 2") r1.update(89, 2, 3) self.assertEqual(str(r1), "[Square] (89) 3/10 - 2") r1.update(89, 2, 3, 4) self.assertEqual(str(r1), "[Square] (89) 3/4 - 2") def test_update_id_noKeyword(self): """test update id with no-keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") r1.update("string") self.assertEqual(str(r1), "[Square] (string) 10/10 - 10") r1.update([1]) self.assertEqual(str(r1), "[Square] ([1]) 10/10 - 10") r1.update({1}) self.assertEqual(str(r1), "[Square] ({1}) 10/10 - 10") r1.update((1, 1)) self.assertEqual(str(r1), "[Square] ((1, 1)) 10/10 - 10") r1.update({'key': 2}) self.assertEqual(str(r1), "[Square] ({'key': 2}) 10/10 - 10") r1.update(2.4) self.assertEqual(str(r1), "[Square] (2.4) 10/10 - 10") r1.update(True) self.assertEqual(str(r1), "[Square] (True) 10/10 - 10") r1.update(False) self.assertEqual(str(r1), "[Square] (False) 10/10 - 10") r1.update(None) self.assertEqual(str(r1), "[Square] (2) 10/10 - 10") r1.update(float('nan')) self.assertNotEqual(r1.id, r1.id) r1.update(float('inf')) self.assertEqual(str(r1), "[Square] (inf) 10/10 - 10") def test_update_id_Keyword(self): """test update id with keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") r1.update(id="string") self.assertEqual(str(r1), "[Square] (string) 10/10 - 10") r1.update(id=[1]) self.assertEqual(str(r1), "[Square] ([1]) 10/10 - 10") r1.update(id={1}) self.assertEqual(str(r1), "[Square] ({1}) 10/10 - 10") r1.update(id=(1, 1)) self.assertEqual(str(r1), "[Square] ((1, 1)) 10/10 - 10") r1.update(id={'key': 2}) self.assertEqual(str(r1), "[Square] ({'key': 2}) 10/10 - 10") r1.update(id=2.4) self.assertEqual(str(r1), "[Square] (2.4) 10/10 - 10") r1.update(id=True) self.assertEqual(str(r1), "[Square] (True) 10/10 - 10") r1.update(id=False) self.assertEqual(str(r1), "[Square] (False) 10/10 - 10") r1.update(id=None) self.assertEqual(str(r1), "[Square] (2) 10/10 - 10") r1.update(id=float('nan')) self.assertNotEqual(r1.id, r1.id) r1.update(id=float('inf')) self.assertEqual(str(r1), "[Square] (inf) 10/10 - 10") def test_update_size_noKeyword(self): """test update size with no-keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, "string") with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, [1]) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, {1}) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, (1, 1)) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, {'key': 2}) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, 2.4) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, True) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, False) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, None) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, float('nan')) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(10, float('inf')) def test_update_size_Keyword(self): """test update size with keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size="string") with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=[1]) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size={1}) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=(1, 1)) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size={'key': 2}) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=2.4) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=True) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=False) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=None) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=float('nan')) with self.assertRaisesRegex(TypeError, "width must be an integer"): r1.update(size=float('inf')) def test_update_size_int_fail(self): """test size with integer that is equal or less than 0 """ Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") with self.assertRaisesRegex(ValueError, "width must be > 0"): r1.update(0, -1, 1) with self.assertRaisesRegex(ValueError, "width must be > 0"): r1.update(1, -1, -1) with self.assertRaisesRegex(ValueError, "width must be > 0"): r1.update(1, 0, 1) with self.assertRaisesRegex(ValueError, "width must be > 0"): r1.update(size=-1) with self.assertRaisesRegex(ValueError, "width must be > 0"): r1.update(size=-3) with self.assertRaisesRegex(ValueError, "width must be > 0"): r1.update(size=0) def test_update_x_noKeyword(self): """test update x with no-keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") r1.update(10, 10, 0) self.assertEqual(str(r1), "[Square] (10) 0/10 - 10") with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, "string") with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, [1]) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, {1}) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, (1, 1)) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, {'key': 2}) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, 2.4) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, True) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, False) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, None) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, float('nan')) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(10, 10, float('inf')) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(20, 10, 2.4, 2.3) def test_update_x_Keyword(self): """test update x with keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") r1.update(x=0) self.assertEqual(str(r1), "[Square] (1) 0/10 - 10") with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x="string") with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=[1]) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x={1}) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=(1, 1)) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x={'key': 2}) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=2.4) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=True) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=False) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=None) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=float('nan')) with self.assertRaisesRegex(TypeError, "x must be an integer"): r1.update(x=float('inf')) def test_update_y_noKeyword(self): """test update y with no-keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") r1.update(10, 10, 10, 0) self.assertEqual(str(r1), "[Square] (10) 10/0 - 10") with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, "string") with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, [1]) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, {1}) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, (1, 1)) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, {'key': 2}) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, 2.4) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, True) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, False) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, None) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, float('nan')) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(10, 10, 10, float('inf')) def test_update_y_Keyword(self): """test update y with keyword argument""" Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") r1.update(y=0) self.assertEqual(str(r1), "[Square] (1) 10/0 - 10") with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y="string") with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=[1]) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y={1}) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=(1, 1)) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y={'key': 2}) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=2.4) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=True) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=False) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=None) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=float('nan')) with self.assertRaisesRegex(TypeError, "y must be an integer"): r1.update(y=float('inf')) def test_update_x_y_int_fail(self): """test x and y with integer that is less than 0 """ Base._Base__nb_objects = 0 r1 = Square(10, 10, 10) self.assertEqual(str(r1), "[Square] (1) 10/10 - 10") with self.assertRaisesRegex(ValueError, "x must be >= 0"): r1.update(1, 1, -1, 1) with self.assertRaisesRegex(ValueError, "y must be >= 0"): r1.update(1, 1, 1, -1) with self.assertRaisesRegex(ValueError, "x must be >= 0"): r1.update(1, 1, -1, -1) with self.assertRaisesRegex(ValueError, "x must be >= 0"): r1.update(x=-1) with self.assertRaisesRegex(ValueError, "y must be >= 0"): r1.update(y=-2) with self.assertRaises(ValueError): r1.update(y=-2, x=-1) def test_to_dictionary(self): """test to_dictionary medthod""" Base._Base__nb_objects = 0 r1 = Square(2, 1, 9) r1_d = r1.to_dictionary() d = {'x': 1, 'y': 9, 'id': 1, 'size': 2} self.assertDictEqual(r1_d, d) self.assertEqual(type(r1_d), dict) r2 = Square(1, 1) r2.update(**r1_d) self.assertNotEqual(r1, r2) def test_to_dictionary_with_args(self): """test to dictionary with arguments""" r1 = Square(10, 2, 1, 9) with self.assertRaises(TypeError): r1.to_dictionary(1) with self.assertRaises(TypeError): r1.to_dictionary([1]) with self.assertRaises(TypeError): r1.to_dictionary({1}) with self.assertRaises(TypeError): r1.to_dictionary("s") with self.assertRaises(TypeError): r1.to_dictionary({'key': 1}) with self.assertRaises(TypeError): r1.to_dictionary(1.2) with self.assertRaises(TypeError): r1.to_dictionary(True) with self.assertRaises(TypeError): r1.to_dictionary(False) with self.assertRaises(TypeError): r1.to_dictionary(None) with self.assertRaises(TypeError): r1.to_dictionary(float('nan')) with self.assertRaises(TypeError): r1.to_dictionary(float('inf')) with self.assertRaises(TypeError): r1.to_dictionary(1, 2) if __name__ == '__main__': unittest.main()
import numpy as np import random class NeuralNet: def __init__(self, structure, learning_rate): """ Initialize the Neural Network. - structure is a dictionary with the following keys defined: num_inputs num_outputs num_hidden - learning rate is a float that should be used as the learning rate coefficient in training Initialize weights to random values in the range [-0.05, 0.05]. Initialize global variables """ self.learn = learning_rate self.num_in = structure['num_inputs'] + 1 self.num_out = structure['num_outputs'] self.num_hid = structure['num_hidden'] self.input = [] self.output = [] self.hidden = [] self.weights1 = ((np.random.rand(self.num_in, self.num_hid)) - 0.5) / 10.0 self.weights2 = ((np.random.rand(self.num_hid, self.num_out)) - 0.5) / 10.0 def sigmoid(self, unit): """ Sigmoid activation function :param unit: value(s) to be activated. :type unit: float, scalar, or vector :return type: float """ return 1/(1+np.exp(-unit)) def forward_propagate(self, x): """ Push the input 'x' through the network :param x: vecor of inputs to the network :type x: vector :return type: vector :return: activation on the output nodes. """ x = np.append(x,[1.0]) # add bias hidden_row = np.dot(x, self.weights1) hidden_row_activated = self.sigmoid(hidden_row) output_row = np.dot(hidden_row_activated, self.weights2) output_final = self.sigmoid(output_row) self.input = x self.hidden = hidden_row_activated self.output = output_final return output_final #old iterative code ''' hidden_row = [] for hidden1 in range(self.num_hid): total = 0 for inp in range(self.num_in): total = total + (self.weights1[inp][hidden1]* x[inp]) sig = 1/(1+np.exp(-total)) hidden_row.append(sig) output_row = [] for out in range(self.num_out): total = 0 for hidden2 in range(self.num_hid): total = total + (self.weights2[hidden2][out] * hidden_row[hidden2]) sig = 1/(1+np.exp(-total)) output_row.append(sig) self.input = x self.hidden = hidden_row self.output = output_row return output_row''' def back_propagate(self, target): """ Updates the weights of the network based on the last forward propagate :param target: the (correct) label of the last forward_propagate call :type target: vector :return: None """ # calculate error between output layer and hidden layer first_step_errors = [] for i in range(self.num_hid): unit_error = 0 for j in range(self.num_out): y = self.output[j] x = self.hidden[i] t = target[j] E = (y-t) unit_error += (E*(y*(1-y)))*self.weights2[i][j] de_dw = (E * (y * (1-y))) * x self.weights2[i][j] = self.weights2[i][j] - self.learn * de_dw # change weights first_step_errors.append(unit_error) # Calculate error between hidden layer and input layer for k in range(self.num_in): for l in range(self.num_hid): y = self.hidden[l] x = self.input[k] E = first_step_errors[l] de_dw = (E * (y * (1-y))) * x self.weights1[k][l] -= self.learn * de_dw # change weights def train(self, X, Y, iterations=1000): """ Trains the network on observations X with labels Y. :param X: matrix corresponding to a series of observations - each row is one observation :type X: numpy matrix "param Y: matrix corresponding to the correct labels for the observations :type Y: numpy matrix :return: None """ for it in range(iterations): for idx in range(len(X)): x = X[idx] y = Y[idx] self.forward_propagate(x) self.back_propagate(y) def test(self, X, Y): """ Tests the network on observations X with labels Y. :param X: matrix corresponding to a series of observations - each row is one observation :type X: numpy matrix "param Y: matrix corresponding to the correct labels for the observations :type Y: numpy matrix :return: mean squared error, float """ total_error = 0 for i in range(len(X)): x = self.forward_propagate(X[i]) t = Y[i] vector_diff = 0 for j in range(len(x)): vector_diff += (x[j]-t[j])**2 total_error += (vector_diff/len(x)) return total_error/len(Y)
# imports from maze import * from sys import * import pygame from math import floor WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255) INVO = (210,103,40) class MazeView: """ Provide some functions to visualise the result of the maze generator """ #-------------------------------------------------------------------------------------# # function definitions for drawing the maze with pygame # #-------------------------------------------------------------------------------------# def __init__(self, cell = 102 , wall = 10, directory = "datas/generated/defaultMuseum", writeMap = False): self.cellSize = cell self.wallSize = wall self.writeDirectory = directory self.writeMap = writeMap # generates a window with maze with all cells isolated from each other def base_window(self, m): winwidth = m.cols*self.cellSize+(m.cols+1)*self.wallSize winheight = m.rows*self.cellSize+(m.rows+1)*self.wallSize w = pygame.display.set_mode((winwidth,winheight)) pygame.display.set_caption("Museum map") w.fill(BLACK) for i in range(m.rows): for j in range(m.cols): pygame.draw.rect(w,WHITE,(self.wallSize+(j*self.cellSize+j*self.wallSize),self.wallSize+(i*self.cellSize+ i*self.wallSize),self.cellSize,self.cellSize)) return w #-------------------------------------------------------------------------------------- # knocks down walls from base_window to create the path def maze_window(self, m): w = self.base_window(m) for i in range(m.rows): for j in range(m.cols): if not m.maze[i][j][BOTTOMWALL]: pygame.draw.rect(w,WHITE,(j*self.cellSize+(j+1)*self.wallSize,(i+1)*self.cellSize+(i+1) *self.wallSize,self.cellSize,self.wallSize)) if not m.maze[i][j][RIGHTWALL]: pygame.draw.rect(w,WHITE,((j+1)*self.cellSize+(j+1)*self.wallSize,i*self.cellSize+(i+1) *self.wallSize,self.wallSize,self.cellSize)) pygame.display.update() return w #-------------------------------------------------------------------------------------- # paints the solution path in the maze window def maze_path_window(self, m,w): path = m.solutionpath # print every cell within the solution path for index in range(len(path)-1): actrow = path[index][0] actcol = path[index][1] nextrow = path[index+1][0] nextcol = path[index+1][1] pygame.draw.rect(w,RED,(actcol*self.cellSize+(actcol+1)*self.wallSize,actrow*self.cellSize+(actrow+ 1)*self.wallSize,self.cellSize,self.cellSize)) # also paint the white spaces between the cells if actrow == nextrow: if actcol < nextcol: pygame.draw.rect(w,RED,((actcol+1)*self.cellSize+(actcol+1)*self.wallSize,actrow*self.cellSize+ (actrow+1)*self.wallSize,self.wallSize,self.cellSize)) else: pygame.draw.rect(w,RED,(actcol*self.cellSize+actcol*self.wallSize,actrow*self.cellSize+(actrow+ 1)*self.wallSize,self.wallSize,self.cellSize)) elif actcol == nextcol: if actrow < nextrow: pygame.draw.rect(w,RED,(actcol*self.cellSize+(actcol+1)*self.wallSize,(actrow+1)*self.cellSize+ (actrow+1)*self.wallSize,self.cellSize,self.wallSize)) else: pygame.draw.rect(w,RED,(actcol*self.cellSize+(actcol+1)*self.wallSize,actrow*self.cellSize+ actrow*self.wallSize,self.cellSize,self.wallSize)) # add a different color for start and end cells startrow = path[0][0] startcol = path[0][1] endrow = path[-1][0] endcol = path[-1][1] pygame.draw.rect(w,BLUE,(startcol*self.cellSize+(startcol+1)*self.wallSize,startrow*self.cellSize+( startrow+1)*self.wallSize,self.cellSize,self.cellSize)) pygame.draw.rect(w,GREEN,(endcol*self.cellSize+(endcol+1)*self.wallSize,endrow*self.cellSize+(endrow+ 1)*self.wallSize,self.cellSize,self.cellSize)) pygame.display.update() if self.writeMap: filename = self.writeDirectory + "map.bmp" pygame.image.save(w, filename) print "Full map successfully saved to " + filename for index in range(0,len(path)): surface = w.copy() actrow = path[index][0] actcol = path[index][1] pygame.draw.rect(surface,INVO,(actcol*self.cellSize+(actcol+1)*self.wallSize,actrow*self.cellSize+( actrow+1)*self.wallSize,self.cellSize,self.cellSize)) filename = self.writeDirectory + "map"+str(index)+".bmp" pygame.image.save(surface, filename) print "Partial map successfully saved to" + filename def visualize(mazeValue, dirFile = "datas/generated/defaultMuseum"): #mazeValue.solve_maze() #print maze #print maze.solutionpath # show the maze with the solution path mazeView = MazeView (108,12,dirFile, True) pygame.init() window = mazeView.maze_window(mazeValue) mazeView.maze_path_window(mazeValue,window) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #================================================================================# # Main Program # #================================================================================# def main_function(rows, cols , recursive = False, cell = 102 , wall = 10): # sizes and colors maze = [] # generate random maze, solve it if recursive : minSize = floor((rows * cols) * 0.7) result = maze_search(rows, cols, minSize) maze = result[0] else : maze = Maze(rows,cols) maze.solve_maze() print maze #print maze #print maze.solutionpath # show the maze with the solution path mazeView = MazeView (cell,wall) pygame.init() window = mazeView.maze_window(maze) mazeView.maze_path_window(maze,window) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if __name__ == "__main__": if argv[1] == "-h": print "Usage : numbersRows numbersCols sizeCell sizeWall \n ex : python mazeView.py 100 100 10 2" exit(0) # get the maze size from program arguments rows = int(argv[1]) cols = int(argv[2]) sizeCell = int(argv[3]) sizeWall = int(argv[4]) main_function(rows, cols, False,sizeCell ,sizeWall ) # if ( argv[5] == 'T'): # main_function(rows, cols, False,sizeCell ,sizeWall ) # else : # main_function(rows, cols, True, sizeCell ,sizeWall)
class Pizza(): def __init__(self,tipo): self.ingredientes = ["Mozzarella","Tomate"] self.tipo = tipo def seleccion(self): pass def agregar(self,agregado): self.agregado = agregado self.ingredientes.append(self.agregado) def mostrar(self): self.ing = str(self.ingredientes).replace("[","") self.ing = self.ing.replace("]","") self.ing = self.ing.replace("'","") print("La pizza es ", self.tipo," y sus ingredientes son ", self.ing) class Vegetariana(Pizza): def seleccion(self): ing = int(input("Seleccione uno de los siguientes ingredientes: \n 1-Pimiento \n 2-Tofu \n")) if ing == 1: i = "Pimiento" if ing == 2: i = "Tofu" self.agregar(i) class Clasica(Pizza): def seleccion(self): ing = int(input("Seleccione uno de los siguientes ingredientes: \n 1-Peperoni \n 2-Jamon \n 3-Salmon \n")) if ing == 1: i = "Peperoni" if ing == 2: i = "Jamon" if ing == 3: i = "Salmon" self.agregar(i) def main(): selec = input("Seleecione el tipo de pizza \n 1-Vegetariana \n 2-Clasica \n") if selec == "1": pizza = Vegetariana("Vegetariana") pizza.seleccion() pizza.mostrar() elif selec == "2": pizza = Clasica("Clasica") pizza.seleccion() pizza.mostrar() else: print("Opcion no valida") if __name__ == "__main__": main()
""" Ejercicio 6 Escribir un programa que pida al usuario un número entero y muestre por pantalla si es un número primo o no. """ def primo(num): if num < 2: return False for i in range(2, num): if num % i == 0: return False return True def start(): num = int(input("Ingrese el numero a analizar: ")) if primo(num): print("Es primo") else: print("No es primo") start()
""" Ejercicio 13 Generar 10 números aleatorios, mostrarlos por pantalla y mostrar el promedio. """ from random import randint promedio = 0 for i in range(10): numero = randint(0,10) print(numero) promedio = promedio + numero print(promedio/10)
class Alumno(): def __init__(self,sexo,nombre): self.sexo = sexo self.nombre = nombre def separar(self): if (self.sexo == "M" and self.nombre[0]<= "M") or (self.sexo == "H" and self.nombre[0]>= "N"): print("Pertenece al Grupo A") else: print("Pertenece al Grupo B") def main(): sexo = input("Ingrese H si es hombre o M si es mujer: \n") nombre = input("Ingrese su nombre: ") alumno = Alumno(sexo,nombre) alumno.separar() if __name__ == "__main__": main()
""" Ejercicio 18 Modificar el programa del ejercicio 17 agregando un control de datos vacíos. Si por algún motivo alguno de los datos viene vacío o igual a "" debemos generar una excepción indicando que ocurrió un problema con la fuente de datos y notificar por pantalla. La excepción debe ser una excepción propia. """ import json class ValorVacio(ValueError): def __init__(self): super(ValorVacio, self).__init__() class Ventas(): def __init__(self, path): self.path = path self.documento = open(self.path,"r") self.texto = self.documento.read() self.filas = self.texto.split("\n") def pasar_JSON(self): self.datos= {} self.datos['ventas'] = [] for valor in self.filas : lista = valor.split(",") self.datos['ventas'].append({ 'nombre': lista[0], 'monto': lista[1], 'descripcion': lista[2], 'formapago': lista[3]}) with open('ARCHIVO_ORIGINAL.json', 'w') as file: json.dump(self.datos, file, indent=4) def mostrar(self): with open('ARCHIVO_ORIGINAL.json') as file: datos = json.load(file) for venta in datos['ventas']: try: values = venta.values() if "" in values: raise ValorVacio() else: print('Nombre: ', venta['nombre']) print('Monto: $', venta['monto']) print('Descripcion: ', venta['descripcion']) print('Forma de pago: ', venta['formapago']) print('') except ValorVacio: print ("---------ERROR----------") print("Error en los datos del cliente: ", venta['nombre']) print ('Ningun valor puede estar vacio') print("\n") """ Ejemplo: venta = Ventas("c:/Users/amaro/OneDrive/Documents/Programacion 1/TP1/datos_ventas.txt") venta.pasar_JSON() venta.mostrar() """
from decimal import * class Value: def bellardBig(self,n): pi = Decimal(0) k = 0 while k < n: pi += (Decimal(-1)**k/(1024**k))*( Decimal(256)/(10*k+1) + Decimal(1)/(10*k+9) - Decimal(64)/(10*k+3) - Decimal(32)/(4*k+1) - Decimal(4)/(10*k+5) - Decimal(4)/(10*k+7) -Decimal(1)/(4*k+3)) k += 1 pi = pi * 1/(2**6) print(self) return pi if __name__=="__main__": instan=Value(); x=instan.bellardBig(2); print ("3.141765873015873015873015873"); # print the digit that required print( '%.4f' % x) print(x)
# Rename Images with Date Photo Taken # Purpose: Renames image files in a folder based on date photo taken from EXIF metadata # Author: Matthew Renze # Update: Clement Changeur # Usage: python rename.py input-folder # - input-folder = (optional) the directory containing the image files to be renamed # Examples: python.exe Rename.py C:\Photos # python.exe Rename.py # Behavior: # - Given a photo named "Photo Apr 01, 5 54 17 PM.jpg" # - with EXIF date taken of "4/1/2018 5:54:17 PM" # - when you run this script on its parent folder # - then it will be renamed "2018-04-01 17.54.17.jpg" # If name is taken, renamed by "xxx-1" or "xxx-2" etc.. # Notes: # - For safety, please make a backup before running this script # - Currently only designed to work with .jpg, .jpeg, and .png files # - EXIF metadata must exist or an error will occur # - If you omit the input folder, then the current working directory will be used instead. # Import libraries import os import sys import time from PIL import Image, ExifTags # Set list of valid file extensions valid_extensions = [".mp4", ".MP4", ".mov", ".MOV"] valid_image_extensions = [".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG"] # If folder path argument exists then use it # Else use the current running folder if len(sys.argv) < 1: folder_path = input_file_path = sys.argv[1] else: print("Start : Use current folder") folder_path = os.getcwd() # Get all files from folder file_names = os.listdir(folder_path) print(file_names) rename_number = 0 # For each file for file_name in file_names: is_image = False new_file_name = "" new_file_name_ext = "" try: # Get the file extension file_ext = os.path.splitext(file_name)[1] # If the file does not have a valid file extension # then skip it if file_ext in valid_image_extensions: is_image = True elif file_ext in valid_extensions: pass else: continue # Get the old file path old_file_path = os.path.join(folder_path, file_name) if is_image: # Open the image try: print("______________________________________") print("Open image :", file_name) image = Image.open(old_file_path) except: print("Fail to open image") is_image = False continue if is_image: try: # Get the date taken from EXIF metadata date_taken = image._getexif()[36867] # Close the image image.close() # Reformat the date taken to "YYYY-MM-DD HH-mm-ss" date_time = date_taken.replace(":", "-") # Change time format to HH.mm.ss dataStrip = date_time.split(" ") new_file_name = dataStrip[0] + " " + dataStrip[1].replace("-", ".") except: image.close() print("No data in EXIF metadata, take modified date") new_file_name = time.strftime( "%Y-%m-%d %H.%M.%S", time.localtime(os.path.getmtime(old_file_path)) ) print( time.strftime( "%Y-%m-%d %H.%M.%S", time.localtime(os.path.getmtime(old_file_path)), ) ) else: # Video # Reformat the date taken to "YYYY-MM-DD HH-mm-ss" print("______________________________________") new_file_name = time.strftime( "%Y-%m-%d %H.%M.%S", time.localtime(os.path.getmtime(old_file_path)) ) print( "Open video :", time.strftime( "%Y-%m-%d %H.%M.%S", time.localtime(os.path.getmtime(old_file_path)) ), ) # Combine the new file name and file extension new_file_name_ext = new_file_name + file_ext.lower() if file_name == new_file_name_ext: print("Already OK :", new_file_name_ext) continue # Check if image with same name not present i = 1 end = True while end: if new_file_name_ext in os.listdir(folder_path): new_file_name_ext = new_file_name + "-" + str(i) + file_ext.lower() if file_name == new_file_name_ext: print("Already OK :", new_file_name_ext) break i += 1 else: end = False print("New name :", new_file_name_ext) # Create the new folder path new_file_path = os.path.join(folder_path, new_file_name_ext) # Rename the file os.rename(old_file_path, new_file_path) rename_number += 1 except Exception as err: print("Error while processing : ", err) print("______________________________________") print("Stop : %s files rename for %s files " % (rename_number, len(file_names)))
"""Function to run if the user wants to send a thank you note.""" import os import sys def clear_screen(): """Taken from the Treehouse shopping_list exercise.""" os.system("cls" if os.name == "nt" else "clear") donors_info = { 'Sam Wippy': [100000], 'Willy Wonka': [12, 13, 14], 'Garth Brooks': [1] } def send_thank_you(): """Give user choices to send a thank you note to a donor.""" clear_screen() while True: full_name = input(""" Enter the full name of the person you'd like to send a thank you to. Or: [L] to see a list of previous donors. [B] to return to the main menu. [Q] to quit the program. > """).lower() if full_name == 'q': sys.exit() elif full_name == 'b': break elif full_name == 'l': for key in sorted(donors_info.keys()): print(key) else: add_new_or_update_donor_info(full_name) def add_new_or_update_donor_info(full_name): """Take care of managing user input into our data table.""" clear_screen() while True: donation_amount = input("Enter donation amount or [B] to go back: ") if donation_amount == 'b': return try: donation_amount = float(donation_amount) if donation_amount < 0: clear_screen() print("Please enter a positive donation amount.") continue if full_name not in [key.lower() for key in donors_info.keys()]: donors_info[full_name.title()] = [] donors_info[full_name.title()].append( donation_amount) print('Added ${1} to {0}\'s donation history.'.format( full_name.title(), donation_amount)) break except ValueError: clear_screen() print("Please enter a positive, numerical donation amount.") continue print(""" ================================== Dear {name}, Thank you for your generous donation of ${amount}. We have so many things that we have to do better... and certainly ipsum is one of them. Lorem Ispum is a choke artist. It chokes! I think my strongest asset maybe by far is my temperament. I have a placeholding temperament. Your donation of ${amount} goes toward accomplishing really cool shit at this place. Lorem Ipsum is the single greatest threat. We are not - we are not keeping up with other websites. When other websites give you text, they’re not sending the best. They’re not sending you, they’re sending words that have lots of problems and they’re bringing those problems with us. They’re bringing mistakes. They’re bringing misspellings. {name}, they’re typists… And some, I assume, are good words. An ‘extremely credible source’ has called my office and told me that Barack Obama’s placeholder text is a fraud. I think the only difference between me and the other placeholder text is that I’m more honest and my words are more beautiful. If Trump Ipsum weren’t my own words, perhaps I’d be dating it. Sincerely, The Pants Foundation ==================================""".format(name=full_name.title(), amount=donors_info[full_name .title()][-1])) def create_report(donors_info): """Make a list for each column from dict data then populate row data into a table. """ donor_name = list(donors_info.keys()) donation = donors_info.values() num_of_donation = [len(a) for a in donation] total_donation = [sum(a) for a in donation] average_donation = [int(sum(a) / len(a)) for a in donation] sorted_donations = sorted(list(zip( donor_name, total_donation, num_of_donation, average_donation)), key=lambda tup: tup[1], reverse=True) clear_screen() print( "\nDonor Name{}" "Total Amount{}" "Number of Donations{}" "Average Donation Amount{}" .format( ' ' * 20, ' ' * 18, ' ' * 11, ' ' * 8 )) for row in sorted_donations: print('{}{}{}{}{}{}{}{}'.format( row[0], ' ' * (30 - len(str(row[0]))), row[1], ' ' * (30 - len(str(row[1]))), row[2], ' ' * (30 - len(str(row[2]))), row[3], ' ' * (30 - len(str(row[3]))))) print('\n') def main(): """The main function.""" while True: user_menu = input( """Welcome to the Mailroom-Tron 3000 v1.5. Type your user selection:\n [E] to EMAIL an existing donor or new donor. [R] for REPORT of donors and their donations. [Q] to quit the program. > """) if user_menu.lower() == 'q': break elif user_menu.lower() == 'e': send_thank_you() continue elif user_menu.lower() == 'r': create_report(donors_info) continue if __name__ == '__main__': main()
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # 总资产 asset_all = 0 li = input("请输入总资产:") asset_all = int(li) goods = [ {"name":"电脑","price":1999}, {"name":"鼠标","price":10}, {"name":"游艇","price":20}, {"name":"美女","price":998}, ] for i in goods: # {"name":"电脑","price":1998} print(i["name"],i["price"]) car_dict = {} # car_dict = { # "电脑":{"price":单价,num:123} # } while True: i2 = input("请选择商品(Y/y结算):") # 电脑 if i2.lower() == "y": break # 循环所有的商品,查找需要的商品 for item in goods: if item["name"] == i2: # item = {"name":"电脑","prite":1999} name = item["name"] # 判断购物车是否已经有该商品,有,num+1 if name in car_dict.keys(): # pass car_dict[name]["num"] = car_dict[name]["num"] + 1 else: car_dict[name] = {"num":1,"single_price":item["price"]} print(car_dict) # { # "鼠标": {"single_price":10,"num":1}, 1*10 # "电脑": {"single_price":1999,"num":9} 9*1999 # } all_price = 0 for k,v in car_dict.items(): n = v["single_price"] m = v["num"] all_sum = m * n all_price = all_price + all_sum if all_price > asset_all: print("穷逼") else: print("我跟你回家吧")
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # li = ["alex","eric"] # 列表 # li = ("alex","eric") # 元祖 # s = "_".join(li) # .join 把字符串链接起来 # print(s) # s = "alex" # # news = s.lstrip() # 移除左边空白‘ # news = s.rstrip() # 移除右边空白 # news = s.strip() # 移除两边空白 # print(news) # s = "alex SB alex" # ret = s.partition("SB") # 其他先不知道 搞成元祖类型了 # print(ret) # s = "alex SB alex" # ret = s.replace("al","BB",1) # 你想把谁替换成谁 加后面参数从左往右找几个 # print(ret) # s = "alexalex" # ret = s.split("e",1) # 分割 # print(ret) # # s = "aLeX" # print(s.swapcase()) # 大写遍小写 小写变大写 # # s = "the school" # ret = s.title() # 变标题 # print(ret) # # # # 字符串索引 # s = "alex" # print(s[0]) # print(s[1]) # print(s[2]) # print(s[3]) # ret = len(s) # print(ret) # 知道这个字符串有多长 # 切片 s = "alex" # 0<= <2 # print(s[0:2]) # 循环 # start = 0 # while start < len(s): # temp = s[start] # print(temp) # start += 1 # for 循环 for item in s: # item 随便定义的 if item == "L": break print(item)
# -*- coding:utf-8 -*- print('hello,python') print('hello,'+'python') temp = '你是我的小苹果' temp_unicode = temp.decode('utf-8') temp_gbk = temp_unicode.encode("gbk") print(temp_gbk)
# %% [markdown] # **コンプリヘンション(comprehension)**<br> # **リスト内包表記**<br> # **[式 for 変数 in リスト if 条件]**<br> # In[]: sample_list1 = ['a', 'b', 'c', 'd', 'e'] print(sample_list1) sample_list2 = [i*3 for i in sample_list1 if i >= 'c'] print(sample_list2) # %% [markdown] # **ディクショナリ内包表記**<br> # **{式 : 式 for 変数 in リスト if 条件}**<br> # In[]: sample_dict1 = {'a': 100, 'b': 120, 'c': 200, 'd': 300, 'e': 400} print(sample_dict1) sample_dict2 = {i*3 for i in sample_dict1 if i >= 'c'} print(sample_dict2) # %% [markdown] # **セット内包表記**<br> # **{式 for 変数 in リスト if 条件}**<br> # In[]: sample_set1 = {'a', 'b', 'c', 'd', 'e'} print(sample_set1) sample_set2 = {i*3 for i in sample_set1 if i >= 'c'} print(sample_set2) # %% [markdown] # **タプル**<br> # In[]: sample = ('a', 'b', 'c', 'd', 'e') print("sample:", sample) print("type:", type(sample)) # In[]: sample = () # 中身が空 print("sample:", sample) print("type:", type(sample)) # In[]: sample = ('a') # 要素が1つだけの場合は後ろに','をつけないとタプルにならない print("sample:", sample) print("type:", type(sample)) # In[]: sample = ('a',) # 要素が1つだけの場合は後ろに','をつける print("sample:", sample) print("type:", type(sample)) # In[]: sample = 'a', # ()を省略 print("sample:", sample) print("type:", type(sample)) # In[]: sample = list(['a', 'b', 'c']) # タプル⇒リスト print("sample:", sample) print("type:", type(sample)) # In[]: sample = tuple(['a', 'b', 'c']) # リスト⇒タプル print("sample:", sample) print("type:", type(sample)) # In[]: sample = ('a', 'b', 'c', 'd', 'e') print("sample:", sample) print("type:", type(sample)) print("sample[0]:", sample[0]) # インデックスを指定して要素を取り出す print("type:", type(sample[0])) # In[]: sample = 'a', 'b', 'c' print(type(sample)) for a in enumerate(sample): print("a:", a) # In[]: sample = ('a', 'b', 'c', 'd', 'e') print(sample) print(sample[2:5:2]) # タプル名[開始:終了:ステップ(間隔)] # In[]: # In[]: # In[]: # In[]: # In[]: # In[]: # In[]: # In[]: # In[]:
# import libraries import sys import pandas as pd import numpy as np from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): """ Load the files, read the messages and categories files and merge both dataframe . Return the dataframe with messages and the categories of each message. Arguments: ---- messages_filepath: path to read “disaster_messages.csv” file categories_filepath: path to read “disaster_categories.csv” file Output: ---- Merge dataframe of both files """ # load message datasets messages = pd.read_csv(messages_filepath) # load categories dataset categories = pd.read_csv(categories_filepath) # merge datasets df = pd.merge(messages, categories, on='id') return df def clean_data(df): """ Process a Datatase of messages and categories: after clean and drop duplicates The messages are classified in categories in numerical format Arguments: ---- Dataframe from after execute load data Output: ---- Dataframe of messages and categories clean """ # create a dataframe of the 36 individual category columns categories = df.categories.str.split(pat = ';', expand = True) # select the first row of the categories dataframe row = categories.iloc[0,:] # use this row to extract a list of new column names for categories. # one way is to apply a lambda function that takes everything # up to the second to last character of each string with slicing category_colnames =[] for r in row: category_colnames.append(r[:-2]) categories.columns = category_colnames #convert to dummies for column in categories: # set each value to be the last character of the string categories[column] = categories[column].astype(str).str[-1] # convert column from string to numeric categories[column] = pd.to_numeric(categories[column]) #categories[column] = categories[column].astype(int) # drop the original categories column from `df` df = df.drop(['categories'], axis=1) # concatenate the original dataframe with the new `categories` dataframe df = pd.concat([df, categories], axis=1) # drop duplicates df.drop_duplicates(inplace=True) return df def save_data(df, database_filename): """ Save the clean dataframe into a sqlite database Arguments: ---- Dataframe from after clean Output: ---- You can access to a database with a Database_filename """ engine = create_engine('sqlite:///'+database_filename) df.to_sql('df', engine, index=False) pass def main(): """ Runs load_data, clean_data and save_data and the result is a database of messages and categories data """ if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning data...') df = clean_data(df) print('Saving data...\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved to database!') else: print('Please provide the filepaths of the messages and categories '\ 'datasets as the first and second argument respectively, as '\ 'well as the filepath of the database to save the cleaned data '\ 'to as the third argument. \n\nExample: python process_data.py '\ 'disaster_messages.csv disaster_categories.csv '\ 'DisasterResponse.db') if __name__ == '__main__': main()
#Entrada de Dados: #Digite a primeira nota: 4 #Digite a segunda nota: 5 #Digite a terceira nota: 6 #Digite a quarta nota: 7 #Saída de Dados: #A média aritmética é 5.5 nota1 = input("Digite a primeira nota") nota2 = input("Digite a segunda nota") nota3 = input("Digite a terceira nota") nota4 = input("Digite a quarta nota") total = float(nota1) + float(nota2) + float(nota3) + float(nota4) media = total/4 print ("A média aritmética é", media)
#Receba um número inteiro na entrada e imprima #par #quando o número for par ou #ímpar #quando o número for ímpar. numero = int(input("Digite seu número: ")) numero = numero%2 if (numero == 0): print('Par') else: print('Ímpar')
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np df = pd.read_csv('train.csv') """ from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(df,df['SalePrice'],test_size=0.1,random_state=0) """ #Since we have a separate test data we dont need the above train_test_split() # Dealing with MISSING VALUES (NaN) # # Let's handle categorical variables first features_nan = [feature for feature in df.columns if df[feature].isnull().sum()>1 and df[feature].dtypes == 'O'] # We replace NaN categories with a common label called 'Missing' def replace_cat_features(dataset, features_nan): data = dataset.copy() data[features_nan]=data[features_nan].fillna('Missing') return data df = replace_cat_features(df, features_nan) numerical_with_nan = [feature for feature in df.columns if df[feature].isnull().sum()>1 and df[feature].dtypes != 'O'] for feature in numerical_with_nan: median = df[feature].median() # Always create a new feature to identify what values were Nan # So tmrw if they ask why is there a unknown value, # by checking this feature we know it was missing hence replaced for analysis purpose df[feature+'nan'] = np.where(df[feature].isnull(),1,0) df[feature].fillna(median, inplace=True) #print(df[numerical_with_nan].isnull().sum()) # We have succesfully engineered categorical and numerical variables now # Dealing with TEMPORAL VARIABLES # We analysed that older the house, lower the price # Thus replace these year features with one feature for feature in ['YearBuilt','YearRemodAdd','GarageYrBlt']: df[feature]=df['YrSold']-df[feature] num_features = ['LotArea','LotFrontage','SalePrice','1stFlrSF','GrLivArea'] for feature in num_features: df[feature] = np.log(df[feature]) # Handling rare categorical feature # Replace all categories which occur less than 1% times in the whole dataset # SO that such categories are grouped as one categorical_features = [feature for feature in df.columns if df[feature].dtypes == 'O'] for feature in categorical_features: temp = df.groupby(feature)['SalePrice'].count()/len(df) temp_df = temp[temp>0.01].index df[feature] = np.where(df[feature].isin(temp_df), df[feature],'Rare_Var') """ Now we aim to map all categorical values in some order which we select to be the mean of the output and sort it accoridngly assuming that is hte priority """ for feature in categorical_features: labels_ordered = df.groupby([feature])['SalePrice'].mean().sort_values().index labels_ordered = {k:i for i,k in enumerate(labels_ordered,0)} df[feature] = df[feature].map(labels_ordered) ## Feature Scaling feature_scale = [feature for feature in df.columns if feature not in ['Id','SalePrice']] from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() df[feature_scale] = scaler.fit_transform(df[feature_scale]) """ Now our input data is cooked and can be fed as the training data We will repeat the same for test_data And save both as csv files """ df.to_csv('engg_X_train.csv', index=False)
# Mario Fernández # Exercise 1 # Si se quieren modificar los valores, más abajo en el main se pueden cambiar def RGB_TO_YUV(R, G, B): # Implementar las líneas que están presentes en la teoría (diapo 46) Y = 0.257 * R + 0.504 * G + 0.098 * B + 16 U = -0.148 * R - 0.291 * G + 0.439 * B + 128 V = 0.439 * R - 0.368 * G - 0.071 * B + 128 print("THE RGB VALUES", R, ",", G, "AND", B, "IN YUV ARE:", Y, ",", U, "AND", V) def YUV_TO_RGB(Y, U, V): # Implementar las líneas que están presentes en la teoría (diapo 46) R = 1.164 * (Y - 16) + 1.596 * (V - 128) G = 1.164 * (Y - 16) - 0.813 * (V - 128) - 0.391 * (U - 128) B = 1.164 * (Y - 16) + 2.018 * (U - 128) print("THE YUV VALUES", Y, ",", U, "AND", V, "IN RGB ARE:", R, ",", G, "AND", B) if __name__ == '__main__': RGB_TO_YUV(10, 10, 10) # aquí se pueden modificar los valores YUV_TO_RGB(100, 100, 100) # aquí se pueden modificar los valores
# Heap Practice Module # Dec 15 2020 # 11 Jan 2021 # TODO def array_to_heap(arr): ''' returns a heap data structure ''' pass # MIN HEAP # COMPLETE binary tree where each node is SMALLER than its children # root is minimum element in tree # Key Operations: # insert O(logn) # start by inserting at bottom left to right in order to maintain complete property # now we fix min heap tree by swapping the new element with its parent until we find appropriate spot # extract_min O(1) (fixing is O(logn)) # remove min element (root) and replace it with last element in tree (bottommost rightmost) # now, bubble down this element (swapping with its children) until min heap prop is restored if __name__ == "__main__": h = [9,5,2,1,4,3,7,8,6]
indices = dict() def preorder(inorder:list, postorder:list, shift=0) -> list: if inorder == [] or postorder == []: return [] # get last element (our root) from postorder root = postorder.pop() # find its index in inorder idx = indices[root] - shift # elements before and after before_root = inorder[:idx] after_root = inorder[idx+1:] # print(before_root, after_root, idx) # add root to our result, then the left subtree result, then right result = [root] result += get_preorder(before_root, postorder[:idx], shift) result += get_preorder(after_root, postorder[idx:], shift+idx+1) return result def get_preorder(inorder:list, postorder:list, start:int, end:int) -> list: if start > end: return [] # get last element (our root) from postorder root = postorder[end] # find its index in inorder idx = indices[root] result = [root] result += get_preorder(inorder, postorder, start, idx - 1) result += get_preorder(inorder, postorder, idx + 1, end) return result
# # ##################### # # ps1a # # PSET 1A # # ##################### #inputs annual_salary = float(input("Annual salary: ")) portion_saved = float(input("Monthly portion saved: ")) total_cost = float(input("Cost of your dream home: ")) #knowns portion_down_payment = 0.25 current_savings = 0 monthly_salary = annual_salary/12 r = 0.04 #calculates months months = 0 while current_savings <= portion_down_payment*total_cost: months+=1 current_savings+=(current_savings*r/12) current_savings+=portion_saved*monthly_salary print("Number of months:",months)
# HAAR CASCASE METHOD: # feature based machine learning # uses pretrained images of labeled poitives and negatives # runs through thousands of classifiers in a cascaded manner # Use cases: detecting faces import numpy as np import cv2 img = cv2.imread("Detection/assets/faces.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) path = 'Detection/haarcascade_frontalface_default.xml' path = 'Detection/haarcascade_eye.xml' face_cascade = cv2.CascadeClassifier(path) faces= face_cascade.detectMultiScale( gray, scaleFactor=1.02, minNeighbors=20, minSize=(10,10)) print(f'Num of faces: {len(faces)}') for (x,y,w,h) in faces: cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2) cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
def keyword_generate(inputt): string = str(inputt) res = '' for char in string: res += chr(int(char)) return res def dhke1(t,p,m,a,message_in, encrypt): if encrypt: # generate the key with your a: num_key = int(pow(m,a,p)) # get the keyword keyword = keyword_generate(num_key) return vigenere_cipher(message_in, keyword, encrypt=encrypt) # else decrypt else: # generate key from their t: num_key = int(pow(t, a, p)) # get keyword keyword = keyword_generate(num_key) return vigenere_cipher(message_in, keyword, encrypt) def dhke(t,p,m,a,message_in, encrypt): num_key = pow(t, a, p) # get the keyword keyword = keyword_generate(num_key) return vigenere_cipher(message_in, keyword=keyword, encrypt=encrypt) def vigenere_cipher(message,keyword,encrypt): return 'hey' # res = "" # keyword_idx = 0 # for char in message: # shift_char = keyword[keyword_idx] # shift = ord(shift_char) - 32 # keyword_idx = (keyword_idx+1)%len(keyword) # res += caesar_cipher(char, shift=shift, encrypt=encrypt) # return res if __name__ == "__main__": print(keyword_generate(1342))
''' Tutorial 2: Image Fundamentals and Manipulation Piero Orderique 15 Feb 2021 ''' import cv2 from random import randint #* openCV loads in image as numpy array! img = cv2.imread('Detection/assets/MIT_Dome.jpg', -1) #* h, w, channels --- pic is actually rep by 3D array in BGR (NOT RGB) print(img.shape) ''' [ row0: [[b00, g00, r00], [b01, g01, r01], ... ], row1: [[b10, g10, r10], [b11, g11, r11], ... ], ... ] ''' #* Changing pixels to random # for i in range(300): # for j in range(img.shape[1]): # img[i][j] = [randint(0, 255), randint(0, 255), randint(0, 255)] #* lets copy part of the image and paste it somewhere else in the image #? tag is copying the pixels in rows 300-699, cols 400-1199 tag = img[300:700, 400:1200] #? now paste somewhere in the image (must be same shape) (lets just move it up) img[0:400, 400:1200] = tag cv2.imshow('Image', img) cv2.waitKey(0) cv2.destroyAllWindows()
# Graph Searching Algorithms # Piero Orderique # 11 Jan 2021 # SIDE_NOTE: # fixed login authentication error with git by running: git config --global credential.helper winstore # from https://stackoverflow.com/questions/11693074/git-credential-cache-is-not-a-git-command # Structures - adjacency list implementation class Graph: def __init__(self, nodes=[]) -> None: self.nodes = nodes class Node: def __init__(self, data, adjacent=[]) -> None: self.data = data self.adjacent = adjacent self.visited = False # used for searching! def __str__(self) -> str: rep = 'Data: ' + str(self.data) return rep class Queue: class QueueNode: def __init__(self, data=None) -> None: self.data = data self.next = None class NoSuchElementException(Exception): pass def __init__(self) -> None: self.first = None self.last = None def add(self, item): t = self.QueueNode(item) if self.last != None: self.last.next = t self.last = t if self.first == None: self.first = self.last def remove(self): if self.first == None: raise self.NoSuchElementException data = self.first.data self.first = self.first.next if self.first == None: self.last = None return data def peek(self): if self.first == None: raise self.NoSuchElementException return self.first.data def isEmpty(self): return self.first == None def __str__(self) -> str: # rep = 'first in queue: {}\nlast in queue: {}'.format(self.first.data, self.last.data) # return rep rep = '' n = self.first while n: rep += str(n.data) +' -> ' n = n.next rep += 'None' return rep def visit(node:Node): print(node) # DFS - like pre order traversal! Root -> left -> right def DFS(root:Node): if root == None: return visit(root) root.visited = True for node in root.adjacent: if node.visited == False: DFS(node) # BFS - NOT RECURSIVE! Use a QUEUE!!! (iterative solution = best solution) def BFS(root:Node): queue = Queue() root.visited = True queue.add(root) # add to the end of queue while not queue.isEmpty(): r = queue.remove() # remove tree node from front of queue visit(r) for node in r.adjacent: if node.visited == False: node.visited = True queue.add(node) # Driver Code: # -------------------------------------------- # root node picture: # 1 # / | \ # 2 0 3 # / \ / \ # 4 5 6 7 root = Node(1, [ Node(2, [ Node(4), Node(5) ]), Node(0), Node(3, [ Node(6), Node(7) ]) ]) # graph wrapper class (only if it contains disconnected components) graph = Graph(nodes=[root]) if __name__ == "__main__": BFS(root)
########## un ordered collection of unique elements ########## ##### sets are mutable ##### set1 = {1, 2, 3 , 4 , 4 } print(set1) set1.add(5) print(set1) ###### union(), intersection(), difference(), symmetric difference() set2 = {2,5,3,5,3,1,7,8} print(set1.union(set2)) #all unique values from both sets print(set1.intersection(set2)) #common print(set1.difference(set2)) # different from set1 print(set1.symmetric_difference(set2)) # different from both sets
#pass variable to script from sys import argv script, filename = argv #call a function on txt to open (filename) txt = open(filename) print "Here's your file %r: " %filename #give command to file by using dot . print txt.read() #Hey txt, do your read command with no parameter! txt.close() file_again = raw_input ("Please type any filename") txt_again = open(file_again) print txt_again.read() txt_again.close()
#f(0) = 0 #f(1) = 1 #f(n) = f(n-1) + f(n-2) def f(n): sum = (n-1) + (n - 2) sentence = """ For F({}) = f({}-1)+ f({}-2) is {} """.format(n,n,n, sum) print sentence def main(): print """ f(0) = 0 f(1) = 1 f(n) = f(n-1) + f(n-2) Find f(n) """ a = int(raw_input("Enter an integer for 'n': ")) f(a) main()
""" Logic operations for combining objects that represent named statements, to improve readability. Named statements are represented as name/statement pairs in a dict. Because conjunction is more common, it is represented my merging dicts. Disjunction is represented by a list instead. E.x.: >>> a = Name(a, "A") {"A": a} >>> b = Name(b, "B") {"B": b} >>> And(a,b) {"A": a, "B": b} >>> Or(a,b) [{"A":a}, {"B":b}] """ import boolexpr as bx from boolexpr import * from itertools import combinations, permutations, chain def merge(*dicts): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dicts: result.update(dictionary) return result def Name(statement, name): return {name: statement} def And(*statements): o = {} for s in statements: o = merge(o, s) return o def Or(*statements): return statements def count(statements): if type(statements) is list or type(statements) is tuple: # disjunction return sum(count(s) for s in statements) elif type(statements) is dict: # conjunction return sum(count(s) for s in statements.values()) else: # atomic statement return 1 def compile(statements): if type(statements) is list or type(statements) is tuple: # disjunction return or_s(*[compile(s) for s in statements]) elif type(statements) is dict: # conjunction return and_s(*[compile(s) for s in statements.values()]) else: # atomic statement return statements def named(arg): def wrap(fn, name=arg): """Wrapper for functions that return logic statements, to track where they came from""" def wrapped(*args, **kwds): n = name or "-".join([a.name for a in args] + [fn.__name__]) return Name(fn(*args, **kwds), n) return wrapped if type(arg) is str: return wrap else: return wrap(arg, None)
#------------------------------------------------------------------------------- # Name: harmonograph # Purpose: # # Author: Adam & Matthew # # Created: 12/11/2016 # Copyright: (c) Adam & Matthew 2016 #------------------------------------------------------------------------------- import turtle as graph import math as m # pendulum formula: amplitude * # sin(time*frequency + phase_offset) * # e**(-time*damping_constant) def posn (time,amplitude,frequency,phase,decay): return amplitude* \ m.sin(time*frequency+phase)* \ m.e**(-decay*time) ## turtle basics ## ## make turtle go fast by turning off tracing ##graph.tracer(0,0) ## ##for x in range(500): ## t.forward (x) ## t.right (170) ## ## only needed if turtle.tracer(0,0) used earlier ##t.update() ###period and frequency ## ### g is acceleration due to gravity = 9.8m/s^2 ##g = 9.8 ## ##for i in range(1,10): ## length = i/10 ## # compute period ## p = 2 * m.pi * m.sqrt(length/g) ## # computer frequency ## f = 1/p ## print (length,p,f) ### sin function ### ##steps = 1000 ##dx = .1 ##x=0 ##amplitude = 100 ##for i in range (0,steps): ## x = x + dx ## y = amplitude*m.sin(x) ## #print (x,y) ## graph.setpos (x*10,y) # harmonograph ### x pendulum ##a1=200 ###f1=3.12 ##p1=0 ##d1=.004 ## ### y pendulum ##a2=200 ###f2=3 ##p2=m.pi/2 ##d2=.004 ## ### gx - gimbal x ##a3=200 ###f3=3 ##p3=0 ##d3=.004 ## ### gy- gimbal y ##a4=200 ###f4=3.13 ##p4=3*m.pi/2 ##d4=.004 # x pendulum a1=200 f1=3.10 p1=0 d1=.04 # y pendulum a2=200 f2=3 p2=m.pi/3 d2=.04 # gx - gimbal x a3=0 f3=3.15 p3=0 d3=.004 # gy- gimbal y a4=0 f4=3.1 p4=3*m.pi/2 d4=.004 # time and delta dt=.01 t=0 steps=20000 graph.tracer(0,0) graph.penup() x0=posn(0,a1,f1,p1,d1)+posn(0,a3,f3,p3,d3) y0=posn(0,a2,f2,p2,d2)+posn(0,a4,f4,p4,d4) graph.setpos(x0,y0) graph.pendown() for i in range(1,steps): t=t+dt x=posn(t,a1,f1,p1,d1)+posn(t,a3,f3,p3,d3) y=posn(t,a2,f2,p2,d2)+posn(t,a4,f4,p4,d4) graph.setpos(x,y) graph.update()
//sort()method -permanently letter=['b','a','d','e','g','f'] print(letter) ['b','a','d','e','g','f'] letter.sort () print(letter) ['a','b','d','e','f','g'] letter.sort(reverse=true) print(letter) ['g','f','e','d','b','a'] print(letter) ['g','f','e','d','b','a'] //sorted()Function-temporary letter=['b','a',''d','e','g','f'] print(letter) ['b','a','d','e','g','f'] sorted(letter) ['a','b','d','e','f','g'] print(letter) ['b','a','d','e','g','f'] sorted(letter,reverse=true) ['g','f','e','d','b','a'] letter=['b,'A','d','E','g','f','c'] print(letter) ['b,'A','d','E','g','f','c'] sorted(letter) ['A','E','b','c','d','f','g']
#-----------------------------------------------------------------------------# # Title: CDInventory.py # Desc: Script for Assignment 05, managing a CD inventory. # Change Log: (Who, When, What) # Jurg Huerlimann 2020-Aug-07, Created File from CDInventory_Starter.py script. # Jurg Huerlimann 2020-Aug-08 Changed functionality to use dictonary # Jurg Huerlimann 2020-Aug-09 Added functionality to load existing data from file # Jurg Huerlimann 2020-Aug-10 Added functionality to delete info from inventory # Jurg Huerlimann 2020-Aug-11 Added functionality to save inventory to file #-----------------------------------------------------------------------------# # Declared variables strChoice = '' # User input lstTbl = [] # list of lists to hold data dicRow = {} #list of data row strFileName = 'CDInventory.txt' # Name of data file objFile = None # file object # Get user Input, display menu options print('The Magic CD Inventory\n') while True: # 1. Display menu allowing the user to choose: print('[l] Load Inventory from file\n[a] Add CD\n[i] Display Current Inventory') print('[d] Delete CD from Inventory\n[s] Save Inventory to file\n[x] Exit') strChoice = input('l, a, i, d, s or x: ').lower() # convert choice to lower case at time of input print() if strChoice == 'x': # Exit the program if the user chooses so break if strChoice == 'l': # load inventory from file lstTbl.clear() objFile = open(strFileName, 'r') # open CDInventory.txt file for row in objFile: # read row by row and add to dictionary lstRow = row.strip().split(',') dicRow = {'id': int(lstRow[0]), 'title': lstRow[1], 'artist': lstRow[2]} lstTbl.append(dicRow) objFile.close() print('The inventory has been loaded, please use [i] to display it .') print() # break elif strChoice == 'a': # add CD info through questions and add to dictionary strID = input('Enter an ID: ') strTitle = input('Enter the CD\'s Title: ') strArtist = input('Enter the Artist\'s Name: ') intID = int(strID) dicRow = {'id': intID, 'title': strTitle, 'artist': strArtist} lstTbl.append(dicRow) elif strChoice == 'i': # Display the current inventory from in-memory print('ID, CD Title, Artist') for row in lstTbl: print(*row.values(), sep = ', ') elif strChoice == 'd': # functionality of deleting an entry delEntry = int(input('What line would you like to delete? PLease enter the ID number: ')) for entry in range(len(lstTbl)): if lstTbl[entry]['id'] == delEntry: del lstTbl[entry] print('Your entry has been deleted from inventory.') print() break elif strChoice == 's': # Save the data to a text file CDInventory.txt objFile = open(strFileName, 'w') # using w rewrites the content of the file for row in lstTbl: strRow = '' for item in row.values(): strRow += str(item) + ',' strRow = strRow[:-1] + '\n' objFile.write(strRow) objFile.close() else: print('Please choose either l, a, i, d, s or x!')
# Choose your own adventure game - Individual Python Projects --- 19th Dec 2020 import random import time def displayIntro(): print('\nYour car broke down in your drive through the desert 2 days ago.') time.sleep(2) print('You have been walking across the sand dunes for what feels like forever with no roads or people in in sight.') time.sleep(2) print('\nYou close your eyes and pray to God that you will make it out of this situation alive.') time.sleep(2) print('You reopen your eyes and look to your feet.') time.sleep(1.5) print('\nYou find yourself now standing on a path branching in 2 different directions.') def choosePath(): path = "" while path != "1" and path != "2": # input validation path = input('\nWhich path will you take? 1 or 2?: ') return path def checkPath(chosenPath): print('You head down the path') time.sleep(1) print('The sun beams down harshly on your skin. You feel the dryness of your skin and your throat') time.sleep(1) print('Hours pass and you begin to doubt if you went down the correct path') correctPath = random.randint(1, 2) if chosenPath == str(correctPath): print('You notice what appears to be two figures in the distance') time.sleep(2) print('You break into the best jog you can manage in your exhausted, dehydrated state.') print('You see a man accompanied by a camel. You approach him and he offers you food and water.') time.sleep(1) print('You accept and ask him to help make your way back towards society') print('He walks you to a coles that was only 87 meters away.') else: print('You see what appears to be numberous sticks slowly circling you.') time.sleep(2) print('Those aren\'t sticks...') time.sleep(1.7) print('...') time.sleep(2) print('AHHHHHHH, THEY\'RE SNAKES!') time.sleep(1) print('You are attacked and killed by the snakes') playAgain = "yes" while playAgain == "yes" or playAgain == "y": displayIntro() choice = choosePath() checkPath(choice) # choice is equal to '1' or '2'. playAgain = input('Do you want to play again? (yes or y to continue: ')
# -*- coding: utf-8 -*- """ Created on Sat Mar 28 17:49:46 2020 @author: Zaki """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs #to create our dataset from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report #define learning rate and epochs learning_rate=0.001 #we should try first 0.1 then 0.01 , 0.001 .. no_of_epochs=100 batch_size=32 #1#generate a sample data set with 2 features columns and one class comuln #features with random numbers and class with either 0 or 1 #total number of samples will be 100 (X,y) = make_blobs(n_samples=100,n_features=2,centers=2,cluster_std=1.5,random_state=1) #cluster_std is how much varitation each data should have #convert y from(100,) to (100,1) y=y.reshape((y.shape[0],1)) #reshape X, add one column [1] due to the new W X= np.c_[X,np.ones((X.shape[0]))] #2#splitting the dataset (trainX,testX,trainY,testY)=train_test_split(X,y,test_size=0.5,random_state=50) #initialize a 3x1 weight matrix w= np.random.randn(X.shape[1],1) #initialize a list for storing loss values during epochs losses_value=[] #3#Evaluation #define sigmoid function def sigmoid_function(x): return 1.0/(1+np.exp(-x)) #define predict function#This is for evaluation not training def predict_function(X,W): prediction=sigmoid_function(X.dot(W)) #use step function to convert the prediction to class labels 1 or 0 prediction[prediction<=0.5]=0 prediction[prediction>0.5]=1 return prediction #define the method to split the training data into batches def get_batches(X,y,batch_size): #loop through the training data and yields the tuples whitch contain batches of data for i in np.arange(0,X.shape[0],batch_size): yield ((X[i:i+batch_size],y[i:i+batch_size])) #4#start training epochs#TO HAVE THE W* #looping the number of epochs for epoch in np.arange(0,no_of_epochs): #declare loss variable for every epoch loss_for_epoch = [] #loop for every batch of training data for (batchX,batchY) in get_batches(X,y,batch_size): prediction = sigmoid_function(batchX.dot(w)) #find error error=prediction-batchY #find the loss value and append it to the losses_value list loss_value=np.sum(error ** 2) loss_for_epoch.append(loss_value) #find the gradient , dot product of training input (transposed) and current error gradient= batchX.T.dot(error) #add to the existing value of weight W,the new variation #using the negative gradient (the descending gradient) w=w - (learning_rate) * gradient losss_value_average=np.average(loss_for_epoch) losses_value.append(losss_value_average) print("Epoch Number : {}, loss :{:.7f}".format(int(epoch),loss_value)) #test and evaluation of our model print("Starting evaluation") predictions = predict_function(testX,w) print(classification_report(testY,predictions)) #plotting the data set as scatter plot plt.style.use("ggplot") plt.figure() plt.title("Scatter plot of dataset") plt.scatter(testX[:,0],testX[:,1]) #plotting the error vs epochs graph plt.style.use("ggplot") plt.figure() plt.title("Loss vs Epochs") plt.xlabel("Epoch") plt.ylabel("Loss") plt.plot(np.arange(0,no_of_epochs),losses_value)
# Python to Json data = { 'name': 'Gopinath Jayakumar', 'Exp': '10+', 'value': None, 'is_nothing': True, 'hobbies': ('always sleeping....', 'always sleeping....') } import json # dumps: Convert python data to json print(type(data)) data = json.dumps(data, indent=4) print(data) # dump: write the json file with open('p_to_j.json', 'w') as file: json.dump(data, file, indent=4)
import os import csv from typing import Counter csvpath = os.path.join('Resources','election_data.csv') Votes = [] Candidates = [] percent_votes = [] total_votes = 0 with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_Header = next(csvfile) for row in csvreader: total_votes += 1 if row[2] not in Candidates: Candidates.append(row[2]) index = Candidates.index(row[2]) Votes.append(1) else: index = Candidates.index(row[2]) Votes[index] += 1 for num_votes in Votes: percentage = (num_votes/total_votes) *100 percentage = round(percentage) percentage = "%.3f" % percentage percent_votes.append(percentage) winner = max(Votes) index = Votes.index(winner) Winning_candidate = Candidates[index] print("Election Results") print("----------------------------------------------------") print(f"Total Votes: {total_votes}") print("----------------------------------------------------") for i in range(len(Candidates)): print(f"{Candidates[i]}: {str(percent_votes[i])}% {str(Votes[i])}") print("----------------------------------------------------") print(f"Winner: {Winning_candidate}") print("----------------------------------------------------") output_file = os.path.join('Analysis', 'analysis.txt') with open(output_file, "w") as txtfile: txtfile.write("Election Results" + "\n") txtfile.write("----------------------------------------------------" + "\n") txtfile.write(f"Total Votes: {total_votes}" + "\n") txtfile.write("----------------------------------------------------" + "\n") for i in range(len(Candidates)): txtfile.write(f"{Candidates[i]}: {str(percent_votes[i])}% {str(Votes[i])}" + "\n") txtfile.write("----------------------------------------------------" + "\n") txtfile.write(f"Winner: {Winning_candidate}" + "\n") txtfile.write("----------------------------------------------------" + "\n")
# get input with open('Day15/input.txt', 'r') as f: initNums = [int(x) for x in f.readline().split(',')] # return the number said on that turn def numberSaid(turnNum: int): # first n numbers said said = {k:v for v,k in enumerate(initNums, 1)} nextnum = 0 turn = len(initNums) + 1 # iterate until reach number of turns while turn != turnNum: # number was said before if nextnum in said: # get difference in turns diff = turn - said[nextnum] # mark down current turn said[nextnum] = turn # next number to be said is the difference between the turns nextnum = diff # number was not said before else: # mark down current turn said[nextnum] = turn # next number to be said is 0 nextnum = 0 # next turn turn += 1 # reached select turn return(nextnum) print(f'The 2020th number is {numberSaid(2020)}') print(f'The 30000000th number is {numberSaid(30000000)}')
# required fields fields = [ 'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid' # 'cid' ] # passport extends dictionary with a custom isValid function class Passport(dict): def isValid(self): # check if all fields exist for field in fields: if field not in self: return False return True # get input with open('Day04/input.txt', 'r') as f: inp = f.read() # split by two newline characters items = [x.split() for x in inp.split('\n\n')] # create passport dictionaries passports = [] for item in items: passport = Passport() passports.append(passport) # split key:value pairs with colon for field in item: key, value = field.split(':') passport[key] = value # count valid passports numValidPassports = sum(passport.isValid() for passport in passports) print(f'The number of valid passports is {numValidPassports}')
user1_name = input('User1, what is your name?') print('') print('Welcome {}'.format(user1_name)) print('') user2_name = input('User2, what is your name?') print('Welcome {}'.format(user2_name)) print('') # Доска board = [ [1,2,3], [4,5,6], [7,8,9] ] board_image = [ ['1','2','3'], ['4','5','6'], ['7','8','9'] ] print('') print(board_image[0]) print(board_image[1]) print(board_image[2]) print('') # победные ходы winning_moves=[ [1,4,7], [1,2,3], [7,8,9], [3,6,9], [3,5,7], [1,5,9] ] user1_moves=[] user2_moves=[] def smbd_won(hodi): for i in winning_moves: # print(i) if (i[0] in hodi) and (i[1] in hodi) and (i[2] in hodi): return True def board_show(): for i in user1_moves: if i == 1: board_image[0][0] = 'x' elif i == 2: board_image[0][1] = 'x' elif i == 3: board_image[0][2] = 'x' elif i == 4: board_image[1][0] = 'x' elif i == 5: board_image[1][1] = 'x' elif i == 6: board_image[1][2] = 'x' elif i == 7: board_image[2][0] = 'x' elif i == 8: board_image[2][1] = 'x' elif i == 9: board_image[2][2] = 'x' for i in user2_moves: if i == 1: board_image[0][0] = 'o' elif i == 2: board_image[0][1] = 'o' elif i == 3: board_image[0][2] = 'o' elif i == 4: board_image[1][0] = 'o' elif i == 5: board_image[1][1] = 'o' elif i == 6: board_image[1][2] = 'o' elif i == 7: board_image[2][0] = 'o' elif i == 8: board_image[2][1] = 'o' elif i == 9: board_image[2][2] = 'o' print(board_image[0]) print(board_image[1]) print(board_image[2]) def check_move(move): if move in list(set(user1_moves+user2_moves)): print('this move is already done. chose another') return False else: print('move is: {}'.format(move)) return True user_input = False while (len(user1_moves) + len(user2_moves)) <= 8: while user_input == False: u1 = input('{}, your next move ?'.format(user1_name)) u1=int(u1) # print('u1 = ', u1, 'type ', type(u1)) user_input = check_move(u1) user1_moves.append(u1) # print('user1_moves', user1_moves) board_show() if smbd_won(user1_moves): print('{} is the winner! Congrats!'.format(user1_name)) break # print('len user1_moves = {}'.format(len(user1_moves))) user_input = False if (len(user1_moves) + len(user2_moves)) >= 9: print('it looks like a draw') print('Game over') break while user_input == False: u2 = input('{}, your next move ?'.format(user2_name)) u2=int(u2) # print('u2 = ',u2,'type ', type(u2)) user_input = check_move(u2) user2_moves.append(u2) board_show() if smbd_won(user2_moves): print('{} is the winner! Congrats!'.format(user2_name)) break # print('len user2_moves = {}'.format(len(user2_moves))) user_input = False # print('len total = ', len(user1_moves)+len(user2_moves)) if (smbd_won(user1_moves) == False) and (smbd_won(user2_moves) == False): print('it looks like draw')
def max(i_list: list) -> int: """ Compute the max of a list :param i_list: The source list :return: The maximum of the list """ max = i_list[0] for element in i_list[1:]: if element>max: max=element return max if __name__ == "__main__": print(max([4,5,6,3,4,9,10,1,3,9]))
def palindrome(word: str) -> bool: """ Check if a string is palindrome :param word: the word to analyze :return: True if the statement is verified, False otherwise """ i=0 while i < int((len(word)+1)/2): if word[i] != word[-(i+1)]: return False i+=1 return True if __name__ == "__main__": print(palindrome("ottootto"))
# define a function which given a binary search tree # T of integers and a rectangular matrix M # of integers verify if there exists an ordered row of # M (e.g. values in ascending order) whose # values are in T. class Node: def __init__(self, value, left=None, right=None): self.left = left self.right = right self.value = value def find_element_bst(tree: Node, element: int) -> bool: """ Return if an element is present into a bst :rtype: bool :param tree: a tree to be analyzed :param element: the element to find :return: The statement if the element is present or not """ if tree is None: return False if tree.value == element: return True if element > tree.value: return find_element_bst(tree.right, element) else: return find_element_bst(tree.left, element) def ascending(list: list) -> bool: """ Check if a list is in ascending ordering :rtype: bool :param list: a non empty list to check :return: if the list is in ascending order """ for i in range(len(list) - 1): if list[i] < list[i + 1]: return True return False def check_fact(matrix, tree): _flag = [False for _ in range(len(matrix))] for (row,index) in zip(matrix,range(len(matrix))): if ascending(row): _flag[index] = True for element in row: if not find_element_bst(tree, element): _flag[index] = False break return True in _flag if __name__ == '__main__': matrix1 = [[1, 2, 3], [2,4,5,6,10],[1, 2, 3]] tree = Node(4, Node(2), Node(5, Node(4), Node(10, Node(6)))) print(check_fact(matrix1,tree))
def insert(value: int, in_list: list) -> list: """ Insert a value in an ordered list :param value: value to insert :param in_list: list where we add the value :return: the new list """ for idx in range(len(in_list)): if in_list[idx] >= value: return in_list[:idx] + [value] + in_list[idx:] return in_list + [value] def insertion_sort(in_list: list) -> list: """ Compute the insertion sort algorithm :param in_list: the list where we compute the algorithm :return: return an ordered list """ if len(in_list) == 0: return [] _hidden_list = in_list.copy() _hidden_list.pop(0) inducted_list = insertion_sort(_hidden_list) return insert(in_list[0],inducted_list) if __name__ == "__main__": print(insertion_sort([10,3,1,8,0,-1,100,140]))
def duplicate(i_list: list,n)-> list: """ Duplicate each element of the list :param i_list: The source list :param n: The number of repetitions for each element :return: The duplicated list """ _shallow_list = [] for element in i_list: i=0 while i<n: _shallow_list.append(element) i+=1 return _shallow_list if __name__ == "__main__": print(duplicate([1,2,3],7))
def belong(in_list1: list, in_list2: list) -> list: """ Check wheter or not all the element in list in_list1 belong into in_list2 :param in_list1: the source list :param in_list2: the target list where to find the element in in_list1 :return: return True if the statement is verified otherwise return False """ return all(element in in_list2 for element in in_list1) def no_repetition_no_permutation(i_list: list)-> bool: """ Given a list of list, check if some row is repeated or if they are permutation of other row :param i_list: The source matrix :return: Return True if there are no repeated or permutated row, False otherwise """ i = 0 while i < len(i_list): j=i+1 while j < len(i_list): if belong(i_list[i],i_list[j]): return False j += 1 i+=1 return True if __name__ == "__main__": print(no_repetition_no_permutation( [[1,2,3],[4,5,6,7],[4,7,6],[7,8,9]] ))
class Tree: """ Class which represent a tree as a node, it use more or less the same notation as we used in prolog, the only difference is that here we omit the nil value when there is an empty node. """ def __init__(self, elem, left=None, right=None): """ Constructor for a node, the sub-trees can be omitted if there is no value for these. :param value: The node payload. :param left: the left sub-tree (defined as another Node) :param right: the right sub-tree (defined as another Node) """ self.left = left self.right = right self.elem = elem def from_in_order_to_tree(list_tree_representation: list) -> Tree: """ Return a representation of the inorder tree as an instance of Node class :param list_tree_representation: the inorder list of element :return: a tree """ if not list_tree_representation: return None if len(list_tree_representation) == 1: return Tree(list_tree_representation[0]) return Tree( list_tree_representation [int((len(list_tree_representation)) / 2)], from_in_order_to_tree(list_tree_representation [:(int((len(list_tree_representation)) / 2))]), from_in_order_to_tree(list_tree_representation [(int((len(list_tree_representation)) / 2)) + 1:])) def print_in_order(tree: Tree) -> list: """ Perform the "in-order" traversal of a given tree :param tree: the tree to be evaluated :return: a list which contains all the nodes of the tree """ if tree is None: return [] left = print_in_order(tree.left) right = print_in_order(tree.right) return left + [tree.elem] + right def add_node_bst_2(tree: Tree, node: int) -> Tree: """ Add a node to bst in every position of the tree, not forced in a leaf Args: tree: Tree The source tree. node: The node that we want add. Returns: The new tree. """ _in_order_list = print_in_order(tree) i=0 while i < len(_in_order_list): if _in_order_list[i]>node: break i+=1 _in_order_list.insert(i,node) return from_in_order_to_tree(_in_order_list) if __name__ == "__main__": print(print_in_order(add_node_bst_2(Tree(3, Tree(1,None,Tree(2)), Tree(6, Tree(4), Tree(7,None,Tree(9)))),5)))
# -*- coding: utf-8 -*- """ Created on Mon Sep 10 08:36:12 2018 @author: Ashlee """ import numpy as np # computational assignment 2 python equivalent def system_of_ODEs(t=0, C=[6.25,0], k1=0.15, k2=0.6, k3=0.1, k4=0.2): ''' This function defines a system of ordinary differential equations $ \ frac{dC_A}{dt} &= -k_1 C_A-k_2 C_A$ and $ \ frac{dC_B}{dt} &= k_1 C_A-k_3-k_4 C_B$ that describe the mass concentration of species A and B subject to the following chemical reactions at constant total volume: A-->B A-->C B-->D B-->E Input: t time, h C mass concentration: row vector [C_A, C_B], mg/L k1 rate constant, 1/h k2 rate constant, 1/h k3 rate constant, mg/L/h k4 rate constant, 1/h Output: output time derivatives of mass concentrations, array [dC_A_dt, dCB_dt], mg/L/h Author: Professor Ashlee N. Ford Versypt, Ph.D. Oklahoma State University, School of Chemical Engineering [email protected] ''' assert t>=0, "time can only be positive" C_A = C[0] C_B = C[1] dC_A_dt = -k1*C_A-k2*C_A dC_B_dt = k1*C_A-k3-k4*C_B return [dC_A_dt,dC_B_dt]#could use numpy.array to make column vector output #C = np.array([6.25,0]) #z = system_of_ODEs(C) #print(z) print(system_of_ODEs()) print(system_of_ODEs(1,[1,1],k4=1,k3=1,k2=1,k1=1))
def add(x,y): """ Add two numbers together """ return x + y def subtract(x, y): """ returns x - y""" return x - y
#!/usr/bin/env python3 import csv import json import math import time API_KEY = "API KEY HERE" TIMEOUT = 600 RADIUS_OF_EARTH = 6371000 def haversine(lon1, lat1, lon2, lat2): """ Calculate the distance between two points on a sphere using the haversine forumula From: stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points Args: lon1, lat1: Floating point components of the first coordinate pair. lon2, lat2: Floating point components of the second coordinate pair. Returns: A floating point representing the distance between the two points, in meters. """ lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) m = RADIUS_OF_EARTH * c return m def inverse_haversine(lon, lat, radius, tolerance = 1e-6): """ Given an origin latitude and longitude, return the bounding box of extreme lats/longs and their corresponding longs/lats This is not a *true* implementation of an inverse haversine, as it only focuses on points with extreme longitudes or latitudes (theta = 0, pi/2, pi, and 3pi/2). The algorithm works by first doing a binary search for the point with max longitude and a search for the point with max latitude. The algorithm then calculates the difference in degree between these points and the origin point to find the point with min longitude and the point with max longitude - the max and min longitudes should be equally far apart from the origin, as should the max and min latitudes. Args: lat: The latitude of the origin point lon: The longitude of the origin point radius: The radius of the circle to calculate, in meters tolerance: The smallest number of the geospatial degree to which an error can be tolerated Returns: A dictionary containing the extreme longitudes and latitudes """ extremes = {} for component in ["max_longitude", "max_latitude"]: trial_coords = (lon, lat) increment = 1 direction = 0 previous_direction = 0 while True: current_radius = haversine(lon, lat, *trial_coords) current_precision = current_radius - radius # within tolerance if ( (abs(current_precision) < tolerance) and (previous_direction is not 0) ): if (component == "max_longitude"): extremes[component] = trial_coords[0] else: extremes[component] = trial_coords[1] break # oscillating behaviour: decrease the increment and change the # direction elif (current_radius > radius): if (previous_direction == 1): increment /= 2 direction = -1 else: if (previous_direction == -1): increment /= 2 direction = 1 previous_direction = direction # adjust the trial coordinates to be closer to the goal if (component == "max_longitude"): trial_coords = ( trial_coords[0] + (direction * increment), trial_coords[1] ) else: trial_coords = ( trial_coords[0], trial_coords[1] + (direction * increment) ) extremes["min_longitude"] = lon - (extremes["max_longitude"] - lon) extremes["min_latitude"] = lat - (extremes["max_latitude"] - lat) return extremes def split_bbox(bbox, splits, direction): """ Split a gmaps_scraper kwargs bbox kwargs into n parts in a single direction Args: bbox: A gmaps_scraper bbox kwargs dictionary splits: The number of splits to make direction: Either "vertical" or "horizontal" Returns: An array of smaller bbox kwargs dictionaries """ results = [] if (direction == "vertical"): lat_segment = ((bbox["max_latitude"] - bbox["min_latitude"]) / splits) for i in range(splits): results.append({ "min_longitude": bbox["min_longitude"], "min_latitude": bbox["min_latitude"] + (lat_segment * i), "max_longitude": bbox["max_longitude"], "max_latitude": bbox["min_latitude"] + (lat_segment * (i + 1)) }) elif (direction == "horizontal"): lon_segment = ((bbox["max_longitude"] - bbox["min_longitude"]) / splits) for i in range(splits): results.append({ "min_longitude": bbox["min_longitude"] + (lon_segment * i), "min_latitude": bbox["min_latitude"], "max_longitude": bbox["min_longitude"] + (lon_segment * (i + 1)), "max_latitude": bbox["max_latitude"] }) return results def bbox_to_geojson(bbox): """ Convert gmaps_scraper bbox kwargs into a GeoJSON string Args: bbox: A gmaps_scraper bbox kwargs dictionary Returns: A GeoJSON string """ return json.dumps({ "type": "Polygon", "coordinates": [[ [bbox["max_longitude"], bbox["max_latitude"]], [bbox["max_longitude"], bbox["min_latitude"]], [bbox["min_longitude"], bbox["min_latitude"]], [bbox["min_longitude"], bbox["max_latitude"]], ]] }) if (__name__ == "__main__"): # about 5 miles radius_meters = 8046.72 with open("top50cities.csv", "r") as f: for row in csv.DictReader(f): city = row.pop("city").lower().replace(" ", "_").replace("/", "_") for key in row: row[key] = float(row[key]) northeast = inverse_haversine( row["max_longitude"], row["max_latitude"], radius_meters ) southwest = inverse_haversine( row["min_longitude"], row["min_latitude"], radius_meters ) perimeter_bboxes = [ { # North "min_longitude": southwest["min_longitude"], "min_latitude": row["max_latitude"], "max_longitude": row["max_longitude"], "max_latitude": northeast["max_latitude"] }, { # East "min_longitude": row["max_longitude"], "min_latitude": row["min_latitude"], "max_longitude": northeast["max_longitude"], "max_latitude": northeast["max_latitude"] }, { # South "min_longitude": row["min_longitude"], "min_latitude": southwest["min_latitude"], "max_longitude": northeast["max_longitude"], "max_latitude": row["min_latitude"] }, { # West "min_longitude": southwest["min_longitude"], "min_latitude": southwest["min_latitude"], "max_longitude": row["min_longitude"], "max_latitude": row["max_latitude"] } ] # The perimeter bounding boxes are too elongated, so we need to # split them a little scraping_bboxes = [] scraping_bboxes += split_bbox(perimeter_bboxes[0], 3, "horizontal") scraping_bboxes += split_bbox(perimeter_bboxes[1], 3, "vertical") scraping_bboxes += split_bbox(perimeter_bboxes[2], 3, "horizontal") scraping_bboxes += split_bbox(perimeter_bboxes[3], 3, "vertical") """ for i in range(len(scraping_bboxes)): with open("temp%s%d" % (city, i), "w") as f: f.write(bbox_to_geojson(scraping_bboxes[i])) with open("temp%s%d" % (city, len(scraping_bboxes) + 1), "w") as f: f.write(bbox_to_geojson(row)) """ scrape_name = "%s_%s_perimeter_%dm" % ( datetime.datetime.now().strftime("%Y-%m-%d"), city, radius_meters ) scraper = gmaps_scraper.scrapers.PlacesNearbyScraper( gmaps = googlemaps.Client( API_KEY, timeout = TIMEOUT ), output_directory_name = scrape_name, writer = "mongo" ) for bbox in scraping_bboxes: scraper.scrape_subdivisions( grid_width = 3, query = "", **bbox )
import time import pandas as pd CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. 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('\033[1m' + 'Hello! Let\'s explore some US bikeshare data!' + '\033[0m') # get user input for city (chicago, new york city, washington). city = ['chicago', 'new york city', 'washington'] while True: city = input(str('\033[1m' + '\nWhich city would you like to see data on? Chicago, New York City, Washington?\n' + '\033[0m').lower()) if city in ('chicago', 'new york city', 'washington'): break else: print('Please ensure you wrote in lower case OR we do not have data on that city, please choose one of the three cities listed.') # get user input for month (all, january, february, ... , june) months = ['all', 'january', 'february', 'march', 'april', 'may', 'june'] while True: month = input(str('\033[1m' + 'Would you like to search by one of the following months? January, February, March, April, May, June, or all? ' + '\033[0m').lower()) if month in months: break else: print('We only have data for the first six months, please choose one of the listed months, or choose all.') days = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] # get user input for day of week (all, monday, tuesday, ... sunday) while True: day = input(str('\033[1m' + '\nWould you like to search by one of the following days?\nSunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or all of them?\n' + '\033[0m').lower()) if day in days: break else: print('Your answer does not match any of the above options, please try again!\n') 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 """ df = pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name if month != 'all': #use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month)+1 df = df[df['month'] == month] if day != 'all': df = df[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequest times of travel.""" print('\033[1m' + '\nCalculating the most frequent times of travel...\n' + '\033[0m') start_time = time.time() """ Based on the chosen city, month and day, find and prints the most popular month Arguments: DataFrame Returns: The most popular month """ df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] = df['Start Time'].dt.month popular_month = df['month'].mode()[0] print('\033[1m' + 'Most popular month:' + '\033[0m', popular_month) """ Based on the chosen city, month and day, find and prints the most popular day Arguments: DataFrame Returns: Most popular day """ df['Start Time'] = pd.to_datetime(df['Start Time']) df['day'] = df['Start Time'].dt.dayofweek popular_day = df['day'].mode()[0] print('\033[1m' + 'Most popular day:' + '\033[0m', popular_day) """ Based on the chosen city, month and day, find and prints the most popular hour of the day Arguments: DataFrame Returns: Most Popular hour """ df['Start Time'] = pd.to_datetime(df['Start Time']) df['hour'] = df['Start Time'].dt.hour popular_hour = df['hour'].mode()[0] print('\033[1m' + 'Most Popular Start Hour:' + '\033[0m', popular_hour) print("\nThis took %s seconds."%(time.time()-start_time)) print('-'*40) def station_stats(df): """ Calculating the most popular stations and trips Arguments: DataFrame Returns: Statistics on the most popular stations and trips. """ print('\033[1m' + 'Calculating the most popular stations and trip...\n' + '\033[0m') start_time = time.time() # display the most commonly used start station start_stn = df['Start Station'].mode()[0] print('Most popular start station is {}.'.format(start_stn)) # display the most commonly used end station end_stn = df['End Station'].mode()[0] print('Most popular end station is {}.'.format(end_stn)) # Display the most frequent combination of start and end stations df['Most_Common_Trip'] = df["Start Station"]+ " to " + df["End Station"] most_common = df['Most_Common_Trip'].mode()[0] print('The most common trip is {}.'.format(most_common)) print("\nThis took %s seconds."%(time.time()-start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip durations.""" print('\033[1m' + 'Calculating the statistics on the total and average trip durations...\n' + '\033[0m') start_time = time.time() # display the total travel time total_travel_time = df['Trip Duration'].sum() m, s = divmod(total_travel_time, 60) h, m = divmod(m, 60) print('The total travel time is {} hours, {} minutes and {} seconds.'.format(h, m, s)) # display mean travel time mean_travel_time = df['Trip Duration'].mean() m, s = divmod(mean_travel_time, 60) h, m = divmod(m, 60) print('The mean travel time is {} hours, {} minutes and {} seconds.'.format(h, m, s)) print("\nThis took %s seconds." %(time.time()-start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\033[1m' + 'Calculating User Stats...\n' + '\033[0m') start_time = time.time() # find the breakdown of user_types print('User types:\n') user_type = df['User Type'].value_counts() print(user_type) print("\nThis took %s seconds." %(time.time()-start_time)) print('-'*40) # find the breakdown of gender def gender_age(df, city): """Displays statistics on bikeshare users.""" #city = get_filters if city == 'chicago' or city == 'new york city': print('\033[1m' + 'Calculating Gender and Age stats...\n' + '\033[0m') start_time = time.time() print('\nGender:\n') gender = df['Gender'].value_counts() print(gender) # Display earliest, most recent, and most common year of birth print('\nInformation related to Birth Years:\n') oldest = int(df['Birth Year'].min()) youngest = int(df['Birth Year'].max()) most_common = int(df['Birth Year'].mode()) print('\nThe oldest users were born in {}.\nThe youngest users were born in {}.' '\nMost users were born in {}.'.format(oldest, youngest, most_common)) print("\nThis took %s seconds." %(time.time()-start_time)) print('-'*40) def display_data(df): '''Displays five lines of data if the user specifies that they would like to. After displaying five lines, ask the user if they would like to see five more. Continues asking until they say stop. Arguments: DataFrame Returns: If the user says yes then this function returns the next five lines of the dataframe and then asks the question again by calling this function again. If the user says no then this function returns, but without any value ''' first = 0 while True: ask_user = input('\033[1m' + '\nWould you like to view individual trip data? ' '\'yes\' or \'no\'.\n' + '\033[0m').lower() if ask_user == 'yes': print(df.iloc[first:first+5]) first = first + 5 else: break 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) gender_age(df, city) display_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
def number_sum_finder(): inputString = input('put numbers [ex)3 4 6 7 9] : ') numberList = [int(k) for k in inputString.split(' ')] numberList = sorted(numberList) print (numberList)
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:])) def merge(arr1, arr2): arr = [] i, j = 0, 0 for _ in range(len(arr1) + len(arr2)): if j >= len(arr2) or (i < len(arr1) and arr1[i] <= arr2[j]): i += 1 arr.append(arr1[i - 1]) elif j < len(arr2): j += 1 arr.append(arr2[j - 1]) return arr
def binary_search(arr, value): if len(arr) is 0: return False m = len(arr) // 2 if arr[m] is value: return True elif value < arr[m]: return binary_search(arr[:m], value) else: return binary_search(arr[m + 1:], value)
# Used to store multiple values in one single variable. # Create an array cars = ["Bmw", "Volvo","Audi"] print(cars) # Access array cars = ["Bmw", "Volvo","Audi"] x = cars[1] print(x) # Modify cars = ["Bmw", "Volvo","Audi"] cars[1] = "Mercedes" print(cars) # Lenght cars = ["Bmw", "Volvo","Audi"] x = len(cars) print(x) # Looping cars = ["Bmw", "Volvo","Audi"] for x in cars: print(x) # Adding array elements cars = ["Bmw", "Volvo","Audi"] cars.append("Honda") print(cars) # Remove array element cars = ["Bmw", "Volvo","Audi"] cars.pop(1) # cars.remove("Volvo") print(cars)
x = 5 #deklariranje varijabli y = "John" print (x) #ispis varijabli print (y) a, b, c = "A", "B", "C" print (a) print (b) print (c) x = "super" print ("Python je " + x) #kombinacija s + (spajanje varijabli i teksta) p = 5 d = 10 print (p + d) #Globalne varijable (varijabla izvan funkcije) x = "super" def myfunc(): print("Python je " + x) myfunc() #Globalne varijable (varijabla unutar funkcije) x = "great" def myfunc(): x = "extra" print("Python je " + x) myfunc() print("Python je " + x)
def prime(m): count = 0 for i in range(2,m): if( m%i) == 0: count +=1 if count == 0: return True else: return False n = eval(input()) num = round(n)+1 j = 5 Output = "" while j>0: if prime(num): j -= 1 Output += "{},".format(num) num += 1 print(Output[:-1]) #标准答案 def prime(m): for i in range(2,m): if m % i == 0: return False return True n = eval(input()) n_ = int(n) n_ = n_+1 if n_ < n else n_ count = 5 while count > 0: if prime(n_): if count > 1: print(n_, end=",") else: print(n_, end="") count -= 1 n_ += 1
def getNum(): s = input() ls = list(eval(s)) return ls def mean(numbers): s = 0.0 for i in numbers: s += i return s/len(numbers) def dev(numbers,mean): sdev = 0.0 for num in numbers: sdev = sdev + (num - mean)**2 return pow(sdev / (len(numbers)-1),0.5) def median(numbers): numbers.sort() size = len(numbers) if size % 2 == 0: med = (numbers[size//2-1]+numbers[size//2])/2 else: med = numbers[size//2] return med n = getNum() m = mean(n) print("平均值:{:.2f},标准差:{:.2f},中位数:{}".format(m,dev(n,m),median(n)))
#平方根格式化 #不完全版 num = input() sqnum=pow(eval(num),0.5,3) #result=round(sqnum,3) if len(str(result))<=30: print("{:+>30}".format(result)) else: print(result) #标准答案: a = eval(input()) print("{:+>30.3f}".format(pow(a,0.5)))
#从Web解析到网络空间 ''' Python库之网络爬虫 Python库之Web信息提取 Python库之Web网站开发 Python库之网络应用开发 Python库之网络爬虫 Requests:最友好的网络爬虫功能库 提供了简单易用的类HTTP协议网络爬虫功能 支持链接池,SSL,Cookies,HTTP(S)代理等 Python最主要的页面级网络爬虫功能库 import requests r = requests.get('https://api.github.com/user',\ auth=('user','pass')) r.status_code r.headers['content-type'] t.encoding t.text Scrapy:优秀的网络爬虫 提供了构建网络爬虫系统的框架功能,功能半成品 支持批量和定时网页爬取,提供数据处理流程等 Python最主要且最专业的网络爬虫框架 pyspider:强大的Web网页爬取系统 提供了完整的网页爬取系统构建功能 支持数据库后端,消息队列,优先级,分布式架构等 Python重要的网络爬虫类第三方库 Python库之Web信息提取 Beautiful Soup:HTML和XML的解析库 提供了解析HTML和XML等Web信息的功能 又名beautifulsoup4或bs4,可以加载多种解析引擎 常与网络爬虫库搭配使用,如Scrapy,requests等 Re:正则表达式解析和处理功能库 提供了定义和解析正则表达式的一批通用功能 可用于各类场景,包括定点的Web信息提取 Python最主要的标准库之一,无需安装 eg: re.search() re.split() re.match() re.finditer() re.findall() re.sub() r'\d{3}-\d{8}|\d{4}-\d{7}' Python-Goose:提取文章类型Web页面的功能库 提供了对Web页面中文章信息/视频等元数据的提取功能 针对特定类型Web页面,应用覆盖面较广 Python最主要的Web信息提取库 eg: from goose import Goose url = 'http://www.elmundo.es/elmundo/2012/10/28/espana/1351388909.html' g = Goose({'use_meta_language':False,'target_language':'es'}) article = g.extract(url=url) article.cleaned_text[:150] Django:最流行的Web应用框架 提供了构建Web系统的基本应用框架 MTV模式:模型(model),模板(Template),视图(views) Python最重要的Web应用框架,略显复杂的应用框架 Pyramid:规模适中的Web应用框架 提供了简单方便构建Web系统的应用框架 不大不小,规模适中,适合快速构建并适度扩展类应用 Python产品级Web应用框架,起步简单可扩展性好 from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def hell_world(requesr): return Response('Hello world!') if __name__ == '__main__'; with Configurator() as config: config.add('hello','/') config.add_view(hello,route_name('hello')) app = config.make_wsgi_app() server = make_server('0.0.0.0',6543,app) server.server_forever() Flask:Web应用开发微框架 提供了最简单构建Web系统的应用框架 特点是简单,规模小,快速 Django>Pramid>Flask eg: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello,World!' WeRoBot:微信公众号开发框架 提供了解析微信服务器消息及反馈消息的功能 建立微信机器人的重要技术手段 aip:百度AI开放平台接口 提供了访问百度AI服务的Python功能接口 语音,人脸,OCR,NLP,只是图谱,图像搜索等领域 Python百度AI应用的最主要方式 MyQR:二维码生成第三方库 提供了生成二维码的系列功能 基本二维码,艺术二维码,动态二维码 '''
alpha = "a b c d e f g h i j k l m n o p q r s t u v w x y z".split(" ") def binarySearch(toFind, items=[], count=1): if len(items) == 0: return False midpoint = len(items) // 2 mid = items[midpoint] # print(toFind, items, mid) if toFind == mid: return (True, count) elif toFind < mid: return binarySearch(toFind, items[:midpoint], count + 1) else: return binarySearch(toFind, items[midpoint + 1:], count + 1) # print(binarySearch("p", alpha)) # print(binarySearch("V", alpha)) numbers = list(range(2**9)) for number in numbers: _, count = binarySearch(number, numbers) print(number, count)
# -*- coding: utf-8 -*- import string string.ascii_lowercase ''' The below code is a long form of the Caesar Cipher def caesar(message, key): coded_message = "" alphabet = string.ascii_lowercase + " " letters = dict(enumerate(alphabet)) key = 3 code = {letter: (place + key) % 27 for (place, letter) in enumerate(alphabet)} num = [] for char in message: num.append(code[char]) for mun in num: coded_message += letters[mun] print(coded_message) return(coded_message) ''' alphabet = string.ascii_lowercase + " " letters = dict(enumerate(alphabet)) def caesar(message, key): """ This is a Caesar cipher. Each letter in a message is shifted by a few characters in the alphabet, and returned. message: A string you would like to encode or decode. Must consist of lowercase letters and spaces. key: An integer, indicating how many characters each letter in the message will be shifted. """ coded_message = {letter: (place + key) % 27 for (place, letter) in enumerate(alphabet)} coded_message_string = "".join([letters[coded_message[letter]] for letter in message]) return coded_message_string message = "hi my name is caesar" key = -3 caesar(message,key) coded_message = caesar(message, key=3) print(coded_message) #decoded_message = caesar(coded_message, key=-3) #print(decoded_message) def decaesar(message, key): lett = {v:k for k,v in letters.items()} decoded_message = {(place + key) % 27: letter for (place, letter) in enumerate(alphabet)} dec = "".join([decoded_message[lett[letter]]for letter in coded_message]) return dec
import random optionsList = ["r", "p", "s"] compChoiceFinal = None userChoiceFinal = None tie = "You chose the same option was the computer. Draw" lose = "Your choice was the wrong option. You lose." win = "Your choice was the right option! You win!" def user_choice(): user_choice = input("Choose rock, paper, or scissors (type: r, p, or s): ") if user_choice not in optionsList: print("Not one of the options. Try again.") user_choice() elif user_choice == str("r"): userChoiceFinal = optionsList[0] elif user_choice == str("p"): userChoiceFinal = optionsList[1] elif user_choice == str("s"): userChoiceFinal = optionsList[2] return userChoiceFinal def computer_choice(): compChoiceFinal = random.choice(optionsList) return compChoiceFinal def main(): rockPaperScissors_file = open("rockPaperScissors.txt", "r") print(rockPaperScissors_file.read()) rockPaperScissors_file.close() plays = int(input("Best out of how many games?: ")) player_wins = 0 computer_wins = 0 while player_wins < plays and computer_wins < plays: print("") userChoiceFinal = user_choice() compChoiceFinal = computer_choice() print("") endMessage = "Your input: " + str(userChoiceFinal) + "\nComputer's input: " + str(compChoiceFinal) + "\n" if userChoiceFinal == "r": if compChoiceFinal == "r": print(endMessage + tie) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif compChoiceFinal == "p": computer_wins += 1 print(endMessage + lose) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif compChoiceFinal == "s": player_wins += 1 print(endMessage + win) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif userChoiceFinal == "p": if compChoiceFinal == "r": player_wins += 1 print(endMessage + win) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif compChoiceFinal == "p": print(endMessage + tie) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif compChoiceFinal == "s": computer_wins += 1 print(endMessage + lose) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif userChoiceFinal == "s": if compChoiceFinal == "r": computer_wins += 1 print(endMessage + lose) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif compChoiceFinal == "p": player_wins += 1 print(endMessage + win) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) elif compChoiceFinal == "s": print(endMessage + tie) print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) if player_wins == plays or computer_wins == plays: print("Scores: \nYou: " + str(player_wins) + " Computer: " + str(computer_wins)) print("We have a winner!") break main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''Chap5 高阶函数 ''' fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=len)) ################################################################ def factorial(n): return 1 if n < 2 else n * factorial(n-1) fact = factorial # 构建 0! 到 5! 的一个阶乘列表 print(list(map(fact, range(6)))) # 使用列表推导执行相同的操作 print([fact(n) for n in range(6)]) # 使用 map 和 filter 计算直到 5! 的奇数阶乘列表 print(list(map(factorial, filter(lambda n: n % 2, range(6))))) # 使用列表推导做相同的工作,换掉 map 和 filter,并避免了使用 lambda 表达式 print([factorial(n) for n in range(6) if n % 2])
#!/usr/bin/env python3 # host = localhost # database: example1 # user: root # password: 123456 # table: students # 向 students 表插入数据 import pymysql.cursors # 打开数据库连接 connection = pymysql.connect(host = 'localhost', user = 'root', password = '123456', db = 'example1', charset = 'utf8mb4') try: with connection.cursor() as cursor: # SQL 插入语句 sql = "INSERT INTO students (name, score) VALUES ('steve', 99)" cursor.execute(sql) # 提交到数据库执行 connection.commit() with connection.cursor() as cursor: sql = "SELECT id, name FROM students WHERE score=99" cursor.execute(sql) result = cursor.fetchone() # 获取单条数据 print(result) finally: connection.close()
str1=input("Enter a string: ") from itertools import permutations perms = [''.join(p) for p in permutations(str1)] newperms=set(perms) print("Permutations: ",newperms)
c=3 for x in range(3): for y in range(5): if y<(c*2)-1: if y%2==0: print(c,end="") else: print("*",end="") print("") c-=1 c=1 for x in range(3): for y in range(5): if y<(c*2)-1: if y%2==0: print(c,end="") else: print("*",end="") print("") c+=1
for x in range(8): for y in range(8): if x==y: print("*", end="") elif x+y==7: print("*", end="") else: print(" ", end="") print("")
from tkinter import * window = Tk("kilograms -> grams, lbs, oz") window.geometry('1000x300') Label(window, text="Enter Weight in Kilograms").grid(row=0) e1_value = StringVar() e1 = Entry(window, textvariable=e1_value) e1.grid(row=0, column=1) def convert_kgs_lbs(): grams = float(e1_value.get()) * 1000 pounds = float(e1_value.get()) * 2.20462 ounces = float(e1_value.get()) * 35.274 t1.delete("1.0", END) t1.insert(END, grams) t2.delete("1.0", END) t2.insert(END, pounds) t3.delete("1.0", END) t3.insert(END, ounces) # Label for results Label(window, text="grams").grid(row=3, column=1) Label(window, text="pounds").grid(row=3, column=2) Label(window, text="ounces").grid(row=3, column=3) # text widgets t1 = Text(window, height=1, width=20, wrap=WORD, bd=2, bg="green") t2 = Text(window, height=1, width=20, wrap=WORD, bd=2, bg="green") t3 = Text(window, height=1, width=20, wrap=WORD, bd=2, bg="green") t1.grid(row=4, column=1) t2.grid(row=4, column=2) t3.grid(row=4, column=3) btn = Button(window, text="Click", width=25, activebackground="#00ff32", command=convert_kgs_lbs) btn.grid(row=0, column=2) # btn.pack(side="bottom") def kg_to_lbs(): print("hi") window.mainloop()
# 4.3 numbers = list(range(1, 21)) for number in numbers: print(number) print("\n") # 4.4 # millions = list(range(1, 1000000)) # for number in millions: # print(number) # print("\n") # 4.5 millions = list(range(1, 10000001)) print(min(millions)) print(max(millions)) print(sum(millions)) print("\n") # 4.6 odds = list(range(1, 20, 2)) for odd in odds: print(odd) print("\n") # 4.7 threes = list(range(3, 31, 3)) for three in threes: print(three) print("\n") # 4.8 cubes = [] for number in range(1, 11): cube = number**3 cubes.append(cube) for cube in cubes: print(cube) print("\n") # 4.9 cubes = [number**3 for number in range(1,11)] for cube in cubes: print(cube) print("\n") # 4.10 threes = list(range(3, 31, 3)) print(f"The first three numbers in the slice are: {threes[0:3]}") print(f"The middle three numbers in the slice are: {threes[4:7]}") print(f"The last three numbers in the slice are: {threes[7:]}")
people = [] person = { 'first_name': 'jason', 'last_name': 'ware', 'age': '42', 'city': 'cedar park', } people.append(person) person = { 'first_name': 'stuart', 'last_name': 'ware', 'age': '39', 'city': 'liberty hill', } people.append(person) person = { 'first_name': 'chad', 'last_name': 'ware', 'age': '37', 'city': 'euless', } people.append(person) for person in people: name = f"{person['first_name'].title()} {person['last_name'].title()}" age = person['age'] city = person['city'].title() print(f"{name}, of {city}, is {age} years old.")
word = input("Write an english word: ") prve_pismeno = word[0] stred = word[1:] convert = stred + prve_pismeno + "ay" print(convert) # PRIKLAD:DOMACI UKOLY2: ULOHA 9 # from random import randrange # cislo = randrange(3) # if cislo == 0: # print("kamen") # if cislo == 1: # print("nuzky") # else: # print("parir") # PRIKLAD:DOMACI UKOLY2: ULOHA 6,7 # strana = int(input("Zadaj stranu krychle: ")) # povrch = 6 * strana **2 # objem = strana **3 # print("S krychle je " + str(povrch) + " cm2") # print("V krychle je " + str(objem) + " cm3")
import disk import core from datetime import datetime def print_inventory(inventory): for item in inventory.values(): print('{}, Price: ${}, Stock: {}, replacement: ${}'.format( item['name'], item['price'], item['stock'], item['replacement'], )) def get_name(): answer = input("What's you name?").strip() return answer def sign_in(): while True: print() answer = input(' Employee(1) or Costumer(2):').strip().lower() if answer in ['1', '2']: return answer else: print('invalid response') def rent_or_return(name): print() print('\nWould you like to [rent] or [return] today ' + name + '?') print('\nEnter [done] if you want to exit application.') while True: answer = input('>>> ').lower().replace('[', '').replace(']', '').strip() if answer in ['rent', 'return']: return answer elif answer == 'done': exit() else: print("Invalid response.") def get_rental_item(inventory, name): print('What would you like to rent?') print(', '.join(inventory.keys())) while True: answer = input('>>> ').lower().replace('[', '').replace('[', '').strip() if answer in inventory.keys(): if core.in_stock(inventory, answer): return answer else: print('oops that item is not in stock... please pick another') else: print('invalid response') def user_days(): while True: answer = input('How long would you like to rent our merchandise? ') if answer.isdigit(): return int(answer) else: print('invalid response') def print_receipt(name, item, days, cost, tax, deposit, total): print(''' Customer Name: {} Renting a {} for {} days. \tCost: ${:.2f} \tTax: ${:.2f} \tDeposit: ${:.2f} TOTAL: ${:.2f} '''.format(name, item, days, cost, tax, deposit, total)) def rental_shell(inventory, name): rental_item = get_rental_item(inventory, name) days = user_days() core.rent_item(inventory, rental_item) cost = core.item_cost(inventory, rental_item, days) tax = core.get_tax(cost) deposit = core.get_deposit(inventory, rental_item) total = cost + tax + deposit print_receipt(name, rental_item, days, cost, tax, deposit, total) disk.write_history_file(inventory, rental_item, user_days, total, deposit) # prints out instructions for this program def instructions(): print('\nTo exit enter done.') print('\n' "Deposit will be refunded with return.") # def return_choice(): # while True: # answer = input('How long would you like to rent our merchandise?') # if answer.isdigit(): # return answer # else: # print('invalid response') def main(): inventory = disk.read_file('inventory.txt') inventory = core.make_inv(inventory) name = get_name() print_inventory(inventory) decision = sign_in() # decision 1 == employee while True: if decision == '1': decision = rent_or_return(name) if decision == 'rent': rental_shell(inventory, name) # decision 2 == customer if decision == '2': decision = rent_or_return(name) if decision == 'rent': rental_shell(inventory, name) elif decision == 'return': core.return_item(inventory, user_choice) # elif rent_or_return() == 'return': # return_choice() # core.add_to_stock(inventory, return_choice) # print(inventory[return_choice]) # elif rent_or_return() == 'done': # break # elif user_days() == '': # break # else: # print('Not in stock') # print(inventory.keys()) # user_choice() # '?').strip().lower() # if core.in_stock(inventory, user_choice): # user_days() # inventory[user_choice]['stock'] -= 1 # print(inventory[user_choice]) # taxed = core.price_with_tax(inventory, user_choice) # cost_indays = int(inventory[user_choice]['price'] * user_days) # print('taxed:', core.price_with_tax(inventory, user_choice)) # print('cost with days rented:', cost_indays) # taxed = core.price_with_tax(inventory, user_choice) # cost_indays = inventory[user_choice]['price'] * int(user_days) # replacement = core.find_replacement(inventory, user_choice) # total = round(taxed + cost_indays + replacement, 2) # print('total:', total) # disk.write_file(inventory, user_choice, user_days) elif decision == 'done': break if __name__ == '__main__': main()
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(): """ Asks user to specify a city, month, and day to analyze. 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!') #List of cities to check against user input cities=['chicago', 'new york city', 'washington'] #Ask user to enter name of city they wish to explore its data city=input("would you like to see data for Chicago, New York City or Washington?:\n").lower() while city not in cities: city=input("Please enter correct city name (Chicago, New York City or Washington):\n").lower() print("You have chosen={}".format(city)) #List of first 6 months of 2017 (january, february, ... , june,all) to check against user input months=['january', 'february', 'march', 'april', 'may', 'june','all'] #Ask user to input month name (january, february, ... , june,all) or choose all to filter by month month=input("Enter a month name (January - June) to filter the data by spacific month or enter 'all':\n").lower() while month not in months: month=input("Please enter correct month name (January - June) or enter 'all':\n").lower() print("You have chosen={}".format(month)) #List of days (saturday, sunday, ... friday,all) to check against user input days=['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','all'] #Ask user to input day of week or choose all to filter by day day=input("Enter day name to filter by day or enter 'all':\n").lower() while day not in days: day=input("Please enter correct day name or enter 'all':\n").lower() print("You have chosen={}".format(day)) print('-'*40) return city, month, day def load_data(city, month, day): #Load data of the chosen city by the user df=pd.read_csv(CITY_DATA[city]) """ 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 """ #Format Start Time values from String to Datetime df['Start Time']=pd.to_datetime(df['Start Time']) #Create month column from Start Time column date df['month']=df['Start Time'].dt.month #Create weekday column from Start Time Coloumn date df['day_of_week']=df['Start Time'].dt.weekday_name #Add hour and ST & End station combination column for upcoming analysis #Create hour column from Start Time column df['hour']=df['Start Time'].dt.hour #Create ST & End station combination column from Start Station and End Station columns df['ST End Stations']=df['Start Station'] + "+" + df['End Station'] #Filter data table based on user chosen month/s if month !='all': months=['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 df=df[df['month']==month] #Filter data table based on user chosen day/s if day !='all': df=df[df['day_of_week']==day.title()] 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() # Calculate the most common month common_month=df['month'].mode()[0] print("The most common month is={}".format(common_month)) # Calculate the most common day of week common_dow=df['day_of_week'].mode()[0] print("The most common day of week is={}".format(common_dow)) # Calculate the most common start hour common_st_hr=df['hour'].mode()[0] print("The most common start hour is={}".format(common_st_hr)) 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() # Display most commonly used start station common_st_station=df['Start Station'].mode()[0] print("The most common start station is={}".format(common_st_station)) # Display most commonly used end station common_end_station=df['End Station'].mode()[0] print("The most common end station is={}".format(common_end_station)) # Display most frequent combination of start station and end station trip common_combination=df['ST End Stations'].mode()[0] print("The most frequant combination of trips is={}".format(common_combination)) 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() # Calculate total travel time in seconds total_travel_time=df['Trip Duration'].sum() print("Total travel time in seconds is= {} seconds".format(total_travel_time)) # Calculate total travel time in minutes ttt_in_minutes=total_travel_time/60 ttt_in_minutes=format(ttt_in_minutes, ".2f") print("Total travel time in minutes is= {} minutes".format(ttt_in_minutes)) # Calculate mean travel time in seconds mean_travel_time=df['Trip Duration'].mean() mean_travel_time=format(mean_travel_time, ".2f") print("Mean travel time in seconds is= {} seconds".format(mean_travel_time)) # Calculate mean travel time in minutes mean_travel_time=float(mean_travel_time) mean_travel_time_min=mean_travel_time/60 print("Mean Travel time in minutes is=",format(mean_travel_time_min, ".2f"),"minutes") 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() # Calculate counts of user types (Subscriber, Customer and Dependent) user_types=df['User Type'].value_counts() print("Type of users distributed as=\n",user_types) # Calculate counts of gender (Male and Female) for Chicago and New York City if 'Gender' in df.columns: genders=df['Gender'].value_counts() print("Users genders distributed as=\n",genders) else: print("No gender details available for this city.") #Display earliest, most recent, and most common year of birth for Chicago and New York City #Display earliest year of birth(oldest customer) if 'Birth Year' in df.columns: eldest=df['Birth Year'].min() print("Earliset year of birth=",int(eldest)) #Display most recent birth year (youngest customer) youngest=df['Birth Year'].max() print("Most recent year of birth=",int(youngest)) #Display most common year of birth common_year=df['Birth Year'].mode()[0] print("Most common year of birth=",int(common_year)) else: print("No birth year information available for this city.") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def display_raw_data(df): answer="" i=0 while answer != "yes" or answer != "no" or answer != "n" or answer !="y": answer=input("Do you want to see 5 rows of raw data?(yes or no):\n").lower() if answer=="yes" or answer=="y": print(df.iloc[i:i+5]) i+=5 elif answer=="no" or answer =="n": print("End of program, thank you.") break else: print("wrong input, only (yes, no)..") continue 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) display_raw_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
jack_dit = raw_input("Dit quelque chose, Jack: ") retour = "" for i in jack_dit: j = i.lower() if (j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u' or j == 'y' or j == ' '): retour += i print "Sans les voyelles:", retour raw_input()
def init(data): data['first'] = {} data['middle'] = {} data['last'] = {} def lookup(data,label,name): return data[label].get(name) def store(data,full_name): names = full_name.split() if len(names) == 2: names.insert(1, '') labels = 'first', 'middle', 'last' for label, name in zip(labels, names): people = lookup(data, label, name) if people: people.append(full_name) else: data[label][name] = [full_name] def store2(data,*full_names): for full_name in full_names: names = full_name.split() if len(names) == 2: names.insert(1, '') labels = 'first', 'middle', 'last' for label, name in zip(labels, names): people = lookup(data, label, name) if people: people.append(full_name) else: data[label][name] = [full_name] def story(**kwds): return 'Once upon a time, there was a ' \ '%(job)s called %(name)s.' % kwds def power(x,y,*others): if others: print 'received redundant parameters:',others return pow(x, y) def multiplier(factor): def multiplyByFactor(number): return number*factor return multiplyByFactor def factorial(n): result = n for i in range(1, n): result *= i return result def factorial1(n): if n == 1: return n else: return n * factorial1(n - 1) def search(sequence,number,lower,upper): if lower == upper: assert number == sequence[upper] return upper else: middle = (lower + upper) / 2 if number > sequence[middle]: return search(sequence, number, middle + 1, upper) else: return search(sequence, number, lower, middle)
def prime(p): for i in range(2,int(p**(1/2))+1): if p % i ==0: return False return True for i in range(2,101): if prime(i): print(i)
count = 0 while count<5: print(count,"小于 5") count +=1 else: print(count,"大于或等于 5")
def is_leap(year): if (year%4==0 and year%100!=0)or (year%100==0 and year%400 != 0): return True return False year=int(input("请输入一个年份:")) if is_leap(year): print("{}是一个闰年".format(year)) else: print("{}不是一个闰年".format(year))
# # python书P56的2.7 # from turtle import * # pensize(2) # pencolor("blue") # for i in range(3): # setheading(-(120*i)+30) # forward(100) # penup() # goto(100*2*(3**(1/2))/3, 0) # pendown() # for i in range(3): # setheading(-(120 * i) - 150) # forward(100) # done() # python书P57的2.8 from turtle import * pencolor("blue") for i in range(99): setheading((i % 4)*90+90) forward(3+3*i) done()
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import random import simplegui import math # initialize global variables used in your code hidden=0 low =0 high=0 counter=0 # helper function to start and restart the game def new_game(): # remove this when you add your code frame.start() # define event handlers for control panel def range100(): # button that changes range to range [0,100) and restarts new_game() global counter counter=7 print "New game. Range is from 0 to 100" print "Number of remaining guesses is: ", counter,"\n" global hidden hidden=random.randint(0,100) def range1000(): new_game() global counter counter=10 # button that changes range to range [0,1000) and restarts print "New game. Range is from 0 to 1000" print "Number of remaining guesses is: ", counter global hidden hidden=random.randint(0,1000) def input_guess(guess): a=int(guess) # main game logic goes here print "Guess was: ",a global counter global hidden counter= counter-1 if(counter<0): print "You are out of guesses. The correct number is: ",hidden else: print "Number of remaining guesses is: ",counter if(a<hidden): print "Higher!\n" elif(a>hidden): print "Lower!\n" elif(a==hidden): print "Correct!\n" # create frame frame=simplegui.create_frame("Guess Number",400,300) # register event handlers for control elements frame.add_button("Range is [0,1000)",range1000,200) frame.add_button("Range is [0,100)",range100,200) frame.add_input("Enter a number",input_guess,100) # call new_game and start frame new_game() # always remember to check your completed program against the grading rubric
def main(): # for contador in range(1000): # if contador % 2 != 0: #si el residuo es distinto de 0 # continue #se salta lo que viene despues del continue # print(contador) # for i in range(10000): # print(i) # if i == 5967: # break # texto = input('Escribe un texto: ') # for letra in texto: # if letra == 'o': # break # print(letra) i = 0 while i < 1000: if i == 97: break print(i) i += 1 # i = 0 #para terminar el programa ctrl + c # while i < 100: # if i // 4: # continue # print(i) # i += 1 if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A collection of simple math operations """ def simple_add(a,b): return a+b def simple_sub(a,b): return a-b def simple_mult(a,b): return a*b def simple_div(a,b): return a/b def poly_first(x, a0, a1): return a0 + a1*x def poly_second(x, a0, a1, a2): return poly_first(x, a0, a1) + a2*(x**2) def power(a,b): return a**b def factorial (n) : # n : positive integer n0 = 1 if n == 0 : pass else : for k in range(n) : n0 *= k+1 return n0
# Three points, P1, P2 and P3, are randomly selected within a unit square. # Consider the three rectangles with sides parallel to the sides of the # unit square and a diagonal that is one of the three line segments. # Find the area of the second largest rectangle formed. import numpy as np import random def pick_points(): points_list=[] for points in range(0,3): x = random.random() y = random.random() point=(x,y) points_list.append(point) return points_list exp_area_list = [] for i in range(0,100000000): points_list = pick_points() x1 = points_list[0][0] y1 = points_list[0][1] x2 = points_list[1][0] y2 = points_list[1][1] x3 = points_list[2][0] y3 = points_list[2][1] R1=np.abs(x1-x3)*np.abs(y1-y3) R2=np.abs(x1-x2)*np.abs(y1-y2) R3=np.abs(x2-x3)*np.abs(y3-y2) area_list = [R1,R2,R3] area_list.pop() exp_area_list.append(max(area_list)) print(round(np.mean(exp_area_list), 10))