text
stringlengths
37
1.41M
#Escribir un programa que almacene el abecedario en una lista, elimine de la lista las letras que ocupen posiciones múltiplos de 3, #y muestre por pantalla la lista resultante abecedario=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","ñ","o","p","q","r","s","t","u","v","w","x","y","z"] for i in range(len(abecedario)-1,-1,-1) : if i%3==0 : abecedario.pop(i-1) print (abecedario)
#Escribir una función a la que se le pase una cadena <nombre> y muestre por pantalla el saludo ¡hola <nombre>!. def Saludo(nombre): """ Funcion que devuelve un saludo por pantalla Parametros: nombre: Nombre de usuario """ print("¡Hola "+nombre+"!") return izena=str(input("Introduzca su nombre: ")) Saludo(izena)
#Escribir una función que calcule el total de una factura tras aplicarle el IVA. # La función debe recibir la cantidad sin IVA y el porcentaje de IVA a aplicar, y devolver el total de la factura. # Si se invoca la función sin pasarle el porcentaje de IVA, deberá aplicar un 21%. def Factura(cantidad,iva=21): """ Funcion que devuelve el valor de una factura, dependiendo de la cantidad y el porcetaje IVA a aplicar Parametros: cantidad= Cantidad en euros de la factura IVA= impuesto al valor añadido, un valor que en caso de ser nulo es 21. """ return cantidad + cantidad*iva/100 print(Factura(1000,10)) print(Factura(1000))
import os import sys class Point: x = 0 y = 0 signal = 0 def __init__(self, x, y, signal): self.x = x self.y = y self.signal = signal def __eq__(self, other): return self.x, self.y == other.x, other.y def __hash__(self): return hash((str(self.x), str(self.y))) def manhattanDist(x1, y1): return abs(x1) + abs(y1) def makeWirePoints(wire): wirePoints = [] curr = Point(0,0, 0) signal = 0 for inst in wire: direction = inst[0] distance = int(inst[1:]) if direction == "U": while(distance): curr.y += 1 signal+=1 wirePoints.append(Point(curr.x, curr.y, signal)) distance -= 1 elif direction == "R": while(distance): curr.x += 1 signal+=1 wirePoints.append(Point(curr.x, curr.y, signal)) distance -= 1 elif direction == "L": while(distance): curr.x -= 1 signal+=1 wirePoints.append(Point(curr.x, curr.y, signal)) distance -= 1 elif direction == "D": while(distance): curr.y -= 1 signal+=1 wirePoints.append(Point(curr.x, curr.y, signal)) distance -= 1 return wirePoints def main(): wires = [] with open(os.getcwd() + "/day3input.txt", "r") as f: for line in f: wires.append(line.rstrip("\n").split(",")) points1 = makeWirePoints(wires[0]) points2 = makeWirePoints(wires[1]) intersections = set(points1).intersection(points2) dist = [] for p in intersections: dist.append(manhattanDist(p.x, p.y)) print(min(dist)) steps = [] for intersection in intersections: w1p = Point(0,0,0) w2p = Point(0,0,0) for p in points1: if (intersection.x == p.x and intersection.y == p.y): if(intersection.signal != p.signal): w1p = p else: w1p = intersection for p in points2: if (intersection.x == p.x and intersection.y == p.y): if(intersection.signal != p.signal): w2p = p else: w2p = intersection steps.append(w1p.signal + w2p.signal) print(min(steps)) main()
class DictEntry: """ Dictionary entry word - word in foreign language , translation - in native language learn index - int in range [0,100] """ def __init__(self, spelling: str, translation: str, learning_index: int, sql_id: int = 0) -> None: self.spelling = spelling self.translation = translation self.learning_index = learning_index if learning_index > 0 else 0 self.sql_id = sql_id def set_learn_index(self, value) -> None: if value < 0: self.learning_index = 0 elif value >= 100: self.learning_index = 100 else: self.learning_index = value def increase_learn_index(self) -> None: self.learning_index += (5 if self.learning_index < 100 else 0) def decrease_learn_index(self) -> None: self.learning_index -= (5 if self.learning_index > 0 else 0) def set_word(self, value) -> None: self.spelling = value def set_translation(self, value) -> None: self.translation = value def print_entry(self) -> str: return "{} - {} : {}".format(self.spelling, self.translation, self.learning_index)
def toLowerCase(sym): #function that changes uppercase to lowercase symbol return sym+32 if 65 <= sym and sym <= 90 else sym #if symbol is in range [65; 90] we should add 32 to make lowercase symbol def main(): #main function that will write ASCII of uppercase symbol and return ASCII of uppercase symbol = 66 #code of uppercase symbol symbol = toLowerCase(symbol) #call function that gets uppercase symbol return symbol #return code of uppercase symbol
# ======= DEFINE LIBRARIES ======= # import matplotlib.pyplot as plt #Graph plotting tools import math #Mathematical functions import time as time_ #Time measurement functions import numpy as np #Basic fucntions toolkit import sys #System commands # ================================ # # ======= DEFINE INPUT VARIABLES/CONSTANTS ======= #1.5 c = 299792458 #Speed of light pi = math.pi #pi theta = 1/(2-2**(1./3.)) #Value always used to compute Forrest-Ruth algorithm (constant) r_s = 1 #Schwarschild radius phi_i = 0.0 #Starting angle t_i = 0.00 #Starting time # ================================================== # # ======= USER INPUTS TO CHOOSE l VALUE ======= # l_factor = input("l = x√(12)\nEnter value for x (must be 1 < x ≤ 4): ") #User prompt and input line printed in console type(l_factor); l_factor = float(l_factor) #Convert from string type to float type l = l_factor*math.sqrt(12) #Use user input to calculate l if l_factor < 1 or l_factor > 4: #Condition to check that user input is valid input("Invalid entry - enter value between 1 ≤ x ≤ 4: ") #User prompt to input different value when user input invalid type(l_factor); l_factor = float(l_factor) #Convert from string type to float type l = l_factor*math.sqrt(12) #Use user input to calculate l if l_factor < 1 or l_factor > 4: #Condition to check that user input is valid print("Program teriminated - please retry") #Message printed to console if user input invalid sys.exit() #Terminate program # ======= PLOT EFFECTIVE POTENTIAL AS FUNCTION OF R ======= # # ------- Calculate V and create lists for V and distance x ------ # x = r_s-0.005 #Define initial distance x_values =[x] #Create distance values list V_values =[-(r_s/(2*x))+((l**2)/(2*(x**2)))-((r_s*(l**2))/(2*(x**3)))] #Create V values list while x < 100*l_factor*r_s: V = -(r_s/(2*x))+((l**2)/(2*(x**2)))-((r_s*(l**2))/(2*(x**3))) #Calculate V value for corresponding x value x = x + (0.1*r_s) #move to next x value x_values.append(x); V_values.append(V) #Append new values to lists # -- End -- # # # # # ------- Find turning point - based on code by Malvolio (2013) ------- # x_at_tp = []; V_at_tp = [] #Create arrays to hold values at turning points n = 2 #Loop counter while n <= (len(x_values))-2: #Loop whilst loop counter less than array length - 2 if ((V_values[n-2] < V_values[n-1] and V_values[n] < V_values[n-1]) #Condition satisfied at maximum or (V_values[n-2] > V_values[n-1] and V_values[n] > V_values[n-1] )): #Conditiion satisfied at minimum x_at_tp.append(x_values[n-1]) #Append time at turning points V_at_tp.append(V_values[n-1]) #Append radius at turning points n = n + 1 #Increase loop counter by one # -- End -- # # # # # ------- Find minimum and maximum values of V ------- # V_min = min(float(d) for d in V_at_tp) #Find minimum values in V_at_tp V_max = max(float(d) for d in V_at_tp) #Find maximum values in V_at_tp x_min = max(float(d) for d in x_at_tp) #Find minimum values in x_at_tp print("Min V =", V_min, ", Max V =", V_max, ", x at min V =", x_min) #Print values found plt.xlabel('Distance [r_s]'); plt.ylabel('V(r)'); plt.title('Effectiv3e Potential') #Define plot lables plt.xlim(0, (x_min+0.1*x_min)); plt.ylim((V_min+(0.1*V_min)), (V_max+(0.1*V_max))) #Scale plot axes to show interesting region plt.plot(x_values, V_values) #Define things to plot plt.show() #Show plots # ============================================================ # # ======= FIND POSITIONS OF ORBITS ======= # V_half_max = V_max/2 #Find the half point between zero and V_max V_quart_min = V_min/4 #Find the half point between V_min and zero orbit = [0, V_min, V_max, V_quart_min, V_half_max, V_half_max] #Array of V(r) values corrsponding to different orbits #In order: NULL, Stable circular, unstable circular, precession, escape, trapped i = 1 #Loop counter V_orbit =[]; r_orbit = [] #Define empty lists to hold values while i <= 5: #Condition to cycle through each entry in orbit list if i == 5: #Special case for trapped orbits j = max(V_values, key=lambda X: abs(X - orbit[i])) #Based on code by kennytm (2012) #Find the value to the left of the V(r) peak closest to V_half_max V_orbit.append(j) #Append the V(r) value found in line above r_app = round((x_values[V_values.index(V_orbit[i-1])]), 2) #Find the r value corresponding to the V(r) value found two lines above by finding the index value of the V(r) value in V_values list and looking for corresponding x_values list index value if r_app < r_s: #Condition to check if r value found above is less than Schwarzschild radius r_app = r_app + 10*(r_s - r_app) #Increase r value to ensure it is larger than Schwarzschild radius r_orbit.append(r_app) #Append r value to r_orbit list else: r_orbit.append(r_app) #Append r value to r_orbit list else: #Case for other orbits j = min(V_values, key=lambda X: abs(X - orbit[i])) #Based on code by kennytm (2012) #Find value to the right of the v(r) peak closest to V value listed in orbit list V_orbit.append(j) #Append the V(r) value found in the line above r_app = round((x_values[V_values.index(V_orbit[i-1])]), 2) #Find the r value corresponding to the V(r) value found two lines above by finding the index value of the V(r) value in V_values list and looking for corresponding x_values list index value if r_app < r_s: #Condition to check if r value found above is less than Schwarzschild radius r_app = r_app + 10*(r_s - r_app) #Increase r value to ensure it is larger than Schwarzschild radius r_orbit.append(r_app) #Append r value to r_orbit list else: r_orbit.append(r_app) #Append r value to r_orbit list i = i + 1 #Increase loop counter value # ======================================== # # ======= USER INPUTS TO CHOOSE E and r ======= # print("--- ORBIT PROFILE EXAMPLE VALUES ---") #Print new line message to user print("Stable Circular = ", r_orbit[0], "\nPrecession = ", r_orbit[2], "\nEscape = ", r_orbit[3]) print("Unstable Circular = ", r_orbit[1], "\nTrapped = ", r_orbit[4]) #Print suggested values for orbits to user r_i = input("Enter value for distance: " ) #User prompt to input value for r r_i = float(r_i) #Convert user intput from string type to float type if r_i < r_s: #Condition to check if user input value for r is less than Schwarszchild radius r_i = input("Value must be larger than 1. PLease enter new value: ") #Error message and input prompt to user r_i = float(r_i) #Convert user input from string type to float type if r_i < r_s: #Condition to check if user input value for r is less than Schwarszchild radius print("Program terminated - please try again") #Error message to ell user invalid entry sys.exit() #Terminate the program V_user = -(r_s/(2*r_i))+((l**2)/(2*(r_i**2)))-((r_s*(l**2))/(2*(r_i**3))) #Calculate V(r) at the position of r chosen by user V_max_input = V_max + 0.5 #Set max. max input E to be V_max + 0.5 print("\nMax. V(r)", round(V_max, 2)) #Print max possible value user can input print("Enter value for particle energy (", round(V_user, 2), "≤ E <", round(V_max_input, 1), " or V(r)): ") #Show user range of input values for E E_user = input() #Read user input from new line if E_user == 'V(r)' or E_user == 'v' or E_user == 'V' or E_user == round(V_user, 2): #Read user input to see if it matches any values corresponding V(r) E_user = V_user #Set E_user to be V(r) value from using user defined r v_i = 0 #Particle velocity must be zero as is on V(r) curve (no kinetic energy) else: E_user = float(E_user) #Convert user input from string type to float type if E_user == round(V_max_input, 1): #Condition to check if user has entered max. possible user E E_user = V_max_input - 0.01*V_max_input #Ensure E is less than V_max_input if E_user > V_max_input or E_user < V_user: #Condition to check if value is niether greater than max. possible user E or less than V(r) E_user = input("Invalid value! Enter new value: ") #Message prompting user to input new value if E_user == 'V(r)' or E_user == 'v' or E_user == 'V': #Read user input to see if it matches any values corresponding V(r) E_user = V_user #Set E_user to be V(r) value from using user defined r else: E_user = float(E_user) #Convert user input from string type to float type if E_user == round(V_max_input, 1): #Condition to check if user has entered max. possible user E E_user = V_max_input - 0.01*V_max_input #Ensure E is less than V_max_input if E_user > V_max_input or E_user < V_user: #Condition to check if value is niether greater than max. possible user E or less than V(r) print("Program terminated - please retry") #Error message to ell user invalid entry sys.exit() #Terminate the program if E_user > V_user: #Condition to check if user input E is greater than V(r) direction = input("Inwards or outwards motion? (Enter + or -)\n") #User prompt to input direction of particle motion if direction == "+": #Condition when user selects positive particle direction (away from black hole) v_i = math.sqrt((2*E_user) - (2*V_user)) #Calculate particle velocity from user inputs and assign positive value if direction == "-": #Condition when user selects negative particle direction (towards from black hole) v_i = -math.sqrt((2*E_user) - (2*V_user)) #Calculate particle velocity from user inputs and assign negative value w_i = l/(r_i**2) #Calculate angular velocity from user inputs # ================================================================================= # # ======= DEFINE FUNCTIONS ======= # #These functions are later called in main iterative algorithm to find r, v, phi and w def dvdt(r): return (l**2)/(r**3) - (r_s)/(2*(r**2)) - ((3*r_s*(l**2))/(2*(r**4))) #Equation (1.8) in report def dphidt(r): return (l/(r**2)) #From equation (1.4) in report def drdt(v): return v #From substitution for equation (1.8) in report def dwdt(r, drdt): return ((-2*l)/(r**3))*drdt #Equation (1.9) in report # ================================== # # ======= MAIN FOREST-RUTH ALGORITHM TO CALCULATE NEW VALUES ======= # i_max = ((3.34e-9)*c) #Default setting of 1 second (not in metres of time) def main_algorithm(t, r, v, phi, w, l, i_max): #Input arguments to function start_time = time_.time() #Calculate start_time based on system time run_time = 0 #Reset run_time = 0 to prevent errors # ------- Define lists to hold values ------- # radius = [r] rad_vel = [v] time = [t] ang_vel = [w] angle = [phi] time_at_tp = [] radius_at_tp = [] round_angle = [] # ------- Function to find optimal step size for r ------- # def step(r0, v0, h01): h1 = h01; j = 1; Error = 1 #Set inital values for fucntion step_r = [r0] #Define an list to hold values later calculated while abs(Error) > 0.000001: #Error to be obtained through convergence r1 = r0 + (theta*(h1/2)*drdt(v0)) #Forest-Ruth algorithm to find r for given step h v1 = v0 + (theta*h1*dvdt(r1)) #... r2 = r1 + ((1 - theta)*(h1/2)*drdt(v1)) #... v2 = v1 + ((1 - (2*theta))*h1*dvdt(r2)) #... r3 = r2 + ((1 - theta)*(h1/2)*drdt(v2)) #... v3 = v2 + (theta*h1*dvdt(r3)) #... step_r.append(r3 + (theta*(h1/2)*drdt(v3))) #Append r values to list Error = (step_r[j]-step_r[j-1])/step_r[j] #Calculate difference between subsequent r values Ep1 = abs(Error*100) #Ouput error as percentage h1 = h1/2 #Reduce step size and re-calculate r j = j+1 return h1, Ep1 #Return program arguments i = 0 h0 = (i_max/2) #Define initial 'test' step size (in seconds as based off un-normalised i_max value) h, Ep = step(r, v, h0) #Call optimised r step value while i <= i_max: #Set maximum number of iterations # ------- Forest-Ruth to find r and v ------- # r0 = r v0 = v r1 = r0 + (theta*(h/2)*drdt(v0)) v1 = v0 + (theta*h*dvdt(r1)) r2 = r1 + ((1 - theta)*(h/2)*drdt(v1)) v2 = v1 + ((1 - (2*theta))*h*dvdt(r2)) r3 = r2 + ((1 - theta)*(h/2)*drdt(v2)) v3 = v2 + (theta*h*dvdt(r3)) r = r3 + (theta*(h/2)*drdt(v3)) #Re-set r value v = v3 #Re-set v value t = (t + h) #Recalculate time by adding step onto initial value # ------- Forest-Ruth to find r and v ------- # phi0 = phi w0 = w phi1 = phi0 + (theta*(h/2)*dphidt(r0)) w1 = w0 + (theta*h*dwdt(r1, drdt(v1))) phi2 = phi1 + ((1 - theta)*(h/2)*dphidt(r1)) w2 = w1 + ((1 - (2*theta))*h*dwdt(r2, drdt(v2))) phi3 = phi2 + ((1 - theta)*(h/2)*dphidt(r2)) w3 = w2 + (theta*h*dwdt(r3, drdt(v3))) phi = phi3 + (theta*(h/2)*dphidt(r3)) #Re-set phi value w = w3 #Re-set v value # ------- Process values from Forest-Ruth algorithms ------- # # 1. Append new values to lists radius.append(r); time.append(t); rad_vel.append(v); ang_vel.append(w); angle.append(phi); round_angle.append(round(phi, 4)) # 2. Add to loop counters and calculate run time i = i + h #Add step size to initial i to create next i value run_time = time_.time() - start_time #Calculate the time elapsed since the start of the function # 4. Function exit conditions if i > 10 and (round(angle[-1], 7) == round(angle[-10], 7)): #Condition to check if rounded final values in angle list are equal i = i_max + 1 #Increase loop counter value to exceed i_max to exit loop print("Angle constant") #Print message to user if (angle[-1] < 4*pi and (i+h) >= i_max): #Condition to check last value in angle array and position in loop i_max = i_max+h #Increase i_max to allow for more iteraitons to allow for angle condition to be met if radius[-1] <= 0.1: #Condition to stop code breakdown at r = 0 singularity i = i_max+1 #Increase loop counter value to exceed i_max to exit loop print("Radius too small") #Print message to user if run_time > 10: #Condition to check if run time hasn't exceeded 10s i = i_max+1 #Increase loop counter value to exceed i_max to exit loop print("* 10s Processing Time Exceeded *") #Print message to user explaining run-time is too long return radius, time, rad_vel, ang_vel, angle, round_angle, time_at_tp, radius_at_tp #Return the lists from the function # ----- Values to return from function ----- # return radius, time, rad_vel, ang_vel, angle, round_angle, time_at_tp, radius_at_tp #Return the lists from the function radius, time, rad_vel, ang_vel, angle, round_angle, time_at_tp, radius_at_tp = main_algorithm(t_i, r_i, v_i, phi_i, w_i, l, i_max) #Call main algorithm with argument values # =============================================== # # ======= OUTPUT POLAR PLOT ======= # time_s = [x/c for x in time] #Divide by c as there are n/c seconds in n metres of time y_max = (max(radius)+((max(radius))*0.1)) #Set axes limits to ensure plot shows most relevant parts of orbits fig = plt.Figure() #Define new plotting object ax = plt.subplot(1,1,1, polar=True) #Create polar subplot ax.set(xlim=(0, 2*pi), ylim=(0, y_max)) #Set axes constraints ax.set_theta_zero_location("N") #Rotate plot so 0 angle is at top of plot ax.plot(angle, radius, 'k') #Create polar plot and select black line color circle = plt.Circle((0, 0), 1, transform=ax.transData._b, color='gray') #Create circle vector object to represent black hole ax.add_artist(circle) #Impose circle object onto polar plot #Code to create circle vector based on code by HYRY (2013) label_position=ax.get_rlabel_position() #Call positional argument of label and define new variable ax.text(np.radians(label_position+20),ax.get_rmax()/2.,'r', rotation=label_position,ha='center',va='center', ) #Reference: tmdavison (2015) #Adjust position of radial axis label plt.show() #Show polar plot # ================================= # # ======= *** END OF PROGRAM *** ======= #
def three_loops(array): n = len(array) max_sum = array[0] for start in range(n): for end in range(start, n): current_sum = sum(array[start:end+1]) # print(array[start:end+1]) if current_sum > max_sum: max_sum = current_sum # print(max_sum) return max_sum def two_loops(array): n = len(array) max_sum = array[0] for start in range(n): current_sum = 0 for end in range(start, n): current_sum += array[end] # update the current sum as we go # print(array[start:end+1]) if current_sum > max_sum: max_sum = current_sum # print(max_sum) return max_sum def one_loop(array): n = len(array) max_sum = array[0] current_sum = array[0] for i in range(1, n): current_sum = max(current_sum+array[i], array[i]) # print(current_sum) # print(array[i:]) max_sum = max(max_sum, current_sum) # print(max_sum) return max_sum # print(three_loop([2, 3, 4, -2, -4, 3])) # Time Complexity O(n^3) # print(two_loops([2, 3, 4, -2, -4, 3])) # Time Complexity O(n^2) # print(one_loop([2, 3, 4, -2, -4, 3])) # Time Complexity O(n) arr1 = [3, 4, -9, 1, 2] arr2 = [1, 2, 3] arr3 = [-1, -2, -3] assert three_loops(arr1) == two_loops(arr1) assert three_loops(arr2) == two_loops(arr2) assert three_loops(arr3) == two_loops(arr3) assert one_loop(arr1) == two_loops(arr1) assert one_loop(arr2) == two_loops(arr2) assert one_loop(arr3) == two_loops(arr3)
#Get the feet from the user: meters = float(input("Enter the number in feet:")) meters_in_ft= meters*0.305 print(meters_in_ft, "meters")
from random import shuffle class Blackjack(): def __init__(self, starting_chips): self.chips = starting_chips self.short = True self.humhand = [] self.aihand = [] self.deck = [] self.makeDeck() # self.runout = [] def makeDeck(self): self.deck = list(range(0,52)) shuffle(self.deck) def dealCard(self): c = self.deck.pop()#randint(0,51) num = c % 13 suit = c//13 num+=2 return (num, suit) def dealHand(self): self.humhand = [] self.aihand = [] if len(self.deck)<10: self.makeDeck() # self.runout = [] self.humhand.append(self.dealCard()) self.humhand.append(self.dealCard()) self.aihand.append(self.dealCard()) self.aihand.append(self.dealCard()) # print(self.humhand) def dealAI(self): # print("AI Cards: ") humbool, humcount = self.isBusted(self.humhand) aibool, aicount= self.isBusted(self.aihand) while (not aibool) and (aicount<humcount): self.hitAI() aibool, aicount = self.isBusted(self.aihand) sai = [] for cardind in range(len(self.aihand)): sai.append(self.cardToString(self.aihand[cardind])) print("AI Cards:") self.printAsciiCards(sai) print("Total AI count: " + str(aicount)) if (aicount<humcount) or aibool: print("You win!!!!") return "HUM" if aicount>humcount: print("You lose :(") return "AI" else: print("Tie!") return "TIE" def hit(self, l): l.append(self.dealCard()) return self.isBusted(l) def hitMe(self): return self.hit(self.humhand) def hitAI(self): return self.hit(self.aihand) def isBusted(self, hand): count = 0 aces = 0 for each in hand: v = each[0] if v in {11,12,13}: v = 10 if v == 14: v = 11 aces+=1 count+=v while(count>21) and(aces>0 ): count-=10 aces-=1 return (count>21,count) def getState(self): sme = [] for card in self.humhand: sme.append(self.cardToString(card)) sai = [("?", "?")] for cardind in range(1, len(self.aihand)): sai.append(self.cardToString(self.aihand[cardind])) print("AI Cards:") self.printAsciiCards(sai) print() print("Your Cards: ", end="") self.printAsciiCards(sme) return self.isBusted(self.humhand) def startHand(self): self.dealHand() def printAsciiCards(self, cardsstringlist): print(cardsstringlist) a = "+----+\n| |\n| |\n| |\n+----+" totstring = "\n\n\n\n".split("\n") newcard = a.split("\n") for each in cardsstringlist: m = list(newcard[1]) m[1] = each[1] m[4] = each[0] m = "".join(m) newcard[1] = m for each in range(len(totstring)): totstring[each] += " " + newcard[each] print("\n".join(totstring)) def cardToString(self, card): num = card[0] suit = card[1] suits = {0:"Spades", 1:"Hearts", 2:"Clubs", 3:"Diamonds"} shortSuits = {0:"♠", 1:"♥", 2:"♣", 3:"♦"} shortCards = {13:"K", 14:"A", 10:"T", 11:"J", 12: "Q"} cards = {13: "King", 14: "Ace", 11: "Jack", 12: "Queen"} if self.short: suit = shortSuits[suit] if num in shortCards: num = shortCards[num] else: suit = suits[suit] if num in cards: num = cards[num] num = str(num) return (num,suit) class BlackjackInputRunner(): def __init__(self): name = input("What is your name? ") print("Hi, " + name + " - let's play blackjack!") while True: try: userInput = input("How many chips do you want to start with? ") val = int(userInput) if val < 1: raise ArithmeticError break except ValueError: print("That's not an int!") except ArithmeticError: print("Not a valid chipcount!") self.startcount = val self.game = Blackjack(val) def startGame(self): print("Let's get into it! Hit q when you want to stop") self.game.dealHand() # p.hitMe() self.runGameLoop() def runGameLoop(self): play = True bettingtime = True while play: if bettingtime: bet, bettingtime, play = self.allowBetting(bettingtime, play) bust, count = self.game.getState() if bust: print("You busted!") bettingtime, play = self.askAboutNewGame(bettingtime, play) else: bettingtime, play = self.notBustedPrompt(bet, bettingtime, count, play) print("Game over: You finished with " + str( self.game.chips) + " chips, %.2f percent of your initial chipcount!" % ( self.game.chips / self.startcount * 100)) def notBustedPrompt(self, bet, bettingtime, count, play): myin = "" while myin == "": print("Total count right now: " + str(count)) myin = input("What will you do? Hit H to see another card, or hit S to stop. ") if myin in {"H", "h"}: self.game.hitMe() elif myin in {"S", "s"}: winner = self.game.dealAI() if winner == "HUM": self.game.chips += bet * 2 if winner == "TIE": self.game.chips += bet bettingtime, play = self.askAboutNewGame(bettingtime, play) elif myin in {"Q", "q"}: play = False else: print("That's not a valid response - try again!") myin = "" return bettingtime, play def askAboutNewGame(self, bettingtime, play): myin = "" while myin == "": if self.game.chips == 0: play = False print("You have no more chips :(") break myin = input( "If you want to play again using the same deck (to learn how to count cards), play again by hitting A, or hit R to reset the deck and play again! Hit q to quit.") bettingtime = True if myin in {"A", "a"}: self.game.dealHand() # p.hitMe() # elif myin in {"S", "s"}: elif myin in {"R", "r"}: self.game.makeDeck() self.game.dealHand() elif myin in {"Q", "q"}: play = False else: print("That's not a valid response - try again!") myin = "" return bettingtime, play def allowBetting(self, bettingtime, play): while True: try: print("Chipcount: " + str(self.game.chips)) bet = input("How much do you want to bet? ") val = int(bet) if val < 1: raise ArithmeticError if val > self.game.chips: print("You dont have that many chips!") else: break except ValueError: print("That's not an int!") except ArithmeticError: print("Not a valid bet!") bet = val self.game.chips -= bet bettingtime = False return bet, bettingtime, play if __name__ == "__main__": game = BlackjackInputRunner() game.startGame()
from operator import __add__ as _add from functools import reduce from pybs.utils import memoized2 as memoized @memoized def number_of_trees_of_order(n): """Returns the number of unordered rooted trees with exactly *n* vertices. Uses a formula from Sloane's OEIS sequence no. ``A000081``. """ if n < 2: return n result = 0 for k in range(1, n): result += k * number_of_trees_of_order(k) * _s(n-1, k) return result // (n - 1) @memoized def _s(n, k): """Used in number_of_trees_of_order""" result = 0 for j in range(1, n//k + 1): result += number_of_trees_of_order(n+1-j*k) return result # Joe Riel (joer(AT)san.rr.com), Jun 23 2008 def number_of_trees_up_to_order(n): '''Number of _trees up to, not including order `n`. Based on :class:`number_of_trees_of_order`. ''' return reduce(_add, map(number_of_trees_of_order, range(n)), 0) def number_of_tree_pairs_of_total_order(n): """Needed for conjugate symplectic check. Known as :math:`m_n`. \ Taken from Hairer et al. \ On Conjugate symplecticity of B-series integrators """ # TODO: Implement general formula instead of table lookup. table = [0, 0, 1, 1, 3, 6, 16, 37, 96, 239, 622, 1607, 4235] return table[n]
# PROGRAM NAME: simple_nn.py # PROGRAM PURPOSE: Creates a very barebones neural network # PROGRAMMER: Dillon Pietsch # DATE WRITTEN: 8/15/17 # Initialize weight of singular node for NN weight = 0.1 def neural_network(input, weight): prediction = input * weight return prediction # 1-D Test Data number_of_toes = [8.5, 9.5, 10, 9] # 1-D Result Data results = [] # Iterate through all of the toes in number_of_toes for toe in number_of_toes: # Get a prediction based off of data and the set weight pred = neural_network(toe, weight) # Add all of the predictions to the results list results.append(round(pred, 4)) # Round function is built-in to Python and rounds a number to X decimal points. # Show the expected results print(results)
#!/usr/bin/env python2.7 #File: lebailly/BME205/HW1/wordcount #Author: Chris LeBailly """ wordcount counts the number of "words" (a contiguous sequence of characters from the set {abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'}) in stdin. Results can be sorted alphabetically (--alpha), by count descending (--descend), by count ascending (--ascend), or reverse alphabetically (--alpha --descend). Output to stdout is two-column tab-separated word-count pairs (one pair a line). """ from __future__ import division, print_function import sys, argparse, collections, re def main(args): """ Parses command line arguments, reads text from stdin, and prints two-column tab-separated word-count pairs to stdout in the order specified in the command line arguments. """ #Structure of main follows from code given in assignment. options = parse_arguments() counts = collections.defaultdict(int) #counts['abc'] is the number of times the word 'abc' occurs in the input. #defaultdict used to make counts of unseen words be 0. for word in read_word(sys.stdin): counts[word] += 1 print_output(counts, options) def parse_arguments(): """ Parses arguments from comandline to set sort option (--ascend, --descend, and --alpha). """ parser = argparse.ArgumentParser(description = __doc__) order = parser.add_mutually_exclusive_group() parser.add_argument('--alpha', action='store_true', help="Sorts words alphabetically. Sorts by count if not specified.") order.add_argument('--descend', '-d', action='store_true', help='''Sorts in descending order for both alphabetical and count sorts. If sorting by counts, words with same counts are sorted alphabetically. Sorts in alphabetically descending order if --alpha is also specified.''') order.add_argument('--ascend', '-a', dest='descend', action='store_false', help='''Sorts in ascending order for both alphabetical and count sorts. If sorting by counts, words with same counts are sorted alphabetically. Sorts in alphabetically ascending order if --alpha is also sepcified.''') return parser.parse_args() def read_word(source): """ Generator function which reads one "word" at a time from 'source'. """ #Separators is a regular expression for characters not found in a word separators = re.compile('[^a-zA-Z\']') for line in source: for word in separators.split(line): if(word != ''): yield word def print_output(counts, options): """ Sorts 'counts' based on 'options' and prints result to stdout. """ #Orders words alphabetically in ascending order if options.descend == False and options.alpha == True: sorted_count = sorted(counts.items()) #Orders words alphabetically in descending order elif options.descend == True and options.alpha == True: sorted_count = sorted(counts.items(), reverse = True) #Orders words by count in ascending order elif options.descend == False and options.alpha == False: sorted_count = sorted(counts.items(), key=lambda x:(x[1],x[0])) #Orders words by count in descending order else: sorted_count = sorted(counts.items(), key=lambda x:(-x[1],x[0])) #Prints sorted_count to stdout for word, frequency in sorted_count: print("{}\t{}".format(word,frequency)) #Sends warning to stderr if no "words" are found in stdin if len(counts) == 0: sys.stderr.write("WARNING: No words found in stdin.\n") if __name__ == "__main__" : sys.exit(main(sys.argv))
import requests import json urlAwesome = "https://economia.awesomeapi.com.br/last/USD-BRL,EUR-BRL,BTC-BRL" cotacoes = requests.get(urlAwesome) cotacoes = cotacoes.json() while True: print("Converta dinheiro real para qualquer outro") print() print("1 - DÓLAR") print("2 - EURO") print("3 - BITCOIN") print() tipo_de_moeda = int(input("Escolha um tipo de moeda para conversão \n")) print() moeda = 0 if tipo_de_moeda == 1: cotacao = cotacoes["USDBRL"] moeda = float(cotacao["bid"]) elif tipo_de_moeda == 2: cotacao = cotacoes["EURBRL"] moeda = float(cotacao["bid"]) elif tipo_de_moeda == 3: cotacao = cotacoes["BTCBRL"] moeda = float(cotacao["bid"]) real = float(input("Digite um dinheiro real para conversão \n")) print() total = real * moeda if tipo_de_moeda == 1: print(f"{real} real é igual a {total} dólar") elif tipo_de_moeda == 2: print(f"{real} real é igual a {total} euros") elif tipo_de_moeda == 3: print(f"{real} real é igual a {total} bitcoin") barras = "" for i in range(0, 100): barras += "=" print(barras)
grade=float(input("Enter your total points: ")) if grade >= 90: print("Congratulations you got an A") elif grade >= 80: print("Congratulation you got B") elif grade >= 70: print("congratulations you got C") elif grade >= 60: print("Not much just D") else: print("You suck!! go and study harder")
class Solution(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) if length < 3: return -1 sum_from_right = [0] i = length-1 while i >= 0: next_sum = nums[i] + sum_from_right[0] sum_from_right = [next_sum] + sum_from_right i -= 1 i = 0 sum = 0 while i < length: if sum == sum_from_right[i+1]: return i else: sum += nums[i] i += 1 return -1
from abc import ABC, abstractmethod class BaseValidator(ABC): # позволяет привязать имя поля, к которому относится дескриптор def __set_name__(self, owner, name): self.field_name = name def __get__(self, instance, owner): return instance.__dict__[self.field_name] def __set__(self, instance, value): self.validate(value) instance.__dict__[self.field_name] = value def validate(self, value): if len(value) < self.min_length or len(value) > self.max_length: raise ValueError('%s must be in (%d, %d) characters' % (self.field_name.upper(), self.min_length, self.max_length)) """ Validator for Not-None fields""" class NoneValidator(BaseValidator): def validate(self, value): if value is None: raise ValueError('Field %s must be presented' % self.field_name) class UsernameValidator(BaseValidator): def __init__(self, min_length, max_length, unacceptable_symbols=None): if unacceptable_symbols is None: unacceptable_symbols = [' ', '!', '?'] self.min_length = min_length self.max_length = max_length self.unacceptable_symbols = unacceptable_symbols def validate(self, value: str): if len(value.split(' ')) != 1: raise ValueError('Spaces not allowed in username') super(UsernameValidator, self).validate(value) class EmailValidator(BaseValidator): def __init__(self, min_length, max_length): self.min_length = min_length self.max_length = max_length def validate(self, value: str): if '@' not in value: raise ValueError('Email must contains @ symbol') super(EmailValidator, self).validate(value) """ Так как валидация пароля по своей структуре идентична валидации username, наследуемся от UsernameValidator""" class PasswordValidator(UsernameValidator): def validate(self, value: str): super(PasswordValidator, self).validate(value) # def __init__(self, min_length, max_length, unacceptable_symbols=None): # super(PasswordValidator, self).__init__(min_length, max_length, unacceptable_symbols)
import time as t import math def TotExecution_Time(func): def inner(n): starttime= t.time() func(num) endtime = t.time() print("The total execution time taken:",endtime-starttime) return inner @TotExecution_Time def Factorial(n): fact = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): t.sleep(1) fact = fact*i print("The factorial of",num,"is",fact) # To take input from the user num = int(input("Enter a number: ")) t.sleep(3) Factorial(num)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Unicode and string related functions """ import unicodedata def unicoderemove(s, category_check): ''' Remove characters of certain categories from the unicode string Args: s (str): input string, assumed in utf8 encoding if it is a bytestring category_check (callable): a function that takes output of unicodedata.category() and returns if such character should be kept in the output Returns: The unicode string of input transformed into normal form KD (compatibility decomposition) with characters of the specified categories removed ''' assert isinstance(s, str) return "".join(c for c in unicodedata.normalize('NFKD', s) if category_check(unicodedata.category(c))) def unicodereplace(s, replacer, category_check): ''' Replace characters of certain categories from the unicode string by replacer Args: s (str): input string, assumed in utf8 encoding if it is a bytestring r (str): replacement string category_check (callable): a function that takes output of unicodedata.category() and returns if such character should be kept in the output Returns: The unicode string of input transformed into normal form KD (compatibility decomposition) with each characters of the specified categories replaced by the replacement string ''' assert isinstance(s, str) return "".join(c if category_check(unicodedata.category(c)) else replacer for c in unicodedata.normalize('NFKD', s)) # Remove characters of nonspacing mark (Mn) category deaccent = lambda s: unicoderemove(s, lambda c: c != 'Mn').replace('\u02b9', '') # Remove punctuations, category names are from http://www.fileformat.info/info/unicode/category/index.htm depunctuation = lambda s: unicodereplace(s, ' ', lambda c: c not in ['Pc','Pd','Pe','Pf','Pi','Po','Ps']) # Keep only letters, all CJK ideographs are defined as other letters (Lo) letters_only = lambda s: unicoderemove(s, lambda c: c in ['Ll','Lm','Lo','Lt','Lu']) digits_only = lambda s: unicoderemove(s, lambda c: c == 'Nd') letters_tokens = lambda s: unicodereplace(s, ' ', lambda c: c in ['Ll','Lm','Lo','Lt','Lu']) # vim:set ts=4 sw=4 sts=4 tw=100 fdm=indent et:
import unittest from decimal import Decimal from util import alert class TestDict(unittest.TestCase): def test_alert(self): rate = 1 # 初始上涨3.5%,报警 cache_rate, diff, is_alert = alert(10.35, 10, rate=rate) print(cache_rate, diff) self.assertEqual(cache_rate, Decimal('3.5')) self.assertTrue(is_alert) # 保持上一价格,不报警 cache_rate, diff, is_alert = alert(10.35, 10, cache_rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('0')) self.assertFalse(is_alert) # 上一价格基础上下跌0.5,不报警 cache_rate, diff, is_alert = alert(10.30, 10, cache_rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('-0.5')) self.assertFalse(is_alert) # 上一价格基础上下跌至1.1,报警 cache_rate, diff, is_alert = alert(10.24, 10, cache_rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('-1.1')) self.assertTrue(is_alert) # 上一价格基础上上涨2.2,报警 cache_rate, diff, is_alert = alert(10.46, 10, cache_rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('2.2')) self.assertTrue(is_alert) # 初始下跌3.5%,报警 cache_rate, diff, is_alert = alert(9.65, 10, rate=rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('-3.5')) self.assertTrue(is_alert) # 下跌2 cache_rate, diff, is_alert = alert(9.45, 10, cache_rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('-2')) self.assertTrue(is_alert) # 上一价格基础上上涨10.1,报警 cache_rate, diff, is_alert = alert(10.46, 10, cache_rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('10.1')) self.assertTrue(is_alert) # 上一价格基础上下跌0.1,不报警 cache_rate, diff, is_alert = alert(10.45, 10, cache_rate) print(cache_rate, diff) self.assertEqual(diff, Decimal('-0.1')) self.assertFalse(is_alert)
""" Prashanth Khambhammettu ([email protected]) 2013/02/20 : Summation of Sine Waves """ import matplotlib.pyplot as plt import numpy as np import math as math import sys """ Sine function Returns an array of times and values of sin(pi*n*t) /n where t belongs to [-1,1] n is the input parameter """ def xn(n): if(n==0): sys.exit('Cannot divide by zero') pi=math.pi delta=1e-04 t= np.arange(-1,1+delta,delta) #print t.shape y=np.empty(t.shape, dtype=float) #print y.shape y=np.sin(pi*n*t) return t,y/n """ Summation function Sums several xn functions Calculates sigma(xn(2K+1)) for k=0 to N returns an array of times and summation values """ def summation(N): if(N<0): sys.exit('Cannot Compute when N is less than 0') #Compute the first wave t,y = xn(2*0+1) #Add the remaining waves when we have more than one if(N>0): for k in range(1,N+1): t,ynew=xn(2*k+1) y=y+ynew return t,y """ Main part of the program """ ax1 =plt.subplot(2,2,1) t1,y1 =summation(0) ax1.plot(t1,y1,'r-') ax1.grid(which='both') plt.title ('N=0') ax2 =plt.subplot(2,2,2) t2,y2 =summation(2) ax2.plot(t2,y2,'r-') ax2.grid(which='both') plt.title ('N=2') ax3 =plt.subplot(2,2,3) t3,y3 =summation(20) ax3.plot(t3,y3,'r-') ax3.grid(which='both') plt.title ('N=20') ax4 =plt.subplot(2,2,4) t4,y4 =summation(150) ax4.plot(t4,y4,'r-') ax4.grid(which='both') plt.title ('N=150') plt.xlim(-1,1) plt.ylim(-1,1) plt.show()
print('Hello') #создадим список и сразу выводим его spisok2 = ['Gosha','Max','Denis'] print(spisok2) #Добавим в список переменную spisok2.append('Alex') print(spisok2) #создадим ещё один список и добавим всё его содержимое в первый spisok1 = ['Gordon'] spisok2.extend(spisok1) print(spisok2) #удаляем из списка конкретную переменную spisok2.remove('Alex') print(spisok2) #удалим список del spisok1 print('') #разворачиваем список print(spisok2) spisok2.reverse() print(spisok2) #создадим новый список и отсортируем его print('') spisok = ['83','1','67'] print(spisok) spisok.sort() print(spisok) #очистим этот список spisok.clear() print(spisok) #выводим 1 и 3 элемент списка print('') str = ['gosha','alex','masha','valera'] print(str[0], str[2])
# author: tornado2 answer = input ("HELLO") answer = answer.lower() word = answer.split() if word[0] = "how": if word[1] = "do": if word[2] = "you": if word[3] = "do": print "I'm fine" if word[1] = "are": if word[2] = "you": if word[3] = "a": if word[4] = "robot": print "I am not a robot. I am THE Cleverbot 3000"
# -*- coding: utf-8 -*- """ Created on Wed Aug 19 14:20:29 2020 @author: USER """ def circle_area(x): num=x*x*3.14 return num def circle_circum(x): num=x*2*3.14 return num circle_area(n) n= int(input("number")) print(n) n= int(input("number")) cicle_circum(n) print(n)
# my first python script quotes = { "Moe": "A wise guy, huh?", "Larry": "Ow!", "Curly": "Nyuk nyuk!", } stooge = "Larry" print(stooge, "says:", quotes[stooge]) language = 7 print("Language %s: I am Python. What's for supper?") print(language, "I am Python. What's for supper?") stooge = "Moe" print(quotes[stooge])
# Opening file readFile = open("poojith.txt", "r") # running a loop for every line in the file for line in readFile: #You can use the len method to find how many chracters there are. #lengthofLine = len(str(line)) #print(lengthofLine) if 'Python' in line: #using the replace method I was able to replace the word Python with Java Script. print (line.replace('Python', "Java Script"))
# 给定一个可包含重复数字的序列,返回所有不重复的全排列。 # # 示例: # # 输入: [1,1,2] # 输出: # [ # [1,1,2], # [1,2,1], # [2,1,1] # ] # Related Topics 回溯算法 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.res = [] nums.sort() self.fun(nums,[]) return self.res def fun(self, nums, last_res): if not nums: self.res.append(last_res) return self.fun(nums[0:0] + nums[1:], last_res+[nums[0]]) for i in range(1, len(nums)): if i>0 and nums[i] == nums[i-1]: continue self.fun(nums[0:i] + nums[i + 1:], last_res+[nums[i]]) # class Solution: # def permuteUnique(self, nums: List[int]) -> List[List[int]]: # if not nums: return [] # nums.sort() # res = [] # # def backtrack(nums, tmp): # if not nums: # res.append(tmp) # return # for i in range(len(nums)): # if i > 0 and nums[i] == nums[i - 1]: # continue # backtrack(nums[:i] + nums[i + 1:], tmp + [nums[i]]) # # backtrack(nums, []) # return res # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution() res = solution.permuteUnique([1,2, 1]) print(res)
# 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 # # 求在该柱状图中,能够勾勒出来的矩形的最大面积。 # # # # # # 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。 # # # # # # 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。 # # # # 示例: # # 输入: [2,1,5,6,2,3] # 输出: 10 # Related Topics 栈 数组 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def largestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ if not heights: return None res = heights[0] stack = [-1] for i in range(len(heights)): while stack[-1] != -1 and heights[stack[-1]] > heights[i]: res = max(res, heights[stack.pop(-1)] * (i - stack[-1] - 1)) stack.append(i) print(stack) print(res) length = len(heights) for i in stack[::-1]: if i == -1: continue res = max(res, heights[stack.pop(-1)] * (length - stack[-1] - 1)) return res # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution() res = solution.largestRectangleArea([1, 0, 3, 2, 2]) print(res)
# 有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同, # 你能对此优化吗? # # 示例: # # 输入:words = ["I","am","a","student","from","a","university","in","a","city"], # word1 = "a", word2 = "student" # 输出:1 # # 提示: # # # words.length <= 100000 # # Related Topics 双指针 字符串 # leetcode submit region begin(Prohibit modification and deletion) import collections class Solution(object): def findClosest(self, words, word1, word2): """ :type words: List[str] :type word1: str :type word2: str :rtype: int """ dict_ = collections.defaultdict(list) for i, j in enumerate(words): dict_[j].append(i) list1 = dict_[word1] list2 = dict_[word2] length1 = len(list1) length2 = len(list2) i, j = 0, 0 res = float("inf") while i < length1 or j < length2: if abs(list1[i] - list2[j]) == 1: return 1 res = min(res,abs(list1[i] - list2[j])) if list1[i]> list2[j]: j +=1 else: i +=1 return res def findClosest(self, words, word1, word2): i, j = None, None res = float("inf") for index,elem in enumerate(words): if elem == word1: i = index if i and j: res = min(res,abs(i-j)) elif elem == word2: j = index if i and j: res = min(res,abs(i-j)) return res # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution() distance = solution.findClosest(["I", "am", "a", "student", "from", "a", "university", "in", "a", "city"], "a", "student") print(distance)
# 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋 # 装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 # # 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 # # 示例 1: # # 输入: [2,3,2] # 输出: 3 # 解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。 # # # 示例 2: # # 输入: [1,2,3,1] # 输出: 4 # 解释: 你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。 #   偷窃到的最高金额 = 1 + 3 = 4 。 # Related Topics 动态规划 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ def fun(arr): cur, pre = 0, 0 for i in arr: pre, cur = cur, max(pre+i,cur) return cur return max(fun(nums[0:-1]),fun(nums[1:])) if len(nums) != 1 else nums[0] # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution() res = solution.rob([2, 3]) print(res)
# 给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 num # s[i] 的元素的数量。 # # 示例: # # 输入: [5,2,6,1] # 输出: [2,1,1,0] # 解释: # 5 的右侧有 2 个更小的元素 (2 和 1). # 2 的右侧仅有 1 个更小的元素 (1). # 6 的右侧有 1 个更小的元素 (1). # 1 的右侧有 0 个更小的元素. # # Related Topics 排序 树状数组 线段树 二分查找 分治算法 # leetcode submit region begin(Prohibit modification and deletion) class TreeNode(object): def __init__(self, value): self.left = None self.right = None self.value = value # 节点值 self.count = 0 # 左子树节点数量 # # class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ root = None res = [0 for _ in range(len(nums))] for i in reversed(range(len(nums))): root = self.insert_node(root, nums[i], res, i) return res def insert_node(self, root, value, res, res_index): if root is None: root = TreeNode(value) elif value <= root.value: root.count += 1 root.left = self.insert_node(root.left, value, res, res_index) else: res[res_index] += root.count + 1 root.right = self.insert_node(root.right, value, res, res_index) return root class Solution: def countSmaller(self, nums): size = len(nums) if size == 0: return [] if size == 1: return [0] temp = [None for _ in range(size)] indexes = [i for i in range(size)] res = [0 for _ in range(size)] self.__helper(nums, 0, size - 1, temp, indexes, res) return res def __helper(self, nums, left, right, temp, indexes, res): if left == right: return mid = left + (right - left) // 2 # 计算一下左边 self.__helper(nums, left, mid, temp, indexes, res) # 计算一下右边 self.__helper(nums, mid + 1, right, temp, indexes, res) if nums[indexes[mid]] <= nums[indexes[mid + 1]]: return self.__sort_and_count_smaller(nums, left, mid, right, temp, indexes, res) def __sort_and_count_smaller(self, nums, left, mid, right, temp, indexes, res): # [left,mid] 前有序数组 # [mid+1,right] 后有序数组 # 先拷贝,再合并 for i in range(left, right + 1): temp[i] = indexes[i] l = left r = mid + 1 for i in range(left, right + 1): if l > mid: # l 用完,就拼命使用 r # [1,2,3,4] [5,6,7,8] indexes[i] = temp[r] r += 1 elif r > right: # r 用完,就拼命使用 l # [6,7,8,9] [1,2,3,4] indexes[i] = temp[l] l += 1 # 注意:此时前面剩下的数,比后面所有的数都大 res[indexes[i]] += (right - mid) elif nums[temp[l]] <= nums[temp[r]]: # [3,5,7,9] [4,6,8,10] indexes[i] = temp[l] l += 1 # 注意: res[indexes[i]] += (r - mid - 1) else: assert nums[temp[l]] > nums[temp[r]] # 上面两种情况只在其中一种统计就可以了 # [3,5,7,9] [4,6,8,10] indexes[i] = temp[r] r += 1 if __name__ == '__main__': solution = Solution() res = solution.countSmaller([1,0,2]) print(res) # leetcode submit region end(Prohibit modification and deletion)
# 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 # # # # 示例: # # 输入:n = 3 # 输出:[ # "((()))", # "(()())", # "(())()", # "()(())", # "()()()" # ] # # Related Topics 字符串 回溯算法 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ res = ["()"] if n ==1: return res res = self.generateParenthesis(n-1) temp_res = [] for i in res: for j in range(len(i)): temp_res.append(i[:j]+"()"+i[j:]) return list(set(temp_res)) # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': solution = Solution() res = solution.generateParenthesis(4) print(res) print(len(res)) # i = ["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"] # j = ['()(()())', '()()(())', '(()(()))', '(((())))', '(()())()', '((())())', '()(())()', '()((()))', '()()()()', '(())()()', '((()()))', '((()))()', '(()()())'] # print(len(i)) # print(len(j)) # for w in i: # if w not in j: # print(w)
import re from string import ascii_lowercase, digits def has_upper(s, field_name): msg = 'The {0} you entered cannot have uppercase letters.'.format(field_name) if any([char.isupper() for char in s]): return True, msg return False, None def has_nonalpha(s, field_name): msg = 'The {0} you entered can only have alphanumeric characters.'.format(field_name) if not all([(char in ascii_lowercase or char in digits) for char in s.lower()]): return True, msg return False, None def has_upper_nonalpha(s, field_name): upper_results = has_upper(s, field_name) alpha_results = has_nonalpha(s, field_name) return [msg for msg in (upper_results[1], alpha_results[1]) if msg is not None]
''' Time Complexity Best : O(nlog(n)) Average : O(nlog(n)) Worst : O(nlog(n)) ''' def HEAP_SORT(A): heap_size = BUILD_MAX_HEAP(A) for i in range(len(A)-1, 1, -1): A[0], A[i] = A[i], A[0] heap_size -= 1 MAX_HEAPIFY(A, 0, heap_size) def BUILD_MAX_HEAP(A): heap_size = len(A) for i in range(int(len(A)/2), -1, -1): MAX_HEAPIFY(A, i, heap_size) return heap_size def MAX_HEAPIFY(A, i, heap_size): l = 2 * i + 1 r = 2 * i + 2 #check if left side of root exists and is greater than root. if l < heap_size and A[l] > A[i]: largest = l else: largest = i #check if right side of root exists and is greater than root. if r < heap_size and A[r] > A[largest]: largest = r #change root if needed if largest != i: A[i], A[largest] = A[largest], A[i] MAX_HEAPIFY(A, largest, heap_size) A = [9, 8, 7, 6, 5] HEAP_SORT(A) print(A)
#!/usr/bin/python3 """ Queries the Reddit API. Returns the number of subscribers for a given subreddit If an invalid subreddit is given, the function should return 0. """ import requests def number_of_subscribers(subreddit): """ Function queries the Reddit API and returns the number of subscribers """ if subreddit is None or type(subreddit) is not str: return (0) headers = {'User-Agent': 'Python/requests: APIadvancedproject: v1.0.0 (by /u/natpons)'} req = requests.get('http://www.reddit.com/r/{}/about.json'.format( subreddit), headers=headers).json() num_subs = req.get('data', {}).get('subscribers') return num_subs
n = 10000 step = 1./(n-1) iterations = 100 import matplotlib.pyplot as plt dist = [1./n] * n values = [0.] * n for it in range(iterations): value_action = [] cumulative_dist = [0.] * n s = 0. for i in range(n): s += dist[i] cumulative_dist[i] = s - dist[i] / 2. for action in range(n): val = 0. val += cumulative_dist[int((action+1) / 3)] if action * 3 < n: val += cumulative_dist[action * 3] else: val += 1. val -= cumulative_dist[action] value_action.append((val, action)) value_action.sort() for i in range(n): val, ac = value_action[i] dist[ac] = (2 * i + 1.) / (n * n) values[ac] = val dist = [x * n for x in dist] actions = [step * x for x in range(n)] plt.plot(actions, values) plt.xlabel('Choice') plt.ylabel('Chance of winning') plt.show() plt.plot(actions, dist) plt.xlabel('Choice') plt.ylabel('Probability') plt.show() val, ac = value_action[n-1] print ('Action ' + str(ac / (n-1.)) + ' has highest chance of winning = ' + str(val))
s = 'hi ' * 3 + 'hello ' * 3 + 'test ' * 2 + 'world ' * 3 # input("Please enter string: ") words = {} for word in s.split(): if word in words: words[word] += 1 else: words[word] = 1 # words[word] = words.get(word, 0) + 1 print(words) max_cnt = 0 max_word = '' for key, value in words.items(): if value >= max_cnt: max_cnt = value max_word = key print(max_word, ':', max_cnt)
def iteratively_pow(num, exp): res = 1 while exp > 0: res *= num exp -= 1 return res print(iteratively_pow(2, 5)) def recursive_pow(num, exp): # base case if exp == 0: return 1 # recursive case return num * recursive_pow(num, exp - 1) print(recursive_pow(2, 5)) def fibonacci_recursive(n): return n if 0 <= n <= 1 else fibonacci_recursive(n-1) + fibonacci_recursive(n-2) ''' x1 x2 y x1 x2 y 0 1 1 2 ''' def fibonacci_it(num): x1 = 0 x2 = 1 while num > 0: y = x1 + x2 x1 = x2 x2 = y num -= 1 return x1 print(fibonacci_recursive(10)) print(fibonacci_it(10))
x = 4 y = 0 i = input() # print('Результат деления:', x / y) try: print('Результат деления:', x / y) # except Exception as ex: # pass except ZeroDivisionError as ex: print(ex) except OverflowError: pass except FloatingPointError as ex: pass
x = 0 if x == 0: print('Yes') else: print('No') print('Yes') if x == 0 else print('No') print('No') if x else print('Yes') print('No' if x else 'Yes') # x / y = z y = 56 z = (x / y if y else x)
""" class <NAME>(<Base class>): pass """ class Point: X = 5 Y = 8 def __init__(self, x, y): self.x = x self.y = y def get_x(self): return self.x def get_y(self): return self.y def set_x(self, x): self.x = x def set_y(self, y): self.y = y def get_res(self): return self.x + self.__class__.X def __str__(self): return 'x = {}, y = {}'.format(self.x, self.y) def __add__(self, other): return self.x + other.x, self.y + other.y pt1 = Point(4, 8) print(id(pt1)) # print(pt1.x, pt1.y) print(pt1.get_x(), pt1.get_y()) pt2 = Point(1, 2) # print(pt2.x, pt2.y) print(id(pt2)) # pt1.x = 7 # print(pt1.x, pt1.y) print('attr of class X:', Point.X) print('result pt1:', pt1.get_res()) print('result pt2:', pt2.get_res()) Point.X = 6 print('attr of class X:', Point.X) print('result pt1:', pt1.get_res()) print('result pt2:', pt2.get_res()) print(str(pt1)) print(pt1 + pt2) res = pt1 + pt2 pt3 = Point(res[0], res[1]) print(pt3)
# Lab Topic 04-Flow control if elif and else # Author: Andrew Beaty # Practice Work by Sheila Bambrick number = int(input("enter an integer:")) if (number % 2) == 0: print ("{} is an even number".format(number)) else: print("{} is an odd number".format (number))
from tkinter import * import random def startGame(): boardWidth = 30 boardHeight = 30 tilesize = 10 class Snake(): def __init__(self): self.snakeX = [20, 20, 20] self.snakeY = [20, 21, 22] self.snakeLength = 3 self.key = "w" self.points = 0 def move(self): # move and change direction with wasd for i in range(self.snakeLength - 1, 0, -1): self.snakeX[i] = self.snakeX[i-1] self.snakeY[i] = self.snakeY[i-1] if self.key == "w": self.snakeY[0] = self.snakeY[0] - 1 elif self.key == "s": self.snakeY[0] = self.snakeY[0] + 1 elif self.key == "a": self.snakeX[0] = self.snakeX[0] - 1 elif self.key == "d": self.snakeX[0] = self.snakeX[0] + 1 self.eatApple() def eatApple(self): if self.snakeX[0] == apple.getAppleX() and self.snakeY[0] == apple.getAppleY(): self.snakeLength = self.snakeLength + 1 x = self.snakeX[len(self.snakeX)-1] # Snake grows y = self.snakeY[len(self.snakeY) - 1] self.snakeX.append(x+1) self.snakeY.append(y) self.points = self.points + 1 apple.createNewApple() def checkGameOver(self): for i in range(1, self.snakeLength, 1): if self.snakeY[0] == self.snakeY[i] and self.snakeX[0] == self.snakeX[i]: return True # Snake eat itself if self.snakeX[0] < 1 or self.snakeX[0] >= boardWidth-1 or self.snakeY[0] < 1 or self.snakeY[0] >= boardHeight-1: return True # Snake out of Bounds return False def getKey(self, event): if event.char == "w" or event.char == "d" or event.char == "s" or event.char == "a" or event.char == " ": self.key = event.char def getSnakeX(self, index): return self.snakeX[index] def getSnakeY(self, index): return self.snakeY[index] def getSnakeLength(self): return self.snakeLength def getPoints(self): return self.points class Apple: def __init__(self): self.appleX = random.randint(1, boardWidth - 2) self.appleY = random.randint(1, boardHeight - 2) def getAppleX(self): return self.appleX def getAppleY(self): return self.appleY def createNewApple(self): self.appleX = random.randint(1, boardWidth - 2) self.appleY = random.randint(1, boardHeight - 2) class GameLoop: def repaint(self): canvas.after(200, self.repaint) canvas.delete(ALL) if snake.checkGameOver() == False: snake.move() snake.checkGameOver() canvas.create_rectangle(snake.getSnakeX(0) * tilesize, snake.getSnakeY(0) * tilesize, snake.getSnakeX(0) * tilesize + tilesize, snake.getSnakeY(0) * tilesize + tilesize, fill="red") # Head for i in range(1, snake.getSnakeLength(), 1): canvas.create_rectangle(snake.getSnakeX(i) * tilesize, snake.getSnakeY(i) * tilesize, snake.getSnakeX(i) * tilesize + tilesize, snake.getSnakeY(i) * tilesize + tilesize, fill="blue") # Body canvas.create_rectangle(apple.getAppleX() * tilesize, apple.getAppleY() * tilesize, apple.getAppleX() * tilesize + tilesize, apple.getAppleY() * tilesize + tilesize, fill="green") # Apple else: # GameOver Message canvas.delete(ALL) canvas.create_text(150, 100, fill="darkblue", font="Times 20 italic bold", text="GameOver!") canvas.create_text(150, 150, fill="darkblue", font="Times 20 italic bold", text="Points:" + str(snake.getPoints())) snake = Snake() apple = Apple() root = Tk() canvas = Canvas(root, width=300, height=300) canvas.configure(background="yellow") canvas.pack() gameLoop = GameLoop() gameLoop.repaint() root.title("Snake") root.bind('<KeyPress>', snake.getKey) root.mainloop() # startGame()
# MATH10222, orbital motion for an inverse square central field. # This computes the solution of Newton's second law directly. # Initial conditions r=d, r-dot=0, theta=0 import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation import math # graph range xLeft = -0.5 xRight = 1.5 yBottom = -1. yTop = 1 # paramters d = 1.0 # initial radius of P from O gamma = 8.0 # bigger gamma means more attractive force field HO = 1.0 # angular momentum constant # time stepper for direct solution of Newton's 2nd law dt = 0.0025 tMax = 0.86 # force function, vector force is m*F(f)*r-hat-vector def F(r): return -gamma/r**2 # Newtonian gravitation # Newton's 2nd law (in polar form) written as THREE first order equations # d/dt [r,rdot,theta] = [rdot,F(r)+HO/r^3,HO/r^2] # d/dt(theta) = HO/r^2 # systemState contains : [r,rdot,theta] where rdot=dr/dt def NewtonSecond( systemState, t): derivState = np.zeros_like(systemState) derivState[0] = systemState[1] # d/dt(r) = rdot derivState[1] = F(systemState[0]) + HO/systemState[0]**3 # d/dt(rdot) = F(r) + HO/r^3 derivState[2] = HO/systemState[0]**2 # d/dt(theta) = HO/r^2 (obviously trivial to integrate) return derivState # time points used in solving Newton's second law t = np.arange(0.0,tMax,dt) # initial condition: state[0]=r=d, state[1]=rdot=0.0, state[2]=theta=0 state = np.array([d,0.0,0.0]) soln = integrate.odeint(NewtonSecond, state, t) # matplotlib for output fig = plt.figure(figsize=(5,5)) ax = plt.axes() particlePoint1, = ax.plot([], [], 'o', color='r', markersize=8, zorder=20, label="particle now") particlePoint2, = ax.plot([], [], 'o', color='b', markersize=8, zorder=20, label="particle before") keplerLine1, = ax.plot([], [], '-', color='r', markersize=8, zorder=20) keplerLine2, = ax.plot([], [], '-', color='b', markersize=8, zorder=20) plt.xlim(xLeft,xRight) plt.ylim(yBottom,yTop) plt.xlabel("position, x = r*cos(theta)") plt.ylabel("position, y = r*sin(theta)") plt.title("Orbital motion") plt.plot(0.0,0.0, 'o') # origin of the force field at r=0 # construct the (X,Y) path from polar solution X=[] Y=[] for i in range(0,len(t)): X.append(soln[i,0]*math.cos(soln[i,2])) Y.append(soln[i,0]*math.sin(soln[i,2])) # plot the path plt.plot(X,Y,'-',color='k', linewidth=0.5, label="path") plt.legend(loc='lower right', frameon=False) # animate the position of the particle in the well function def animate(i): # P is at x = r*cos(theta) and y = r*sin(theta) particlePoint1.set_data(X[i],Y[i]) # current point particlePoint2.set_data(X[i-20],Y[i-20]) # old point keplerLine1.set_data([0.0,X[i]],[0.0,Y[i]]) keplerLine2.set_data([0.0,X[i-20]],[0.0,Y[i-20]]) # area of the triangle between the current and old point remains constant ani = animation.FuncAnimation(fig, animate, np.arange(20,len(t)), interval=10) ani.save("CentralFields2.mp4", fps=25) #, dpi=100) plt.show()
import pyperclip import random import string class Credential: """ Class that generates new instances of user credentials """ credential_list = [] def __init__(self, account_name, account_email, account_password): ''' __init__ method that helps us define properties for our objects. Args: account_name: New account name. account_email : New account email address. account_password : New account password. ''' self.account_name = account_name self.account_email = account_email self.account_password = account_password def save_credential(self): ''' save_user method saves credential objects into user_list ''' Credential.credential_list.append(self) def delete_credential(self): ''' delete_credential method deletes a saved credential from the credential_list ''' Credential.credential_list.remove(self) def generate_password(self, size=8, char=string.ascii_uppercase+string.ascii_lowercase+string.digits): ''' Function to generate an 8 character password for a credential ''' gen_pass=''.join(random.choice(char) for _ in range(size)) return gen_pass @classmethod def find_by_account_name(cls,account_name): ''' Method that takes in an account_name and returns a credential that matches that name. Args: account_name: name to search for Returns : Credential of person that matches the name. ''' for credential in cls.credential_list: if credential.account_name == account_name: return credential @classmethod def credential_exist(cls,account_name): ''' Method that checks if a credential exists from the credential list. Args: account_name:account name to search if it exists Returns : Boolean: True or false depending if the credential exists ''' for credential in cls.credential_list: if credential.account_name == account_name: return True return False @classmethod def display_credential(cls): ''' method that returns the credential list ''' return cls.credential_list @classmethod def copy_account_password(cls,account_name): credential_found = Credential.find_by_account_name("account_name") pyperclip.copy(credential_found.account_password)
"""CPU functionality.""" import sys import operator class CPU: """Main CPU class.""" #load immediate (save the value) #constructing cpu and other functions def __init__(self): self.ram = [0] * 256 # 256 bytes of memories self.reg = [0] * 8 # 8 registers self.pc = 0 # program counter self.halted = False # halt self.sp = 0xF4 # stack pointer def ram_read(self, mar): # MAR (Memory Address Register) return self.ram[mar] # contains address being read or written to def ram_write(self, mdr, mar): # MDR (Memory Data Register) self.ram[mar] = mdr # data that was read or data to write def LDI(self): # store a value in a register self.reg[self.ram_read(self.pc+1)] = self.ram_read(self.pc+2) self.pc += 3 def PRN(self): # print value in a register print(f'value: {self.reg[self.ram_read(self.pc+1)]}') self.pc += 2 def HLT(self): # Halt self.halted = True self.pc += 1 def PUSH(self): self.sp -= 1 #decrement by 1 reg_a = self.ram_read(self.pc+1) self.ram_write(self.reg[reg_a], self.sp) #save the value in that RAM address self.pc += 2 def POP(self): if self.sp == 0xF4: return 'Stack is Empty' self.reg[self.ram_read(self.pc+1)] = self.ram_read(self.sp) #assign the value to that register self.sp += 1 #increment stack pointer by one self.pc +=2 #CALL return addr gets pushed on the stack def CALL(self): self.reg[self.sp] -= 1 return_addr = self.ram_read(self.pc+2) self.ram_write(return_addr, self.reg[self.sp]) reg_a = self.ram_read(self.pc+1) subroutine_addr = self.reg[reg_a] self.pc = subroutine_addr #RETURN return addr gets popped off the stack def RET(self): return_addr = self.reg[self.sp] self.reg[self.sp] += 1 self.pc = return_addr def MUL(self): operand_a = self.ram_read(self.pc+1) operand_b = self.ram_read(self.pc+2) self.alu("MUL", operand_a, operand_b) self.pc +=3 # Run the CPU def run(self): self.pc = 0 #hash table because it's cooler than if-elif run_instruction = { 1: self.HLT, 17: self.RET, 71: self.PRN, 69: self.PUSH, 70: self.POP, 80: self.CALL, 130: self.LDI, 162: self.MUL, } while not self.halted: IR = self.ram_read(self.pc) # Instruction Register (IR) run_instruction[IR]() self.trace() self.halted = True def load(self): address = 0 with open(sys.argv[1]) as func: for line in func: string_val = line.split("#")[0].strip() if string_val == '': continue v = int(string_val, 2) self.ram[address] = v address += 1 def alu(self, op, reg_a, reg_b): """ALU operations.""" #again, hash table because it is cooler than if-else ops = { "ADD" : lambda x,y: x+y, "MUL" : lambda x,y: x*y, "DIV" : lambda x,y: x/y, "SUB" : lambda x,y: x-y } try: self.reg[reg_a] = ops[op](self.reg[reg_a], self.reg[reg_b]) return self.reg[reg_a] except: raise("Unsupported ALU operation") def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f"TRACE: %02X | %02X %02X %02X |" % ( self.pc, #self.fl, #self.ie, self.ram_read(self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2) ), end='') for i in range(8): print(" %02X" % self.reg[i], end='') print()
def queryHandling(): locations = [[(1,2),(2,1),(3,3)],[(1,9),(3,8),(2,4)]] #items = [(6,2),(9,3),(10,5)] i = 0 k = 0 itemQuery = int(raw_input("Enter the item you wish to query: ")) #location is the array of different locations #locations is the singular location #items is the different elements inside a singular location #items[0] is the item number #items[1] is the item quantity for location in locations: for item in location: if item[0] == itemQuery: print "Item"+str(i)+" is in location"+str(k) print "There is "+str(item[1])+" of item"+str(i)+" in location"+str(k) i+=1 i = 0 k+=1;
class Contact: contacts = [] next_id = 1 def __init__(self, first_name, last_name, email, note): self.first_name = first_name self.last_name = last_name self.email = email self.note = note self.id = Contact.next_id Contact.next_id += 1 @classmethod def create(cls, first_name, last_name, email, note): valid = next((contact for contact in cls.contacts if contact.email == email), None) if valid: print("Email address already exists") else: new_contact = Contact(first_name, last_name, email, note) cls.contacts.append(new_contact) return new_contact @classmethod def all(cls): for contact in Contact.contacts: print("{} {}, {}".format(contact.first_name, contact.last_name, contact.email)) @classmethod def find(cls, ident): for contact in cls.contacts: if ident == contact.id: return contact def update(self): """ This method should allow you to specify, chosen instance will come from CRM class 1. which of the contact's attributes you want to update 2. the new value for that attribute and then make the appropriate change to the contact """ print("Copy and paste the attribute would you like to change:\nfirst_name\nlast_name\nemail\nnote") attribute = input() validation = ["first_name", "last_name", "email", "note"] if attribute in validation: print("Ok, what is the new {}?".format(attribute)) new_attr = input() setattr(self, attribute, new_attr) print("Attribute updated") else: print("Invalid attribute provided") @classmethod def find_by(cls, search_field, search_value): """This method should work similarly to the find method above but it should allow you to search for a contact using attributes other than id by specifying both the name of the attribute and the value eg. searching for 'first_name', 'Betty' should return the first contact named Betty """ for curr_contact in cls.contacts: if search_field == "first_name" and search_value == curr_contact.first_name: return curr_contact elif search_field == "last_name" and search_value == curr_contact.last_name: return curr_contact elif search_field == "email" and search_value == curr_contact.email: return curr_contact elif search_field == "note" and search_value == curr_contact.note: return curr_contact else: return False @classmethod def delete_all(cls): cls.contacts = [] def full_name(self): """Returns the full (first and last) name of the contact""" if self in Contact.contacts: print("{} {}".format(self.first_name, self.last_name)) def delete(self): """This method should delete the contact HINT: Check the Array class docs for built-in methods that might be useful here """ for contact in Contact.contacts: if self == contact: Contact.contacts.remove(self) print("Contact deleted") def __str__(self): return "Name: {} {}, email: {}, note: {}".format(self.first_name, self.last_name, self.email, self.note) # test1 = Contact.create("Sanchit", "Jain", "[email protected]", "hello") # test2 = Contact.create("Tarishi", "Jain", "[email protected]", "hello") # test3 = Contact.create("Josh", "Teneycke", "[email protected]", "hello") # print(len(Contact.contacts)) # test1.full_name() # test1.update() # Contact.all() # # Contact.delete_all() # print(len(Contact.contacts))
# -*- coding: utf-8 -*- from collections import Counter, defaultdict from itertools import product from operator import itemgetter MAX_SENTENCE = 3 class AutoCompleteSearch(object): def __init__(self) -> object: self.sentences = [] def create_counter(self, sentences): """ Create Counter for each sentence. :param sentences: list of sentence. :return: """ for sentence in sentences: tmp = [sentence] sentence = sentence.lower().split() cnt = Counter() for word in sentence: cnt[word] += 1 tmp.append(cnt) self.sentences.append(tmp) return def search(self, search_keys): search_keys = search_keys.lower().split() search_result = defaultdict(int) if search_keys[-1] != '#': print("The input string needs to ends with #.") return for sentence, search_key in product(self.sentences, search_keys[:-1]): for word in sentence[1].keys(): if search_key in word: search_result[sentence[0]] += sentence[1].get(word, 0) return search_result if __name__ == "__main__": sentences = [ "i love you", "i love you so much", "i love love you so much", "i love you so so much", "you love me", "you like me" ] search_key = "i lov you haha #" # Create instance. obj = AutoCompleteSearch() obj.create_counter(sentences) result = obj.search(search_key) sorted_result = sorted(result.items(), key=itemgetter(1), reverse=1) for sentence in sorted_result[:MAX_SENTENCE]: print(sentence[0]) print("==========================") search_key = "love you #" result = obj.search(search_key) sorted_result = sorted(result.items(), key=itemgetter(1), reverse=1) for sentence in sorted_result[:MAX_SENTENCE]: print(sentence[0]) print("==========================") search_key = "i love you" result = obj.search(search_key) if result: sorted_result = sorted(result.items(), key=itemgetter(1), reverse=1) for sentence in sorted_result[:MAX_SENTENCE]: print(sentence[0])
''' A PALINDROME IS STRING WHICH IS SAME IF REad from start or end ''' word = input("Enter a word : ") reverse = word[::-1] if reverse == word: print("Is palindrome" else: print("Not Palindrome") =------------------------------------------------------------------------------------------------------- " sum of digits using while loop " number = input("enter four digit number : ") total = 0 x = 0 while x < len(number): total = int(number[x]) + total x = x+1 print(total)
# coding=utf-8 from random import randint def roll_dice(n=2): """ 摇色子 :param n: 色子个数 :return: n颗色子点数之和 """ total = 0 for _ in range(n): total += randint(1,6) return total def add(a=0,b=0,c=0): return a+b+c # 如果没有指定参数那么使用默认值摇两颗色子 print(roll_dice()) # 摇三颗色子 print(roll_dice(3)) print(add()) print(add(1)) print(add(1, 2)) print(add(1, 2, 3)) # 传递参数时可以不按照设定的顺序进行传递 print(add(c=50, a=100, b=200))
""" for循环实现100内的偶数求和 version 0.1 author lql """ sum = 0 for x in range(0,100,2): sum = sum+x print(sum) """ 另外一种实现方式 """ sum = 0 for x in range(1,100): if x%2 ==0: sum +=x print(sum)
class Node: def __init__(self, data): self._data = data self._nextNode = None @property def data(self): return self._data @property def nextNode(self): return self._nextNode @nextNode.setter def nextNode(self, v): self._nextNode = v class LinkedList: def __init__(self): self._rootNode = None def insert(self, data): tmp = Node(data) if self._rootNode == None: self._rootNode = tmp return n = self._rootNode while n.nextNode != None: n = n.nextNode n.nextNode = tmp def dump(self): tmp = self._rootNode while tmp != None: print(tmp.data) tmp = tmp.nextNode if __name__ == "__main__": a = LinkedList() a.insert("Bostanci") a.insert("Suadiye") a.insert("Erenkoy") a.insert("Caddebostan") a.dump()
def main(): with open("input.txt", "r") as f: lines = f.readlines() first_wire_moves, second_wire_moves = [line.split(",") for line in lines] first_current_point = (0, 0) first_wire_points = [] second_current_point = (0, 0) second_wire_points = [] for move in first_wire_moves: new_points = make_move(move, first_current_point) first_current_point = new_points[-1] if new_points else first_current_point first_wire_points.extend(new_points) for move in second_wire_moves: new_points = make_move(move, second_current_point) second_current_point = new_points[-1] if new_points else second_current_point second_wire_points.extend(new_points) crossings = set(first_wire_points).intersection(set(second_wire_points)) print(min(abs(x[0]) + abs(x[1]) for x in crossings)) print(min(first_wire_points.index(c) + second_wire_points.index(c) + 2 for c in crossings)) def make_move(move, start_point): distance = int(move[1:]) direction = move[0] index = 0 if direction in ("U", "D") else 1 vertical = direction in ("U", "D") sign = -1 if direction in ("U", "L") else 1 return [ ( start_point[0] + sign * (i + 1) * vertical, start_point[1] + sign * (i + 1) * (not vertical) ) for i in range(distance) ] if __name__ == "__main__": main()
a=int(input("enter the number whichg has to be square :")) for i in range (1,a): b=(i*i) print(b)
adj=['red','big','tasty'] fruits=['apple','banana','cherry'] for x in adj: for y in fruits: if y=="banana" and x=='red': continue print(x,y)
year=int(input("enter the year:")) if (year%4==0) and (year%100!=0) or (year%400==0): print('leap year') else: print('not a leap year')
n=int(input("nhập n: ")) d=dict() for i in range(1,n+1): d[i]=i*i print(d)
list = [i for i in input()] cup1 = 1 cup2 = 0 cup3 = 0 for x in range(len(list)): if list[x] == "A": if cup1 == 1: cup1 = 0 cup2 = 1 elif cup2 == 1: cup1 = 1 cup2 = 0 elif list[x] == "B": if cup2 == 1: cup2 = 0 cup3 = 1 elif cup3 == 1: cup3 = 0 cup2 = 1 elif list[x] == "C": if cup1 == 1: cup1 = 0 cup3 = 1 elif cup3 == 1: cup3 = 0 cup1 = 1 if cup1 == 1: print("1") elif cup2 == 1: print("2") else: print("3")
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.res = 0 def pathSum(self, root: TreeNode, sum: int) -> int: if root == None: return 0 self.res += self.helper(root, sum) self.pathSum(root.left, sum) self.pathSum(root.right, sum) return self.res def helper(self, root, sum): if root == None: return [] path = [] res = [] def dfs(root, tar): if root == None: return path.append(root.val) tar -= root.val if tar == 0: path1 = path.copy() res.append(path1) dfs(root.left, tar) dfs(root.right, tar) path.pop() dfs(root, sum) return len(res)
""" https://leetcode-cn.com/problems/number-of-provinces/solution/python-duo-tu-xiang-jie-bing-cha-ji-by-m-vjdr/ 并查集是一种数据结构: 并查集这三个字,一个字代表一个意思。 1.并(Union),代表合并 2.查(Find),代表查找 3.集(Set),代表这是一个以字典为基础的数据结构,它的基本功能是合并集合中的元素,查找集合中的元素 并查集的典型应用是有关连通分量的问题 并查集解决单个问题(添加,合并,查找)的时间复杂度都是O(1)O(1) 因此,并查集可以应用到在线算法中 并查集的实现: 并查集跟树有些类似,只不过她跟树是相反的。在树这个数据结构里面,每个节点会记录它的子节点。在并查集里,每个节点会记录它的父节点。 """ class UnionFind: def __init__(self): """ 记录每个节点的父节点 """ self.father = {} def add(self, x): """ 初始化: 当把一个新节点添加到并查集中,它的父节点应该为空 添加新节点 """ if x not in self.father: self.father[x] = None def merge(self, x, y): """ 合并两个节点: 如果发现两个节点是连通的,那么就要把他们合并,也就是他们的祖先是相同的。这里究竟把谁当做父节点一般是没有区别的。 """ root_x, root_y = self.find(x), self.find(y) if root_x != root_y: self.father[root_x] = root_y def is_connected(self, x, y): """ 判断两节点是否相连: 判断两个节点是否处于同一个连通分量的时候,就需要判断它们的祖先是否相同 """ return self.find(x) == self.find(y) def find(self, x): """ 查找祖先: 查找祖先的方法是:如果节点的父节点不为空,那就不断迭代。 + 路径压缩 """ root = x while self.father[root] != None: root = self.father[root] # 路径压缩:使得路径深度恒定为2 while x != root: original_father = self.father[x] self.father[x] = root x = original_father return root
""" 迭代法: """ class Solution: def subsets(self, nums): res = [[]] for i in nums: res = res + [[i] + num for num in res] return res # print(Solution().subsets([1, 2, 3])) """ 递归:回溯 """ class Solution1: def subsets(self, nums): res = [] l = len(nums) def helper(i, tmp): res.append(tmp) print(res, tmp) for j in range(i, l): # 每个j走一个递归,走完整个列表,进行回溯 helper(j + 1, tmp + [nums[j]]) helper(0, []) return res print(Solution1().subsets([1, 2, 3]))
""" 暴力解法 """ class Solution: def exchange(self, nums): res1 = [] res2 = [] for i in nums: if i % 2 == 1: res1.append(i) if i % 2 == 0: res2.append(i) return res1 + res2 """ 双指针解法 """ class Solution1: def exchange(self, nums): i, j = 0, len(nums) - 1 while i < j: while i < j and nums[i] % 2 == 1: i += 1 while i < j and nums[j] % 2 == 0: j -= 1 nums[i], nums[j] = nums[j], nums[i] return nums
''' 滑动窗口: 思路: 这道题主要用到思路是:滑动窗口 什么是滑动窗口? 其实就是一个队列,比如例题中的 abcabcbb,进入这个队列(窗口)为 abc 满足题目要求,当再进入 a,队列变成了 abca, 这时候不满足要求。所以,我们要移动这个队列! 如何移动? 我们只要把队列的左边的元素移出就行了,直到满足题目要求! 一直维持这样的队列,找出队列出现最长的长度时候,求出解! 时间复杂度:O(n)O(n) ''' def lengthOfLongestSubstring(s): if not s: return 0 left = 0 lookup = set() n = len(s) max_len = 0 cur_len = 0 for i in range(n): cur_len += 1 while s[i] in lookup: # 如果有重复两次的就把前面的都移走,直到集合里面没有重复的 lookup.remove(s[left]) left += 1 cur_len -= 1 if cur_len > max_len: max_len = cur_len lookup.add(s[i]) print(lookup) print(max_len) return max_len lengthOfLongestSubstring('abcdaamnytuaa') """ 利用defaultdict(int) """ def lengthOfLongestSubstring1(s): """ :type s: str :rtype: int """ from collections import defaultdict lookup = defaultdict(int) start = 0 end = 0 max_len = 0 counter = 0 while end < len(s): if lookup[s[end]] > 0: counter += 1 lookup[s[end]] += 1 end += 1 while counter > 0: if lookup[s[start]] > 1: counter -= 1 lookup[s[start]] -= 1 start += 1 max_len = max(max_len, end - start) # print(max_len) return max_len lengthOfLongestSubstring1('abcdaa')
class Solution: def wordBreak(self, s, wordDict): if len(wordDict) == 0: return False l = len(s) dp = [False for i in range(l + 1)] dp[0] = True for i in range(l): for j in range(i + 1, len(s) + 1): if (dp[i] and s[i:j] in wordDict): print(s[i:j]) dp[j] = True print(i, j) print(dp) return dp[-1] print(Solution().wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]))
def letterCombinations(digits): if not digits: return [] digit2chars = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } res = [i for i in digit2chars[digits[0]]] for i in digits[1:]: result = [] for m in res: for n in digit2chars[i]: result.append(m+n) res = result print(result) return result print(letterCombinations('234'))
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: if not A and not B: return True if not A or not B: return False def dfs(s, t): if not t: return True if not s: return False return s.val == t.val and dfs(s.left, t.left) and dfs(s.right, t.right) return dfs(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def pathSum(self, root: TreeNode, target: int): path = [] tmp = [] def helper(root, target): if not root: return tmp.append(root.val) # 全局变量先加入 target -= root.val # 内部变量每次递归的时候都有自己的固定的值 if target == 0 and not root.left and not root.right: path.append(list(tmp)) helper(root.left, target) helper(root.right, target) tmp.pop() # 全局变量后删除 helper(root, target) return path
""" 暴力枚举:超时 """ class Solution: def findContinuousSequence(self, target: int): i = 1 nums = [] result = [] while i < target: nums.append(i) i += 1 for i in range(len(nums) // 2): for j in range(i, len(nums)): res = nums[i:j] if sum(res) == target: result.append(res) return result print(Solution().findContinuousSequence(15)) """ 利用滑动窗口的思想, 通过双指针实现滑动窗口 1.当窗口的和小于 target 的时候,窗口的和需要增加,所以要扩大窗口,窗口的右边界向右移动; 2.当窗口的和大于 target 的时候,窗口的和需要减少,所以要缩小窗口,窗口的左边界向右移动; 3.当窗口的和恰好等于 target 的时候,我们需要记录此时的结果。设此时的窗口为 [i, j), 那么我们已经找到了一个 i开头的序列,也是唯一一个 i开头的序列,接下来需要找 i+1 开头的序列,所以窗口的左边界要向右移动。 """ class Solution: def findContinuousSequence(self, target: int): i = 1 j = 1 sum = 0 result = [] while i <= target // 2: if sum < target: sum += j j += 1 elif sum > target: sum -= i i += 1 else: res = list(range(i, j)) result.append(res) sum -= i i += 1 return result
class Solution: def groupAnagrams(self, strs): dic = {} for i in strs: tmp = tuple(sorted(i)) dic[tmp] = dic.get(tmp, []) + [i] res =[] for i in dic: res.append(dic[i]) return res print(Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
""" 暴力超时 """ class Solution: def myPow(self, x: float, n: int) -> float: res = 1 if x > 0: for i in range(n): res *= x return res elif x == 0: return 0 else: x = -x for i in range(n): res *= x res = 1 / res return res """ 矩阵快速幂 """ class Solution1: def myPow(self, x: float, n: int) -> float: def quickMul(N): if N == 0: return 1.0 y = quickMul(N // 2) if N % 2 == 0: return y * y else: return y * y * x if n >= 0: return quickMul(n) else: return 1.0 / quickMul(-n) # -n -> -(-2)
class Solution: def merge(self, left, right): tmp = [] len1 = len(left) len2 = len(right) i, j = 0, 0 while i < len1 and j < len2: if left[i] > right[j]: self.res += (len1 - i) tmp.append(right[j]) j += 1 else: tmp.append(left[i]) i += 1 tmp += left[i:] if left[i:] else right[j:] return tmp def mergeSort(self, nums): l = len(nums) if l <= 1: return nums mid = l // 2 left = self.mergeSort(nums[:mid]) right = self.mergeSort(nums[mid:]) return self.merge(left, right) def reversePairs(self, nums) -> int: self.res = 0 self.mergeSort(nums) return self.res print(Solution().reversePairs([7, 5, 6, 4]))
class Solution: def hammingWeight(self, n: int) -> int: res = bin(n) return res.count('1') """ >> 和 <<都是位bai运算,对二进制数进行移位操作。 << 是左移,末位补0,类比十进制数在末尾添0相当于原数乘以10,x<<1是将x的二进制表示左移一位,相当于原数x乘2。比如整数4在二进制下是100, 4 << 1左移1位变成1000(二进制),结果是8。 >>是右移,右移1位相当于除以2。 而>>=和<<=,就是对变量进行位运算移位之后的结果再赋值给原来的变量,可以类比赋值运算符+=和-=可以理解。 比如x >>= 2, 就是把变量x右移2位,再保留x操作后的值。 """ class Solution1: def hammingWeight(self, n: int) -> int: res = 0 while n: print(n, bin(n)) res += n & 1 n >>= 1 return res print(bin(20)) print(Solution1().hammingWeight(20))
class ListNode: def __init__(self, x): self.val = x self.next = None # # # @param head ListNode类 # @param n int整型 # @return ListNode类 # class Solution: def removeNthFromEnd(self, head, n): # write code here p = head cnt = 0 while p: p = p.next cnt += 1 dummpy = ListNode(0) dummpy.next = head p = dummpy res = 0 while p: if res == cnt - n + 1: p.next = p.next.next break res += 1 p = p.next return dummpy.next
""" 暴力解法:超出时间限制 """ def maxArea(height): max_area = 0 for i in range(len(height) - 1): for j in range(i+1, len(height)): a = height[i:j+1] print(a) s = min(a[0], a[len(a)-1]) cur_area = s * (j-i) if cur_area > max_area: max_area = cur_area # print(max_area) return max_area maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]) # a = [1, 2, 3] # print(len(a)) # for i in range(len(a)): # 正序 # print(i) # # for i in range(len(a)-1, -1, -1): # 倒序 # print(i) # # print(a[1:2]) """ 双指针法:O(N) """ def maxArea1(height): max_area = 0 i, j = 0, len(height)-1 while i < j: cur_area = min(height[i], height[j]) * (j - i) if cur_area > max_area: max_area = cur_area if height[i] < height[j]: i += 1 else: j -= 1 print(max_area) return max_area maxArea1([1, 8, 6, 2, 5, 4, 8, 3, 7])
# encoding: UTF-8 """ Module to perform HTTP requests. To do so: import http1 response = http1.request('http://www.google.com') print(f'Status: {response.status} ({response.message})') print(f'Headers: {response.headers}') print(f'Body: {response.body.strip()}') """ import base64 from urllib.parse import urljoin from urllib.parse import urlparse from urllib.parse import urlencode from http.client import HTTPConnection from http.client import HTTPSConnection class Response: """HTTP response to encapsulates status code (200, 404, as an integer), message (such as 'OK', 'Not Found', as a string), headers (as a dictionnary), and body (as a string).""" def __init__(self, status, message, headers={}, body=None): self.status = status self.message = message self.headers = headers self.body = body def __str__(self): if self.body: _body = str(self.body).strip().replace('\n', '\\n') if len(_body) > 100: _body = _body[:97]+'...' else: _body = '' return "Response(status=%s, message='%s', headers=%s, body='%s')" %\ (self.status, self.message, self.headers, _body) class TooManyRedirectsException(Exception): pass def request(url, params={}, method='GET', body=None, headers={}, content_type=None, content_length=True, username=None, password=None, capitalize_headers=True, follow_redirect=True, max_redirect=3): """Perform a http_request: - url: the URL call, including protocol and parameters (such as 'http://www.google.com?foo=1&bar=2'). - params: URL parameters as a map, so that {'foo': 1, 'bar': 2} will result in an URL ending with '?foo=1&bar=2'. - method: the HTTP method (such as 'GET' or 'POST'). Defaults to 'GET'. - body: the body of the request as a string. Defaults to None. - headers: request headers as a dictionnary. Defaults to '{}'. - content_type: the content type header of the request. Defauls to None. - content_length: tells if we should add content length headers to the request. Defaults to true. - username: username while performing basic authentication, must be set with password. - password: password while performing basic authentication, must be set with username. - capitalize_headers: tells if headers should be capitalized (so that their names are all like 'Content-Type' for instance). - follow_redirect: tells if http1 should follow redirections (status codes 3xx). Defaults to True. - max_redirect: maximum number of redirections to follow. If there are too many redirects, a TooManyRedirectsException is raised. Defaults to 3. Returns the response as a Response object. Raise TooManyRedirectsException. NOTE: to call HTTPS URLs, Python must have been built with SSL support.""" _urlparts = urlparse(url) _host = _urlparts.netloc _matrix_params = _urlparts.params _params = '' if len(_urlparts.query) > 0: _params = _urlparts.query if len(params) > 0: if len(_params) > 0: _params += '&' _params += urlencode(params) _path = _urlparts.path if _matrix_params: _path += ';%s' % _matrix_params if len(_params) > 0: _path += '?' _path += _params _https = (_urlparts.scheme == 'https') _headers = {} for _name in headers: _headers[str(_name)] = str(headers[_name]) if content_type: _headers['Content-Type'] = str(content_type) if content_length: if body: _headers['Content-Length'] = str(len(body)) else: _headers['Content-Length'] = '0' if username and password: authorization = "Basic %s" % base64.b64encode(("%s:%s" % (username, password))) _headers['Authorization'] = authorization _capitalized_headers = {} if capitalize_headers: for _name in _headers: _capitalized = '-'.join([s.capitalize() for s in _name.split('-')]) _capitalized_headers[_capitalized] =_headers[_name] _headers = _capitalized_headers if _https: connection = HTTPSConnection(_host) else: connection = HTTPConnection(_host) connection.request(method, _path, body, _headers) _response = connection.getresponse() # method getheaders() not available in Python 2.2.1 _response_headers = {} _pairs = list(_response.msg.items()) if _pairs: for _pair in _pairs: _name = _pair[0] _value = _pair[1] if capitalize_headers: _name = '-'.join([s.capitalize() for s in _name.split('-')]) _response_headers[_name] = _value if _response.status >= 300 and _response.status < 400 and \ follow_redirect: if max_redirect <= 0: raise TooManyRedirectsException location = urljoin(url, _response_headers['Location']) connection.close() return request(url=location, params=params, method=method, body=body, headers=headers, content_type=content_type, content_length=content_length, username=username, password=password, capitalize_headers=capitalize_headers, follow_redirect=True, max_redirect=max_redirect-1) response = Response(status=_response.status, message=_response.reason, headers=_response_headers, body=_response.read()) connection.close() return response def get(*args, **kwargs): return request(*args, method='GET', **kwargs) def head(*args, **kwargs): return request(*args, method='HEAD', **kwargs) def post(*args, **kwargs): return request(*args, method='POST', **kwargs) def put(*args, **kwargs): return request(*args, method='PUT', **kwargs) def delete(*args, **kwargs): return request(*args, method='DELETE', **kwargs) def connect(*args, **kwargs): return request(*args, method='CONNECT', **kwargs) def options(*args, **kwargs): return request(*args, method='OPTIONS', **kwargs) def trace(*args, **kwargs): return request(*args, method='TRACE', **kwargs)
#!/usr/bin/env python3 # -*- encoding = utf-8 -*- # 该代码由本人学习时编写,仅供自娱自乐! # 本人QQ:1945962391 # 欢迎留言讨论,共同学习进步! # 装饰器实例1---通过装饰器装饰打印效果 # def outer(fun): # def inner(): # print("inner is start") # fun() # print("inner is done") # return inner # # # @outer # --> name = outer(name) # def name(): # print("I am while") # # # name() # 装饰器实例2---通过装饰器装饰打印效果 # def outer(fun): # def inner(): # print("hello this is our school") # fun() # print("this teacher is our teacher") # return inner # # # @outer # while_name = outer(name) # def while_name(): # print("I am while") # # # @outer # for_name = outer(name) # def for_name(): # print("I am for") # # # while_name() # print("I am +++++++++++++++++++++++++") # for_name() # 装饰器实例2---通过装饰器装饰打印效果 import time def zs_loger(fun): types, data = fun() content = "[%s]:[%s]%s" return content % (time.ctime(), types, data) @zs_loger # loger1 = zs_loger(loger1) def loger1(): return "Error", "your password error" @zs_loger # loger2 = zs_loger(loger2) def loger2(): return "woring", "your are logout" print(loger1) print(loger2)
#!/bin/python3 """ Monica wants to buy exactly one keyboard and one USB drive from her favorite electronics store. The store sells n different brands of keyboards and m different brands of USB drives. Monica has exactly s dollars to spend, and she wants to spend as much of it as possible (i.e., the total cost of her purchase must be maximal). Given the price lists for the store's keyboards and USB drives, find and print the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead. """ def getMoneySpent(keyboards, drives, s): lst = max([i+j if i+j <= s else 0 for i in keyboards for j in drives]) return lst if lst > 0 else -1 s,n,m = input().strip().split(' ') s,n,m = [int(s),int(n),int(m)] keyboards = list(map(int, input().strip().split(' '))) drives = list(map(int, input().strip().split(' '))) # The maximum amount of money she can spend on a keyboard and USB drive, or # -1 if she can't purchase both items moneySpent = getMoneySpent(keyboards, drives, s) print(moneySpent)
#!/bin/python """ Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number? Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings. Input Format The first line contains a single string, a. The second line contains a single string, b. Constraints It is guaranteed that a and b consist of lowercase English alphabetic letters (i.e., a through z). Output Format Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other. Sample Input cde abc Sample Output 4 Explanation We delete the following characters from our two strings to turn them into anagrams of each other: Remove d and e from cde to get c. Remove a and b from abc to get c. We must delete characters to make both strings anagrams, so we print on a new line. """ from collections import Counter import itertools # ============================================================================ # Solution 1 # ============================================================================ def number_needed(a, b): count_a = Counter(a) count_b = Counter(b) count_a.subtract(count_b) return sum(abs(i) for i in count_a.values()) # ============================================================================ # Solution 2 # ============================================================================ def number_needed2(a, b): count = 0 for i in range(97, 123): ia = sum(letter == chr(i) for letter in a) ib = sum(letter == chr(i) for letter in b) count += abs(ia - ib) return count # ============================================================================ # Solution 3 # ============================================================================ # TODO: not working yet def number_needed3(a, b): count = 0 for i in range(97, 123): ia = len([i for i in itertools.ifilter(lambda x: x == chr(i), a)]) ib = len([i for i in itertools.ifilter(lambda x: x == chr(i), b)]) count += abs(ia - ib) return count # ============================================================================ # Solution 4 # ============================================================================ def number_needed4(a, b): a = Counter(a) b = Counter(b) c = a - b d = b - a e = c + d return len(list(e.elements())) a = 'bacdc' b = 'dcbac' # a = raw_input().strip() # b = raw_input().strip() print number_needed3(a, b)
n = int(input('insira um número: ')) if n > 0: print('É positivo') else: print('É negativo')
#Faça um Programa que peça dois números e imprima a soma. n1 = int(input("n1: ")) n2 = int(input("n2: ")) print(n1 * n2)
import os import csv totalmonths = 0 net = 0 monthlychange = [] months = [] greatest_increase = 0 greatest_increase_month = 0 greatest_decrease = 0 greatest_decrease_month = 0 csvpath = os.path.join('.', 'Resources', 'budget_data.csv') with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) row = next(csvreader) previousrow = int(row[1]) totalmonths += 1 net += int(row[1]) greatest_increase = int(row[1]) greatest_increase_month = row[0] for row in csvreader: totalmonths += 1 net += int(row[1]) change_revenue = int(row[1]) - previousrow monthlychange.append(change_revenue) previousrow = int(row[1]) months.append(row[0]) if int(row[1]) > greatest_increase: greatest_increase = int(row[1]) greatest_increase_month = row[0] if int(row[1]) < greatest_decrease: greatest_decrease = int(row[1]) greatest_decrease_month = row[0] averagechange = sum(monthlychange)/ len(monthlychange) highest = max(monthlychange) lowest = min(monthlychange) print(f"Financial Analysis") print(f"---------------------------") print(f"Total Months: {totalmonths}") print(f"Total: ${net}") print(f"Average Change: ${averagechange:.2f}") print(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})") print(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})") output_file = os.path.join('.', 'Resources', 'output.txt') with open(output_file, 'w',) as newtextfile: newtextfile.write(f"Financial Analysis\n") newtextfile.write(f"---------------------------\n") newtextfile.write(f"Total Months: {totalmonths}\n") newtextfile.write(f"Total: ${net}\n") newtextfile.write(f"Average Change: ${averagechange}\n") newtextfile.write(f"Greatest Increase in Profits:, {greatest_increase_month}, (${highest})\n") newtextfile.write(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${lowest})\n")
def encrypt(text,key): result="" for i in range(len(text)): char = text[i] if char==" ": result+=" " continue if char.isupper(): result+=chr((ord(char)+key-65)%26 +65) else: result+=chr((ord(char)+key-97)%26 +97) return result def decrypt(ciphertext,key): result="" for i in range(len(ciphertext)): char = ciphertext[i] if char==" ": result+=" " continue if char.isupper(): result+=chr((ord(char)-key-65)%26+ 65) else: result+=chr((ord(char)-key-97)%26+ 97) return result text = "defend the east wall of the castle" key = 1 print("Plain Text:",text) print("Key:",key) ciphertext = encrypt(text,key) print("Cipher Text:",ciphertext) print("Decrypted text:",decrypt(ciphertext,key))
# file to plot different graphs for the MLP model import os import numpy as np import matplotlib.pyplot as plt def plot_training_loss(hyperparameters, loss_curves, hyperparameter_type): """ Function to plot loss curves for MLP, for different activation functions :param hyperparameters: a list of hyperparameters used to retrieve the loss curves :param loss_curves: a nested list of loss curves for each activation function :param hyperparameter_type: string of hyperparameter that is being changed """ fig = plt.figure(figsize=(10, 10), dpi=80) ax = fig.add_subplot(1, 1, 1) ax.set_xlabel("Fold") ax.set_ylabel("Cross Entropy Loss") ax.set_title("MLP Cross Entropy for Different {}".format(hyperparameter_type)) for i, curve in enumerate(loss_curves): ax.scatter([i for i in range(len(curve))], curve) ax.legend(hyperparameters) fig.savefig(os.path.join("plots", "mlp", "loss_{}_comparison.png".format(hyperparameter_type))) def plot_metrics(accuracies, precisions, recalls, f1s, hyperparameters, hyperparameter_type): """ Plots different performance metrics as a function of different hyperparameters :param accuracies: list containing accuracy found for each hyperparameter :param precisions: list containing precision found for each hyperparameter :param recalls: list containing recall found for each hyperparameter :param f1s: list containing f1 score for each hyperparameter :param hyperparameters: list containing hyperparameters to be plotted :param hyperparameter_type: string containing hyperparameter name :return: """ fig = plt.figure(figsize=(10, 10), dpi=80) ax = fig.add_subplot(1, 1, 1) ax.set_ylabel("Score (0-1)") ax.set_title("Comparing Metrics for Different {}".format(hyperparameter_type)) metrics = [np.array(accuracies) / 100, precisions, recalls, f1s] for metric in metrics: if hyperparameter_type == "activation_func" or hyperparameter_type == "shape": ax.set_xlabel(hyperparameter_type) xs = np.arange(len(hyperparameters)) ax.plot(xs, metric) ax.set_xticks(xs) ax.set_xticklabels(hyperparameters) elif hyperparameter_type == "reg_param": ax.set_xlabel("$log_{}$({})".format("{10}", hyperparameter_type)) ax.plot(np.log(hyperparameters), metric) ax.legend(["Accuracy", "Precision", "Recall", "F1 Score"]) fig.savefig(os.path.join("plots", "mlp", "{}_metric_comparison.png".format(hyperparameter_type)))
import numpy as np import pandas as pd def import_and_process(fname, input_cols=None, target_col=None): """ Imports a dataset, pre-processes it and splits it into train and test parts. :param fname: Filename/path of data file. :param input_cols: List of column names for the input data. :param target_col: Column name of the target data. :return: inputs_train_crossval - train inputs data split into sub-arrays for cross-validation targets_train_crossval - train targets data split into sub-arrays for cross-validation inputs_train -- the whole training inputs data as a numpy.array object targets_train -- the whole training targets data as a 1d numpy array of class ids inputs_test -- the test inputs data as a numpy.array object targets_test -- the test targets data as a 1d numpy array of class ids input_cols -- ordered list of input column names classes -- ordered list of classes """ # if no file name is provided then use synthetic data df = pd.read_csv(fname) # print("dataframe.columns = %r" % (dataframe.columns,) ) N = df.shape[0] # pre-process and encode data df_onehot = pre_process_bc(df) # if no target name is supplied we assume it is the last column in the # data file if target_col is None: target_col = df_onehot.columns[-1] potential_inputs = df_onehot.columns[:-1] else: potential_inputs = list(df_onehot.columns) # print([potential_inputs]) # target data should not be part of the inputs potential_inputs.remove(target_col) # if no input names are supplied then use them all if input_cols is None: input_cols = potential_inputs # get the class values as a pandas Series object class_values = df_onehot[target_col] classes = class_values.unique() # Split targets from inputs ys = df_onehot[target_col] xs = df_onehot[input_cols] # Split data into train and test parts (stratified) x_train, x_test, y_train, y_test = stratified_split(ys, xs, test_part=0.2) x_train = x_train.reset_index(drop=True) y_train = y_train.reset_index(drop=True) # We now want to translate classes to targets, but this depends on our # encoding. For now we will perform a simple encoding from class to integer. # We do this for each of our k data splits targets_train = np.empty(len(y_train)) targets_test = np.empty(len(y_test)) for class_id, class_name in enumerate(classes): is_class_train = (y_train == class_name) is_class_test = (y_test == class_name) targets_train[is_class_train] = class_id targets_test[is_class_test] = class_id # We're going to assume that all our inputs are real numbers (or can be # represented as such), so we'll convert all these columns to a 2d numpy array object inputs_train = x_train.values inputs_test = x_test.values # Split the training data into 5 for cross validation data_split = stratified_split_k_fold(y_train, x_train, 5) targets_train_crossval, inputs_train_crossval = [], [] # We repeat the same step for the cross-validation data for i in range(len(data_split)): y_train = np.empty(len(data_split[i][2])) y_valid = np.empty(len(data_split[i][3])) for class_id, class_name in enumerate(classes): is_class_train = (data_split[i][2] == class_name) is_class_valid = (data_split[i][3] == class_name) y_train[is_class_train] = class_id y_valid[is_class_valid] = class_id targets_train_crossval.append({"train": y_train, "valid": y_valid}) x_train = data_split[i][0].values x_valid = data_split[i][1].values inputs_train_crossval.append({"train": x_train, "valid": x_valid}) return inputs_train_crossval, targets_train_crossval, inputs_train, targets_train, inputs_test, targets_test, \ input_cols, classes def pre_process_bc(df): """ Pre-processing function specific to the breast-cancer dataset. :param df: DataFrame of breast cancer data. :return df_onehot: Processed df with encoded categories and missing values replaced. """ # some values are missing, replace them with mode modes = df.mode() mode_n_caps = modes["node-caps"][0] mode_b_quad = modes["breast-quad"][0] replace_map = {"node-caps": {"?": mode_n_caps}, "breast-quad": {"?": mode_b_quad}, "class": {"no-recurrence-events": 0, "recurrence-events": 1} } df.replace(replace_map, inplace=True) # get the names of the headers headers = df.columns # currently data is categorical, encode the data so models can be applied # columns 1,2,3,4,5,7,8,9 need encoding # different types of encoding for certain cols # ordinal features can used number encoding (cols: 1, 3, 4) # non-ordinal features with more than 2 categories -> one-hot (cols: 2, 8) # non-ordinal features with 2 categories -> binary (cols: 5, 7, 9) # encoding with numbers automatically makes binary columns, so binary encoding and number encoding can be done # together headers_to_encode = headers[[1, 3, 4, 5, 7, 9]] for header in headers_to_encode: df[header] = df[header].astype("category") df[header] = df[header].cat.codes # encoding columns 2 (menopause) and 8 (breast-quad) to make one-hot vectors df_onehot = df.copy() df_onehot = pd.get_dummies(df_onehot, columns=['menopause', 'breast-quad'], prefix=['menopause', 'breast-quad']) return df_onehot def stratified_split(y, x, test_part=0.2): """ :param y: A pandas Series of target values. Assumes two classes, encoded as 0 and 1. :param x: A pandas DataFrame of input values. :param test_part: A float representing the percentage of data which should be used as test data (default 20%). :return : y and x split into train and test parts. """ # Perform split on the two classes separately, due to class imbalance class0 = y[y == 0] class1 = y[y == 1] # Arrange and shuffle dataset (within each class) index_array_c0 = class0.index.values index_array_c1 = class1.index.values np.random.shuffle(index_array_c0) np.random.shuffle(index_array_c1) # Within each class, split dataset into two parts determined by the test_part param idx_test_class0, idx_train_class0 = np.array_split(index_array_c0, [int(test_part * len(index_array_c0))]) idx_test_class1, idx_train_class1 = np.array_split(index_array_c1, [int(test_part * len(index_array_c1))]) # Merge back into single array idx_test = np.concatenate((idx_test_class0, idx_test_class1)) idx_train = np.concatenate((idx_train_class0, idx_train_class1)) # Get the x_train and x_test using the indices x_test = x.iloc[idx_test] x_train = x.iloc[idx_train] # Same for y y_test = y.iloc[idx_test] y_train = y.iloc[idx_train] return x_train, x_test, y_train, y_test def stratified_split_k_fold(y, x, k=5): """ Given inputs and targets, splits them into k folds in a stratified manner. :param y: A pandas Series of target values. Assumes two classes, encoded as 0 and 1. :param x: A pandas DataFrame of input values. :param k: An integer representing the number of folds to split the data in. :return data_split: A list containing k sub-lists, each having 4 arrays of train and test inputs, and train and test targets. """ data_split = [] # Perform k-fold split on the two classes separately, due to class imbalance class0 = y[y == 0] class1 = y[y == 1] # Arrange and shuffle dataset (within each class) index_array_c0 = class0.index.values index_array_c1 = class1.index.values np.random.shuffle(index_array_c0) np.random.shuffle(index_array_c1) # Split dataset into k near-equal parts (test parts) within each class, then merge back into single array test_idx_split_0 = np.array_split(index_array_c0, k) test_idx_split_1 = np.array_split(index_array_c1, k) test_idx_split = [np.concatenate((test_idx_split_0[i], test_idx_split_1[i])) for i in range(k)] # For each part of the above split, use it as a holdout for array in test_idx_split: # Test part is the array of indexes x_test = x.iloc[array] # Train part is all other indexes x_test_idx = x.index.isin(array) x_train = x.iloc[~x_test_idx] # Same for y y_test = y.iloc[array] y_test_idx = y.index.isin(array) y_train = y.iloc[~y_test_idx] data_split.append([x_train, x_test, y_train, y_test]) return data_split
Fahrenheit = float(input("Quantos graus Fahrenheit: ")) Celsius = (Fahrenheit - 32) / 9 print(Fahrenheit, " graus Fahrenheit são iguais a ", Celsius, " graus celsius")
# -*- coding: utf-8 -*- """ Created on Sun Jul 5 19:31:21 2020 @author: Christoffer """ import os import json def remove(listobj): cnt = 0 objectList = [] for elements in listobj: if elements == " {\n": objectList.append(cnt) if elements == " },\n" or elements == " }\n": objectList.append(cnt) cnt = cnt + 1 return(objectList) def replace(listobj): #listobj = [element.replace('=', ':') for element in listobj] listobj = [element.strip() for element in listobj] return(listobj) def dictify(listobj): newDict = {} lastKey = '' concValue = '' closingBracket = True cnt = 0 cnt2 = 0 tmpArray = [] tmpDict = {} separator = 0 # for elements in listobj: # #print(elements) # if elements.find('=') > 0 and closingBracket == True: # #print("1") # separator = elements.find('=') # key = elements[0:separator] # value = elements[separator+1:len(elements)] # newDict[key] = value # lastKey = key # concValue = '' # cnt = 0 # elif elements.find('{') >= 0 and cnt2 > 0: # #print('2') # closingBracket = False # cnt = cnt + 1 # concValue = concValue + elements + '\n' # elif elements.find('}') >= 0: # #print('3') # cnt = cnt -1 # if cnt == 0: # closingBracket = True # concValue = concValue + elements + '\n' # #print(concValue) # #print(lastKey) # newDict[lastKey] = concValue # else: # #print("4") # concValue = concValue + elements + '\n' # #print(concValue) # cnt2 = cnt2 + 1 for x in range(len(listobj)): if x > 0: #Checks if the value is another table if listobj[x] == '{': print('trigg') print(x) tmpArray = [] tmpDict = {} closingBracket = False for y in range(x +1, len(listobj)): if listobj[y] == '}' or listobj[y] == '},': print('break: ' + str(y)) print(listobj[y]) break else: #print('append: ' + str(y)) #print(listobj[y]) tmpArray.append(listobj[y]) print(tmpArray) #newDict[lastKey] = dictify(tmpArray) closingBracket = True continue #Checks if the line is a "normal" key/value pair, no nested tables elif listobj[x].find('=') > 0 and not (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0): separator = listobj[x].find('=') key = listobj[x][0:separator] value = listobj[x][separator+1:len(listobj[x])] newDict[key] = value lastKey = key concValue = '' cnt = 0 #Checks if the line is a nested table elif listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0: #{ size = 64, filename = "__base__/graphics/icons/mip/coal.png", scale = 0.25, mipmap_count = 4 }, #['{ size = 64', ' filename = "__base__/graphics/icons/mip/coal-1.png"', ' scale = 0.25', ' mipmap_count = 4 }', ''] #print('test3') #newDict = {} tmpArray = [] tmpArray = listobj[x].split(',') tmpArray = [element.replace('{', '') for element in listobj] tmpArray = [element.replace('}', '') for element in listobj] #newDict[lastKey] = dictify(tmpArray) #print(tmpArray) separator = listobj[x].find('=') key = listobj[x][0:separator] value = listobj[x][separator+1:len(listobj[x])] elif listobj[x].find('=') > 0 and not (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0): print('trigg???') separator = listobj[x].find('=') key = listobj[x][0:separator] value = listobj[x][separator+1:len(listobj[x])] newDict[key] = value lastKey = key concValue = '' cnt = 0 elif (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0): print('test') return(newDict) def removeExtend(listobj): if listobj[0] == 'data:extend(\n': listLen = len(listobj) listobj.pop(listLen-1) listobj.pop(listLen-2) listobj.pop(0) listobj.pop(0) return(listobj) def writeDictToLuaFile(listobj): file_name = r"C:\Users\Christoffer\Documents\test2.lua" file = open(file_name, 'w') file.write('data:extend(\n') file.write('{\n') listLen = len(listobj) for x in range(listLen): file.write(' {\n') for key, value in listobj[x].items(): #print(value) file.write(' ' + key + '=' + value + '\n') if x >= (listLen-1): file.write(' }\n') else: file.write(' },\n') file.write('}\n') file.write(')') path = r"C:\Users\Christoffer\Documents" path = path + r"\demo-turret.lua" file = open(path, 'r') fileLines = file.readlines() file.close() fileLen = len(fileLines) newFile = removeExtend(fileLines) listOfIndexes = remove(newFile) newFile = replace(newFile) elements = len(listOfIndexes) / 2 itemList = [] for i in range(int(elements)): itemList.append(dictify(newFile[listOfIndexes[(i*2)]:listOfIndexes[(i*2)+1]+1])) newlist = newFile[listOfIndexes[0]:listOfIndexes[1]+1] #newDict = dictify(newlist) #writeDictToLuaFile(itemList) #file_name = r"C:\Users\Christoffer\Documents\test2.lua" #file = open(file_name, 'w') # #for line in fileLines: # file.write(line) # # #file.close()
# Convolutional Neural Network from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from keras.preprocessing.image import ImageDataGenerator # Initialising the CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Convolution2D( 32, 3, 3, input_shape=(64, 64, 3), activation='relu')) # Step 2 - Pooling classifier.add(MaxPooling2D(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(Convolution2D(32, 3, 3, activation='relu')) classifier.add(MaxPooling2D(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection classifier.add(Dense(output_dim=128, activation='relu')) classifier.add(Dense(output_dim=1, activation='sigmoid')) # Compiling the CNN classifier.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Fitting the CNN to the images train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) training_set = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary') test_datagen = ImageDataGenerator(rescale=1./255) test_set = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary') classifier.fit_generator( training_set, samples_per_epoch=8000, nb_epoch=25, validation_data=test_set, nb_val_samples=2000)
#Inputting user information argument = True container = [] while argument: x = input("Enter first name:") y = input("Enter last name:") z = input("Enter email:") info = {'first name': x, 'last name': y, 'email': z} #Generating the random password import string import random (string.ascii_letters + string.digits,5) ink = (''.join(random.sample((string.ascii_letters + string.digits)*5,5))) password = ((x[0:2] + y[-2:]) + ink) #Total output password_loop = True while password_loop: #Get user details print(info) #Show generated password print("Your password is : "+ str(password)) #Ask if he would like to continue password_like = input("Do you like the generated password? \n If Yes, Enter 'Yes' \n If No, Enter 'No' and supply:") if password_like == "yes": print(password) break #Password_like == "no" else: password = input("Enter password longer than 7 character:") #password length loop if len(password) >=7: print(password) break while True: if len(password) < 7: print("Your password is lower than seven(7)") password = input("Enter your password to be seven(7) characters and above: ") else: print("Password accepted") break count = 1 new_user = input("Enter new user \n ").upper() if new_user == "NO": argument = False for details in container: print(details) else: argument = True
class LinkedListNode: def __init__(self, value, nextNode = None): self.value = value self.nextNode = nextNode class LinkedList: def __init__(self, head = None): self.head = head def insert(self, value): node = LinkedListNode(value) if self.head is None: self.head = node return currentNode = self.head while True: if currentNode.nextNode is None: currentNode.nextNode = node break currentNode = currentNode.nextNode def printLinkedList(self): currentNode = self.head while currentNode is not None: print(currentNode.value + '->') currentNode = currentNode.nextNode else: print(None) ll = LinkedList() ll.printLinkedList() ll.insert('3') ll.printLinkedList() ll.insert('44') ll.printLinkedList()
from functools import lru_cache @lru_cache(maxsize=10000) def Fibonacci(n): if n == 1: return 1 elif n == 2: return 1 elif n > 2: return Fibonacci(n - 1) + Fibonacci(n - 2) valid = True number = 0 while valid: number += 1 if 10 > Fibonacci(number) / 10 ** 999 > 1: valid = False print(number)
import math def is_prime_num(num): sq = int(math.sqrt(num)) for j in range(2, sq): if num % j == 0: return False return True def if_Pandigital_number(num): l_digits = [] str_num = str(num) c = 0 for digit in str_num: if digit in l_digits: return False else: l_digits.append(int(digit)) l_digits.sort() for digit in l_digits: c += 1 if not digit == c: return False return True counter = 0 start_point = 10 correct_point = start_point while correct_point < 987_654_321: correct_point = start_point if if_Pandigital_number(correct_point) and is_prime_num(correct_point): counter = correct_point start_point += 1 print('largest Pandigital prime below 1,000,000', counter)
#!/usr/bin/python3 #Filename:continue.py while True: s = input("enter something:") if s == "quit": break elif len(s) < 3: print("short") continue print("length is OK") print("loop is over")
#!/usr/bin/python3 #Filename:func_return.py def maximum(x, y): if(x > y): return x else: return y x = int(input("x = ")) y = int(input("y = ")) val = maximum(x, y) print(val)
#!/usr/bin/python3 #Filename:if.py number = 23 guess = int(input("Enter number:")) if(guess == number): print("Congratulation you guess it!") print("(But you can\'t get any prizes)") elif(guess < number): print("it is higher than that") else: print("it is lower than that") print("Done")
#!/usr/bin/python3 #Filename:method.py class Person: def __init__(self, name): self.name = name def sayHi(self): print("Hello %s" %self.name) p = Person('Allen') p.sayHi()
#!/usr/bin/python3 #Filename:expression.py length = 5 breadth = 2 area = length * breadth print("the area is",area) print("perimeter is",2 * (length + breadth))
#The next line of code imports the whole Tkinter module from tkinter import * root = Tk() class robotPosition(): def __init__(self, location): self.label = location location.bind('<ButtonPress-1>', self.StartMove) location.bind('<ButtonRelease-1>', self.StopMove) self.positions = {} def StartMove(self, event): startx = event.x starty = event.y self.positions['start'] = (startx, starty) def StopMove(self, event): stopx = event.x stopy = event.y self.positions['stop'] = (stopx, stopy) # This calculates the distance using the formula def distancetraveled(self): x1 = self.positions['start'][0] x2 = self.positions['stop'][0] y1 = self.positions['start'][1] y2 = self.positions['stop'][1] return ((x2-x1)**2 + (y2-y1)**2)**0.5 location = Canvas(root, width = 300, height = 300) robotPosition(location) location.pack() root.mainloop()
# -*- coding: utf-8 -*- """ Created on Mon May 11 08:11:49 2020 @author: Harshal """ t=int(input()) for i in range(t): n=int(input()) a=n//2 if a%2==1: print("NO") else: print("YES") odd=[] even=[] for i in range(2,n+1,2): even.append(i) for i in range(1,n-1,2): odd.append(i) odd.append(odd[-1]+2+len(even)) for i in even+odd: print(i,end=" ")
import sqlite3 class Money(): def __init__(self): self.connection = sqlite3.connection(users.db) self.cursor = self.connection.cursor() def get_account(self): query = "SELECT * FROM users WHERE account_number = {}".format(account_number) self.cursor.execute(query) money = self.cursor.fetchall() return money