text
stringlengths
37
1.41M
# Create function that returns the average of an integer list def average_numbers(num_list): avg = sum(num_list)/float(len(num_list)) # divide by length of list return avg # Take the average of a list: my_avg my_avg = average_numbers([1, 2, 3, 4, 5, 6]) # Print out my_avg print(my_avg) ----------------------------------- # Import numpy as np import numpy as np # List input: my_matrix my_matrix = [[1,2,3,4], [5,6,7,8]] # Function that converts lists to arrays: return_array def return_array(matrix): array = np.array(matrix, dtype = float) return array # Call return_array on my_matrix, and print the output print(return_array(my_matrix)) ------------ # Create a class: DataShell class DataShell: pass ------------------------------ # Create empty class: DataShell class DataShell: # Pass statement pass # Instantiate DataShell: my_data_shell my_data_shell = DataShell # Print my_data_shell print(my_data_shell) --------------------------------- # Create class: DataShell class DataShell: # Initialize class with self argument def __init__(self): # Pass statement pass # Instantiate DataShell: my_data_shell my_data_shell = DataShell() # Print my_data_shell print(my_data_shell) ------------------------------------- # Create class: DataShell class DataShell: # Initialize class with self and integerInput arguments def __init__(self, integerInput): # Set data as instance variable, and assign the value of integerInput self.data = integerInput # Declare variable x with value of 10 x = 10 # Instantiate DataShell passing x as argument: my_data_shell my_data_shell = DataShell(x) # Print my_data_shell print(my_data_shell.data) ----------------------------------------------------- # Create class: DataShell class DataShell: # Initialize class with self, identifier and data arguments def __init__(self, identifier, data): # Set identifier and data as instance variables, assigning value of input arguments self.identifier = identifier self.data = data # Declare variable x with value of 100, and y with list of integers from 1 to 5 x = 100 y = [1, 2, 3, 4, 5] # Instantiate DataShell passing x and y as arguments: my_data_shell my_data_shell = DataShell(x, y) # Print my_data_shell.identifier print(my_data_shell.identifier) # Print my_data_shell.data print(my_data_shell.data) --------------------------------------------------------------- # Create class: DataShell class DataShell: # Declare a class variable family, and assign value of "DataShell" family = "DataShell" # Initialize class with self, identifier arguments def __init__(self, identifier): # Set identifier as instance variable of input argument self.identifier = identifier # Declare variable x with value of 100 x = 100 # Instantiate DataShell passing x as argument: my_data_shell my_data_shell = DataShell(x) # Print my_data_shell class variable family -------------------------------------------------------- print(my_data_shell.family) ----------------------------- # Create class: DataShell class DataShell: # Declare a class variable family, and assign value of "DataShell" family = "DataShell" # Initialize class with self, identifier arguments def __init__(self, identifier): # Set identifier as instance variables, assigning value of input arguments self.identifier = identifier # Declare variable x with value of 100 x = 100 # Instantiate DataShell passing x as the argument: my_data_shell my_data_shell = DataShell(x) # Print my_data_shell class variable family print(my_data_shell.family) # Override the my_data_shell.family value with "NotDataShell" my_data_shell.family = "NotDataShell" # Print my_data_shell class variable family once again print(my_data_shell.family) -------------------------------------------------------------- # Create class: DataShell class DataShell: # Initialize class with self argument def __init__(self): pass # Define class method which takes self argument: print_static def print_static(self): # Print string print("You just executed a class method!") # Instantiate DataShell taking no arguments: my_data_shell my_data_shell = DataShell() # Call the print_static method of your newly created object my_data_shell.print_static() ----------------------------------------- # Create class: DataShell class DataShell: # Initialize class with self and dataList as arguments def __init__(self, dataList): # Set data as instance variable, and assign it the value of dataList self.data = dataList # Define class method which takes self argument: show def show(self): # Print the instance variable data print(self.data) # Declare variable with list of integers from 1 to 10: integer_list integer_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Instantiate DataShell taking integer_list as argument: my_data_shell my_data_shell = DataShell(integer_list) # Call the show method of your newly created object my_data_shell.show() -------------------------------------------------- # Create class: DataShell class DataShell: # Initialize class with self and dataList as arguments def __init__(self, dataList): # Set data as instance variable, and assign it the value of dataList self.data = dataList # Define method that prints data: show def show(self): print(self.data) # Define method that prints average of data: avg def avg(self): # Declare avg and assign it the average of data avg = sum(self.data)/float(len(self.data)) # Print avg print(avg) # Instantiate DataShell taking integer_list as argument: my_data_shell my_data_shell = DataShell(integer_list) # Call the show and avg methods of your newly created object my_data_shell.show() my_data_shell.avg() --------------------------------------------- # Create class: DataShell class DataShell: # Initialize class with self and dataList as arguments def __init__(self, dataList): # Set data as instance variable, and assign it the value of dataList self.data = dataList # Define method that returns data: show def show(self): return self.data # Define method that prints average of data: avg def avg(self): # Declare avg and assign it the average of data avg = sum(self.data)/float(len(self.data)) # Return avg return avg # Instantiate DataShell taking integer_list as argument: my_data_shell my_data_shell = DataShell(integer_list) # Print output of your object's show method print(my_data_shell.show()) # Print output of your object's avg method print(my_data_shell.avg()) -------------------------------- # Load numpy as np and pandas as pd import numpy as np import pandas as pd # Create class: DataShell class DataShell: # Initialize class with self and inputFile def __init__(self, inputFile): self.file = inputFile # Define generate_csv method, with self argument def generate_csv(self): self.data_as_csv = pd.read_csv(self.file) return self.data_as_csv # Instantiate DataShell with us_life_expectancy as input argument data_shell = DataShell(us_life_expectancy) # Call data_shell's generate_csv method, assign it to df df = data_shell.generate_csv() # Print df print(df) ------------------------------------------- # Import numpy as np, pandas as pd import numpy as np import pandas as pd # Create class: DataShell class DataShell: # Define initialization method def __init__(self, filepath): # Set filepath as instance variable self.filepath = filepath # Set data_as_csv as instance variable self.data_as_csv = pd.read_csv(filepath) # Instantiate DataShell as us_data_shell us_data_shell = DataShell(us_life_expectancy) # Print your object's data_as_csv attribute print(us_data_shell.data_as_csv) -------------------------------- # Create class DataShell class DataShell: # Define initialization method def __init__(self, filepath): self.filepath = filepath self.data_as_csv = pd.read_csv(filepath) # Define method rename_column, with arguments self, column_name, and new_column_name def rename_column(self, column_name, new_column_name): self.data_as_csv.columns = self.data_as_csv.columns.str.replace(column_name, new_column_name) # Instantiate DataShell as us_data_shell with argument us_life_expectancy us_data_shell = DataShell(us_life_expectancy) # Print the datatype of your object's data_as_csv attribute print(us_data_shell.data_as_csv.dtypes) # Rename your objects column 'code' to 'country_code' us_data_shell.rename_column('code', 'country_code') # Again, print the datatype of your object's data_as_csv attribute print(us_data_shell.data_as_csv.dtypes) ------------------------------------------------------------ # Create class DataShell class DataShell: # Define initialization method def __init__(self, filepath): self.filepath = filepath self.data_as_csv = pd.read_csv(filepath) # Define method rename_column, with arguments self, column_name, and new_column_name def rename_column(self, column_name, new_column_name): self.data_as_csv.columns = self.data_as_csv.columns.str.replace(column_name, new_column_name) # Define get_stats method, with argument self def get_stats(self): # Return a description data_as_csv return self.data_as_csv.describe() # Instantiate DataShell as us_data_shell us_data_shell = DataShell(us_life_expectancy) # Print the output of your objects get_stats method print(us_data_shell.get_stats()) ----------------------------------------------- # Create class DataShell class DataShell: # Define initialization method def __init__(self, filepath): self.filepath = filepath self.data_as_csv = pd.read_csv(filepath) # Define method rename_column, with arguments self, column_name, and new_column_name def rename_column(self, column_name, new_column_name): self.data_as_csv.columns = self.data_as_csv.columns.str.replace(column_name, new_column_name) # Define get_stats method, with argument self def get_stats(self): # Return a description data_as_csv return self.data_as_csv.describe() # Instantiate DataShell as us_data_shell us_data_shell = DataShell(us_life_expectancy) # Print the output of your objects get_stats method print(us_data_shell.get_stats()) ------------------------------------------------------------------- # Create a class Animal class Animal: def __init__(self, name): self.name = name # Create a class Mammal, which inherits from Animal class Mammal(Animal): def __init__(self, name, animal_type): self.animal_type = animal_type # Create a class Reptile, which also inherits from Animal class Reptile(Animal): def __init__(self, name, animal_type): self.animal_type = animal_type # Instantiate a mammal with name 'Daisy' and animal_type 'dog': daisy daisy = Mammal('Daisy', 'dog') # Instantiate a reptile with name 'Stella' and animal_type 'alligator': stella stella = Reptile('Stella', 'alligator') # Print both objects print(daisy) print(stella) ------------------------------------ # Create a class Vertebrate class Vertebrate: spinal_cord = True def __init__(self, name): self.name = name # Create a class Mammal, which inherits from Vertebrate class Mammal(Vertebrate): def __init__(self, name, animal_type): self.animal_type = animal_type self.temperature_regulation = True # Create a class Reptile, which also inherits from Vertebrate class Reptile(Vertebrate): def __init__(self, name, animal_type): self.animal_type = animal_type self.temperature_regulation = False # Instantiate a mammal with name 'Daisy' and animal_type 'dog': daisy daisy = Mammal('Daisy', 'dog') # Instantiate a reptile with name 'Stella' and animal_type 'alligator': stella stella = Reptile('Stella', 'alligator') # Print stella's attributes spinal_cord and temperature_regulation print("Stella Spinal cord: " + str(stella.spinal_cord)) print("Stella temperature regulation: " + str(stella.temperature_regulation)) # Print daisy's attributes spinal_cord and temperature_regulation print("Daisy Spinal cord: " + str(daisy.spinal_cord)) print("Daisy temperature regulation: " + str(daisy.temperature_regulation)) ------------------------------------ # Load numpy as np and pandas as pd import numpy as np import pandas as pd # Create class: DataShell class DataShell: def __init__(self, inputFile): self.file = inputFile # Create class CsvDataShell, which inherits from DataShell class CsvDataShell(DataShell): # Initialization method with arguments self, inputFile def __init__(self, inputFile): # Instance variable data self.data = pd.read_csv(inputFile) # Instantiate CsvDataShell as us_data_shell, passing us_life_expectancy as argument us_data_shell = CsvDataShell(us_life_expectancy) # Print us_data_shell.data print(us_data_shell.data) ------------------------------------ # Define abstract class DataShell class DataShell: # Class variable family family = 'DataShell' # Initialization method with arguments, and instance variables def __init__(self, name, filepath): self.name = name self.filepath = filepath # Define class CsvDataShell class CsvDataShell(DataShell): # Initialization method with arguments self, name, filepath def __init__(self, name, filepath): # Instance variable data self.data = pd.read_csv(filepath) # Instance variable stats self.stats = self.data.describe() # Instantiate CsvDataShell as us_data_shell us_data_shell = CsvDataShell("US", us_life_expectancy) # Print us_data_shell.stats print(us_data_shell.stats) ------------------------------------ # Define abstract class DataShell class DataShell: family = 'DataShell' def __init__(self, name, filepath): self.name = name self.filepath = filepath # Define class CsvDataShell class CsvDataShell(DataShell): def __init__(self, name, filepath): self.data = pd.read_csv(filepath) self.stats = self.data.describe() # Define class TsvDataShell class TsvDataShell(DataShell): # Initialization method with arguments self, name, filepath def __init__(self, name, filepath): # Instance variable data self.data = pd.read_table(filepath) # Instance variable stats self.stats = self.data.describe() # Instantiate CsvDataShell as us_data_shell, print us_data_shell.stats us_data_shell = CsvDataShell("US", us_life_expectancy) print(us_data_shell.stats) # Instantiate TsvDataShell as france_data_shell, print france_data_shell.stats france_data_shell = TsvDataShell("France", france_life_expectancy) print(france_data_shell.stats) -----------------------------------------
# -*- coding: utf-8 -*- """ PS3 Itsaso Apezteguia """ import numpy as np import math import sympy from sympy import symbols from scipy.optimize import fsolve import scipy.optimize as sc import matplotlib.pyplot as plt """ Question 1: TRANSITIONS IN A REPRESENTATIVE AGENT ECONOMY """ ## a) COMPUTING THE STEADY STATE # Setting some of the parameters: theta = 0.67 h = 0.31 y = 1 k1 = 4 i = 0.25 c = y - i delta = 1/16 # in steady state delta = i/k # From the production function we can get the level of productivity z: def zeta(z): f = (k1**(1-theta)*(z*h)**theta)-y return f z1 = fsolve(zeta,1) print('The initial steady state level of productivity (z) is', z1) print('The initial steady state level of consumption (c) is', c) print('The initial steady state level of production (y) is', y) print('The initial steady state level of investment (i) is', i) print('The initial steady state level of capital (k) is', k1) # Obtaining beta: b = 1/((1-theta)*k1**(- theta)*(z1*h)**theta + 1-delta) #This comes from the euler equation at the steady state, where f´(k) = 1/beta print('The discount factor beta is', b) ## b) DOUBLING PERMANENTLY THE PORDUCTIVITY PARAMETER AND SOLVING FOR THE STEADY STATE z2 = 2*z1 def capital_ss(k): f = (1-theta)*k**(-theta)*(z2*h)**theta+(1-delta)-(1/b) # From f´(k) = 1/beta we obtain an expression for k return f k2 = fsolve(capital_ss,4) i2 = delta*k2 y2 = k2**(1-theta)*(z2*h)**theta c2 = y2 - i2 print('The new steady state level of productivity (z) is', z2) print('The new steady state level of consumption (c) is', c2) print('The new steady state level of production (y) is', y2) print('The new steady state level of investmetn (i) is', i2) print('The new steady state level of capital (k) is', k2) ## c) COMPUTING THE TRANSITION FROM THE FIRST TO THE SECOND STEADY STATE # Transition path for CAPITAL # The Euler equation for this economy: def euler(k1,k2,k3): return k2**(1-theta)*(z2*h)**theta-k3+(1-delta)*k2-b*((1-theta)*k2**(-theta)*(z2*h)**theta+(1-delta))*(k1**(1-theta)*(z2*h)**theta-k2+(1-delta)*k1) # Transition matrix: def ktransition(z): F = np.zeros(100) z = z F[0] = euler(4,z[1],z[2]) z[99] = k2 F[98] = euler(z[97],z[98],z[99]) for i in range(1,98): F[i] = euler(z[i],z[i+1],z[i+2]) return F z = np.ones(100)*4 k = fsolve(ktransition, z) k[0] = 4 plt.plot(k) plt.title('Transition path of capital from the first to the second steady state') plt.xlabel('Time') plt.ylabel('Capital') plt.show() # Transition paths for output, consumption and savings: yt = k**(1-theta)*(z2*h)**theta # Due to the fact that savings have a t+1 structure st = np.empty(100) for i in range(99): st[i] = k[i+1]-(1-delta)*k[i] st[99]=st[98] ct = yt - st plt.plot(yt, label= 'Output') plt.plot(st, label= 'Savings') plt.plot(ct, label= 'Consumption') plt.title('Transition path for output, savings and consumption') plt.xlabel('Time') plt.ylabel('Levels') plt.legend() plt.show() ## D) COMPUTING THE TRANSITION BEFORE AN UNEXPECTED SHOCK k_s = np.empty(100) # capital level for the unexpected shock t = 10 k_s[0:t] = k[0:t] # the k_s variable takes same values as the k of the transition without shocks until the shock occurs # After period 10 is when the path will change # New Euler equation (with z taking initial values) def euler_new(k1,k2,k3): return k2**(1-theta)*(z1*h)**theta-k3+(1-delta)*k2-b*((1-theta)*k2**(-theta)*(z1*h)**theta+(1-delta))*(k1**(1-theta)*(z1*h)**theta-k2+(1-delta)*k1) # New transition matrix: def ktransition_new(z): F = np.zeros(90) # shape = duration of the previous transition(100) - period when shock occurs(10) z = z F[0] = euler_new(k_s[9],z[1],z[2]) z[89] = k1 F[88] = euler_new(z[87],z[88],z[89]) for i in range(1,88): F[i] = euler_new(z[i],z[i+1],z[i+2]) return F z = np.ones(90)*8 k = fsolve(ktransition_new,z) k[0] = k_s[9] k_s[10:100] = k plt.plot(k_s) plt.title('Transition path of capital with an unexpected shock in z at t=10') plt.xlabel('Time') plt.ylabel('Capital') plt.show() # Transition paths for output, consumption and savings: z_n1 = np.ones(10)*z2 # labour prodcrivity for the first 10 periods z_n2 = np.ones(90)*z1 # labour productivity for the last 90 periods (before the shock) z_n = np.concatenate((z_n1, z_n2)) y_s = k_s**(1-theta)*(z_n*h)**theta s_s = np.empty(100) for i in range(99): s_s[i] = k_s[i+1]-(1-delta)*k_s[i] s_s[99]=s_s[98] c_s = y_s - s_s plt.plot(y_s, label= 'Output') plt.plot(s_s, label= 'Savings') plt.plot(c_s, label= 'Consumption') plt.title('Transition path for output, savings and consumption with an unexpected shock in z at t=10') plt.xlabel('Time') plt.ylabel('Levels') plt.legend() plt.show()
# -*- coding: utf-8 -*- """ Created on Wed Apr 25 14:01:19 2018 @author: urand Théophane """ import tkinter as tk p = 37 #Numéro du corps class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title("Courbes elliptiques") self.can = tk.Canvas(self, width = 600, height = 600) #Définition de la fenêtre self.can.pack() self.can.create_line(50,550, 550, 550, width = 3) #Définition de la grille self.can.create_line(50,50, 50, 550, width = 3) for i in range (p): self.can.create_line(45, 550-i*500/(p-1), 55, 550-i*500/(p-1), width = 2) self.can.create_line(50, 550-i*500/(p-1), 550, 550-i*500/(p-1)) self.can.create_text(35, 550-i*500/(p-1), text = str(i)) self.can.create_line(550-i*500/(p-1), 545, 550-i*500/(p-1), 555, width = 2) self.can.create_line(550-i*500/(p-1), 50, 550-i*500/(p-1), 550) self.can.create_text(550-i*500/(p-1),565, text = str(p-1-i)) def placePoint(self, point, color): """Fonction permetant de placer un point dans la grille Paramètres : point-> un tuple correspondant aux coordonnées du point à placer color -> Couleur avec laquelle on veut afficher le point """ Px = point[0]*500/(p-1) + 50 Py = 500 - point[1]*500/(p-1) + 50 self.can.create_oval(Px-5, Py-5, Px+5, Py+5, fill = color) def show(a,b, color): """Fonction permettant de placer tous les points apartenant à une courbe elliptique donnée Paramètres : a, b -> Les paramètres de la courbe color -> La couleur dans la quelle afficher les points de la courbe """ for i in courbeElliptique[(a,b)]: app.placePoint(i, color) if __name__=="__main__": app = App() courbeElliptique = dict() points = list() for a in range (p): for b in range (p): for x in range (p): for y in range (p): if ((y**2-x**3-a*x-b)%p == 0): points.append((x,y)) courbeElliptique[(a,b)] = points #On créé un dictionnaire avec comme clé les parametres de la courbe et comme valeurs, tous les points vérifiant l'équation de la courbe points = list() show(1,1, "red") show(5, 9, "green") show(8, 30, "yellow") app.mainloop()
""" This function's main goal is to translate the coordinates of the mouse into what position of the chessboard the mouse is in This was a repetative implementation, there might (most likely) another way to implement this that is more effecient both in the run time, and the time it took to code IF YOU DON'T KNOW THE CHESS POSITIONS: http://www.chess-poster.com/english/learn_chess/notation/images/coordinates_2.gif """ class find_position(): def chess_position(self, pos): if pos[0] <= 102.5 and pos[1] <= 100: return "a1" elif pos[0] <= 205 and pos[1] <= 100: return "b1" elif pos[0] <= 307.5 and pos[1] <= 100: return "c1" elif pos[0] <= 410 and pos[1] <= 100: return "d1" elif pos[0] <= 512.5 and pos[1] <= 100: return "e1" elif pos[0] <= 615 and pos[1] <= 100: return "f1" elif pos[0] <= 717.5 and pos[1] <= 100: return "g1" elif pos[0] <= 820 and pos[1] <= 100: return "h1" elif pos[0] <= 102.5 and pos[1] <= 200: return ("a2") elif pos[0] <= 205 and pos[1] <= 200: return ("b2") elif pos[0] <= 307.5 and pos[1] <= 200: return ("c2") elif pos[0] <= 410 and pos[1] <= 200: return ("d2") elif pos[0] <= 512.5 and pos[1] <= 200: return ("e2") elif pos[0] <= 615 and pos[1] <= 200: return ("f2") elif pos[0] <= 717.5 and pos[1] <= 200: return ("g2") elif pos[0] <= 820 and pos[1] <= 200: return ("h2") elif pos[0] <= 102.5 and pos[1] <= 300: return ("a3") elif pos[0] <= 205 and pos[1] <= 300: return ("b3") elif pos[0] <= 307.5 and pos[1] <= 300: return ("c3") elif pos[0] <= 410 and pos[1] <= 300: return ("d3") elif pos[0] <= 512.5 and pos[1] <= 300: return ("e3") elif pos[0] <= 615 and pos[1] <= 300: return ("f3") elif pos[0] <= 717.5 and pos[1] <= 300: return ("g3") elif pos[0] <= 820 and pos[1] <= 300: return ("h3") elif pos[0] <= 102.5 and pos[1] <= 400: return ("a4") elif pos[0] <= 205 and pos[1] <= 400: return ("b4") elif pos[0] <= 307.5 and pos[1] <= 400: return ("c4") elif pos[0] <= 410 and pos[1] <= 400: return ("d4") elif pos[0] <= 512.5 and pos[1] <= 400: return ("e4") elif pos[0] <= 615 and pos[1] <= 400: return ("f4") elif pos[0] <= 717.5 and pos[1] <= 400: return ("g4") elif pos[0] <= 820 and pos[1] <= 400: return ("h4") elif pos[0] <= 102.5 and pos[1] <= 500: return ("a5") elif pos[0] <= 205 and pos[1] <= 500: return ("b5") elif pos[0] <= 307.5 and pos[1] <= 500: return ("c5") elif pos[0] <= 410 and pos[1] <= 500: return ("d5") elif pos[0] <= 512.5 and pos[1] <= 500: return ("e5") elif pos[0] <= 615 and pos[1] <= 500: return ("f5") elif pos[0] <= 717.5 and pos[1] <= 500: return ("g5") elif pos[0] <= 820 and pos[1] <= 500: return ("h5") elif pos[0] <= 102.5 and pos[1] <= 600: return ("a6") elif pos[0] <= 205 and pos[1] <= 600: return ("b6") elif pos[0] <= 307.5 and pos[1] <= 600: return ("c6") elif pos[0] <= 410 and pos[1] <= 600: return ("d6") elif pos[0] <= 512.5 and pos[1] <= 600: return ("e6") elif pos[0] <= 615 and pos[1] <= 600: return ("f6") elif pos[0] <= 717.5 and pos[1] <= 600: return ("g6") elif pos[0] <= 820 and pos[1] <= 600: return ("h6") elif pos[0] <= 102.5 and pos[1] <= 700: return ("a7") elif pos[0] <= 205 and pos[1] <= 700: return ("b7") elif pos[0] <= 307.5 and pos[1] <= 700: return ("c7") elif pos[0] <= 410 and pos[1] <= 700: return ("d7") elif pos[0] <= 512.5 and pos[1] <= 700: return ("e7") elif pos[0] <= 615 and pos[1] <= 700: return ("f7") elif pos[0] <= 717.5 and pos[1] <= 700: return ("g7") elif pos[0] <= 820 and pos[1] <= 700: return ("h7") elif pos[0] <= 102.5 and pos[1] <= 800: return ("a8") elif pos[0] <= 205 and pos[1] <= 800: return ("b8") elif pos[0] <= 307.5 and pos[1] <= 800: return ("c8") elif pos[0] <= 410 and pos[1] <= 800: return ("d8") elif pos[0] <= 512.5 and pos[1] <= 800: return ("e8") elif pos[0] <= 615 and pos[1] <= 800: return ("f8") elif pos[0] <= 717.5 and pos[1] <= 800: return ("g8") elif pos[0] <= 820 and pos[1] <= 800: return ("h8")
import random from problem.problem_instance_properties import ProblemInstanceProperties from mutators.mutators import simple_mutator from crossovers.crossovers import single_point_crossover from selectors.selectors import tournament_selector class ProblemInstance: """ Class that represents an instantiated genetic problem, containing everything related with the populations and the mutation and crossover mechanisms. """ def __init__(self, problem, mutator=simple_mutator, crossover=single_point_crossover, selector=tournament_selector, properties=ProblemInstanceProperties(), initial_population=None): """ Constructor for the class. Args: problem (Problem): Genetic problem mutator (function): Mutator function used for the chromosome mutations crossover (function): Crossover function used for performing crossover over two individuals selector (function): Selection function used in order to select the individuals for the next generation properties (ProblemInstanceProperties): Class containing all the properties of the problem instance initial_population (list<number>): A list containing individuals for the initial population. If none or an empty list is provided, the population will be initialized randomly. A minimum of 2 individuals are required """ self.problem = problem self.mutator = mutator self.crossover = crossover self.selector = selector self.properties = properties if initial_population == None or initial_population == [] or len(initial_population) < 2: self.parents = self.create_population() else: self.parents = initial_population self.childs = [] self.generation_count = 0 def create_population(self): """ Generates a population for the problem instance using random genes. The population will fit the properties.selection_amount number. Returns: list<list<number>>: Initial population for the problem instance """ return [self.create_individual() for _ in range(self.properties.selection_amount)] def create_individual(self): """ Generates a single individual (chromosome) for the problem instance using random genes. Returns: list<number>: A single individual for the problem instance """ return random.choices(self.problem.genes, k=self.problem.individuals_length) def is_halted(self): """ Returns whether the problem has been already halted or not, this is, if the actual generation has reached the maximum generation count or not. Returns: boolean: Whether the actual generation has reached the maximum number of generations """ return self.properties.halting_generations <= self.generation_count def calculate_next_generation(self): """ Calculates the next generation of individuals. It doesn't take into account whether the problem instance has already halted or not, so it can calculate subsequent generations after finishing. """ self.parents = self.selector(self.parents, self.problem.fitness, self.properties) self.childs = [self.crossover(c1, c2) for [c1, c2] in [random.choices(self.parents, k=2) for _ in range(self.properties.selection_amount)]] self.childs = [self.mutator(chromosome, self.problem.genes, self.properties) for chromosome in self.childs] self.parents = self.childs.copy() self.generation_count += 1 def run_until_halt(self): """ Runs the problem instance and calculates generation until the halting condition is met. """ while not self.is_halted(): self.calculate_next_generation() def get_best_individual(self): """ Gets the best individual from the current generation. Returns: list<number>: Best individual in the current generation """ cmp = max if self.properties.optimization_type == "MAX" else min return cmp(self.childs, key=lambda x: self.problem.fitness(x)) def decode_individual(self, individual): """ Auxiliary method. Decodes an individual. Args: individual (list<number>): A given individual for this problem Returns: ?: The solution after being decoded for this problem """ return self.problem.decode(individual) def fitness_individual(self, individual): """ Auxiliary method. Calculates the fitness of an individual. Args: individual (list<number>): A given individual for this problem Returns: number: The fitness of the given individual with respect to this problem """ return self.problem.fitness(individual)
import matplotlib.pyplot as plt import numpy as np """Space Complexity""" # example def return_squares(n): square_list = [] for num in n: square_list.append(num * num) return square_list nums = [2, 4, 6, 8, 10] print(return_squares(nums)) """Worst vs Best Case Complexity""" # example # def search_algo(num, items): # for item in items: # if item == num: # return True # else: # return False # # # nums = [2, 4, 6, 8, 10] # # print(search_algo(2, nums)) """Finding the Complexity of Complex Functions""" # example # def complex_algo(items): # for i in range(5): # print("Python is awesome") # # for item in items: # print(item) # # for item in items: # print(item) # # print("Big O") # print("Big O") # print("Big O") # # # complex_algo([4, 5, 6, 8]) """Quadratic Complexity O(n^2)""" # example # def quadratic_algo(items): # for item in items: # for item2 in items: # print(item, ' ', item2) # # # quadratic_algo([4, 5, 6, 8]) """Linear Complexity O(n)""" # x = [2, 4, 6, 8, 10, 12] # y = [4, 8, 12, 16, 20, 24] # # plt.plot(x, y, 'b') # plt.xlabel('Inputs') # plt.ylabel('Steps') # plt.title('Linear Complexity') # plt.show() # example # def linear_algo(items): # for item in items: # print(item) # # for item in items: # print(item) # # # linear_algo([4, 5, 6, 8]) # example # x = [2, 4, 6, 8, 10, 12] # y = [2, 4, 6, 8, 10, 12] # # plt.plot(x, y, 'b') # plt.xlabel('Inputs') # plt.ylabel('Steps') # plt.title('Linear Complexity') # plt.show() # example # def linear_algo(items): # for item in items: # print(item) # # # linear_algo([4, 5, 6, 8]) """Constant Complexity O(C)""" # x = [2, 4, 6, 8, 10, 12] # # y = [2, 2, 2, 2, 2, 2] # # plt.plot(x, y, 'b') # plt.xlabel('Inputs') # plt.ylabel('Steps') # plt.title('Constant Complexity') # plt.show() # example # def constant_algo(items): # result = items[0] * items[0] # print(result) # # # constant_algo([4, 5, 6, 8]) """Factorial""" # factorial version 2.0 # def fact2(n): # if n == 0: # return 1 # else: # return n * fact2(n-1) # # # print(fact2(5)) # factorial version 1.0 # def fact(n): # product = 1 # for i in range(n): # product = product * (i+1) # return product # # # print(fact(5))
"""fibonacci via recursion""" def fibonacci(n): if n in (1, 2): return 1 return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(7)) # print(fibonacci(10)) # print(fibonacci(33)) """fibonacci via 'for' loop""" # fib1 = fib2 = 1 # n = int(input()) # # if n < 2: # quit() # # print(fib1, end=' ') # print(fib2, end=' ') # # for i in range(2, n): # fib1, fib2 = fib2, fib1 + fib2 # print(fib2, end=' ') # # print() """fibonacci via 'while' loop""" # 2.0 example # fib1 = fib2 = 1 # # n = int(input("The number of Fibonacci element: ")) - 2 # # while n > 0: # fib1, fib2 = fib2, fib1 + fib2 # n -= 1 # # print(fib2) # 1.0 example # Number = int(input("\nPlease Enter the Range Number: ")) # # i = 0 # First_Value = 0 # Second_Value = 1 # # # Find & Displaying Fibonacci series # while i < Number: # if i <= 1: # Next = i # else: # Next = First_Value + Second_Value # First_Value = Second_Value # Second_Value = Next # print(Next) # i = i + 1
class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def insert_left(self, child_val): subtree = self.pop(1) if len(subtree) > 1: self.insert(1, [child_val, subtree, []]) else: self.insert(1, [child_val, [], []]) def insert_right(self, child_val): subtree = self.pop(2) if len(subtree) > 1: self.insert(2, [child_val, [], subtree]) else: self.insert(2, [child_val, [], []]) return self def get_self_val(self): return self[0] def set_self_val(self, new_val): self[0] = new_val def get_left_child(self): return self[1] def get_right_child(self): return self[2] # def insert_left(self, child): # if self.left is None: # self.left = child # else: # child.left = self.left # self.left = child # # def insert_right(self, child): # if self.right is None: # self.right = child # else: # child.right = self.right # self.right = child
# Advent of Code 2019 - day 4 import re def has_double_digit(num: int): return re.search(r'(\d)(?<!(?=\1)..)\1(?!\1)', str(num)) is not None def has_right_length(num: int, length: int=6): return len(str(num)) == length def has_no_decreasing_digits(num: int): return re.search(r'^1*2*3*4*5*6*7*8*9*$', str(num)) is not None def inspect_range(r: range, length: int=6): matching_numbers = [] for num in r: #print("Inspecting {}: has_right_length={} has_double_digit={} has_no_decreasing_digits={}".format(num, has_right_length(num, length), has_double_digit(num), has_no_decreasing_digits(num))) if (has_right_length(num, length) and has_double_digit(num) and has_no_decreasing_digits(num)): matching_numbers.append(num) return matching_numbers test_range = range(1220,1261) puzzle_range = range(402328,864247+1) arr = inspect_range(test_range, 4) print("Got {} matching numbers in the test range {}-{}".format(len(arr), test_range.start, test_range.stop)) arr = inspect_range(puzzle_range, 6) print("Got {} matching numbers in the puzzle range {}-{}".format(len(arr), puzzle_range.start, puzzle_range.stop))
import numpy as np import math as mt from functions import * class Curve: def get_dist(self, x=None, y=None): """ Returns ------- numpy array distances between consecutive points given by pairs of coordinates; the first value is 0 """ if x is None: x = self.x if y is None: y = self.y len_x = np.shape(x)[0] len_y = np.shape(y)[0] if len_x != len_y: print('x and y have different lengths') return else: length = [0] for ind in range(0, len_x - 1): length.append(mt.sqrt((x[ind + 1] - x[ind]) ** 2 + (y[ind + 1] - y[ind])**2)) return np.array(length) def get_dist_from_beginning(self, x=None, y=None): """ Returns ------- numpy array length of a curve at each given point """ if x is None: x = self.x if y is None: y = self.y distances = self.get_dist(x, y) if distances is not None: dist = [] d = 0 for element in distances: d += element dist.append(d) return np.array(dist) else: return def get_curve(self, x=None, y=None): """ Returns ------- float length of a curve given by points coordinates x and y """ if x is None: x = self.x if y is None: y = self.y distances = self.get_dist(x, y) if distances is not None: return np.sum(distances) else: return def get_ends_of_segments(self, x=None, y=None): """ Returns ------- numpy array vector of indices of points at which the particular curve segment finishes """ if x is None: x = self.x if y is None: y = self.y number_of_pieces = self.number_of_pieces distances = self.get_dist_from_beginning(x, y) curve_length = self.get_curve(x, y) if curve_length is not None and distances is not None: distances = np.round(distances, 12) piece_length = curve_length / number_of_pieces indices = [] for n in range(1, number_of_pieces + 1): indices.append( np.where(distances <= round(n * piece_length, 12))[0][-1]) return np.array(indices) else: return def get_nominal_percentage(self, amount=500): """ Returns ------- numpy array nominal percentage of points corresponding to equal-length segments of the curve (assuming a large number of points) """ new_x = self.new_x(self.number_of_pieces * amount) new_y = self.new_y(self.number_of_pieces * amount) length = new_x.size indices = self.get_ends_of_segments(new_x, new_y) if indices is not None: indices = np.insert(indices, 0, 0) percentage = np.diff(indices) / length * 100 return np.round(percentage) else: return def get_nominal_ends(self): """ Returns ------- numpy array indices of points corresponding to ends of equal-length segments of the curve """ perc = self.get_nominal_percentage() cum_perc = np.insert(np.cumsum(perc), 0, 0) indices = cum_perc / 100 * self.length # subtracting 1, because 100% = length and the last index is length-1 indices[-1] = indices[-1] - 1 return indices.astype('int') def horizontal_stripes(self, stripes_number): """ Parameters ---------- stripes_number : int number of horizontal stripes for area enclosed by the curve to be divided Returns ------- numpy array array with indices of points which enclose each strip Remark: this method has been tested for a heart curve only; numbers of strips depends on nubers of points building the figure """ x = self.x y = self.y y_max = y.max() y_min = y.min() y_vector = np.linspace(y_max, y_min, stripes_number) indices = [] for i in range(y_vector.size - 1): inds = np.where((y <= y_vector[i]) & (y >= y_vector[i + 1]))[0] inds = np.insert(inds, 0, inds[0] - 1) if x.size - 1 not in inds: inds = np.append(inds, inds[-1] + 1) ind_inf_points = indices_of_inflection_points(y[inds]) inf_points_num = ind_inf_points.size if inf_points_num > 1 and 0 not in inds: ind1 = inds[:ind_inf_points[1] + 1] ind1 = np.append(ind1, ind1[-1] + 1) ind2 = inds[ind_inf_points[1] + 1:] ind2 = np.insert(ind2, 0, ind2[0] - 1) inds = [ind1, ind2] indices.append(inds) return np.array(indices)
def bye_duplicate (): noki = input ("ENTER NUMBERS:") noki = list (noki) nok = [] for i in noki: if i not in nok: nok.append(i) print(nok) bye_duplicate()
""" This is the program for credit card manager. Author: Gurleen Kaur Date: 01-08-2021 """ transactions = [] months = { 0: "January", 1: "February", 2: "March", 3: "April", 4: "May", 5: "June", 6: "July", 7: "August", 8: "September", 9: "October", 10: "November", 11: "December" } def welcome(): welcome_msg = { 1: "Enter the fixed amount(to be paid every month)", 2: "Enter the transaction amount", 3: "Make a payment", 4: "Transaction History", 5: "QUIT" } print("\nWelcome to CredManager") print("~" * 30) print("Enter your choice") for key in welcome_msg.keys(): print("[{}]:{}".format(key, welcome_msg[key])) print("~" * 30) def fixed_amount(amount): print(f"We have set a fixed amount of \u20b9{amount}") def transaction_amount(expense): print(f"Made a transaction of \u20b9{expense}") transactions.append(expense) def make_payment(fixed_amt): payment = 0 for transaction in transactions: payment = payment + transaction print(f"Total amount transacted:\u20b9{payment}") pay = 0.10 * payment + payment print(f"You have to pay \u20b9{pay}") amt = pay # By default=> start from JAN month = 0 # start from next month while amt > 0: amt = amt - fixed_amt month += 1 print("The amount would be paid till", months.get(month % 12)) print("Total months:", month) def transaction_history(): idx = 0 print("-" * 20) for transaction in transactions: idx += 1 print(f"[{idx}]:\u20b9{transaction}") print("-" * 20) def enter_choice(): while True: choice = int(input("\nEnter your choice:")) if choice == 1: amount = int(input("Enter the fixed amount(to be paid every month):")) fixed_amount(amount) elif choice == 2: expense = int(input("Enter the transaction amount:")) transaction_amount(expense) elif choice == 3: make_payment(amount) elif choice == 4: print("Transaction History") transaction_history() elif choice == 5: break else: print("Enter a valid choice!") def main(): welcome() enter_choice() if __name__ == '__main__': main()
#include<bits/stdc++.h> using namespace std; // Struct struct Node { int data; struct Node* next; }; /* Function to get the middle of the linked list*/ void printMiddle(struct Node *head) { struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } printf("The middle element is [%d]\n\n", slow_ptr->data); } } // Function to add a new node void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // A utility function to print a given linked list void printList(struct Node *ptr) { while (ptr != NULL) { printf("%d->", ptr->data); ptr = ptr->next; } printf("NULL\n"); } // Driver Code int main() { // Start with the empty list struct Node* head = NULL; // Iterate and add element for (int i=5; i>0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; }
import math import heapq def minimum_distance(n, x, y): result = 0 cost = {}; h = []; vertices = {} new_tree = {} for i in range(n): if i == 0: cost[i] = 0; else: cost[i] = float('inf'); heapq.heappush(h, (cost[i],i)); vertices[i] = i; while len(h)>0: (c, v) = heapq.heappop(h); del vertices[v] new_tree[v]=v; edge_weights = []; for vertex in vertices.values(): for existent in new_tree.values(): w = math.sqrt((x[existent]-x[vertex])**2 + (y[existent]-y[vertex])**2); heapq.heappush(edge_weights,(w, vertex)); if len(edge_weights)>0: (min_w, z) = heapq.heappop(edge_weights); if cost[z] > min_w: cost[z] = min_w; result+= min_w; new_list=[]; for (weight, node) in h: if node == z: new_list.append((min_w, z)) else: new_list.append((weight, node)) h = new_list; heapq.heapify(h); return result x = [0,0,1,3,3] y = [0,2,1,0,2] print("{0:.9f}".format(minimum_distance(5, x, y)))
import Queue def distance(a, s, t): frontier = Queue.Queue() frontier.put(s) dist = {}; for i in range(len(adj)): dist[i]= float("inf") dist[s] = 0; while not frontier.empty(): u = frontier.get() if u==t: return dist[u]; else: neighbours=a[u]; for e in neighbours: if dist[e] == float("inf"): frontier.put(e); dist[e] = dist[u] + 1; return -1 adj=[[1,3,2],[0,2],[1,0],[0]] print(distance(adj,1,3)) adj_2= [[2,3],[4],[0,3],[2,0],[1]] print(distance(adj_2, 3, 5))
import sys with open(sys.argv[1], 'r') as f: for line in f: uniqueSet = set() print ','.join(str(item) for item in [x for x in line.strip().split(',') if x not in uniqueSet and not uniqueSet.add(x)])
import sys with open(sys.argv[1], 'r') as f: for line in f: sentence = line.split(', ')[0] replace = line.split(', ')[1].strip() for c in replace: sentence = str.replace(sentence, c, '') print sentence
#!/usr/bin/python3 ''' Read an integer N. For all non-negative integers i<N, print i^2. ''' n = int(input()) for i in range (0,n): print(i*i)
import numpy as np def monopoly_outcome(env, agent): ''' Calculate the theoretical optimum quantity, price and profit earned by a monopolist with linear cost and demand functions ''' q = (env.intercept - agent.mc) / 2 * env.slope p = env.intercept - env.slope * q profit = p * q - agent.mc * q results = {0: {'quantity': q, 'price': p, 'profit' : profit}} return results def duopoly_outcome_comp(env, agents): ''' Calculate the competitive outcome quantities, price and profits earned by duopolists with linear cost and demand functions ''' q1 = (env.intercept - 2 * agents[0].mc + agents[1].mc) / 3 * env.slope q2 = (env.intercept - 2 * agents[1].mc + agents[0].mc) / 3 * env.slope p = env.intercept - env.slope * (q1 + q2) profit1 = p * q1 - agents[0].mc * q1 profit2 = p * q2 - agents[1].mc * q2 results = {0: {'quantity': q1, 'price': p, 'profit' : profit1}, 1: {'quantity': q2, 'price': p, 'profit' : profit2}} return results def duopoly_outcome_coll(env, agents): ''' Calculate the collusive outcome quantities, price and profits earned by duopolists with linear cost and demand functions ''' mc = np.min([agent.mc for agent in agents]) q = (env.intercept - mc) / 2 * env.slope p = env.intercept - env.slope * q profit = p * q - mc * q results = {0: {'quantity': q/2, 'price': p, 'profit' : profit/2}, 1: {'quantity': q/2, 'price': p, 'profit' : profit/2}} return results def duopoly_outcome_deviate(env, agents): ''' Calculate the optimal quantities, price and profits earned by duopolists when one is playing collusively, but the other deviates. With linear cost and demand functions ''' mc = np.min([agent.mc for agent in agents]) q = (env.intercept - mc) / 2 * env.slope residual_intercept = env.intercept - q//2 q = (residual_intercept - agents[0].mc) // (2 * env.slope) p = residual_intercept - env.slope * q profit = p * q - agents[0].mc * q results = {0: {'quantity': q, 'price': p, 'profit' : profit}, 1: {'quantity': q, 'price': p, 'profit' : profit}} return results
#!/usr/bin/env python # get input from user response = raw_input("Would you like a toast? [Yes/No]: ") # set response string using if/else construction # Test response to a string if response == "Yes": response_str = "That's great!" else: response_str = "How about a muffin?" # output the response string print response_str
#!/usr/bin/env python # create the subroutine def addNums (*numbers): sum = 0 # initialize starting sum value for num in numbers: # collection loop to get each number sum += num # sum up nums print "The summation is: %d" % sum # output results # call the subroutine addNums(5, 2, 4, 3, 6) # pass a series of numbers
#!/usr/bin/env python import sys # illustrative variables ARG_COUNT = len(sys.argv) - 1 # get num of real arguments FIRST = 1 # index of first argument print "The arugments passed are:" # use collection loop with range to enumerate arguments # Note: range ending must be one greater than desired range for count in range(FIRST,ARG_COUNT+1): # range to gen sequence of numbers arg = sys.argv[count] # get arg using index # print count and argument using count index print " item %d: %s" % (count,arg)
#!/usr/bin/env python import sys # illustrative variables ARG_COUNT = len(sys.argv) - 1 # get num of real arguments FIRST = 1 # index of first argument # utility variables count = ARG_COUNT # initialize counter print "The arugments passed are:" # use count style loop while count >= FIRST: arg = sys.argv[count] # get arg using index # print count and argument using count index print " item %d: %s" % (count,arg) count -= 1 # decrement counter
#Savitskiy Kirill #Problem set 1 # #Problem 1 s = 'dfsefqwfdsaweo' vow = 'euoai' n = 0 for i in vow: for j in s: if i == j: n += 1 print (n) # #Problem 2 s = 'bobazcbobobegghaklbob' w = 'bob' n = 0 for i in range (0,len(s)-2): if (s.find(w,i,i+3)>=0): n += 1 print (n) # #Problem 3 def item_order(order): #order = 'salad water hamburger salad hamburger' s = order.split(' ') meal = ['salad', 'hamburger', 'water'] count = [0,0,0] ind = 0 for i in meal: for j in s: if (i == j): count[ind] = count[ind]+1 ind += 1 print ('salad:', count[0], ' hamburger:', count[1], ' water:', count[2]) item_order('salad water hamburger salad hamburger')
# # Ejercicio _colabirativo_ #cambios introducidos 25/01 import numpy as np # **Ejercicio 1**: Escribir un arreglo con 100 números equiespaciados del 0 al 9. Pista: `linspace` np.linspace(0,9,100) # **Ejercicio 2:** crear un arreglo 1D de 20 ceros. # Reemplazar los primeros 15 elementos por unos. arr = np.zeros(20) nuevo = np.ones(15) arr[:15] = nuevo arr # **Ejercicio 3:** crear un arreglo 1D de 50 ceros. # Reemplazar los primeros 25 elementos por los números naturales del 0 al 24. arr = np.zeros(50) new = np.arange(25) arr[:25] = new arr # **Ejercicio 4:** crear un arreglo 2D de 3 filas y 3 columnas, lleno de ceros. # Reemplazar los elemento de la segunda columna por los números 1, 2 y 3 respectivamente. # Es decir, crear la siguiente matriz: # # ``` # 0 1 0 # 0 2 0 # 0 3 0 # ``` arr = np.zeros((3,3)) arr[:,1] = [1,2,3] arr # **Ejercicio 5:** crear un arreglo 2D de 3 filas y 3 columnas, lleno de ceros. # Reemplazar los elemento de la diagonal por unos. Es decir, crear la siguiente matriz: # # ``` # 1 0 0 # 0 1 0 # 0 0 1 # ``` arr = np.zeros((3,3)) for i in range(3): arr[i,i] = 1 # **Ejercicio 6:** crear un arreglo 2D de 100 filas y 100 columnas, lleno de ceros. # Reemplazar los elemento de la diagonal por unos. Es decir, crear la siguiente matriz: # # ``` # 1 0 0 ... 0 0 0 # 0 1 0 ... 0 0 0 # 0 0 1 ... 0 0 0 # ... # 0 0 0 ... 1 0 0 # 0 0 0 ... 0 1 0 # 0 0 0 ... 0 0 1 # ``` arr = np.zeros((100,100)) arr = np.eye(100) arr
def ok(n, m): if n == 1 or m == 1: return False if n == 2: return m % 3 == 0 if m == 2: return n % 3 == 0 if n % 2 == 0 and m % 3 == 0: return True if n % 3 == 0 and m % 2 == 0: return True if n % 6 == 0: return True if m % 6 == 0: return True return False for T in range(int(input())): n, m = list(map(int, input().split())) print('Yes' if ok(n, m) else 'No')
import re s = input() c = re.sub(r'[aeiouy]', '', s) v = re.sub(r'[^aeiouy]', '', s) print('Vowel' if c < v else 'Consonant')
import sys s = input() start, finish = input().split() start = list(map(int, start.split('-'))) finish = list(map(int, finish.split('-'))) a = [2000, 1, 1] if s == 'WEEK': a = [1999, 12, 27] elif s == 'FEBRUARY_THE_29TH': a = [1996, 2, 29] def addMonth(d, cnt): for i in range(cnt): month = d[1] year = d[0] if month == 12: month = 1 year += 1 else: month += 1 d = [year, month, d[2]] return d days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def addYears(d): year = d[0] + 4 if year % 100 == 0 and year % 400 != 0: year += 4 return [year, d[1], d[2]] def addDays(d, cnt): year, month, day = d day += cnt now = days[month] if month == 2 and (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)): now += 1 if day > now: day -= now month += 1 if month == 13: month = 1 year += 1 d = [year, month, day] return d def nxt(d, what): if s == 'WEEK': return addDays(d, 7) elif s == 'MONTH': return addMonth(d, 1) elif s == 'QUARTER': return addMonth(d, 3) elif s == 'YEAR': return addMonth(d, 12) else: return addYears(d) def prv(d): year, month, days = d days -= 1 if days == 0: month -= 1 days = 28 if month == 0: year -= 1 q = [year, month, days] while True: w = addDays(q, 1) if w == d: return q q = w q = [] while a <= start: a = nxt(a, s) if prv(a) >= finish: q.append([start, finish]) else: q.append([start, prv(a)]) while True: b = nxt(a, s) if b <= finish: q.append([a, prv(b)]) else: break a = b q.append([a, finish]) def get(x): return '0' + str(x) if x < 10 else str(x) def frmt(d): return '-'.join([str(d[0]), get(d[1]), get(d[2])]) print(len(q)) print('\n'.join(map(lambda x: ' '.join(map(frmt, x)), q)))
class Function: """Representation of a Function""" def __init__(self, identifier, returntype, arguments, implemented, label): """Initialize with an identifier(string), returnType(Type), argument(argumentList), implemented(bool) and label(string)""" self.identifier = identifier self.returntype = returntype self.arguments = arguments self.staticsize = 0 self.label = label self.implemented = implemented def getStaticSize(self): """Get the static size required for the SSP command""" size = 5 + self.staticsize + self.getParameterSize() return size def getParameterSize(self): """Get the parameter size required for the cup command""" size = 0 for argument in self.arguments.arguments: size += argument.basetype.getSize() return size
# Rewrite the program that prompts the user for a list of numbers and prints out # the maximum and minimum of the numbers at the end when the user enters "done". # Write the program to store the numbers the user enters in a list and use the # max() and min() functions to compute the maximum and minimum numbers after the # loop completes. if __name__ == '__main__': numbers = [] while True: n = input() if n == "done": break else: numbers.append(int(n)) print("Maximum: "+str(max(numbers))) print("Minimum: "+str(min(numbers)))
#-*- coding:utf-8 -*- import random import itertools # plan 0 def genList0 (x): dic = [str(i+1) for i in range(x)] res = list(set(['-'.join(sorted(random.sample(dic,2))) for i in range(x*2)])) return genList(x) if len(res) < x else res[0:x] def randomList (x): return [i if random.randint(1,2) == 1 else '-'.join(i.split('-')[::-1]) for i in genList0(x)] # plan 1 def genList(x): return [i if random.randint(1,2) == 1 else '-'.join(i.split('-')[::-1]) for i in [str(i[0]) + '-' + str(i[1]) for i in random.sample(list(itertools.combinations(list(range(1,x+1)),2)),x)]] # plan 2 def genList2(x): dic = list(range(1,x+1)) random.shuffle(dic) return [str(i[0]) + '-' + str(i[1]) for i in random.sample(list(itertools.combinations(dic,2)),x)] # plan 3 def genRanList(min, max = None): if not str(min).isdigit(): print('Error: The parameters must be positive integers') exit() if max == None: max = min min = 1 elif not str(max).isdigit(): print('Error: The parameters must be positive integers') exit() if max <= 2: print('Error: The parameters must be more than 2') exit() dic = list(range(min, max + 1)) random.shuffle(dic) res = random.sample(list(itertools.combinations(dic,2)),max - min + 1) return [str(i[0]) + '-' + str(i[1]) for i in res] if __name__ == "__main__": #print(randomList(10)) #print(genList(10)) #print(genList2(3)) print(genRanList(3,15)) #def randnum(min_num,max_num=None): # '随机生成不重复俩俩对应数组' # '|--生成一个指定范围的数列' # '|--打乱数组排序' # '|--生成无序排列组合' # # '|--format函数' # '|--格式化排列组合的中间值 可选填符号 ' # '|--添加指定符号 ' # '|--返回格式化后的数列 ' # # '判断传进的是否一个参数 是的话 min_num = 1' # if max_num==None: # max_num=min_num # min_num = 1 # # list1=list(range(min_num,max_num)) # random.shuffle(list1) # result=random.sample(list(itertools.combinations(list1,2)),len(list1)) # # print(result) # def format(fmt='-'): # '格式转换 默认是 ‘-’' # '可以自定义格式 闭包概念' # fmtre=[] # for x in result: # fmtre.append(str(x[0])+fmt+str(x[1])) # return fmtre # return format # #temp=randnum(11) #print(temp()) #print(temp(' '))
vat = 0.23 cena = float(input()) def calculate_vat(netto): wart_vat = cena * vat netto = cena - wart_vat return(netto) if __name__ == "__main__": vat = calculate_vat(1000) print("{0}".format(vat)) # drugi sposob def calucate_vat(netto): return (netto * 23)/100 if __name__ == "__main__": vat = calucate_vat(777) print("{​​​​0}​​​​".format(vat))
import unittest import io import sys import main ## Test Classes and Methods class TestRoll(unittest.TestCase): # Check that a Roll created with a face value of 4 has a value of 4 def test_roll_creation(self): face = 4 result = main.Roll(face) self.assertEqual(result.value, face) class TestDie(unittest.TestCase): # Check that each face of a Die is <= 6 def test_die_creation(self): result = main.Die() for face in result.die: self.assertLessEqual(face.value, 6) # Check that a roll of a Die is <= 6 def test_die_roll(self): die = main.Die() result = die.roll() self.assertLessEqual(result,6) class TestPlayer(unittest.TestCase): # Check that a Player created with a name has that name attribute def test_player_creation(self): name = 'test player' result = main.Player(name) self.assertEqual(result.name, name) class TestHand(unittest.TestCase): # Check that a Hand created with a player has that player attribute, as well as an initial score of 0 def test_hand_creation(self): name = 'test player' player = main.Player(name) result = main.Hand(player) self.assertEqual(result.player, player) self.assertEqual(result.score, 0) # Check that a Hand has 3 values after 3 dice are rolled and kept def test_hand_keep_roll(self): name = 'test player' player = main.Player(name) result = main.Hand(player) die_a = main.Die() die_b = main.Die() die_c = main.Die() result.keep_roll(die_a.roll()) result.keep_roll(die_b.roll()) result.keep_roll(die_c.roll()) self.assertEqual(len(result.rolls), 3) # Check that an empty hand is displayed as "[empty]" def test_hand_display_hand_empty(self): name = 'test player' player = main.Player(name) hand = main.Hand(player) result = io.StringIO() sys.stdout = result hand.display_hand() result = result.getvalue().rstrip() self.assertEqual(result, '[empty]') # Check that the number of pips displayed matches the value of a non-empty hand def test_hand_display_hand_not_empty(self): name = 'test player' player = main.Player(name) hand = main.Hand(player) die_a = main.Die() die_b = main.Die() hand.keep_roll(die_a.roll()) hand.keep_roll(die_a.roll()) result = io.StringIO() sys.stdout = result hand.display_hand() result = result.getvalue().rstrip() self.assertEqual(result.count('o'), sum(hand.rolls)) # Check that Hand.qualified() returns boolean False after 1 roll def test_hand_qualified(self): name = 'test player' player = main.Player(name) hand = main.Hand(player) die_a = main.Die() hand.keep_roll(die_a.roll()) result = hand.qualified() self.assertEqual(result, False) # Check that Hand.calc_score() returns 0 after 1 roll, and varied behavior after 3 rolls based on qualification def test_hand_calc_score(self): name = 'test player' player = main.Player(name) hand = main.Hand(player) die_a = main.Die() hand.keep_roll(die_a.roll()) hand.calc_score() result = hand.score #self.assertEqual(result, 0) die_b = main.Die() die_c = main.Die() die_d = main.Die() hand.keep_roll(die_b.roll()) hand.keep_roll(die_c.roll()) hand.calc_score() result = hand.score if 1 in hand.rolls and 4 in hand.rolls: self.assertIn(result, hand.rolls) else: self.assertEqual(result, 0) class TestBank(unittest.TestCase): # Check that a Bank created with a player has that player attribute, as well as an initial ante of 0 def test_bank_creation(self): name = 'test player' player = main.Player(name) result = main.Bank(player) self.assertEqual(result.player, player) self.assertEqual(result.ante, 0) # Check that a Bank's total increases by the ante after a win, and ante resets def test_bank_win(self): name = 'test player' player = main.Player(name) result = main.Bank(player) initial_total = result.total ante = 10 result.ante = ante result.win() self.assertEqual(initial_total+ante, result.total) self.assertEqual(result.ante, 0) # Check that a Bank's total decreases by the ante after a loss, and ante resets def test_bank_lose(self): name = 'test player' player = main.Player(name) result = main.Bank(player) initial_total = result.total ante = 10 result.ante = ante result.lose() self.assertEqual(initial_total-ante, result.total) self.assertEqual(result.ante, 0) # Check that a Bank's total stays the same after a tie, and ante resets def test_bank_tie(self): name = 'test player' player = main.Player(name) result = main.Bank(player) initial_total = result.total ante = 10 result.ante = ante result.tie() self.assertEqual(initial_total, result.total) self.assertEqual(result.ante, 0) if __name__ == '__main__': unittest.main()
# 1. simple decorator def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper def say_whee(): print("Whee!") say_whee = my_decorator(say_whee) # @my_decorator is a syntax suger @my_decorator # same as say_whee = my_decorator(say_whee) def say_whee(): print("Whee!") # 2. decoratored functions with arguement and return values def do_twice(func): def wrapper(*args, **kwargs): func(*args, **kwargs) return func(*args, **kwargs) return wrapper @do_twice def say_hellow(name): print('hellow %s' % name) # 3. preserve information about the original function import functools def do_twice_new(func): @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return func(*args, **kwargs) return wrapper
#!/usr/bin/env python3 def heap_sort(l, n): for i in reversed(range(n//2)): move_down(l, n, i) for i in reversed(range(n)): l[0], l[i] = l[i], l[0] move_down(l, i, 0) def move_down(l, n, i): leftChild, rightChild, largest = 2*i+1, 2*i+2, i if leftChild < n and l[leftChild] > l[largest]: largest = leftChild if rightChild < n and l[rightChild] > l[largest]: largest = rightChild if largest != i: l[i], l[largest] = l[largest], l[i] move_down(l, n, largest) if __name__ == "__main__": list_test = [2,4,7,1,3,2,10,9,10,11,34] heap_sort(list_test, len(list_test)) print(list_test)
def listTest(): li_test = [] li_test.append(0) assert(len(li_test) == 1) assert(li_test[0] == 0) li_test.extend([1,2,3]) assert(len(li_test) == 4) li_test.insert(1, 9) # insert 9 before the index 1 assert(li_test[1] == 9 and li_test[2] == 1) # remove elem '9' in li_test # if not exist raise ValueError exceptional li_test.remove(9) assert(li_test[1] == 1) assert(li_test.pop() == 3) li_test.append(3) li_test.extend([1,2,3]) # a.index(x[,start[, end]]) assert(li_test.index(3) == 3) # find index from index 4 to len(li_test) assert(li_test.index(3, 4) == 6) assert(li_test.count(3) == 2) # count elem '3' in li_test # list.copy() only supported in python 3.x # li_copy = li_test.copy() li_copy = li_test[:] # sort li_copy.sort(), li_test.sort(reverse=True) n = len(li_test) - 1 for i,elem in enumerate(li_test): assert(elem == li_copy[n-i]) # reverse li_copy.reverse() for i, elem in enumerate(li_test): assert(elem == li_copy[i]) if __name__ == "__main__": listTest()
import heapq def heappop_max(heap): """Pop the largest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt heapq._siftup_max(heap, 0) else: returnitem = lastelt return returnitem def heappush_max(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def cal_depth(heap): h_n = len(heap) depth = i = 0 while i < h_n: depth += 1 i = 2*i+1 return depth def gen_heap_graph(heap_graph, heap, pos, depth, level): if len(heap) < pos+1: return num_empty = 2**depth-1 empty_list = [" " for i in range(num_empty)] line = empty_list + [heap[pos]] + empty_list if len(heap_graph) < level+1: heap_graph.append(line) else: heap_graph[level] = heap_graph[level] + [' '] + line childleft = 2*pos + 1 childright = childleft + 1 gen_heap_graph(heap_graph, heap, childleft, depth-1, level+1) gen_heap_graph(heap_graph, heap, childright, depth-1, level+1) def print_heap(heap): depth = cal_depth(heap) heap_graph = [] gen_heap_graph(heap_graph, heap, 0, depth-1, 0) for line in heap_graph: linestr = ''.join([str(item) for item in line]) print linestr if __name__ == "__main__": h1 = [12,2,33,4,5,6,7,81,9,10] heapq._heapify_max(h1) print heappop_max(h1) heappush_max(h1, 50) print_heap(h1)
from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score from sklearn.decomposition import PCA import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer try: #The classifier, here, attempts to read the 'tweet-class.csv' file #`header=None` means that the column names have not been given #`sep=','` means that the columns of the csv are separated by commas #`names=['tweets','class']` means that we have assigned names to the columns such that the first column represents # the tweets while the second column contains the corresponding class labels df = pd.read_csv('tweet-class.csv', header=None, sep=',',names=['tweets', 'class']) # columns names if no header #The TfidfVectorizer function transforms the input text into a feature vector #fit_transform() is used to learn the vocabulary dictionary and return term-document matrix vect = TfidfVectorizer() x = vect.fit_transform(df['tweets'].values.astype('U')) y = df['class'] #Setting parameters for the classifier. SIZE=50 STEP=.02 #Dividing the tweet-class.csv file into training and test dataset in the ratio of 85%:15% train,test,train_lab,test_lab=train_test_split(x,y,test_size=.15,random_state=100) clf=DecisionTreeClassifier() clf.fit(train,train_lab) #Running the classifier and printing the output labels for the rows in the test dataset, along with the #accuracy score output=clf.predict(test) print output print accuracy_score(test_lab,output) except UnicodeDecodeError as e: print 'unicode error'
n = int(input("Enter integer : ")) cnt = 0 if n == 0 or n == 1 : print (n,"is not a prime.") elif n == 2 : print (n,"is a prime.") else : for i in range (1,n+1) : if n % i == 0 : cnt = cnt + 1 if cnt > 2 : print (n,"is not a prime.") elif cnt == 2 : print (n,"is a prime.")
# -------------------------- Problem 1 --------------------------------------- with open('score.txt', 'r') as f: studentList = f.readlines() scList = [] # เป็นลิสต์ของลิสต์ของคะแนนกับชื่อ for line in studentList: name, score = line.strip().split() score = float(score) scList.append([score, name]) scList.sort(reverse=True) # เรียงด้วยคะแนนก่อน แล้วเรียงด้วยชื่อ for sc_name in scList: print(sc_name[1]) # ดึงชื่อมาพิมพ์ # ------------------------- Problem 2 ------------------------------------ monthlyIncome = [] # เก็บรายได้ต่อเดือน print('Enter monthly income in 2561:') for i in range(12): inc = int(input()) monthlyIncome.append(inc) quarterlyIncome = [] # เก็บรายได้ต่อไตรมาส for i in range(0,12,3): threeMonthIncome = monthlyIncome[i:i+3] quarterlyIncome.append(sum(threeMonthIncome)) highQtIncome = max(quarterlyIncome) # หารายได้สูงสุดของไตรมาส for i in range(4): # หาไตรมาสของรายได้สูงสุด if quarterlyIncome[i]==highQtIncome: print('Highest income is in quarter',i+1) # ----------------------- Problem 3 ----------------------------------- stock = {} # ดิคชันนารีที่มี product ID, เลข size เป็นคีย์ คู่กับค่าที่เป็นจำนวนสินค้ sizeTable = {'S':0, 'M':1, 'L': 2, 'XL':3} # เก็บเลข size revSz = ['S', 'M', 'L', 'XL'] # ใช้แปลงเลข size กลับมาเป็น S, M, L, XL for i in range(10): product, size, num = input('Enter product ID, size, number of items: ').split() num = int(num) k = (product, sizeTable[size]) # สร้างคีย์จาก product ID และ size ที่แปลงเป็นตัวเลขแล้ว if k in stock.keys(): # เช็คว่ามีคีย์นี้ในดิคชันนารีหรือยัง stock[k] = stock[k]+num else: stock[k] = num sortK = list(stock.keys()) # ดึงคีย์มาสร้างเป็นลิสต์ sortK.sort() # เรียงคีย์ for product, sCode in sortK: print(product, revSz[sCode],stock[product, sCode]) # แปลงเลข size เป็น S, M, L, XL ด้วย revSz
# coding=utf-8 #!/usr/bin/python # Cody Dillinger - EE556 - Homework 4 - MultiLayer Perceptron and Backpropagation for XOR Problem import numpy as np import matplotlib.pyplot as plt import csv, math ############################################################################ def activation_out(x): shiftx = x - np.max(x) exps = np.exp(shiftx) return exps / np.sum(exps) #e_x = np.exp(x - np.max(x)) #return e_x / e_x.sum() #return (10.0 * np.exp(0.001*x)) / (1.0 + np.exp(0.001*x)) ############################################################################ def activation_derivative_out(x): #jacob = [] #print 'x', x #for i in range(len(x)): # jacob.append([]) # for j in range(len(x)): # jacob[i].append([]) # if i == j: # jacob[i][j] = x[i] * (1 - x[i]) # else: # jacob[i][j] = -x[i] * x[j] #print 'jacobian', jacob #return jacob deriv = (.01 * np.exp(0.001*x)) / ((np.exp(0.001*x) + 1.0)**2) #while deriv.any() < .1: # deriv = deriv * 1.5 return deriv #return (10.0 * np.exp(x)) / (np.exp(2.0*x) + 2.0*np.exp(x) + 1.0) ############################################################################ def activation1(x): return (2.0 * np.exp(x)) / (1.0 + np.exp(x)) - 1 ############################################################################ def activation_derivative1(x): deriv = (2.0 * np.exp(x)) / (np.exp(2.0*x) + 2.0*np.exp(x) + 1.0) #while deriv.any() < .1: # deriv = deriv * 1.5 return deriv ############################################################################ def mean_square_error(x): sum_ = 0 sqr_err = [] nan_found = False for i in range(len(x)): if math.isnan(x[i][0]): nan_found = True sqr = ((x[i][0]) **2) sum_ += sqr # sum of squares sqr_err.append([sqr]) # keep matrix of squared error values if nan_found: print 'nan found in error before squaring' return np.array(sqr_err), sum_ / len(x) # return squares and mean square ############################################################################ class MLP: def __init__(self, inputs): self.inputs = inputs self.neuron_num = 10 #len(self.inputs) # num neurons in hidden layers self.feature_num = len(self.inputs[0]) # num features in feature vector self.hidden_layer_num = 10 # num hidden layers self.w_input = np.random.random((self.feature_num, self.neuron_num)) # *.01 self.w_hidden = [] for i in range(self.hidden_layer_num): if i < self.hidden_layer_num - 1: self.w_hidden.append(np.random.random((self.neuron_num, self.neuron_num))) else: self.w_hidden.append(np.random.random((self.neuron_num, 1))) #self.w_hidden1 = np.random.random((self.neuron_num, self.neuron_num)) *.01 #self.w_hidden2 = np.random.random((self.neuron_num, 1)) *.01 # print 'w in', self.w_input # print 'w hidden', self.w_hidden def predict(self, input): # returns final layer output prediction input_next = input weight_next = self.w_input for i in range(self.hidden_layer_num): sum = np.dot(input_next, weight_next) layer_out = activation1(sum) weight_next = self.w_hidden[i] input_next = layer_out sum = np.dot(input_next, weight_next) layer_out = activation_out(sum) return layer_out def get_outputs(self, inputs): # returns more data (all layer outputs) than predict() function input_next = inputs weight_next = self.w_input layer_outputs = [] for i in range(self.hidden_layer_num): sum = np.dot(input_next, weight_next) print 'some of sum', i, 'are', sum[0], sum[5], sum[10] layer_out = activation1(sum) print 'some of layer', i, 'out are', layer_out[0], layer_out[10], layer_out[18] layer_outputs.append(layer_out) weight_next = self.w_hidden[i] input_next = layer_out sum = np.dot(input_next, weight_next) layer_out = activation_out(sum) layer_outputs.append(layer_out) return layer_outputs def learn(self, inputs, outputs, alpha): learning = True iter = 0 convergence_value = 1 # step size when back propagation learning is "done" costs = [] while learning: print 'w in', self.w_input[0], self.w_input[2] for i in range(self.hidden_layer_num): print 'w hidden', i, 'parts are', self.w_hidden[0][0], self.w_hidden[0][2] layer_outputs = self.get_outputs(inputs) final_layer_error = outputs - layer_outputs[self.hidden_layer_num] #final_layer_error = -np.dot(outputs.T, np.log(activation_out(layer_outputs[self.hidden_layer_num]))) square_err, mean_square_err = mean_square_error(final_layer_error) costs.append(mean_square_err) layer_deltas = [] # list in reverse order dJ_dW = [] # list in reverse order print 'final layer error', final_layer_error derivative_out = activation_derivative_out(layer_outputs[len(layer_outputs)-1]) print 'derivative out', derivative_out layer_delta_out = (1/(len(inputs))) * final_layer_error * derivative_out #layer_delta_out = final_layer_error * derivative_out print 'layer delta out', layer_delta_out layer_deltas.append(layer_delta_out) for i in range(self.hidden_layer_num - 1): dJdW = np.dot(layer_deltas[i].T, layer_outputs[len(layer_outputs)-i-1]) print 'dJdW', dJdW dJ_dW.append(dJdW) layer_deltas.append(np.dot(layer_deltas[i], dJ_dW[i]) * activation_derivative1(layer_outputs[len(layer_outputs)-i-1])) dJ_dW.append(np.dot(inputs.T, layer_deltas[len(layer_deltas) - 1])) # layer1_delta.T, inputs) print 'len input', len(inputs) # (1/(len(inputs))) # layer3_delta = (1/(len(inputs))) * layer3_error * activation_derivative_out(layer_outputs[2]) # print 'layer 3 delta', layer3_delta # layer2_delta = layer2_error * activation_derivative_out(layer2_out) # layer1_error = np.dot(layer2_delta, self.w_hidden.T) # .T is transpose with np array # dJ_dW_hidden2 = np.dot(layer3_delta.T, layer_outputs[1]) # print 'dj dw hidden 2', dJ_dW_hidden2 # dJ_dW_hidden = np.dot(layer2_delta.T, layer1_out) # layer1_delta = (1/m) * layer1_error * activation_derivative1(layer1_out) # layer2_delta = np.dot(layer3_delta, dJ_dW_hidden2) * activation_derivative1(layer_outputs[1]) # layer1_delta = np.dot(layer2_delta, dJ_dW_hidden) * activation_derivative1(layer1_out) # dJ_dW_hidden1 = np.dot(layer2_delta.T, layer_outputs[0]) # print 'dj dw hidden 1', dJ_dW_hidden1 # layer1_delta = np.dot(layer2_delta, dJ_dW_hidden1) * activation_derivative1(layer_outputs[0]) #dJ_dW1 = np.dot(inputs.T, layer_deltas[len(layer_deltas)-1])#layer1_delta.T, inputs) #print 'dj dw 1', dJ_dW1 # dJ_dW1 = np.dot(layer1_delta.T, inputs) for i in range(self.hidden_layer_num): self.w_hidden[i] = self.w_hidden[i] - alpha * dJ_dW[len(dJ_dW)-i-1] #self.w_hidden1 = self.w_hidden1 - alpha * dJ_dW_hidden1 #self.w_hidden2 = self.w_hidden2 - alpha * dJ_dW_hidden2 # np.dot(layer1_out.T, layer2_delta) self.w_input = self.w_input - alpha * dJ_dW[0] # np.dot(inputs.T, layer1_delta) print 'iter', iter, ', error', mean_square_err iter += 1 if mean_square_err < convergence_value or iter > 3000: learning = False # print 'w in', self.w_input # print 'w hidden', self.w_hidden return costs ############################################################################ def get_data(filename): with open(filename, 'r') as csvfile: reader = csv.reader(csvfile, delimiter = ',') features = [] class_parameter = [] for row in reader: features.append([float(i) for i in row[:10]]) class_parameter.append([int(row[10])]) print features print class_parameter features = np.array(features) class_parameter = np.array(class_parameter) return features, class_parameter ############################################################################ def main(): glass_training_features, glass_training_class = get_data('glass1.data') # half of data glass_features, glass_correct_class = get_data('glass2.data') # other half of data perceptron = MLP(glass_training_features) costs = perceptron.learn(glass_training_features, glass_training_class, 10) # train the parameters print 'prediction for training set:', perceptron.predict(glass_training_features) print 'prediction for inputs2', perceptron.predict(glass_features) print 'costs', costs plt.plot(costs) plt.ylabel('Cost: Mean Square Error') plt.title('Codys Cost Function (MSE) Plot for HW 4 Glass Problem') plt.xlabel('Number of Batch Gradient Steps') plt.show() return main()
def sort(nums: list[int]): if len(nums) in [0, 1]: return mergesort(nums, 0, len(nums)-1) def mergesort(nums, left, right): if left == right: return mid = left + (right - left) // 2 mergesort(nums, left, mid) mergesort(nums, mid+1, right) merge(nums, left, mid, right) def merge(nums, left, mid, right): if left == right: return p0 = left p1 = mid + 1 temp = [] while p0 <= mid or p1 <= right: if p1 > right: temp.append(nums[p0]) p0 += 1 continue if p0 > mid: temp.append(nums[p1]) p1 += 1 continue if nums[p0] <= nums[p1]: temp.append(nums[p0]) p0 += 1 else: temp.append(nums[p1]) p1 += 1 nums[left: right+1] = temp
class JumpGame(object): def __init__(self, board): self._board = board self._size = len(board) self._cache = [[None] * self._size for _ in range(self._size)] def jump(self): return self._jump_at(0, 0) def _jump_at(self, y, x): n = self._size if x >= n or y >= n: return False if y == n-1 and x == n-1: return True if self._cache[y][x] is not None: return self._cache[y][x] jump_size = self._board[y][x] self._cache[y][x] = self._jump_at(y + jump_size, x) or self._jump_at(y, x + jump_size) return self._cache[y][x] def jump(board, y, x): n = len(board) if x >= n or y >= n: return False if y == n-1 and x == n-1: return True jump_size = board[y][x] return jump(board, y + jump_size, x) or jump(board, y, x + jump_size) if __name__ == "__main__": board1 = ( (2, 5, 1, 6), (3, 1, 1, 2), (3, 2, 3, 2), (1, 1, 3, 1) ) assert(JumpGame(board1).jump()) board2 = ( (2, 5, 1, 6), (3, 1, 1, 3), (3, 2, 1, 2), (1, 1, 3, 1) ) assert(False == JumpGame(board2).jump())
def euler_circuit(adj, circuit, here): for there in range(len(adj)): if adj[here][there] > 0: adj[here][there] -= 1 adj[there][here] -= 1 print("here: %d, there: %d, circuit: %s" % (here, there, circuit)) euler_circuit(adj, circuit, there) circuit.append(here) print(circuit) if __name__ == "__main__": adj = [ [0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 1, 1], [1, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 1, 0] ] circuit = [] euler_circuit(adj, circuit, 0) circuit.reverse() print("result:%s" % circuit)
from collections import Counter def is_perm_of_palindrome(s): counter = Counter(s) num_of_odds = 0 for c, n in counter.items(): if n % 2 != 0: num_of_odds += 1 if num_of_odds > 1: return False return num_of_odds == 0 or num_of_odds == 1 if __name__ == "__main__": assert(False == is_perm_of_palindrome("abcde")) assert(True == is_perm_of_palindrome("ababc"))
class DisjointSet(object): def __init__(self, size): self.parent = [] self.rank = [] for i in range(size): self.parent.append(i) self.rank.append(1) def find(self, u): if u == self.parent[u]: return u self.parent[u] = self.find(self.parent[u]) return self.parent[u] def union(self, u, v): u = self.find(u) v = self.find(v) if (u == v) return if rank[u] > rank[v]: self.parent[v] = u else: self.parent[u] = v if rank[u] == rank[v]: rank[v] += 1 if __name__ == "__main__": ds = DisjointSet(10) ds.union(1, 9) ds.union(0, 8) ds.union(8, 9) print(ds.find(0)) print(ds.parent)
import random import string def getCode(length = 10, char = string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation): try: crtPass = "".join(random.choice( char) for x in range(length)) print 'Use The Password in side the ' return crtPass except TypeError: print'Incorrect parameter' """ This is a Alphanumeric Password Genarator it is default setting is for 10 characters you can enter the any other length you desire """
from math import sqrt for _ in range(int(input())): c = int(input()) d = 1 + 8 * c x = int((sqrt(d) - 1) // 2) print(x)
from math import sqrt for _ in range(int(input())): n, v1, v2 = map(int, input().split()) t1 = sqrt(2) * n / v1 t2 = 2 * n / v2 if t1 < t2: print("Stairs") else: print("Elevator")
n = int(input()) people = 5 liked = 2 total = 2 for x in range(2, n+1): people = 3 * liked liked = people // 2 total += liked print(total)
length = int(input()) string = input() key = int(input()) msg = "" for x in string: if ord('a') <= ord(x) <= ord('z'): msg += chr(((ord(x) - ord('a') + key) % 26) + ord('a')) elif ord('A') <= ord(x) <= ord('Z'): msg += chr(((ord(x) - ord('A') + key) % 26) + ord('A')) else: msg += x print(msg)
def ismultipleof(arr, num): for i in arr: if num % i != 0: return False return True def isfactorof(arr, num): for i in arr: if i % num != 0: return False return True n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) a.sort() b.sort() count = 0 for x in range(a[-1], b[0]+1): if ismultipleof(a, x) and isfactorof(b, x): count += 1 print(count)
arr = list(map(int, input().split())) word = input() h = 0 for x in word: if arr[ord(x)-ord('a')] > h: h = arr[ord(x)-ord('a')] print(h * len(word))
for _ in range(int(input())): n = int(input()) l = [1, 2] for i in range(2, n): l.append(0) l[i] = l[i-1] + 3 for i in range(n): print(l[i], end=" ") print("")
l = [] for _ in range(int(input())): l.append(int(input())) print(*sorted(l), sep="\n")
fact = [1] for i in range(1, 21): fact.append(0) fact[i] = fact[i-1] * i for _ in range(int(input())): print(fact[int(input())])
yrs = [2010, 2015, 2016, 2017, 2019] for _ in range(int(input())): if int(input()) in yrs: print("HOSTED") else: print("NOT HOSTED")
prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] #, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] for _ in range(int(input())): n = int(input()) pdt = 1 count = 0 for x in prime: pdt *= x if pdt > n: break elif pdt == n: count += 1 break count += 1 print(count)
for _ in range(int(input())): num = input() n = int(num) count = 0 for x in num: if x == "0": continue else: if n % int(x) == 0: count += 1 print(count)
import numpy as np # put user made clustering algorithms here to transform them into sklearn esque class objects class RandomAssign(object): """ Randomly assigns all stars to a cluster. If the number of clusters is not specified, the algorithm chooses a random number less than the total number of stars. """ def __init__(self,k = None): """ Assigns the number of clusters. k: The number of clusters to assign to (can be None but this doesn't correspond to no clusters) """ self.k = k return None def fit_predict(self,clusterdata): """ Assigns each star in clusterdata to a random group. Will also update k to be a random number less than the total number of samples if k is unspecified clusterdata: array of abundance or spectra information to cluster Returns cluster assignments. """ numstars = clusterdata.shape[0] if not self.k: self.k = np.random.randint(0,numstars,size=1) self.labels_pred = np.random.randint(0,self.k,size=numstars) return self.labels_pred
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] ### your code goes here ###predictions ,ages, net_worths type are numpy.ndarray, need to add [i][0] for i in range(len(predictions)): p = predictions[i][0] a = ages[i][0] n = net_worths[i][0] err = round(abs(p-n)/n, 4 ) cleaned_data.append((a, n, err)) # sort list using lambda small to large cleaned_data = sorted(cleaned_data, key=lambda d:d[2]) #remove 10% outliers points cleaned_data = cleaned_data[:80] return cleaned_data
''' state - the state of the game being evaluated level - determines what level being evaluated where Max: level % 2 == 0 Min: level % 2 != 0 ''' def minimax(state, level): ''' If we are at a terminal state, return the utility (value) of the state. This may be a simple +1/0/-1 representing whether the terminal state is a win, draw, or loss. ''' if terminalTest(state): return utility(state) else: if level % 2 == 0: # max node max = float("-inf") for s in successors(state): temp = minimax(s,level+1) if temp > max: max = temp return max else: # min node min = float("inf") for s in successors(state): temp = minimax(s,level+1) if temp < min: min = temp return min
# -*- coding: utf-8 -*- #!usr/bin/env python 3 def write_file(data,filepath): with open(filepath,'w') as f: for n in data: f.write(str(n)+'\n') f.close()
stack = [] lb = int(input("Enter the lower bound:")) ub = int(input("Enter the upper bound:")) for n in range(lb, ub): for x in range(2, n): # Keep this as 2 no matter what if n % x == 0: #print(n, 'equals', x, '*', int(n/x)) break else: # loop fell through without finding a factor print(n, 'is a prime number') stack.append(n) print('Type "main()" for a list of primes between ',lb,' and ',ub) def main(): for item in stack: print(item)
def main(): print (letter) score = float(input('What mark did you get?')) if score >= 90: letter = 'A*' main() print("Very good") elif score >= 80: letter = 'A' main() print("Well done") elif score >= 70: letter = 'B' main() print("Not bad") elif score >= 60: letter = 'C' main() print("Could do better") else: letter = 'D' main() print("Jesus Christ, what happened?")
rep = 1 while rep == 1: num = int(input("Enter a number you think is a prime:")) for n in range(num,num+1): for x in range(2,n): if n % x == 0: print("no,",n, 'equals', x, '*', int(n/x)) break else: print(n, "is a prime number. Well done.")
person = input('Enter your name: ') print('Hello,', person+'!') # The + sign means there is no space after the name
temperature = float(input('What is the temperature? ')) if temperature > 30: print('Wear shorts.') else: print('Wear trousers.') print('Get some exercise outside.') import os os.system("pause")
SIZE= 10 class Heaps: def __init__(self): self.heap = [0]*SIZE self.size = 0 def insert(self,data): if self.size == SIZE: return self.heap[self.size]=data self.size+=1 self.check(self.size-1) def check(self,index): parent_index = (index-1)//2 if index > 0 and self.heap[index] < self.heap[parent_index]: self.swap(index,parent_index) self.check(parent_index) def getmin(self): return self.heap[0] def getmax(self): return self.heap[self.size-1] def poll(self): min = self.getmin() self.swap(0,self.size-1) self.size -= 1 #decrement and remove the last item self.check_down(0) return min def check_down(self,index): left_index = 2*index +1 right_index = 2*index +2 smallest_val_index = index if left_index < self.size and self.heap[left_index] < self.heap[smallest_val_index]: smallest_val_index= left_index if right_index < self.size and self.heap[right_index] < self.heap[smallest_val_index]: smallest_val_index= right_index if index != smallest_val_index: self.swap(index,smallest_val_index) self.check_down(smallest_val_index) def heap_sort(self): if self.heap: for i in range(0,self.size): print (self.poll()) def swap(self,index1,index2): self.heap[index1], self.heap[index2] = self.heap[index2],self.heap[index1] if __name__ == "__main__": Heap = Heaps() Heap.insert(10) Heap.insert(12) Heap.insert(-1) Heap.insert(19) Heap.insert(80) print ("min: ",Heap.getmin()) print ("max :", Heap.getmax()) Heap.heap_sort()
##used to calculate standard deviation import math import numpy class StandardDeviation(): ##passed in a pt array and returns the simple standard deviation @staticmethod def simple2(pt_array): num_points = len(pt_array) ##calculate avg sum = 0 for pt in pt_array: sum += pt.value avg = sum/float(num_points) ##calculate sum of squares sos = 0 for pt in pt_array: sos += (pt.value-avg)*(pt.value-avg) sos /= float(num_points-1) return math.sqrt(sos) ##stddev using numpy @staticmethod def simple(pt_array): val_array = [] for p in pt_array: val_array.append(p.value) return numpy.std(val_array)
#Perceptron. #created by Isaí vargas Chávez-Age 19 All rigths reserved @ # Compilador Clang 6.0 (clang-600.0.57)] on darwin. # version 1.0. # 03/02/2018 in Mexico City. import math import random import artificialNeuron from artificialNeuron import Neuron if __name__ == "__main__": neuron = Neuron ( ) #New neuron born with 1 inicialization in bias as default. iterathion = 0 numberinputs=int(input("Introduce el numero de entradas deseadas para el set de entrenamiento:")) numberinputs = numberinputs + 1 for i in range(numberinputs): inputTrainSet=int(input("Introduce el set de entrenamiento:")) neuron.add_trainingVector(inputTrainSet ) numberinputs=int(input("Introduce el numero de entradas deseadas:")) for i in range(numberinputs): # inputvector.append ( int(input( ) )) inputsignal=int(input("Introduce la entrada:")) inputsignal = float(inputsignal) neuron.add_inputVector( inputsignal ) #Pass the input data to the Neuron Class numberinputs = numberinputs + 1 neuron.add_weightsVector(numberinputs ) k=0 while(neuron.y !=neuron.trainingVector[ iterathion] ): iterathion = iterathion + 1 k = k+1 neuron.v=neuron.Synapsis( iterathion,numberinputs,inputsignal) neuron.y=neuron.Signum( ) inputweight=neuron.Learn(neuron.y,iterathion,inputsignal,inputweight,inputTrainSet,k) if ( neuron.inputsVector == neuron.trainingVector ): print("Aprendizaje completado:",neuron.inputsVector,neuron.trainingVector) print("Las Entradas introducidas son : " ,neuron.inputsVector) print ("Los pesos sinapticos introducidos son:",neuron.weightsVector)
# Programming Question-5 Algorithms Part 1 # Question 1 # Dijkstra's Shortest Path import numpy as np graph = [] # read with open('/Users/minjay/Documents/Documents/Courses/Algorithms_Part1/dijkstraData.txt') as f: for line in f: line = line.rstrip() line = line.replace(',', '\t') line = line.split('\t') line = [int(i) for i in line] graph.append(line) # transform nodes = [] edges = [] weights = [] for line in graph: nodes.append(line[0]) for i in range(1, len(line), 2): tmp = [line[0], line[i]] flag = 0 for j in edges: if set(tmp)==set(j): flag = 1 break if flag==0: edges.append(tmp) weights.append(line[i+1]) # init n = len(nodes) X = [1] # row-major order A = np.ones((1, n))*1000000 A[0][0] = 0 # main while len(X)<n: # put outside min_dist = 1000000 w_star = 0 v_star = 0 for j in range(len(edges)): edge = edges[j] if edge[0] in X and edge[1] not in X: dist = A[0][edge[0]-1]+weights[j] if dist<min_dist: min_dist = dist w_star = edge[1] v_star = edge[0] elif edge[0] not in X and edge[1] in X: dist = A[0][edge[1]-1]+weights[j] if dist<min_dist: min_dist = dist w_star = edge[0] v_star = edge[1] # put outside X.append(w_star) A[0][w_star-1] = min_dist print(A[0][6]) print(A[0][36]) print(A[0][58]) print(A[0][81]) print(A[0][98]) print(A[0][114]) print(A[0][132]) print(A[0][164]) print(A[0][187]) print(A[0][196])
# Write the code that: # 1. Prompts the user to enter a letter in the alphabet: # Please enter a letter from the alphabet (a-z or A-Z): # 2. Write the code that determines whether the letter entered is a vowel # 3. Print one of following messages (substituting the letter for x): # - The letter x is a vowel # - The letter x is a consonant letter = input('Enter a letter from the alphabet (a-z or A-Z): ').lower() if letter in 'a e i o u': print(f'The letter {letter} is a vowel') else: print(f'The letter {letter} is a consonant') # Write the code that: # 1. Prompts the user to enter a phrase: # Please enter a word or phrase: # 2. Print the following message: # - What you entered is xx characters long # 3. Return to step 1, unless the word 'quit' was entered. phrase = '' while phrase != 'quit': phrase = input('Enter word or phrase: ') print(f'What you entered is {len(phrase)} characters long') # Write the code that: # 1. Prompts the user to enter a dog's age like this: # Input a dog's age: # 2. Calculates the equivalent dog years, where: # - The first two years count as 10 years each # - Any remaining years count as 7 years each # 3. Prints the answer in the following format: # The dog's age in dog years is xx dog_years = int(input("Input the dog age: ")) if dog_years < 3: human_years = dog_years * 10 else: human_years = 20 + (dog_years - 2) * 7 print(f"The dog age in human years is {human_years}") # Write the code that: # 1. Prompts the user to enter the three lengths of a triangle (one at a time): # Enter the lengths of three side of a triangle: # a: # b: # c: # 2. Write the code that determines if the triangle is: # equalateral - all three sides are equal in length # scalene - all three sides are unequal in length # isosceles - two sides are the same length # 3. Print a message such as: # - A triangle with sides of <a>, <b> & <c> is a <type of triangle> triangle print('Enter lengths for the sides of a triangle:') a = int(input('a: ')) b = int(input('b: ')) c = int(input('c: ')) if a == b and b == c: print(f'A triangle with {a}, {b} & {c} is an equalateral triangle') elif a != b and a != c and b != c: print(f'A triangle with {a}, {b} & {c} is a scalene triangle') else: print(f'A triangle with {a}, {b} & {c} is an isosceles triangle') # exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / number: 3 # term: 5 / number: 5 # etc. term = 0 a = 0 b = 1 while term < 50: if term < 2: print(f'term: {term} / number: {term}') else: num = a + b print(f'term: {term} / number: {num}') a = b b = num term += 1 # exercise-06 What's the Season? # Write the code that: # 1. Prompts the user to enter the month (as three characters): # Enter the month of the year (Jan - Dec): # 2. Then prompts the user to enter the day of the month: # Enter the day of the month: # 3. Calculate what season it is based upon this chart: # Dec 21 - Mar 19: Winter # Mar 20 - Jun 20: Spring # Jun 21 - Sep 21: Summer # Sep 22 - Dec 20: Fall # 4. Print the result as follows: # <Mmm> <dd> is in <season> month = input('Enter the abbreviated month of the seasons (Jan - Dec): ') day = int(input('Enter the date of that month: ')) if month in ('Jan', 'Feb', 'Mar'): season = 'Winter' elif month in ('Apr', 'May', 'Jun'): season = 'Spring' elif month in ('Jul', 'Aug', 'Sep'): season = 'Summer' else: season = 'Fall' if month == 'Mar' and day > 20: season = 'Spring' elif month == 'Jun' and day > 20: season = 'Summer' elif month == 'Sep' and day > 21: season = 'Fall' elif month == 'Dec' and day > 21: season = 'Winter' print(f'{month} {day} is in {season}')
""" import time t = time.time() e = (1 + (float(1) / 10000000000)) ** 10000 # eulers number """ def fact(n): # factorial function. i = 2 s = 1 while i <= n: s *= i i += 1 return s def ncr(n, r): return fact(n) / (fact(r) * fact(n-r)) class Sample(): # class for a random sample . def __init__(self, list): # list contains he values of the random sample. self.list = list def sum(self): s = 0 for i in self.list: s += i return s def mean(self): # wokring out the mean of the random sample. s = self.sum() return float(s) / len(self.list) def var(self): # wokring out the variance of the random sample. m = self.mean() s = 0 for i in self.list: s += float((i - m) ** 2) / (len(self.list) - 1) return s def stddev(self): # wokring out standard deviation of the random sample. s = self.var() return s ** 0.5 class Binomial(): # class for a binomially distributed random variable x. def __init__(self, n, p): self.n = float(n) self.p = float(p) def mean(self): return self.n * self.p def var(self): return self.n * self.p * (1 - self.p) def stddev(self): s = self.var() return s ** 0.5 def probx(self, x): # probability distribution function of x. return ncr(self.n, x) * (self.p ** x) * ((1 - self.p) ** (self.n - x)) def cumprobx(self, x): # cumulative distribution function of x. s = 0 i = 0 while i <= x: s += self.probx(i) i += 1 return s def invcumprobx(self, x): # inverse cumulative distribution function of x. # Works out the chance of being successful in x trials or more. return 1 - self.cumprobx(x) + self.probx(x) class Poisson(): # class for a poisson distributed random variable x def __init__(self, p): self.p = p def mean(self): return self.p def var(self): return self.p def stddev(self): return self.p ** 0.5 def probx(self, x): # probability distribution function of x. return ((self.p ** x) * (e ** (-1 * self.p))) / fact(x) def cumprobx(self, x): # cumulative distribution function of x. # Works out the chance of being successful in trials x or less. s = 0 i = 0 while i <= x: s += self.probx(i) i += 1 return s def invcumprobx(self, x): # Works out the chance of being successful in x trials or more. return 1 - self.cumprobx(x) + self.probx(x) # examples sample1 = Poisson(0.6) print sample1.mean() print sample1.cumprobx(50) ylist = [0, 1, 2, 2, 2, 3] q = Sample(ylist) print q.sum() # geometric function , pdf and cdf calc class Geo(): # class for a geometrically distributed random variable x. def __init__(self, p): # p = sucess rate self.p = float(p) def pdf(self, x): # # probability distribution function of x, (x = trials) self.x = float(x) return self.p * (1 - self.p) ** (x - 1), self.x def mean(self): return 1 / pdf(x) t1 = Geo(0.5) print t1.pdf(10),
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 21:00:01 2016 @author: Geetha Yedida """ class Animal(object): """Makes cute animals.""" is_alive = True health = "good" def __init__(self, name, age): self.name = name self.age = age # Add your method here! def description(self): print self.name print self.age hippo = Animal("Hippopotamus", 98) sloth = Animal("Sloth",3) ocelot = Animal("Ocelot", 2) hippo.description() print hippo.health print sloth.health print ocelot.health
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 11:46:04 2016 @author: Geetha Yedida """ def product(integers): product = 1 for i in range(len(integers)): product = product * integers[i] return product
# -*- coding: utf-8 -*- """ Created on Thu Feb 04 13:29:25 2016 @author: Geetha Yedida """ my_list = [i**2 for i in range(1,11)] my_file = open("output.txt", "r+") # Add your code below! for i in my_list: my_file.write(str(i)) my_file.write("\n") my_file.close()
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 11:46:29 2016 @author: Geetha Yedida """ def median(ls): count = len(ls) med = sorted(ls) mid = count / 2 if count % 2 == 0: return (med[mid] + med[mid-1])/2.0 else: return med[mid]
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 11:15:37 2016 @author: Geetha Yedida """ from datetime import datetime now = datetime.now() print '%s/%s/%s %s:%s:%s' % ( now.month, now.day,now.year,now.hour, now.minute,now.second)
import csv, sqlite3 #Read given file and return the sql query def get_sql_query_string(sqlFile): fd = open(sqlFile, 'r') sqlFile = fd.read() fd.close() return sqlFile #Execute given aggregate query(Like sum, count) and return result. def execute_aggregate_query(sqlFile): result = cur.execute(get_sql_query_string(sqlFile)) return result.fetchone()[0] #Execute given query and return result. def execute_query(sqlFile): result = [] for row in cur.execute(get_sql_query_string(sqlFile)): result.append(" ".join(map(str, row))) #print (" ".join(map(str, row))) return result if __name__ == '__main__': con = sqlite3.connect("izmir.db") cur = con.cursor() print("Number of ways: ", execute_aggregate_query("sql/select_way_size.sql")) print("Number of nodes: ", execute_aggregate_query("sql/select_nodes_size.sql")) print("Number of unique users: ", execute_aggregate_query("sql/unique_users.sql")) print( "Top 10 contributing users: ", execute_query("sql/contributing_user.sql")) print("Number of users appearing only once: ", execute_query("sql/users_appearing_only_once.sql")) print("Biggest religion : ", execute_query("sql/biggest_religion.sql")) print("Most popular cuisines : ", execute_query("sql/popular_cuisines.sql")) print("First contribution : ", execute_query("sql/first_contribution.sql")) print("Most popular bank : ", execute_query("sql/popular_bank.sql")) print("Most popular amenity : ", execute_query("sql/amenity.sql")) con.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 8 19:06:13 2018 @author: duh17 """ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if x.bit_length() > 31 : return 0 temp = -int(str(-x)[::-1]) if x < 0 else int(str(x)[::-1]) return 0 if temp.bit_length() > 31 else temp x = 1534236469 do = Solution() print(do.reverse(x))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 8 18:48:25 2018 @author: duh17 """ class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix[:] = map(list,zip(*matrix[::-1])) matrix = [ [1,2,3], [4,5,6], [7,8,9] ] do = Solution() do.rotate(matrix) print(matrix)
Countries=['Afghanistan','Albania', 'Argentina','Austria','Bahamas','Bahrain','Bangladesh','Barbados','Belarus','Belgium','Bermuda','Bhutan','Bolivia'] Capital=["Kabul",'Tirana','Buenos Aires','Vienna','Nassau','Manama','Dhaka','Bridgetown','Minsk','Brussels','Hamilton','Thimphu','Sucre'] Currency=["Afghani","Lek", "Peso","Euro","Bahamian Dollar","Bahraini dinar","Taka","Barbadian Dollar","Belarusian ruble","Euro","Bermudian Dollar","Bhutanese ngultrum","Boliviano"] Continent=["Asia","Europe",' ',"Europe","North America","Asia","Asia","North America","Europe","Europe","North America","Asia","South America"] C=[Countries,"Capital","Currency","Continent"] S=[Countries,Capital,Currency,Continent] score= 0 correct_answers=[] wrong_answers=[] from random import randint for i in range(10): question_type = randint(1,3) country_index=randint(0,12) Answer=input("what is the "+ C[question_type]+" of "+ C[0][country_index]+"? ") if Answer== (S[question_type][country_index]) : score+=1 print("Correct! \n") else: wrong_answers.append("Question " + str(i)+": The "+ C[question_type]+" of "+ C[0][country_index]+" is "+S[question_type][country_index]) print("Wrong! \n") print("your score is "+ str(score)) print("Corrections:") for i in range(len(wrong_answers)): print(wrong_answers[i])
from string import punctuation """ Write a small text editor, that is, write a program that asks the user to input a text and then the program offers the following options: 1) Count the number of words in the text. 2) Count the number of a given string in the text. 3) Count the number of punctuation marks in the text. 4) Remove the punctuation marks. 5) Remove capitalization 6) Putting the first letter in the capital in case it is not. """ Text=input("Enter the text: ") option=eval(input("Enter the option: ")) if option ==1: print("The number of words are "+str( Text.count(" ")+1)) if option ==2 : search_word=input("Enter the sting that you want to count ") print("The number of "+ search_word+"s is " + str( Text.count(search_word) )) if option ==3: num=0 from string import punctuation for c in Text: if c in punctuation: num+=1 print(num) if option ==4: for c in punctuation: Text = Text.replace(c, '' ) print(Text) if option == 5: E=Text.lower() print(E) if option ==6: for i in range(len(Text)): if Text[i]=="." and i !=len(Text)-1 : Text=Text[:i+1]+ " "+Text[i+2].upper() +Text[i+3:]
alphabet = 'abcdefghijklmnopqrstuvwxyz' key = 'xznlwebgjhqdyvtkfuompciasr' secret_message = input( ' Enter your message: ' ) secret_message = secret_message.lower() for c in secret_message: if c.isalpha(): print(key[alphabet.index(c)],end= '' ) else: print(c, end= '' ) print()
# Problem B - Digit Sums # input N = input() N_str = list(N) N_num = int(N) # initialization digit_sum = 0 # count for n in N_str: tmp = int(n) digit_sum += tmp # check if N_num%digit_sum==0: print("Yes") else: print("No")
# Problem A - スーパーICT高校生 # input process S = input() # initialization teacher_data = 'ict ' str_step = 0 # step process for i in range(len(S)): if S[i].lower()==teacher_data[str_step]: str_step += 1 if str_step==3: break # output process if str_step==3: print('YES') else: print('NO')
# 競技プログラミングで使える関数集合 # 組み合わせ def combinations_count(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r)) # 最大公約数を列挙する関数 def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n//i) divisors.sort() return divisors # bit全探索を行ってくれる関数 def bit_search(): opt_list = [] for i in range(8): opt = [0, 0, 0] for j in range(3): if ((i>>j)&1): opt[3-j-1] = 1 opt_list.append(opt) # 素因数分解 def factorization(n): arr = [] temp = n for i in range(2, int(-(-n**0.5//1))+1): if temp%i==0: cnt=0 while temp%i==0: cnt+=1 temp //= i arr.append([i, cnt]) if temp!=1: arr.append([temp, 1]) if arr==[]: arr.append([n, 1]) return arr # Union Find class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): return {r: self.members(r) for r in self.roots()} def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots()) # 逆元を求めるスクリプト n = 10 ** 9 k = 2 * 10 ** 5 mod = 10**9 + 7 def modinv(x): return pow(x, mod-2, mod) modinv_table = [-1] * (k+1) for i in range(1, k+1): modinv_table[i] = modinv(i) def binomial_coefficients(n, k): ans = 1 for i in range(k): ans *= n-i ans *= modinv_table[i + 1] ans %= mod return ans print(binomial_coefficients(n, k)) # 二項係数を求めるスクリプト MOD = 998244353 fact = [1, 1] fact_inv = [1, 1] inv = [0, 1] for i in range(2, N+1): fact.append((fact[-1] * i)%MOD) inv.append((-inv[MOD%i] * (MOD//i))%MOD) fact_inv.append((fact_inv[-1] * inv[-1])%MOD) def cmb(n, r, p): if (r < 0) or (n < r): return 0 r = min(r, n-r) return fact[n] * fact_inv[r] * fact_inv[n-r] % p
# Problem A - Heavy Rotation # input N = int(input()) # output if N%2==0: print("White") else: print("Black")
# Problem A - 暗証番号 # input N = list(input()) # initialization nums_len = len(set(N)) # output if nums_len==1: print("SAME") else: print("DIFFERENT")
import unittest from math import sqrt def distanceFormula(x1, y1, x2, y2): try: return sqrt(pow((x2-x1), 2) + pow((y2-y1), 2)) except: print("Please provide a proper input") class distanceFormulaTests(unittest.TestCase): def test_normalInputs(self): self.assertEqual(distanceFormula(1,1,0,0), sqrt(2)) def test_bigInputs(self): self.assertEqual(distanceFormula(200, 200, -200, -200), sqrt(320000)) def test_negativeInputs(self): self.assertEqual(distanceFormula(-5, -5, -6, -6), sqrt(2)) if __name__ == 'main__': unittest.main()
""" Так как PyPika не имеет возможности задавать конструкции вида `col IS TRUE` или `col IS FALSE`, то эта возможность была добавлена при помощи этого патча. Данный модуль необходимо импортировать для использования данной возможности """ from functools import wraps from typing import Any import pypika def add_method(cls): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) setattr(cls, func.__name__, wrapper) return func return decorator class TrueCriterion(pypika.terms.NullCriterion): def get_sql(self, with_alias: bool = False, **kwargs: Any) -> str: sql = "{term} IS TRUE".format(term=self.term.get_sql(**kwargs), ) return pypika.terms.format_alias_sql(sql, self.alias, **kwargs) class FalseCriterion(pypika.terms.NullCriterion): def get_sql(self, with_alias: bool = False, **kwargs: Any) -> str: sql = "{term} IS FALSE".format(term=self.term.get_sql(**kwargs), ) return pypika.terms.format_alias_sql(sql, self.alias, **kwargs) @add_method(pypika.terms.Term) def istrue(self) -> "TrueCriterion": return TrueCriterion(self) @add_method(pypika.terms.Term) def nottrue(self) -> "pypika.terms.Not": return self.istrue().negate() @add_method(pypika.terms.Term) def isfalse(self) -> "FalseCriterion": return FalseCriterion(self) @add_method(pypika.terms.Term) def notfalse(self) -> "pypika.terms.Not": return self.isfalse().negate()
#--- endswith() string.endswith('.csv') # returns True if the string ends with the string passed in as the argument #--- iterating through a dictionary d = {(1,2): 3, (4,5): 6} for k, v in d: print(k) print(v) # A new built-in function, enumerate(), will make certain loops a bit clearer. # enumerate(thing), where thing is either an iterator or a sequence, # returns a iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth. L = [10,11,12,13,14] for i, item in enumerate(L): # ... compute some result based on item ... print(i) print(item) #------ replace characters in a string ------ # # http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python import re line = re.sub('[!@#$]', '', line) # OR # Python 3 translation_table = dict.fromkeys(map(ord, '!@#$'), None) unicode_line = unicode_line.translate(translation_table) # OR # Python 3 unicode_line = unicode_line.translate({ord(c): None for c in '!@#$'}) #OR new_headlines_words = [] for word in headlines_words: for char in word: if char in bad_chars: word = word.replace(char,'') new_headlines_words.append(word) #---- map : apply a function to each item in a list map(function, iter) # Example : make a list containing the length of each strings in a list of strings map(len, strings) #---- filter : filter / only keep elements that satisfy a a predicate. filter(pred, iter) # Example : filter(is_even, range(100)) #--------------------- ERRORS --------------------# # List of errors: https://www.tutorialspoint.com/python/python_exceptions.htm #---- isinstance isinstance(object, type) #---- Assert : assert tests an expression, and if the result comes up false, an exception is raised. # assert is like a raise-AssertionError-if-not statement. # An expression is tested, and if the result comes up false, an AssertionError exception is raised. assert statement #---- Exception handling #---- finally try: except: finally: #---- else try: except: else: try: fh = open(file_path, "r+") except Exception as e: print "type of exception is: ", e.__class__.__name__ # OR try: fh = open(file_path, "r+") except IOError, argument: print argument
# Example of a decorator #Write code here def wrapper(function): def fun(lst): result = function(lst) sorted_list = sorted(result) return sorted_list return fun @wrapper def convert_to_phone(num_list): output = [] for phone_num in num_list: output.append('+1' + ' ' + str(phone_num[-10:-7]) + ' ' + str(phone_num[-7:-4]) + ' ' + phone_num[-4:]) return output if __name__ == '__main__': phone_nums = ['06502505121', '+19658764040'] convert_to_phone(phone_nums)
from itertools import permutations suits = ['h', 'c', 's', 'd'] def all_permutations(): for y1 in suits: for y2 in suits: if y2 == y1: continue for y3 in suits: if y3 in {y1, y2}: continue for y4 in suits: if y4 in {y1, y2, y3}: continue yield dict(zip(suits, [y1, y2, y3, y4])) def permutations_of(x): return {tuple(p[i] for i in x) for p in all_permutations()}
""" This module is python practice exercises for programmers new to Python. All exercises can be found at: http://www.practicepython.org/exercises/ You may submit them there to get feedback on your solutions. Put the code for your solutions to each exercise in the appropriate function. DON'T change the names of the functions! You may change the names of the input parameters. Put your code that tests your functions in the if __name__ == "__main__": section Don't forget to regularly commit and push to github. Please include an __author__ comment. """ import json import requests from bs4 import BeautifulSoup # 5: List Overlap def list_overlap(list1, list2): # olap = [] # for x in list1: # if x in list2: # olap.append(x) olap = list(set(list1) & set(list2)) return olap # 7: List Comprehensions def even_list_elements(input_list): # for x in input_list: # if x%2 == 0: # even.append(x) even = [x for x in input_list if x % 2 == 0] return even # 10: List Overlap Comprehensions def list_overlap_comp(list1, list2): return [x for x in list1 if x in list2] # 14: List Remove Duplicates # Use a SET for this exercise! def remove_dups(input_list): return list(set(input_list)) # 15: Reverse Word Order def reverse_words(sentence): splitsent = sentence.split() splitsent.reverse() return " ".join(splitsent) # 21: Write To A File # Name of the file should be exer21.txt def write_file(): base_url = 'http://www.nytimes.com' r = requests.get(base_url) soup = BeautifulSoup(r.text, "lxml") with open("exer21.txt", "w") as open_file: for story_heading in soup.find_all(class_="story-heading"): if story_heading.a: open_file.write(story_heading.a.text.replace("\n", " ").strip()) else: open_file.write(story_heading.contents[0].strip()) # 22: Read From File def count_names_in_file(): namedict = {} with open('listnames.txt', 'r') as open_file: for line in open_file.readlines(): line = line.strip() namedict[line] = namedict.get(line, 0) + 1 return namedict # 33: Birthday Dictionaries # Your function should know at least three birthdays def birthdays(): birthdict = {'Michael Scott' : 'March 15, 1964', 'Jim Halpert' : 'October 1, 1978', 'Dwight Schrute' : 'January 20, 1977'} print("Welcome to the birthday dictionary! We know the birthdays of:") print(birthdict.keys()) person = input("Who's birthday would you like to look up?: ") print(person + "'s birthday is " + birthdict[person]) # 34: Birthday Json def birthdays_json(): birthdict = {'Michael Scott' : 'March 15, 1964', 'Jim Halpert' : 'October 1, 1978', 'Dwight Schrute' : 'January 20, 1977'} with open("birth.json", "w") as open_file: json.dump(birthdict, open_file) with open("birth.json", "r") as open_file: info = json.load(open_file) person = input("Who's birthday would you like to look up?: ") print(person + "'s birthday is " + info[person]) # # 35: Birthday Months # def birthdays_months(): # Extra Credit! - Class Exercises # found at https://www.hackerrank.com/domains/python/py-classes # Class 2 - Find the Torsional Angle # class Points(object): # def __init__(self, x, y, z): # def __sub__(self, no): # def dot(self, no): # def cross(self, no): # def absolute(self): # return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5) # #Classes: Dealing with Complex Numbers # class Complex(object): # def __init__(self, real, imaginary): # def __add__(self, no): # def __sub__(self, no): # def __mul__(self, no): # def __div__(self, no): # def mod(self): # def __str__(self): # if self.imaginary == 0: # result = "%.2f+0.00i" % (self.real) # elif self.real == 0: # if self.imaginary >= 0: # result = "0.00+%.2fi" % (self.imaginary) # else: # result = "0.00-%.2fi" % (abs(self.imaginary)) # elif self.imaginary > 0: # result = "%.2f+%.2fi" % (self.real, self.imaginary) # else: # result = "%.2f-%.2fi" % (self.real, abs(self.imaginary)) # return result if __name__ == "__main__": # put your test code here birthdays()
# Given the root of a binary search tree, and a target K, return two nodes in # the tree whose sum equals K. # For example, given the following tree and K of 20: # 10 # / \ # 5 15 # / \ # 11 15 # Return the nodes 5 and 15. class Tree(object): def __init__(self, val, L, R): self.val = val self.left = L self.right = R def kTreeSum(T, sum): if (T.val > sum): kTreeSum(T.left, sum) else: return 42 def main(): T0 = Tree(5, None, None) T1 = Tree(15, None, None) T2 = Tree(10, T0, Tree(15, Tree(11, None, None), T1)) assert(kTreeSum(T2, 20) == (T0, T1))
from PIL import Image, ImageEnhance from os import listdir def reduce_opacity(im, opacity): """Returns an image with reduced opacity.""" assert opacity >= 0 and opacity <= 1 if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return im def watermark(im, mark, position, opacity: float = 1): """Adds a watermark to an image.""" if opacity < 1: mark = reduce_opacity(mark, opacity) if im.mode != 'RGBA': im = im.convert('RGBA') # create a transparent layer the size of the image and draw the # watermark in that layer. layer = Image.new('RGBA', im.size, (0, 0, 0, 0)) if position == 'tile': for y in range(0, im.size[1], mark.size[1]): for x in range(0, im.size[0], mark.size[0]): layer.paste(mark, (x, y)) elif position == 'scale': # scale, but preserve the aspect ratio ratio = min( float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) w = int(mark.size[0] * ratio) h = int(mark.size[1] * ratio) mark = mark.resize((w, h)) layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2)) else: layer.paste(mark, position) # composite the watermark with the layer return Image.composite(layer, im, layer).convert("RGB") if __name__ == '__main__': path = '/home/jake/Mounts/Media-Server/files/html/rstanger/' mark = Image.open('res/overlay.png') for file in listdir(path): if file.endswith('.thumb'): continue print(file) image = Image.open(path + file) watermark(image, mark, 'tile', 0.1).save(path + file + ".marked", "JPEG")
""" Instance Method Class Method Static Method """ # Instance Method #The purpose of instance methods is to set or get details about instances (objects), # and that is why they’re known as instance methods. # They have one default parameter- self # Any method you create inside a class is an instance method unless you specially specify Python otherwise. class MyClass: def __init__(self, a): self.a = a def instance_method(self): print(f"This is an instance method with parameter {self.a}") def get_class_name(self): print(f"I am from class: {self.__class__.__name__}") obj = MyClass(10) obj.instance_method() obj.get_class_name() # we CANNOT access the instance methods directly from class #MyClass.instance_method() # TypeError: instance_method() missing 1 required positional argument: 'self' # it is obvious because instance methods accept an instance of the class as the default parameter. # And you are not providing any instance as an argument. # Though this can be bypassing the object name as the argument: #MyClass.instance_method(obj) #This is an instance method with parameter 10 >> WORKS as instance obj is passed :) #USAGE # The instance methods are the most commonly used methods. print("********end********") # Class Method # The purpose of the class methods is to set or get the details (status) of the class. # That is why they are known as class methods. # They can’t access or modify specific instance data. # They are bound to the class instead of their objects. # In order to define a class method, # you have to specify that it is a class method with the help of the @classmethod decorator # Class methods also take one default parameter- cls, # which points to the class. Again, this not mandatory to name the default parameter “cls”. # But it is always better to go with the conventions # Class methods can be accessed both by instances of class and as well as directly from class class MyClass2: @classmethod def class_method(cls): print(f"i am from class method") print(f"I am from class: {cls.__name__}") #accessing cls method via instances obj2 = MyClass2 obj2.class_method() #accessing cls method via Class # we can access the class methods directly without creating an instance or object of the class #MyClass2.class_method() #also prints same class Animal: def __init__(self, name,color,age): self.name = name self.color = color self.age = age @classmethod def class_method(cls): print("This is class method") def run(self): print(f"{self.name} is running") def change_color(self,new_color): self.color = new_color dog = Animal("ron",'blue',5) # dog.run() Animal.class_method() # dog.class_method() dog.change_color("red") # we can change instance state using instance method # But class method cannot access or modify specific instance data # means Cls method cannt access or modify self.name or similar instance attrs # USAGE # The most common use of the class methods is for creating factory methods. # Factory methods are those methods that return a class object (like a constructor) for different use cases. from datetime import date class Dog: def __init__(self,name,age): self.name = name self.age = age @classmethod def get_age_by_year(cls,name,year): return cls(name,date.today().year - year) d = Dog('blue','2') #blue 2 print(d.name,d.age) # below, we used cls method to create another cls object d = Dog.get_age_by_year('blue',2009) print(d.name,d.age) #blue 11 # Factory methods are those methods that return a class object (above) print("********end********") # Static Method # Static methods cannot access the class data and instance data. # In other words, they do not need to access the class data. # They are self-sufficient and can work on their own. # Since they are not attached to any class attribute, # they cannot get or set the instance state or class state. class MyClass3: @staticmethod def static_method(): print("This is static method") print("I don't need neither class nor an instance") # In order to define a static method, # we can use the @staticmethod decorator # (in a similar way we used @classmethod decorator). # Unlike instance methods and class methods, we do not need to pass any special or default parameters. obj3 = MyClass3 obj3.static_method() MyClass3.static_method() # we can call static methods from both class and instance # but mind that we cannot change the state of class and instance # these methods are used for creating utility functions. # For accomplishing routine programming tasks we use utility functions #USAGE class Calculator: def __init__(self): self.buttons = 4 def change_buttons(self, new_buttons): self.buttons = new_buttons @staticmethod def do_addition(x,y): print(x+y) try: print(f"{self.buttons}") except: print("cant get self.buttons from static method") # Whenever you have to add two numbers, # you can call this method directly without worrying about object construction. Calculator.do_addition(10,20) c = Calculator c.do_addition(5,10) #both of above works
print ("Hello World from Kevin Toapanta \n Espe\n GEO") # input variables addend1= input('Enter the first number --> ') adden2=input('Enter the second number" --> ') #add two numbers sum= int (addend1) + int(addend2) #displatying the sum print(' The sum od {0} abd {1} is {2} .format(addend1,addend2,sum)) print('The summ is %1f' %(float(input('Enter first number< '))+float(input('Enter second number:'))))