text
stringlengths
37
1.41M
dictionary={} dictionaryFile=open('birthday.txt','a') dictionaryFile.close() dictionaryFile=open('birthday.txt','r') for line in dictionaryFile: #if ',' in line: # dictionary[line[:line.index(',')]]=line[line.index(',')+1:].strip() data=line.strip().split(',') dictionary[data[0]]=data[1] dictionaryFile.close() choice=0 def lookup(): name=input('name: ').lower() print(dictionary.get(name,'Not found')) def addd(): name=input('name: ').lower() while name in list(dictionary.keys()): name=input('name already exists: ').lower() dictionary[name]=input('birthday YYYY/MM/DD: ') def change(): name=input('name: ').lower() while not(name in list(dictionary.keys())): name=input('name does not exist: ').lower() del dictionary[name] dictionary[name]=input('birthday YYYY/MM/DD: ') def delete(): name=input('name: ').lower() while not(name in list(dictionary.keys())): name=input('name does not exist: ').lower() del dictionary[name] def lisst(): print(dictionary) #for name in dictionary: # print(name, dictionary[name]) while choice!=5: choice=input('1.lookup \n2.add\n3.change\n4.delete\n5.quit\n6.list\nnumber: ') if choice.isdigit(): choice=int(float(choice)) if choice==1: lookup() elif choice==2: addd() elif choice==3: change() elif choice==4: delete() elif choice==6: lisst() print() dictionaryFile=open('birthday.txt','w') for name in dictionary: dictionaryFile.write(name+','+dictionary[name]+'\n') dictionaryFile.close()
from random import shuffle def max_min(lst): """ Função que me retorana min e max de uma lista calcular o valor max e min da lista Calculate the maximum and minimum of a list lst falar tb do tempo de execução se constante, linear... :param lst: list :return: tuple:(max, min) """ if len(lst) == 0: # lst (const) raise ValueError('Empty List') max_value = min_value = lst[0] # uso mais memoria constante, mas apenas uma vez for value in lst: # iterar pelos valores presentes em lst. apenas um for if value > max_value: max_value = value # atualiza valor para max if value < min_value: min_value = value # atualiza valor para min """ diferente de usar a lib min e max com essa formula estou usando uma complexidade maior para implementar mas um valor menor de memoria de execução. """ return max_value, min_value print(max_min([1])) # 1,1 print(max_min([1, 2])) # 1, 2 print(max_min(list(range(100)))) # 0, 99 random_list = list(range(100)) shuffle(random_list) print(max_min(random_list)) print(max_min([])) # error
class Pessoa(object): def __init__(self, nome, nascimento): self.nome = nome self.nascimento = nascimento def idade(self, hoje): hd, hm, ha = hoje nd, nm, na = self.nascimento x = ha - na return x if __name__ == "__main__": fante = Pessoa('John Fante', (8, 4, 1909)) print(fante.idade((6, 11, 2008))) print(fante['nome'])
def isLucky(n): n_string = str(n) n_list = [] is_zero = 0 for digit in n_string: n_list.append(int(digit)) half = len(n_list)/2 for item in range(0, len(n_list)): if item < half: is_zero += n_list[item] else: is_zero -= n_list[item] return not is_zero if __name__ == '__main__': print isLucky(1230)
def reverseParentheses(s): string_array = list(s) while "(" in string_array: inner_open = 0 inner_close = 0 for item in range(0, len(string_array)): if string_array[item] == "(": inner_open = item elif string_array[item] == ")": inner_close = item string_array[inner_open:inner_close + 1] = switchInner(string_array[inner_open:inner_close + 1]) string_array.pop(inner_close) string_array.pop(inner_open) break return ''.join([str(char) for char in string_array]) def switchInner(substring): return substring[::-1] if __name__ == '__main__': print reverseParentheses("(abcde)")
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): if yourLeft == friendsLeft: return yourRight == friendsRight elif yourRight == friendsLeft: return yourLeft == friendsRight else: return False if __name__ == '__main__': print areEquallyStrong(10, 15, 5, 20)
""" A string is said to be beautiful if b occurs in it no more times than a; c occurs in it no more times than b; etc. Given a string, check whether it is beautiful. Example For inputString = "bbbaacdafe", the output should be isBeautifulString(inputString) = true; For inputString = "aabbb", the output should be isBeautifulString(inputString) = false; For inputString = "bbc", the output should be isBeautifulString(inputString) = false. Input/Output [time limit] 4000ms (py) [input] string inputString A string of lowercase letters. Guaranteed constraints: 3 <= inputString.length <= 50. [output] boolean """ def isBeautifulString(input_string): last_count = 50 sort_string = sorted([x for x in input_string]) alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] last_letter = alphabet.index(sort_string[-1]) to_the_last = alphabet[:last_letter + 1] for char in to_the_last: current_count = input_string.count(char) if current_count <= last_count: last_count = current_count else: return False return True if __name__ == '__main__': print isBeautifulString("bbbaacdafe")
def palindromeRearranging(inputString): input_array = list(inputString) once = False checked_letters = [] for letter in input_array: if letter in checked_letters: continue if inputString.count(letter) % 2 == 1: if once: return False else: once = True checked_letters.append(letter) return True if __name__ == '__main__': print palindromeRearranging("zyyzzzzz")
""" You are taking part in an Escape Room challenge designed specifically for programmers. In your efforts to find a clue, you've found a binary code written on the wall behind a vase, and realized that it must be an encrypted message. After some thought, your first guess is that each consecutive 8 bits of the code stand for the character with the corresponding extended ASCII code. Assuming that your hunch is correct, decode the message. Example For code = "010010000110010101101100011011000110111100100001", the output should be messageFromBinaryCode(code) = "Hello!". The first 8 characters of the code are 01001000, which is 72 in the binary numeral system. 72 stands for H in the ASCII-table, so the first letter is H. Other letters can be obtained in the same manner. Input/Output [execution time limit] 4 seconds (py) [input] string code A string, the encrypted message consisting of characters '0' and '1'. Guaranteed constraints: 0 < code.length < 800. [output] string The decrypted message. """ def messageFromBinaryCode(code): decrypted = [] step = 8 for bit in range(0, len(code), 8): decrypted.append(chr(int(code[bit:step], 2))) step += 8 return str.join("", decrypted) if __name__ == '__main__': print messageFromBinaryCode("010010000110010101101100011011000110111100100001")
import string import re #def valid_username(username): # if username.isalpha(): # nameLength = len(username) # if nameLength > 3: # return #def valid_password(psw): # for char in psw: # if char.isalpha() and char.isdigit(): def valid_verifypsw(psw, vpsw): if psw == vpsw: return vpsw USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") def valid_username(username): return USER_RE.match(username) PSW_RE = re.compile(r"^.{3,20}$") def valid_password(psw): return PSW_RE.match(psw) EMAIL_RE = re.compile(r"^[\S]+@[\S]+.[\S]+$") def valid_email(email): return EMAIL_RE.match(email)
# -*- coding: utf-8 -*- """ CSV related help functions """ import csv import codecs from setup import eol, encoding delimiter = ';' def dict2csv(csv_path, a_dict): """Writes a dictionary to a csv file""" with codecs.open(csv_path, 'w', encoding) as csv_file: for (k, v) in a_dict.items(): csv_file.write(u'%s;%s%s' % (k, v, eol)) def csv2dict(csv_path, a_dict, encoding=encoding): """Read a dictionary from a csv file""" with open(csv_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=delimiter) for row in csv_reader: a_dict[row[0].decode(encoding)] = row[1].decode(encoding) return a_dict
name = "John" x = 1 if x == 0: print("Bye bye") else: print("Hello", name)
from __future__ import print_function #class GameTreeNode: # def __init__(self, state): # self.state = state # full game state # self.value = 0. # value of node class FullGameTree: def __init__(self): self.state_val = {} #def create_tree(self, game): # game.clean() # self.dfs(game) def dfs(self, game): """Depth first search. Values are calculated for first (black) player""" if len(self.state_val) % 1000 == 0: print('\r', len(self.state_val), end='') curr_state = game.get_state_hash() if self.state_val.has_key(curr_state): # already seen this state return self.state_val[curr_state] result = game.check_win() if result is True: # current player wins value = 1. # black wins if game.current_player() == 1: # white wins value = -value self.state_val[curr_state] = value #print(game.game_state) return value if result is None: # draw value = 0. self.state_val[curr_state] = value return value # game continues values = [] for move in game.get_valid_moves(): if not game.check_move(move): # invalid move (this should never happen) continue values.append(self.dfs(game)) game.delete_move() # return to previous state min_node = game.current_player() == 0 # we explored white moves => we are in min node of minimax tree value = 0. if min_node: value = min(values) else: value = max(values) self.state_val[curr_state] = value return value
""" Simulate ingest application. This script fetch "california housing data set", samples some rows from it and add the sampled rows in the data file (CSV). Since this is just a prototype, we do not implement any complicated logic (such as stacking data set without duplicate). """ """ We should have a code for each data source. Because - the frequency of retrieval depends on the data source. - the retrieval method also depends on the data source. """ import click from pathlib import Path from configparser import ConfigParser import pandas as pd from lib import DataFrameMetric config = ConfigParser() config.read("config.ini") csv_path = Path(config["loading_housing"]["raw_data"]) metric_path = Path(config["loading_housing"]["metric"]) target_name = config["general"]["target"] tz = config["general"]["tz"] def fetch_data(round:int) -> pd.DataFrame: """ Retrieve the data you need. :param round: round number :return: DataFrame """ """ You have to implement this function. This function can take an option (from the command line) and produces a DataFrame. (If you need a different kind of output, you also need to modify the main function. """ import numpy as np from sklearn.datasets import fetch_california_housing sampling_rate = 0.2*round np.random.seed(51) data = fetch_california_housing(download_if_missing=True) df = pd.DataFrame(data.data, columns=data.feature_names) df[target_name] = data.target ## sampling scores = np.random.uniform(low=0, high=1, size=df.shape[0]) selected = scores < sampling_rate return df.iloc[selected,:].copy() @click.command() @click.option("--round", default=1, type=int) def main(round:int): df = fetch_data(round) with DataFrameMetric(metric_path, name="housing", tz=tz) as metric: metric.add_data(housing=df) """ Store the retrieved data Depending on the data, you might want to modify the following lines. For example you can retrieve the (relatively) same data at any time, you might want to overwrite the file. If the data largely depends on when you retrieve the data, then you might want to have one file for each retrieval. (In this case you need to also be careful about the value of -o option. This should be no directory.) """ df.to_csv(str(csv_path), index_label=False) if __name__ == "__main__": main()
import random import unittest class Deck(object): class Card(object): def __init__(self, name, value, effect): self.name = name self.value = value self.effect = effect def __str__(self): return str(self.name) def __init__(self, file=None): self.deck = [] self.discard = [] if file: my_file = open(file) for line in my_file: data = line.split(":") self.push(data[0], data[1], data[2]) my_file.close() self.shuffle() def __contains__(self, item): for card in self.deck: if card.name == item: return True return False def push(self, name, value, effect): self.deck.append(self.Card(name, value, effect)) def shuffle(self, pile=None): shuffled = [] if not pile: pile = self.deck while pile: shuffled.append(pile.pop(random.randint(0, len(pile)-1))) self.deck = shuffled def draw(self): drawn = self.deck.pop(0) self.discard.append(drawn) if not self.deck: self.shuffle(self.discard) self.discard.clear() return drawn class DeckTest(unittest.TestCase): def test_build(self): test_deck = Deck("test_deck.txt") self.assertTrue("card one" in test_deck) self.assertFalse("" in test_deck) def test_shuffle(self): test_deck = Deck("test_deck.txt") test_deck.shuffle() self.assertTrue("card three" in test_deck) def test_draw(self): test_deck = Deck("test_deck.txt") self.assertEqual(str(test_deck.draw()), "card one")
import re # This function takes in a line of text and returns # a list of words in the line. def split_line(line): return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line) dictionary_list = [x for line in open('search_files/dictionary.txt') for x in split_line(line)] file = open('search_files/AliceInWonderLand200.txt') alice_array = [] line_list = [] l = 1 for line in file: for word in split_line(line): alice_array.append(word.upper()) line_list.append(l) l += 1 print(len(line_list), len(alice_array)) print('--- Linear Search ---') def linear_search(key, arr): i = 0 while i < len(arr) and arr[i] != key: i += 1 if i < len(arr): pass else: print('Line', line_list[alice_array.index(key)], 'possible misspelled word:', key) for word in alice_array: linear_search(word, dictionary_list) print('--- Binary Search ---') def binary_search(key, arr): lower_bound = 0 upper_bound = len(arr) - 1 found = False middle_pos = 0 while not found and lower_bound <= upper_bound: middle_pos = (upper_bound + lower_bound) // 2 if arr[middle_pos] < key: lower_bound = middle_pos + 1 elif arr[middle_pos] > key: upper_bound = middle_pos - 1 else: found = True if found: pass else: print('Line', line_list[alice_array.index(key)], 'possible misspelled word:', key) for word in alice_array: binary_search(word, dictionary_list)
import random # LOOPS (16pts TOTAL) # PROBLEM 1 (Fibonacci - 4pts) # The Fibonacci sequence is a sequence of numbers that starts with 1, followed by 1 again. # Every next number is the sum of the two previous numbers. # I.e., the sequence starts with 1, 1, 2, 3, 5, 8, 13, 21,... # Write a program that calculates and prints the Fibonacci sequence # until the numbers get higher than 1000. # n = 1 previous_number = -1 current_number = 0 for i in range(1, 1001): n = current_number current_number += previous_number previous_number = n # also check out this neat formula that works too! fib = (((1 + 5 ** (1 / 2)) / 2) ** i - ((1 - 5 ** (1 / 2)) / 2) ** i) / 5 ** (1 / 2) # print(round(fib)) print(-current_number) # PROBLEM 2 (Dice Sequence - 6pts) # You roll five six-sided dice, one by one. # What is the probability that the value of each die # is greater than OR EQUAL TO the value of the previous die that you rolled? # For example, the sequence “1, 1, 4, 4, 6” is a success, # but “1, 1, 4, 3, 6” is not. Determine the # probability of success using a simulation of a large number of trials. a = 0 b = 500 die = random.randrange(6) f = 0 while f <= 100: for i in range(6): new_die = random.randrange(6) if new_die >= die: a += 1 die = new_die if f == 0: print("Probability: {}%".format(10000*a/b)) f += 1 print("Probability after many trials: {}%".format(100*a/b)) # PROBLEM 3 (Number Puzzler - 6pts) # A, B, C, and D are all different digits. # The number DCBA is equal to 4 times the number ABCD. # What are the digits? # Note: to make ABCD and DCBA conventional numbers, neither A nor D can be zero. # Use a quadruple-nested loop to solve. digit_1 = 0 digit_2 = 0 digit_3 = 0 digit_4 = 0 def is_unique(x): seen = set() return not any(i in seen or seen.add(i) for i in x) for a in range(1000): digit_1 = random.randrange(10) for b in range(10): digit_2 = random.randrange(10) for c in range(10): digit_3 = random.randrange(10) for d in range(10): digit_4 = random.randrange(10) if is_unique([digit_1, digit_2, digit_3, digit_4]): if digit_1 != 0 and digit_4 != 0: ABCD = 1000*digit_1 + 100*digit_2 + 10*digit_3 + digit_4 DBCA = 1000*digit_4 + 100*digit_3 + 10*digit_2 + digit_1 print(ABCD) print(DBCA) if DBCA == 4*ABCD: print("Found it. A = {}, B = {}, C = {}, and D = {}".format(digit_1, digit_2, digit_3, digit_4)) # Eventually prints "Found it. A = 2, B = 1, C = 7, and D = 8"
import pandas import d3py from d3py.displayable import SimpleServer import logging """ This example is based on d3py_bar.py but the goal is to highlight how to configure a server for your figure. For the initial release, we simple support Python's SimpleHTTPServer. Got you sights on a different server? Look at the displayable module. """ df = pandas.DataFrame( { "count" : [1,4,7,3,2,9], "apple_type": ["a", "b", "c", "d", "e", "f"], } ) # by default point your browser to port 8000 at localhost # This example changes the port. with d3py.PandasFigure(df,server=SimpleServer(port=7878)) as p: p += d3py.Bar(x = "apple_type", y = "count", fill = "MediumAquamarine") p += d3py.xAxis(x = "apple_type") p.show()
""" Question: Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's length. """ def solution(nums, k): for _ in range(k): maximum = max(nums) nums.remove(maximum) return maximum result = solution([3,2,1,5,6,4],2) print(result)
amount = 2400 transaction_type = "L" if transaction_type == "L": if amount <= 25000: discount = amount*.0 print( "Net Amount:", discount) if amount <=57000: discount = amount*.5 print( "Net Amount:", discount) else: if amount <=100000: discount = amount*.075 print ("Net Amount:", discount) if amount >= 100000: discount = amount*.10 print ("Net Amount:", discount )
s1=int(input("enter any num")) s2=int(input("enter any num")) s3=int(input("enter any num")) s4=int(input("enter any num")) sum=s1+s2+s3+s4 if(sum==360): print("it is trange") else: print("not trange")
#checkin.py #import pyperclip def bend(): #This function is used to determine if there is a bend, and if so, the severity weakBend = "Device has a minor bend in the frame." medBend = "Device has a moderate bend in the frame." strongBend = "Device has a severe bend in the frame." bend = eval(input("If device has bend in frame, input 1. \nIf not, input 2.\n")) bendList = [weakBend,medBend,strongBend] if bend == 1: bend = eval(input("If bend is minor, input 1. \nIf moderate, input 2. \nIf severe, input 3.\n")) bend = bend - 1 try: return bendList[bend] except: return bend() else: return ("") #checkin.py def screen(): #This function is to differentiate between broken glass, glass/lcd, or just LCD try: glass = "broken glass, LCD still functional." lcd = "broken LCD." glassLcd = "broken glass and LCD." workList = [glass,lcd,glassLcd] workScreen = eval(input("Glass broken? 1, \nLCD broken? 2, \nGlass and LCD broken? 3\n")) #This will become incorporated with the gui. We are simply using temporary #numbers to produce the same output workScreen = workScreen - 1 return workList[workScreen] except: return screen() def turnaround(): time1 = eval(input("How long will this take to get done?")) def abletotest(): test = eval(input("Were you able to test the device? Input a 1, \notherwise input a 2\n")) if test == 1: return "" elif test == 2: return "Device was unable to be tested at check-in due to the nature of the damage. Device will be tested after the repair, and customer will be notified if any additional damage is identified." else: return abletotest() def screenrepair(): deviceName = input("What is the device name? i.e. Samsung Galaxy S7 Edge\n") deviceColor = input("What color is the screen? i.e. White, Rose Gold, Black\n") screenWork = screen() bendWork = bend() turnaroundWork = input("How long will this take to get done? i.e. '2.5 hours,' ',3-5 days,'\n") testWork = abletotest() print("Customer has brought in a",deviceColor,deviceName,"with a", screenWork,bendWork,"Customer understands turn-around time of",turnaroundWork,testWork) #pyperclip.copy("Customer has brought in a",deviceColor,deviceName,"with a", #screenWork,bendWork,"Customer understands turn-around time of",turnaroundWork,testWork) def waterdiag(): return def chargeport(): return def miscdiag(): return def laptopglass(): return def main(): screenrepair()
#!/usr/bin/env python3 # coding: utf-8 class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height def get_volume(self): vol = self.length * self.width * self.height return vol box_one = Box(10, 20, 30) box_two = Box(20, 30, 40) class ColouredBox(Box): def __init__(self, length, width, height, colour): super().__init__(length, width, height) self.colour = colour box_one = ColouredBox(10, 20, 30, "Blue") print(box_one.get_volume()) print(box_one.colour)
#!/usr/bin/env python3 # coding: utf-8 # 1, 2, 3, 4, 5 # 2, 4, 6, 8, 10 # 3, 6, 9, 12, 15 # 4, 8, 12, 16, 20 # 5, 10, 15, 20, 25 size = int(input("How big would you like your times table? ")) for a in range(1, size + 1): for b in range(1, size + 1): product = a * b print("{}\t".format(product), end="") print()
import unittest from calculator import Calculator class TestMyCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_initial_value(self): self.assertEqual(0, self.calc.value) # Creamos un nuevo test para comprobar una suma def test_add_method(self): # Ejecutamos el método self.calc.add(1, 3) # Comprobamos si el valor es el que esperamos self.assertEqual(4, self.calc.value)
import sqlite3 db=sqlite3.connect("test.db") db.execute("drop table if exists results") try: db.execute("create table resultss(name,Class,section,telugu,hindi,english,maths,science,social)") except: print("already ") db=sqlite3.connect("test.db") #table created name="ashu" Class ="2" section="a" telugu="90" hindi="92" english="95" maths="88" science="89" social="90" cmd="insert into resultss(name,Class,section,telugu,hindi,english,maths,science,social)values('{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(name,Class,section,telugu,hindi,english,maths,science,social) db.execute(cmd) db.commit() name="riya" Class ="2" section="a" telugu="99" hindi="96" english="97" maths="88" science="89" social="90" cmd="insert into resultss(name,Class,section,telugu,hindi,english,maths,science,social)values('{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(name,Class,section,telugu,hindi,english,maths,science,social) db.execute(cmd) db.commit() name="riyansh" Class ="2" section="a" telugu="92" hindi="96" english="97" maths="88" science="89" social="90" cmd="insert into resultss(name,Class,section,telugu,hindi,english,maths,science,social)values('{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(name,Class,section,telugu,hindi,english,maths,science,social) db.execute(cmd) db.commit() name="riyanshi" Class ="2" section="a" telugu="82" hindi="96" english="97" maths="98" science="89" social="90" cmd="insert into resultss(name,Class,section,telugu,hindi,english,maths,science,social)values('{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(name,Class,section,telugu,hindi,english,maths,science,social) db.execute(cmd) db.commit() db=sqlite3.connect("test.db") rs=db.execute("SELECT * from resultss") for row in rs: print(row) #output #('ashu', '2', 'a', '90', '92', '95', '88', '89', '90') #('riya', '2', 'a', '99', '96', '97', '88', '89', '90') #('riyansh', '2', 'a', '92', '96', '97', '88', '89', '90') #('riyanshi', '2', 'a', '82', '96', '97', '98', '89', '90') mycursor = db.cursor() sql = "DELETE FROM resultss WHERE name = 'riya'" mycursor.execute(sql) db.commit() print(mycursor.rowcount, "record(s) deleted") # row deleted db=sqlite3.connect("test.db") rs=db.execute("SELECT * from resultss") for row in rs: print(row) #output #('ashu', '2', 'a', '90', '92', '95', '88', '89', '90') #('riyansh', '2', 'a', '92', '96', '97', '88', '89', '90') #('riyanshi', '2', 'a', '82', '96', '97', '98', '89', '90') mycursor = db.cursor() sql = "UPDATE resultss SET english='99' WHERE name='riyansh'"; mycursor.execute(sql) db.commit() print(mycursor.rowcount, "updated") #updated db=sqlite3.connect("test.db") rs=db.execute("SELECT * from resultss") for row in rs: print(row) #output #('ashu', '2', 'a', '90', '92', '95', '88', '89', '90') #('riyansh', '2', 'a', '92', '96', '99', '88', '89', '90') #('riyanshi', '2', 'a', '82', '96', '97', '98', '89', '90') mycursor = db.cursor() sql = "UPDATE resultss SET name='reeyansh' WHERE name='riyansh'"; mycursor.execute(sql) db.commit() print(mycursor.rowcount, "updated") #updated
import pandas as pd #1 #This files purpose is to reclassify diseases as a more broad category. #This is done by iterating over the dataframe, and checking if the 6th item in each row is within the predefined list #Each predefined list is manually created and curated by user. #Each item in each predefined list should be spelled exactly how it is in FAERS "pt" #End of script, a new array is created from the original, but only keeping records that list one of the new groups just created # ^ basically everything is stripped except for the adverse events of interest #To increase total data size/more rows, increase the size of groups by adding in more criteria (like expanding cardiac to be more broad by including additional cardiac AE's) def check(los): if los[6] in cardiac: los[6]='Cardiac' return los '''def combo_pt(sub_df): if len(sub_df[(sub_df['pt']=='Seizure') | (sub_df['pt']=='Muscle rigidity')])>2: return sub_df.replace({'Seizure':'Serotonin syndrome','Muscle rigidity':'Serotonin syndrome'}) if len(sub_df[(sub_df['pt']=='Seizure') | (sub_df['pt']=='Muscle spasticity')])>2: return sub_df.replace({'Seizure':'Serotonin syndrome','Muscle spasticity':'Serotonin syndrome'}) else: return sub_df ''' df=pd.read_csv(r'faers_base.csv',low_memory=False) #dfd=pd.DataFrame(columns='primaryid caseid age sex occr_country prod_ai pt drugname'.split('\t')) #in order to begin grouping diseases into categories, build your lists of disease. #Note: The must be present in your raw data frame from FAERS. #Note: Functionality for disease combos is in combo_pt (there are no cases so far with both) cardiac=['Acute cardiac event', 'Cardiac arrest','Sudden death','Cardiac death', 'Arrhythmia','Cardiac arrest','Cardiac arrest neonatal','Sudden cardiac death'] #ss=['Serotonin syndrome','Muscle rigidity'] death=['Sudden death','Sudden infant death syndrome','Accidental death', 'Brain death','Premature baby death','Foetal death','Apparent death', 'Death neonatal'] print('beginning reclassifciation') cases=list(set(df['caseid'])) ''' for i in cases: dfd=pd.concat([dfd,combo_pt(df[df['caseid']==i])])''' print('done reclassifying SS') #df=dfd #turn into an array arr=[list(i) for i in df.values] before=[i[6] for i in arr] for i in arr: if i[6] in cardiac: i[6]='Cardiac' # if i[6] in ss: # i[6]='Serotonin syndrome' if i[6] in death: i[6]='Death' after=[i[6] for i in arr] print('Cardiac: (before: %d) | (after: %d)'%(before.count('Cardiac'),after.count('Cardiac'))) #print('Serotonin syndrome: (before: %d) | (after: %d)'%(before.count('Serotonin syndrome'),after.count('Serotonin syndrome'))) print('Death: (before: %d) | (after: %d)'%(before.count('Death'),after.count('Death'))) df1=pd.DataFrame(arr,columns=['primaryid', 'caseid', 'age', 'sex', 'occr_country','prod_ai', 'pt', 'drugname']) df1.to_csv('faers_ALL_ae_grouping_altered_cardiac.csv') #this is done to trim the data down to increase speed and efficiency of entire system and SHOULD NOT BE USED #FOR ANYTHING ELSE EXCEPT FOR CREATING AE FREQUENCY MATRIX final_df=df1[(df1['pt']=='Cardiac') | (df1['pt']=='Death')] final_df.to_csv('faers_ae_grouping_altered_cardiac.csv')
#交叉验证的方法 from sklearn.datasets import load_iris; from sklearn.model_selection import train_test_split; from sklearn.neighbors import KNeighborsClassifier; import matplotlib.pyplot as plt; #进行交叉验证 from sklearn.cross_validation import cross_val_score; #加载数据集 iris = load_iris(); X = iris.data; Y = iris.target; #分割数据集 X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.3); #建立模型 knn = KNeighborsClassifier(); #训练模型 knn.fit(X_train,Y_train); #将标准率打印出来 print(knn.score(X_test,Y_test)); #使用k折交叉验证模块 cv=5 分成5分 4:1 1份是测试集 scores = cross_val_score(knn,X,Y,cv=5,scoring='accuracy'); #将五次预测的准确率打印出来 print(scores); print(scores.mean()); #建立测试参数集 k_range = range(1,31); k_scores = []; #由迭代的方式计算不同的参数对模型的影响 并且返回交叉验证后的平均准确率 for k in k_range: knn = KNeighborsClassifier(n_neighbors=k); scores = cross_val_score(knn,X,Y,cv = 10,scoring="accuracy"); k_scores.append(scores.mean()); #进行可视化 plt.plot(k_range,k_scores); plt.xlabel("Value of K for KNN"); plt.ylabel("Cross-Validated Accuracy"); plt.show(); #以平均方差进行判断 k_range = range(1,31); k_scores = []; for k in k_range: knn = KNeighborsClassifier(n_neighbors=k); #记得乘上-1 因为计算出来是负数 loss = -cross_val_score(knn,X,Y,scoring="mean_squared_error"); k_scores.append(loss.mean()); plt.plot(k_range,k_scores); plt.xlabel("Value of K for knn"); plt.ylabel("Cross-Validated MSE"); plt.show();
''' Problem Statement url https://www.hackerrank.com/challenges/kangaroo/problem If v1<=v2 , they will never meet. It is required to check if a solution exists for the following equation: x1 + t*v1 == x2 + t*v2 This is equivalent to checking if : (x2-x1)%(v1-v2) == 0 ''' ''' solution ''' def kangaroo(x1, v1, x2, v2): X = [x1, v1] Y = [x2, v2] back = min(X, Y) print(back) fwd = max(X, Y) print(fwd) dist = fwd[0] - back[0] while back[0] < fwd[0]: back[0] += back[1] fwd[0] += fwd[1] if fwd[0] - back[0] >= dist: break print(["NO", "YES"][back[0] == fwd[0]]) kangaroo(0, 3, 4, 2)
import copy from random import shuffle class Sudoku: def __init__(self): self.grid = [[0 for i in range(9)] for j in range(9)] self.solved_path = [] @staticmethod def find_empty(grid): # Return empty row and col (or None if there is no empty one) for row in range(9): for col in range(9): if grid[row][col] == 0: return row, col return None, None @staticmethod def is_valid(row, col, num, grid): # Check if number has been use in either row, column or 3x3 grid (subgrid) # checking if number is used in a row if num in grid[row]: return False # check if number is used in a column for r in range(9): if grid[r][col] == num: return False # check if number is used in 3x3 square (subgrid) first_row = (row // 3) * 3 # First row of the subgrid first_col = (col // 3) * 3 # First column of the subgrid for r in range(first_row, first_row + 3): for c in range(first_col, first_col + 3): if grid[r][c] == num: return False return True def sudoku_grid_action(self, grid, action=None, sudoku_numbers_count=None): # Main solving method # this method is used both for generating sudoku grid and solving it, depends on action argument sudoku_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # base case for recursion row, col = self.find_empty(grid) if row is None: # If there is no empty squares, then it means that sudoku is solved # if we are checking how many solutions there are when generating grid (must be one unique solution) # return grid to compare solution to originally solved grid if action == "CHECK": return grid return True # if program is generating sudoku grid, shuffle sudoku numbers so we don't get the same grid everytime if action == "GENERATE": shuffle(sudoku_numbers) num_list = sudoku_numbers # if program is solving the puzzle, use sudoku numbers 1-9 sequentially elif action == "INSERT": num_list = sudoku_numbers # if program is checking number of possible solutions, list that has been passed in as argument for the method else: num_list = sudoku_numbers_count for number in num_list: # if program is solving puzzle, record attempt the attempt to input the number to the grid if action == "INSERT": self.solved_path.append(["ATTEMPT", row, col, number]) if self.is_valid(row, col, number, grid): grid[row][col] = number # if program is solving puzzle, record successful number input if action == "INSERT": self.solved_path.append(["INSERT", row, col, number]) # continue solving puzzle recursively if self.sudoku_grid_action(grid, action, sudoku_numbers_count): return grid # if program is solving puzzle, record the reset of the current number if action == "INSERT": self.solved_path.append(["DELETE", row, col, number]) grid[row][col] = 0 # reset guess if none values are valid (1-9) return False def get_solutions(self, grid, full_grid): # Return boolean value which will determine whether there is more than one solution after the number was removed sudoku_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # number of possible solutions (for valid sudoku should be one) for i in range(len(sudoku_numbers)): solved_grid = self.sudoku_grid_action(grid, "CHECK", sudoku_numbers) if solved_grid != full_grid: # Check if solved grid is equals to the original one (must be one solution) return False sudoku_numbers.append(sudoku_numbers.pop(0)) # Add first sudoku number to the end to try more combinations return True def get_squares(self): # Return a list of occupied squares on the whole sudoku grid return [(row, col) for row in range(9) for col in range(9) if self.grid[row][col] != 0] def remove_numbers_grid(self): # Remove numbers from full valid grid to generate sudoku puzzle taken_squares = self.get_squares() # Get squares that are occupied shuffle(taken_squares) # Shuffle occupied squares to select random squares taken_squares_count = len(taken_squares) # Attempt count to find unique solutions, the greater attempt count the more difficult sudoku will be # Code will run longer to find unique solution with less clues attempt_count = 3 # Copy of the original grid used for comparison to make sure there is one unique solution full_grid = copy.deepcopy(self.grid) # 17 is the minimum number of clues which leads to a unique solution while attempt_count > 0 and taken_squares_count >= 17: row, col = taken_squares.pop() # get row and column that will be deleted from grid taken_squares_count -= 1 # decrement number of occupied squares on the grid deleted_square = self.grid[row][col] # memorise deleted square for back-tracking self.grid[row][col] = 0 grid_copy = copy.deepcopy(self.grid) if not self.get_solutions(grid_copy, full_grid): # If there is more than one solution, means sudoku is not valid self.grid[row][col] = deleted_square # restore deleted value to the grid taken_squares_count += 1 # Increment occupied squares attempt_count -= 1 # Allow less tries to generate grid return def generate_puzzle(self): self.sudoku_grid_action(self.grid, "GENERATE") self.remove_numbers_grid() return self.grid def solve_puzzle(self): self.sudoku_grid_action(self.grid, "INSERT") return self.grid
#/usr/bin/python ''' Bond related objects and functions. ''' from numpy import * #? from matplotlib.pyplot import * #? from matplotlib.collections import LineCollection #? import pdb #? __all__=['Bond','BondCollection','show_bonds'] #__all__ can hide some class class Bond(object): '''A simple Bond class''' def __init__(self,bondv,atom1,atom2): self.bondv=bondv self.atom1=atom1 self.atom2=atom2 def getreverse(self): '''reverse the bond''' return Bond(-self.bondv,self.atom2,self.atom1) def __str__(self): #called when bond be printed or called by str() return self.bondv.__str__()+' '+str(self.atom1)+' '+str(self.atom2) #maybe self.bondv.__str__() is similar to str(self...)? def __eq__(self,bond2): #called when bond==bond2 return (all(self.bondv==bond2.bondv)) & (self.atom1==bond2.atom1) & (self.atom2==bond2.atom2) #maybe all used because bondv is a vector? class BondCollection(object): ''' A collection of Bond objects, pack it into compact form. *Attributes* atom1s/atom2s: the starting/ending sites of bonds. bondvs: the bond vectors. ''' def __init__(self,atom1s,atom2s,bondvs): self.atom1s=array(atom1s) #array used because atom1s may be just one atom self.atom2s=array(atom2s) self.bondvs=array(bondvs) self.bonds=[Bond(bv,a1,a2) for bv,a1,a2 in zip(bondvs,atom1s,atom2s)] #bonds is class bond made of bondvs,atom1s and atom2s self.__finalized__=True #__finalized__ should be a self-defined attribute,maybe means that it ends? def __getitem__(self,index): #called when bondcollection[index] return self.bonds[index] def __setattr__(self,name,value): #called when a value was given to bondcollection's attribute name finalized=hasattr(self,'__finalized__') #judge if class has this attribute __finalized__.to judge if class has been initialized? if not finalized: return super(BondCollection,self).__setattr__(name,value) #call parent class's __setattr__.but what is bondcollection's parent class? super(BondCollection,self).__setattr__(name,value) if name!='bonds': self.bonds=[Bond(bv,a1,a2) for bv,a1,a2 in zip(self.bondvs,self.atom1s,self.atom2s)] #update bond def __iter__(self): #iterartion? return iter(self.bonds) def __str__(self): return '<BondCollection(%s)>\n'%self.N+'\n'.join([b.__str__() for b in self.bonds]) #join combines strings in sequence.'.'? def __len__(self): #called when len(bondcollection) return self.N @property #change a method into an attribute def N(self): '''The number of bonds''' return len(self.bonds) @property def vdim(self): '''The dimension of bonds.''' return self.bondvs.shape[-1] #-1 means compute the length automotively? def query(self,atom1=None,atom2=None,bondv=None,condition='and'): ''' Get specific bonds meets given requirements. atom1/atom2: One or a list of atom1,atom2. bondv: One or a list of bond vectors. condition: * `and` -> meets all requirements. * `or` -> meets one of the requirements. * `xor` -> xor condition. *return*: A <BondCollection> instance. ''' tol=1e-5 masks=[] assert(condition in ['or','and','xor']) if atom1 is not None: if ndim(atom1)==0: atom1=array([atom1]) #ndim gives the number of array dimension masks.append(any(abs(self.atom1s-atom1[:,newaxis])<0.5,axis=0)) #? if atom2 is not None: if ndim(atom2)==0: atom2=array([atom2]) masks.append(any(abs(self.atom2s-atom2[:,newaxis])<0.5,axis=0)) if bondv is not None: if ndim(bondv)==1: bondv=array([bondv]) masks.append(any(norm(self.bondvs-bondv[:,newaxis,:],axis=-1)<tol,axis=0)) mask=ones(self.N,dtype='bool') for mk in masks: if condition=='or': mask|=mk elif condition=='and': mask&=mk else: mask^=mk return BondCollection(self.atom1s[mask],self.atom2s[mask],self.bondvs[mask]) def show_bonds(bonds,start=None,lw=1,**kwargs): ''' Display a collection of bonds. bonds: A <BondCollection> instance. start: the location of starting atoms. lw,**kwargs: line width of bonds and key word arguments for *return*: None ''' vdim=bonds.vdim #this bonds is a class bondcollection bvs=[] if start is None: start=zeros([bonds.N,vdim]) elif ndim(start)==1: bvs=zip(start,bonds.bondvs+start) else: bvs=zip(start,bonds.bondvs+start) if vdim==1: bvs=[(append(start,[0]),append(end,[0])) for start,end in bvs] lc=LineCollection(bvs,**kwargs) #draw lines lc.set_linewidth(lw) ax=gca() ax.add_collection(lc) ax.autoscale() ax.margins(0.1)
tuple_ = (1,2,3) list_=[1,2,4] tuple_=tuple(list_) print(tuple_) list_[0]=77 a=[] tup = ([],) print(tup) tup[0].append(1) print(tup) a.append(12) print(tup)
def f(arg): # Рекурсия yield arg arg+=1 yield arg arg += 1 yield arg arg += 1 a = f(100) print(next(a)) print(next(a)) print(next(a)) '''''' def run(): print('run') def go(): print('go') def eat(): print('chav-vhav') a = {} a['run'] = run def error(): print('Error') if __name__ == '__main__': com = input() a.get(com,error)()
''' list_ = [1, 2, 3] list_.append(list_) # обект с бесконечностью, добавляет сам семя в конец бесконечое число раз print(list_) print(list_[-1]) for item in list_: print(item) if type(item) == list: for i in item: print(i) if isinstance(item, list): # то же самое, что и 7 строчка for i in item: print(i) ''' ''' a = [1, 2, 3, 4, 5,[77, 88, 99]] b = a.copy() # если написать a=b то в b будут храниться ссылки на а а не копироваться список b[0] = "abc" print(a) print(b) ''' ''' import copy import deepcopy a = [1, 2, 3, 4, 5,[77, 88, 99]] b = deepcopy(a) # если написать a=b то в b будут храниться ссылки на а а не копироваться список b[0] = "abc" print(a) print(b) ''' ''' str_ =("ababababab") str_.replace("a", "c") str_two = str_.replace("a", "c") print(str_) # выведет ababababab потому что строки не изменяются, их нужно перезаписывать print(str_two) list_ = [1, 67, 4, 3564, 4] a = list_.sort() a = sorted(list_) # верхня строчка не работает print(list_) print(a) ''' ''' a=print a(print("Hello, World")) ''' ''' def test(): print("Test") test() ''' def test(name): print("Hello,{}".format(name)) name="World" test(name) def test_func(a,b): return a+b print(test_func(3,5))
x1=int(input()) y1=int(input()) #x2=int(input()) #y2=int(input()) if x>0 and y>0: print("I плоскасть") elif x<0 and y>0: print("II плоскасть") elif x<0 and y<0: print("III плоскасть") else: print("IV плоскасть")
#!/usr/bin/python3 import time def main(): print("Main Function") while True: oneHz(200) def hz(freq): fq = float(1 / freq) t0 = time.time() print(freq, " Hz") while True: if(time.time() > (t0 + fq)): break def oneHz(f): t0 = time.time() print("1 Hz") while True: hz(f) if(time.time() > (t0 + 1)): break if __name__ == "__main__": main()
from PIL import Image import face_recognition # https://github.com/ageitgey/face_recognition/tree/master/examples image1 = face_recognition.load_image_file("01_franzi_60er_gruppe.jpg") image2 = face_recognition.load_image_file("2018_07_30_F60_Schweizerhaus.jpg") image3 = face_recognition.load_image_file("17_matsch_geb_02012012.jpg") # Find all the faces in the image using the default HOG-based model. # This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated. face_locations = face_recognition.face_locations(image3) face_landmarks_list = face_recognition.face_landmarks(image3) print("I found {} face(s) in this photograph.".format(len(face_locations))) print(f"output {face_landmarks_list}") for face_location in face_locations: # Print the location of each face in this image top, right, bottom, left = face_location print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right)) # You can access the actual face itself like this: face_image = image1[top:bottom, left:right] pil_image = Image.fromarray(face_image) pil_image.show() # Find all the faces in the image using a pre-trained convolutional neural network. # This method is more accurate than the default HOG model, but it's slower # unless you have an nvidia GPU and dlib compiled with CUDA extensions. But if you do, # this will use GPU acceleration and perform well. face_locations = face_recognition.face_locations(image3, number_of_times_to_upsample=0, model="cnn") print("I found {} face(s) in this photograph.".format(len(face_locations))) for face_location in face_locations: # Print the location of each face in this image top, right, bottom, left = face_location print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right)) # You can access the actual face itself like this: face_image = image2[top:bottom, left:right] pil_image = Image.fromarray(face_image) pil_image.show() print("done")
#encoding: utf-8 __author__ = 'Josue Wuezo' class Human: def __init__(self): self.age = 25 #This an attribute print ('I am a human being') def talk(self, message): print (message) Leslie = Human() Michael = Human() Leslie.talk("Hello, Michael") Michael.talk("Oh\! Hi, Leslie") print ("I have " + str(Michael.age) + " years old")
#Booleans, Logical Operators & Strings #True or False, 1 or 0 #Boolean: True or False // 1 or 0 bT = True bF = False print (str(bT) +' ' + str(bF)) #Logical Operators: AND (both are true) bA = True and False print (str(bA)) #Logical Operators: OR (at least one is true) bO = True or False print (str(bO)) #Logical Operators: NOT (they are not what they say) bNt = not True bNf = not False print (bNt) print (' & ') print (bNf)
una_lista = [1,2,3,4,5,6,7,8] for elemento in una_lista: print("Hola elemento Num 1", elemento) nombre = ["lara", "papa", "juan", "martin", "luis", "michelle", "pedro","lucia"] for alumnos in nombre: print("Hola alumno:", alumnos)
"""paying-the-minimum program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.""" balance = 4213 #credit card original balance annualInterestRate = 0.2 #constant annual interest rate monthlyPaymentRate = 0.04 #monthly pay rate constant at each month monthlyInterestRate = annualInterestRate / 12.0 #interest rate each month totalPaid = 0.0 #initial value for totalPaid count = 1 #begining loop variable for count in range(1, 13): #calculating (remainingBalance & totalPaid) after 12 months minMonthlyPayment = monthlyPaymentRate * balance #minMonthlyPayment for each month monthlyUnpBalance = balance - minMonthlyPayment #unpaidBalance for each month remainingBalance = monthlyUnpBalance + (monthlyInterestRate * monthlyUnpBalance) #remainingBalance after each month balance = remainingBalance #assign old remainingBalance to balance totalPaid = totalPaid + minMonthlyPayment #totalPaid for each month print 'Month: ' + str(count) print 'Minimum monthly payment: ' + str(round(minMonthlyPayment, 2)) print 'Remaining balance: ' + str(round(remainingBalance, 2)) print 'Total paid: ' + str(round(totalPaid, 2)) #totalPaid after 12 months print 'Remaining balance: ' + str(round(remainingBalance, 2)) #remainingBalance after 12 months
from bs4 import BeautifulSoup import requests import spotipy from spotipy import Spotify from spotipy.oauth2 import SpotifyOAuth time_travel = input("Enter the date you want to create Spotify playlist? Format YYYY-MM-DD") response = requests.get(f"https://www.billboard.com/charts/hot-100/{time_travel}") year_splice = time_travel.split("-")[0] print(year_splice) billboard_url = response.text soup = BeautifulSoup(billboard_url, "html.parser") song_list = soup.find_all(name="span", class_="chart-element__information__song") song_artist_list = soup.find_all(name="span", class_="chart-element__information__artist") song_final_list = [song.getText() for song in song_list] print(song_final_list) scope = "playlist-modify-private" sp: Spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) spotify_user_id = sp.current_user()["id"] print(spotify_user_id) spotify_playlist = f"Billboard Top 100 {time_travel}" playlist = sp.user_playlist_create(user=spotify_user_id, name=spotify_playlist, public=False) playlists_id = playlist["id"] print(playlists_id) spotify_tracks = [] for song in song_final_list: song_uri = f"track:{song} year:{year_splice}" result = sp.search(q=song_uri, type="track") items = result['tracks']['items'] if len(items) > 0: track = items[0] print(track['name'], track['id']) spotify_tracks.append(track['id']) print(spotify_tracks) sp.playlist_add_items(playlist_id=playlists_id, items=spotify_tracks)
letters = ('A','C','B','B','C','A','C','C','B') print(sorted(letters)) print(letters.count('A'),letters.count('B'), letters.count('C'))
""" Demo of a simple plot with a custom dashed line. A Line object's ``set_dashes`` method allows you to specify dashes with a series of on/off lengths (in points). """ import numpy as np import matplotlib.pyplot as plt labels = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22'] x = np.linspace(0, 22, 22) plt.figure('data sizes') lst = [246.284, 242.003 , 198.723 , 190.526 , 180.152 , 170.233 , 158.202 , 145.704 , 139.726 , 134.846 , 133.928, 131.833 , 113.698 , 105.954 , 99.947 , 88.481, 78.468 , 75.820 , 63.563 , 62.193 , 46.761 , 49.498 ] plt.xticks(x, labels, rotation='vertical') plt.plot(x, lst, 'black') plt.ylabel('Size in megabytes') plt.show() plt.figure('0 Mismatches') # Python p0 = [18.861,17.507,15.01,13.786,12.11,11.392,10.595,9.765,9.3,9.003,8.974,8.827,8.159,7.935,7.691,6.803,7.36,7.102,5.499,4.476,3.194,3.466] # C c0 = [14.25,13.964,11.338,10.908,10.454,9.649,9.165,8.434,7.83,7.696,7.763,7.627,6.508,6.032,5.595,4.976,4.583,4.381,3.559,3.628,2.586,2.851] # SMF sfm0 = [4.465,4.574,3.427,3.385,3.193,2.929,2.79,2.611,2.403,2.365,2.376,2.339,1.958,1.813,1.713,1.527,1.391,1.36,1.093,1.115,0.785,0.815] # TRE tre0 = [44.259,43.216,35.323,34.256,32.434,30.399,28.641,26.354,25.063,24.35,24.022,23.576,20.322,18.861,17.908,15.767,14.141,13.568,11.254,11.214,8.295,8.76] plt.plot(x, p0, 'g') l0, = plt.plot(x, p0, '+', linewidth=2, color='green') plt.plot(x, c0, 'b') l1, = plt.plot(x, c0, '*', linewidth=2, color='blue') plt.plot(x, sfm0, color='orange') l2, = plt.plot(x, sfm0, '-', color='orange', linewidth=2) plt.plot(x, tre0, 'r') plt.xticks(x, labels, rotation='vertical') l3, = plt.plot(x, tre0, 'o', color='r', linewidth=2) plt.ylabel('Time in Seconds') plt.legend( (l1, l2, l3, l0),('TPaMa', 'scan_for_matches', 'TRE', 'Python'), loc='upper right', shadow=True) plt.show() plt.figure('1 Insertion') # Python i20 = [30.138,30.224,25.947,24.258,22.177,21.182,19.565,17.943,17.151,16.693,16.654,16.626,14.129,13.265,12.439,11.116,9.909,9.84,7.981,7.852,5.871,6.156] # C i21 = [16.005,16.339,12.666,12.598,10.826,10.111,9.416,8.612,7.749,7.753,7.777,7.525,6.358,5.929,5.735,4.952,4.511,4.389,3.499,3.53,2.581,2.681] # SMF i22 = [9.782,10.362,8.396,7.904,7.856,7.444,6.96,5.792,5.398,5.37,6.584,5.59,4.696,4.354,4.14,3.686,3.376,3.256,2.638,2.658, 1.9, 1.992] # TRE i23 = [50.413,48.526,40.211,38.548,35.259,32.631,30.979,27.891,26.071,25.468,25.384,24.713,21.691,19.583,18.745,16.522,14.838,14.414,11.616,11.689,8.685,9.15] plt.plot(x, i20, 'g') l0, = plt.plot(x, i20, '+', linewidth=2, color='green') plt.plot(x, i21, 'b') l1, = plt.plot(x, i21, '*', linewidth=2, color='blue') plt.plot(x, i22, color='orange') l2, = plt.plot(x, i22, '-', color='orange', linewidth=2) plt.plot(x, i23, 'r') plt.xticks(x, labels, rotation='vertical') l3, = plt.plot(x, i23, 'o', color='r', linewidth=2) plt.ylabel('Time in Seconds') plt.legend( (l1, l2, l3, l0),('TPaMa', 'scan_for_matches', 'TRE', 'Python'), loc='upper right', shadow=True) plt.show() plt.figure('2 Insertions') # Python i20 = [45.179,46.201,39.007,35.685,33.34,31.572,29.456,27.207,25.882,25.265,25.23,25.136,21.305,19.906,18.849,16.727,14.975,14.437,12.032,11.889,8.769,9.273] plt.plot(x, i20, 'g') l0, = plt.plot(x, i20, '+', linewidth=2, color='green') # C i21 = [25.438,26.681,24.798,25.003,21.724,19.603,16.789,17.281,16.246,16.167,16.111,15.715,13.221,11.871,10.971,10.67,9.843,9.41,7.735,7.797,5.378,5.7049] plt.plot(x, i21, 'b') l1, = plt.plot(x, i21, '*', linewidth=2, color='blue') # SMF i22 = [12.59,12.366,10.105,9.722,9.188,8.708,8.054,7.444,6.888,6.906,6.843,6.722,5.547,5.167,4.851,4.407,4.038,3.914,3.153,3.197,2.269,2.35] plt.plot(x, i22, 'r') l2, = plt.plot(x, i22, '-', color='orange', linewidth=2) #TRE i23 = [56.287,55.871,45.486,44.217,41.219,39.462,36.182,33.559,31.695,30.977,30.623,30.238,26.082,24.199,22.687,20.128,18.177,17.596,14.316,14.311,10.523,11.145] plt.plot(x, i23, 'r') plt.xticks(x, labels, rotation='vertical') l3, = plt.plot(x, i23, 'o', color='r', linewidth=2) plt.ylabel('Time in Seconds') plt.legend( (l1, l2, l3, l0),('TPaMa', 'scan_for_matches', 'TRE', 'Python'), loc='upper right', shadow=True) plt.show() plt.figure('3 Insertions') # 3 inserts py3= [62.697,64.168,54.777,50.07,46.989,44.261,40.938,37.517,35.713,34.776,35.857,34.546,29.45,27.571,25.655,23.172,20.543,20.022,16.578,16.327,12.107,12.692] tre3 = [56.111,55.847,45.903,43.669,41.681,39.435,36.478,33.915,31.733,31.205,30.908,30.193,26.05,24.138,22.59,20.334,18.072,17.88,14.33,14.332,10.518,11.02] smf3 = [14.109,14.238,11.695,11.199,10.582,10.004,9.28,8.522,7.863,7.932,7.825,7.725,6.367,5.897,5.516,4.994,4.579,4.413,3.549,3.593,2.515,2.609] c3 = [37.79,44.205,35.391,32.167,26.342,26.055,23.965,22.398,20.713,20.4,20.817,20.129,16.819,15.568,14.525,13.139,11.996,11.65,9.413,9.516,6.798,7.096] plt.plot(x, py3, 'g') l0, = plt.plot(x, py3, '+', linewidth=2, color='green') plt.plot(x, c3, 'b') l1, = plt.plot(x, c3, '*', linewidth=2, color='blue') plt.plot(x, smf3, color='orange') l2, = plt.plot(x, smf3, '-', color='orange', linewidth=2) plt.plot(x, tre3, 'r') plt.xticks(x, labels, rotation='vertical') l3, = plt.plot(x, tre3, 'o', color='r', linewidth=2) plt.ylabel('Time in Seconds') plt.legend( (l1, l2, l3, l0),('TPaMa', 'scan_for_matches', 'TRE', 'Python'), loc='upper right', shadow=True) plt.show() plt.figure('1 1 1') # C c111 = [282.512,281.902,224.1122222,220.995,207.488,196.406,182.2144444,169.439,155.364,155.329,154.54,151.8966667,125.951,117.404,109.535,101.293,92.471,87.63,72.451,71.714,50.843,52.789] # SMF sfm111 = [26.342,24.69,19.659,19.331,18.414,17.46,16.043,14.96,13.742,13.854,13.795,13.607,11.056,10.362,9.737,8.989,8.343,7.958,6.481,6.546,4.484444444,4.71] # TRE tre111 = [70.765,69.637,55.136,54.002,51.479,49.065,45.301,41.43,39.263,39.111,38.398,38.01,32.462,29.395,27.915,24.807,23.058,22.059,17.435,17.9,12.884,13.549] # Python py111 = [241.965,233.21,193.994,174.241,160.494,151.249,140.413,129.152,123.398,119.816,119.338,117.471,108.041,105.709,99.212,90.67,94.816,92.315,72.95,55.734,41.3,46.058] plt.plot(x, py111, 'g') l0, = plt.plot(x, py111, '+', linewidth=2, color='green') plt.plot(x, c111, 'b') l1, = plt.plot(x, c111, '*', linewidth=2, color='blue') plt.plot(x, sfm111, color='orange') l2, = plt.plot(x, sfm111, '-', color='orange', linewidth=2) plt.plot(x, tre111, 'r') plt.xticks(x, labels, rotation='vertical') l3, = plt.plot(x, tre111, 'o', color='r', linewidth=2) plt.ylabel('Time in Seconds') plt.legend( (l1, l2, l3, l0),('TPaMa', 'scan_for_matches', 'TRE', 'Python'), loc='upper right', shadow=True) plt.show()
#-*-coding:utf-8-*- """ python中字典和集合,无论是键还是值,都可以是混合类型。 字典支持索引操作,可以通过dict(['key'])或者dic.get('key')来访问value的值 集合不支持索引操作,其本质上是一个哈希表,和列表不一样。 字典和集合具有高效性,特别是对于查找、插入和删除操作。 之所以如此高效,因为字典和集合的内部结构都是一个张哈希表 字典:该表存储哈希值(hash)、键和值3个元素 集合:区别是哈希表没有键和值的配对,只有单一的元素 字典集合运用场景:对元素的高效查找、去重。 思考题: 1、 d ={'name':'jason','age':20,'gender':'male'} #A d = dict({'name':'jason','age':20,'gender':'male'}) #B 那个更高效? 答案是A。 B方式是是一个function call。需要创建stack,且检查参数合法性等操作,开销更大 2、 d = {'name':'jason',['education']:['Tsinghua University','Stanford Unveristy']} 初始化是否正确? 不正确,列表作为key是不被允许。字典键值不可变,而列表是动态的,可变的,此处可以元组替换列表。 """ #1.创建和访问 #字典创建方式 d1 = {'name':'jason','age':20,'gender':'male'} d2 = dict({'name':'jason','age':20,'gender':'male'}) d3 = dict([('name','jason'),('age',20),('gender','male')]) d4 = dict(name='jason',age=20,gender='male') print(d1==d2==d3) #Set的创建方式 s1 = {1,2,3} s2 = set([1,2,3]) print(s1==s2) #都可以混合搭配 s = {1,'hello',5.0} print(s) #元素访问,字典可以通过Key(也就是索引键)访问 d = {'name':'jason','age':20} print(d['name']) #使用[ ]访问 #print(d['location']) #字典key索引不存在,会报错 print(d.get('name')) #使用get函数进行索引访问,get函数可以有一个默认值,当字典不存在则会返回null print(d.get("location")) #字典key索引不存在,会返回一个null #集合不支持索引,所以不能用s[0]来访问元素 s = {1,2,3} #print(s[0]) 报错。 #判断一个元素是否在集合或者字典中value in dict/set print(1 in s) #判断一个元素是否在集合中,利用value in set来判断 print('name' in d) #2.增加、删除、更新等操作 #字典更新操作 d = {'name':'jason','age':20} d['gender'] = 'male' #增加元素对 'gender':'male' d['bob'] = '1999-02-02' print(d) d['bob'] = '1999-01-04' #更新 print(d) d.pop('gender') #删除 print(d) #集合更新操作 s = {0,1,2,3,8} s.add(4) print(s) s.remove(4) print(s) s.pop() #该操作是删除集合最后一个元素,集合本身无序,无法知道删除那个元素,所以慎用 print(s) #排序,例子,比如你要取出值最大的50对 #字典,本身无序 d = {'b':1,'a':2,'c':10} d_sort_by_key = sorted(d.items(),key=lambda x:x[0]) #根据字典键值升序排序 d_sort_by_value = sorted(d.items(),key=lambda x:x[1]) #根据字典值的升序排序 print(d_sort_by_key) print(d_sort_by_value) #集合 s = {3,4,2,1} print(sorted(s)) #sorted()排序 #字典和集合性能 #字典和结合进行过性能高度优化的数据结构 尤其是查找,添加和删除操作 #与列表数据结构做对比 #例子:电商后台存储,产品ID、名称、价格。需求:给定ID找出价格 #列表存储id和price def find_product_price(products,product_id): for id,price in products: if id == product_id: return price return None products =[(12345,100), (23456,30), (34567,150)] print("The price of product 12345 is {}".format(find_product_price(products,12345))) #字典存储 products={ 12345:100, 23456:30, 34567:150 } print("The price of product 12345 is {}".format(products[12345])) #直接通过键的哈希值知道相应的值。 #如果需求变成找出这些商品有多少种不同的price,依然使用list,下面代码#A,#B是两个循环,因此需要O(n^2)的时间复杂度 #list version: def find_unique_price_using_list(products): unique_price_list = [] for _,price in products: #A if price not in unique_price_list: #B unique_price_list.append(price) return len(unique_price_list) products = [ (12345,100), (23456,30), (34567,150), (45678,30) ] print('number of unique price is {}'.format(find_unique_price_using_list(products))) #如果是使用set,集合是高度优化的哈希表,里面元素不可以重复,并且添加和查找操作只需o(1)复杂度,总时间复杂度就只有o(n) #set version: def find_unique_price_using_set(products): unique_price_set = set() for _,price in products: unique_price_set.add(price) return len(unique_price_set) products = [ (12345,100), (23456,30), (34567,150), (45678,30) ] print('number of unique price is {}'.format(find_unique_price_using_set(products))) #所以时间复杂度set更优 #为了更直观的了解时间复杂度,我们通过100,000个元素产品举例子 import time id = [x for x in range(0,100000)] price = [x for x in range(200000,300000)] products = list(zip(id,price)) print(len(products)) #计算列表版本的时间 start_using_list = time.perf_counter() find_unique_price_using_list(products) end_using_list = time.perf_counter() print("time elapse using list:{}".format(end_using_list - start_using_list)) #结果是:time elapse using list:40.69249 #计算集合版本的时间 start_using_list = time.perf_counter() find_unique_price_using_set(products) end_using_list = time.perf_counter() print("time elapse using list:{}".format(end_using_list - start_using_list)) #结果是:time elapse using list:0.009066700000005312 #可以看到当用户数量级增加到十万时,两者速度差异就非常大。 d = {'name':'jason',('education'):['Tsinghua University','Stanford Unveristy']} print(d)
n=int(input("enter the number=")) for i in range(n): for j in range((n//2)+1): if (j==0) or (i==0 or i==n-1): print("*",end=" ") else: print(" ",end=" ") print()
# Flash one LED - using python rev 3 # Writen by Ray Eacott import RPi.GPIO as GPIO # import import time GPIO.setmode(GPIO.BOARD) # set RPi to use pin numbers GPIO.setwarnings(False) # switch off error messages GPIO.setup(12, GPIO.OUT) # setup pin 12 as output for loop in range(1, 10): # repeat 10 times GPIO.output(12, True) # switch on LED time.sleep(1) # wait 1 second GPIO.output(12, False) # switch off LED time.sleep(1) # wait 1 second next GPIO.cleanup() # reset GPIO program
def ndigits(x): """ Counts the number of digits in x :param x: positive or negative integer to count digits from :return: number of digits in x """ if abs(x) < 10: return 1 return 1 + ndigits(abs(x)/10)
# Anything below here are for testing purpose only balance = 3329 annualInterestRate = 0.2 # End of testing stuff import math def calcEndOfYearBalance(balance, annualInterestRate, monthlyPayment): """ Calculates the credit card balance after one year for the given monthly payment :param balance: the outstanding balance on the credit card :param annualInterestRate: annual interest rate as a decimal :param monthlyPayment: minimum monthly payment rate as a decimal :return: """ monthly_interest_rate = annualInterestRate / 12.0 for month in range(12): balance -= monthlyPayment balance += monthly_interest_rate * balance return balance def calculateMinFixedMonthlyPayment(balance, annualInterestRate): """ Calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months :param balance: the outstanding balance on the credit card :param annualInterestRate: annual interest rate as a decimal """ balance_with_interest = balance + (balance * annualInterestRate) monthly_payment = 0 monthly_payment += int( math.ceil(((balance_with_interest / 13.0) - ((balance_with_interest / 13.0) % 10)) / 10.0) * 10) while calcEndOfYearBalance(balance, annualInterestRate, monthly_payment) > 0: monthly_payment += 10 print "Lowest Payment: " + str(monthly_payment) calculateMinFixedMonthlyPayment(balance, annualInterestRate)
import math def primes(n=1000000): n = 1000000 arr = [True for x in xrange(0,n+1)] arr[0] = False # not prime arr[1] = False # not prime for i in xrange(2, int(math.sqrt(n))+1): pr = i # this is prime for j in xrange(2*pr, n+1, pr): arr[j] = False return (i for i in xrange(n+1) if arr[i] == True) def is_circular(n, primes): """Find all rotations of n and check if prime""" strn = str(n) for i in xrange(len(strn)): strn = strn[-1]+strn[:-1] if int(strn) not in primes: return False return True all_primes = list(primes()) print len(all_primes) circular_primes = [x for x in all_primes if is_circular(x, all_primes)] print len(circular_primes)
import math def how_many_divisors(n): num_divisors = 0 sq = int(math.sqrt(n)) for i in xrange(1,sq): if n%i == 0: num_divisors += 2 if n%sq == 0: num_divisors += 1 return num_divisors n = 1 while True: tr = n * (n+1) / 2 if how_many_divisors(tr) > 500: print tr break n = n+1
import tkinter from tkinter import messagebox def wanna_quit(): if messagebox.askyesno("Quit", "Do you really want to quit?"): # the user clicked yes, let's close the window root.destroy() root = tkinter.Tk() root.protocol('WM_DELETE_WINDOW', wanna_quit) root.mainloop()
import functools import tkinter from tkinter import ttk def print_hello_number(number): print("hello", number) root = tkinter.Tk() big_frame = ttk.Frame(root) big_frame.pack(fill='both', expand=True) for i in range(1, 6): button = ttk.Button(big_frame, text="Hello %d" % i, command=functools.partial(print_hello_number, i)) button.pack() root.mainloop()
def linear_search(item,my_list): found = False i=0 while i<len(my_list) and found == False: if my_list[i] == item: found=True else: i=i+1 return found lista_prueba = [1,5,9,15,25,346,932] print(linear_search(65,lista_prueba)) print(linear_search(1,lista_prueba))
def chocolateFeast(n, c, m): chocolates = n // c wrappers = n // c while wrappers >= m: chocolates += wrappers // m wrappers = (wrappers // m) + (wrappers % m) return chocolates if __name__ == '__main__': t = int(input()) for test in range(t): ncm = [int(inp) for inp in input().split()] n = ncm[0] c = ncm[1] m = ncm[2] print(chocolateFeast(n, c, m))
def collatz(n): while n != 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 return True if __name__ == '__main__': for i in range(1, 10000): print("{}: ".format(i) + str(collatz(i)))
def powerSum(X, N, count): if count<((X**0.5)+1): if X<0: return 0 elif X==0: return 1 if (X-(count**N))>=0: return powerSum(X-(count**N),N,count+1)+powerSum(X,N,count+1) else: return powerSum(X,N,count+1) return 0 X = int(input()) N = int(input()) count = 1 result = powerSum(X, N,count) print(result)
class Node: def __init__(self, value): self.value = value self.parent = None self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, value): if self.root == None: self.root = Node(value) else: return self._insert(self.root, value) def _insert(self, currentNode, value): if value < currentNode.value: if currentNode.left == None: currentNode.left = Node(value) currentNode.left.parent = currentNode else: return self._insert(currentNode.left, value) elif value > currentNode.value: if currentNode.right == None: currentNode.right = Node(value) currentNode.right.parent = currentNode else: return self._insert(currentNode.right, value) else: print('{} is already in tree.'.format(value)) def largestKey(self): if self.root != None: return self._largestKey(self.root) def _largestKey(self, currentNode): if currentNode.right == None: return currentNode.value else: return self._largestKey(currentNode.right) def smallestKey(self): if self.root != None: return self._smallestKey(self.root) def _smallestKey(self, currentNode): if currentNode.left == None: return currentNode.value else: return self._smallestKey(currentNode.left) def traverse(self, mode='pre'): if mode == 'pre': print('Pre-order Traversal') return self._preorder(self.root) elif mode == 'in': print('In-order Traversal') return self._inorder(self.root) else: print('Post-order Traversal') return self._postorder(self.root) def _preorder(currentNode): if currentNode != None: print(currentNode.value) self._preorder(currentNode.left) self._preorder(currentNode.right) def _inorder(currentNode): if currentNode != None: self._preorder(currentNode.left) print(currentNode.value) self._preorder(currentNode.right) def _postorder(currentNode): if currentNode != None: self._preorder(currentNode.left) self._preorder(currentNode.right) print(currentNode.value)
def partition(array: list) -> list: p = array[0] less = [] grt = [] for i in range(1, len(array)): if array[i] < p: less.append(array[i]) else: grt.append(array[i]) ans = quickSort(less) + [p] + quickSort(grt) print(' '.join(map(str, ans))) return ans def quickSort(array: list) -> list: if len(array) > 1: return partition(array) return array if __name__ == '__main__': n = int(input()) lst = [int(inp) for inp in input().split()] quickSort(lst)
def sequenceEquation(n, inp): ans = list() for i in range(1, n + 1): x = inp.index(i) + 1 ans.append(inp.index(x) + 1) return ans if __name__ == '__main__': n = int(input()) inp = [int(i) for i in input().split()] for i in sequenceEquation(n, inp): print(i)
def timeInWords(h,m): words = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine", "thirty"] if h > 12: h %= 12 if (m == 0): return words[h - 1] + " o' clock" elif(m == 15): return "quarter past " + words[h - 1] elif(m == 30): return "half past " + words[h] elif(m == 45): return "quarter to " + words[h] elif(m == 1): return words[m - 1] + " minute past " + words[h - 1] elif(m > 1 and m < 30): return words[m - 1] + " minutes past " + words[h - 1] elif(m > 30 and m < 60): return words[59 - m] + " minutes to "+ words[h] h = int(input()); m = int(input()); result = timeInWords(h,m); print(result);
#!/bin/python3 import os import sys def handshake(n): sum1 = 0 for i in range(n-1,0,-1): sum1 += i return sum1 t = int(input()) for t_itr in range(t): n = int(input()) result = handshake(n) print(result)
def versionCheck(version1, version2): if version1[0] > version2[0]: return True elif version1[0] < version2[0]: return False elif len(version1) > 1: return versionCheck(version1[1:], version2[1:]) else: return 'Same' if __name__ == '__main__': version1 = [int(i) for i in input('Enter version1: ').split('.')] version2 = [int(i) for i in input('Enter version2: ').split('.')] if versionCheck(version1, version2) == 'Same': print('Same Version') elif versionCheck(version1, version2): print('{} is newer than {}.'.format('.'.join([str(i) for i in version1]), '.'.join([str(i) for i in version2]))) else: print('{} is newer than {}.'.format('.'.join([str(i) for i in version2]), '.'.join([str(i) for i in version1])))
def countingValleys(n, s): start = 0 valleys = 0 for i in range(len(s)): if s[i] == 'U': start += 1 elif s[i] =='D': if start == 0: valleys += 1 start -= 1 return valleys n = int(input()) s = input() result = countingValleys(n, s) print(result)
from math import sqrt, ceil def checkPrime(num): if num == 1: return False elif num == 2: return True elif num % 2 == 0: return False for i in range(3, ceil(sqrt(num)) + 1): if num % i == 0: return False return True def sortPrime(inp): inp.sort() for i in inp: if checkPrime(i): yield(i) def main(): inp = [int(x) for x in input().split()] result = sortPrime(inp) print("The entered prime numbers in ascending order are: ") for i in result: print(i) if __name__ == '__main__': main()
import math def func(x,y): return (y-1)**(0.5) pi = 3.14159 a = 0 b = 2 h = (b-a)/4 x = 0 y = 5 while x!=b: y1 = y + h*func(x,y) print(y1) y = y + (h/2)*(func(x,y)+func(x+h,y1)) print(y) x+=h
#Object Oriented Programming class Employee: raiseAmount = 1.05 empNum = 0 def __init__(self, first: str, last: str, pay: float) -> None: self.first = first self.last = last self.email = first + '.' + last + '@company.com' self.pay = pay Employee.empNum += 1 def getFullName(self) -> None: return self.first + ' ' + self.last @classmethod def setRaiseAmount(cls, amount: float) -> None: cls.raiseAmount = amount if __name__ == '__main__': emp1 = Employee('Pratik', 'Rajbhandari', 50000) emp2 = Employee('Test', 'User', 12345) Employee.setRaiseAmount(1.15) print(Employee.raiseAmount) print(emp1.raiseAmount) print(emp2.raiseAmount)
def checkJulianLeap(year): if year%4==0: return True else: return False def checkGeorgianLeap(year): if year%400==0: return True elif year%100==0: return False elif year%4==0: return True def solve(year): if year == 1918: return("26.09." + str(year)) elif year < 1918: if checkJulianLeap(year): return ("12.09." + str(year)) else: return ("13.09." + str(year)) elif year>1918: if checkGeorgianLeap(year): return ("12.09." + str(year)) else: return ("13.09." + str(year)) year = int(input()) result = solve(year) print(result)
import deck import human import ai import RandAI import random import hand_graph import reduce_ai import better_bogo import compete_ai """ What do we need to run a game of five crowns? Initialize the deck each round to a shuffled state Keep track of the round to know how many cards to deal out. Need to be able to store the state of each player's hand. Need to be able to recognize when a hand can go out, might want to provide some sort of automatic hand sorting to make it more obvious. Need to be able to group up cards into runs and sets. Recognize wild cards. Players need to be able to discard. What functionality do we want in the game class versus the player class. Game needs to be able to recognize legitimate hands that can go out Method summary: Init initializes the game, with how many players. Each player needs a list to keep track of the cards currently in their hand Main game running needs to: Deal out the next hand after someone has gone out and everyone got another turn Keep track of each player's score. Track which cards are in the discard pile Player functions that are needed: Draw, and select if they draw from the deck or the discard pile Discard after drawing. Determine sets within their hand. Go out (automatically?) once all cards are put into sets. """ class FiveCrowns: # Players is a list of players def __init__(self, players, test_deck=False, output_hands=None, output_scores=None, output_data=None, print_out=True): self.deck = deck.Deck() self.is_out = False turn_count = 0 self.round_num = 0 if test_deck: self.deck.test_deck() if output_scores is not None: output_scores = open(output_scores, "a") if output_data is not None: output_data = open(output_data, "a") # Meat and potatoes loop that goes through all the rounds, # deals cards, draws cards, discards cards. for self.round_num in range(3, 14): if print_out: print("{0}'s round".format(self.round_num)) self.is_out = False self.deal(self.round_num, players, test_deck) self.discard_pile = [self.deck.draw()] rnd_turn = 0 first_deal = random.randint(0, len(players)) while not self.is_out: # Need the first person of each round to rotate as the deal rotates j = 0 while j < len(players): j += 1 i = (self.round_num%len(players) + j + first_deal) % len(players) if self.deck.isEmpty(): self.deck = deck.Deck(random.shuffle(self.discard_pile)) players[i].draw(self) self.discard_pile.append(players[i].discard(self)) if output_hands is not None: players[i].write_hand() if players[i].complete_hand(): self.is_out = True if output_hands is not None: players[i].write_hand() break turn_count += 1 rnd_turn += 1 j = 0 while j < len(players): j += 1 i = (self.round_num % len(players) + j) % len(players) if not players[i].complete: if self.deck.isEmpty(): self.deck = deck.Deck(random.shuffle(self.discard_pile)) players[i].draw(self) self.discard_pile.append(players[i].discard(self)) players[i].score += players[i].hand_value() if output_hands is not None: players[i].write_hand() for play in players: if print_out: print(play.score, end=" ") if output_scores is not None: output_scores.write(str(play.score)) output_scores.write(", ") if print_out: print("Turns: ", rnd_turn) if output_scores is not None: output_scores.write(str(rnd_turn)) output_scores.write("\n") for play in players: if print_out: print(play.name, " score:", play.score) if output_data is not None: output_data.write(str(play.score)) output_data.write(", ") if output_data is not None: output_data.write(str(first_deal)) output_data.write("\n") if output_data is not None: output_data.close() if output_scores is not None: output_scores.close() if print_out: print("Average turns: ", turn_count/11) def deal(self, round_num, players, test_deck=True): # Resets the hand for the player for play in players: play.hand = [] # Deals out new cards from the top of the deck to players if test_deck: self.deck.test_deck() else: self.deck.__init__() for cards in range(round_num): for play in players: play.hand.append(self.deck.draw()) def card_to_string(self, card): out_string = "('" out_string += card[hand_graph.SUIT_IDX] out_string += "', " out_string += str(card[hand_graph.VAL_IDX]) out_string += ", " out_string += str(card[hand_graph.DECK_IDX]) out_string += ") " return out_string if __name__ == "__main__": player1 = RandAI.Player("Random") player2 = compete_ai.Player("Compete") player3 = reduce_ai.Player("Reduce") player4 = better_bogo.Player("Better Bogo") FiveCrowns([player2, player4], test_deck=False, output_hands="hand_output")
import player import hand_graph POINT_VAL = 1 class Player(player.Player): def draw(self, game): self.hand.append(game.discard) def discard(self, game): groups = self.build_groups() worst_set = groups[0] # Checks if there is a card that is not connected to anything else. choice = self.most_useless_card() # If there is no useless card by itself, have to make a choice about what to discard if choice is not None: game.discard = self.hand.index(choice) return for item in groups: if item[POINT_VAL] > worst_set[POINT_VAL]: worst_set = item # Once the worst set is determined, sort it by point value and then throw out the highest one. choice = 0 game.discard = self.hand.pop(choice) # Finds the highest value card that does not have any neighbors. def most_useless_card(self, game, draw): graph = hand_graph.HandGraph() graph.find_edges(self.hand) useless = [] for node in graph.nodes: if len(node.edges) is 0: useless.append(node) if len(useless) > 0: useless.sort(key=lambda crd: crd[1]) pop = useless.pop() # Check to make sure that the most useless card is not a wild card (wild cards only have edges to other # wild cards) while hand_graph.HandGraph.wild_check(pop, game.round, draw=draw): pop = useless.pop() if not hand_graph.HandGraph.wild_check(pop, game.round, draw=draw): return pop else: return None else: return None # Objective: build the hand into the set of groups that reduce the score the most # Similar system to trying to go out. Attempt to build the longest set for each card. Prioritize sets that save # More points. When building these groups, will have an extra card in the hand so you have to account for that. # 2 groups of 3 in the 5s round is not useful. # Build a group, and then store the group and the points that it is saving or not into a tuple. # This method will be useful both for determining cards to discard and cards to draw. Will probably run for each of # those actions. What is the difference between when you have too many cards or not? def build_groups(self, drawn=True): graph = hand_graph.HandGraph() graph.find_edges(self.hand, drawn) # Keep track of nodes used in finished sets as well as nodes used in unfinished sets. groups = [] unused_nodes = [] reserved_nodes = [] useless = [] for node in graph.nodes: unused_nodes.append(node) while len(unused_nodes) > 0: if len(unused_nodes[0].edges) is 0: groups.append((unused_nodes.pop(0), unused_nodes[0].name[POINT_VAL])) else: # Generates the longest path possible with the available nodes new_sub_graph = graph.sub_graph(unused_nodes[0], unused_nodes, allow_any=True) # Checks if the subgraph was valid, and if it was removes the cards used from the available pile if len(new_sub_graph.nodes) >= 3: for sg_node in new_sub_graph.nodes: if unused_nodes.__contains__(sg_node): unused_nodes.remove(sg_node) # Have to determine the best way to use the cards that we have. First look if they can be used in a # complete set. # If the path was NOT valid, check conditions to see if a valid path could be made else: # If even using all the nodes a valid length path could not be made, return false if len(unused_nodes) is len(graph.nodes): return False longest_sub_graph = graph.sub_graph(unused_nodes[0], graph.nodes) if len(longest_sub_graph) < 3: return False # If a valid path COULD be made, reserve those nodes and try again. else: for card in longest_sub_graph.nodes: if reserved_nodes.__contains__(card): unused_nodes.pop(0) else: reserved_nodes.append(card) unused_nodes = graph.nodes # Return the set of groups and the set of useless cards. return groups + useless # Determine the card that will reduce the score of the hand the most def determine_need(self): return 2
# -*- coding: utf-8 -*- """ Created on Thu Oct 6 20:11:55 2016 @author: xzx @refer to Andrew Ng's code in Machine Learning class in coursera """ import numpy as np import math import matplotlib.pyplot as plt def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) def nnCostFunction(Theta1,Theta2,\ input_layer_size,hidden_layer_size, \ num_labels, X, y, lamb): m = float(X.shape[0]) a2 = np.mat(np.hstack((np.ones((m,1)),sigmoid(X * Theta1)))) a3 = sigmoid(a2 * Theta2) Y = np.zeros((int(m),num_labels)) for i in xrange(0,int(m)): Y[i][int(y[i])] = 1.0 J = -1/m * sum(sum(np.multiply(Y , np.log(a3)) + np.multiply((1 - Y) , np.log(1 - a3)))[:,0]) \ + lamb/(2*m) * ( np.multiply(Theta1[::,1::],Theta1[::,1::]).sum() + np.multiply(Theta2[::,1::], Theta2[::,1::]).sum() ) Delta1 = np.zeros(Theta1.shape) Delta2 = np.zeros(Theta2.shape) for t in xrange(0,int(m)): # print "couting:", t a1 = X[t,::] a2 = np.mat(np.hstack((np.ones((1,1)),sigmoid(a1 * Theta1)))) a3 = sigmoid(a2 * Theta2) delta3 = a3 - Y[t,::]; Delta2 = Delta2 + (delta3.T * a2).T delta2 = np.multiply(np.multiply((delta3 * Theta2.T) , a2)\ , (1 - a2)) Delta1 = Delta1 + (delta2[0, 1::].T * a1).T Theta1_grad = (Delta1 + lamb * Theta1)/m Theta2_grad = (Delta2 + lamb * Theta2)/m return J,Theta1_grad,Theta2_grad def predict(Theta1, Theta2, X): """ X should be original data(no bias unit) """ X = np.mat(np.hstack((np.mat(1),np.mat(X)))) h1 = np.mat(sigmoid(X * Theta1)) h2 = sigmoid( np.mat(np.hstack((np.mat(1),np.mat(h1)))) * Theta2) ######## #get the max in h2 return np.argmax(h2) def displayData(X,num = range(10)): """ DISPLAYDATA display 2Ddata in a nice grid by default display first 10 images of X """ X = X[num,::] example_width = int(round(math.sqrt(X.shape[1]))) m, n = X.shape example_height = int(n / example_width) display_rows = int(math.floor(math.sqrt(m))) display_cols = int(math.ceil(m / display_rows)) display_array = np.mat((1,1)) curr_ex = 0 for j in xrange(1,display_rows+1): horizontal = np.mat((1,1)) for i in xrange(1, display_cols+1): if curr_ex > m: break max_val = np.max(np.abs(X[curr_ex, ::])) display = X[curr_ex,::].reshape(example_height, example_width) / max_val curr_ex = curr_ex + 1 if horizontal.shape == (1,2): horizontal = display else : display = np.hstack((-np.ones((display.shape[0],1)), display)) horizontal = np.hstack((horizontal,display)) if display_array.shape == (1,2): display_array = horizontal else : horizontal = np.vstack((-np.ones((1,horizontal.shape[1])),horizontal)) display_array = np.vstack((display_array, horizontal)) if curr_ex > m : break im = plt.imshow(display_array) plt.show()
for i in range(5): print(i) for i in range(11, 19): print(i) # a step with range print(range(10, -100, -30)) # iterate over indices of a sequence # combine range() and len() a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) # behaves as a list but it isn't # it doesn't make the list print(range(10)) print(range(0, 10)) # function list() creates lists from iterables myList = list(range(5,11)) print(myList)
#Practice Chapter 5 - Modules + Turtle print("Jedi Turtle") import turtle turtle.forward(20) turtle. speed(50000000000000000) from turtle import * color('red', 'yellow') begin_fill() pensize(2) while True: forward(200) left(230) right(300) if abs(pos()) < 1: break end_fill() turtle.penup() turtle.left(23) turtle.pendown() color('Blue', 'Green') begin_fill() while True: forward(300) left(190) right(86) if abs(pos()) < 1: break done() #Conditionals a = 100 b = 50 if a > b: print("a is greater than b") if a < b: print("a is less than b") if a == b: print("a is equal to b") # Practicing lists - 04.28.21 # When using lists, one must use "[ , ]"" l1 = ["5", "2", "3", "3.4", "Banana", "Horse"] if "Banana" in l1: print("Fruit in list.") if "Banana" not in l1: print("No fruit found.")
# -*- coding: utf-8 -*- """ Created on Fri Jul 15 15:56:54 2022 @author: Aster Taylor This script provides a demonstration of how to add functions to the SAMUS class which provide data outputs. All functions must either take no inputs or take 'self', and use class variables. This script provides examples of both, and uses multiple data types. """ import SAMUS #defines function which doesn't use class variables def func(): return([1,"test"],["ones","string"]) #defines function which uses class variables def get_viscosity(self): return(float(self.mu),"viscosity") #create class mod_class=SAMUS.model("modularity_test",mu=10**4) #runs simulation for a brief period with only 1 time step per rotation frame=mod_class.run_model(1,data_name='example_traj', funcs=['moment_of_inertia','princ_axes', func,get_viscosity]) #prints DataFrame as demonstration print("Test Frame:") print(frame)
import os from utils import StringDistance, extract_digit class GenderCorrection: """Correct Religion based on input by comparing Levenshtein distance to tongiao.txt """ def __init__(self, cost_dict_path=None, gender_path = None): dir_path = os.path.dirname(os.path.realpath(__file__)) if cost_dict_path is None: cost_dict_path = os.path.join(dir_path, 'data', 'cost_char_dict.txt') if gender_path is None: gender_path = os.path.join(dir_path, 'data', 'gioitinh.txt') self.string_distance = StringDistance(cost_dict_path=cost_dict_path) self.genders = [] with open(gender_path, 'r', encoding='utf-8') as f: for line in f: entity = line.strip() if not entity: break entity = entity.split('\n') self.genders.extend(entity) self.genders = tuple(set(self.genders)) def correct(self, phrase, correct_phrases, nb_candidates=2, distance_threshold=40): candidates = [(None, distance_threshold)] * nb_candidates max_diff_length = distance_threshold for correct_phrase in correct_phrases: if abs(len(phrase) - len(correct_phrase)) >= max_diff_length: continue if extract_digit(correct_phrase) != extract_digit(phrase): distance = 100 else: distance = self.string_distance.distance(phrase, correct_phrase) if distance < candidates[-1][1]: candidates[-1] = (correct_phrase, distance) candidates.sort(key=lambda x: x[1]) return candidates def gender_correction(self, gender): if not isinstance(gender, str): raise ValueError("Only Str Input") gender = gender.replace('.', ' ') result = self.correct(gender, self.genders, nb_candidates=1, distance_threshold=20) if len(result) != 0: return result[0][0], result[0][1] else: return gender, -1 if __name__ == '__main__': a = GenderCorrection() print(a.gender_correction("nú"))
from ..algebra import AABB, Vector from ..fields import Cell, CellInterval def map_aabb_to_cell_interval(aabb, field_orig, field_res, field=None): """Maps an ``aabb`` to a ``CellInterval``of the ``field``. Parameters ---------- aabb: AABB The domain to be mapped. field_orig: Vector field_res: float Notes ----- Only if ``field`` is specified the returned CellInterval is ensured to be valid or empty in case aabb does not intersect with the field. """ c = CellInterval( (aabb.min-field_orig)//field_res, (aabb.max-field_orig)//field_res ) if field is not None: return field.cell_interval.intersection(c) return c def map_solids(solids, field, field_orig=Vector(0), field_res=Vector(1), solid_value=1, void_value=0): """Maps all ``solids`` onto the ``field``. Parameters ---------- Notes ----- In contrast to :func:`map_solid_volume_fraction` this function maps solids in a binary manner, i.e. the cell value will be set to either ``solid_value`` or ``void_value`` depending on whether the cell center is inside the solid. """ for solid in solids: cell_interval = map_aabb_to_cell_interval(solid.aabb, field, field_orig, field_res) for cell in cell_interval: cell_center = field_orig + field_res * (Vector(cell) + Vector(0.5)) if solid.contains(cell_center): field[cell] = solid_value def map_solid_volume_fraction(solids, field, level=1, field_orig=Vector(0), field_res=Vector(1)): """Maps the solid volume fraction of ``solids`` onto the ``field``. Parameters ---------- solids: array-like The set of solids that will be mapped. field: Field The field onto which the solids will be mapped. level: int The octree level during mapping. If level == 0, this function is equivalent to calling :func:`map_solids` with ``solid_value`` = 1. field_orig: Vector The origin of the field. field_res: Vector The resolution of the field. """ if level == 0: map_solids(solids, field, field_orig, field_res, solid_value=1) return dv = 1./8**level for solid in solids: cell_interval = map_aabb_to_cell_interval(solid.aabb, field, field_orig, field_res) for cell in cell_interval: solid_fraction = 0.0 cell_aabb = AABB(cell, cell.shifted(1)).scaled(field_res).shifted(field_orig) # loop through all octree elements of the cell and test if # cell center is inside solid for sub in cell_aabb.iter_subs(level): if solid.contains(sub.center): solid_fraction += dv # set cell value field[cell] += solid_fraction
import re # 1-3 a: abcde is valid: position 1 contains a and position 3 does not. # 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b. # 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c. x = 0 y = 0 passWords = open('day2.input') for line in passWords: policy = re.findall(r'\d+', line) policy = [int(i) for i in policy] letter = re.findall(r'(?i)\b[a-z]\b', line) word = re.findall(r'\b[a-z]*$\b', line) letter = letter[0] word = word[0] policy1 = policy[0] policy2 = policy[1] y += 1 if letter in word[policy1-1] and letter not in word[policy2-1] or letter in word[policy2-1] and letter not in word[policy1-1]: x +=1 print(y, word, x)
from numpy import arange import random from math import ceil # code for emulating competitions with different difficulty levels # we will add the levels of the competition and their difficulty coefficient to the dictionary lvl_compt = { 'street': [0.95, 0.0375, 0.0125, 0, 0], 'town': [0.6, 0.3, 0.1, 0, 0], 'city': [0.1, 0.3, 0.5, 0.1, 0], 'region': [0, 0.1, 0.6, 0.2, 0.05], 'country': [0, 0, 0.2, 0.6, 0.2], 'world': [0, 0, 0, 0.2, 0.8], 'olympic': [0, 0, 0, 0.1, 0.9] } # we request the necessary data to run the program # we catch the error by checking the entered value with valid keys from the mode dictionary while True: user_lvl = input('Select the level of competition - Street, Town, City, Region, Country, World, Olympic:\n').lower() if user_lvl in lvl_compt: break else: print('You have entered the wrong mode, please try again') # сatching the error by checking against two values while True: mode = input('Select mode - time, point:\n').lower() if mode == 'time' or 'point': break else: print('You have entered the wrong mode, please try again') # only a digital value is needed, check with float() while True: qual = input('Enter the time of the qualifying stage (if not, then the worst result):\n') try: float(qual) except ValueError: print('Enter a numerical value') continue break while True: record = input('Enter the record figure (if not, then the maximum possible):\n') try: float(record) except ValueError: print('Enter a numerical value') continue break while True: players = int(input('Enter the number of participants:\n')) try: float(players) except ValueError: print('Enter a numerical value') continue break # create lists for time and points mode if mode == 'time': scale = [round(num, 2) for num in arange(float(qual) * 1.01, float(record) * 0.99, -0.01)] else: scale = [i for i in range(round(int(qual) * 0.99), round(int(record) * 1.01))] def Generating(stage): """ The function generates 5 sublists of equal size from the general list. """ n = ceil(len(stage) / 5) for i in range(0, len(stage), n): dip = stage[i:i + n] if len(dip) < n: dip += [None for q in range(n - len(dip))] yield dip def Choice(scale_dip): """ The function selects a random number from a shuffled list, which, in turn, was selected at random using the weights specified in the parameters. """ weights = lvl_compt[user_lvl] lst = random.choices(scale_dip, weights=weights)[0] random.shuffle(lst) return random.choices(lst) # randomly simulate the user's place in the competition user_place_in_compt = random.randint(1, players) # create a list for the results of the opponents resultation = [] # we create a competition using a loop, # while the user will have to enter his result in real time, depending on his performance position for i in range(1, players + 1): if i == user_place_in_compt: user_score = float(input('Enter your result: ')) else: tmp = Choice(list(Generating(scale)))[0] # fix the bug as "not a bug but a feature" if tmp is None: print(f'Player {i} is disqualified') players -= 1 else: print(f'Opponent Result №{i} - {tmp}') resultation.append(tmp) final_point = 0 # scoring algorithm for different modes if mode == 'point': for j in resultation: if j <= user_score: final_point += 1 else: for j in resultation: if j >= user_score: final_point += 1 print(f'You took {players - final_point} place')
import random import sys import time from decimal import Decimal from discount_rules import buy_two_apples_get_one_free, five_off_when_you_spend_hundred_or_more from enums import UnitType from factories import GroceryFactory from objects import Grocery, Basket, Store, Discount def _random_price(): return round(Decimal(random.randrange(10, 1000) / 100), 2) def _random_quantity(natural_number=True): if natural_number: return Decimal(random.randint(1, 40)) return round(Decimal(random.randrange(10, 1000) / 100), 2) def _delay_print(message, delay=0.03): for character in message: sys.stdout.write(character) sys.stdout.flush() time.sleep(delay) print('\n') def generate_groceries(): all_groceries = [Grocery('Apples', price_per_unit=Decimal('1.20'), quantity=Decimal('3'))] all_groceries += [GroceryFactory(price_per_unit=_random_price(), quantity=_random_quantity(False), unit_type=UnitType.KILOGRAM) for _ in range(7)] all_groceries += [GroceryFactory(price_per_unit=_random_price(), quantity=_random_quantity(), unit_type=UnitType.UNIT) for _ in range(7)] return sorted(all_groceries) def generate_store(): return Store(discounts=[Discount(rule=buy_two_apples_get_one_free)]) def print_intro(): print('Hello and welcome to my store!') print("My name is Wout, I'll guide you around.") print('I have a crazy assortment of goods, and when I say crazy I mean it.') print("Check it out! I've ordered them from cheap to expensive.") print('Also try the apples, they are delicious. If you buy 3, you get 1 for free!') def print_options(): print('--') for index, grocery in enumerate(all_groceries): print(f'{index}) {grocery}') print('--') def get_choice(): print('Please make a selection of items you want to buy.') print('Example: for item 1 6 and 10, type: `1 6 10`') choice = [] while(not choice): try: choice = [int(i) for i in input('Your choice: ').rstrip().split(' ') if len(all_groceries) > int(i) >= 0] choice = sorted(list(set(choice))) # Sort and get rid of any duplicates if not choice: print("I don't know these numbers.") except ValueError: # Very naughty print('Nice try, use numbers only.') print('') print('') return choice def generate_basket(choice): return Basket([all_groceries[i] for i in choice]) def print_basket(): print("You've chosen the following items:") print('--') print(basket) print('--') print('Nice choice ;)') print('') print('Now, maybe you have some coupon with you?') def get_extra_discounts(): valid_coupon_code = 'WineDirect' time.sleep(2.50) _delay_print(f"------ A gollum wispers in your ear: " f"'Hint, enter the coupon code `{valid_coupon_code}` for $5 off if your order is larger than $100.'") coupon_code = input('Coupon code: ') extra_discounts = [] if coupon_code.lower() == valid_coupon_code.lower(): extra_discounts += [Discount(rule=five_off_when_you_spend_hundred_or_more)] print('That looks like a valid coupon code! I wonder where you got it from..') else: print("Hmm I don't know this coupon code, better luck next time!") return extra_discounts def generate_receipt(extra_discounts): return store.checkout(basket, extra_discounts=extra_discounts) def print_receipt(): time.sleep(1) _delay_print('Let me just count them up, give me a second...') time.sleep(1) _delay_print('Done! Here is your receipt.') time.sleep(0.5) print('') print('') print('RECEIPT') print('--------------------------------------------------') print(receipt) print('--------------------------------------------------') print('') print('') time.sleep(2) def print_door(): _delay_print('Thank you!') time.sleep(1) _delay_print("Here's the door.") print('''\ ______________ |\ ___________ /| | | /|,| | | | | | |,x,| | | | | | |,x,' | | | | | |,x , | | | | |/ |%==| | | | /] , | | | | [/ () | | | | | | | | | | | | | | | | | | | ,' | | | | ,' | | |_|,'_________|_| ''') print('') input('Press any key to exit.') all_groceries = generate_groceries() store = generate_store() print_intro() print_options() basket = generate_basket(get_choice()) print_basket() receipt = generate_receipt(get_extra_discounts()) print_receipt() print_door()
# # we want to show in e.g. M if there is at least 1 M, that is, optimal so that # number/(1000^optimalExp) >= 1 # mathematics->logarithms-> # optimalExp = log(number) / log(1000); # import math units = ['','k','M','G','T','P','E','Z','Y'] def formatNumber (number, decimals = 2) : optimalExp = math.floor( math.log(number) / math.log(1000) ) number = number / (1000 ** optimalExp) return str(round(number, decimals)) + units[optimalExp] inputNumber = int(input('number: ')) print(formatNumber(inputNumber))
import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np def evaluate_agents(num_runs, num_steps, agents, mab, agent_names=None): """ Function to call each agent on a given MAB for a pre-specified number of runs and timesteps for each run. By comparing these multiple times against the same MAB, we can get a sense of how they would perform on average to a similar type of problem. The rewards at each time step are averaged across each run per agent, and plotted alongside each other. Additionally, a metric we like to care about is if the agent is able to identify the optimal arm, and how often it chooses it. The pct of the time the agent chose the optimal arm at each timestep is also plotted for comparison. Args: num_runs : int, number of runs to do for each agent num_steps : int, number of steps to walk through in each run agents : list of ActionValueMethod, list of instantiated agents to compare mab : MAB, instantiated MAB to compare agents against agent_names : list of str, optional list of names to add to legend of comparison plots, otherwise defaults to agent_00x in order of agents """ if agent_names is None: agent_names = ['agent_{:3d}'.format(i) for i in range(len(agents))] steps = [i for i in range(num_steps)] avg_rewards = [] avg_pct_optimals = [] for agent in agents: avg_reward, avg_pct_optimal = evaluate_agent(num_runs, num_steps, agent, mab) avg_rewards.append(avg_reward) avg_pct_optimals.append(avg_pct_optimal) for reward in avg_rewards: plt.plot(steps, reward) plt.title('Average rewards') plt.legend(agent_names) plt.show() for avg_pct_optimal in avg_pct_optimals: plt.plot(steps, avg_pct_optimal) plt.title('Average pct optimal arm') plt.legend(agent_names) plt.show() def evaluate_agent(num_runs, num_steps, agent, mab): rewards = np.zeros(shape=(num_runs, num_steps), dtype=np.float32) optimal_arm = int(np.argmax([mu for mu, sigma in mab.bandits])) pct_optimal = np.zeros(shape=(num_runs, num_steps), dtype=np.float32) for i in range(num_runs): agent.reset() for j in range(num_steps): action = agent.act() reward = mab.pull_bandit(action) rewards[i, j] = reward pct_optimal[i, j] = agent.counts[optimal_arm] / np.sum(agent.counts) agent.update(action, reward) return np.mean(rewards, axis=0), np.mean(pct_optimal, axis=0) def ucb_race_chart(steps, ucb, mab, outfile, fps=30): """ Runs a UCB agent for a number of steps against an MAB and creates an output gif showing the estimated value of each arm according to the agent along with the uncertainty. Args: steps : int, number of steps to create the gif for ucb : UpperConfidenceBound mab : MAB outfile : str, name of output file, should end in .gif, but the commented out line would allow for an output of a .mp4 file as well fps : int, frames per second, divide steps by fps to get length in seconds of output file """ num_arms = len(mab.bandits) arm_pulls = [0] * num_arms for _ in range(num_arms): arm = ucb.act() reward = mab.pull_bandit(arm) ucb.update(arm, reward) indices = np.arange(num_arms) ylim = max([mu for mu, sigma in mab.bandits]) * 1.7 def draw_ucb_chart(frame_num): ax.clear() ax.set_ylim(-1, ylim) p1 = ax.bar(indices, ucb.get_q_values()) p2 = ax.bar(indices, ucb.get_uncertainty_values(), bottom=ucb.get_q_values()) ax.set_xlabel('UCB Arm') plt.title('UCB Average Rewards and Upper Bounds Step {:3d}'.format(frame_num)) plt.legend((p1[0], p2[0]), ('Average Rewards', 'Uncertainty'), loc='upper right') arm = ucb.act() arm_pulls[arm] += 1 reward = mab.pull_bandit(arm) ucb.update(arm, reward) count_text = '' for arm, count in enumerate(arm_pulls): count_text += 'Arm {}: {:03d}\n'.format(arm, count) ax.text(0.9, 0.4, count_text, fontsize=14, transform=plt.gcf().transFigure) plt.subplots_adjust(right=0.85) fig, ax = plt.subplots(figsize=(12, 8)) animator = animation.FuncAnimation(fig, draw_ucb_chart, frames=range(steps)) animator.save(outfile, dpi=80, writer='imagemagick') # animator.save(outfile, fps=fps, extra_args=['-vcodec', 'libx264'])
for n in range(11): print(n) controlador = 0 while (controlador <= 10): print(controlador) controlador += 1
products = [] while True: name = input ("Fil in the product name: ") if name == "q": break price = input ("Fill in the product price: ") products.append([name, price]) print(products) for p in products: print(p[0], "price is", p[1])
from functools import reduce class Matrix(list): """ По своей сути обычный список с дополнительной проверкой в конструкторе и методом """ def __init__(self, matrix): if len(matrix) != len(matrix[0]): raise ValueError('Идиот, матрица должна быть квадратной') super().__init__(matrix) def pos_vertex(self, vertex): """ По объекту vertex возвращает число, соотвествующее позиции в matrix :param vertex: int или vertex :return: int """ if isinstance(vertex, Vertex): vertex = vertex.pos if vertex < 0 or vertex >= super().__len__(): raise ValueError('Вершина не принадлежат базовому графу') return vertex class Vertex(object): def __init__(self, matrix: Matrix, pos: int): self.matrix = matrix self.pos = pos @property def pos(self): return self._pos @pos.setter def pos(self, value): self._pos = self.matrix.pos_vertex(value) def __eq__(self, other): # Это нужно, чтобы можно было сравнивать вершини как vertex_1 == vertex_2 return self.matrix is other.matrix and self.pos == other.pos def distance(self, vertex): if vertex.matrix is not self.matrix: raise ValueError('Вершины должны принадлежать одному графу') return self.matrix[self.pos][vertex.pos] def __repr__(self): return f"V(matrix=<matrix at {id(self.matrix)}>, pos={self.pos})" def __str__(self): return f"V = {self.pos:>3}" class Graph(object): """ По своей сути подграф какого-то графа (сам граф представлется матрицей смежности). Если в контсруктор не передать списков вершин этого подграфа, то будет считаться, что подграф. является полным графом и будет содержать все вершины. Для внуртеннего предстваления вершин используется списков целых чисел, однако большинство методов поддерживают как и объекты вершин, так и целые цисла, которые их характеризуют """ def __init__(self, matrix: Matrix, vertex_lst=None): self.matrix = matrix self.vertex_lst = vertex_lst or list(range(len(matrix))) def __getitem__(self, vertex): # Обращаемся к графу graph[4] и получаем объект 4 вершини. Если она есть в этом графе return Vertex(self.matrix, self.pos_vertex(vertex)) @property def raw_vertex_lst(self): """ Возращает внутреннее представление вершин (int). И даже не пытайтесь из поменять. Не получится, вахахаха :return: (0, 1, 4, 5 ... ) """ return tuple(self._vertex_lst) @property def vertex_lst(self): """ Возращает список объектов вершит :return: [vertex_0, vertex_1, ... ] """ return [Vertex(self.matrix, x) for x in self._vertex_lst] @vertex_lst.setter def vertex_lst(self, vertex_lst): """ Для установки новых вершин graph.vertex_lst = [1, 3, 5] или graph.vertex_lst = [vertex_1, vertex_2, ...] :param vertex_lst: :return: None """ if not isinstance(vertex_lst, list): raise TypeError('Список вершин должен быть списком') self._vertex_lst = [self.matrix.pos_vertex(x) for x in vertex_lst] def pop(self, vertex): """ Удаляет из подграфа вершину :param vertex: int или vertex :return: vertex """ del self._vertex_lst[self._vertex_lst.index(self.pos_vertex(vertex))] return Vertex(self.matrix, vertex) def add(self, vertex): """ ДОбавляет в подграф вершину :param vertex: int или vertex :return: vertex """ self._vertex_lst = sorted(self._vertex_lst + [self.matrix.pos_vertex(vertex)]) return Vertex(self.matrix, vertex) def pos_vertex(self, vertex): """ Возвращает число, для внутреннего представления вершины и делает проверку на принадлежность :param vertex: int или vertex :return: int """ if isinstance(vertex, Vertex): vertex = vertex.pos if vertex not in self.raw_vertex_lst: raise ValueError('Данная вершина не принадлежить этому графу') return vertex def __iter__(self): """ Это, чтобы было удобно итерароваться по вершинам подграфа через for """ return (Vertex(self.matrix, x) for x in self._vertex_lst) def __len__(self): return len(self._vertex_lst) def __repr__(self): """ Красивая печать подграфа :return: str """ matrix = "\n".join(map(lambda x: f"\t{str(x)}", self.matrix)) return f'Graph(matrix=[\n{matrix}\n], vertex_lst={self._vertex_lst})' def __sub__(self, other): """ Вычитание одного подграфа из другого :param other: graph :return: graph """ vertex_lst = [x for x in self._vertex_lst if x not in other.raw_vertex_lst] return self.__class__(self.matrix, vertex_lst) class SegGraph(Graph): """ Это Конкретная реализация графа с прикладными методами для решения задачи компановки """ def delta(self, vertex): """ показывает, насколько уменьшится число внешних связей куска графа если из него удалить вершину vertex """ pos = self.pos_vertex(vertex) return 2 * sum( self.matrix[pos][x] for x in self.raw_vertex_lst ) def p(self, vertex): """ Локальное значение p """ pos = self.pos_vertex(vertex) return sum(self.matrix[x][pos] for x in self.raw_vertex_lst) def bound(self, vertex): """ Возвращает связанные вершины подграфа :param vertex: vertex or int :return: [vertex_1, vertex_2, ... ] """ pos = self.pos_vertex(vertex) row = self.matrix[pos] return [ Vertex(self.matrix, x) for x in self.raw_vertex_lst if row[x] != 0 or x == pos ] def alpha(self, other, vertex): """ Для итерационной компановки :param other: graph :param vertex: vertex or int :return: int """ return sum( reduce(lambda a, x: a + ( -vertex.distance(x) if vertex in graph else vertex.distance(x)), graph, 0) for graph in (self, other) )
def yes_or_no(): count = 2 while True: if count % 2: yield 'no' else: yield 'yes' count += 1 def yes_or_no(): answer = "yes" while True: yield answer answer = "no" if answer == "yes" else "yes" gen = yes_or_no() print(next(gen)) # 'yes' print(next(gen)) # 'no' print(next(gen)) # 'yes' print(next(gen)) # 'no'
def be_polite(fn): def wrapper(): print("What a pleasure to meet you!") fn() print("Have a great day!") return wrapper @be_polite def greet(): print("My name is Norberto.") @be_polite def rage(): print("I HATE YOU!") greet = be_polite(greet) polite_rage = be_polite(rage) polite_rage() # now call functions taking advantage of decorator greet() rage()
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 1/3, random_state = 0) print(f"X_train = {X_train}") print(f"X_test = {X_test}") print(f"Y_train = {Y_train}") print(f"Y_test = {Y_test}") print() # Simple Linear Regressor ## The squared differences are calculated instead of the absolute differences because it makes the calculation of the first derivative of the loss error function easier. ## Feature Scaling is not required because the prediction is a simple linear combination where the coefficients can adapt their scale to put everything on the same scale. ## Understanding the P-Value ### The Null Hypothesis is the assumption that the parameters associated to the independent variables are equal to zero. #### Under this assumption, the observations are random and don't follow a certain pattern. ### The P-Value is the probability that the parameters associated to the independent variables have certain nonzero values given that the Null Hypothesis is true. ### The P-Value is a statistical metric: the lower its value, the more statistically significant is an independent variable (how much better a predictor it will be). ### The P-Value only applies to linear models. # Create and train Simple Linear Regression model from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, Y_train) # Predict Test Set results Y_predict = regressor.predict(X_test) # Output Training Set results plt.scatter(X_train, Y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary v. Years of Experience (Training Set)') plt.xlabel('Years of Experience (years)') plt.ylabel('Salary ($)') plt.savefig('Salary_v_Years_of_Experience_(Training_Set).png') plt.clf() # Output Test Set results plt.scatter(X_test, Y_test, color = 'red') plt.plot(X_test, Y_predict, color = 'blue') plt.title('Salary v. Years of Experience (Test Set)') plt.xlabel('Years of Experience (years)') plt.ylabel('Salary ($)') plt.savefig('Salary_v_Years_of_Experience_(Test_Set).png') plt.clf() # Predict salary with 12 years of experience print(f"Salary w/ 12 YoE = {regressor.predict([[12]])}\n") # Print simple linear regressor coefficient and intercept print(f"Coefficient = {regressor.coef_}") print(f"Intercept = {regressor.intercept_}")
#Using list comprehension def triple_and_filter(listOfNums): return [num * 3 for num in list(filter(lambda x: not x % 4, listOfNums))] #Using map function def triple_and_filter(lst): return list(filter(lambda x: x % 4 == 0, map(lambda x: x*3, lst))) print(triple_and_filter([1, 2, 3, 4]))
class User: active_users = 0 def __init__(self, first, last, age): self.first = first self.last = last self.age = age User.active_users += 1 def __repr__(self): return f"{self.first} is {self.age}" @classmethod def display_active_users(cls): return f"There are currently {cls.active_users} active users." @classmethod def from_string(cls, data_str): first, last, age = data_str.split(",") return cls(first, last, int(age)) def logout(self): User.active_users -= 1 return f"{self.first} has logged out" def full_name(self): return f"{self.first} {self.last}" def initials(self): return f"{self.first[0]}.{self.last[0]}." def likes(self, thing): return f"{self.first} likes {thing}" def is_senior(self): return self.age >= 65 def birthday(self): self.age += 1 return f"Happy {self.age}th, {self.first}" class Moderator(User): total_mods = 0 def __init__(self, first, last, age, community): super().__init__(first, last, age) self.community = community Moderator.total_mods += 1 @classmethod def display_active_mods(cls): return f"There are currently {cls.total_mods} active mods." def remove_post(self): return f"{self.full_name()} removed a post from the {self.community} community" print(User.display_active_users()) jasmine = Moderator("Jasmine", "O'conner", 61, "Piano") jack = Moderator("Jack", "O'conner", 41, "Horses") print(User.display_active_users()) u1 = User("Tom", "Sanchez", 35) u1 = User("Tom", "Cruise", 56) u1 = User("Tom", "Smith", 23) print(User.display_active_users()) print(jasmine.full_name()) print(jasmine.community) print(User.display_active_users()) print(Moderator.display_active_mods())
message = input('Hey, how\'s it going? ').lower() while message != 'stop copying me': print(message) message = input().lower() print('UGH FINE YOU WIN')
from functools import wraps def double_return(fn): @wraps(fn) def wrapper(*args, **kwargs): result = fn(*args, **kwargs) return [result, result] return wrapper @double_return def add(x, y): return x + y print(add(1, 2)) @double_return def greet(name): return "Hi, I'm " + name print(greet("Norberto Sánchez-Dichi"))
from csv import DictReader with open("fighters.csv") as file: csv_reader = DictReader(file) for row in csv_reader: print(row['Name']) from csv import DictReader with open("fighters_other_delimiter.csv") as file: csv_reader = DictReader(file, delimiter = "|") for row in csv_reader: print(row['Name'])
class BankAccount: def __init__(self, owner): self.owner = owner self.balance = 0.0 def getBalance(self): return self.balance def deposit(self, amount): self.balance += amount return self.balance def withdraw(self, amount): self.balance -= amount return self.balance acct = BankAccount("Darcy") acct.owner #Darcy acct.balance #0.0 acct.deposit(10) #10.0 acct.withdraw(3) #7.0 acct.balance #7.0
student = { 'name': 'Norberto', 'owns_parrot' : True, 'favorite_language': 'Python', 25 : 'my favorite number!'} print(f'{student =}') parrot = {'name': 'Lorenzo', 'age': 1.5, 'isLoco': True} print(f'{parrot =}') car = dict(name = 'pegasus', age = 1.0) print(f'{car = }')
#List of Numbers more_numbers = [6, 1, 8, 2] print(f'more_numbers = {more_numbers}') print(f'sorted more_numbers = {sorted(more_numbers)}') print(f'sorted more_numbers in reverse = {sorted(more_numbers, reverse = True)}') #Dictionary users = [ {"username": "samuel", "tweets": ["I love cake", "i love fruit"]}, {"username": "katie", "tweets": ["I love my cate"]}, {"username": "jeff", "tweets": [], "color": "purple"}, {"username": "bob123", "tweets": [], "num": 10, "color": "teal"}, {"username": "doggo_luvr", "tweets": ["dogs are the best"]}, {"username": "guitar_gal", "tweets": []}, ] print(f'users = {users}') print(f'sorted users by length = {sorted(users, key=len)}') print(f'sorted users by alphabetical order = {sorted(users, key=lambda user: user["username"])}') print(f'sorted users by alphabetical order = {sorted(users, key=lambda user: len(user["tweets"]), reverse = True)}')
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Convert Y to 2D Array for Feature Scaling Y = Y.reshape(len(Y), 1) print(f"Y as a 2D array = {Y}") print() # Split Dataset: Training Set and Test Set from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0) print(f"X_train = {X_train}") print(f"X_test = {X_test}") print(f"Y_train = {Y_train}") print(f"Y_test = {Y_test}") print() # Feature Scaling (done after splitting to avoid information leakage) ## Feature scaling also done for dependent variable so as to not neglect them in the model ## X_train and Y_train both have a different mean and standard deviation and so they require their own scale ## Feature Selection using P-Values to find most significant variables is not possible because SVR is a non-linear model. However, Feature Extraction is possible using Dimensionality Reduction. from sklearn.preprocessing import StandardScaler standardScaler_X = StandardScaler() standardScaler_Y = StandardScaler() X_train_scaled = standardScaler_X.fit_transform(X_train) Y_train_scaled = standardScaler_Y.fit_transform(Y_train) print(f"X_train_scaled = {X_train_scaled}") print(f"Y_train_scaled = {Y_train_scaled}") print() # The Nature of Statistical Learning Theory by Vladimir Vapnik # ε-Insensitive Tube is a margin of error in SVR that is allowed for the model. # Slack Variables ζ1* (below ε-Insensitive Tube) and ζ2 (above ε-Insensitive Tube) are used to calculate error. ## The Slack Variables are the support vectors that form the structure of the ε-Insensitive Tube. # Create and train Support Vector Regression (SVR) model # Use The Gaussian Radial Basis Function (RBF) Kernel ## Other kernels are Polynomial, Gaussian, Laplace RBF, Hyperbolic Tangent, Sigmoid, Bessel Function of First Kind, Anova RB, and Linear Spline in 1D from sklearn.svm import SVR regressor = SVR(kernel = 'rbf') regressor.fit(X_train_scaled, Y_train_scaled.ravel()) # Predict using Support Vector Regression Y_predict = standardScaler_Y.inverse_transform(regressor.predict(standardScaler_X.transform(X_test))) # Output Training and Test Set results np.set_printoptions(precision = 2) print(f"[Y_predict Y_test] = {np.concatenate((Y_predict.reshape(len(Y_predict), 1), Y_test.reshape(len(Y_test), 1)), axis = 1)}") print() # Evaluate Model Performance from sklearn.metrics import r2_score print(f"R2 Score = {r2_score(Y_test, Y_predict)}") print(f"Adusted R2 Score = {1 - (1 - r2_score(Y_test, Y_predict)) * ((len(X_test) - 1) / (len(X_test) - len(X_test[0]) - 1))}")
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0) print(f"X_train = {X_train}") print(f"X_test = {X_test}") print(f"Y_train = {Y_train}") print(f"Y_test = {Y_test}") print() # Multiple Linear Regressor ## 1. Linearity - Assumes a linear relationship between the dependent and independent variables. ### Scatterplots can show whether there is a linear or curvilinear relationship. ## 2. Homoscedasticity - Assumes variance of error terms is similar across the values of the independent variables. ### A plot of standardized residuals versus predicted values shows whether points are equally distributed across all independent variables. ## 3. Multivarate Normality - Assumes that the residuals are normally distributed. ### The residuals are the differences between the observed and predicted values. ## 4. Independence of Errors - Assumes the residuals are independent. ## 5. Lack of Multicollinearity - Assumes that the independent variables are not highly correlated with each other. ### This assumption is tested using Variance Inflation Factor (VIF) values. # Create and train the Multiple Regression model from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, Y_train) # Predict Test Set results Y_predict = regressor.predict(X_test) # Output Training and Test Set results np.set_printoptions(precision = 2) print(f"[Y_predict Y_test] = {np.concatenate((Y_predict.reshape(len(Y_predict), 1), Y_test.reshape(len(Y_test), 1)), axis = 1)}") print() # Print multiple linear regressor coefficient and intercept. print(f"Coefficients = {regressor.coef_}") print(f"Intercept = {regressor.intercept_}") print() # Evaluate Model Performance ## The Adjusted R-squared score or the Pearson Matrix can evaluate Multiple Linear Regressor performance. from sklearn.metrics import r2_score print(f"R2 Score = {r2_score(Y_test, Y_predict)}") print(f"Adusted R2 Score = {1 - (1 - r2_score(Y_test, Y_predict)) * ((len(X_test) - 1) / (len(X_test) - len(X_test[0]) - 1))}")
class User: active_users = 0 @classmethod def display_active_users(cls): return f"There are currently {cls.active_users} active users." @classmethod def from_string(cls, data_str): first, last, age = data_str.split(",") return cls(first, last, int(age)) def __init__(self, first, last, age): self.first = first self.last = last self.age = age User.active_users += 1 def __repr__(self): return f"{self.first} is {self.age}" def logout(self): User.active_users -= 1 return f"{self.first} has logged out" def full_name(self): return f"{self.first} {self.last}" def initials(self): return f"{self.first[0]}.{self.last[0]}." def likes(self, thing): return f"{self.first} likes {thing}" def is_senior(self): return self.age >= 65 def birthday(self): self.age += 1 return f"Happy {self.age}th, {self.first}" user1 = User("Joe", "Dawson", 25) user2 = User("Jack", "Chap", 29) user3 = User.from_string("Tom,Jones,45") print(User.active_users) print(user1) print(user1.full_name()) print(user2.full_name()) print(User.display_active_users()) print(user1.likes("Ice Cream")) print(user2.likes("Chips")) print(user1.initials()) print(user2.initials()) print(user3.initials()) print(user1.is_senior()) print(user1.birthday()) print(user1.age) print(user2.logout()) print(User.active_users)
class Animal(): def speak(self): raise NotImplementedError("Subclass needs to implement this method") class Dog(Animal): def speak(self): return "woof" class Cat(Animal): def speak(self): return "meow" class Fish(Animal): pass d = Dog() print(d.speak()) f = Fish() print(f.speak()) sample_list = [1, 2, 3] sample_tuple = (1, 2, 3) sample_string = "awesome" len(sample_list) len(sample_tuple) len(sample_string)
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set X_train = X[:, 1:2] Y_train = Y print(f"X_train = {X_train}") print(f"Y_train = {Y_train}") print() # Create and train the Linear Regression model from sklearn.linear_model import LinearRegression linearRegressor = LinearRegression() linearRegressor.fit(X_train, Y_train) # Polynomial Regressor ## The Polynomial Regressor is linear on the coefficients because they are not raised to a power. ## However, the Polynomial Regressor is a non-linear function because the inputs are raised to a power. ## Feature Scaling is not required because the coefficients adjust to put everyting on the same scale. ## To evaluate the polynomial regressor, compute the "Mean of Squared Residuals" (the mean of the squared errors). ## Can't apply Backward Elimination to Polynomial Regression models because there are no coefficients combined in a linear regression equation and therefore there are no p-values. # Create and train Polynomial Regression model from sklearn.preprocessing import PolynomialFeatures polynomialPreprocessor = PolynomialFeatures(degree = 4) X_train_polynomial = polynomialPreprocessor.fit_transform(X_train) linearRegressor_polynomial = LinearRegression() linearRegressor_polynomial.fit(X_train_polynomial, Y) # Output Linear Regression Results plt.scatter(X_train, Y_train, color = 'red') plt.plot(X_train, linearRegressor.predict(X_train), color = 'blue') plt.title('Linear Regression Model') plt.xlabel('Position Level') plt.ylabel('Salary') plt.savefig('Linear Regression.png') plt.clf() # Output Polynomial Regression Results plt.scatter(X_train, Y_train, color = 'red') plt.plot(X_train, linearRegressor_polynomial.predict(X_train_polynomial), color = 'blue') plt.title('Polynomial Regression Model') plt.xlabel('Position Level') plt.ylabel('Salary') plt.savefig('Polynomial_Regression.png') plt.clf() # Output Polynomial Regression Results w/ more data points X_train_grid = np.arange(min(X_train), max(X_train), 0.1) X_train_grid = X_train_grid.reshape((len(X_train_grid), 1)) X_train_polynomial_grid = polynomialPreprocessor.fit_transform(X_train_grid) plt.scatter(X_train, Y_train, color = 'red') plt.plot(X_train_grid, linearRegressor_polynomial.predict(X_train_polynomial_grid), color = 'blue') plt.title('Polynomial Regression Model w/ More Data Points') plt.xlabel('Position Level') plt.ylabel('Salary') plt.savefig('Polynomial_Regression_with_More_Data_Points.png') plt.clf() # Predict using Linear Regression np.set_printoptions(precision = 2) Y_linear_predict = linearRegressor.predict([[6.5]]) # Output prediction salary for a position 6 using linear regression. print(f"Salary for a position 6 using linear regression is = {Y_linear_predict}\n") # Predict using Polynomial Regression Y_polynomial_predict = linearRegressor_polynomial.predict(polynomialPreprocessor.fit_transform([[6.5]])) # Output prediction salary for a position 6 using linear regression. print(f"Salary for a position 6 using polynomial regression is = {Y_polynomial_predict}\n")