text
stringlengths
37
1.41M
def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr)-1-i): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(bubble_sort([100, 4, 1, 3, 200, 5,3,4,1,2])) def selection_sort(arr): for i in range(len(arr)-1, 0, -1): maxIndex = 0 for j in range(i+1): if arr[j] > arr[maxIndex]: maxIndex = j arr[i], arr[maxIndex] = arr[maxIndex], arr[i] return arr print(selection_sort([100, 4, 1, 3, 200, 5,3,4,1,2])) def mergeSort(arr): if len(arr) == 1: return arr a = arr[:int(len(arr)/2)] b = arr[int(len(arr)/2):] a = mergeSort(a) b = mergeSort(b) c = [] i = 0 j = 0 while i < len(a) and j < len(b): if a[i] < b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 c += a[i:] c += b[j:] return c print(mergeSort([100, 4, 1, 3, 200, 5,3,4,1,2]))
#!/usr/bin/env python3 """ Fix names in auth_users. Usage: ./fix_names data/site/epcon.db Uses nameparser package to do the hard work of splitting names into first and last name. Written by Marc-Andre Lemburg, 2019. """ import sqlite3 import sys import nameparser ### def connect(file): db = sqlite3.connect(file) db.row_factory = sqlite3.Row return db def get_users(db): c = db.cursor() c.execute('select * from auth_user') return c.fetchall() def fix_names(users): """ Fix names in user records. Yields records (first_name, last_name, id). """ for user in users: id = user['id'] first_name = user['first_name'].strip() last_name = user['last_name'].strip() if not first_name and not last_name: # Empty name: skip print (f'Skipping empty name in record {id}') continue elif first_name == last_name: full_name = first_name elif first_name.endswith(last_name): full_name = first_name elif not last_name: full_name = first_name elif not first_name: full_name = last_name else: # In this case, the user has most likely entered the name # correctly split, so skip full_name = first_name + last_name print (f'Skipping already split name: {first_name} / {last_name} ({id})') continue print (f'Working on "{full_name}" ({id})') # Handle email addresses if '@' in full_name: print (f' - fixing email address') # Remove domain part e_name = full_name[:full_name.find('@')] if '+' in e_name: # Remove alias e_name = e_name[:e_name.find('+')] # Try to split name parts e_name = e_name.replace('.', ' ') e_name = e_name.replace('_', ' ') e_name = e_name.strip() if len(e_name) < 4: # Probably just initials: leave email as is pass else: full_name = e_name # Parse name name = nameparser.HumanName(full_name) name.capitalize() first_name = name.first last_name = name.last print (f' - splitting name into: {first_name} / {last_name} ({id})') yield (first_name, last_name, id) def update_users(db, user_data): c = db.cursor() c.executemany('update auth_user set first_name=?, last_name=? where id=?', user_data) db.commit() ### if __name__ == '__main__': db = connect(sys.argv[1]) users = get_users(db) user_data = fix_names(users) update_users(db, user_data)
#!/usr/bin/env python """ Use BeautifulSoup to follow links to scrape data from understat.com To setup - `pip install bs4` """ import argparse import json import os from datetime import datetime, timedelta import pytz import requests from bs4 import BeautifulSoup from tqdm import tqdm LEAGUE_URL = "https://understat.com/league/epl/{}" MATCH_URL = "https://understat.com/match/{}" base_url = { "1516": LEAGUE_URL.format("2015"), "1617": LEAGUE_URL.format("2016"), "1718": LEAGUE_URL.format("2017"), "1819": LEAGUE_URL.format("2018"), "1920": LEAGUE_URL.format("2019"), "2021": LEAGUE_URL.format("2020"), "2122": LEAGUE_URL.format("2021"), } def get_matches_info(season: str): """Get the basic information for each match of the `season` from understat.com Parameters ---------- season : str String corresponding to the season for which we need to find the match info. Returns ------- list List of dictionaries containing the following information for each match: `id`: ID of the match used by understat.com `isResult`: True if the object is the result of a match. `h`: Dictionary object containing the home team information. `a`: Dictionary object containing the away team information. `goals`: Dictionary with number ofgoals scored by the home and away teams. `xG`: The xG statistic for both teams. `datetime`: The date and time of the match. `forecast`: Forecasted values for win/loss/draw. """ try: response = requests.get(base_url[season]) except KeyError: raise KeyError( f"Please provide valid season to scrape data: " f"{season} not in {list(base_url.keys())}" ) if response.ok: html = response.text start = html.find("JSON") + 11 end = html.find(")", start) json_string = html[start:end] json_string = json_string.encode("utf-8").decode("unicode_escape") matches_list = json.loads(json_string[1:-1]) return matches_list else: raise ValueError( f"Could not receive data for the given season. " f"Error code: {response.status_code}" ) def parse_match(match_info: dict): """Parse match webpage This function parses the webpage for the match corresponding to `match_id` and returns a dictionary with the required information. Parameters ---------- match_id: dict A dictionary that contains the basic information regarding the match like `id`, `h` (home_team), `a` (away_team) Returns ------- dict Dictionary with the following structure: { "home": home_team, "away": away_team, "goals": (dict) goals, "subs": (dict) subs, } The `goals` dict is structured as a dictinonary of lists {"home": [], "away": []} where each entry of the list is of the form [goal_scorer, time_of_goal]. The subs dict is also a dict of lists of the form {"home": [], "away": []} with each entry of the form [player_in, player_out, time_of_substitution]. """ match_id = match_info.get("id", None) if not match_id: raise KeyError( "`id` not found. Please provide the id of the match in the dictionary." ) home_team = match_info.get("h").get("title") away_team = match_info.get("a").get("title") date = match_info.get("datetime") if not date or datetime.fromisoformat(date) + timedelta(hours=3) > datetime.now( pytz.utc ): # match not played yet or only recently finished, skip return None response = requests.get(MATCH_URL.format(match_id)) if response.ok: soup = BeautifulSoup(response.text, features="lxml") else: raise RuntimeError( f"Could not reach match {match_id} " f"({home_team} vs. {away_team}, {date}) " f"at understat.com: {response.status_code}" ) timeline = soup.find_all( "div", attrs={"class": "timiline-container"}, recursive=True ) goals = {"home": [], "away": []} subs = {"home": [], "away": []} for event in timeline: if event.find("i", attrs={"class": "fa-futbol"}): scorer = event.find("a", attrs={"class": "player-name"}).text goal_time = event.find("span", attrs={"class": "minute-value"}).text[:-1] block = event.find("div", attrs={"class": "timeline-row"}).find_parent() if "block-home" in block["class"]: goals["home"].append((scorer, goal_time)) else: goals["away"].append((scorer, goal_time)) rows = event.find_all("div", attrs={"class": "timeline-row"}) if rows: for r in rows: if r.find("i", attrs={"class": "player-substitution"}): sub_info = [a.text for a in r.find_all("a")] sub_time = event.find("span", attrs={"class": "minute-value"}).text[ :-1 ] sub_info.append(sub_time) block = r.find_parent() if "block-home" in block["class"]: subs["home"].append(sub_info) else: subs["away"].append(sub_info) result = { "datetime": date, "home": home_team, "away": away_team, "goals": goals, "subs": subs, } return result def get_season_info(season: str, result: dict = {}): """Get statistics for whole season This function scrapes data for all the matches and returns a single dictionary that contains information regarding the goals and substitutions for all matches. Parameters ---------- season: str The season for which the statistics need to be reported. results: dict, optional Previously saved match results - won't get new data for any match ID present in results.keys(), by default {} Returns ------- dict Contains all the information regarding the home team, the away team, the goals scored and their times, and the substitutions made in the match. """ matches_info = get_matches_info(season) for match in tqdm(matches_info): if match.get("id") not in result.keys(): parsed_match = parse_match(match) if parsed_match: result[match.get("id")] = parsed_match return result def main(): parser = argparse.ArgumentParser(description="Scrape understat archives") parser.add_argument( "--season", help="Season to scrape data for", choices=list(base_url.keys()), required=True, ) parser.add_argument( "--overwrite", help="Force overwriting previously saved data if set", action="store_true", ) args = parser.parse_args() season = args.season overwrite = args.overwrite result = {} save_path = os.path.join( os.path.dirname(__file__), f"../data/goals_subs_data_{season}.json" ) if os.path.exists(save_path) and not overwrite: print( f"Data for {season} season already exists. Will only get data for new " "matches. To re-download data for all matches use --overwrite." ) with open(save_path, "r") as f: result = json.load(f) goal_subs_data = get_season_info(season, result=result) with open(save_path, "w") as f: json.dump(goal_subs_data, f, indent=4) if __name__ == "__main__": main()
#!/usr/bin/env python # coding: utf-8 # # Exercici 3 # # Crea una funció que donada una taula de dues dimensions, et calculi els totals per fila i els totals per columna. # In[2]: import numpy as np num = np.array([[12,3,1,4],[55,2,6,9]]) suma_fila = np.sum(num, axis = 0) suma_columna = np.sum(num, axis = 1) print("Filas: {}".format(suma_fila)) print("Columnas: {}".format(suma_columna)) # In[ ]:
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load our program, # but it will execute nothing yet. # -------------------------------------------------------- import pyspark # ------------------------------------------ # FUNCTION my_main # ------------------------------------------ def my_main(sc): pairRDD = sc.parallelize([(1, 2), (3, 4), (3, 6)]) pairRDD.persist() print("--- count_by_key ---") countRDD = pairRDD.countByKey().items() for w in countRDD: print(w) print("--- lookup_key ---") valuesForAKeyRDD = pairRDD.lookup(3) for w in valuesForAKeyRDD: print(w) # --------------------------------------------------------------- # PYTHON EXECUTION # This is the main entry point to the execution of our program. # It provides a call to the 'main function' defined in our # Python program, making the Python interpreter to trigger # its execution. # --------------------------------------------------------------- if __name__ == '__main__': # 1. We configure the Spark Context sc = pyspark.SparkContext.getOrCreate() sc.setLogLevel('WARN') print("\n\n\n") # 2. We call to my_main my_main(sc)
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load our program, # but it will execute nothing yet. # -------------------------------------------------------- import pyspark # ------------------------------------------ # FUNCTION my_main # ------------------------------------------ def my_main(sc): # 1. Operation C1: Creation 'parallelize', so as to store the content of the collection ["This is my first line", "Hello", "Another line here"] # into an RDD. As we see, in this case our RDD is a collection of String items. # C1: parallelize # dataset -----------------> inputRDD inputRDD = sc.parallelize(["This is my first line", "Hello", "Another line here"]) # 2. Operation T1: Transformation 'sortBy', so as to get inputRDD sorted by the desired order we want. # The transformation operation 'sortBy' is a higher order function. # It requires as input arguments: (i) A function F and (ii) a collection of items C. # The function F specifies the weight we assign to each item. # In our case, given an RDD of String items, our function F will weight each item with the number of words that there are in the String. # C1: parallelize T1: sortBy # dataset -----------------> inputRDD ------------> sortedRDD sortedRDD = inputRDD.sortBy(lambda line: len(line.split(" "))) # 3. Operation A1: collect the items from sortedRDD # C1: parallelize T1: sortBy A1: collect # dataset -----------------> inputRDD ------------> sortedRDD -------------> resVAL resVAL = sortedRDD.collect() # 4. We print by the screen the collection computed in resVAL for item in resVAL: print(item) # --------------------------------------------------------------- # PYTHON EXECUTION # This is the main entry point to the execution of our program. # It provides a call to the 'main function' defined in our # Python program, making the Python interpreter to trigger # its execution. # --------------------------------------------------------------- if __name__ == '__main__': # 1. We configure the Spark Context sc = pyspark.SparkContext.getOrCreate() sc.setLogLevel('WARN') print("\n\n\n") # 2. We call to my_main my_main(sc)
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load our program, # but it will execute nothing yet. # -------------------------------------------------------- import pyspark # ------------------------------------------ # FUNCTION my_mult # ------------------------------------------ def my_mult(x, y): # 1. We create the output variable res = x * y # 2. We return res return res # ------------------------------------------ # FUNCTION my_main # ------------------------------------------ def my_main(sc): # 1. Operation C1: Creation 'parallelize', so as to store the content of the collection [1,2,3,4] into an RDD. # Please note that the name parallelize is a false friend here. Indeed, the entire RDD is to be stored in a single machine, # and must fit in memory. # C1: parallelize # dataset -----------------> inputRDD inputRDD = sc.parallelize([1, 2, 3, 4]) # 2. Operation P1: We persist inputRDD, as we are going to use it more than once. # C1: parallelize P1: persist ------------ # dataset -----------------> inputRDD -------------> | inputRDD | # ------------ # 3. Operation A1: Action 'reduce', so as to get one aggregated value from inputRDD. # The action operation 'reduce' is a higher order function. # It is the most common basic action. With reduce(), we can easily sum the elements of our RDD, count the number of elements, # and perform other types of aggregations. # It requires as input arguments: (i) A function F and (ii) an RDD. # It produces as output argument a single result, computed by aggregating the result of applying F over all items of RDD (taken two by two). # Example: reduce (+) [1,2,3,4] = 10 (computed by doing 1 + 2 = 3, 3 + 3 = 6 and 6 + 4 = 10) # where F is (+), C is [1,2,3,4] and C' is 10 # In our case, the collection C is always going to be RDD1, and C' the new RDD2. # Thus, the only thing we are missing is specifying F. # As you see, F must be a function receiving just 2 parameter (the items i1 and i2 of C we want to apply F(i1, i2) to). # We can define F with a lambda abstraction. # C1: parallelize P1: persist ------------ # dataset -----------------> inputRDD -------------> | inputRDD | # ------------ # | # | A1: reduce # |------------> res1VAL # res1VAL = inputRDD.reduce(lambda x, y: x + y) # 4. We print by the screen the result computed in res1VAL print(res1VAL) # 5. Operation A2: Action 'reduce', so as to get one aggregated value from inputRDD. # In this case we define F with our own function. # C1: parallelize P1: persist ------------ # dataset -----------------> inputRDD -------------> | inputRDD | # ------------ # | # | A1: reduce # |------------> res1VAL # | # | A2: reduce # |------------> res2VAL res2VAL = inputRDD.reduce(my_mult) # 6. We print by the screen the result computed in res2VAL print(res2VAL) # --------------------------------------------------------------- # PYTHON EXECUTION # This is the main entry point to the execution of our program. # It provides a call to the 'main function' defined in our # Python program, making the Python interpreter to trigger # its execution. # --------------------------------------------------------------- if __name__ == '__main__': # 1. We configure the Spark Context sc = pyspark.SparkContext.getOrCreate() sc.setLogLevel('WARN') print("\n\n\n") # 2. We call to my_main my_main(sc)
# Created by Victor Honorato Pinheiro 05/09/2021 ''' A game in python than generate random maze everytime. FULL PERMISSION FOR PERSONAL OR COMERCIAL USE The maze generator use the Randomized Prim's algorithm Check (https://en.wikipedia.org/wiki/Maze_generation_algorithm#Randomized_Prim's_algorithm) ''' import pygame import time import random ## Defining constants #Colors WHITE = (255,255,255) BLACK = (0,0,0) RED = (213,50,80) #Dimensions, please chose multiple of 10 WIDTH=600 HEIGHT=400 class maze(): #initial state of the game def __init__(self, width, height): pygame.init() self.dis=pygame.display.set_mode((width,height)) pygame.display.update() pygame.display.set_caption("Maze game!") self.game_over = False self.width = width self.height = height #Start the game and give instructions when to finish def start(self): pygame.display.update() while not self.game_over: for event in pygame.event.get(): # Quit when clicked the close button if event.type == pygame.QUIT: self.game_over=True print(event) pygame.quit() quit() def generate_maze(self): #fill display with blue self.dis.fill(RED) # Get the starting point of the algoritm (step 2 on the list), multiple of 10 self.starting_height = int(random.random()*self.height) self.starting_width = int(random.random()*self.width) #verifying that free spot start at the edge: if self.starting_height == 0: self.starting_height = 10 if self.starting_height == self.height: self.starting_height = self.height - 10 if self.starting_width == 0: self.starting_width = 10 if self.starting_width == self.width: self.starting_width = self.width - 10 #now this block is a path and the walls around it should be add to a wall list pygame.draw.rect(self.dis, WHITE, [self.starting_width, self.starting_height, 10, 10]) self.walls = [] self.walls.append([self.starting_width-10, self.starting_height]) pygame.draw.rect(self.dis, BLACK, [self.starting_width-10,self.starting_height , 10, 10]) self.walls.append([self.starting_width, self.starting_height-10]) pygame.draw.rect(self.dis, BLACK, [self.starting_width,self.starting_height-10 , 10, 10]) self.walls.append([self.starting_width, self.starting_height+10]) pygame.draw.rect(self.dis, BLACK, [self.starting_width,self.starting_height+10 , 10, 10]) self.walls.append([self.starting_width+10, self.starting_height]) pygame.draw.rect(self.dis, BLACK, [self.starting_width+10,self.starting_height , 10, 10]) #Step 3 algo, pick a random cell from the wall list while there is walls there. while self.walls: #pick random wall self.rand_wall = self.walls[int(random.random()*len(self.walls)-1)] #Check if its a left wall if self.rand_wall[1] != 0: if self.dis.get_at((self.rand_wall[0]-10,self.rand_wall[1])) == RED and self.dis.get_at((self.rand_wall[0]+10,self.rand_wall[1])) == WHITE : #Get numbere of surrounding walls s_cells = self.surrounding_cells(self.rand_wall) if s_cells < 2: #new path pygame.draw.rect(self.dis, WHITE, [self.rand_wall[0], self.rand_wall[1] , 10, 10]) #Mark the new walls #Upper cell if (self.rand_wall[1] !=0): if self.dis.get_at((self.rand_wall[0],self.rand_wall[1]-10)) == WHITE: pygame.draw.rect(self.dis, BLACK, [self.rand_wall[0], self.rand_wall[1]-10 , 10, 10]) if [self.rand_wall[0],self.rand_wall[1]-10] not in self.walls: self.walls.append([self.rand_wall[0],self.rand_wall[1]-10]) #Bottom cell if (self.rand_wall[1] !=self.height-1): if self.dis.get_at((self.rand_wall[0],self.rand_wall[1]+10)) == WHITE: pygame.draw.rect(self.dis, BLACK, [self.rand_wall[0], self.rand_wall[1]-10 , 10, 10]) if [self.rand_wall[0],self.rand_wall[1]+10] not in self.walls: self.walls.append([self.rand_wall[0],self.rand_wall[1]+10]) #left cell if (self.rand_wall[0] !=0): if self.dis.get_at((self.rand_wall[0]-10,self.rand_wall[1])) == WHITE: pygame.draw.rect(self.dis, BLACK, [self.rand_wall[0]-10, self.rand_wall[1] , 10, 10]) if [self.rand_wall[0]-10,self.rand_wall[1]] not in self.walls: self.walls.append([self.rand_wall[0]-10,self.rand_wall[1]]) #Delete wall for wall in self.walls: if wall[0] == self.rand_wall[0] and wall[1] == self.rand_wall[1]: self.walls.remove(wall) break #Check if its an upper wall if self.rand_wall[0] != 0: if self.dis.get_at((self.rand_wall[0],self.rand_wall[1]-10)) == RED and self.dis.get_at((self.rand_wall[0],self.rand_wall[1]+10)) == WHITE : s_cells = self.surrounding_cells(self.rand_wall) if s_cells < 2: #Check if its an bottom wall if self.rand_wall[0] != self.height - 10: if self.dis.get_at((self.rand_wall[0],self.rand_wall[1]+10)) == RED and self.dis.get_at((self.rand_wall[0],self.rand_wall[1]-10)) == WHITE : s_cells = self.surrounding_cells(self.rand_wall) if s_cells < 2: #Check if its a right wall if self.rand_wall[1] != self.width: if self.dis.get_at((self.rand_wall[0]+10,self.rand_wall[1])) == RED and self.dis.get_at((self.rand_wall[0]-10,self.rand_wall[1])) == WHITE : s_cells = self.surrounding_cells(self.rand_wall) if s_cells < 2: def surrounding_cells(self, rand_walls): s_cells = 0 if self.dis.get_at((rand_walls[0],rand_walls[1]-10)) == WHITE: s_cells += 1 if self.dis.get_at((rand_walls[0],rand_walls[1]+10)) == WHITE: s_cells += 1 if self.dis.get_at((rand_walls[0]-10,rand_walls[1]-10)) == WHITE: s_cells += 1 if self.dis.get_at((rand_walls[0]+10,rand_walls[1]-10)) == WHITE: s_cells += 1 return s_cells game = maze(WIDTH, HEIGHT) game.generate_maze() game.start()
class Node(object): def __init__(self, value, next_node = None): self.value = value self.next_node = next_node def detect_cycle_with_dict(head): nodes_seen = {} current_node = head while current_node != None: if current_node in nodes_seen: return True nodes_seen[current_node] = True current_node = current_node.next_node return False a = Node(1) b = Node(2) c = Node(3) a.next_node = b b.next_node = c print(detect_cycle_with_dict(a)) c.next_node = a print(detect_cycle_with_dict(a)) def detect_cycle_two_pointer(head): pointer_one = head pointer_two = head # We dont need to check if pointer one is null # because pointer two will always be head. # If pointer two reaches null then we know there is no cycle while pointer_two != None and pointer_two.next_node != None: pointer_one = pointer_one.next_node pointer_two = pointer_two.next_node.next_node if pointer_one == pointer_two: return True return False a = Node(1) b = Node(2) c = Node(3) a.next_node = b b.next_node = c print(detect_cycle_two_pointer(a)) c.next_node = a print(detect_cycle_two_pointer(a))
def reverse_sentence(sentence): words = [] current_word = "" i = 0 while i < len(sentence): if sentence[i] == " ": words.append(current_word) current_word = " " else: current_word += sentence[i] i += 1 words.append(current_word) i = len(words) - 1 while i > 0: print(f"{words[i]} ") i -= 1 print(f"{words[0]}.") reverse_sentence("This is the best.")
def reverse_string(string): if len(string) == 1: return string return reverse_string(string[1:]) + string[0] print(reverse_string("abc"))
# Problem Set 4C import string from MIT60001_ps4a import get_permutations ### HELPER CODE ### def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. ''' print("Loading word list from file...") # inFile: file inFile = open(file_name, 'r') # wordlist: list of strings wordlist = [] for line in inFile: wordlist.extend([word.lower() for word in line.split(' ')]) print(" ", len(wordlist), "words loaded.") return wordlist def is_word(word_list, word): ''' Determines if word is a valid word, ignoring capitalization and punctuation word_list (list): list of words in the dictionary. word (string): a possible word. Returns: True if word is in word_list, False otherwise Example: >>> is_word(word_list, 'bat') returns True >>> is_word(word_list, 'asdf') returns False ''' word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"") return word in word_list WORDLIST_FILENAME = 'MIT60001_ps4_words.txt' # you may find these constants helpful VOWELS_LOWER = 'aeiou' VOWELS_UPPER = 'AEIOU' CONSONANTS_LOWER = 'bcdfghjklmnpqrstvwxyz' CONSONANTS_UPPER = 'BCDFGHJKLMNPQRSTVWXYZ' class SubMessage(object): def __init__(self, text): ''' Initializes a SubMessage object text (string): the message's text ''' self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) def get_message_text(self): ''' Used to safely access self.message_text outside of the class ''' return self.message_text def get_valid_words(self): ''' Used to safely access a copy of self.valid_words outside of the class. This helps you avoid accidentally mutating class attributes. ''' return self.valid_words def build_transpose_dict(self, vp): ''' vowels_permutation (string): a string containing a permutation of vowels (a, e, i, o, u) Example: When input "eaiuo": Mapping is a->e, e->a, i->i, o->u, u->o and "Hello World!" maps to "Hallu Wurld!" Returns: a dictionary mapping a letter (string) to another letter (string). ''' ret = {} for letter in string.ascii_uppercase + string.ascii_lowercase: ret[letter] = letter for i, letter in enumerate(VOWELS_LOWER): ret[letter] = vp[i] for i, letter in enumerate(VOWELS_UPPER): ret[letter] = vp[i].upper() return ret def apply_transpose(self, transpose_dict): ''' transpose_dict (dict): a transpose dictionary Returns: an encrypted version of the message text, based on the dictionary ''' letters = list(self.get_message_text()) for i, letter in enumerate(letters): letters[i] = transpose_dict.get(letter, letter) return ''.join(letters) class EncryptedSubMessage(SubMessage): def __init__(self, text): ''' Initializes an EncryptedSubMessage object text (string): the encrypted message text ''' super().__init__(text) def decrypt_message(self): ''' Attempt to decrypt the encrypted message Idea is to go through each permutation of the vowels and test it on the encrypted message. For each permutation, check how many words in the decrypted text are valid English words, and return the decrypted message with the most English words. If no good permutations are found (i.e. no permutations result in at least 1 valid word), return the original string. If there are multiple permutations that yield the maximum number of words, return any one of them. Returns: the best decrypted message Hint: use your function from Part 4A ''' # Get all permutations of vowels max_match_count = 0 max_match_permutation = "" for vowel_possiblility in get_permutations(VOWELS_LOWER): # Try with current vowels curr_sentence = self.apply_transpose(self.build_transpose_dict(vowel_possiblility)) # Count number of matches curr_match_count = 0 for curr_word in curr_sentence.split(" "): if is_word(self.valid_words, curr_word): curr_match_count += 1 if curr_match_count > max_match_count: max_match_count = curr_match_count max_match_permutation = vowel_possiblility if max_match_count == 0: return self.get_message_text() return self.apply_transpose(self.build_transpose_dict(max_match_permutation)) if __name__ == '__main__': # Example test case message = SubMessage("Hello World!") permutation = "eaiuo" enc_dict = message.build_transpose_dict(permutation) assert message.apply_transpose(enc_dict) == "Hallu Wurld!" enc_message = EncryptedSubMessage(message.apply_transpose(enc_dict)) assert enc_message.decrypt_message() == 'Hello World!' print("All assertions passed.")
# Problem Set 2, hangman.py # Hangman Game # ----------------------------------- # Helper code import random import string WORDLIST_FILENAME = "MIT60001_ps2.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print(" ", len(wordlist), "words loaded.") return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = load_words() def is_word_guessed(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing; assumes all letters are lowercase letters_guessed: list (of letters), which letters have been guessed so far; assumes that all letters are lowercase returns: boolean, True if all the letters of secret_word are in letters_guessed; False otherwise ''' return all(letter in letters_guessed for letter in secret_word) def get_guessed_word(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing letters_guessed: list (of letters), which letters have been guessed so far returns: string, comprised of letters, underscores (_), and spaces that represents which letters in secret_word have been guessed so far. ''' return ''.join([letter if letter in letters_guessed else "_ " for letter in secret_word]) def get_available_letters(letters_guessed): ''' letters_guessed: list (of letters), which letters have been guessed so far returns: string (of letters), comprised of letters that represents which letters have not yet been guessed. ''' return ''.join([letter for letter in string.ascii_lowercase if letter not in letters_guessed]) def match_with_gaps(my_word, other_word): ''' my_word: string with _ characters, current guess of secret word other_word: string, regular English word returns: boolean, True if all the actual letters of my_word match the corresponding letters of other_word, or the letter is the special symbol _ , and my_word and other_word are of the same length; False otherwise: ''' my_word = my_word.replace(" ", "") if len(my_word) != len(other_word): return False # Build dict of word other_word_dist = {} for (i, letter) in enumerate(other_word): if not letter in other_word_dist: other_word_dist[letter] = [] other_word_dist[letter].append(i) # Match my_word with dict above for letter in other_word_dist: my_word_distribution = set(my_word[pos] for pos in other_word_dist[letter]) if len(my_word_distribution) != 1 or (not letter in my_word_distribution and not "_" in my_word_distribution): return False return True def show_possible_matches(my_word): ''' my_word: string with _ characters, current guess of secret word returns: nothing, but should print out every word in wordlist that matches my_word Keep in mind that in hangman when a letter is guessed, all the positions at which that letter occurs in the secret word are revealed. Therefore, the hidden letter(_ ) cannot be one of the letters in the word that has already been revealed. ''' matches = [] for word in wordlist: if match_with_gaps(my_word, word): matches.append(word) if len(matches) != 0: for word in matches: print(word, end=" ") print("\n") else: print("No matches found") def hangman(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. ''' guesses = 6 warnings = 3 letters_guessed = [] print("Welcome to the game Hangman!") print("I am thinking of a word that is", len(secret_word), "letters long.") while guesses > 0: print("You have", guesses, "guesses left, and", warnings, "warnings left.") print("Available letters", get_available_letters(letters_guessed)) while True: try: letter = input("Enter a new letter: ").lower() if letter != "*" and (not letter.isalpha() or len(str(letter)) != 1 or letter in letters_guessed): raise ValueError break except: print("You must enter a single, previously unpicked letter, or *!") if warnings > 0: warnings -= 1 print("You lose a warning; you have", warnings, "warnings left.") elif warnings == 0: print("You can't pick a letter? You lose a guess! You have", guesses, "guesses.") guesses -= 1 # Update guesses, show user if not * if letter != "*": letters_guessed.append(letter) # Check for win if is_word_guessed(secret_word, letters_guessed): print ("You win! Score was", guesses * len(set(secret_word))) return True # Check for hint if letter == "*": print("Here are the possible matches!") show_possible_matches(get_guessed_word(secret_word, letters_guessed)) continue if letter in secret_word: print("Good guess! The letter", letter, "is in the word.") else: print("The letter", letter, "is not in the word. Try again.") if letter in ['a', 'e', 'i', 'o', 'u']: guesses -= 2 else: guesses -= 1 print(get_guessed_word(secret_word, letters_guessed)) print("-----------------------") return False # ----------------------------------- word = choose_word(wordlist) if not hangman(word): print ("You lose, the word was", word)
"""API MediaWiki file""" import requests class Wiki: """Uses Wikipedia's API to fetch extract and link of the page""" def __init__(self, question): self.question = question self.url = 'https://fr.wikipedia.org/w/api.php' self.params = {'action': 'query', 'generator': 'search', 'prop': 'extracts', 'explaintext': True, 'indexpageids': True, 'exsentences': 3, 'gsrlimit': 1, 'gsrsearch': self.question, 'exsectionformat': 'plain', 'format': 'json' } def search(self): """Search page_id, Wikipedia summary extract and page's link""" try: response = requests.get(self.url, self.params) result = response.json() page_id = result['query']['pageids'][0] page = result['query']['pages'][page_id]['extract'] url = 'http://fr.wikipedia.org/?curid=' + page_id return {'page': page, 'url': url} except IndexError: return "no result found" except KeyError: return 'no result found'
is_underage = int(input('What is your age:')) if is_underage >= 21: print('you may drink, smoke, and drive if you wish!') elif is_underage >= 18: print('You may smoke and drive!') elif is_underage >= 16: print('you may drive!') else : print('Enjoy your bike and the buss kid!')
from functools import reduce def multiply(x: int,y: int) -> int: return x*y def find_numbers(begin: int, end: int) -> list: """ :param begin: range start, int :param end: range end, int :return: list of numbers where number %7==0 and number %5 != 0 >>> find_numbers(5, 15) [7, 14] """ query_numbers = [] for number in range(begin, end): if (number %7 == 0 and number %5 != 0): query_numbers.append(number) return query_numbers def create_dict(span: int) -> dict: """ :param span: range end, int :return: dictionary like {i: i*i} >>> create_dict(3) {1: 1, 2: 4, 3: 9} """ if span < 0: print('A value for dictionary should be >0') return dictionary = dict() for i in range(1, span+1): dictionary[i] = pow(i, 2) return dictionary def factorial(number: int) -> int: """ :param number: input number, int :return: factorial(number), int >>> factorial(8) 40320 >>> factorial(-2) A value for factorial should be >= 0 """ if number < 0: print('A value for factorial should be >= 0') return if (number == 0 or number == 1): return 1 return number * factorial(number-1) def factorial_1(number: int) -> int: """ :param number: input number, int :return: factorial(number), int >>> factorial(-1) A value for factorial should be >= 0 >>> factorial(0) 1 """ if number < 0: print('A value for factorial should be >= 0') return if (number == 0 ): number = 1 return reduce(multiply, range(1,number+1)) def main(): # task one version_1 print('\nTASK_1 VERSION_1') print(*find_numbers(2000, 3201), sep = ', ', end='') # task one version_2 print('\n\nTASK_1 VERSION_2') print(*list(filter(lambda x: x%7==0 and x%5!=0, range(2000, 3201))), sep=', ', end='') print('\n Enter a number for task 2 and task 3:') n = int(input()) # task two print('\nTASK_2:\n') print(create_dict(n)) # task three version_1 print(f'\nTASK_3 VERSION_1\n') print(f'factorial({n}) = {factorial(n)}') #task three version_2 print(f'\nTASK_3 VERSION_2\n') print(f'factorial({n}) = {factorial_1(n)}') if __name__ == '__main__': main() import doctest doctest.testmod()
# this will print the date and time # import datetime # print (datetime.datetime.now()) # this will print a string with the date & time on 2 different lines # import datetime # print("The date and time is") # print (datetime.datetime.now()) # this will print everything on one line # import datetime # print("The date and time is", datetime.datetime.now()) # variables import datetime mynow = datetime.datetime.now() print(mynow) # different types of variables we can have mynumber = 10 mytext = "Hello" # to print the variables we created above print(mynumber, mytext) # different types of variables we cannot use # - # numbers #simple types: integers, strings and floats x = 10 y = "10" sum1 = x + x sum2 = y + y print(sum1, sum2) # int is short integer # str is short for string # int x = 10 ---> x = 10 # str y = 10 ---> y = "10" sum1 = x + x sum2 = y + y print(sum1, sum2) z = 10.1 print(type(x), type(y), type(z))
#################### ### BRIAN TIPOLD ### ### UBER PATHING ### #################### ## First time learning python ;) ### INIT ### import sys import csv import random #CONSTANTS INFINITY = sys.maxsize #VARIABLES graph = [] # graph requests = [] # list of requests networkCSV = open('network.csv', 'r') requestsCSV = open('requests.csv', 'r') totalWaitTime = 0 # total wait time is initialized listOfUbers = [] # list to hold uber drivers numOfCustomers = 0 # total number of customers/requests #DIJKSTRA'S ALGORITHM def timeOfShortestPath(startLocation, endLocation): if startLocation == endLocation: # if trying to compute distance between the same node return 0 # the distance is zero distances = [] # initialize list to hold shortest distances previous = [] # initialize list to hold the previous node it came through for i in range(0, 50): # for each node in graph previous.append(None) # last node is none distances.append(INFINITY) # current best distance is infinity distances[startLocation] = 0 # best distance to starting node is zero visited = [] # nothing in the visited list current = startLocation # current node is start location while endLocation not in visited: # when end node is in the visited list, the shortest path is found smallestDistanceNotVisited = INFINITY # initialize variable to hold current shortest path for i in range(0,50): # for each node in graph if distances[i]<smallestDistanceNotVisited and i not in visited: # pick shortest distance smallestDistanceNotVisited = distances[i] current = i for i in range(0, 50): # for each node in graph if graph[current][i] != 0 and i not in visited: # for each possible neighbour not visited yet if graph[current][i] + distances[current] < distances[i]: # if smaller than whats currently in distances distances[i] = graph[current][i]+distances[current] # update distances previous[i] = current visited.append(current) # add current node to visited list return distances[endLocation] # once the while loop breaks, return the distance of end node #CLASSES class uber: def __init__(self, startLocation): # constructor self.startLocation = startLocation # start location of driver self.currentRequest = request(0, startLocation, startLocation) # current job the driver is working on self.queuedRequest = None # job queue if too many requests come in class request: def __init__(self, startTime, startLocation, endLocation): self.startTime = startTime self.startLocation = startLocation - 1 self.endLocation = endLocation - 1 self.lengthOfJob = timeOfShortestPath(startLocation - 1, endLocation - 1) #IMPORT CSV dataReader = csv.reader(networkCSV, delimiter=',') # imports for row in dataReader: graph.append(row) for i in range(0, 50): row[i] = int(row[i]) dataReader = csv.reader(requestsCSV, delimiter=',') for row in dataReader: tempTime = int(row[0]) tempStart = int(row[1]) tempEnd = int(row[2]) requests.append(request(tempTime, tempStart, tempEnd)) numOfCustomers = len(requests) ### ALGORITHM ### numOfUbers = int(input("Input number of Ubers: ")) # take user input if numOfUbers < 2 or numOfUbers > 50: # throw exception if bad input print("Enter a number between 2 and 50") exit(1) #LIST OF DRIVERS for i in range(0, numOfUbers): # create drivers listOfUbers.append(uber(random.randint(0, 49))) # initialize them at random locations #HANDLE THE FIRST REQUEST closestUber = -1 # give first request to whichever driver is closest temp = INFINITY for i in range(0, numOfUbers): tempWaitTime = timeOfShortestPath(listOfUbers[i].startLocation, requests[0].startLocation) if tempWaitTime<temp: temp = tempWaitTime closestUber = i listOfUbers[closestUber].currentRequest = requests[0] #CALCULATE THE REST OF THE REQUEST for i in range(1, numOfCustomers): # for each request shortestWaitTime = INFINITY # variable for current best wait time closestUber = -1 # current closest uber deltaTime = requests[i].startTime - requests[i - 1].startTime # time since last request for j in range(0, numOfUbers): # for each uber if listOfUbers[j].queuedRequest == None: # if there is a request timeLeftInCurrentJob = max(0, listOfUbers[j].currentRequest.lengthOfJob - deltaTime) timeToNextPickup = timeOfShortestPath(listOfUbers[j].currentRequest.endLocation, requests[i].startLocation) tempWaitTime = timeLeftInCurrentJob + timeToNextPickup else: # if there is not a request timeToQueuedRequest = timeOfShortestPath(listOfUbers[j].currentRequest.endLocation, listOfUbers[j].queuedRequest.startLocation) timeToNextPickup = timeOfShortestPath(listOfUbers[j].queuedRequest.endLocation, requests[i].startLocation) tempWaitTime = max(0, listOfUbers[j].currentRequest.lengthOfJob - deltaTime + listOfUbers[j].queuedRequest.startTime + timeToQueuedRequest) + timeToNextPickup listOfUbers[j].queuedRequest = None # queued job is handled, so remove it if tempWaitTime < shortestWaitTime: # update current best wait time shortestWaitTime = tempWaitTime closestUber = j if listOfUbers[closestUber].currentRequest.lengthOfJob - deltaTime > 0: # if the uber cant complete his current job, listOfUbers[closestUber].queuedRequest = requests[i] # add it to queue else: # otherwise listOfUbers[closestUber].currentRequest = requests[i] # update current job with the new one totalWaitTime += shortestWaitTime # handle a new request and add it to wait time print("Wait time is: ", totalWaitTime) # output wait time print("Average wait time is: ", round(totalWaitTime / 300, 2)) # output avg wait time while i != 'q': i = input("press 'q' to quit:")
""" # Copyright Nick Cheng, 2018 # Distributed under the terms of the GNU General Public License. # # This file is part of Assignment 1, CSCA48, Winter 2018 # # This is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this file. If not, see <http://www.gnu.org/licenses/>. """ from wackynode import WackyNode # Do not add import statements or change the one above. # Write your WackyQueue class code below. class WackyQueue(): def __init__(self): self._oddlist = WackyNode(None, None) # dummy node self._evenlist = WackyNode(None, None) def __str__(self): result = "" curr = self._oddlist.get_next() while curr: result += str(curr.get_item()) result += " -> " curr = curr.get_next() result += "None (odd) \n" curr = self._evenlist.get_next() while curr: result += str(curr.get_item()) result += " -> " curr = curr.get_next() return result + "None (even)\n" def insert(self, obj, pri, node=None, curr=None, next=None): if not node: # for changepriority (in case you check for same node) node = WackyNode(obj, pri) if not curr: # for changepriority (avoid starting from head) curr, next = self._oddlist, self._evenlist while curr.get_next() and curr.get_next().get_priority() >= pri: next, curr = curr.get_next(), next node.set_next(next.get_next()) next.set_next(curr.get_next()) curr.set_next(node) def extracthigh(self): remove_node = self._oddlist.get_next() self._oddlist.set_next(self._evenlist.get_next()) self._evenlist.set_next(remove_node.get_next()) remove_node.set_next(None) return remove_node def isempty(self): return not self._oddlist.get_next() def changepriority(self, obj, pri): curr, next = self._oddlist, self._evenlist while curr.get_next() and curr.get_next().get_item() != obj: next, curr = curr.get_next(), next if curr.get_next() and curr.get_next().get_priority() != pri: old_pri = curr.get_next().get_priority() # optional curr.get_next().set_priority(pri) node = curr.get_next() # optional temp = curr.get_next().get_next() curr.set_next(next.get_next()) next.set_next(temp) if pri < old_pri: # optional self.insert(obj, pri, node, curr, next) # optional else: self.insert(obj, pri, node) def _reverse(self, head): num_node = 0 prev = None curr = head.get_next() while curr: curr.set_priority(-curr.get_priority()) temp = curr.get_next() curr.set_next(prev) prev = curr curr = temp num_node += 1 head.set_next(prev) return num_node def negateall(self): if (self._reverse(self._oddlist) + self._reverse(self._evenlist)) % 2 == 0: temp = self._oddlist.get_next() self._oddlist.set_next(self._evenlist.get_next()) self._evenlist.set_next(temp) def getoddlist(self): return self._oddlist.get_next() def getevenlist(self): return self._evenlist.get_next() print("\n\n\n\n\n\n\n") if __name__ == "__main__": wq = WackyQueue() wq.insert('6', 6) wq.insert('6', 6) wq.insert('A', 1) wq.insert('A', 0) wq.insert('A', 1) wq.insert('A', 0) wq.insert('B', 0) wq.insert('B', 0) wq.insert('Z', -2) wq.insert('P', -2) print(wq) print(wq.isempty()) wq.changepriority('B', -100) wq.changepriority('6', 4) wq.insert('5', 5) print(wq) wq.negateall() print(wq) wq.changepriority('A', 100) wq.insert('C', -1) print("---") print(wq) wq.negateall() print(wq) wq.changepriority('P', -0.5) wq.changepriority('KYLE', 100) wq.negateall() print(wq) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.extracthigh()) print(wq.isempty()) # print(wq.extracthigh()) # wq = WackyQueue() # wq.insert("A", 1) # wq.insert("B", 3) # wq.insert("C", 2) # wq.insert("D", 1) # wq.insert("E", 3) # wq.insert("F", 0) # wq.insert("G", -1) # wq.insert("H", -2) # print(wq) # wq.negateall() # print("negatall") # print(wq) # wq.insert("I", 3) # print("insert('I', 3)") # print(wq) # wq.negateall() # print("negatall") # print(wq) # print("removed: ", wq.extracthigh().get_item()) # print(wq) # wq.changepriority("D", 4) # print(wq) # # wq.changepriority("E", 4) # # print(wq, "changepriority('E', 4)\n") # # wq.changepriority("F", 3) # # print(wq, "changepriority('F', 3)\n") # # wq.changepriority("E", 1) # # print(wq, "changepriority('E', 1)\n") # wq.insert("Z", -3) # wq.negateall() # print("negatall\n", wq) # print("\n\n\n\n\n")
""" Helped function to plot data using matplotlib """ import matplotlib.pyplot as plt def plot_top_n(data_counts, title, xlabel, top=10): """ Produces a matplotlib plot with the given title and xlabel displaying the top results in data_counts Params: data_counts: a Counter object title, xlabel: strings top: optional integer arg """ most_numerous = data_counts.most_common(top) items, counts = zip(*most_numerous) plt.title(title) plt.xlabel(xlabel) plt.xticks(fontsize=10, rotation=90) plt.scatter(items, counts) plt.show()
import random import sys class Cell: def __init__(self, index, value): self.index = index self.value = value class Board: field = [] region_1 = [] region_2 = [] region_3 = [] region_4 = [] def __init__(self): self.create_board() def create_board(self): for i in range(6): self.field.append([]) for j in range(6): self.field[i].append(Cell(((i*6)+j),"-")) def print_board(self): for i in range(len(self.field)): if i == 3: print("=============") for j in range(len(self.field)): if j == 3: print("| ", end='') if j != 5: print(self.field[i][j].value, end = ' ') else: print(self.field[i][j].value) def insert_token(self, token, row, col): if self.field[int(row)][int(col)].value == "-": self.field[int(row)][int(col)].value = token def index_of_row_and_col(self,row,col): print(self.field[int(row)-1][int(col)-1].index+1) def checkWin(self, token): #check horizontal wins for i in range(len(self.field)): for j in range(len(self.field)-4): if((self.field[i][j].value == token) and (self.field[i][j+1].value == token) and (self.field[i][j+2].value == token) and (self.field[i][j+3].value == token) and (self.field[i][j+4].value == token)): return True #check vertical wins for i in range(len(self.field)-4): for j in range(len(self.field)): if((self.field[i][j].value == token) and (self.field[i+1][j].value == token) and (self.field[i+2][j].value == token) and (self.field[i+3][j].value == token) and (self.field[i+4][j].value == token)): return True #check \ diagonal wins for i in range(len(self.field)-4): for j in range(len(self.field)-4): if((self.field[i][j].value == token) and (self.field[i+1][j+1].value == token) and (self.field[i+2][j+2].value == token) and (self.field[i+3][j+3].value == token) and (self.field[i+4][j+4].value == token)): return True #check / diagonal wins for i in range(len(self.field)-4): for j in range(len(self.field)-4,len(self.field)): if((self.field[i][j].value == token) and (self.field[i+1][j-1].value == token) and (self.field[i+2][j-2].value == token) and (self.field[i+3][j-3].value == token) and (self.field[i+4][j-4].value == token)): return True return False def print_region(self,region): if region == 1: region = self.region_1 if region == 2: region = self.region_2 if region == 3: region = self.region_3 if region == 4: region = self.region_4 for i in range(len(region)): for j in range(len(region)): print(self.field[i][j].value, end = ' ') myBoard = Board() myBoard.define_regions() print(len(myBoard.region_1)) myBoard.print_region(1)
from mergesortwhichisnotmyne import mergeSort def merge_sort(arr): #spliting if len(arr) > 1: mid = len(arr)//2 right = arr[mid:] left = arr[:mid] print("spliting completed") # recursive call merge_sort(right) merge_sort(left) #iterators for the two list i = 0 j = 0 #iterator for the main list k = 0 #merging while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 print("merging completed") else: arr[k] = right[j] j += 1 k += 1 while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 list = [2,1,2,3,4,5,3,4,7,5,6,78,5,6,7,9,6,54,7,54,7] mergeSort(list) print(list)
from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() self.hideturtle() self.penup() self.color('white') self.setposition(0, 270) self.score_left = 0 self.score_right = 0 self._write_score() def add_score_to_left(self): self.score_left += 1 self._write_score() def add_score_to_right(self): self.score_right += 1 self._write_score() def _write_score(self): self.clear() self.write(f'{self.score_left}:{self.score_right}', align='center', font=('Arial', 24))
student_grades = [57, 74, 49, 0, 87, 66, 89] for g in student_grades: assert student_grades[g] != 0 if student_grades[g] >= 52: print('This student passed.') else: print('This student failed.') print('Program complete')
def multExcept(ln): rn = [] tot = 1 for x in ln: tot = tot * x for i in enumerate(ln): rn.append(tot/ln[i[0]]) return rn def multExceptNoDiv(ln): rn = [] for i in enumerate(ln): tot = 1 for j in enumerate(ln): if i[0] == j[0]: tot = tot*1 else: tot = tot * j[1] rn.append(tot) return rn if __name__ == "__main__": print(multExcept([1,2,3,4,5])) print(multExceptNoDiv([1,2,3,4,5])) print(multExcept([3,2,1])) print(multExceptNoDiv([3,2,1]))
def addToK(ln,k): # find if any 2 numbers in ln sum to k ld = [0] # list of differences found = False for x in ln: if x in ld: found = True ld.append(k-x) return found if __name__ == '__main__': print(addToK([10,15,3,7], 17))
import integrator import math # Pure Python implementation def python_midpoint(): difference = 1 n = 90600 f = lambda x: math.sin(x) while (difference > 1E-10): n += 1 sum_of_integral = integrator.integrate(f, 0, math.pi, n, method="midpoint", implementation="default") difference = abs(2 - sum_of_integral) print(n) print('Python - sum = {} difference = {} N = {}'.format(sum_of_integral, difference, n)) # Numpy implementation def numpy_midpoint(): difference = 1 n = 90600 f = lambda x: math.sin(x) while (difference > 1E-10): n += 1 sum_of_integral = integrator.integrate(f, 0, math.pi, n, method="midpoint", implementation="numpy") difference = abs(2 - sum_of_integral) print(n) print('Numpy - sum = {} difference = {} N = {}'.format(sum_of_integral, difference, n)) # Numba implementation def numba_midpoint(): difference = 1 n = 90600 f = lambda x: math.sin(x) while (difference > 1E-10): n += 1 sum_of_integral = integrator.integrate(f, 0, math.pi, n, method="midpoint", implementation="numpy") difference = abs(2 - sum_of_integral) print(n) print('Numba - sum = {} difference = {} N = {}'.format(sum_of_integral, difference, n)) # Cython implementation def cython_midpoint(): difference = 1 n = 90600 f = lambda x: math.sin(x) while (difference > 1E-10): n += 1 sum_of_integral = integrator.integrate(f, 0, math.pi, n, method="midpoint", implementation="numpy") difference = abs(2 - sum_of_integral) print(n) print('Cython - sum = {} difference = {} N = {}'.format(sum_of_integral, difference, n)) if __name__ == '__main__': python_midpoint() numpy_midpoint() numba_midpoint() cython_midpoint()
class Solution: def is_palindrome(self, x: int) -> bool: num = str(x) length = len(num) count = -1 for i in range(int(length / 2)): if num[i] != num[count]: return False count -= 1 return True
n = int(input('Enter the range of the fibonacci series to be printed : ')) def fib(n): # create list to hold the numbers of the series numbers = [0] * (n + 1) numbers[1] = 1 for i in range(2, n + 1): numbers[i] = numbers[i - 1] + numbers[i - 2] return numbers print fib(n)
class Student: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender s1 = Student('Parthibhan', 21, 'M') print s1 print s1.age
# decimel(.) precision of three for 0.3333 print '{0:.3f}'.format(1.0/3) # decimel(.) precision of 7 print '{0:.7f}'.format(1.0/3) # decimel precision 5 print '{0:.5f}'.format(55.0/33) # fill with underscores if width is less print '{0:_^5}'.format('Hello') print '{0:_^6}'.format('Hello') print '{0:_^11}'.format('Hello') print '{0:_^1000}'.format('Hello') # keyword-based print '{name} wrote this {program} code'.format(name = 'parthibhan', program = 'python') # prevent line feed being printed usin comma print 'a', x = 'a' print x, print 'a with line feed' print 'a'
def total(initial=5, *numbers, **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return count print total(10,1,2,5,99, vegetables=50, fruits=100, juices = 3)
# This is example of format method in python name = 'PARTHIBHAN' age = 20 print ' {0} is learning python at the age of {1} '.format(name,age) print ' playing with python at {0} '.format(age) # {0} represnts the the first argument passed to foramt method # The numbers are optional print ' My age is {} '.format(age)
b=1 a=int(input("введите число: ")) while (a!=1): b=b*a a=a-1 print("факториал числа:",b)
def add_nums(): number1 = 1 number2 = 2 answer = number1+number2 print( "{} plus {} is {}".format(number1,number2,answer)) add_two_numbers() def greetings_from_collaborator(name): print("Hi, I am your collaborator, {} :)".format(name)) greetings_from_collaborator("Gloria")
""" This module holds accessory functions that helps to accomplish the other tasks, such as calculates a piece column/line based on index and the number of columns or lines. """ def get_col_by_index(index, cols): """ It calculates the chess board column based on array index representations """ return index % cols def get_line_by_index(index, lines): """ It calculates the chess board line based on array index representations """ if index < lines: return 1 elif index == lines: return 2 elif index >= (lines - 1) * lines: return lines else: for line in range(2, lines): if index >= (line - 1) * lines and index < line * lines: return line return -1 def has_valid_number_pieces(configuration, original_permutation): """ Checks if a certain chess configuration has the valid number of pieces """ pieces = set(original_permutation) while len(pieces) > 0: piece = pieces.pop() if original_permutation.count(piece) != configuration.count(piece): return False return True
OPERATORS = {'+': (1, lambda x, y: x + y), '-': (1, lambda x, y: x - y), '*': (2, lambda x, y: x * y), '/': (2, lambda x, y: x / y)} def calc(formula: str) -> int: def simplification(formula_string: str) -> str: formula_string = formula_string.replace(' ', '') formula_string = formula_string.replace('--', '+') formula_string = formula_string.replace('+-', '-') formula_string = formula_string.replace('/-(', '/(0-1)/(') formula_string = formula_string.replace('*-(', '*(0-1)*(') formula_string = formula_string.replace('/-', '/(0-1)/') formula_string = formula_string.replace('*-', '*(0-1)*') formula_string = formula_string.replace('(-', '(0-') if formula_string[0] == '-': formula_string = '0'+formula_string return formula_string def parse(formula_string: str) -> float: number = '' for s in formula_string: if s in '1234567890.': number += s elif number: yield float(number) number = '' if s in OPERATORS or s in "()": yield s if number: yield float(number) def shunting_yard(parsed_formula: str) -> str: stack = [] for token in parsed_formula: if token in OPERATORS: while stack and stack[-1] != "(" and OPERATORS[token][0] <= OPERATORS[stack[-1]][0]: yield stack.pop() stack.append(token) elif token == ")": while stack: x = stack.pop() if x == "(": break yield x elif token == "(": stack.append(token) else: yield token while stack: yield stack.pop() def calculate(polish: str) -> int: stack = [] for token in polish: if token in OPERATORS: y, x = stack.pop(), stack.pop() stack.append(OPERATORS[token][1](x, y)) else: stack.append(token) return stack[0] return calculate(shunting_yard(parse(simplification(formula)))) if __name__ == '__main__': assert calc("1 + 1") == 2 assert calc("8/16") == 0.5 assert calc("3 -(-1)") == 4 assert calc("2 + -2") == 0 assert calc("10- 2- -5") == 13 assert calc("(((10)))") == 10 assert calc("3 * 5") == 15 assert calc("-7 * -(6 / 3)") == 14
def maximum_prime(n): m = 2 z = n #используем z, чтобы в дальнейшем сохранить выполнение цикла while True: if m > z: break else: if n%m == 0: #Здесь делим на все числа подряд if n == m: #Т.к. простые числа будут удалять break #возможность выдачи сложного делителя else: n //= m continue else: m += 1 continue return m
# Example 1: # # Input: "III" # Output: 3 # Example 2: # # Input: "IV" # Output: 4 # Example 3: # # Input: "IX" # Output: 9 # Example 4: # # Input: "LVIII" # Output: 58 # Explanation: L = 50, V= 5, III = 3. # Example 5: # # Input: "MCMXCIV" # Output: 1994 # Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. class Solution: def romanToInt(self, s: str) -> int: dic = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } total = 0 while s: if len(s) == 1 or dic[s[0]] >= dic[s[1]]: total += dic[s[0]] s = s[1:] else: total += dic[s[1]] - dic[s[0]] s = s[2:] return total
# Example 1: # # Input: s = "anagram", t = "nagaram" # Output: true # Example 2: # # Input: s = "rat", t = "car" # Output: false class Solution: def isAnagram(self, s: str, t: str) -> bool: s_dict = {} t_dict = {} for char in s: if char in s_dict.keys(): s_dict[char] += 1 else: s_dict[char] = 1 for char in t: if char in t_dict.keys(): t_dict[char] += 1 else: t_dict[char] = 1 if s_dict == t_dict: return True else: return False
""" Autor: Carbajal Ramos Juan Jesús Fecha: 04/07/19 """ #Realice un programa en Python que dado como datos los sueldos de 10 trabajadores de una empresa, #obtenga el total de nómina de la misma. Puede utilizar un ciclo for o un ciclo while. def main(): st = 0.0 for i in range(0, 10): print('Sueldo', i + 1, ': ', end = '') s = float(input('')) st = st + s print('Total nominal: ', st) if __name__ == '__main__': main()
""" Autor: Carbajal Ramos Juan Jesús Fecha: 05/07/19 """ import math class Punto(object): def __init__(self, x, y): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def setX(self, x): self.x = x def setY(self, y): self.y = y def toString(self): return 'El punto tiene las siguientes coordenadas', self.x, ',', self.y class Circunferencia(Punto): def __init__(self, radio): self.radio = radio def getRadio(self): return self.radio def setRadio(self, radio): self.radio = radio def getArea(self): return math.pi * math.pow(self.getRadio(), 2) def toString(self): return 'La circunferencia tiene como centro:', self.getX(), ',', self.getY(), ',', self.getRadio(), 'el area es: ', self.getArea() class Cilindro(Circunferencia): def __init__(self, altura): self.altura = altura def getAltura(self): return self.altura def setAltura(self, altura): self.altura = altura def getVolumen(self): return self.getArea() * self.altura def toString(self): return 'El volumen es:', self.getVolumen() def main(): p1 = Punto(2,3) print(p1.toString()) p2 = Punto(0,0) print(p2.toString()) p2.setX(-2) p2.setY(-4) print(p2.toString()) p3 = Circunferencia(12.34) p3.setX(10) p3.setY(12) print(p3.toString()) p4 = Cilindro(9.81) p4.setRadio(3.12) p4.setX(2) p4.setY(2) print(p4.toString()) if __name__ == '__main__': main()
#!/usr/bin/env python3 """ This would make a good library file for Chequeings and Savings bank accounts. """ class Account: """ Abstract base class for other types of accounts like Current (i.e. Chequeing) and Savings. """ def __init__(self, name, balance, min_balance): self.name = name self.balance = balance self.min_balance = min_balance def deposit(self, amount): """ Add the provided amount to balance. """ self.balance += amount def withdraw(self, amount): """ Substract the requested ammount from balance. """ if self.balance - amount >= self.min_balance: self.balance -= amount else: print("Sorry, not enough funds.") def statement(self): """ Report how much money is left in the account. """ print("Account Balance: ${}:".format(self.balance)) class Current(Account): """ Chequeing accounts (aka Current) have a minimum_balance requirement. """ def __init__(self, name, balance): super().__init__(name, balance, min_balance=-1000) def __str__(self): return "{}'s Current Account: Balance ${}".format(self.name, self.balance) class Savings(Account): """ Savings have zero minumum balance requirement. """ def __init__(self, name, balance): super().__init__(name, balance, min_balance=0) def __str__(self): return "{}'s Savings Account: Balance ${}".format(self.name, self.balance) CHEQUEING = Current("Ziyad", 500)
class Dog : species = 'firstdog' def __init__(self,name,age): self.name= name self.age = age print(Dog) a = Dog('mikky','5') print(a.name)
# # # # # str1 = "12345" # # list1 = list(str1) # # print (list1) # # b=",".join(list1) # # print(b) # # print(type(b)) # # c=b.split(",") # # print(c) # a=["1","3","5",6] # b=",".join(map(str,a)) # c=b.replace(",","") # print(type(b)) # d=list(c) # print(d) # print(d.index("1")) # d.remove("6") # print(d) # d.insert(3,6) # print(d) # re=d a # print(re) # d.pop() # print(d) # d.append(6) # print(d) # 从控制台接收逗号分隔的数字序列并生成一个列表和一个包含每个数字的元组的程序。 # # 假设向程序提供了以下输入: # # 34,67,55,33,12,98 # # 那么,输出应该是: # # ['34', '67', '55', '33', '12', '98'] # # ('34', '67', '55', '33', '12', '98') # # values=str (input("请输入值:")) # l=values.split(",") # t=tuple(l) # print(l) # print (t) class InputOutString(object): def __init__(self): self.s = "" def getString(self): self.s = input() def printString(self): print (self.s.upper()) strObj = InputOutString() strObj.getString() strObj.printString() # class InputOutString(): # def __int__(self): # self.s="" # def getString(self): # self.s=input() # def printString(self): # print(self.s.upper()) # strObj = InputOutString() # strObj.getString() # strObj.printString() #
from pprint import pprint def main(): print("Note: when computing matrix, elements of seq x will be drawn vertically and that of seq y will go horizontally:") s1 = list(str(input("Enter seq for x:"))) s2 = list(str(input("Enter seq for y:"))) x = [int(ord(i)) for i in s1] y = [int(ord(i)) for i in s2] # x = [1,0,0,1,0,1,0,1] # y = [0,1,0,1,1,0,1,1,0] numbmatrix = [[0 for _ in range(0, len(y)+1)] for _ in range(0, len(x)+1)] arrowmatrix = [[0 for _ in range(0, len(y)+1)]] i = 1 while i<=len(x): arrowrow = [0] j=1 while j<=len(y): # this is the main logic of computing number if x[i-1] == y[j-1]: numbmatrix[i][j] = numbmatrix[i - 1][j - 1] + 1 # diagonal arrow arrowrow.append(chr(int('0x2196', 16))) else: if numbmatrix[i-1][j]>=numbmatrix[i][j-1]: numbmatrix[i][j] = numbmatrix[i-1][j] # up arrow arrowrow.append(chr(int('0x2191', 16))) else: numbmatrix[i][j] = numbmatrix[i][j-1] # left arrow arrowrow.append(chr(int('0x2190', 16))) ######### j+=1 arrowmatrix.append(arrowrow) i+=1 # this is just for printing printFinalMatrix(numbmatrix, arrowmatrix) # computing the lcs lastIndex = [len(numbmatrix)-1, len(numbmatrix[0])-1] r = lastIndex[0] lcs = [] while r>0: if arrowmatrix[lastIndex[0]][lastIndex[1]] == chr(int('0x2196', 16)): # diag lcs.append(x[lastIndex[0]-1]) lastIndex[0]-=1 lastIndex[1]-=1 r-=1 elif arrowmatrix[lastIndex[0]][lastIndex[1]] == chr(int('0x2191', 16)): # up arrow lastIndex[0]-=1 r-=1 else: lastIndex[1] -= 1 # note: lcs list is appended so it is in reverse order, do reverse it again lcs = [chr(x) for x in lcs[::-1]] print("\nLCS ({}) = {}".format(len(lcs), lcs)) def printFinalMatrix(numbmatrix, arrowmatrix): fmat = [[0 for _ in range(0, len(numbmatrix[0]))] for _ in range(0, len(numbmatrix))] a=1 while a<len(numbmatrix): b=1 while b<len(numbmatrix[0]): fmat[a][b] = arrowmatrix[a][b]+str(numbmatrix[a][b]) b+=1 a+=1 pprint(fmat) # pprint(numbmatrix) # pprint(arrowmatrix) if __name__ == "__main__": main()
import itertools import time # read in our number set with open('Data.txt', 'r') as f: data = f.read().split() """ # @desc: trivial implementation to find the best way to partition the set into two sets of as close to equal sum as possible # @param: elements: list of numbers (n < 30) # @return: two partitioned sets """ def trivial_implementation(elements): # generate all combinations for set of elements min_diff = 1000000 # set of sets for all combinations generated by each iteration of loop on line 23 combos = [[]] len_elements = len(list(elements)) for i in range(len_elements): combos.append(itertools.combinations(elements, i)) # find respective sums and store set with smallest difference from half sum all elements for b in combos: for a in b: sum_a = sum(map(int, a)) set_diff = abs((sum(map(int, elements)))/2 - sum_a) if set_diff < min_diff: min_diff = set_diff best_set = a # print("Difference between the two sets = ", min_diff) other_set = [] for e in elements: if e not in best_set: other_set.append(e) # return both sets as a list of ints return list(map(int, other_set)), list(map(int, best_set)) """ # @desc: robust heuristic implementation to find efficient (and near best) way to partition the set into two sets of equal sum # @param: list of integers for two-way partitioning # @return: two partitioned sets """ def robust_implementation(elements): # performing two way set partition using greedy heuristic algorithm sorted_elements = sorted(map(int, elements), reverse= True) set1 = [] set2 = [] # set_diff represents the difference in scores of sum(set1) - sum(set2) # when it is positive, set1 has a larger sum and vice versa set_diff = 0 var = True count = 0 while count < len(sorted_elements): # if difference is greater than 0, set1 has a larger score if set_diff > 0: # subtract from set_diff because you are giving the larger score to set2 if sorted_elements[count] > sorted_elements[count+1]: # add larger element to set2 set2.append(sorted_elements[count]) set1.append(sorted_elements[count+1]) set_diff = set_diff - (sorted_elements[count] - sorted_elements[count+1]) else: set1.append(sorted_elements[count]) set2.append(sorted_elements[count+1]) set_diff = set_diff - (sorted_elements[count+1] - sorted_elements[count]) # set 2 has a larger or equal score else: # subtract difference between elements from set_diff because larger element is going into set1 if sorted_elements[count] > sorted_elements[count+1]: # add larger element to set1 set1.append(sorted_elements[count]) set2.append(sorted_elements[count+1]) set_diff = set_diff + (sorted_elements[count] - sorted_elements[count+1]) else: set2.append(sorted_elements[count]) set1.append(sorted_elements[count+1]) set_diff = set_diff + (sorted_elements[count+1] - sorted_elements[count]) # increment counter by 2 because moving 2 elements at a time count = count + 2 # edge case for odd amounts of elements in a set if count == len(sorted_elements) - 1: print(sorted_elements[count], " ") print(sum(set1), sum(set2)) if set_diff > 0: set2.append(sorted_elements[count]) set_diff = set_diff - sorted_elements[count] else: set1.append(sorted_elements[count]) set_diff = set_diff + sorted_elements[count] break # return both sets return set1, set2 if __name__ == '__main__': # create output file output = open("OutputFile.txt", 'w') # call trivial implementation start_trivial = time.perf_counter() triv_set1, triv_set2 = trivial_implementation(data) elapsed_triv = (time.perf_counter() - start_trivial) print("Set 1 elements: ", sorted(triv_set1, reverse=True), '\n', "Set 2 elements: ", sorted(triv_set2, reverse=True), file=output) print("Trivial remainder:", abs(sum(triv_set1) - sum(triv_set2)), file=output) print("Time required for trivial implementation: ", elapsed_triv, " seconds\n\n", file=output) # # call robust implementation start_robust = time.perf_counter() rob_set1, rob_set2 = robust_implementation(data) elapsed_robust = (time.perf_counter() - start_robust) print("Set 1 elements: ", rob_set1, '\n', "Set 2 elements: ", rob_set2, file=output) print("Robust remainder:", abs(sum(rob_set1) - sum(rob_set2)), file=output) print("Time required for robust implementation: ", elapsed_robust, "seconds\n\n", file=output)
from sys import stdin N = int(stdin.readline()) inputsum = sum([int(stdin.readline()) for _ in range(N)]) if N / 2 > N - inputsum: print("Junhee is cute!") else: print("Junhee is not cute!")
#!/usr/bin/env python3 # Created by: Seti Ngabo # Created on: Sept 2021 # this program calculates the area and perimeter of a rectangle # with dimensions 5cm x 3cm def main(): # this function calculates the area and perimeter print("If a rectangle has the dimensions:") print("5cm x 3cm") print("") print("Area is {}cm^2".format(5 * 3)) print("Perimeter is {}cm".format(2 * (5 + 3))) if __name__ == "__main__": main()
def valid_file(given_file): """ :param given_file: name of the supplied file :return: if the file is of valid format Note: Lazy Check """ if ".csv" not in given_file: print("Not a .csv type file? ") return False else: return True filename = input("Filename: ") new_filename = filename[0: len(filename) - 4] # dec_filename = new_filename + "_decrypted.csv" new_filename += "_decrypted.lzma" f = open(filename, "rb") # ignore first 43 bytes data_enc = f.read(43) # save rest of bytes data = f.read() empty = b'\x00' new_data = data[25:] first_8 = new_data[:8] rest = new_data[12:] print(new_data) new_file = open(new_filename, "wb") # insert 6 bytes in between new_file.write(first_8 + empty * 6 + b'\x11' + b'\x13' + rest) # save & finish new_file.close() f.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 14 17:07:40 2021 @author: n7 """ import os from . import text as tx from . import utils as ut def tabular(df, col_style=None, index=False): r""" Generate LaTeX tabular environment code for a DataFrame. Parameters ---------- df : pandas.DataFrame DataFrame for which the LaTeX tabularenvironment will be created. col_style : str or None, optional LaTeX column formatting for the table. If None, \|c\|c\|---\|c\| will be used. The default is None. index: bool, optional Specifies whether the row indices should be included as a separate column. The default is False. Returns ------- ltx : str LaTeX code for the tabular environment. """ if col_style is None: col_style = "|" for col in df.columns: col_style += r"c|" if (index): col_style += r"c|" header = [tx.bf(col) for col in df.columns] ltx = df.to_latex(header=header, index=index, column_format=col_style, escape=False) ltx = ltx.replace(r"\toprule", r"\hline").replace(r"\midrule" + os.linesep, "").replace(r"\bottomrule" + os.linesep, "").replace(r"\\", r"\\ \hline") return ltx def tab(df, pos="h!", caption=None, col_style=None, index=False, ref=None): """ Convert a DataFrame to a LaTeX Table Parameters ---------- df : pandas.DataFrame DataFrame for which the LaTeX table will be created. pos : str, optional LaTeX positioning scheme. The default is "h!". caption : str or None, optional Caption for the table. If None, the caption will not be added to the LaTeX table code. The default is None. col_style : str or None, optional LaTeX column formatting for the table. The default is None. index: bool, optional Specifies whether the row indices should be included as a separate column. The default is False. ref : str or None, optional Tag for adding a reference label to the table. If None, no label is added. The default is None. Returns ------- ltx : str LaTeX code for the table. """ pos = "[" + pos + "]" ltx = tabular(df, col_style) # Encapsulate in "table" tags ltx = ut.encapsln("table", ltx, pos, True, caption, "top", ref) return ltx
def main(): #write your code below this line string = str(input("Enter a string: ")) integer = int(input("Enter an integer: ")) Float = float(input("Enter a float: ")) Boolean = input("Enter a boolean: ") print("You give the string " + string) print("You gave the integer " + str(integer)) print("You gave the float " + str(Float)) if Boolean == "true": print("You gave the boolean " + Boolean) elif Boolean == "false": print("You gave the boolean " + Boolean) else: print("You didn't enter a Boolean!") if __name__ == '__main__': main()
import pandas as pd import sqlite3 import numpy as np from sklearn import preprocessing from math import radians, cos, sin, asin, sqrt import seaborn as sns from statistics import mode import matplotlib.pyplot as plt db = sqlite3.connect('ui/education.db') c = db.cursor() def haversine(lon1, lat1, lon2, lat2): ''' Calculate the circle distance between two points on the earth (specified in decimal degrees) This is from pa3 ''' # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) # 6367 km is the radius of the Earth km = 6367 * c m = 1000*km return m db.create_function("haversine", 4, haversine) def combine(): ''' This function calls all other relevant functions to generate a database with all relevant information (SchoolID, Latitude, Longitude, Average Graduation Rate, AverageACT, AverageAP3). Then the function normalizes each metric so that it is between 0-100, then computes the final education score and stores it back into the database. ''' create1() create2() create3() create4() lst = c.execute('SELECT school_data.SchoolID, Latitude, Longitude,\ AverageGraduation, AverageACT, AverageAP3 FROM school_data JOIN location \ ON school_data.SchoolID = location.SchoolID JOIN AverageACT \ ON location.SchoolID = AverageACT.SchoolID LEFT JOIN AverageAP \ ON location.SchoolID = AverageAP.SchoolID').fetchall() fulldata = pd.DataFrame.from_records(lst, columns = ['SchoolID', 'Latitude',\ 'Longitude','Average Graduation Rate', 'Average ACT', 'AvereageAP3+']) fulldata.fillna(0, inplace=True) front = fulldata[['SchoolID', 'Latitude', 'Longitude']] #This part takes care of the rescaling # Create x, where x the 'scores' column's values as floats x = fulldata[['Average Graduation Rate', 'Average ACT',\ 'AvereageAP3+']].values.astype(float) # Create a minimum and maximum processor object min_max_scaler = preprocessing.MinMaxScaler() # Create an object to transform the data to fit minmax processor x_scaled = min_max_scaler.fit_transform(x)*100 # Run the normalizer on the dataframe df_scaled = pd.DataFrame(x_scaled) df_scaled["score"] = (6/10)*df_scaled[0] + (4/10)*df_scaled[1]\ + (1/10)*df_scaled[2] result = pd.concat([front, df_scaled], axis=1) result.rename(columns = {0:'Average Graduation Rate',1:'Average ACT',\ 2:'AvereageAP3+'}, inplace = True) result.to_sql('school_metric', db, index = False) c.execute('drop table AverageACT') c.execute('drop table school_data') c.execute('drop table location') c.execute('drop table AverageAP') def create1(): ''' Imports the Graduation rate from the csv file and creates a database linking school id to the average draduation rate. ''' data = pd.read_csv("Education/Grad rate.csv") data.columns = data.iloc[0] processed = data[1:][["SchoolID", "2011","2012",\ "2013","2014","2015","2016","2017"]] processed.set_index('SchoolID', inplace=True) processed.fillna(np.nan) processed['2011'] = processed['2011'].str.replace('%','') processed['2012'] = processed['2012'].str.replace('%','') processed['2013'] = processed['2013'].str.replace('%','') processed['2014'] = processed['2014'].str.replace('%','') processed['2015'] = processed['2015'].str.replace('%','') processed['2016'] = processed['2016'].str.replace('%','') processed['2017'] = processed['2017'].str.replace('%','') processed = processed.apply(pd.to_numeric, args=('coerce',)) processed['AverageGraduation'] = processed.mean(axis=1) processed.to_sql('school_data', db, index = True) def create2(): ''' Imports the School locations from the csv file and creates a database linking school id to the lat long of each school. ''' data = pd.read_csv("Education/CPS Location.csv") processed = data[["SCHOOL_ID","Y","X"]] processed.rename(columns = {'SCHOOL_ID': 'SchoolID',\ 'Y':'Latitude','X': 'Longitude'}, inplace = True) processed.to_sql('location', db, index = False) def create3(): ''' Imports the ACT data from the csv file and creates a database linking school id to the Average composite ACT score of each school. ''' data = pd.read_csv("Education/ACT Score.csv") processed = data[["School ID","Composite"]] processed.rename(columns = {'School ID':'SchoolID'}, inplace = True) processed.to_sql('composite', db, index = False) Average_Composite = c.execute('SELECT SchoolID, AVG(Composite) \ FROM composite GROUP BY SchoolID').fetchall() processed = pd.DataFrame.from_records(Average_Composite,\ columns = ['SchoolID','AverageACT']) c.execute('drop table composite') processed.fillna(13, inplace=True) processed.to_sql('AverageACT', db, index = False) #return processed def create4(): ''' Imports the AP data from the csv file and creates a database linking school id to the Average percentage of students gettingg 3+ AP scores. ''' data = pd.read_csv("Education/AP Score.csv") data.columns = data.iloc[1] data.drop(data.index[0], inplace=True) data.drop(data.index[0], inplace=True) data.columns.values[6] = 'Percentage3' data.drop(data[data['Percentage3'] == "*"].index, inplace=True) data = data[["SchoolID","Percentage3"]] data.to_sql('ap', db, index = False) Average_AP = c.execute('SELECT SchoolID, AVG(Percentage3)\ FROM ap GROUP BY SchoolID').fetchall() processed = pd.DataFrame.from_records(Average_AP,\ columns = ['SchoolID','AverageAP3']) processed.to_sql('AverageAP', db, index = False) c.execute('drop table ap') #return processed def eduscore(lati,longi,distance): ''' Given a latitude, longitude, and a given radius. Find the education score for that lat long. ''' params = [lati, longi, distance] rv = c.execute('SELECT AVG(score) FROM school_metric \ WHERE haversine(?,?,Latitude,Longitude) < ?', params).fetchall() for tup in rv: score = list(tup)[0] if score > 100: score = 100 return score def create_heatmap(): alldata = c.execute('SELECT SchoolID, score FROM school_metric').fetchall() data = pd.DataFrame.from_records(alldata, columns=['SchoolID','score']) location = pd.read_csv("Education/CPS Location.csv") split = pd.DataFrame(location.SCH_ADDR.str.split(',').tolist(),columns = ['PURE','ZIP']) idtolocation = pd.concat([location["SCHOOL_ID"], split["PURE"]],axis=1) return small def identify_distribution(): ''' We want to identify the best way to normalize the time it takes for a request to be completed by identifying its distribution and working with outliers. Input: s (time taken - pandas series) ''' rv = c.execute('SELECT score FROM school_metric').fetchall() s = [] for tup in rv: score = list(tup)[0] if score > 100: score = 100 s.append(score) s = pd.Series(s) # take a look at the distribution: sns.distplot(s) plt.title('Histogram Eduscore') plt.savefig('Histogram Eduscore.png') # get key statistics: mu = np.mean(s) std = np.std(s) print('AVERAGE :', mu) print('STDEV :', std) '''Sources: Average ACT scores: https://cps.edu/Performance/Documents/Datafiles/AverageACT_2016_SchoolLevel.xls Graduation rates: https://cps.edu/Performance/Documents/DataFiles/Metrics_CohortGraduationDropout_SchoolLevel_2017.xls AP Scores : https://cps.edu/Performance/Documents/DataFiles/Metrics_AP_SchoolLevel_2017.xls Location : https://data.cityofchicago.org/Education/Chicago-Public-Schools-School-Locations-SY1718/4g38-vs8v/data '''
def checkio(number): # define string container wordedNumber = [] # define a few special cases numberLookup = { '1': 'one' , '2':'two' , '3':'three' , '4':'four' , '5':'five' , '6':'six' , '7':'seven' , '8':'eight' , '9':'nine' , '10':'ten' , '11':'eleven' , '12':'twelve' , '13':'thirteen' , '14':'fourteen' , '15':'fifteen' , '16':'sixteen', '17':'seventeen', '18':'eighteen' , '19':'nineteen', '20':'twenty' , '30':'thirty' , '40':'forty' , '50':'fifty' , '60':'sixty' , '70':'seventy' , '80':'eighty' , '90':'ninety' } print ('The raw number: %d' % number) # if we are in the thousands, translate the number of thouands we have and # append the 'thousand' string to it thousands = int(number / 1000) if thousands > 0: wordedNumber.append(numberLookup[str(thousands)] + " thousand") number -= thousands * 1000 # if we are in the hundreds, translate the number of hundreds we have and # append the 'hundred' string to it hundreds = int(number / 100) if hundreds > 0: wordedNumber.append(numberLookup[str(hundreds)] + " hundred") number -= hundreds * 100 # if we are in the tens, translate the number if we are between 10 and 20 # since those numbers are special cases. Otherwise translate only the tens # digit (twenty, thirty, forty, ...) tens = int(number / 10) if tens > 0: if 10 <= number <= 20: # set number to 0 after this since this finishes our translations wordedNumber.append(numberLookup[str(number)]) number = 0 else: wordedNumber.append(numberLookup[str(tens * 10)]) number -= tens * 10 # finally, translate the final one's digits if number > 0: wordedNumber.append(numberLookup[str(number)]) # combine the list with whitespace and return number = ' '.join(wordedNumber) print ('The worded number: '+number) return number if __name__ == '__main__': assert checkio(4) == 'four', "First" assert checkio(133) == 'one hundred thirty three', "Second" assert checkio(12) == 'twelve', "Third" assert checkio(101) == 'one hundred one', "Fifth" assert checkio(212) == 'two hundred twelve', "Sixth" assert checkio(40) == 'forty', "Seventh" # for fun assert checkio(999) == 'nine hundred ninety nine', "Eigth" assert checkio(9999) == 'nine thousand nine hundred ninety nine', 'Nineth' print('All ok')
import re """ This program supports two ways of validating ssn; from a txt-file or from direct input in program. 1) If you wish to validate multiple ssn: Go to main() -> set ssn_txt = True -> set filename 2) If you wish to validate on specific ssn: Go to main() -> set_txt = False -> specify the ssn you wish to validate * The ssn's must be of type String Because of the regex, the ssn can not contain multiple dots or dashes in a row. There are multiple good regex-expressions online, but I choose to write my own regex-expression. """ days_in_month = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} class Parse_string: def __init__(self, ssn): self.ssn = ssn def evaluate(self): # | -or # + - 1 eller mer # () - group. F.eks (com|edu) # regex sier: tall 0-9, saa - eller ., osv pattern = re.compile(r'([0-9]+)(-|.)([0-9][0-9]+)(-|.)([0-9]+(-|.))') matches = pattern.finditer(self.ssn) # henter ut gruppe (group) nr 2 og 3 fra re.searchen string_array = [] for match in matches: temp = match.group(0) for char in temp: if char.isdigit(): string_array.append(char) else: continue return string_array class Evaluator: def __init__(self): pass # ******* method for simplicity ****************** def get_birthday(self, string_array): if len(string_array) > 0: # for error-detection when using txt-file if int(string_array[0]) != 0: day = int(string_array[0] + string_array[1]) else: day = int(string_array[1]) if int(string_array[2]) != 0: month = int(string_array[2] + string_array[3]) else: month = int(string_array[3]) year = int(string_array[4] + string_array[5]) else: day, month, year = 0, 0, 0 return day, month, year def get_intarray(self, string_array): int_array = [] for element in string_array: int_array.append(int(element)) return int_array def contains_only_digits(self, string_array): for element in string_array: if element.isalpha(): return False return True def validate_month(self, month): if 1 <= month and month <= 12: return True return False def validate_day(self,day, month, year): max_days = days_in_month[month] if month == 2 and ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)): # check for leapyear max_days = 29 if 1 <= day <= max_days: return True return False def validate_length(self, ssn): if len(ssn) == 11: return True return False # validate controll number 1 def validate_controll_number1(self, ssn): k1 = ssn[9] check_k1 = 11 - ((3 * ssn[0] + 7*ssn[1] + 6*ssn[2] + 1*ssn[3] + 8*ssn[4] + 9*ssn[5] + 4*ssn[6] + 5*ssn[7] + 2 * ssn[8]) % 11) if k1 == check_k1: return True return False # validate controll number 2, which is the last number in the ssn def validate_controll_number2(self, ssn): k2 = ssn[10] k1 = ssn[9] check_k1 = 11 - ((5 * ssn[0] + 4 * ssn[1] + 3 * ssn[2] + 2 * ssn[3] + 7 * ssn[4] + 6 * ssn[5] + 5 * ssn[6] + 4 * ssn[7] + 3 * ssn[8] + 2*k1) % 11) if k2 == check_k1: return True return False # class takes a txt-file as parameter and returns an array containing possible ssn's def read_file(filename): ssn_list = [] with open(filename, 'r') as f: for line in f: ssn_list.append(line) # no need to close file ssn_list = map(str.strip, ssn_list) # removing \n return ssn_list # binding method. Returns whether the ssn is true or not def bind_all(ssn): string_array_ssn = Parse_string(ssn).evaluate() ev = Evaluator() int_array_ssn = ev.get_intarray(string_array_ssn) day, month, year = ev.get_birthday(string_array_ssn) return (ev.validate_length(string_array_ssn) and ev.contains_only_digits(string_array_ssn) and ev.validate_day(day, month, year) and ev.validate_month(month) and ev.validate_controll_number1(int_array_ssn) and ev.validate_controll_number2(int_array_ssn)) def main(): ssn_txt = False filename = "ssns.txt" # set filename here ssn = "1111111111111" # set ssn-number here if ssn_txt: ssn_list = read_file(filename) for element in ssn_list: check = bind_all(element) if not check: print(str(element) + " is not valid.") else: print(str(element) + " is VALID!") else: if bind_all(ssn): print(str(ssn) + ": korrekt personnummer!") return True else: print(str(ssn) + ": ikke korrekt personnummer") main()
#Import packages import csv import json from pprint import pprint #Read vegetables.csv into a variable called vegetables. with open('vegetables.csv', 'r') as f: reader = csv.DictReader(f) vegetables = [dict(row) for row in reader] # Convert Ordered Dict to regular dict (python 3.6 or higher) #group veggies by color in dictionary vegetables_by_color vegetables_by_color = {} for veg in vegetables: color = veg['color'] if color in vegetables_by_color: vegetables_by_color[color].append(veg) else: vegetables_by_color[color] = [veg] pprint(vegetables_by_color) #Write the veggies to a json file with open('vegetables_by_color.json', 'w') as f: json.dump(vegetables_by_color, f, indent = 2)
from datetime import datetime raw_date = "1-May-12" #-d doesn't work on my computer with strptime (it's #fine with strftime), but some googling/trying it and #seeing what happens tells me that strptime works fine #with %d even for non-zero-padded date_format = "%d-%B-%y" parsed_date = datetime.strptime(raw_date, date_format) date_str = parsed_date.strftime("%-m/%-d/%Y") print(date_str)
numbers = [2, 3, 5, 8, 9] for num in numbers: if num % 2 == 0: print("The number " + str(num) + " is even") else: print("The number " + str(num) + " is odd")
#for find the list input in a function with loop: # data=[ # [1,2,3,4,5], # [6,7,8,9,10], # [11,12,13,14,15], # [16,17,18,19,20] # # ] # for i in data: # for j in i : # if j==13 or j==18: # print(j) # break #n=len(data) #print(n) # x=[ # ["Ram","Shyam","Hari"], # ["Sita","Gita","Rita"], # ["Zyan","Arjit","Harry"], # ["Rohan","Sohan","Mohan"] # # # ] # for a in x: # for y in a: # if y=="Ram" or y=="Gita" or y=="Harry" or y=="Sohan": # print(y) # break
# # if # a = 5 # b = 10 # c = 30 # # if a == b: # print("yes") # else: # print("No") # a = 5 # b = 4 # c = 30 # if a > b and a > c: # print("A") # elif b > a and b > c: # print("B") # else: # print("c") # if a > b:-Nested statement # if a > c: # print("A") # else: # print("C") # # else: # if b > c: # print("B") # else: # print("C") # hw-1 # print("*******Driving-License*******\n") # age = int(input("Enter your age:\n")) # if age >=18 and age <= 50: # print("ok") # else: # print("not ok") # Even and oven =total even,total odd, # a = 15 # if a % 2 == 0: # print("Even") # else: # print("odd") # hw-2 # print("********** Mark-sheet**********\n") # a = int(input("Enter the marks of english:")) # b = int(input("Enter the marks of math:")) # c = int(input("Enter the marks of science:")) # d = int(input("Enter the marks of social:")) # e = int(input("Enter the marks of nepali:")) # h = (a + b + c + d + e) / 5 # if h >= 35 and h <= 40: # print("Div-pass") # elif h >= 45 and h <= 60: # print("Div-Second") # elif h >= 60 and h <= 75: # print("Div-First") # elif h >= 75 and h <= 100: # print("Div-Top") # elif h < 0 and h > 100: # print("Invalid") # else: # print("Fail") # hw-3 # print("******Ncell-Talktime*****\n") # print("##Talk-time-Offers##\n") # print("5min=Rs.5") # print("5min-20min=Rs.10") # print("20min-50min=Rs.25") # print("50min-100min=Rs.50\n") # print("*****Choose-your-plan*****") # a = int(input("Enter the talk-time:")) # if a == 5: # print(" *Rs.5 will charge on your talk-time.") # if a > 5 and a < 20: # print("*Rs.10 will charge on your talk-time.") # if a >= 20 and a < 50: # print("*Rs.25 will charge on your talk-time.") # if a >= 50 and a < 100: # print("*Rs.50 will charge on your talk-time.") # elif a<5: # print("Errors") # else: # print("Errors")
names = ["deter", "Bernd", "Martin"] print(names) # liste absteigend sortieren names.sort(reverse=True) print(names) # Zahlen aufsteigend sortieren numbers = [1, 7, 3, 7] numbers.sort() print(numbers) numbers = [0.9, 0.1, 0.5] numbers.sort(reverse=True) print(numbers)
print(list(range(2,5))) L = [] for x in range(1,11): L.append(x*x) print(L) l2 = [x*x for x in range(1,11)] print(l2) print([x*x for x in range(1,11) if x %2 ==0]) # 双层循环 print([m+n for m in 'ABC' for n in 'abc']) l = {1:'a',2:'b',3:'c',4:'5'} print([(k,v) for k,v in l.items()]) # 练习 l3 = ['Hello', 'World', 18, 'Apple', None] l2 = [x.lower() for x in l3 if isinstance(x,str)] print(l2)
print(hex(255)) # 位置参数 def power1(x,n): s = 1 while n > 0: s = x * s n = n - 1 print(s) power1(2,5) # 默认参数 def power2(x,n=2): s=1 while n > 0: s = x * s n = n - 1 print(s) power2(2) def student(name,age,city='北京',height='120'): print('name:',name,'age:',age,'city:',city,'height:',height) student('zhangli',13) student('dianli',20) student('haha',29,height=280,city='河南') student('adada',44,'上海',190) student('etgsg',29,height=280) # 可变参数 def calc1(numbers): s = 0 for n in numbers: s = s + n print(s) # list calc1([1,2,3]) # tuple calc1((3,4,5)) # 报错 # calc1(1,2,3) def calc2(*numbers): # 把一个个参数转为list或turpe s = 0 for num in numbers: s = s + num print(s) calc2(1,2,3) calc2(*[1,2,3]) # 把list和turpe转为一个一个参数 print(*[1,2,3]) # 1 2 3 # 关键字参数 def person1(name,age,**kw): #把多个键值对转为dict print('name:',name,'age:',age,'other:',kw) # 报错 person1('z',13,'北京') person1('z',13,city='北京') extra = {'height':190,'weight':200} person1('dianili',10,**extra) #把dict转为键值对 # 命名关键字 def person2(name,age,*,height): print(name,age,height) # person2('zhangli',19,**extra) TypeError: person2() got an unexpected keyword argument 'weight' # person2('zahng',29,height=190,weight=280) TypeError: person2() got an unexpected keyword argument 'weight' person2('akgf',18,height=190) #练习题 def product(x,*num): s = x for n in num: s = s * n return s # 测试 print('product(5) =', product(5)) print('product(5, 6) =', product(5, 6)) print('product(5, 6, 7) =', product(5, 6, 7)) print('product(5, 6, 7, 9) =', product(5, 6, 7, 9)) if product(5) != 5: print('测试失败!') elif product(5, 6) != 30: print('测试失败!') elif product(5, 6, 7) != 210: print('测试失败!') elif product(5, 6, 7, 9) != 1890: print('测试失败!') else: try: product() print('测试失败!') except TypeError: print('测试成功!')
#!/usr/bin/python from random import randint # Dice Simulation 1 n = int(raw_input("How many iterations should I perform?\n")) counter = 0 for i in range(n): dice1 = randint(1,6) dice2 = randint(1,6) if dice1 == 6 or dice2 == 6: counter += 1 print "Estimated probability of getting a 6 if two dice are thrown: %f and exact result is: %f" % (float(counter)/n,11./36) # n = 100000 leads to a correct result up to 3 decimals. # Dice Simulation 2 N = int(raw_input("How many dice should I roll?\n")) n = int(raw_input("How many iterations should I perform?\n")) counter = 0 for i in range(n): for j in range(N): dice = randint(1,6) if dice == 6: counter += 1 break # it is enough that one dice out of N gives a 6, that is how we have defined the event # calculate the probability theoretical probability from math import factorial # using a list comprehension to produce a binomial distribution prob = sum([float(factorial(N))/(factorial(k)*factorial(N-k))*(1./6)**k * (5./6)**(N-k) for k in range(1,N+1)]) print "Estimated probability of getting a 6 if %d dice are thrown: %f and exact result is: %f" % (N,float(counter)/n, prob) # Dice Simulation 3 n = int(raw_input("How many repititions of the game do we play?\n")) money = 0 for i in range(n): if sum([randint(1,6) for i in range(4)]) < 9: money += 10 else: money -= 1 if money < 0: print "You lost %d amount of money" % (-money) else: print "You won %d amount of money" % (money) # You will lose on the long run, better not to play the game.
# 5. Nonlinear Fit import numpy as np f = lambda x, a, b : np.exp(-a*x) + b # define a lambda function with three arguments x = np.arange(0, 4, 0.01) y = f(x, 2.5, 1.4) # generate y values from the lambda function y = y + 0.25*np.random.randn(len(y)) # add Gaussian noise to the values import pylab as pl pl.plot(x, y) pl.show() import scipy.optimize as opt # NOTE: The optimize package is NOT automatically included when you import scipy as sc. # The function 'optimize.curve_fit' is for fitting a function f(x) to data coordinates (x, y) and returns the fitted parameters to 'popt'. # For further information try 'help(opt.curve_fit)'. popt, pcov = opt.curve_fit(f, x, y) print popt pl.plot(x, y, label = 'Noisy Data') pl.plot(x, f(x, popt[0], popt[1]), label = 'Nonlinear Fit', color = 'r') pl.annotate('$f(x) = e^{-a \cdot x} + b$', size = 16, xy=(1, 1.5), xycoords = 'data', xytext=(1, 2.5), textcoords = 'data', arrowprops=dict(arrowstyle="->") ) pl.xlabel('x') pl.ylabel('f(x)') pl.legend() pl.show()
class Animal: """An abstract animal""" def __init__(self, weight, age): # store your own copy of weight and age such that we can # refer to them later self.__weight=weight self.__age = age # look at move() function self._weightLossPerDistance = 1.0 def age(self): """ This function allows to access self.__age from outside """ return self.__age def weight(self): """ This function allows to access self.__weight from outside """ return self.__weight def eat(self, amount): """ When the animal eats, it inceases the weight by amount. """ self.__weight += amount def move(self, distance): """ Motion needs energy, therefore this function decreases the weight according to the constant self.__weightLossPerDistance. If self.__weight falls below 0 an error message is printed. """ self.__weight -= self._weightLossPerDistance*distance if self.__weight<=0.0: print "I'm starving..." def speak(self): print "I am an abstract animal which can't speak" class Fish(Animal): """This is a fish""" def __init__(self, weight, age): # Call the constructor of the parent class Animal.__init__(self, weight, age) def move(self, distance): # Use the behaviour from the parent class, and, in addition, # print a fish-specific message Animal.move(self, distance) print "I'm swimming through the aquarium" def speak(self): print "blub" class Cat(Animal): """I'm a cat""" def __init__(self, weight, age): Animal.__init__(self, weight, age) self._weightLossPerDistance = 3.0 def move(self, distance): Animal.move(self, distance) print "I'm chasing mice" def speak(self): print "Miau" def eat(self, fish, animalDi): """ This function checks if the argument 'fish' really is of type Fish and, if so, eats it. This accounts to deleting it from the dictionary 'animalDi'. Note that it is (as far as I know) not possible to globally erase the fish instance from memory. So deleting it from a "reservoir of animals" is the closest thing to killing it. """ if isinstance(fish,Fish): delvar=None for a in animalDi: if id(fish)==id(animalDi[a]): delvar=a break if delvar!=None: del animalDi[a] print "Hmmm, that was delicious. Rest in peace fish!" else: print "Couldn't see the fish to eat" else: print "I'm a cat, I don't eat that crap" def test_animal(): a=Animal(27.23,1) f=Fish(3.141,2) c=Cat(2.718,3) pets = { 'abstract':a, 'neo':f, 'snowball':c } for p in pets: pets[p].speak() pets[p].move(2) c.eat(a,pets) c.eat(f,pets) try: pets['neo'].speak() except(KeyError): print "Sorry, the fish is gone" # but accessing f directly still works: f.speak() if __name__=='__main__': test_animal()
# make a binary file from a text file # v short import argparse as ap parser = ap.ArgumentParser(description = 'Save a binary copy of a txt file.') parser.add_argument('file', metavar = 'FILE', type = ap.FileType('r'), help = 'Path to the text file to copy and save.') parser.add_argument('-o', metavar = 'OUTFILE_NAME', default = False, help = 'Name to give to the *.bi outfile.') args = parser.parse_args() inFile = args.file inLines = inFile.readlines() inFile.close() if args.o==False: outFile = open('{0}.bi'.format(inFile.name), 'wb') else: outFile = open('{0}.bi'.format(args.o), 'wb') for line in inLines: outFile.write(line) outFile.close() print 'Created a binary file {0}.'.format(outFile.name)
''' This code is designed to build a classic hangman game Starts on page 132 of the 'Self-Taught Programmer ''' def hangman(): import random word_list = ['arbitrary','benign','chemical','derail','echo','fetter','gargoyle','hairstyle','indigo','jalapeno','kangaroo'] word = random.choice(word_list) wrong = 0 stages = ["", " ", "__________ ", "| ", "| | ", "| O ", "| /|\ ", "| / \ ", "| ", ] rletters = list(word) board = ["__"] * len(word) win = False print('Welcome to Hangman') # print(board) while wrong < len(stages) - 1: print('\n') msg = 'Guess a letter: ' char = input(msg) if char in rletters: cind = rletters.index(char) board[cind] = char rletters[cind] = '$' else: wrong += 1 print((' '.join(board))) e = wrong + 1 print('\n'.join(stages[0:e])) ''' my approach to the loss definition if wrong == len(stages) - 2: print('You\'ve been hung due to being terrible at this') break ''' if '__' not in board: print('You win!') print(' '.join(board)) win = True break if not win: print('\n'.join(stages[0:wrong])) print('You lose! The word was {w}, dummy.'.format(w=word))
# Chapter 4 challenges # 1. Write a function that takes a number as an input and returns that number squared. def squared(x): ''' function squares your input :param x: int. : return: squared x. ''' return x**2 print('Below result should be 4') print(squared(2)) # 2. Create a function that acepts a string as a parameter and prints it. def print_string(my_string): ''' prints the input string :param my_string: str : print: prints the string ''' print(my_string) print('below result should read, well hello there bro!') print_string('well hello there bro!') #3. Write a function that takes three required parameters and two optional paramters def diff_inputs(a,b,c,d=4,e=5): ''' returns the sum of all inputs :param a: int. :param b: int :param c: int. :param d: optional int. :param e: optional int. ''' return a+b+c+d+e print('below should return 5') print(diff_inputs(1,1,1,1,1)) # 4. Write a program with two functions. # The first function should take an integer as a parameterand return the result of the integer divided by 2. # The second function should take an integer as a parameter and return the result of the integer multipled by 4. # Call the first function save the result as a variable, # and pass it as a parameter to the second function def div_func(x): ''' returns x/2 :param x: int. return: x divided by 2 ''' return x/2 def mult_func(y): ''' returns y * 4 :param y: int. :return: float result of y times 4 ''' return y * 4 print('below result should return 20') div_result = div_func(10) mult_result = mult_func(div_result) print(mult_result) # 5. Write a function that converts a string to a float and returns a result. # Use exception handling to catch the exception that could occur. def float_conv(x): ''' converts x to float :param x: string form of float. :return: string converted to float ''' try: return float(x) except ValueError: print('you gotta give me something convertible, fool!') print('below result should return 18.6') print(float_conv('18.6')) # 6. Add a docstring to all of the functions you wrote in challenges 1-5.
while True: print("Main circle") if input("input:") == "1": flag = 1 while flag == 1: print("Second circle") if input("Input:") == "1": continue else: print("End of Second circle") flag = 0 print("Continue of Main circle") # break
bill = float(raw_input("Total bill amount? ")) # may be better to start off with bill_input to indicate this is input #next line, you would then create bill to convert to float() level_of_service = raw_input("Level of service? ") if level_of_service.lower() == "good": tip = bill * 0.20 elif level_of_service.lower() == "fair": tip = bill * 0.15 elif level_of_service.lower() == "bad": tip = bill * 0.10 total = bill + tip print "Tip amount: $%.2f" % tip print "Total amount: $%.2f" % total #instructor's coding #bill_input = raw_input("Total bill amount? ") #bill = float(bill_input) #service = raw_input("Level of service? ") #tip_percent = 0 #if service == "good": # tip_percent = 0.2 #elif service == "fair": # tip_percent = 0.15 #elif service = "bad": # tip_percent = 0.10 #tip_amount = bill * tip_percent #print tip_amount #total = bill + tip_amount #print total
width = int(raw_input("Width? ")) height = int(raw_input("Height? ")) counter = 0 while counter <= height: if counter == 0 or counter == height: print "*" * width counter += 1 else: print "*" + (" " * (width - 2)) + "*" counter += 1
bill = float(raw_input("Total bill amount? ")) level_of_service = raw_input("Level of service? ") split = float(raw_input("Split how many ways? ")) if level_of_service.lower() == "good": tip = bill * 0.20 elif level_of_service.lower() == "fair": tip = bill * 0.15 elif level_of_service.lower() == "bad": tip = bill * 0.10 total = bill + tip amount_per_person = total / split print "Tip amount: $%.2f" % tip print "Total amount: $%.2f" % total print "Amount per person: $%.2f" % amount_per_person
today_seats = [ 'Xavier', 'Clinton', 'Andrew', 'Jimmy' ] yesterday_seats = [ 'Xavier', 'Andrew', 'Clinton' 'Jimmy' ] #repeat a check: #is the person in this seat different from yesterday? current_row = 0 while current_row < len(today_seats): if today_seats[current_row] == yesterday_seats[current_row]: print "Move to another seat, %s" % today_seats[current_row] current_row = current_row + 1 #generate lists range() for i in range(len(today_seats)): if today_seats[i] == yesterday_seats[i]: print "Move!"
# coding: utf8 from __future__ import unicode_literals import os import random import sys import time import pickle import math import io # EzLearner 0.2 #TODO: # 1) Main menu - Modes: Version / Thème # 2) gestion des parenthèses / des slashs ''' n = number of words Every word start with weight 16. Iitial capacity = 16 x number of words. Upon failing on a word, its weight is doubled, up to 256. Update capacity by the difference. Upon succeeding on a word, its weight is halved, up to 1. Update capacity by the difference. Randomly choose a number r between 0 and capacity - 1. Use dichotomy search to get the word in the weighted dictionary. The weighted dictionary is represented as a binary tree, where at each node in the tree is stored the sum of the weights of the nodes that are under it. (ABR) The leaves in the tree are the actual words. At each level in the tree, the sum of weights equal to the total capacity. An update on the weight of the word is performed by changing the weight of the leaf, and by propagating to his fathers the update. Finding the word corresponding to the random number r is performed in O(log(n)). Updating a weight of word is performed in O(log(n)). Building the binary tree is performed recursively in O(nlog(n)). ? ''' from tkinter import * class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.pack(fill=BOTH, expand=1) self.label = Label(self, text="", font=('Arial', 20)) self.label.place(x=200,y=120) self.update("EzLearner") def update(self, st): self.label.configure(text=st) root = Tk() app = Window(root) root.wm_title("EzLearner") root.geometry("600x300") root.update() class TreeDict(): # ToDo: Update, parenthesis handling def __init__(self, list_of_lines, delimiter, meaning_delimiter, father=None, depth=0): n = len(list_of_lines) self.length = n self.father = father self.left = [] self.right = [] self.translations = [] self.depth = depth if n > 1: self.native_word = "" self.weight = 16*len(list_of_lines) self.left.append(TreeDict(list_of_lines[:n//2], delimiter, meaning_delimiter, father=[self], depth=self.depth + 1)) self.right.append(TreeDict(list_of_lines[n//2:], delimiter, meaning_delimiter, father=[self], depth=self.depth + 1)) return elif n == 1: self.weight = 16 line = list_of_lines[-1].split(delimiter) self.native_word = line[0] self.translations = line[-1].split(meaning_delimiter) return else: self.native_word = "" self.weight = 0 return def update(success=True): if success: if self.weight > 1: pass return else: if self.weight < 256: pass return def get_tree(self, r): if self.length <= 1: return self else: if r <= self.left[0].weight: return self.left[0].get_tree(r) else: return self.right[0].get_tree(r - self.left[0].weight) def __len__(self): return self.length def copy(self): # DFS pass def print(self): if self.length <= 1: #print(self.native_word + " -> " + self.translations[0]) #print(self.native_word) app.update(self.native_word) root.update() else: self.left[0].print() self.right[0].print() return def clean_words(word_path="./words/jap_raw", output_path="./words/clean_jap"): # Check for spaces with arrow & comas # Clean unicode emojis pass def setup(words_path="./words/jap_raw", config_path="./config_jap.cfg", dict_save_path="./weighted_dict.pckl"): translate_delimiter = ' → ' # Please include spaces if necessary meaning_delimiter = ', ' # Please include spaces if necessary with open(words_path, mode='r', encoding='utf-8') as word_file: lines = word_file.readlines() n = len(lines) tree_height = math.floor(math.log2(n)) + 1 dictionary = TreeDict(lines, translate_delimiter, meaning_delimiter) with open(dict_save_path, 'wb') as save_file: pickle.dump(dictionary, save_file) def load(dict_save_path="./weighted_dict.pckl"): with open(dict_save_path, 'rb') as save_file: dictionary = pickle.load(save_file) #dictionary.print() return dictionary ## MENU def menu(): print(" ______ ______ __ ______ ______ ______ __ __ ______ ______ ") print('/\ ___\ /\___ \ /\ \ /\ ___\ /\ __ \ /\ == \ /\ "-.\ \ /\ ___\ /\ == \ ') print("\ \ __\ \/_/ /__ \ \ \____ \ \ __\ \ \ __ \ \ \ __< \ \ \-. \ \ \ __\ \ \ __< ") print(' \ \_____\ /\_____\ \ \_____\ \ \_____\ \ \_\ \_\ \ \_\ \_\ \ \_\\\ \_\ \ \_____\ \ \_\ \_\ ') print(" \/_____/ \/_____/ \/_____/ \/_____/ \/_/\/_/ \/_/ /_/ \/_/ \/_/ \/_____/ \/_/ /_/ ") print(" ") print("1. Play with existing config") print("2. Reset - New config") print(" ") tmp = input() if tmp == '1': dico = load() play(dico) save(dico) elif tmp == '2': setup() print("Setup successful.") load() exit() else: print("Invalid menu choice. Exiting program.") exit() def save(dic): # Saves config file try: new_config = open(config_path, 'w', encoding='utf8') for key in dic.keys(): new_config.write(key + ":" + str(dico[key][1]) + "\n") except Exception as e: print(e) finally: new_config.close() def check(answer, translations): pass def pronuncication_parser(native_word): # Return word without pronunciation if "(" in native_word: i = native_word.index("(") return native_word[:i] else: return native_word ## MAIN def play(dic): # Fontion comprenant la boucle principale de jeu done = False while not done: weight = dic.weight r = random.randint(weight) tree = dic.get_tree(r) # TODO: Get Word inFo in by coding method in BTS class word = tree.natie_word translations = tree.translations app.update(word) root.update() answer = input() success = None # ToDo tree.update(success=success) menu()
# combat functions import utilities import random import time health_points = 0 rounds = 0 accuracy = 0.00 enemy = { "name": "Octavio", "hp": 100, "rounds": 1, "accuracy": 1.00 } def combat(rounds1, health_points1, player_steps): global rounds rounds = 6 global health_points health_points = health_points1 if player_steps > 50: enemy["accuracy"] -= 0.50 else: enemy["accuracy"] -= player_steps / 100 enemy["rounds"] += int(player_steps / 10) if enemy["rounds"] > 6: enemy["rounds"] = 6 output = "" while health_points > 0 and enemy["hp"] > 0 and rounds > 0 and enemy["rounds"] > 0: utilities.clear_console() print(" _____ ____ _ _ _ ") print(" | __ \ | _ \ | | | | | | ") print(" | | | | __ _ _ __ ___ ___ | |_) | __ _| |_| |_| | ___ ") print(" | | | |/ _` | '_ \\ / __/ _ \\ | _ < / _` | __| __| |/ _ \\") print(" | |__| | (_| | | | | (_| __/ | |_) | (_| | |_| |_| | __/") print(" |_____/ \__,_|_| |_|\___\___| |____/ \__,_|\__|\__|_|\___|\n") print("{}: 'So, you found me detective. Well now there's no escape... for you!'".format(enemy["name"])) print("He starts to dance.") print("You: 'You son of a bitch!'") print("You start to dance.") print("\nPress ENTER to dance at {}.\n".format(enemy["name"])) print("You:\t HP={}\tDances={}/6".format(health_points, rounds)) print("{}: HP={}\tDances={}/6\n".format(enemy["name"], enemy["hp"], enemy["rounds"])) if output != "": print(output) input() output = quick_time() utilities.clear_console() print(" _____ ____ ") print(" / ____| / __ \ ") print(" | | __ __ _ _ __ ___ ___ | | | |_ _____ _ __ ") print(" | | |_ |/ _` | '_ ` _ \ / _ \ | | | \ \ / / _ \ '__|") print(" | |__| | (_| | | | | | | __/ | |__| |\ V / __/ | ") print(" \_____|\__,_|_| |_| |_|\___| \____/ \_/ \___|_| \n") print("{}: 'So, you found me detective. Well now there's no escape... for you!'".format(enemy["name"])) print("He starts to dance.") print("You: 'You son of a bitch!'") print("You start to dance.") print("\nPress ENTER to dance at {}.\n".format(enemy["name"])) print("You:\t HP={}\tDances={}/6".format(health_points, rounds)) print("{}: HP={}\tDances={}/6\n".format(enemy["name"], enemy["hp"], enemy["rounds"])) print(output) if health_points <= 0 and enemy["hp"] <= 0: return """ You have tied with each other. After the dance, you hug it out. Octavio Ricca invites you to a pub for a drink. You accept and follow him to the Green Tavern. While you are at the pub you learn from Octavio Ricca that Papa Kirill was a very bad man who would deal drugs all around Illinois. His murder was not an act of revenge or hatred but a way of protecting thousands of people. Indeed, not only did Papa Kirill deal the drugs but he also made them in his underground lab; therefore when customers weren't satisfied with the product Papa Kirill was afraid that they would talk badly about his merchandise and his solution was murder. He would change the drug to become lethal on injection. This information was very hard to digest and you ask the waitress for a bottle of vodka. You spend the rest of the night talking about your exploits around the world. A few months later you announce publicly that you are retiring from being an international detective. The media goes crazy and you get a lot of attention for many weeks. You are now running your uncle's restaurant with Octavio Ricca as your right-hand man. You are now lovers and are going to get engaged secretly. Congratulations! You have finished the game.""" elif health_points <= 0: return """You were out-danced by Octavio Ricca. After the dance, you hug it out. Octavio Ricca invites you to a pub for a drink. You accept and follow him to the Green Tavern. While you are at the pub you learn from Octavio Ricca that Papa Kirill was a very bad man who would deal drugs all around Illinois. His murder was not an act of revenge or hatred but a way of protecting thousands of people. Indeed, not only did Papa Kirill deal the drugs but he also made them in his underground lab; therefore when customers weren't satisfied with the product Papa Kirill was afraid that they would talk badly about his merchandise and his solution was murder. He would change the drug to become lethal on injection. This information was very hard to digest and you ask the waitress for a bottle of vodka. You spend the rest of the night talking about your exploits around the world. A few months later you announce publicly that you are retiring from being an international detective. The media goes crazy and you get a lot of attention for many weeks. You are now running your uncle's restaurant with Octavio Ricca as your right-hand man. You are now lovers and are going to get engaged secretly. Congratulations! You have finished the game.""" elif enemy["hp"] <= 0: return """You have out-danced Octavio Ricca. After the dance, you hug it out. Octavio Ricca invites you to a pub for a drink. You accept and follow him to the Green Tavern. While you are at the pub you learn from Octavio Ricca that Papa Kirill was a very bad man who would deal drugs all around Illinois. His murder was not an act of revenge or hatred but a way of protecting thousands of people. Indeed, not only did Papa Kirill deal the drugs but he also made them in his underground lab; therefore when customers weren't satisfied with the product Papa Kirill was afraid that they would talk badly about his merchandise and his solution was murder. He would change the drug to become lethal on injection. This information was very hard to digest and you ask the waitress for a bottle of vodka. You spend the rest of the night talking about your exploits around the world. A few months later you announce publicly that you are retiring from being an international detective. The media goes crazy and you get a lot of attention for many weeks. You are now running your uncle's restaurant with Octavio Ricca as your right-hand man. You are now lovers and are going to get engaged secretly. Congratulations! You have finished the game.""" elif rounds == 0 and enemy["rounds"] > 0: return """You ran out of mojo. Octavio Ricca notices this and approaches, before performing a killer dance move. After the dance, you hug it out. Octavio Ricca invites you to a pub for a drink. You accept and follow him to the Green Tavern. While you are at the pub you learn from Octavio Ricca that Papa Kirill was a very bad man who would deal drugs all around Illinois. His murder was not an act of revenge or hatred but a way of protecting thousands of people. Indeed, not only did Papa Kirill deal the drugs but he also made them in his underground lab; therefore when customers weren't satisfied with the product Papa Kirill was afraid that they would talk badly about his merchandise and his solution was murder. He would change the drug to become lethal on injection. This information was very hard to digest and you ask the waitress for a bottle of vodka. You spend the rest of the night talking about your exploits around the world. A few months later you announce publicly that you are retiring from being an international detective. The media goes crazy and you get a lot of attention for many weeks. You are now running your uncle's restaurant with Octavio Ricca as your right-hand man. You are now lovers and are going to get engaged secretly. Congratulations! You have finished the game.""" else: # enemy["rounds"] == 0: return """Octavio Ricca runs out of dancing points. After the dance, you hug it out. Octavio Ricca invites you to a pub for a drink. You accept and follow him to the Green Tavern. While you are at the pub you learn from Octavio Ricca that Papa Kirill was a very bad man who would deal drugs all around Illinois. His murder was not an act of revenge or hatred but a way of protecting thousands of people. Indeed, not only did Papa Kirill deal the drugs but he also made them in his underground lab; therefore when customers weren't satisfied with the product Papa Kirill was afraid that they would talk badly about his merchandise and his solution was murder. He would change the drug to become lethal on injection. This information was very hard to digest and you ask the waitress for a bottle of vodka. You spend the rest of the night talking about your exploits around the world. A few months later you announce publicly that you are retiring from being an international detective. The media goes crazy and you get a lot of attention for many weeks. You are now running your uncle's restaurant with Octavio Ricca as your right-hand man. You are now lovers and are going to get engaged secretly. Congratulations! You have finished the game.""".format(enemy["name"]) def calc_damage(accuracy): global health_points global rounds # Quick time event to shoot bad guy! to_return = "" damage = random.randrange(20, 60) hit = random.random() rounds -= 1 if hit > accuracy: enemy["hp"] -= damage to_return += "You scored {}!\n".format(damage) else: to_return += "You fell!\n" damage = random.randrange(20, 60) hit = random.random() enemy["rounds"] -= 1 if hit > 0.5: health_points -= damage to_return += "{} scored {}!\n".format(enemy["name"], damage) else: to_return += "{} fell!\n".format(enemy["name"]) if health_points < 0: health_points = 0 if enemy["hp"] < 0: enemy["hp"] = 0 return to_return def quick_time(): # Function to fire at the enemy for i in range(5, 0, -1): utilities.clear_console() print(" _____ ____ _ _ _ ") print(" | __ \ | _ \ | | | | | | ") print(" | | | | __ _ _ __ ___ ___ | |_) | __ _| |_| |_| | ___ ") print(" | | | |/ _` | '_ \\ / __/ _ \\ | _ < / _` | __| __| |/ _ \\") print(" | |__| | (_| | | | | (_| __/ | |_) | (_| | |_| |_| | __/") print(" |_____/ \__,_|_| |_|\___\___| |____/ \__,_|\__|\__|_|\___|\n") print("{}: 'So, you found me detective. Well now there's no escape... for you!'".format(enemy["name"])) print("He starts to dance.") print("You: 'You son of a bitch!'") print("You start to dance.") print("\nPress ENTER to dance at {}.\n".format(enemy["name"])) print("You:\t HP={}\tDances={}/6".format(health_points, rounds)) print("{}: HP={}\tDances={}/6\n".format(enemy["name"], enemy["hp"], enemy["rounds"])) print(i) time.sleep(1) utilities.clear_console() print(" _____ ____ _ _ _ ") print(" | __ \ | _ \ | | | | | | ") print(" | | | | __ _ _ __ ___ ___ | |_) | __ _| |_| |_| | ___ ") print(" | | | |/ _` | '_ \\ / __/ _ \\ | _ < / _` | __| __| |/ _ \\") print(" | |__| | (_| | | | | (_| __/ | |_) | (_| | |_| |_| | __/") print(" |_____/ \__,_|_| |_|\___\___| |____/ \__,_|\__|\__|_|\___|\n") print("{}: 'So, you found me detective. Well now there's no escape... for you!'".format(enemy["name"])) print("He starts to dance.") print("You: 'You son of a bitch!'") print("You start to dance.") print("\nPress ENTER to dance at {}.\n".format(enemy["name"])) print("You:\t HP={}\tDances={}/6".format(health_points, rounds)) print("{}: HP={}\tDances={}/6\n".format(enemy["name"], enemy["hp"], enemy["rounds"])) print("PRESS ENTER") start = time.time() input() end = time.time() difference = end - start if difference > 1: accuracy = 1 else: accuracy = difference return calc_damage(accuracy) return
from flask import Flask, request import json import re app = Flask(__name__) @app.route("/words/avg_len", methods=['POST']) def average_word_length(): words = extract_words_from_input_text(request.get_json()) # get the total length of all the words within the text sum_of_lengths = sum([len(word) for word in words]) # find the average by dividing the total sum by the number of words in text avg_length = float(sum_of_lengths) / float(len(words)) average_word_length = {'average_word_length': avg_length} return json_response(average_word_length) @app.route("/words/most_com", methods=['POST']) def most_common_word(): words = extract_words_from_input_text(request.get_json()) freq = {} # create a hashmap with keys as words and values as word frequency for word in words: if word in freq: freq[word] += 1 else: freq[word] = 1 # grab the values(counts of each word) from the freq hashmap counts_of_each_word = freq.values() # iterate over the hashmap's key/value pairs and grab the word with the highest count most_common_word = [word for word, count in freq.items() if count == max(counts_of_each_word)] # in the case of a tie, sort the array of common words alphabetically and convert to hashmap most_common_word = dict(most_common_word=sorted(most_common_word)[0]) return json_response(most_common_word) @app.route("/words/median", methods=['POST']) def median_word(): words = extract_words_from_input_text(request.get_json()) freq = {} for word in words: if word not in freq: freq[word] = 1 else: freq[word] += 1 # grab the values(counts of each word) from the freq hashmap counts_of_each_word = sorted(freq.values()) mid = len(counts_of_each_word) // 2 # if even number of frequency distributions, grab the middle item and it's preceding item if len(counts_of_each_word) % 2 == 0: median_count = [counts_of_each_word[mid], counts_of_each_word[mid - 1]] else: median_count = [counts_of_each_word[mid]] # iterate over the hashmap's key/value pairs and grab the word(s) within the median distribution median = [word for word, ct in freq.items() if ct in median_count] # convert median array to hashmap median = dict(median=median) return json_response(median) @app.route("/sentences/avg_len", methods=['POST']) def average_sentence_length(): sentences = extract_sentences_from_input_text(request.get_json()) # get the total length of all the sentences within the text sum_of_lengths = sum([len(sentence) for sentence in sentences]) # find the average by dividing the total sum by the number of sentences in text avg_length = float(sum_of_lengths) / float(len(sentences)) average_sentence_length = {'average_sentence_length': avg_length} return json_response(average_sentence_length) @app.route("/phones", methods=['POST']) def find_all_phone_numbers(): phone_numbers = extract_phone_numbers_from_input_text(request.get_json()) return json_response(phone_numbers) def extract_words_from_input_text(input): text = input['text'] text = text.lower() """ 1) use regular expression to find all occurrences of words (pieces of input string with > 1 alphabet char AND containing only alphabet chars) 2) split into array containing just words 3) concatenate array into single string with spaces separating each word """ words = " ".join(re.findall("[a-zA-Z]+", text)) words = words.split() return words def extract_sentences_from_input_text(input): text = input['text'] text = text.lower() """ 1) sentences are defined as a grouping of alphanumeric chars separated by '.', '?', or '!' 1) use regular expression to split text on '.', '?', and '!' -- these act as delimiters between sentences """ sentences = re.split(r"[\.|\?|\!]+", text) return sentences def extract_phone_numbers_from_input_text(input): text = input['text'] """ 1) phone numbers are defined as a group of 10 digits separated by dashes 2) dashes separate the phone number into a 3-3-4 combination -- 1st three numbers separated by a dash followed by another 3 numbers separated by a dash and lastly the last 4 numbers 3) use regex to find a grouping of numbers in the above 3-3-4 combination """ phone_numbers = re.findall(r'\d{3}-\d{3}-\d{4}', text) return phone_numbers def json_response(data): response = app.response_class( response=json.dumps(data) + '\n', status=200, mimetype='application/json' ) return response if __name__=='__main__': app.run(host='0.0.0.0')
def convert(number): remainders = [] current_number = number to_binary = [] while True: quotient = current_number / 2 remainder = current_number % 2 current_number = quotient remainders.append(remainder) if quotient == 1 or quotient == 0: break if quotient != 0: to_binary.append(quotient) to_binary += remainders[::-1] print(''.join(str(element) for element in to_binary)) convert(8) # convert(1)
# Given: Existing array should maintain the property of the max heap def max_heapify(array, index, length): # # maintain the property of max heap # Step 1: Consider the element at `index` is largest largest = index # Step 2: Compute left child left = 2*index + 1 # Step 3: Compute right child right = 2*index + 2 # print('Left: {}; Right: {}; Largest: {}; Array: {}'.format(left, right, largest, array)) # Step 4: Exit if either left or right exceeds the length of the array if(left > length or right > length): return # Step 5: Set the largest as left child index if the left child is greater than the one at `index` if(left < length and array[left] > array[largest]): largest = left # Step 6: Set the largest as right child index if the right child is greater than the one at `index`. if(right < length and array[right] > array[largest]): largest = right # Step 7: Swap the element at `index` with the element at `largest` only if largest is not the current node # Perform the iteration recursively if(largest != index and largest < length): array[largest], array[index] = array[index], array[largest] max_heapify(array, largest, length) delete.count += 1 # def delete(array): print('Input:', array) # pick the last element last_element = array[len(array) - 1] # move the last element at the root array[0] = last_element array.pop() delete.count = 0 # balance the max heap max_heapify(array, 0, len(array)) print('Output:', array) print('No. of iterations:', delete.count) # array = [2,8,7,4,3,1]; # max_heapify(array, 0, len(array)) # array = [8,7,4,3,1]; # delete(array) # when the root node be deleted i.e. O(logN) =~ 3 array = [100, 80, 70, 60, 40, 50, 30, 20, 10, 0]; delete(array)
#-*- coding: UTF-8 -*- import random fahr, wind = eval(input("enter three of sides for triangle(ex. Farhrenhiat, wind speed):")) if -58<= fahr <= 41 and wind >=2: effectiveFahr = 35.74 + 0.6215*fahr - 35.75*(wind**0.16) + 0.4275*fahr*wind**0.16 print("Effective Temperature: ", format(effectiveFahr,".5f")) else: # unit == 1 CNY print("It is impossible to calculate the effective fahrenheit")
#-*- coding: UTF-8 -*- import random year, month = eval(input("Enter the year and month...(ex, 2000, 2): ")) if month == 1: print("Last Date: ", year,"-",month,"-31") elif month == 2: if year % 4 ==0 and year % 100 !=0 or year % 400==0: print("Last Date: ", year,"-",month,"-29") else: print("Last Date: ", year,"-",month,"-28") elif month == 3: print("Last Date: ", year,"-",month,"-31") elif month == 4: print("Last Date: ", year,"-",month,"-30") elif month == 5: print("Last Date: ", year,"-",month,"-31") elif month == 6: print("Last Date: ", year,"-",month,"-30") elif month == 7: print("Last Date: ", year,"-",month,"-31") elif month == 8: print("Last Date: ", year,"-",month,"-31") elif month == 9: print("Last Date: ", year,"-",month,"-30") elif month == 10: print("Last Date: ", year,"-",month,"-31") elif month == 11: print("Last Date: ", year,"-",month,"-30") else: print("Last Date: ", year,"-",month,"-31")
#-*- coding: UTF-8 -*- import sys status = eval(input("0 - single filer\n" + \ "1 - married filing joinly\n" + \ "2 - married filing seperatly\n" + \ "4 - head of househod\n" + " which filer do you select? ")) income = eval(input("enter your taxable inocme ? ")) tax = 0 if status == 0: if income <= 8350: tax = income * 0.10 elif income <= 33950: tax = 8835 * 0.10 + (income-8350) * 0.15 elif income <= 82250: tax = 8835 * 0.10 + (33950 * 0.15) + (income -33950) * 0.15 elif income <= 171550: tax = 8835 * 0.10 + (33950 - 8530) * 0.15 + (88250 - 33950) * 0.25 + (income - 88250) * 0.28 elif income <= 372950: tax = 8835 * 0.10 + (33950 - 8530) * 0.15 + (88250 - 33950) * 0.25 + (171550 - 88250) * 0.28 + \ (income - 171550) * 0.33 else: tax = 8835 * 0.10 + (33950 - 8530) * 0.15 + (88250 - 33950) * 0.25 + (171550 - 88250) * 0.28 + \ (372950 - 171550) * 0.33 + (income - 372950) elif status == 1: printf("------") elif status == 2: printf("------") elif status == 3: printf("------") else: printf("------") sys.exit() print("tax: ", format(tax, ".2f"))
#-*- coding: UTF-8 -*- stuNo = eval(input("enter the number of students: ")) max1 = 0 max2 = 0 for i in range(0, stuNo): score = eval(input("enter the score of a student: ")) if max1 < score: temp = max1 max1 = score if max2 < temp: max2 = temp print(max1, max2) print(i) print("max1: ", max1, "max2: ", max2)
#-*- coding: UTF-8 -*- import math radius = 3 print("area is", radius*radius*math.pi, end='and ') print("circle length is ", 2*radius*math.pi,".")
#-*- coding: UTF-8 -*- import random number1 = random.randint(0,100) number2 = random.randint(0,100) hab1 = number1 + number2 hab2 = eval(input("enter two integer number for an answer: ")) if hab1 == hab2: print("Successful. number1: ",number1, "number2: ", number2, "hab: ", hab1) else: print("Try...again num1, num2, hab1: ", number1, number2, hab1)
#-*- coding: UTF-8 -*- import random number = random.randint(0,100) print("Why don't you enter a magic number between 0 and 100:") guess = -1 while guess != number: guess = eval(input("Enter a magic number:")) if guess == number: print("successful", number) elif guess > number: print("less than the guess") else: print("more than the guess")
#-*- coding: UTF-8 -*- import random a,b,c,d,e,f = eval(input("enter coefficients for the 2x2 equation(ex:a,b,c,d,e,f):")) if (a*d-b*c) == 0: print("no soultion") else: x = (e*d - b*f)/(a*d - b*c) y = (a*f - e*c)/(a*d - b*c) print("x = ", x, "y = ", y)
#-*- coding: UTF-8 -*- # enter integer variable from a user seconds = eval(input("input the nubmer [seconds]: ")) # get the values of the minutes and seconds minutes = seconds // 60 remainingSeconds = seconds % 60 # show the result print("About input sconds, ", seconds,"[sec], ==> minutes,", minutes, \ "[minutes],", remainingSeconds,"[seconds]")
#-*- coding: UTF-8 -*- import math print("degree sin cos") for deg in range(0, 360, 10): rad = math.degrees(deg) print(format(deg, "<4d"), \ format(math.sin(rad),"10.4f"), \ format(math.cos(rad),"10.4f"))
#-*- coding: UTF-8 -*- ''' def sum(s, t): result = 0 for i in range(s, t+1): result += i return result def main(): print("sum from 1 to 10:", sum(1,10)) print("sum from 20 to 37:", sum(20,37)) main() ''' def max(a, b): if a > b: result = a else: result = b return result def main(): i = 5 j = 2 k = max(i,j) print("max value: ", k) main()
#-*- coding: UTF-8 -*- import random number1 = random.randint(0,9) number2 = random.randint(0,9) number3 = random.randint(0,9) answer = eval(input(str(number1) + "+" + str(number2) + "+" + str(number3) + "= ")) print(number1, "+", number2, "+", number3, "=", answer)
#Imports import random from bs4 import BeautifulSoup import requests import datetime import calendar ## Instructions ## """ This is a chatbot that will intiate a conversation with the user. The bot will ask the user various questions, which can be seen in the questions array. """ ## End of Instructions ## ## Greeting/Introduction Phase ## # Make an array of jokes and choose a random one to tell the user def joke(): jokes = ["Why did the kid throw his clock out the window? Because he wanted to see time fly!", "Why are fish so smart? Because they live in schools!", "Where do polar bears keep their money? In a snow bank!", "Why did the pony get sent to his room? He wouldn’t stop horsing around!"] joke_choice = random.choice(jokes) print(joke_choice) # Define the function age which will tell the user which day they were born on def age(): age = input("Please input your birthday in the form of dd mm yyyy ") #from GeeksForGeeks (https://www.geeksforgeeks.org/python-program-to-find-day-of-the-week-for-a-given-date/) (This function will find which day the user was born on) def findDay(date): born = datetime.datetime.strptime(date, '%d %m %Y').weekday() return (calendar.day_name[born]) print(f"According to your birthdate, that means you were born on {findDay(age)}") # Define the function color which will tell a user a fun fact about their favorite color. If the color isn't in the list, the bot will simply say that color is their favorite too def color(): favorite_color = input(questions[2] + " ") colors = { "red": "Red makes things appear closer than they really are.", "orange": "Orange was a symbol of glory and fruits of the earth in early Christian church and was also known as the wisdom ray.", "yellow": "Yellow is the best color to create enthusiasm for life and can awaken greater confidence and optimism.", "green": "In China, green jade represents virtue and beauty", "blue": "Blue is the favored color choice for toothbrushes.", "purple": "Carrots used to be purple, now most are orange!", "black": "The color black represents strength, seriousness, power, and authority.", "white": "The color white is cleanliness personified, the ultimate in purity!! This is why it is traditionally worn by western brides, and the reason why doctors wear white jackets.", "pink": "The color pink is symbolizes joy and happiness." } for key in colors: if(key == favorite_color.lower()): print(colors[key]) else: print(f"{favorite_color} is my favorite color too!") def greeting(): greeting = input("How are you doing today? ") good_responses = ["well", "good", "fantastic", "ok"] bad_responses = ["bad", "not so well", "horrible", "sad", "unhappy"] for x in good_responses: if x == greeting.lower(): print("I'm glad to hear that!") for x in bad_responses: if x == greeting.lower(): print("I'm sorry to hear that. Hopefully, this bot can make your day better!") def hobbies(): hobbies = input("What is your favorite hobby? ") print(f"{hobbies} is very interesting!") def food(): food = input("What is your favorite food? ") print(f"{food} is a great food!") # Detects to see if the user would like to end the conversation stop_conversation = "0" # Choose a random question from this array to ask the user questions = ["Would you like to hear a joke?", "How old are you?", "What is your favorite color?", "How are you?", "What are your hobbies?", "What is your favorite food?"] # Chooses a random element from the array to ask the user bot_choice = random.choice(questions) print("Hello I am chatbot!") while(stop_conversation != "1"): if(bot_choice == questions[0]): joke() break if (bot_choice == questions[1]): age() break if (bot_choice == questions[2]): color() break if (bot_choice == questions[3]): greeting() break if (bot_choice == questions[4]): hobbies() break if (bot_choice == questions[5]): food() break
prev = int(input()) print("Start = " + str(prev)) i = 1 while(1): value = input() i += 1 if (value == "END"): print("SUCCESS, End = " + str(current)) exit() else: current = int(value) if (current != prev + 1): print("WRONG! LINE=" + str(i) + " Got " + str(current) + ", expected " + str(prev + 1) + ".") exit() prev += 1
#Exercício 04. ​ Crie uma função que recebe como parâmetro um número real ​ n #e retorna True caso o número seja par. #Criando a função e verificando se o numero e par def numero_real_par(numero): if numero % 2 == 0: return True else: return False #obs: para usar esta função no interpretador python , from q04 import numero_real_par
'''Exercício 09. ​ Crie um menu onde o usuário pode escolher quais das funções do exercício 08 será chamada. O programa deve imprimir o resultado e solicitar que o usuário escolha uma outra função. O menu deve possuir uma opção de saída do programa. Ex. menu = """ ======= MENU ======= 1) SOMA(A, B) 2) SUBTRACAO(A, B) 3) MULTIPLICACAO(A, B) 4) DIVISAO(A, B) 5) SAIR DO PROGRAMA ''' #Definindo as funções def soma(a,b): return a + b def subtracao(a,b): return a - b def multiplicacao(a,b): return a * b def divisao(a,b): return a / b #Criando a repetição e o menu do programa opcao = 0 while(opcao != 5): print("=======MENU=======") print("1) SOMA") print("2) SUBTRAÇÃO") print("3) MULTIPLICAÇÃO") print("4) DIVISÃO") print("5) SAIR DO PROGRAMA") opcao = int(input("Digite uma opção do menu: ")) #Recebe os numeros digitados pelo usuario para passar para função que o if vai chaamar if opcao == 5: break if opcao > 0 and opcao < 5: numero_a = float(input("Digite um numero: ")) numero_b = float(input("Digite outro numero: ")) if opcao == 1: resultado =soma(numero_a,numero_b) print("O resultado da operação escolhida e",resultado) elif opcao == 2: resultado = subtracao(numero_a,numero_b) print("O resultado da operação escolhida e",resultado) elif opcao == 3: resultado = multiplicacao(numero_a,numero_b) print("O resultado da operação escolhida e",resultado) elif opcao == 4: resultado = multiplicacao(numero_a,numero_b) print("O resultado da operação escolhida e",resultado) else: print("Opção digitada e invalida")
from sklearn import datasets import numpy as np # Read Data iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target # Split dataset into SEPARATE Training and Test Datasets from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) # Standardize the Features for Gradient Descent from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) # using the 'fit' method to estimate the parameters, sample mean and standard deviation, for EACH feature dimension X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) # Train a Perceptron Model from sklearn.linear_model import Perceptron ppn = Perceptron(n_iter=40, eta0=0.1, random_state=0) ppn.fit(X_train_std, y_train) y_pred = ppn.predict(X_test_std) print('Misclassified samples: %d' % (y_test != y_pred).sum()) # Calculate the Classification Accuracy from sklearn.metrics import accuracy_score print('Accuracy: %.2f' % accuracy_score(y_test, y_pred)) # Plot from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02): # setup marker generator and color map markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # plot the decision surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # plot all samples for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl) # highlist TEST samples if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c='y', alpha=1.0, marker='o', s=20, label='test set') X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((y_train, y_test)) # plot_decision_regions(X=X_combined_std, y=y_combined, classifier=ppn, test_idx=range(105, 150)) # # plt.xlabel('petal length [standardized]') # plt.ylabel('petal width [standardized]') # plt.legend(loc='upper left') # plt.title('Perceptron') # plt.show() # # # # Logistic Regression # from sklearn.linear_model import LogisticRegression # lr = LogisticRegression(C=1000.0, random_state=0) # # lr.fit(X_train_std, y_train) # # plot_decision_regions(X_combined_std, y_combined, classifier=lr, test_idx=range(105, 150)) # # plt.xlabel('petal length [standardized]') # plt.ylabel('petal width [standardized]') # plt.legend(loc='upper left') # plt.title('Logistic Regression') # plt.show() # # # print(lr) # # lr.predict_proba(X_test_std[0, :]) # # # Regularization Parameter Visualization # weights, params = [], [] # # for c in np.arange(-5, 5): # lr = LogisticRegression(C=10.0**c, random_state=0) # lr.fit(X_train_std, y_train) # weights.append(lr.coef_[1]) # params.append(10.0**c) # # weights = np.array(weights) # # plt.plot(params, weights[:, 0], label='petal length') # plt.plot(params, weights[:, 1], linestyle='--' ,label='petal width') # plt.ylabel('weights coefficient') # plt.xlabel('C') # # plt.legend(loc = 'upper left') # plt.xscale('log') # plt.show() # # SVM # from sklearn.svm import SVC # # svm = SVC(kernel='linear', C=1.0, random_state=0) # svm.fit(X_train_std, y_train) # # plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) # plt.xlabel('petal length [standardized]') # plt.ylabel('petal width [standardized]') # plt.legend(loc='upper left') # plt.title('SVM') # # plt.show() # SGDClassifier (Stochastic GD Classifier) ''' Also supports online learning via the partial_fit method. We could initialize the stochastic gradient descent version of the Percetron, LR and SVM with default parameters as follow http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier ''' # from sklearn.linear_model import SGDClassifier # ppn = SGDClassifier(loss='perceptron') # lr = SGDClassifier(loss='log') # svm = SGDClassifier(loss='hinge') # Solving Non-Linear Problems using a Kernel SVM ## Create a simple dataset that has the form of an XOR gate np.random.seed(0) X_xor = np.random.randn(200, 2) y_xor = np.logical_xor(X_xor[:, 0]>0, X_xor[:, 1]>0) y_xor = np.where(y_xor, 1, -1) # # plt.scatter(X_xor[y_xor==1, 0], X_xor[y_xor==1, 1], c='b', marker='x', label='1') # plt.scatter(X_xor[y_xor==-1, 0], X_xor[y_xor==-1, 1], c='r', marker='s', label='-1') # plt.ylim(-3.0) # plt.legend() # plt.show() # svm = SVC(kernel='rbf', random_state=0, gamma=0.1, C=10) # svm.fit(X_xor, y_xor) # plot_decision_regions(X_xor, y_xor, classifier=svm) # plt.legend(loc='upper left') # plt.show() # # svm = SVC(kernel='rbf', random_state=0, gamma=0.2, C=1.0) # svm.fit(X_train_std, y_train) # # plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) # plt.xlabel('petal length [standardized]') # plt.ylabel('petal width [standardized]') # plt.legend(loc='upper left') # plt.title('RBF Kernel SVM, Small Gamma, Soft Boundary') # plt.show() # # svm = SVC(kernel='rbf', random_state=0, gamma=100.0, C=1.0) # svm.fit(X_train_std, y_train) # # plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105, 150)) # plt.xlabel('petal length [standardized]') # plt.ylabel('petal width [standardized]') # plt.legend(loc='upper left') # plt.title('RBF Kernel SVM, Large Gamma, Much Tighter') # plt.show() # # Different Impurity Criteria Visualization # def gini(p): # return p*(1-p) + (1-p)*(1-(1-p)) # # def entropy(p): # return -p*np.log2(p) - (1-p)*np.log2(1-p) # # def error(p): # return 1-np.max([p, 1-p]) # # x = np.arange(0.0, 1.0, 0.01) # ent = [entropy(p) if p!= 0 else None for p in x] # sc_ent = [e*0.5 if e else None for e in ent] # err = [error(i) for i in x] # fig = plt.figure() # ax = plt.subplot(111) # for i, lab, ls, c in zip([ent, sc_ent, gini(x), err], # ['Entropy', 'Entropy(scaled)', 'Gini Impurity', 'Misclassification'], # ['-', '-', '--', '-.'], # ['black', 'lightgray', 'red', 'green', 'cyan']): # line = ax.plot(x, i, label=lab, linestyle=ls, lw=2, color=c) # # ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=3, fancybox=True, shadow=False) # ax.axhline(y=0.5, linewidth=1, color='k', linestyle='--') # ax.axhline(y=1.0, linewidth=1, color='k', linestyle='--') # # plt.ylim([0, 1.1]) # plt.xlabel('p(i=1') # plt.ylabel('Impurity Index') # plt.show() # Building a Decision Tree ''' Train a decision tree with a Maximum-Depth of 3 using Entropy as a criterion for impurity ''' from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0) tree.fit(X_train, y_train) X_combined = np.vstack((X_train, X_test)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X_combined, y_combined, classifier=tree, test_idx=range(105, 150)) plt.xlabel('petal length [cm]') plt.ylabel('petal width [cm]') plt.legend(loc='upper left') plt.show() # Decision tree can be exported as a .dot file after training, which we can visualize using the GraphViz program # from sklearn.tree import export_graphviz # # export_graphviz(tree, out_file='tree.dot', feature_names=['petal length', 'petal width']) # Combining weak to strong learners via Random Forests from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(criterion='entropy', n_estimators=10, random_state=1, n_jobs=2) forest.fit(X_train, y_train) plot_decision_regions(X_combined, y_combined, classifier=forest, test_idx=range(105, 150)) plt.xlabel('petal length') plt.ylabel('petal width') plt.legend(loc='upper left') plt.show() # KNN - Lazy Algorithm from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski') knn.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=knn, test_idx=range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.show()
import string def cesar(key, phrase): ''' функція декодуваня слів ''' str_arr = string.ascii_lowercase str_arr2 = string.ascii_lowercase[key:] + string.ascii_lowercase[:key] str_arr += string.ascii_uppercase str_arr2 += string.ascii_uppercase[key:] + string.ascii_uppercase[:key] cliper_dict= {} for k, v in zip(str_arr, str_arr2): cliper_dict[k] = v ss = "" for letter in phrase: if letter in cliper_dict: ss += cliper_dict[letter] else: ss += letter return ss with open('story.txt', 'r') as ff: # зчитуємо закодований текст text = ff.read() with open('words.txt', 'r') as eng_dict: # зчитуємо словник англійських слів words_eng = eng_dict.read() # опрацьовуємо текст text = text.strip() for symbol in string.punctuation: text = text.replace(symbol, "") words = text.split() print(text) print(words) # декодування слів діапазоном ключів і підрахунок цінності ключа dict_keys={} for key in range(1, 27): key_value = 0 for word in words: if cesar(key, word) in words_eng: key_value += 1 dict_keys[key] = int(key_value/len(words)*100)# + "%" # dict_keys[key] = key_value print(dict_keys) # робота оптимального ключа key_value_max = max(dict_keys.items(), key=lambda item: item[1]) print(key_value_max) decoded_text = "" for word in words: decoded_text += cesar(key_value_max[0], word) + " " print(f"ключ {key_value_max[0]}, цінність {key_value_max[1]}%") print(decoded_text)
name = (input('Введіть Ваше Прізвище Імя Побатькові: ')) print(name) nameI = name.title() nameI = nameI.split() print(nameI) for i in range(len(nameI)): n = nameI[i] print(n[0], end="")
""" @author: Shubham Shantaram Pawar """ import pandas as pd import numpy as np import matplotlib .pyplot as plt def computeCost(X, y, theta): m = len(y) h = np.matmul(X, theta) J = (1/(2 * m)) * np.sum(np.square(np.subtract(h,y))) return J def gradientDescent(X, y, theta, alpha, num_iters): m = len(y) J_history = np.zeros((num_iters,1)) for iter in range(0, num_iters): h = np.matmul(X, theta) theta = np.subtract(theta, ((alpha/m) * np.matmul(X.T, np.subtract(h, y)))) J_history[iter] = computeCost(X, y, theta) return (theta, J_history) def main(): df = pd.read_csv( filepath_or_buffer='linear_regression_test_data.csv', header=0, sep=',') df.dropna(how="all", inplace=True) df.tail() data = df.iloc[0:,1:].values x = data[:,0] y = data[:,1] y_theoretical = data[:,2] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title('Original Data') ax.scatter(x, y, color='blue') ax.set_aspect('equal', 'box') ax.set_xlabel('x') ax.set_ylabel('y') fig.set_size_inches(20, 12) fig.show() m = len(x) x = np.reshape(x, (m,1)) y = np.reshape(y, (m,1)) theta = np.zeros((2,1)) iterations = 500 alpha = 0.1 X = np.concatenate((np.ones((m,1)),x),axis=1) theta, J_history = gradientDescent(X, y, theta, alpha, iterations) print("theta 0:", theta[0][0]) print("theta 1:", theta[1][0]) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title('Regression Line') ax.scatter(x, y, color='blue', label = 'y vs x') ax.scatter(x, y_theoretical, color='red', label = 'y-theoretical vs x') plt.plot(x, theta[0][0] + x * theta[1][0], 'r-', label = 'Regression Line') ax.set_aspect('equal', 'box') ax.set_xlabel('x', fontsize = 13) ax.set_ylabel('y / y-theoretical', fontsize = 13) ax.legend() fig.set_size_inches(20, 15) fig.show() plt.savefig('Regression Line') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlabel(r'iteration') ax.set_ylabel(r'$J(\theta)$') ax.scatter(range(iterations), J_history, color='blue', s=10) fig.set_size_inches(8, 5) fig.show() if __name__ == '__main__': main()
numeros = (int(input('digite um numero: ')), int(input('digite outro numero: ')), int(input('digite mais um numero: ')), int(input('digite o ultimo numero: '))) print(f'os numeros digitados foram {numeros}') print(f'o numero 9 apareceu {numeros.count(9)} vez(es)') if 3 in numeros: print(f'o numero 3 aparece pela primeria vez na posição {numeros.index(3)+1}') else: print('o numero 3 nao esta em nenhuma posição') print(f'os numeros pares são', end=' ') for n in numeros: if n % 2 == 0: print(n, end=' ')