blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
86dc3ac8a4043b92be47954fb561d0da0efbed0d
mchalela/lensing
/gentools/distance.py
7,248
3.609375
4
import os import numpy as np import scipy.sparse from astropy.cosmology import FLRW def sphere_angular_separation(lon1, lat1, lon2, lat2): ''' Angular separation between two points on a sphere Parameters ---------- lon1, lat1, lon2, lat2 : Angle, Quantity or float Longitude and latitude of the two points. Quantities should be in angular units; floats in radians Returns ------- angular separation : Quantity or float Type depends on input; Quantity in angular units, or float in radians Notes ----- The angular separation is calculated using the Vincenty formula [1], which is slightly more complex and computationally expensive than some alternatives, but is stable at at all distances, including the poles and antipodes. [1] http://en.wikipedia.org/wiki/Great-circle_distance ''' sdlon = np.sin(lon2 - lon1) cdlon = np.cos(lon2 - lon1) slat1 = np.sin(lat1) slat2 = np.sin(lat2) clat1 = np.cos(lat1) clat2 = np.cos(lat2) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon denominator = slat1 * slat2 + clat1 * clat2 * cdlon sep = np.arctan2(np.sqrt(num1 ** 2 + num2 ** 2), denominator) return sep def sphere_angular_vector(ra, dec, ra_center, dec_center, units='rad'): ''' Angular separation and orientation between two points on a sphere. Orientation is meassured from declination axis clockwise. Parameters ---------- ra, dec, ra_center, dec_center : Angle, Quantity or float Right ascension and declination of the two points. units : String indicating ra and dec units. Options are: 'rad', 'deg'. Default: 'rad'. Returns ------- distance, orientation : Quantity or float Polar vector on the sphere in units defined by 'units'. ''' if units not in ['rad', 'deg']: raise ValueError('Argument units="{}" not recognized. ' 'Options are: "rad", "deg".'.format(units)) if units == 'deg': ra, dec = np.deg2rad(ra), np.deg2rad(dec) ra_center, dec_center = np.deg2rad(ra_center), np.deg2rad(dec_center) #center all points in ra ra_prime = ra-ra_center ra_center = 0 #convert to positive values of RA negative = (ra_prime<0) ra_prime[negative] += 2*np.pi #define wich quadrant is each point Q1 = (ra_prime<np.pi) & (dec-dec_center>0) Q2 = (ra_prime<np.pi) & (dec-dec_center<0) Q3 = (ra_prime>np.pi) & (dec-dec_center<0) Q4 = (ra_prime>np.pi) & (dec-dec_center>0) #Calculate the distance between the center and object, and the azimuthal angle dist = sphere_angular_separation(ra_prime, dec, ra_center, dec_center) #build a triangle to calculate the spherical cosine law x = sphere_angular_separation(ra_center, dec, ra_center, dec_center) y = sphere_angular_separation(ra_prime, dec, ra_center, dec) #Apply shperical cosine law cos_theta = (np.cos(y) - np.cos(x)*np.cos(dist))/(np.sin(x)*np.sin(dist)) #Round cosines that went over because of rounding errors round_high = (cos_theta > 1) round_low = (cos_theta < -1) cos_theta[round_high] = 1 cos_theta[round_low] = -1 theta = np.arccos(cos_theta) #Correct the angle for quadrant (because the above law calculates the acute angle between the "horizontal-RA" direction #and the angular separation great circle between the center and the object #theta[Q1] = theta[Q1] # First quadrant remains the same theta[Q2] = np.pi - theta[Q2] theta[Q3] = np.pi + theta[Q3] theta[Q4] = 2*np.pi - theta[Q4] if units == 'deg': dist, theta = np.rad2deg(dist), np.rad2deg(theta) return dist, theta def _precompute_lensing_distances(zl_max, zs_max, dz=0.0005, cosmo=None): '''Precompute lensing distances DL, DS, DLS and save to a file Parameters ---------- zl_max, zs_max : float Maximum redshift to wich the distances will be computed dz : float Redshift step cosmo: cosmology instance of astropy.cosmology.FLRW, like Planck15 or LambdaCDM. Returns ------- file : string Filename where the sparse matrix was saved. The format is 'PrecomputedDistances_dz_{}.npz'.format(dz) ''' if not isinstance(cosmo, FLRW): raise TypeError, 'cosmo is not an instance of astropy.cosmology.FLRW' zl = np.arange(0., zl_max+dz, dz) zs = np.arange(0., zs_max+dz, dz) B = scipy.sparse.lil_matrix((len(zl), len(zs)), dtype=np.float64) for i in xrange(len(zl)): B[i, i:] = cosmo.angular_diameter_distance_z1z2(zl[i], zs[i:]).value path = os.path.dirname(os.path.abspath(__file__))+'/' filename = 'PrecomputedDistances_dz_{}.npz'.format(dz) scipy.sparse.save_npz(path+filename, scipy.sparse.csc_matrix(B)) return path+filename #----------------------------------------------------------------------- # Recuperamos los datos def compute_lensing_distances(zl, zs, precomputed=False, dz=0.0005, cosmo=None): ''' Compute lensing Angular diameter distances. Parameters ---------- zl, zs : array, float Redshift of the lens and the source. precomputed : bool If False the true distances are computed. If False the distances will be interpolated from a precomputed file. dz : float step of the precomputed distances file. If precomputed is True, this value will be used to open the file: 'PrecomputedDistances_dz_{}.npz' cosmo: cosmology instance of astropy.cosmology.FLRW, like Planck15 or LambdaCDM. Returns ------- DL, DS, DLS : array, float Angular diameter distances. DL: dist. to the lens, DS: dist. to the source, DLS: dist. from lens to source. ''' if not precomputed: if not isinstance(cosmo, FLRW): raise TypeError, 'cosmo is not an instance of astropy.cosmology.FLRW' DL = cosmo.angular_diameter_distance(zl).value DS = cosmo.angular_diameter_distance(zs).value DLS = cosmo.angular_diameter_distance_z1z2(zl, zs).value else: path = os.path.dirname(os.path.abspath(__file__))+'/' H = scipy.sparse.load_npz(path+'PrecomputedDistances_dz_{}.npz'.format(dz)).todense() H = np.asarray(H) Delta_z = dz zl_big = zl/Delta_z zs_big = zs/Delta_z zl_idx = zl_big.astype(np.int32) zs_idx = zs_big.astype(np.int32) zl1_frac = (zl_big - zl_idx)*Delta_z zs1_frac = (zs_big - zs_idx)*Delta_z zl2_frac = (zl_idx+1 - zl_big)*Delta_z zs2_frac = (zs_idx+1 - zs_big)*Delta_z # Lineal interpolation for DL and DS DL = (H[0, zl_idx]*zl2_frac + H[0, zl_idx+1]*zl1_frac) / Delta_z DS = (H[0, zs_idx]*zs2_frac + H[0, zs_idx+1]*zs1_frac) / Delta_z # Bilineal interpolation for DLS A = H[zl_idx, zs_idx]*zl2_frac*zs2_frac B = H[zl_idx+1, zs_idx]*zl1_frac*zs2_frac C = H[zl_idx, zs_idx+1]*zl2_frac*zs1_frac D = H[zl_idx+1, zs_idx+1]*zl1_frac*zs1_frac DLS = (A + B + C + D) / Delta_z**2 return [DL, DS, DLS]
5b6c10ced0e43f45bfb4ec8734dead06be7de988
Pallav277/Python_Turtle_Graphics
/Smiley.py
834
3.703125
4
# importing turtle module import turtle turtle.bgcolor('black') smiley = turtle.Turtle() # function for creation of eye def eye(col, rad): smiley.down() smiley.fillcolor(col) smiley.begin_fill() smiley.circle(rad) smiley.end_fill() smiley.up() # draw face smiley.width(4) smiley.fillcolor('yellow') smiley.begin_fill() smiley.circle(100) smiley.end_fill() smiley.up() # draw eyes smiley.goto(-40, 120) eye('white', 15) smiley.goto(-37, 130) eye('black', 5) smiley.goto(40, 120) eye('white', 15) smiley.goto(37, 130) eye('black', 5) # draw mouth smiley.goto(-40, 85) smiley.down() smiley.right(90) smiley.circle(40, 180) smiley.up() # draw tongue smiley.goto(-10, 45) smiley.down() smiley.right(180) smiley.fillcolor('red') smiley.begin_fill() smiley.circle(10, 180) smiley.end_fill() smiley.hideturtle()
ef13c2bfcd1fa62ff80fdea426b2b7573fbf2190
jigglypuff27/MSI
/Python/Dictionary.py
506
4.1875
4
#Dictionary x= {'morning':'wake','evening':'snack','noon':'lunch','night':'dinner'} print(x) #O/P{'morning': 'wake', 'evening': 'snack', 'noon': 'lunch', 'night': 'dinner'} for k,v in x.items(): print(f'{k}:{v}') # morning:wake # evening:snack # noon:lunch # night:dinner for k in x.keys(): print(k) #all the keys for v in x.values(): print(v) #all the values print(x['morning']) #output wake x['morning']='wakeup' x['midnoon']='sleep2' print('morning' in x)
be5eb2aad7659740cd0225d8537f6093906e4118
jasmineve/lpthw
/ex6.py
757
4.625
5
# This assigns a string with formatted variables to the variable x x = "There are %d types of people." % 10 # This assigns a string to variable called 'binary' binary = "binary" # This assigns a string to the variable 'do_not' do_not = "don't" # The right side is a string with two formatters, the left side is variable y y = "Those who know %s and those who %s." % (binary, do_not) print x print y # notice how a single sentence can be a formatted variable as well. print "I said: %r." % x # notice the difference between %r and %s print "I also said: '%s'." % y hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." print w + " " +e
37880f32e0d26b6337a564558d074e0544734080
geekcoderr/python_algorithms
/algo_armstrong_number.py
494
4.3125
4
#Take input from user.. >> tke=(input("Enter the number to check whether it's an Armstrong number or not :: ")) sumof=0 temp=tke leng=len(tke) tke=list(tke) #Loop will start to compute power of number with length.. >> for i in range(0,leng): tke[i]=int(tke[i]) sumof+=tke[i]**leng #Print answer to user if number is armstrong or not.. >> if sumof==int(temp): print("YES ! (",temp,") is an Armstrong Number !") else: print("NO ! (",temp,") is not an Armstrong Number !") exit(0)
56f9b67fb814e65f3573000a1c6ee8c05606c49f
ewdurbin/opstacle
/opstacle/util.py
842
3.5
4
import datetime import collections import threading class ExpireCounter: """Tracks how many events were added in the preceding time period """ def __init__(self, timeout=1): self.lock=threading.Lock() self.timeout = timeout self.events = collections.deque() def add(self,item): """Add event time """ with self.lock: self.events.append(item) threading.Timer(self.timeout,self.expire).start() def __len__(self): """Return number of active events """ with self.lock: return len(self.events) def expire(self): """Remove any expired events """ with self.lock: self.events.popleft() def __str__(self): with self.lock: return str(self.events)
0944aea35f32894abe6ed80d2d26881a3758aa5f
tfinlay/pywinterm
/pywinterm/display/util.py
2,935
3.53125
4
""" Display utilities """ import os def clear_window(): """ Clears the screen :return: None """ os.system("cls") def render_chars(arr): """ Prints every character to the terminal window :param arr: iter<String>, each String is a line in the terminal :return: None """ for row in arr: print(arr) def set_window_title(title): """ Set the window title :param title: String :return: None """ os.system("TITLE {}".format(title)) def resize_window(width, height): """ Resize the terminal window :param width: width of the terminal (chars) :param height: height of the terminal (rows) :return: None """ os.system("mode con: cols={} lines={}".format(width, height)) def flatten_root(root): """ DEPRECATED: Merged into RootDisplay Merges displays into one list of strings for outputting :param root: Display, the root display :return: list<list<char>> """ print("WARNING: pywinterm.display.util.flatten_root() is deprecated, please use the built in pywinterm.display.RootDisplay.flatten() method instead") screen = [[" " for i in range(root.width)] for x in range(root.height)] # pre-generate the matrix """ for l in range(len(root.text)): # render the text line = list(root.text[l]) for i in range(len(line)): screen[l].insert(i, line[i]) """ def flatten_display(display, x=0, y=0): """ Merges displays into one list of strings for outputting :param display: Display, the display we're merging :param x: int, total x indent of parent :param y: int, total y indent of parent :return: None """ y_total = display.y + y x_total = display.x + x for l in range(len(display.text)): # render the text # decide on how many spaces to leave before the text (to handle alignment) indent = 0 if isinstance(display.text[l], Label): #if display.text[l].text_alignment == 0: # left alignment if display.text[l].text_alignment == 1: # centre alignment indent = (display.width // 2) - (len(display.text[l]) // 2) elif display.text[l].text_alignment == 2: # right alignment indent = display.width - len(display.text[l]) for i in range(len(display.text[l])): #print("screen[{}][{}] = {}".format(l + y_total, i + x_total + indent, display.text[l][i])) screen[l + y_total][i + x_total + indent] = display.text[l][i] for disp in display.children: # repeat for all of the children, and the children's children etc. flatten_display(disp, x_total, y_total) flatten_display(root) # begin the flattening of displays return screen
36dfa78a6e2f12784c58248a08897d9dec865e2a
SergioHerreroSanz/dam2d17
/Sistemas_de_Gestión_Empresarial/P3_Python/PythonApplication6/Ej09_POO.py
3,051
3.921875
4
# -*- coding: utf-8 -*- ''' 8 PDO ''' class Mueble: # el primer registro siempre self en todos def __init__(self, tipo): # constructor self.tipo = tipo # Propiedad publica def getTipo(self): # Metodo getter return self.tipo def setTipo(self, tipo): self.tipo = tipo # Llamamos al constructor pero no usamos self en ningun momento a llamar mu = Mueble(3) print("Mueble(3)") print("El tipo es (metodo): ", mu.getTipo()) print("El tipo es (propiedad):", mu.tipo) print(" # HERENCIA") class Mesa(Mueble): # metemos las clases padre dentro de parentesis y separadas por comas, def __init__(self, tipo, color): # Llamamos al padre para inicalizar, tipo proviene de padre, con lo cual no lo tengo declarado desde mi metodo self.color = color # Nuestra propiedad, si pertenece a Mesa Mueble.__init__(self, tipo) self.color = color # nuestra propiedad si pertenece a la mesa def getColor(self): # nuestros metodos return self.color def setColor(self, color): self.color = color ms = Mesa(5, 7) print("Mesa(5,7)") print("El tipo es: ", ms.getTipo()) # metodo del padre print("El color es: ", ms.getColor()) # metodo mio print("# sobreescritura de metodos") class Mesa2(Mueble): def __init__(self, tipo, color): Mueble.__init__(self, tipo) self.color = color def getColor(self): return self.color def setColor(self, color): self.color = color def getTipo(self): # Sobre escribimos al padre, como existe en nuestra clase usara nuestro metodo en lugar del del padre return self.tipo + 1 ms2 = Mesa2(5, 7) print("Mesa2(5,7)") print("El tipo es: ", ms2.getTipo()) print("EL color es: ", ms2.getColor()) print("#no existe nada privado") class UnaPrivada: def __init__(self): self.__Privada = 1 # Supuesta variable privada self.Publica = 2 pr = UnaPrivada() print("Publica; ", pr.Publica) # Pese a ser privada podemos accedder a ella, es obligatorio el primer_, es obligatorio que la variable privada tenga dos __, sino el analizador sintactiva va a cantar print("Privada: ", pr._UnaPrivada__Privada) # Propiedades class Propiedades: def __init__(self, dia): self.__d = dia # propiedad __d que almacenara el valor privado self.diaPublica = dia def __getDia(self): return self.__d def __getDiaPublico(self): return self.diaPublica def __setDia(self, dia): self.__d = dia self.diaPublica = dia dia = property(__getDia, __setDia) # Propiedad dia creada # Propiedad diaPublica creada diaPublico = property(__getDiaPublico, __setDia) # redundante, ya hemos creado como publica en el constructor self.diaPublica = dia, pero para ver # que es posible de ambas formas d = Propiedades(3) print("Dia antes", d.dia) print("Dia Publica", d.diaPublica) # desde constructor print("Dia Publico", d.diaPublico) # desde property d.dia = 7 print("Dia Despues", d.dia) # nueva propiedad
5809cde51f5b406f4e674e3546879573bf8953f2
Anekjain/Programming-Solution
/misc/Hartals.py
696
3.796875
4
#!/usr/bin/env python def hartalCount(p,d): hartal_days = [] for j in p: for i in range(d): i += 1 if(i % j == 0 ): hartal_days.append(i) if(i%7 == 6 or i%7 == 0): #REMOVING HARTALS ON SATURDAY AND SUNDAY hartal_days.pop() #REMOVING DUPLICATES OF MULTIPLES [ex: 2,3 both have multiple 6] hartal_days = list(dict.fromkeys(hartal_days)) return hartal_days if __name__ == "__main__": hartal_parameters =[3,4,8] hartal_parameters = list(dict.fromkeys(hartal_parameters)) #REMOVING DUPLICATES Days = 14 Lost_Days = hartalCount(hartal_parameters, Days) print(len(Lost_Days))
b424e6dc098239cfd125327cf5776df789820264
Priyadharshinii/begginnerr
/armstrong.py
209
3.640625
4
r1=input("enter lower range") r2=input("enter higher range") for num in range(r1,r2+1): sum=0 temp=num o=len(str(num)) while temp>0: r=temp%10 sum+=r**o temp//=10 if num==sum: print(num)
ed5f150b6847a6214535b561c83ae4b973499ec3
DT211C-2019/programming
/Year 2/Paul Geoghegan/S1/Labs/Lab7/l7q3.py
335
4.3125
4
#Assignes value for string str = "Monty Python" #Sets value for length length = 0 #Prints first character print("The first character is", str[0]) #Prints last character print("The last character is", str[11]) #Prints the last character using len print("The last character using len() is", str[len(str)-1]) #Prints Monty print(str[:5])
5fbdc1a74e32256094162a91bd4c9bc92e9d1cbc
Rajahx366/Codewars_challenges
/5kyu_Josephus_Permutation.py
1,996
3.75
4
""" This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege. Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act). Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea. You are now to create a function that returns a Josephus permutation, taking as parameters the initial array/list of items to be permuted as if they were in a circle and counted out every k places until none remained. Tips and notes: it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1. For example, with n=7 and k=3 josephus(7,3) should act this way. [1,2,3,4,5,6,7] - initial sequence [1,2,4,5,6,7] => 3 is counted out and goes into the result [3] [1,2,4,5,7] => 6 is counted out and goes into the result [3,6] [1,4,5,7] => 2 is counted out and goes into the result [3,6,2] [1,4,5] => 7 is counted out and goes into the result [3,6,2,7] [1,4] => 5 is counted out and goes into the result [3,6,2,7,5] [4] => 1 is counted out and goes into the result [3,6,2,7,5,1] [] => 4 is counted out and goes into the result [3,6,2,7,5,1,4] So our final result is: josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4] For more info, browse the Josephus Permutation page on wikipedia; related kata: Josephus Survivor. Also, live game demo by OmniZoetrope. """ def josephus(items,k): ans = [] pos = k - 1 while len(items) > 0: print(pos) if pos > len(items) - 1: pos = pos % len(items) ans.append(items.pop(pos)) print(items) pos += k - 1 return ans
a7cb3d4381202069ba4a304887e7df5e955d44c1
Folkert94/Advent_of_Code_2020
/day_3/day_3.py
668
3.65625
4
def get_numbers(input_file): numbers = [] with open(input_file, 'r') as input: for line in input: temp = line.strip() numbers.append(temp) return numbers field = get_numbers("input.txt") def count_trees(slope): p, q = slope i = 0 j = 0 count = 0 while i < len(field): if field[i][j] == '#': count += 1 i += p if q == 1: j = (j + q) % len(field[0]) else: j = (i * q) % len(field[0]) return count result = count_trees((1, 1)) * count_trees((1, 3)) * count_trees((1, 5)) * count_trees((1, 7)) * count_trees((2, 1)) print(result)
d8c2dd8ba2fbbc26f3010fbae473b9512decfd55
benpry/resource-rational-goal-pursuit
/code/main/linear_quadratic_regulator.py
13,353
3.671875
4
""" Code for the optimal (LQR) model and the sparse attention (sparse LQR) model. """ import torch import numpy as np from Microworld_experiment import Microworld class OptimalAgent: """ An agent that uses a linear quadratic regulator to pursue a goal A: endogenous transition matrix B: exogenous input matrix endogenous: the current endogenous state of the system Q: the cost matrix for each endogenous state Qf: the cost of the final endogenous state R: the cost of the exogenous inputs """ A: torch.Tensor B: torch.Tensor endogenous: torch.Tensor Q: torch.Tensor Qf: torch.Tensor R: torch.Tensor T: int def __init__(self, A, B, Q, Qf, R, T, init_endogenous): """ Initialize this agent. A: endogenous transition matrix B: exogenous input matrix init_endogenous: the starting endogenous state for the system Q: the cost matrix for each endogenous state Qf: the cost of the final endogenous state R: the cost of the exogenous inputs """ self.A = A self.B = B self.Q = Q self.Qf = Qf self.R = R self.T = T self.endogenous = init_endogenous def get_actions(self): """ Compute the optimal sequence of actions by backward induction via dynamic programming This uses the dynamic programming algorithm from slide 23 of these slides: https://stanford.edu/class/ee363/lectures/dlqr.pdf """ # n is the number of timesteps the agent has n = self.T # initialize array of P matrices P = [0 for _ in range(n + 1)] # iteratively compute the value matrices P[n] = self.Qf for t in range(n, 0, -1): P[t - 1] = self.Q + torch.mm(torch.mm(self.A.t(), P[t]), self.A) - torch.mm(torch.mm( torch.mm(torch.mm(self.A.t(), P[t]), self.B), (self.R + torch.mm(self.B.t(), torch.mm(P[t], self.B))).inverse()), torch.mm(self.B.t(), torch.mm(P[t], self.A))) # iteratively compute the optimal action matrices K = [] for t in range(n): Kt = -torch.mm((self.R + torch.mm(torch.mm(self.B.t(), P[t+1]), self.B)).inverse(), torch.mm(torch.mm(self.B.t(), P[t+1]), self.A)) K.append(Kt) # compute the list of optimal actions u = [] curr_x = self.endogenous for t in range(n): u.append(torch.mv(K[t], curr_x)) curr_x = torch.mv(self.A, curr_x) + torch.mv(self.B, u[-1]) # returns the optimal sequence of actions return u class SparseLQRAgent: """ An agent that uses a linear quadratic regulator to pursue a goal A: endogenous transition matrix B: exogenous input matrix endogenous: the current endogenous state of the system Q: the cost of the endogenous state Qf: the cost of the final endogenous state R: the cost of the exogenous inputs attention_cost: the attention cost """ A: torch.Tensor B: torch.Tensor endogenous: torch.Tensor Q: torch.Tensor Qf: torch.Tensor R: torch.Tensor T: int def __init__(self, A, B, Q, Qf, R, T, init_endogenous, attention_cost): """ Initialize this agent. A: endogenous transition matrix B: exogenous input matrix init_endogenous: the starting endogenous state for the system Q: the cost matrix for each endogenous state Qf: the cost of the final endogenous state R: the cost of the exogenous inputs """ self.A = A self.B = B self.Q = Q self.Qf = Qf self.R = R self.T = T self.endogenous = init_endogenous self.attention_cost = attention_cost def create_edges(self): """ Create a set of edges representing the system's dynamics :return: :rtype: """ # come up with links between endogenous variables possible_links_a, possible_links_b = [], [] for i in range(len(self.A)): for j in range(len(self.A)): if self.A[i, j] != 0. and i != j: possible_links_a.append(['var_source', i, j]) # come up with links between exogenous and endogenous variables for i in range(len(self.B)): for j in range(4): if self.B[i, j] != 0.: possible_links_b.append(['var_exo', i, j]) all_comb = possible_links_a + possible_links_b return all_comb def create_attention_mv(self, attention_vector): """ Create a representation of a microworld with the specified attention vector endogenous: the initial endogenous state attention_vector: """ # create copies of A and B so certain variables can be ignored A = self.A.clone().detach() B = self.B.clone().detach() # set the variables specified by the attention vector to zero for i in attention_vector: if i[0] == 'var_source': A[i[1], i[2]] = 0. elif i[0] == 'var_exo': B[i[1], i[2]] = 0. # set up a microworld with A and B env = Microworld(A=A, B=B, init=self.endogenous) return env def compute_optimal_sequence(self, microworld): """ Compute the optimal sequence of actions by backward induction via dynamic programming This uses the DP algorithm from slide 23 of these slides: https://stanford.edu/class/ee363/lectures/dlqr.pdf """ # n is the number of timesteps the agent has n = self.T # initialize array of P matrices P = [0 for _ in range(n + 1)] # unpack the matrices and endogenous state of the microworld A = microworld.A B = microworld.B endogenous = microworld.endogenous_state # iteratively compute the value matrices P[n] = self.Qf for t in range(n, 0, -1): P[t - 1] = self.Q + torch.mm(torch.mm(A.t(), P[t]), A) - torch.mm(torch.mm( torch.mm(torch.mm(A.t(), P[t]), B), (self.R + torch.mm(B.t(), torch.mm(P[t], B))).inverse()), torch.mm(B.t(), torch.mm(P[t], A))) # iteratively compute the optimal action matrices K = [] for t in range(n): Kt = -torch.mm((self.R + torch.mm(torch.mm(B.t(), P[t+1]), B)).inverse(), torch.mm(torch.mm(B.t(), P[t+1]), A)) K.append(Kt) # compute the list of optimal actions u = [] curr_x = endogenous for t in range(n): u.append(torch.mv(K[t], curr_x)) curr_x = torch.mv(A, curr_x) + torch.mv(B, u[-1]) # returns the optimal sequence of actions return u def test_attention_vector(self, best_attention_vector, microworld, new_edge=None): """ Test the attention vector specified by "best_attention_vector" with the edge new_edge added best_attention_vector: the best attention vector prior to the new edge being added microworld: the microworld the agent operates in new_edge: the new edge we are considering adding to the representation of the microworld """ # add the new edge to the attention vector if new_edge: best_attention_vector.append(new_edge) test_attention_vector = best_attention_vector[:] endogenous = microworld.endogenous_state # focus on only the parts of the microworld the agent is paying attention to microworld_attention = self.create_attention_mv(test_attention_vector) # compute the sequence of optimal actions action_sequence = self.compute_optimal_sequence(microworld_attention) # simulate a trajectory through the real microworld with the chosen actions for i in range(len(action_sequence)): microworld.step(action_sequence[i]) # get the final state and reset the real microworld final_state = microworld.endogenous_state microworld.endogenous_state = endogenous # compute the full (squared) cost function full_cost = final_state.matmul(self.Qf).dot(final_state)\ + sum([a.matmul(self.R).dot(a) for a in action_sequence]) # compute number of non-zero connections non_zero_connections = microworld_attention.A.flatten() != 0. self_connections = microworld_attention.A.flatten() != 1. # get the number of edges that the agent attends to cost_edges = float(torch.sum(non_zero_connections * self_connections) + torch.sum(microworld_attention.B.flatten() != 0.)) cost = np.sqrt(full_cost) + self.attention_cost * cost_edges # remove the newly-added edge if new_edge: best_attention_vector.pop(-1) return action_sequence, cost def find_best_attention_vector_of_size_k(self, best_attention_vector, list_of_edges, microworld): """ Find the best attention vector of size k. I.e. if you can only pay attention to k relationships, which should they be? best_attention_vector: the best of the previously-computed attention vectors list_of_edges: a list of all the edges that could be attended to microworld: the microworld in which the agent operates """ performance_all_new_edges, all_exogenous = [], [] # keep trying to add an edge and see how it affects the performance for new_edge in list_of_edges: # test the resulting attention vector action_sequence, cost = self.test_attention_vector(best_attention_vector, microworld, new_edge=new_edge) # add the performance and action to the list of existing states and actions performance_all_new_edges.append(cost) all_exogenous.append(action_sequence) # get the best edge, performance, and attention vector best_edge = np.nanargmin(performance_all_new_edges) best_edge_performance = np.nanmin(performance_all_new_edges) # add the best-performing edge to the attention vector and remove it from the list of edges best_attention_vector.append(list_of_edges[best_edge]) list_of_edges.pop(best_edge) # select the exogenous actions corresponding to the best edge best_exogenous = all_exogenous[best_edge] return best_attention_vector, best_edge_performance, list_of_edges, best_exogenous def choose_opt_attention_vector(self): """ get the best attention vector in the microworld """ list_of_edges = self.create_edges() best_all_sizes, best_all_sizes_performance, best_exogenous_all_sizes = [], [], [] best_attention_vector = [] microworld = Microworld(A=self.A, B=self.B, init=self.endogenous) for i, attention_vector_size in enumerate(range(len(list_of_edges) + 1)): if attention_vector_size == 0: # test the attention vector that attends to everything best_exogenous, performance = self.test_attention_vector([], microworld) performance = performance.item() else: # get the best attention vector with size i, along with its performance, edges, etc. best_attention_vector, performance, list_of_edges, best_exogenous = \ self.find_best_attention_vector_of_size_k(best_attention_vector, list_of_edges, microworld) # deepcopy best_all_sizes.append(best_attention_vector[:]) best_all_sizes_performance.append(performance) best_exogenous_all_sizes.append(best_exogenous) choice = np.nanargmin(best_all_sizes_performance) exogenous = best_exogenous_all_sizes[choice] return choice, exogenous def get_actions(self): """ compute the optimial action sequence """ best_attention_vector, best_action_sequence = self.choose_opt_attention_vector() return best_action_sequence if __name__ == "__main__": # test case computing the optimal action sequence with the sparse LQR agent. A = torch.tensor([[1., 0., 0., 0., 0.], [0., 1., 0., 0., -0.5], [0., 0., 1., 0., -0.5], [0.1, -0.1, 0.1, 1., 0.], [0., 0., 0., 0., 1.]]) B = torch.tensor([[0., 0., 2., 0.], [5., 0., 0., 0.], [3., 0., 5., 0.], [0., 0., 0., 2.], [0., 10., 0., 0.]]) init_endogenous = torch.tensor([200., 20., 100., 50., -10.]) Q = torch.tensor([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) Qf = torch.tensor([[15., 0., 0., 0., 0.], [0., 15., 0., 0., 0.], [0., 0., 15., 0., 0.], [0., 0., 0., 15., 0.], [0., 0., 0., 0., 15.]]) R = 0.01 * torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1]]) T = 10 attention_cost = 300. test_agent = SparseLQRAgent(A, B, Q, Qf, R, T, init_endogenous, attention_cost) opt_u = test_agent.get_actions() print(f"opt_u: {opt_u}")
057aa0c021e5b31f5ecdf694f54f53c371a8cbc1
IPFactory/WelcomeCTF2021
/ppc/revival/solve.py
357
3.8125
4
def Fib(n, memo): if n == 1: return 0 elif n == 2: return 1 elif n in memo: return memo[n] else: memo[n] = Fib(n-1, memo) + Fib(n-2, memo) return memo[n] N = 3 memo = {} while True: if Fib(N,memo) >= 31271819149290786098591076778525667781144930000000: print(N) exit() N += 1
1a94816747a23effd6e3cc120ad9b62db4113e4d
flothesof/advent_of_code2019
/puzzle05.py
4,448
3.53125
4
def run(program, input_value): index = 0 prints = [] while True: instruction = program[index] op_str = f"{instruction:05}" # pad with zeros if necessary op = op_str[-2:] A, B, C = op_str[0], op_str[1], op_str[2] jump = False # add if op == '01': nincrement = 4 if C == '0': first = program[program[index + 1]] else: first = program[index + 1] if B == '0': second = program[program[index + 2]] else: second = program[index + 2] assert A == '0' program[program[index + 3]] = first + second # multiply elif op == '02': nincrement = 4 if C == '0': # position first = program[program[index + 1]] else: # immediate first = program[index + 1] if B == '0': second = program[program[index + 2]] else: second = program[index + 2] assert A == '0' program[program[index + 3]] = first * second # input saved to address elif op == '03': nincrement = 2 assert C == '0' addr = program[index + 1] program[addr] = input_value # output elif op == '04': nincrement = 2 if C == '0': addr = program[index + 1] else: addr = index + 1 prints.append(program[addr]) # jump if true elif op == '05': if C == '0': first_param = program[program[index + 1]] else: first_param = program[index + 1] if B == '0': second_param = program[program[index + 2]] else: second_param = program[index + 2] if first_param != 0: jump = True new_index = second_param else: nincrement = 3 # jump if false elif op == '06': if C == '0': first_param = program[program[index + 1]] else: first_param = program[index + 1] if B == '0': second_param = program[program[index + 2]] else: second_param = program[index + 2] if first_param == 0: jump = True new_index = second_param else: nincrement = 3 # less than elif op == '07': nincrement = 4 if C == '0': first = program[program[index + 1]] else: first = program[index + 1] if B == '0': second = program[program[index + 2]] else: second = program[index + 2] assert A == '0' if first < second: # strict? program[program[index + 3]] = 1 else: program[program[index + 3]] = 0 # equals elif op == '08': nincrement = 4 if C == '0': first = program[program[index + 1]] else: first = program[index + 1] if B == '0': second = program[program[index + 2]] else: second = program[index + 2] assert A == '0' if first == second: program[program[index + 3]] = 1 else: program[program[index + 3]] = 0 # end program elif op == '99': break else: raise NotImplementedError() if jump: index = new_index del new_index else: index = index + nincrement del nincrement return program, prints assert run([1002, 4, 3, 4, 33], input_value=1)[0] == [1002, 4, 3, 4, 99] assert run([1101, 100, -1, 4, 0], input_value=1)[0] == [1101, 100, -1, 4, 99] program = list(map(int, open('data/input05').read().split(','))) print(f'solution to part1: {run(program, input_value=1)[1][-1]}') # we need to reload the program since we modify it in place... program = list(map(int, open('data/input05').read().split(','))) print(f'solution to part2: {run(program, input_value=5)[1][-1]}')
5b6f08f5b5f374057e9389ebf4d7b8f8eb40e672
breastroke423/python_challenge
/charenge4.py
4,029
3.578125
4
from bs4 import BeautifulSoup import requests import pandas as pd import openpyxl ''' # ↓用意されたHTML html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ # ↓BeautifulSoupの初期化 soup = BeautifulSoup(html_doc, 'html.parser') # ↓インデントをきれいにして出力 print(soup.prettify()) # 特定のタグだけ指定して抽出 print(soup.title) print(soup.title.string) print(soup.title.getText()) # 普通のタグ指定では最初の一つしか取れない print(soup.a) # 全部取るときはfind_all print(soup.find_all("a")) # 変数に代入してprint testprint = soup.find_all("a") print(testprint[0]) print(len(testprint)) j = 1 while j < 4: for i in testprint: print(str(j)+"."+ i.string) j += 1 # すべてのURLを取ってきて、一行ずつprint testprint2 = soup.find_all("a") for i in testprint2: print(i.get("href")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ↑ここで切り分け↓ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ url = "https://review-of-my-life.blogspot.com/" response = requests.get(url) print(response.text) url = "https://review-of-my-life.blogspot.com/" html_doc = requests.get(url).text soup = BeautifulSoup(html_doc, 'html.parser') # BeautifulSoupの初期化 print(soup.prettify()) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ↑ここで切り分け↓ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ testprint3 = soup.find_all("a") for i in testprint3: print(i.string) print("↑ここで切り分け↓") for i in testprint3: print(i.get("href")) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ↑ここで切り分け↓ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ url = "https://review-of-my-life.blogspot.com/" html_doc = requests.get(url).text soup = BeautifulSoup(html_doc, 'html.parser') # BeautifulSoupの初期化 result = soup.find_all("h3", {"class": "post-title"}) for i in result: print(i.text) url = "https://review-of-my-life.blogspot.com/" html_doc = requests.get(url).text soup = BeautifulSoup(html_doc, 'html.parser') # BeautifulSoupの初期化 tags = soup.find_all("h3", {"class": "post-title"}) for tag in tags: print (tag.a.string) print (tag.a.get("href")) ''' columns = ["Name", "URL"] df = pd.DataFrame(columns=columns) # print(df) se = pd.Series(['LINEから送った画像を文字起こししてくれるアプリを作るときのメモ①', 'https://review-of-my-life.blogspot.com/2018/03/moji-okosi-1.html'], columns) # 行を作成 df = df.append(se, columns) # データフレームに行を追加 # print(df) df1 = pd.DataFrame(columns=columns) # 列名を指定する# TODO1 以下の表のようになるように、データフレームを作成してください。 se = pd.Series(['データ解析の実務プロセス入門(あんちべ)』を読んで特に学びが多かったこと', 'https://review-of-my-life.blogspot.com/2018/03/moji-okosi-1.html'], columns) # 行を作成 df1 = df1.append(se, columns) # データフレームに行を追加 se = pd.Series(['sqlite3覚書 データベースに接続したり、中身のテーブル確認したり', 'https://review-of-my-life.blogspot.com/2018/04/sqlite3.html'], columns) # 行を作成 df1 = df1.append(se, columns) se = pd.Series(['LINEから送った画像を文字起こししてくれるアプリを作るときのメモ①', ' https://review-of-my-life.blogspot.com/2018/03/moji-okosi-1.html'], columns) # 行を作成 df1 = df1.append(se, columns) print(df1)
b3eb8c6e7a01e8343bd62a14f141ec93ea0b6e20
ShivaliBandi/Automation_scripts_using_python
/WebLauncher.py
1,107
3.609375
4
#Web Launcher import webbrowser import urllib.request #This method is for checking internet connection def Connection_Established(): try: urllib.request.urlopen('http://216.58.192.142',timeout = 5) #print(url) #If we connect with specified url,then return True otherwise throw Exception. return True except Exception as eobj: return False def main(): connect = Connection_Established() if connect: #print(webbrowser.open(url)) prints True #Display url using default browser webbrowser.open("https://www.hackerrank.com/",new = 2) #Open url in a new window of the default browser, if possible, otherwise, open url in the only browser window webbrowser.open_new("https://www.geeksforgeeks.org/") #Open url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new(). webbrowser.open_new_tab("https://leetcode.com/") webbrowser.open("https://www.deccansociety.com/applicantLogin.htm?a=2&b=3&c=1385",new = 0) else: print("There is no internet connection...!") if __name__ == "__main__": main()
bfc5c6bd95f4667a156d61eb892d5521b68a0af8
emblaoye/python-semesteroppgaver
/sem1.py
3,764
3.546875
4
def stigend_eller_synkende(tall1, tall2, tall3): print('Tall nr 1:', tall1) print('Tall nr 2:', tall2) print('Tall nr 3:', tall3) if tall1 < tall2 < tall3: print('Disse talle er stigende') elif tall1 > tall2 > tall3: print('Disse tallene er synkende') else: print('Disse tallene er verken stigende eller synkende') def kortverdi(kort): if kort == 'D': verdi = 'Ruter' elif kort == 'H': verdi = 'Hjerter' elif kort == 'S': verdi = 'Spar' elif kort == 'C': verdi = 'Kløver' return (verdi) def tallverdi(tall): if tall == 'A': verdi = 'Ess' elif tall == '2': verdi = 'To' elif tall == '3': verdi = 'Tre' elif tall == '4': verdi = 'Fire' elif tall == '5': verdi = 'Fem' elif tall == '6': verdi = 'Seks' elif tall == '7': verdi = 'Syv' elif tall == '8': verdi = 'Åtte' elif tall == '9': verdi = 'Ni' elif tall == '10': verdi = 'Ti' elif tall == 'J': verdi = 'Knekt' elif tall == 'Q': verdi = 'Dame' elif tall == 'K': verdi = 'Konge' return (verdi) def korttype(): verdi = input('Hva er kortverdi?: ') tall = input('Hva er tallverdi?: ') print('Kortet sin verdi er', kortverdi(verdi), tallverdi(tall)) def tilNok(verdi, kurs): if kurs == 'EUR': return verdi * 9.68551 elif kurs == 'USD': return verdi * 8.50373 elif kurs == 'GBP': return verdi * 0.92950 elif kurs == 'AUD': return verdi * 6.06501 elif kurs == 'NOK': return verdi def fraNok(verdi, kurs): if kurs == 'EUR': return verdi / 9.68551 elif kurs == 'USD': return verdi / 8.50373 elif kurs == 'GBP': return verdi / 0.92950 elif kurs == 'AUD': return verdi / 6.06501 elif kurs == 'NOK': return verdi def valutakalkulator(): fraValuta = input('Hvilken valuta ønsker du å konvertere fra?: ') tilValuta = input('Hvilken valuta ønsker du å konvertere til?: ') verdi = float(input('Hvilken verdi ønsker du å konvertere?: ')) if fraValuta == 'NOK': nyVerdi = fraNok(verdi, tilValuta) else: nyVerdi = tilNok(verdi, fraValuta) print('%f %s er %f %s' % (verdi, fraValuta, nyVerdi, tilValuta)) def oppgave4(): for i in range(10): print('%d**3=%d' %(i, i**3)) def oppgave5(): start = int(input('Start: ')) stopp = int(input('Stopp: ')) n = int(input('Hvilket tall vil du dele på?: ')) print('Verdier mellom %d og %d som er delelige på %d: ' % (start, stopp, n)) for i in range(start, stopp+1): if i % n == 0: print(i) def tilFahrenheit(celsius): return (celsius * 1.8) + 32 def oppgave6a(): #printer en tabell som konverterer fra Celsius til Fahrenheit print('%7s %10s %15s' % ('Celsius', 'Farhenheit', 'Status')) for i in range(0, 101, 10): if i < 60: print('%7d %10d Jeg har det bra' % (i, tilFahrenheit(i))) else: print('%7d %10d Jeg svetter ihjel' % (i, tilFahrenheit(i))) def renteOkning(verdi, fra, til): #returnerer hvor mye veriden av pengene har vokst fra året 'fra', til året 'til' for i in range(fra, til): verdi = verdi*1.02 return verdi def oppgave7a(): print(renteOkning(100, 1910, 2020)) krone = 19 < renteOkning(1, 1954, 2019) if krone: print('Krone-is har ikke hatt høyere inflasjon enn 2%') else: print('Krone-is har hatt høyere inflasjon enn 2%') def main(): #korttype() #valutakalkulator() #oppgave4() #oppgave5() #oppgave6a() #oppgave7a() main()
8036bfe766b2b30f54a9e50e37928d85b5484049
rkoblents/python-text-adventure-api
/textprint/section.py
8,475
3.78125
4
from typing import Optional, TYPE_CHECKING, Tuple from textprint.line import Line if TYPE_CHECKING: from textprint.textprinter import TextPrinter class Section: OLD_LINES_AMOUNT = 100 """The amount of lines to keep and possibly render if they fit on screen""" OLD_LINES_REMOVE_AT_TIME = 10 """The amount of lines to remove if the amount of lines gets above OLD_LINES_AMOUNT + OLD_LINES_REMOVE_AT_TIME""" def __init__(self, rows: Optional[int], columns: Optional[int] = None, fill_up_left_over: bool = True, fake_line: Optional[str] = None): """ NOTE: You cannot have two sections in the same TextPrinter where rows are both None and fill_up_left_over are both True. This is because if two Sections try to fill up the rows that are left, they will keep asking each other how many rows the other takes up. (This causes a RecursionError) :param rows: The max number of rows to show, or None to show len(self.lines) :param columns: The max number of columns, unused for right now :param fill_up_left_over: By default True. When True and rows is not None, when the amount of rows printed is less than rows, this will still fill up the amount of rows determined by parameter rows. If False, this section will not be the max number of rows (rows) until this has printed enough. If rows are None, this determines whether or not this Section should try to fill up any left over space. :param fake_line: A string that is only used if fill_up_left_over is True, if None, fake_lines aren't used, otherwise fake_lines are placed in all the lines that the section occupies except for the ones that have already been printed. """ self.rows = rows self.columns = columns self.fill_up_left_over = fill_up_left_over self.fake_line = fake_line self.lines = [] """A list of all the lines in this section""" def get_lines_taken(self, printer: 'TextPrinter', include_extra_rows=True) -> int: """ :param printer: The printer being used :param include_extra_rows: Some lines need more than 1 row to fit. If this is True, it will count all the rows each line takes up, False otherwise. :return: The number of lines """ terminal_width = printer.dimensions[1] length = len(self.lines) if include_extra_rows: # most of the time, this is True length = 0 for line in self.lines: length += line.get_rows_taken(terminal_width) # could be 2 or 3 if the line is overflowing if self.rows is None: # is there no set number of rows? if not self.fill_up_left_over: # if we aren't forcing the number of rows this section has return length # Now then, we'll just use as many rows as we'd like before = printer.calculate_lines_to(self) after = printer.calculate_lines_after(self) else_height = (before + after) # isn't recursive because it doesn't call the get_lines_taken method from the passed section (self) height = printer.dimensions[0] if else_height + length >= height or self.fill_up_left_over: # if length will put other things off screen or full length = height - else_height # will set the exact amount needed to show everything on screen (by \ # hiding lines) return length # self.rows is not None if self.fill_up_left_over or length > self.rows: return self.rows # this is very likely to be returned return length def goto(self, text_printer: 'TextPrinter', row: int, column: int, flush=False) -> Tuple[int, int]: """ Changes the cursor to the position relative to this section :param text_printer: The TextPrinter that this section is contained in :param row: The row relative to this section. (0 will be the first line which usually displays the last \ element in self.lines) :param column: The column, nothing special here unless this is changed in the future. Usually you'd set it \ to 0 unless you want to start printing in the middle of the screen. :param flush: Normally False unless you are calling this method and nothing else. If this is False and you\ don't have another method flush (or yourself), the console will not show the cursor in the wanted \ position :return: A Tuple value where [0] represents the row and [1] represents column (y, x) (yes weird but [0] is \ more important) Note that the reason this is returned is because row will likely be different than \ the passed row because this method acts relative to this section. (The returned value is not) """ r = row + text_printer.calculate_lines_to(self) c = column text_printer.goto(r, c, flush=flush) return r, c def println(self, text_printer: 'TextPrinter', message: str, flush=False) -> Line: line = Line(message, self, len(self.lines)) self.lines.append(line) # we will need force_reprint, because we need to redraw all lines in correct places self.update_lines(text_printer, flush=flush, force_reprint=True) # write to the line that the newly created Line should occupy,\ # if a new line was needed, it should have been added return line def clear_lines(self, text_printer: 'TextPrinter', flush=False): self.lines.clear() self.update_lines(text_printer, flush=flush, force_reprint=True) def __remove_old_lines(self): if len(self.lines) < self.__class__.OLD_LINES_AMOUNT + self.__class__.OLD_LINES_REMOVE_AT_TIME: return amount_removed = 0 while len(self.lines) > self.__class__.OLD_LINES_AMOUNT: del self.lines[0] # removes first item by index amount_removed += 1 for line in self.lines: line.line_number -= amount_removed def update_lines(self, text_printer: 'TextPrinter', flush=False, force_reprint=False): """ Simple method to update all the lines and make sure they are in the right place :param text_printer: The TextPrinter that contains this section :param flush: By default False. Determines whether the stream will be flushed at the end of this method call :param force_reprint: By default False :return: """ self.__remove_old_lines() terminal_width = text_printer.dimensions[1] # length = len(self.lines) length = 0 # calculate length with this for loop for line in self.lines: length += line.get_rows_taken(terminal_width) taken = self.get_lines_taken(text_printer) # how many lines should this section take row = 0 # the current row usually incremented by 1 or 2 if a line overflows for line in self.lines: # update all the lines that should be on screen if length - row <= taken: line.update(text_printer, reprint=force_reprint) row += line.get_rows_taken(terminal_width) assert row == length, "Since this is False, then one of the Line#update isn't doing something right." if self.fake_line is not None: # adding extra lines may look like it affected the speed, but it's because it happens even with regular \ # lines when the screen fills up. extra_lines = length - len(self.lines) # for line in self.lines: used when extra_lines is initially 0 # extra_lines += line.get_rows_taken(terminal_width) - 1 for i in range(row - taken, extra_lines * -1): # this was very painful to think about, basically, it creates a fake line for each empty line that is \ # owned by the section and that is not an actual line that has already been printed. # notice that we go to zero. This is because the first line's line_number is 0. (Goes negative to pos) fake_line = Line(self.fake_line, self, i) fake_line.update(text_printer) if flush: text_printer.flush()
4a959a722cdd7714bc6dc2d456374880e748a4d3
QiuFeng54321/python_playground
/loop_structure/edited_Q1.py
153
3.953125
4
# Quest: 1. Input two integers x, y, print the larger integer print("The sum is", int(input("First integer: ")) + int(input("Second integer: ")))
5da0ead112ac8814419d50d2825c9272976bf91b
paepcke/discrete_differentiator
/src/discrete_differentiator/discrete_differentiator.py
7,441
3.890625
4
#!/usr/bin/env python ''' Created on Jan 27, 2015 @author: paepcke Takes a sequence of numbers, and returns a sequence of numbers that are the derivative of the given sample. Takes the sequence either as a Python array, or in a CSV file. Differentiation is done as follows: For first data point uses: f'(x) =(-f(x+2h) + 4*f(x+h) - 3*f(x))/(2h) For internal data points uses: f'(x) =(f(x+h) - f(x-h))/(2h) For last data point uses: f'(x) =(f(x-2h) - 4*f(x-h) + 3*f(x))/(2h) Accommodates CSV files with multiple columns, of which one is contains the sequence to differentiate. Accommodates CSV files with or without column header. To run unit tests, uncomment the unittest main at the bottom. ''' import argparse import csv import os import sys class DiscreteDifferentiator(object): # ------------------------------ Public -------------------------------- @classmethod def differentiate(theClass, seqOrFileName, xDelta=1, outFileFd=sys.stdout, colIndex=0, csvDelimiter=',', csvQuotechar='"', skipLines=0): ''' Main and only (class) method. So, call with DiscreteDifferentiator.differentiate(...) The sequence is assumed to be the Y-values of a function over an even-spaced series of x values. Like this: x y ----- 0 10 1 20 2 14 ... But only the Y values are supplied. In spite of the many parameters, simple cases are simple. Examples: o differentiate([2,4,6,7]) o Given a csv file foo.csv with a single column of numbers: differentiate('foo.txt') o A csv file like this: "trash column", 10 "more trash", 20 differentiate('foo.txt', colIndex=1) :param seqOrFileName: Either the number array, or a file name :type seqOrFileName: {[{float | int}] | string} :param xDelta: the number of integers between two X-axis ticks. Assumed to be 1, but can be any positive int. Assumes that first number in given sequence is f(0) :type xDelta: int :param outFileFd: file object of the file to which result sequence is written. Default is sys.stdout :type outFileFd: FILE :param colIndex: if sequence is given in a CSV file, this parameter is the CSV zero-origin column index. Default is 0 :type colIndex: int :param csvDelimiter: delimiter used in CSV file. Default is comma :type csvDelimiter: str :param csvQuotechar: char used to quote column fields that contain the delimiter. Default is '"' :type csvQuotechar: str :param skipLines: number of lines in CSV file to skip before number sequence starts. Default is 0 :type skipLines: int ''' try: seq = theClass.importSequence(seqOrFileName, colIndex=colIndex, csvDelimiter=csvDelimiter, csvQuotechar=csvQuotechar, skipLines=skipLines) except ValueError as e: outFileFd.write('Error during file import: ' + repr(e)) res = [] res.append((-(seq[0+2*xDelta]) + 4*seq[0+xDelta] - 3*seq[0])/float(2*xDelta)) for indx in range(1,len(seq)-1): res.append((seq[indx+xDelta] - seq[indx-xDelta]) / float(2*xDelta)) res.append((seq[-1-2*xDelta] - 4*seq[-1-xDelta] + 3*seq[-1])/float(2*xDelta)) # Print to stdout, one value at a time: for resNum in res: outFileFd.write(str(resNum) + '\n') return res # ------------------------------ Private -------------------------------- @classmethod def importSequence(cls, seqOrFileName, colIndex=0, csvDelimiter=',', csvQuotechar='"', skipLines=0): ''' Import the sequence of numbers, either given a sequence as an array, or a file name. :param seqOrFileName: Either the number array, or a file name :type seqOrFileName: {[{float | int}] | string} :param colIndex: if sequence is given in a CSV file, this parameter is the CSV zero-origin column index. Default is 0 :type colIndex: int :param csvDelimiter: delimiter used in CSV file. Default is comma :type csvDelimiter: str :param csvQuotechar: char used to quote column fields that contain the delimiter. Default is '"' :type csvQuotechar: str :param skipLines: number of lines in CSV file to skip before number sequence starts. Default is 0 :type skipLines: int ''' if type(seqOrFileName) == list: seq = seqOrFileName else: seq = [] with open(seqOrFileName, 'r') as fd: csvReader = csv.reader(fd, delimiter=csvDelimiter, quotechar=csvQuotechar) for i in range(skipLines): #@UnusedVariable next(csvReader) for rowArr in csvReader: try: num = float(rowArr[colIndex]) except ValueError: raise ValueError("All rows in the data file ('%s') must be numbers in column %s; found: %s" % (seqOrFileName, str(colIndex), str(rowArr))) except IndexError: # If empty line, just skip it: if len(rowArr) == 0: continue seq.append(num) return seq if __name__ == '__main__': parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-i', '--colIndex', help='index of column in CSV file that contains the number sequence to differentiate \n' +\ 'Default: 0.', dest='colIndex', default=0); parser.add_argument('-d', '--delimiter', help='CSV field delimiter. Default: comma.', dest='csvDelimiter', default=','); parser.add_argument('-q', '--csvQuotechar', help='CSV delimiter escape quote char. Default: double-quote.', dest='csvQuotechar', default='"'); parser.add_argument('-s', '--skipLines', help='number of lines to skip in file to avoid column headers, etc. Default: 0', dest='skipLines', default=0); parser.add_argument('fileName', help='The CSV file path.' ) args = parser.parse_args(); DiscreteDifferentiator.differentiate(args.fileName, colIndex=int(args.colIndex), csvDelimiter=args.csvDelimiter, csvQuotechar=args.csvQuotechar, skipLines=int(args.skipLines) )
da513825966939e95d5c400bd1bc63e83ed67646
it3r4-gonzales/PythonCourse101
/PythonforBeginners/Data types, Input and Output/expenses.py
566
3.96875
4
##sum of expenses # expenses = [10.5,8,5,15,20,5,3] # sum = 0 # for value in expenses: # sum = sum + value # print("You spent $", sum, " on lunch this week.", sep='') #sum function expenses = [10.5,8,5,15,20,5,3] total = sum(expenses) print("You spent $", total, " on lunch this week.", sep='') #Adding Input To Expenses Calculator total2=0 expenses2 = [] num_expenses = int(input("Enter # of expenses:")) for i in range(num_expenses): expenses2.append(float(input("Enter an expense:"))) total2 = sum(expenses2) print("You spent $", total2, sep=' ')
430dcfc88f30ff21456e192d1ce5754f14300a5c
123tharindudarshana/testproject
/linklist/LinkedList.py
1,517
3.734375
4
from Node import Node class linkedist: def __init__(self): self.head=Node() def listlenth(self): current=self.head count=0 while current is not None: count=count+1 #print(current. getData()) current =current.getNext() return count def addNodeBeginning(self,data): newNode=Node() newNode.setData(data) if self.head is None: self.head=newNode else: newNode.setNext(self.head) self.head=newNode self.length+1 def addNodeEnd(self,data): newNode=Node() newNode.setData(data) if self.head is None: self.head=newNode else: current=self.head while current is not None: current =current.getNext() current.setNext(newNode) newNode.setNext(None) self.length+=1 def addNodeInpos(self,pos,data): if pos>self.length-1 or pos<0: return None elif pos==0: self.addNodeBeginning(data) elif pos == self.length -1: self.addNodeEnd(data) elif pos ==self.length-1: self.addNodeEnd(data) else: newNode=Node() newNode.setData(data) count=0 current =self.head # while count !=pos -1: #count=0 #current=
0c32e313f9d3beb1af51d0b9a50225eef27163ec
CrackedCode7/Udemy-Learning
/basics/hello.py
247
3.90625
4
print('Python is easy') #The print function prints a message enclosed in double quotes to the console # can be used for single line comments '''can be used to have multiple line comments''' """alternatively you can use triple double quotes"""
d3317d61affebfb1c3658c1d6f37842eed6a02cf
a1723/django_brain_games
/project/brain_games/brain_even_helpers.py
138
3.59375
4
def get_even_correct_answer(num1): # проверяем число на чётность return "yes" if (num1 % 2 == 0) else "no"
8113a240b09da5e3a6c07c6808a6e2b1377cbe6d
wellington16/BSI-UFRPE
/2016.1/Exércicio LAB DE PROGRAMAÇÃO/Períodos anteriores/exercicio5/12.py
356
3.8125
4
rota=None def F(n): if n == 1: return 1 elif (n % 2) == 0: rota='Passou aqui' return F(n/2) elif (n % 2) != 0 and (n > 1): rota='Aqui tambem' return F(3*n+1) print(F(1)) print(rota) print(F(2)) print(rota) print(F(3)) print(rota) print(F(5)) print(rota) print(F(8)) print(rota) print(F(13)) print(rota)
8e51cf4b49e4de3ad99b643043012b7dc9bec34c
spoorthichintala/Selenium_Demo_Python
/Python_Demo/Reand_and_Write_JSON_File_Data.py
513
3.5625
4
import json # function to add to JSON def write_json(new_data, filename='TestData.json'): with open(filename, 'w') as file: json.dump(file_data, file, indent=4) with open("TestData.json") as json_file: # First we load existing data into a dict. file_data = json.load(json_file) # Join new_dat3a with file_data temp = file_data["Login_details"] # python object to be appended y = { "uname": "Kumar", "upass": "Dixit" } temp.append(y) write_json(y)
542bceff437ee51af01f6292ee5d8528427eb418
Nishnha/advent-of-code
/2020/day2/part2.py
523
3.578125
4
num_valid = 0 with open("input.txt", "r") as input: for line in input: valid = False x = line.split(" ") p = x[0].split("-") pos1 = int(p[0]) - 1 pos2 = int(p[1]) - 1 letter = x[1].strip(":") password = x[2] print(pos1, pos2, letter, password) if password[pos1] == letter: valid = not valid if password[pos2] == letter: valid = not valid if valid: num_valid += 1 print(num_valid)
4b33c4b3fee0e230ad67fd0e7a7f0b5d37fe6439
widelec9/codewars
/kata/python/6kyu/nut_farm.py
434
3.53125
4
def shake_tree(tree): nuts = [1 if c == 'o' else 0 for c in tree.pop(0)] while len(tree) > 0: for i, c in enumerate(tree[0]): if nuts[i] > 0 and c in ['\\', '/', '_']: if c == '\\' and i < len(nuts) - 1: nuts[i+1] += nuts[i] elif c == '/' and i > 0: nuts[i-1] += nuts[i] nuts[i] = 0 tree.pop(0) return nuts
c4cd55ec702dd4ef95293ed2133367df8053ab1f
glissader/Python
/ДЗ Урок 8/main2.py
1,121
3.65625
4
# Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. # Проверьте его работу на данных, вводимых пользователем. # При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. class CustomZeroDivisionError(Exception): def __str__(self) -> str: return 'Division By Zero' @staticmethod def check_zero_division(num: int, den: int) -> float: if den == 0: raise CustomZeroDivisionError else: return num / den while True: try: num = int(input("Введите числитель ").strip()) den = int(input("Введите знаменатель ").strip()) print(f"Результат = {CustomZeroDivisionError.check_zero_division(num, den)}") break except CustomZeroDivisionError as e: print(e)
1e25e0c7710e2d9ed059fae795dc8ccca46c42ea
dpoulomi/PythonPractice
/python_practice/largest_number_from_array.py
1,688
3.984375
4
import random def quick_sort(input_array, start_index, end_index): if start_index < end_index: partition_index = partition(input_array, start_index, end_index) quick_sort(input_array, start_index, partition_index -1) quick_sort(input_array, partition_index + 1, end_index) def partition(array, start_index, end_index): pivot_index = random.randint(start_index, end_index) swap_array_element(array, pivot_index, end_index) loop_index = 0 smaller_element_index = -1 while loop_index < end_index: if append_compare(array[loop_index], array[end_index]): smaller_element_index = smaller_element_index + 1 swap_array_element(array, smaller_element_index, loop_index) loop_index = loop_index + 1 swap_array_element(array, smaller_element_index + 1, end_index) return smaller_element_index + 1 def compare(element1, element2): if element1 < element2: return True else: return False def append_compare(element1, element2): xy = "{}{}".format(element1, element2) yx = "{}{}".format(element2, element1) if xy > yx: return True else: return False def swap_array_element(array, index1, index2): temp = array[index1] array[index1] = array[index2] array[index2] = temp def find_largest_number(input_array): pass def print_appending_array(array): result = '' for element in array: result = "{}{}".format(result, element) print(result) if __name__ == '__main__': input_array = [ 4, 3, 2, 1, 5 ] quick_sort(input_array, 0, len(input_array) - 1) print_appending_array(input_array)
c917449ef1d6686212e19722ba183bd782e3ed3f
ciberciv/pepi_challenge
/classes/TripGraph.py
4,317
3.65625
4
from classes.CitiesGraph import CitiesGraph from collections import defaultdict import functools import operator import queue class TripGraph(CitiesGraph): def __init__(self, cities, connections, maxDays): assert 2 <= maxDays <= 7, "Trip has to be between 2 and 7 days long" CitiesGraph.__init__(self, cities, connections) self.startingCity = list(filter(lambda city: self.nodes[city].isBase, self.nodes))[0] self.maxDays = maxDays self.daysToStartingCity = self.getDaysToCities() self.bestPath = self.getBestPath() def getDaysToCities(self): """ Return a dictionary with cities as keys and minimum days to go back to the starting city as values using BFS. :return : dict(int) """ visited = [] distances = defaultdict(int) q = queue.Queue() distances[self.startingCity] = 0 q.put(self.startingCity) visited.append(self.startingCity) while not q.empty(): currentCity = q.get() for adjacentCity in self.edges[currentCity]: nextCityName = adjacentCity.nextNode if nextCityName in visited: continue distances[nextCityName] = distances[currentCity] + 1 q.put(nextCityName) visited.append(nextCityName) return distances def getPossiblePaths(self, path, daysLeft): """ In each recursive call, returns a list of lists with the possible paths developing over time. In the end, returns a list of lists of correct paths (that is, ends in startingCity and in less than the initial days. It stops if it reaches a node from which it can't return to startingCity in the number of daysLeft. :param path: list<str> :param daysLeft: int :return: list<list<str>> """ currentCity = self.startingCity shorterPath = [] if path: currentCity = path[-1] if path[-1] == self.startingCity: shorterPath = path if daysLeft: possiblePaths = [self.getPossiblePaths(path + [nextCity.nextNode], daysLeft - 1) for nextCity in self.edges[currentCity] if self.daysToStartingCity[currentCity] <= daysLeft] # Handles return to startingCity if shorterPath: possiblePaths.append([shorterPath]) # Adds paths shorter than maxDays return functools.reduce(operator.iconcat, possiblePaths, []) # Reduces list of lists caused by recursion elif path[-1] == self.startingCity: return [path] else: return [] def calculatePathProfit(self, path): """ Given a path, gets the actual reward considering the reward and the cost of the trip :param path: list<str> :return: int """ visited = [] profit = 0 currentCity = self.startingCity for city in path: reward = self.nodes[city].reward * (city not in visited) # Handles visited cities cost = [edge.cost for edge in self.edges[currentCity] if edge.nextNode == city][0] visited.append(city) currentCity = city profit += reward - cost return profit def getBestPath(self): """ Selects the best path out of the possible paths :return: (list<str>, int) """ # This sorting works taking advantage of how tuple sort is implemented in Python. # It will be sorted according to rewards in descending order (due to reverse=True). If two or more pairs have # the same cost, since we set the order to be descending, the longest path would take preference. However, if # we take the negative of their lengths instead, the shortest one would be the first. sortedPaths = sorted([(path, self.calculatePathProfit(path)) for path in self.getPossiblePaths([], self.maxDays)], key=lambda pathProfitPair: (pathProfitPair[1], -len(pathProfitPair[0])), reverse=True) bestPath = sortedPaths[0] bestPath[0].insert(0, self.startingCity) return bestPath
c1bf8475323437fd8f9f9f43316824522fcf8b26
psarkozy/HWTester
/MIHF/FlappyQ/py_files/flappy_env_server.py
5,683
3.53125
4
#!/usr/bin/env python import random from math import sqrt random_seed = random.randint(0, 200) class Vector(object): def __init__(self, x, y): super(Vector, self).__init__() self.x, self.y = x, y def __add__(self, vector): if isinstance(vector, self.__class__): return self.__class__(self.x + vector.x, self.y + vector.y) return super(Vector, self).__add__(vector) def __mul__(self, vector): if isinstance(vector, self.__class__): return self.__class__(self.x * vector.x, self.y * vector.y) return self.__class__(self.x * vector, self.y * vector) def __repr__(self): return "{0}, {1}".format(self.x, self.y) @property def length(self): return sqrt(self.x ** 2 + self.y ** 2) def normalize(self): _length = self.length self.x = self.x / _length self.y = self.y / _length class Bird(object): size = 3 max_speed = 25 def __init__(self, pos): self.pos = pos self.vel = Vector(0, 0) super(Bird, self).__init__() def step(self, force, keep): if keep: self.vel = self.vel + force else: self.vel = force if self.vel.length > self.max_speed: self.vel.normalize() self.vel = self.vel * self.max_speed self.pos = self.pos + self.vel def check_collide(self, tubes): if (self.pos.y < 0) or (self.pos.y + self.size > Environment.map_size.y): return True for tube in tubes: if self.pos.x + self.size > tube.pos.x and self.pos.x < tube.pos.x + Tube.width: if self.pos.y < tube.height or self.pos.y + self.size > tube.height + Tube.gap_size: return True return False class Tube(object): gap_size = 20 tube_speed = Vector(-2, 0) width = 10 height_range = (5, 15) def __init__(self, pos, height): self.pos = pos self.height = height self.scored = False super(Tube, self).__init__() def step(self): self.pos = self.pos + self.tube_speed def distance_to_bird(self, bird): return self.pos.x - bird.pos.x class Environment(object): map_size = Vector(80, 40) tube_interval = 30 gravity = Vector(0, 1) jumpforce = Vector(0, -5) def __init__(self): self.tube_heights = [] self.reset() super(Environment, self).__init__() @property def action_space(self): return [0, 1] @property def observation_space(self): return [ [-1, Environment.map_size.y - Bird.size + 1], [-Bird.max_speed, Bird.max_speed], [-(Tube.width + 1), Environment.map_size.x], [Tube.height_range[0], Tube.height_range[1]] ] @property def observation_space_size(self): return [s[1] - s[0] + 1 for s in self.observation_space] @property def state(self): tubes_sorted = sorted(self.tubes, key=lambda p: p.distance_to_bird(self.bird)) if self.bird.pos.y < 0: current_bird_pos = -1 elif self.bird.pos.y > Environment.map_size.y - Bird.size: current_bird_pos = Environment.map_size.y - Bird.size + 1 else: current_bird_pos = self.bird.pos.y current_bird_pos = current_bird_pos + 1 current_bird_vel = self.bird.vel.y + Bird.max_speed current_tube_dst = tubes_sorted[0].distance_to_bird(self.bird) + Tube.width + 1 current_tube_hgt = tubes_sorted[0].height - Tube.height_range[0] return current_bird_pos, current_bird_vel, current_tube_dst, current_tube_hgt def is_valid_state(self, value): ret = True for i, v in enumerate(value): ret = ret and (v >= self.observation_space[i][0] and v <= self.observation_space[i][1]) return ret def spawn_tube(self): tube_height = self.rnd.randint(*Tube.height_range) self.tubes.append(Tube(Vector(Environment.map_size.x, 0), tube_height)) def step(self, action): assert action in self.action_space reward = 0 if not self.done: self.step_counter += 1 if action == 0: self.bird.step(Environment.gravity, keep=True) elif action == 1: self.bird.step(Environment.jumpforce, keep=False) if self.step_counter % Environment.tube_interval == 0: self.spawn_tube() for tube in self.tubes: tube.step() if tube.pos.x + Tube.width < self.bird.pos.x and not tube.scored: tube.scored = True reward = 1.0 self.tubes = list(filter(lambda tube: not tube.scored, self.tubes)) if self.bird.check_collide(self.tubes): reward = -1.0 self.done = True return (self.state, reward, self.done, { 'bird': { 'pos': self.bird.pos, 'size': Bird.size }, 'tubes': { 'list': list(map(lambda tube: (tube.pos.x, tube.height), self.tubes)), 'width': Tube.width, 'gapsize': Tube.gap_size } }) def reset(self): self.rnd = random.Random(random_seed) self.bird = Bird(Vector(10, Environment.map_size.y // 2)) self.step_counter = 0 self.tubes = [] self.spawn_tube() self.done = False return self.state
795578e5fce1469a121521e936f971910b095f97
zzz0072/Python_Exercises
/07_RSI/ch01/Fraction.py
3,591
3.921875
4
#!/usr/bin/env python3 def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, num, den): if type(num) != int or type(den) != int: raise TypeError if num == 0 or den == 0: raise SyntaxError if num < 0 and den < 0: num = abs(num) den = abs(den) elif num > 0 and den < 0: num = -num den = abs(den) common_den = abs(gcd(den, num)) self.num = num // common_den self.den = den // common_den def __str__(self): return str(self.num) + "/" + str(self.den) def __repr__(self): return 'Fraction:' + str(self.num) + "/" + str(self.den) def __add__(self, next_frac): res_num = self.num * next_frac.den + next_frac.num * self.den res_den = self.den * next_frac.den common_den = abs(gcd(res_den, res_num)) return Fraction(res_num // common_den, res_den // common_den) def __radd__(self, next_frac): res_num = self.num + next_frac * self.den return Fraction(res_num, self.den) def __sub__(self, next_frac): res_num = self.num * next_frac.den - next_frac.num * self.den res_den = self.den * next_frac.den common_den = abs(gcd(res_den, res_num)) return Fraction(res_num // common_den, res_den // common_den) def __mul__(self, next_frac): new_num = self.num * next_frac.num new_den = self.den * next_frac.den common_den = abs(gcd(new_den, new_num)) return Fraction(new_num // common_den, new_den // common_den) def __truediv__(self, next_frac): new_num = self.num * next_frac.den new_den = self.den * next_frac.num common_den = abs(gcd(new_den, new_num)) return Fraction(new_num // common_den, new_den // common_den) def __iadd__(self, next_frac): res_num = self.num * next_frac.den + next_frac.num * self.den res_den = self.den * next_frac.den common_den = abs(gcd(res_den, res_num)) return Fraction(res_num // common_den, res_den // common_den) def __eq__(self, cmp_frac): num_1 = self.num * cmp_frac.den num_2 = cmp_frac.num * self.den return num_1 == num_2 def __ne__(self, cmp_frac): num_1 = self.num * cmp_frac.den num_2 = cmp_frac.num * self.den return not(num_1 == num_2) def __lt__(self, cmp_frac): return self.num * cmp_frac.den < cmp_frac.num * self.den def __gt__(self, cmp_frac): return self.num * cmp_frac.den > cmp_frac.num * self.den def getNum(self): return self.num def getDen(self): return self.den if __name__ == "__main__": myfac = Fraction(-2, -4) print(myfac) myfac2 = Fraction(1, -3) print(myfac2) myfac3 = myfac + myfac2 print(myfac3) myfac += myfac2 print(myfac) print(str(myfac.getNum()) + "|" + str(myfac.getDen())) print(str(myfac.getNum()) + "|" + str(myfac.getDen())) myfac = myfac - myfac2 print(myfac) print(str(gcd(4, 2))) print(myfac == myfac2) myfac3 = Fraction(2, 4) print(myfac2 == myfac3) print(myfac) print(myfac2) print(myfac * myfac2) myfac3 = myfac / myfac2 print(myfac / myfac2) print(myfac < myfac2) print(myfac2 < myfac) print(myfac) myfac = myfac.__radd__(1) myfac = 1 + myfac print(myfac) # myfac = Fraction(1.4, 4) # myfac = Fraction(1, 'qq')
9b449116d0c8259cbd6c70b0a2b16026d2c55c69
frankieliu/problems
/leetcode/python/6/zigzag-conversion.py
2,089
4.3125
4
"""6. ZigZag Conversion Medium 834 2589 Favorite Share The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Accepted 268,762 Submissions 899,355 """ class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ slen = len(s) if slen <= 1 or numRows == 1: return s # numRows = n midRows = numRows - 2 # number of distinct spots dist = numRows + midRows """ numRows = 4 P 0 loner A L 1 shares 6 Y A 2 shares 5 P 3 loner dis numRows = 5 0 loner 1 shares 7 = 8 - 1 2 shares 6 = 8 - 2 3 shares 5 = 8 - 3 4 loner """ out = "" for i in range(0, numRows): if i == 0 or i == numRows-1: out += s[i::dist] # print(i, out) else: p1 = i p2 = dist - i # print(p1, s[p1], p2, s[p2]) tmp = "" while True: if p1 <= slen - 1: tmp += s[p1] if p2 <= slen - 1: tmp += s[p2] if p1 >= slen and p2 >= slen: break p1 += dist p2 += dist # print(i, tmp) out += tmp return out s = Solution() print(s.convert("ab", 1))
d0bede460d9b28f5bdf847db3746340c506c5397
Frootloop11/lectures
/week 10/find_in_files.py
995
3.96875
4
import os def find_in_files(search_string, file_extension, files_found): """Find files of type file_extension that contain search_string.""" count = 0 for directory_name, directories, filenames in os.walk("."): for filename in filenames: if os.path.splitext(filename)[1] == file_extension: count += 1 current_file = open(os.path.join(directory_name, filename), 'r') text = current_file.read() if search_string in text: full_filename = os.path.join(directory_name, filename) files_found.append(full_filename) current_file.close() return count def test_find(): filenames = [] search_string = "print" file_extension = ".py" count = find_in_files(search_string, file_extension, filenames) print("Examined {} {} files and found '{}' in:\n{}".format(count, file_extension, search_string, filenames))
d390591611153ca80aa1dc292908f504a08f997f
yuhanlyu/arrivability
/files/random_generate.py
633
4.03125
4
import random def random_generate(row, column, number): print row, column print number for i in xrange(number): print 4 x, y = random.randrange(3, row - 3, 5), random.randrange(3, column-3, 5) (w, h) = 1, 5 if random.randint(1, 2) == 1: (w, h) = (h, w) print x, y print x + w, y print x + w, y + h print x, y + h if __name__ == "__main__": #row = input("Number of rows\n") #column = input("Number of columns\n") #number = input("Number of obstacles\n") row, column, number = 50, 50, 80 random_generate(row, column, number)
380348fcb5ee2da37e1701f1260a04aa34a22444
vofchik/python_learning
/exercise_06/task_06.py
499
4.125
4
#!/usr/bin/python3 # Упражнение 6 # Задание 6 # Заполнить список из шести элементов квадратными корнями произвольных # целочисленных значений. Вывести список на экран через запятую. import random roots = [random.randint(0,10000) ** 0.5 for i in range(6)] def float_as_str(x): return '{:.2f}'.format(x) print('Когни: ' + ', '.join(map(float_as_str, roots)))
6f349a56391da322714d84f95ab688b41fe62b26
chmjorn/MastersProject
/mSketch.py
897
3.578125
4
import random import numpy #must be odd numbers width=7 height=7 maze = numpy.chararray((width, height)) for x in range(height): #create map for y in range(width): if (x%2==0): if(y%2==0): maze[x][y]='*' else: maze[x][y]='-' else: if(y%2==0): maze[x][y]='|' else: maze[x][y]='X' print(maze) print for x in range(height): #remove paths for y in range(width): if (x%2==0 and y%2!=0 and random.randint(0,3)==0): maze[x][y]=' ' #1/4 chance to replace '-' with ' ' elif(x%2!=0 and random.randint(0,3)==0): if(y%2==0): maze[x][y]=' ' #replace '|' with ' ' else: if (random.randint(0,1)): maze[x][y]='/' else: maze[x][y]='\\' print(maze) f=open("maze.txt","w") f.write("%s\n" % height) f.write("%s\n" % width) for x in range(height): for y in range(width): f.write("%s" % maze[x][y]) f.write(" ") f.write("\n")
e38ae5e0e0b907f21f3d577b9fef5ead54e4812f
kiefersutherland/pythonLearning
/learn/mpl.py
822
3.53125
4
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt from walk import Radomwalk ''' input_value=list(range(1,1001)) squares=[x**3 for x in input_value] plt.plot(input_value,squares,linewidth=5) ''' while True: rw=Radomwalk(5000) rw.fill_walk() plt.title('我是标题,do u know') pointNumbers=list(range(rw.num_points)) plt.scatter(0,0,c='green',s=200) plt.scatter(rw.x_values[-1],rw.y_vaules[-1],s=200,c='red') #plt.scatter(rw.x_values,rw.y_vaules,s=1,edgecolors=None,c=pointNumbers,cmap=plt.cm.Blues) plt.plot(rw.x_values,rw.y_vaules,linewidth=1) #plt.tick_params(axis='both',which='major',labelsize=14) #plt.axis([0,1100,0,1110110]) plt.axes().get_xaxis().set_visible(False) plt.show() keep_running=input('输入q去中止') if keep_running == 'q': break
a0f48be79a42a74013168a426378a45d229257dc
carloseduardo1987/Python
/ex14_lista1.py
686
4.09375
4
#Questão 14. Sabendo que a relação entre vértices, arestas e faces de um objeto geométrico é dada pela fórmula: # vértices + faces = arestas + 2. # Elabore um programa que calcule o número de vértices de um objeto geométrico genérico. # A entrada será o número de faces e arestas (dadas por um número inteiro e positivo) # e a saída será o número de vértices. faces = int(input('Informe o números de faces do objeto (obs: números inteiro e positivo):')) arestas = int(input('Informe o números de arestas do objeto (obs: números inteiro e positivo):')) vertices = arestas + 2 - faces print('O número de vertices do objeto será {}'.format(vertices))
94d4bd48f272fb1369efbbc1da2acc9174b38ffe
devroopb/number_guesser
/number_guesser.py
1,155
4.21875
4
# Made by Devroop Banerjee # Generate a random number between a range chosen by user # Tell user whether they need to go higher or lower # Return the number of attempts it took import random print("Please input the range of values from which a random number will be generated. You will have to have to guess this number.") while True: start = input("Starting value for range: ") if start.lstrip("-").isdigit(): start = int(start) else: print("Please enter a number next time!") quit() end = input("Ending value for range: ") if end.lstrip("-").isdigit(): end = int(end) else: print("Please enter a number next time!") quit() if end<start: print("End of range can not be smaller than the start. Please try again") else: break r_num = random.randrange(start, end+1) attempt = 0 while True: answer = int(input("What number do you guess? ")) attempt +=1 if (answer > end) or (answer < start): print("Please guess a number within the range you provided") elif answer > r_num: print("Guess lower!") elif answer < r_num: print("Guess higher!") else: print("You have correctly guessed the answer after %d attempts" %attempt) break
5bd7abd88df49bfd2e3f5478d8f2927c53d89a78
murilo-muzzi/Desafio-Murano
/Questão 7.py
1,758
3.75
4
# Desafio PS Murano Investimentos # Candidato: Murilo Marinho Muzzi Ribeiro # e-mail: murilomarinhomuzzi@gmail.com # Questões de computação e programação # Feito em Python # 7) continuar = 'sim' while continuar == 'sim': dados = dict() dados['dre'] = int(input('Digite o DRE: ')) dados['curso'] = input('Digite o Curso: ') dados['nome'] = input('Digite o nome do(a) aluno(a): ') while True: dados['genero'] = input('Digite o gênero: [M] ou [F] ') if dados['genero'] == 'M' or dados['genero'] == 'F': break dados['data_nascimento'] = input('Digite a data de nascimento: ') dados['altura'] = (input('Digite a altura do(a) aluno(a): ')) dados['peso'] = (input('Digite o peso do(a) aluno(a): ')) dados['cra'] = (input('Digite o CR acumulado do(a) aluno(a): ')) dados['cra'] = dados['cra'].replace(",",".") dados['cra'] = float(dados['cra']) while dados['cra'] < 0 or dados['cra'] > 10: dados['cra'] = float(input('Digite novamente o CR acumulado do(a) aluno(a): ')) dados['creditos'] = int(input('Digite a quantidade de créditos obtidos do(a) aluno(a): ')) while dados['creditos'] <= 0: dados['creditos'] = int(input('Digite novamente a quantidade de créditos obtidos do(a) aluno(a): ')) dados['renda'] = (input('Digite a renda do(a) aluno(a): ')) dados['renda'] = dados['renda'].replace(",",".") dados['renda'] = float(dados['renda']) while dados['renda'] < 0: dados['renda'] = float(input('Digite novamente a renda do(a) aluno(a): ')) with open('dados.txt','a') as arquivo: for valor in dados.items(): arquivo.write(str(valor)+'\n') continuar = input('Deseja continuar? [sim] ou [nao] ')
b40e520d3c3d671a43b43ad17f8048d264e4c5c0
cafaray/atco.de-fights
/digitsProduct.py
814
3.796875
4
def digitsProduct(product): if product == 0: return 10 if product < 10: return product number = list() while product > 1: for divisor in range(9, 1, -1): print('evaluating:',product, divisor) if product % divisor == 0: number.append(divisor) product /= divisor if product < 10 and product > 1: number.append(int(product)) product = 1 #print(product) break else: if divisor == 2: return -1 # encontro un primo else: continue if len(number) == 0: return -1 res = '' for i in number: res = str(i) + res return int(res)
c4ec6f2c3d3ee2be8872c209290543dadc1e758f
jcutsavage/OOD-Project
/prime.py
553
4.15625
4
#!/usr/bin/env python #author John Cutsavage #cool code -Victor M import math #this code was taken from stackoverflow.com/questions/18833759/python-prime-number-checker def is_prime(n): if n < 2: #0 and 1 aren't prime; assume only positive integers return False if n % 2 == 0 and n > 2: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True #this is my own code def primes(): n = int(raw_input("Enter a positive integer ")) for i in range(0,n): if is_prime(i): print i #print the number if prime
f24d63ac6af2db6ff4fc068505cdb80503784277
ojohnso8/python-challenge
/PyBank/Main.py
2,867
3.96875
4
#import import os import csv #create csv path budget_csv = os.path.join(".", "budget_data.csv") #Create empty lists for months and revenue months = [] revenue = [] #open csv with open(budget_csv, newline = "") as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") csv_header = next(csvreader) #append month and revenue data from csv into empty lists created in lines 9 and 10 for row in csvreader: months.append(row[0]) revenue.append(int(row[1])) #calculate total months total_months = len(months) # print("Total Months: ", total_months) #calculate the net total amount of "Profit/Losses" over the entire period total_amount = sum(revenue) # print("Total: $",total_amount) #calculate the average of the changes in "Profit/Losses" over the entire period average = sum(revenue)/total_months # print("Average Change: $", round(average, 2)) # The greatest increase/decrease in profits (date and amount) over the entire period greatest_increase= 0 greatest_decrease= 0 inc = 0 dec = 0 for inc in range(len(revenue)): if (revenue[inc]) - (revenue[inc -1 ]) > greatest_increase: greatest_increase = (revenue[inc]) - (revenue[inc - 1]) greatest_inc_month = months[inc] # print('Greatest Increase Month ', greatest_inc_month) # print('Greatest Increase Amt ', '$',greatest_increase) for dec in range(len(revenue)): if (revenue[dec]) - (revenue[dec- 1]) < greatest_decrease: greatest_decrease = (revenue[dec]) - (revenue[dec - 1]) greatest_dec_month = months[dec] # print('Greatest Decrease Month ', greatest_dec_month) # print('Greatest Decrease Amt ', '$',greatest_decrease) #print to terminal print("Financial Analysis") print('------------------------') print("Total Months: ", total_months) print("Total: $",total_amount) print("Average Change: $", round(average, 2)) print('Greatest Increase Month ', greatest_inc_month) print('Greatest Increase Amt ', '$',greatest_increase) print('Greatest Decrease Month ', greatest_dec_month) print('Greatest Decrease Amt ', '$',greatest_decrease) #write output output_path = os.path.join(".", "budget_output.txt") with open(output_path, 'w') as writefile: writefile.writelines('Financial Analysis' + '\n') writefile.writelines('------------------------' + '\n') writefile.writelines('Total Months: ' + str(total_months) + '\n') writefile.writelines('Total $' + str(total_amount) + '\n') writefile.writelines('Average Change: $' + str(round(average, 2)) + '\n') writefile.writelines('Greatest Increase: ' + str(greatest_inc_month) + ' $' + str(greatest_increase) + '\n') writefile.writelines('Greatest Decrease: ' + str(greatest_dec_month) + ' $' + str(greatest_decrease) + '\n')
07dc52f1c26dbbcb7abf233196ff3aeb9a2a402a
x64511/SIC-Assembler
/AssemblerFinal.py
5,720
3.5
4
from collections import OrderedDict def a24to6(Bits): #Function to convert 24 bit binary to hexadecimal res="" arr=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] for i in range(6): s=Bits[i*4:(i*4)+4] x=int(s,2) res+=arr[x] return res def a16to6(Bits): #Function to convert 16 bit binary to hexadecimal res="" arr=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] for i in range(4): s=Bits[i*4:(i*4)+4] x=int(s,2) res+=arr[x] return res def hextobin(n): #Function to convert hexadecimal to binary result="" for i in n: OneHexCharacter="" x=bin(int(i,16)) OneHexCharacter+=x[2:] Zero="0"*(4-len(x[2:])) OneHexCharacter=Zero+OneHexCharacter result+=OneHexCharacter return result[1:] def hexAdd(loc,x): #Function to Add hexadecimal number temp=int(str(loc),16) temp+=int(x) return hex(temp) def readFile(): #Function to read input file symtab=[] optab=[] operand=[] lines=[] f=open('input.txt',"r+") for line in f.readlines(): #Making 3 arrays, each for symbol,opcode and operand for every instruction in input file s=line.strip() if(len(s)!=0 and not s.__contains__(".")): x=s.split(" ") print(x) y=[] for i in range(len(x)): x[i]=x[i].strip() if(len(x[i])>=1): y.append(x[i]) x=y[:] if(len(x)==1): ` x=[" "]+x+[" "] operand.append(x[0]) elif(len(x)==2): x=[" "]+x optab.append(x[0]) operand.append(x[1]) else: symtab.append(x[0]) optab.append(x[1]) operand.append(x[2]) lines.append(x) #lines contains all the lines of input, individually return symtab,optab,operand,lines symtab,optab,operand,lines=readFile() f1=open('intermediate.txt',"w+") tempVar="" ProgName="" machineCodes=[] LOC=0 tim=lines[0] if 'START' or 'Start' in tim: LOC=tim[-1] tempVar=tim[-1] ProgName=tim[0] s=" ".join(tim) f1.write("%s %s\n"%(LOC,s)) machineCodes.append(tempVar) temp=0 if 'START' or 'Start' in tim: temp=1 if(temp==1): machineCodes.append(tempVar) s=" ".join(lines[1]) f1.write("%s %s\n"%(LOC,s)) else: machineCodes.append("0000") for i in range(temp+1,len(lines)): s="".join(lines[i]) if(lines[i][1]=='END'): break else: t=0 if(lines[i][1]=='WORD'): LOC=hexAdd(LOC,3) elif(lines[i][1]=='RESW'): LOC=hexAdd(LOC,3) t=3*int(lines[i][2])-3 elif(lines[i][1] == 'RESB'): LOC=hexAdd(LOC,3) t=int(lines[i][2])-3 elif(lines[i][1] == 'BYTE'): by=0 p=lines[i][2] if(p[0]=="C"): temp=p[2:-1] if(temp=="EOF"): by=3 else: by=len(temp) elif(p[0]=='X'): temp=p[2:-1] by=len(temp)//2 LOC=hexAdd(LOC,3) t=by-3 else: LOC=hexAdd(LOC,3) temporary=LOC[2:]+" "+" ".join(lines[i]) f1.write("%s\n"%(temporary)) machineCodes.append(LOC[2:]) LOC=hexAdd(LOC,t) symtab=[] optab=[] operands=[] for i in lines: # print(i) if(i[0]!=' ' and len(i[0])>=1): symtab.append(i[0]) if(i[1]!=' ' and len(i[1])>=1): optab.append(i[1]) if(i[2]!=' ' and len(i[2])>=1): operands.append(i[2]) abc={} for i in range(len(symtab)): for j in range(len(lines)): if(lines[j][0]==symtab[i]): abc[symtab[i]]=machineCodes[j] opcode={} f3=open("opfile","r+") for line in f3.readlines(): x=line.split(" ") y=[] for j in x: p=j.strip() if(len(p)>0): y.append(p) opcode[y[0]]=y[1] print(opcode) objcode=[] for i in lines: s="" if(i[1]=="START"): s="" elif(i[1]=="WORD"): b=hex(int(i[-1]))[2:] c="0"*(6-len(b)) s+=c+b elif(i[1]=="RESW" or i[1]=="RESB"): s="" elif(i[1]=="END"): continue elif(i[1]=="BYTE"): p=i[-1] if(p[0]=="C"): temp=p[2:-1] if(temp=="EOF"): s="454F46" else: s="" elif(p[0]=='X'): temp=p[2:-1] s=temp elif(i[1]=="RSUB"): s=opcode['RSUB']+"0000" else: oc=opcode[i[1]] s+=oc t="" u=0 opr=i[-1] if(opr.__contains__(',')): t+="1" opr=opr[:opr.index(',')] else: t+="0" if(abc.keys().__contains__(opr)): u=abc[opr] t+=hextobin(u) s+=a16to6(t) objcode.append(s) for objectCode in objcode: print(objectCode) def sst(startaddr): f2.write("T^") x="0"*(6-len(startaddr)) f2.write("%s%s^"%(x,startaddr)) def writeTof2(stradr,ObjectCodes): f2.write("T^") x="0"*(6-len(stradr)) f2.write("%s%s^"%(x,stradr)) temp="" for objco in ObjectCodes: temp+=objco size=len(temp)//2 s=hex(size)[2:] y="0"*(2-len(s)) f2.write("%s%s^"%(y,s)) for i in ObjectCodes: if i!='' and i!=' ': f2.write("%s^"%i) f2.write("\n") mapMAddrToObjCode=OrderedDict() for i in range(len(machineCodes)): mapMAddrToObjCode[machineCodes[i]]=objcode[i] print("mapMAddrToObjCode=",mapMAddrToObjCode) f1.close() f1=open('intermediate.txt',"r+") f2=open('objProg.txt',"w+") f2.write("H^") f2.write("%s"%( )) x=" "*(6-len(ProgName)) f2.write("%s^"%(x)) x="0"*(6-len(tempVar)) f2.write("%s%s^"%(x,tempVar)) y=hex(int(machineCodes[-1],16) - int(machineCodes[0],16) + 1)[2:] x="0"*(6-len(y)) f2.write("%s%s\n"%(x,y)) dr=[] co=0 flag=1 stradr=tempVar for i in range(1,len(machineCodes)): print(machineCodes[i]) print(co) print(dr) if flag==1: stradr=machineCodes[i] flag=0 if(mapMAddrToObjCode[machineCodes[i]]==' ' or co==10): if(len(dr)>0): writeTof2(stradr,dr) dr=[] co=0 flag=1 if(len(mapMAddrToObjCode[machineCodes[i]])>0): co+=1 dr.append(mapMAddrToObjCode[machineCodes[i]]) else: co+=1 dr.append(mapMAddrToObjCode[machineCodes[i]]) if(len(dr)): writeTof2(stradr,dr) f2.write("E^") x=lines[-1][1] if(x=='END'): LastinsAddr="" Lastins=lines[-1][2] for i in range(len(lines)): if(lines[i][0]==Lastins): LastinsAddr=machineCodes[i] t="0"*(6-len(LastinsAddr)) f2.write("%s%s"%(t,LastinsAddr)) else: Lastins="0"*6 f2.write("%s"%(Lastins))
b6635fc1af31a8138fd5efb61bcd59c9f296f63d
RileyWaugh/ProjectEuler
/Problem2.py
863
4.0625
4
#Problem: find sum of all even fibonacci numbers under 4,000,000 (sum of 0,2,8,34, etc #The key thing to realize is that even fibonacci numbers occur every three terms: (0),1,1,(2),3,5,(8),13,21,(34), #this makes sense: even, odd, (even+odd)=odd, (odd+odd)=even, (odd+even)=odd, (even+odd)=odd, (odd+odd)=even, etc def genFib(x): #generates a list of all fibonacci numbers under x, defined as f(0)=0, f(1)=1, f(x)=f(x-1)+f(x-2) fiblist=[] fiblist.append(0) fiblist.append(1) end = 1 while (fiblist[end]+fiblist[end-1]) < x: fiblist.append(fiblist[end]+fiblist[end-1]) end += 1 return fiblist def main(): sum = 0 ctr = 0 fiblist = genFib(4000000) #gen the fibonacci list #print(fiblist[6]) while ctr < len(fiblist): #go through every third term sum += fiblist[ctr] ctr += 3 #hit every third (even) term print(sum) main()
dad724d67b93789b50dcb655dd0d614ca5613f17
gabriellaec/desoft-analise-exercicios
/backup/user_313/ch39_2020_04_12_17_28_14_008686.py
663
3.5
4
termos = [] for n in range(1,999): conta = 0 lista = [0] lista[0] = n while True: if n % 2 == 0: n = n/2 lista.append(n) if n == 1: break else: n = n*3+1 lista.append(n) if n == 1: break termos.append(len(lista)) #print('Collatz para numero {} gerou uma sequencia com {}'.format(lista[0],len(lista))) for i in range(0,len(termos)): a = max(termos) if termos[i] == a: #print ('O numero que gerou a maior sequencia foi {} com uma sequencia de {}'.format(i+1,a)) print(i+1)
5654e8ef93926784e98a2b9b542c18cfa5dab642
theparadoxer02/Data-Structure-and-Algo
/spoj/basics/longest_substring.py
361
3.84375
4
def lstr(string): substring = string[0] oldsubstring = '' for i, char in enumerate(string[1:]): if ord(char) >= ord(string[i]): substring += char else: if len(substring) > len(oldsubstring): oldsubstring = substring substring = char print(oldsubstring) sub = input() lstr(sub)
1a379787c65172d8edd5d9a24f47b6f9b7bce25e
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/1da3f93df4ad4c9dafc527057396bd95.py
466
3.6875
4
def word_count(input): input = input.split() words = [] count = [] for item in input: index=0 newWord=True for word in words: if item == word: count[index]+=1 newWord=False index+=1 if newWord: words.append(item) count.append(1) output = dict(zip(words,count)) return output
782af31d67c20f4b3b7d03b4ad283df4baa296fb
hoklavat/beginner-python
/08_Tuple.py
344
4.125
4
#08- Tuple tuple1 = () print(type(tuple1)) tuple1 = (9) print(type(tuple1)) tuple1 = (1, 2, 3, 4, 5) print(type(tuple1)) print(tuple1[1]) #tuple1[1] = 0 Error: unmutable elements (a, b, c, d, e) = tuple1 print(a) print(len(tuple1)) print(max(tuple1)) print(min(tuple1)) print(tuple1 + (1 ,2 ,3)) print(tuple1 * 2) print(tuple1[3:5]) del tuple1
70e5f42d8e5d2fdcab28947613853517795c2ad7
tahmid-tanzim/problem-solving
/Intervals/meeting-rooms.py
1,331
3.8125
4
#!/usr/bin/python3 # https://leetcode.com/problems/meeting-rooms/ # https://www.lintcode.com/problem/920/ from typing import List """ Description Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. """ class Solution1: # Brute Force # Time Complexity - O(n log(n)) def canAttendMeetings(self, intervals: List[List[int]]) -> bool: intervals.sort() for i in range(len(intervals) - 1): if intervals[i][1] > intervals[i + 1][0]: return False return True if __name__ == "__main__": inputs = ( { "intervals": [[0, 30], [5, 10], [15, 20]], "expected": False }, { "intervals": [[5, 8], [9, 15]], "expected": True }, ) obj = Solution1() test_passed = 0 for idx, val in enumerate(inputs): output = obj.canAttendMeetings(val["intervals"]) if output == val['expected']: print(f"{idx}. CORRECT Answer\nOutput: {output}\nExpected: {val['expected']}\n") test_passed += 1 else: print(f"{idx}. WRONG Answer\nOutput: {output}\nExpected: {val['expected']}\n") print(f"Passed: {test_passed:3}/{idx + 1}\n")
7fb413b55914552cce54e476d433158373619966
Imperial-visualizations/Legacy_server
/visuals_T/examples/plotly.js/translator_examples/anim_3d.py
1,411
3.640625
4
""" Example to create moving 3D sine and cosine spiral. """ from translator.statics import Scatter3D, Document from translator.interaction import Animate import numpy as np # Creating some pretty spirals x = [] y = [] z = [] a = [] b = [] c = [] for t in range(0, 314): x.append(list(np.linspace(-np.pi, np.pi, 50))) y.append(list(np.sin(np.array(x[t]) + t/10))) z.append(list(np.cos(np.array(x[t]) + t/10))) a.append(list(np.linspace(-2, 2, 20))) b.append(list(np.sin(np.array(a[t]) - t/40))) c.append(list(np.cos(np.array(a[t]) - t/40))) # Drawing static 3D line/scatter plots line = Scatter3D(x=x, y=y, z=z, div_id="scatter", mode="markers", marker_size=4, line_color='blue', name='spiral') line.plot(x=a, y=b, z=c, type="scatter3d", name='spiral2', mode="lines", marker_size=2, line_color='red') line.show(xaxis_range=[-np.pi, np.pi], xaxis_title="x", xaxis_titlefont_size=18, zaxis_range=[-1, 1], z_axis_title="z", yaxis_range=[-1, 1], yaxis_title="y", title="3D Animated Sine/Cos Wave Example") # Animating static plots animation = Animate(line, x="x0", y="y0", z="z0") animation.animate(x="z1", y="y1", z="x1") animation.remove_repeated_data() animation.show(transition_duration=10, frame_redraw=False, frame_duration=0) # Saving to HTML html = Document(div_id="scatter", width=700, height=500, js_script=animation.script) html.create("3d_multiple_anim_test.html")
310e48c031cc16c034510d47b599b09a97043056
Isterikus/neural_network_lol
/src/neural_network/test2.py
2,133
3.8125
4
from keras.models import Model, Sequential from keras.layers import Input, Dense, Activation from keras.utils import np_utils # utilities for one-hot encoding of ground truth values import numpy batch_size = 50 # in each iteration, we consider 128 training examples at once num_epochs = 20 # we iterate twenty times over the entire training set hidden_size = 10 # there will be 512 neurons in both hidden layers num_train = 60000 # there are 60000 training examples in MNIST num_test = 10000 # there are 10000 test examples in MNIST # wr00, wr01, wr02, wr03, wr04, wr10, wr11, wr12, wr13, wr14 <- input # x: [[10 wrs], [10 wrs], ...] wr1 = [0.43 + (i / 100) for i in range(10)] wr2 = [0.53 - (i / 100) for i in range(10)] X_train = numpy.array([wr1] * 1000 + [wr2] * 1000) X_test = numpy.array([wr2] * 10 + [wr1] * 10) # y: [[bool], [bool], ...] Y_train = numpy.array([1] * 1000 + [0] * 1000) Y_test = numpy.array([0] * 10 + [1] * 10) X_train = X_train.astype("float32") X_test = X_test.astype("float32") Y_train = Y_train.astype("float32") Y_test = Y_test.astype("float32") Y_train2 = np_utils.to_categorical(Y_train, num_classes = 2) # One-hot encode the labels Y_test2 = np_utils.to_categorical(Y_test, num_classes = 2) # One-hot encode the labels inp = Input(shape=(10,)) # Our input is a 1D vector of size 10 hidden_1 = Dense(hidden_size, activation='relu')(inp) # First hidden ReLU layer hidden_2 = Dense(hidden_size, activation='relu')(hidden_1) # Second hidden ReLU layer out = Dense(2, activation='sigmoid')(hidden_2) # Output softmax layer model = Model(input=inp, output=out) # To define a model, just specify its input and output layers model.compile(loss='categorical_crossentropy', # using the cross-entropy loss function optimizer='adam', # using the Adam optimiser metrics=['accuracy']) # reporting the accuracy print(X_train) print('===') print(Y_train2) model.fit(X_train, Y_train2, batch_size=batch_size, epochs=num_epochs) loss_and_metrics = model.evaluate(X_test, Y_test2, batch_size=batch_size) # Evaluate the trained model on the test set! print(loss_and_metrics)
75e180ffc3dea615ae4fd56d16a09656df1ce1f8
dks1018/CoffeeShopCoding
/2021/Code/Python/WebSiteGrab/old/chris_learning.py
338
3.84375
4
Darius = 24 Chris = 23 while Chris <= 26: if Darius > Chris: print("Your a toddler!") elif Chris > Darius: print("Life is out of balance!") else: print("Everyone on the Earth is now on Mars") print("Darius is",Darius,"Years old!") print("Chris is",Chris,"Years old!\n") Chris = Chris + 1
17026073234b9a0c795d2eb3d71dafc24f58064a
Souzanderson/Python_codes
/CADASTRO DE CURRICULO/criabanco.py
449
3.765625
4
import sqlite3 conn = sqlite3.connect('curriculo.db') cursor=conn.cursor() cursor.execute(""" CREATE TABLE pessoa( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome TEXT NOT NULL, ec TEXT, idade TEXT, ender TEXT, city TEXT, fone TEXT, email TEXT, hab TEXT );""") print('tabela criada com sucesso') conn.close()
13869bccdfbc0ffe34cf15fef0595917b2cdad1a
andonyan/Python-Fundamentals
/functions more exercises/tribonacci 2.py
458
4.21875
4
def tribonacci(num): first = 1 second = 1 third = 2 print('1', end=' ') if num == 2: print('1', end=' ') elif num == 3: print('1 2', end=' ') elif num > 3: print('1 2', end=' ') for i in range(3, num): current = first + second + third first = second second = third third = current print(current, end=' ') n = int(input()) tribonacci(n)
4f0e8cfe6c4c90bb1386237fca9c13b79790e2fa
ValyNaranjo/A1_Naranjo_Valery_MetodosNumericos
/Pregunta6.py
610
3.890625
4
import math print("Programa que encuentra el sen(pi/3) y trunca en 50 \n") #Código en grados, en este caso se utilizará el 60 x_deg = float(input("Ingrese el número que desee resolver en grados ")) print("\n") #Código para cambiar el valor a radianes x = math.radians(x_deg) n = int(input("Ingrese el número en el que desee truncar ")) print("\n") sen_x = 0.0 print("{:^2}{:^15}{:^1}".format("Término", "Dato", "Sen(x)")) #Procedimiento de la serie de Taylor for d in range(n): sen_x = sen_x + (-1)**d*x**(2*d+1) / math.factorial((2*d+1)) print("{:^2}{:^15}{:^1}".format(d+1, d, sen_x))
10783a6e8a9330f6c9d9a9f3204707db62a98d51
eugenechernykh/coursera_python
/week8_null_or_not.py
671
4.03125
4
''' https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/9uqay/nol-ili-nie-nol Проверьте, есть ли среди данных N чисел нули. Формат ввода Вводится число N, а затем N чисел. Формат вывода Выведите True, если среди введенных чисел есть хотя бы один нуль, или False в противном случае. ''' print( any( map( lambda x: x == 0, map( lambda x: int(input()), range(int(input())) ) ) ) )
b5fbfb62253bd8f6a027476acb1d1a3cc3d4a0ba
fransikaz/PIE_ASSIGNMENTS
/homework6.py
1,653
4.25
4
''' HOMEWORK # 6: Advance Loops Create a function that takes in two parameters: rows, and columns, both of which are integers. The function should then proceed to draw a playing board with he same number of rows and columns as specified ''' def drawPlayBoard(row, col): if row != col: # Forcing the number of rows and columns to be equal print("Number of rows and columns must be equal!") elif row > 50: # Maximum screen height (rows) print("Maximum height exceeded") elif col > 50: # Maximum screen width (rows) print("Maximum width exceeded") else: for rows in range(row): if rows % 2 == 0: # True for rows 0, 2, and 4 for cols in range(col): if cols % 2 != 0: # True for columns 1 and 3 # prints "|" in cells (0,1),(0,3),(2,1),(2,3),(4,1), and (4,3) print("|", end="") else: # For columns 0, 2, and 4 which returded False # Prints ' ' in cells (0,0),(0,2),(0,4),(2,0),(2,2),(2,4),(4,0),(4,2) and (4,4) print(" ", end="") print() # Prints new line else: # For rows 1 & 3 which returned False for cols in range(col): if rows % 2 != 0: # True for rows 1 & 3 # Prints "-" in rows 1 & 3 in columns 0 to 4 print("-", end="") print() # Prints new line r = int(input("Enter number of rows: ")) c = int(input("Enter number of columns: ")) drawPlayBoard(r, c)
7148f060b1d6688dd8348aec7156d2738794333f
liuluyang/openstack_mogan_study
/myweb/test/checkio/home/Non-unique-Elements-2-Elementary.py
671
3.71875
4
#coding:utf8 ''' 你将得到一个含有整数(X)的非空列表。在这个任务里, 你应该返回在此列表中的非唯一元素的列表。要做到这一点, 你需要删除所有独特的元素(这是包含在一个给定的列表只有一次的元素)。 解决这个任务时,不能改变列表的顺序。例如:[1,2,3,1,3] 1和3是非唯一元素, 结果将是 [1, 3, 1, 3]。 ''' def checkio(data): for i in set(data): if data.count(i)==1: data.remove(i) return data print checkio([1,3,2,3,5]) def checkio(data): return [i for i in data if data.count(i) > 1] print checkio([1,3,2,3,5])
1a70465ba5e8038fc659edf0f0ef92a10c60d5b4
aobo-y/leetcode
/19.remove-nth-node-from-end-of-list.py
1,434
3.59375
4
# # @lc app=leetcode id=19 lang=python3 # # [19] Remove Nth Node From End of List # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: def buffer(): buffer = [None] * (n + 1) node, i = head, 0 while node: buffer[i % (n + 1)] = node node = node.next i += 1 pre = buffer[i % (n + 1)] target = buffer[(i + 1) % (n + 1)] post = target.next target.next = None if pre: pre.next = post head_ = head else: head_ = post return head def pointer(): ptr = None node, i = head, 0 while node: node = node.next i += 1 if i == n + 1: ptr = head elif i > n + 1: ptr = ptr.next if ptr: target = ptr.next ptr.next = target.next head_ = head else: target = head head_ = head.next target.next = None return head_ return pointer() # @lc code=end
cc83801559532757ed190be62da0abb379475532
Rconte/Small-Projects-and-Courses
/Data Camp Course/Cleaning Data/27_drop_duplicates.py
840
4.1875
4
#Dropping duplicate data #Duplicate data causes a variety of problems. From the point of view of performance, they use up unnecessary amounts of memory and cause unneeded calculations to be performed when processing data. In addition, they can also bias any analysis results. #A dataset consisting of the performance of songs on the Billboard charts has been pre-loaded into a DataFrame called billboard. Check out its columns in the IPython Shell. Your job in this exercise is to subset this DataFrame and then drop all duplicate rows. # Create the new DataFrame: tracks tracks = billboard[['year','artist','track','time']] # Print info of tracks print(tracks.info()) # Drop the duplicates: tracks_no_duplicates tracks_no_duplicates = tracks.drop_duplicates() # Print info of tracks print(tracks_no_duplicates.info())
b5aa936e7b7c8ce9ab3c979ef42ac451251ef798
anderd11/CSCI-1100
/Lab1/check1.3.py
313
3.796875
4
base10size = int(input('Disk size in GB => ')) print(base10size) base2size = int((base10size * 10**9)/(2**30)) lost_size = base10size - base2size print(base10size, "in base 10 is actually",base2size,"in base 2,",lost_size,"GB less than advertised.") print("Input: ",base10size) print("Actual: ",base2size)
cd29abaaf25b79cffdd7ba391ae5827216337409
YerardinPerlaza/holbertonschool-higher_level_programming
/0x0B-python-input_output/6-load_from_json_file.py
243
3.71875
4
#!/usr/bin/python3 """create and object from a json file""" import json def load_from_json_file(filename): """create from json""" with open(filename, encoding="utf-8") as myfile: my_obj = json.load(myfile) return my_obj
8894c8e146c2713616b46e9bf16d6fa8fc05e782
head-256/MNA
/lab6/quadratic_spline.py
1,761
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt def quadratic_spline(data): np1 = len(data) n = np1 - 1 X, Y = zip(*data) X = [float(x) for x in X] Y = [float(y) for y in Y] a = [0.0] * n b = [0.0] * n c = [0.0] * n for i in range(1, n): a[i - 1] = (Y[i + 1] - Y[i - 1]) / ((X[i + 1] - X[i - 1]) * (X[i + 1] - X[i])) \ - (Y[i] - Y[i - 1]) / ((X[i] - X[i - 1]) * (X[i + 1] - X[i])) b[i - 1] = (Y[i] - Y[i - 1]) / (X[i] - X[i - 1]) - a[i - 1] * (X[i] + X[i - 1]) c[i - 1] = Y[i - 1] - b[i - 1] * X[i - 1] - a[i - 1] * X[i - 1]**2 spline = [] for i in range(n - 1): spline.append((a[i], b[i], c[i], X[i])) return spline, X[n] def splines_to_plot(spline, xn, grid_res): n = len(spline) per_spline = int(grid_res / n) if per_spline < 2: per_spline = 2 X = [] Y = [] for i in range(n - 1): S = spline[i] x0 = S[3] x1 = spline[i + 1][3] x = np.linspace(x0, x1, per_spline) for xi in x: X.append(xi) Y.append(S[2] + S[1] * xi + S[0] * xi**2) S = spline[n - 1] x = np.linspace(S[3], xn, per_spline) for xi in x: X.append(xi) Y.append(S[2] + S[1] * xi + S[0] * xi**2) return X, Y if __name__ == '__main__': data = [(0.452, 1.252), (0.967, 2.015), (2.255, 4.342), (4.013, 5.752), (5.432, 6.911)] lstX = [x[0] for x in data] lstY = [x[1] for x in data] spline, xn = quadratic_spline(data) X, Y = splines_to_plot(spline, xn, grid_res=1000) plt.title('Quadratic Spline') plt.grid(True) plt.plot(X, Y, 'r-') plt.plot(lstX, lstY, 'ko') plt.show()
6920d8ab1cae282bb11740e0ce3c1802c7ba7c99
iceycc/daydayup
/python/BaseLessnon/timegeekbang.com/func_test3.py
308
3.8125
4
# a * x + b = y def a_line(a,b): def arg_y(x): return a*x+b return arg_y def a_line(a,b): return lambda x: a*x+b return arg_y # a=3 b=5 # x=10 y=? # x=20 y =? # a=5 b=10 line1 = a_line(3, 5) line2 = a_line(5,10) print (line1(10)) print (line1(20)) #def func1( a,b, x)
22c40deb27c75f1bbb0dc7c3bb947e66ba17e23c
addovej-suff/python_alg_gb
/lesson_5/task_1.py
1,919
3.859375
4
# Пользователь вводит данные о количестве предприятий, # их наименования и прибыль за 4 квартал (т.е. 4 числа) # для каждого предприятия. Программа должна определить # среднюю прибыль (за год для всех предприятий) и отдельно # вывести наименования предприятий, чья прибыль выше среднего и ниже среднего. from collections import defaultdict company_count = int(input('Введите количество предприятий: ')) companies = defaultdict(float) for _ in range(company_count): name = input('Название: ') for q in range(4): profit = float(input(f'Квартал {q + 1}: ')) companies[name] += profit # Round to decimal avg = round(sum(companies.values()) / len(companies), 2) above_avg = [key for key, val in companies.items() if val > avg] below_avg = [key for key, val in companies.items() if val < avg] # If profits of all companies will equals then their profits will be equal average profit eq_avg = [key for key, val in companies.items() if val == avg] above_avg_msg = f'Компании с прибылью выше среднего: {", ".join(above_avg)}' \ if above_avg else 'Нет компаний с прибылью выше среднего' below_avg_msg = f'Компании с прибылью ниже среднего: {", ".join(below_avg)}' \ if above_avg else 'Нет компаний с прибылью ниже среднего' print(f'Средняя прибыль за год по всем предприятиям: {avg}') print(above_avg_msg, below_avg_msg, sep='\n') if eq_avg: print(f'Компании с прибылью равной средней: {", ".join(eq_avg)}')
a91c3b2a0bbcfffb418187d8042760fab4592198
porollansantiago/um-programacion-i-2020
/57031-porollan-santiago/tp1/copia_nueva/ej14/ej14.py
1,155
3.890625
4
import re class Words(): def __init__(self): self.get_words() def get_words(self): texto = """ """ for line in open("texto"): texto += line + " " words = {} for word in re.split(" |, |\n", texto): if word not in words and len(word) > 3: words[word] = texto.count(word) self.words = words def fix_size(self): while len(self.words) > 20: min_key = "" for word in self.words: if not min_key: min_key = word elif self.words[word] < self.words[min_key]: min_key = word self.words.pop(min_key) def show(self): while self.words: first = "" for word in self.words: if not first: first = word elif word.lower() < first.lower(): first = word print(first," se repite: ", self.words[first], " veces") self.words.pop(first) if __name__ == "__main__": words = Words() words.fix_size() words.show()
9b54f61bdb8e7da6163c5cdf9425540676a48164
UO250711/Classroom
/PitoneSChool/ex_len4y6.py
265
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- b=int(input("Introduce un numero: ")) num_len = len(str(abs(b))) if num_len>=4 and num_len<=6: print "Tu numero tiene entre 4 y 6 cifras" else: print "Tu numero NO tiene entre 4 y 6 cifras, tiene: " , num_len
b239ecd6ec8942eab599dc56b9b79eb41416aad0
kapitsa2811/leetcode-algos-python
/sort/SelectionSort.py
654
4
4
# Selection Sort - similar to bubble sort but only makes a single exchange per pass through # O(n^2) def SelectionSort(arr): size = len(arr) if size <= 1: return arr #Loop through arr from end to front for i in range(size-1,0,-1): # default high pos as 0 high = 0 for j in range(i+1): if arr[j] > arr[high]: high = j print(arr[high]) #after each pass, must set it in proper place (always at end) arr[high],arr[i] = arr[i],arr[high] print(arr) return arr # Test arr = [3,6,1,0,7,4] print (SelectionSort(arr))
d5c8b082ed261c2e01b595bbe3eb2eb6b4366300
LinLeng/xiaoxiyouran_all
/python2/20180718零基础学习python/Python-From-Zero-to-One/unmd/课时038 类和对象 继承/review002.py
599
4.15625
4
# Summary:定义一个点(Point)类和直线(Line)类,使用getLen方法可以获得直线的长度 # Author: Fangjie Chen # Date: 2017-11-15 import math class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y class Line(Point): def __init__(self, p1, p2): self.x = p1.x - p2.x self.y = p1.y - p2.y self.len = 0 # 计算直线长度 def getLen(self): self.len = math.sqrt(self.x * self.x + self.y * self.y) return self.len
6e6923df7c1e5b4dde2232d2f1596016da9f2caa
ienoob/python-with-algorithm
/sort/heap_sort.py
983
4.0625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 堆排序, 选择排序的一种方法 """ def heap_basic_sort(data): """ :param data: List<Int> :return: """ result = [] build_heap(data) while len(data): d = data[0] result.append(d) dl = data.pop() if len(data): data[0] = dl else: break max_heap(data, 0) return result def build_heap(data): d_len = len(data) for d in range(d_len//2-1, -1, -1): max_heap(data, d) def max_heap(data, i): left = i*2+1 right = i*2+2 d_len = len(data) lagest = i if right < d_len and data[right] > data[lagest]: lagest = right if left < d_len and data[left] > data[lagest]: lagest = left if lagest != i: data[i], data[lagest] = data[lagest], data[i] max_heap(data, lagest) if __name__ == "__main__": dataset = [2, 3, 5, 1, 6] heap_basic_sort(dataset)
088371a751103cf2848cc2cd5ab9ffcd7fa0f04f
epenelope/python-playground
/find-slice-string.py
214
3.859375
4
#slices the number part of the string and converts it to a float before printing the output. text = 'X-DSPAM-Confidence: 0.8475' sp = text.find('0') end = text.find('5') num = text[sp:end+1] print(float(num))
91869f710517ebc2f5db3df6977ec366b2c3eda1
rdghenrique94/Estudos_Python
/Curso_Python/Modulo1/Modulos/ex020.py
411
3.8125
4
#import random from random import shuffle def main(): n1 = str(input("Primeiro Aluno: ")) n2 = str(input("Segundo Aluno: ")) n3 = str(input("Terceiro Aluno: ")) n4 = str(input("Quarto Aluno:")) #names = ("rodrigo", "danilo", "renato", "carlos") lista = [n1, n2, n3, n4] #random.shuffle(lista) shuffle(lista) print("A ordem de apresentação será") print(lista) main()
7a1b87216d114f4a5ba979081d7760be04af08e9
alexparunov/leetcode_solutions
/src/900-1000/_922_sort-array-by-parity-ii.py
482
3.5
4
""" https://leetcode.com/problems/sort-array-by-parity-ii/ """ from typing import List class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: N = len(A) ans = [-1] * N t = 0 for i, n in enumerate(A): if n % 2 == 0: ans[t] = n t += 2 t = 1 for i, n in enumerate(A): if n % 2 == 1: ans[t] = n t += 2 return ans
4aac2bca78613a443c06f497d96e4a16b78d31d1
TheFuzzStone/hello_python_world
/chapter_6/6_10.py
694
4.15625
4
### 6-10. Favorite Numbers: Modify your program from # Exercise 6-2 (page 102) so each person can have more # than one favorite number. Then print each person’s # name along with their favorite numbers. names_and_numbers = { 'alice': [8, 22, 43, 24,], 'bob': [2, 13, 46, 77,], 'carl': [3, 11,], 'dave': [4, 59, 1,], 'earl': [8,], } for name, numbers in names_and_numbers.items(): if len(numbers) < 2: print("\n" + name.title() + "'s favorite number is:") for number in numbers: print(str(number)) else: print("\n" + name.title() + "'s favorite numbers are:") for number in numbers: print(str(number))
5bf7c152d3d76667ca5345091998bd291ecef983
MiltonPlebeu/Python-curso
/Mundo 2/exercícios/desafio39_HoraDoAlistamentoMilitar.py
1,042
3.984375
4
#Faça um programa que leia o ano de nascimento de um jovem e informe, #de acordo com sua idade: # - Se ele ainda vai se alistar ao serviço militar. # - Se é a hora de se alistar # - Se já passou do tempo do alistamento. #Seu programa também deverá mostrar o tempo que falta ou que passou do prazo from datetime import date atual = date.today().year nascimento = int(input('Ano de nascimento ')) idade = atual - nascimento print('Quem nasceu em {} tem {} anos em {}'.format(nascimento, idade, atual)) if idade == 18: print('Você deve se alistar IMEDIATAMENTE, por que completou {} anos'.format(idade)) elif idade < 18: tempo = 18 - idade print('Você ainda não tem 18 anos. Faltam {} anos para o seu alistamento'. format(tempo)) previsao = atual + tempo print('Seu alistamento será em {}'.format(previsao)) elif idade > 18: tempo = idade -18 print('Voce ja deveria ter se alistado ah {} anos'.format(tempo)) previsao = atual - tempo print('Seu alistamento foi em {}'.format(previsao))
09b9da8cc6b45e9ec2674d6b27502edc37f1ffff
AtIasz/ccOW1
/WeekNo1/apple.py
182
4
4
how_much_a_kg=int(input("How much is a kg apple ?")) how_much_apple=int(input("How much kg would you like?")) price=how_much_a_kg*how_much_apple print ("You will pay: " +str(price))
e2efe29f655bdc9ea99ac9e01e81b6955561fc39
gschen/sctu-ds-2020
/1906101032-邹婷/test03.py
807
3.859375
4
# num = int(input("请输入一个数字:")) # if num % 2 == 0: # if num % 3 == 0: # print("这个数字既能被2也能被3整除") # else: # print("这个数字能被2整除,不能被3整除") # else: # if num % 3 == 0: # print("这个数字能被3整除,不能被2整除") # else: # print(这个数字不能被3整除,不能被2整除) # sum = 0 # a = 1 # while(a <= 100): # sum = sum + a # a = a + 1 # print(sum) # while (a == 1): # print("无限循环中!!!") # count=0 # while count < 5: # print(str(count),"<5") # count = count+1 # else: # print(str(count)+"=5") # list1=[1,2,3,4,5] # for i in list1: # print(i) for i in range(5): print(i) for i in range(0,11,2): print(i) print(list(range(5)))
aa7158b2f5880d0951776dcdff6232c61075e214
garvsac/Matchstick-problem-AI
/driver.py
1,127
3.609375
4
#Garv Sachdeva #2015B4A70551P #Driver file import math from function2 import * from generate2 import * from GUI2 import * import turtle size=4 #% of squares randomly generated percentage = 70 #no of Squares in final state final = 6 #arr = [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0] #cell = [0,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0] cell = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] arr=initial_state_generator1(percentage,cell) #uncomment for checking bfs #ans=bfs(cell,final) #dfs solution is faster in this case ans=dfs(cell,final) path = generatehelper( ans ) #print(path) #draws the randomly generated configuration draw(turtle.Turtle(),arr, "white") for i in range(40): if(arr[i]==1 and path[i]==0): path[i]=1 else: path[i]=0 #comment this line if turtle hangs input("Press Enter to continue...") #deletes the edges not present in the final configuration #does not delete in the correct sequence drawdel(turtle.Turtle(),path, "black" , pathcost(cell,ans),currcell(cell)) print("Click on turtle window to exit") turtle.Turtle().screen.exitonclick()
8076aafbb59addbd02c8c6b79418c05f7b5d5e7d
Lucar-Yulasise/Python-Studen
/Python学习/运算符与表达式.py
1,829
4.1875
4
# 什么是表达式? # 由变量、常量和运算符组成的式子,称为表达式 # 一条语句:见到一个分号代表一条语句的结束,如果一条语句只占一行,分号可以省略。 # 如果一行上面有多条语句,每条用分号隔开。 # 一行语句 a = 100;b = 200;print(a);print(b) print(a) #运算符 # 数学运算符: #功能:进行数学运算 # + 两数相加 # - 两数相减 # * 两数相乘 # / 两数相除 # ** 求幂 # // 取证 # % 取余(取模) print(13%4) print(-13%(-4)) print(-13 % 4) # 赋值运算符 # 基本的赋值运算符 = # 将赋值符号右边的内容赋值给左边的变量 # 组合运算符 # += -= *= /= //= %= **= # a += b # a = a+b # 比较运算符 # == != > < <= >= # 逻辑运算符 # x,y 可以出现boolean的值的表达式或x,y本身就是boolean值 # and 逻辑与 x and y 当整体都为True,整体才为True # or 逻辑或 x or y 当x与y都False,整体为False # not # 成员运算符 in 在指定范围内能够找到该元素,返回True ,否则为False # not in 找不到指定元素 list = [1,3,4,3,4,54,5] print(2 in list) print(2 not in list) # 身份运算符 # is 判断两个变量是否是否引用同一内存地址 # not is a = 23 b = a print("---------------------------------------") print(a is b) print(a is not b) # 位运算符 # & 按位与运算:参与运算的两个值对应位置都为1时,该位置为1,否则为0 # | 按位或运算:参与运算的两个值都为0时为0,否则为1 # ^ 按位异或运算: 参与运算的两个值有且只有一个为1时,该位置为1 # ~ 按位取反运算: # << 左移:二进制位 # >> 右移: a = 10 b = 7 print(a & b) print(~a) print(a << 2) print(a >> 2) # 运算符优先级
2e9fe0c371423d78eafa89bea01f4b9fa0eac038
llm123456/weiruan
/TwoStack.py
558
4
4
#双头栈 class TwoStack(): def __init__(self,arr=None): if not arr: self.arr = [] else: self.arr = arr def l_push(self,value): self.arr.insert(0,value) def l_pop(self): if len(self.arr) > 0: del self.arr[0] def r_push(self,value): self.arr.append(value) def r_pop(self): if len(self.arr) > 0: del self.arr[len(self.arr)-1] def __str__(self): return '['+','.join([str(x) for x in self.arr])+']' if __name__ == '__main__': a = TwoStack() a.l_push(1) # a.l_pop() # a.l_push(2) # a.r_push(3) # a.r_pop() print(a)
da82ed136ec38909750831ace0cbbf35d81ae116
baton10/lesson_002
/Lesson_in_class_002/010_lines.py
1,248
4.15625
4
# Вывести последнюю букву в слове word = 'Архангельск' print(word[-1]) # Вывести количество букв а в слове word = 'Архангельск' print(len(word)) # Вывести количество гласных букв в слове vowels = 'аеёиоуыэюя' # предлагают решать через vowels = u'аеёиоуыэюя'. u - unicode. Преобразование строки в u word = 'Архангельск' vowels = sum(1 for text in word.lower() if text in vowels) print(vowels) # Вывести количество слов в предложении sentence = 'Мы приехали в гости' print(len(sentence.split())) # Вывести первую букву каждого слова на отдельной строке sentence = 'Мы приехали в гости' sentence = sentence.split(' ') print(sentence[0][0]) print(sentence[1][0]) print(sentence[2][0]) print(sentence[3][0]) # написать оптимальнее с циклом, типа мы не знаем кол-во слов # Вывести усреднённую длину слова. sentence = 'Мы приехали в гости' # ???
52e9776b437b99e7db698c7fe4bf0e5dd5471347
KojiNagahara/Python
/TextExercise/13-2/test.py
2,391
3.5625
4
"""動的計画法の実装をテストするモジュール。""" import random import time from item import Item from rootedBinaryTree import max_value, max_value_fast def build_items(): names = ['時計', '絵画', 'ラジオ', '花瓶', '本', 'PC'] values = [175, 90, 20, 50, 10, 200] weights = [10, 9, 4, 2, 1, 20] items = [] for i in range(len(values)): items.append(Item(names[i], values[i], weights[i])) return items def small_test(chooser): """小規模テスト""" start = time.perf_counter() items = build_items() value, taken = chooser(items, 20) elapsed = time.perf_counter() - start for item in taken: print(item) print(f'取得したItemの総価値:{value}') print(f'処理にかかった時間:{elapsed}') def build_many_items(number_of_items, max_value, max_weight): """big_test用のデータ作成自動化""" items = [] for i in range(number_of_items): items.append(Item(str(i), random.randint(1, max_value), random.randint(1, max_value))) return items def big_test(items): """大規模テスト。ただあまり大規模になると結果の視認性が悪くなるので少し表示に工夫したい""" start = time.perf_counter() print('対象Item:') for item in items: print(item) value, taken = max_value(items, 100) elapsed = time.perf_counter() - start print('取得Item:') for item in taken: print(item) print(f'取得したItemの総価値:{value}') print(f'処理にかかった時間:{elapsed}') def big_test_fast(items): """大規模テスト。small_testと同様の実装方針だとmax_value_fastのキャッシュが残ってしまってできなかった""" start = time.perf_counter() print('対象Item:') for item in items: print(item) value, taken = max_value_fast(items, 100, {}) elapsed = time.perf_counter() - start print('取得Item:') for item in taken: print(item) print(f'取得したItemの総価値:{value}') print(f'処理にかかった時間:{elapsed}') print('small_testの実施結果') small_test(max_value) print('高速化したアルゴリズムを用いたsmall_testの実施結果') small_test(max_value_fast) items = build_many_items(20, 10, 10) print('big_testの実施結果') big_test(items) print('高速化したアルゴリズムを用いたbig_testの実施結果') big_test_fast(items)
bf78f6e2d06c69a2508fe63e4dd19735654e26c1
malikxomer/static
/8.Boolean Algebra/2.Logical operators.py
367
3.65625
4
#AND operator 5 and 5 #True True and True #True True and False #False johnny_homework=True throw_out_garbage=True if johnny_homework and throw_out_garbage: #Returns true print('hello') #OR operator poison = False pizza = True pizza or poison #True #NOT operator not False #True not True #False not(True or False) #False
28472086d17d0b134ee9934d5af5d26d267ea7ae
roshanpiu/PythonOOP
/19_Method_Overloading.py
1,537
3.96875
4
'''Method Overloading''' #inherit : use parent class definition classmethod #overide/overload: provide child's own version of a method #extend: do work in addtion to that in parent's method #provide: implement abstract method that parent requires import abc class GetSetParent(object): '''GetSetParent''' __metaclass__ = abc.ABCMeta def __init__(self, value): self.val = 0 def set_val(self, value): '''set_val''' self.val = value def get_val(self): '''get_val''' return self.val @abc.abstractmethod def showdoc(self): '''showdoc''' return class GetSetInt(GetSetParent): '''GetSetInt''' def set_val(self, value): if not isinstance(value, int): value = 0 super(GetSetInt, self).set_val(value) def showdoc(self): print 'GetSetInt object ({0}), only accepts integer values'.format(id(self)) class GetSetList(GetSetParent): '''GetSetList''' def __init__(self, value = 0): self.vallist = [value] def get_val(self): return self.vallist[-1] def get_vals(self): '''get_vals''' return self.vallist def set_val(self, value): self.vallist.append(value) def showdoc(self): print 'GetSetList object, len {0}, store history of values set'.format(len(self.vallist)) X = GetSetInt(3) X.set_val(5) print X.get_val() X.showdoc() GSL = GetSetList(5) GSL.set_val(10) GSL.set_val(20) print GSL.get_val() print GSL.get_vals() GSL.showdoc()
7577e3a943e4c952e224ca348705fe280800add9
eriksylvan/PythonChallange
/10/10.py
783
3.5625
4
# http://www.pythonchallenge.com/pc/return/bull.html # a = [1, 11, 21, 1211, 111221] def nextInSequence(numstr): next = [] # print("Sekvens: ",numstr) # print(len(numstr)) pos = 0 ch = numstr[pos] count = 0 for j in numstr: if j == ch: count = count + 1 else: # print("count: {}_{}".format(count, ch)) next.append([count, ch]) count = 1 ch = j else: # print("count: {}_{}".format(count, ch)) next.append([count, ch]) result = '' for e in next: for f in e: result += str(f) return result a=["1"] for i in range(31): a.append(nextInSequence(a[i])) print("Number: ", a[30]) print("Answer: len(a[30])=", len(a[30]))
3aae620ec0ca2a0e42813ec9447e0cbf6fc48a02
Dale90r/cnpython
/checkpinandbalance.py
432
3.75
4
def dispense_cash(entered_pin, requested_amount, balance): pin = 1234 balance = 300 if entered_pin == pin and requested_amount < balance: print('Pin is correct, requested amount {} balance is {}'.format(requested_amount, balance)) else: requested_amount > balance print("insufficient funds or incorrect pin") dispense_cash(1235, 20, 300)
46637a1c9fcb73b17a1be05f43f68c81c024a362
lucasayres/python-tools
/tools/sha256_file.py
397
3.78125
4
# -*- coding: utf-8 -*- import hashlib def sha256_file(file): """Calculate SHA256 Hash of a file. Args: file (str): Input file. Retruns: str: Return the SHA256 Hash of a file. """ sha256 = hashlib.sha256() with open(file, 'rb') as f: for block in iter(lambda: f.read(65536), b''): sha256.update(block) return sha256.hexdigest()
e60e3e99a1b9e5a7bcc14959bb1c957464bc2a0c
ManibalaSinha/Python
/4.7.2argument.py
597
3.9375
4
# *name: receives a tuple.(consists number of values) # when a final parameter of the form **name is present, it receives a dictionary. # *name must occur before **name def cheeseshop(name, *arguments, **keywords): print("Do you have any ", name, "?") print("I'm sorry, we're all out of", name) for arg in arguments: print(arg) print("-" * 40) for kw in keywords: print(kw, ":", keywords[kw]) cheeseshop("Limburger", "it's very runny, sir.", "it's really very, VERY runny, sir. ", shopkeeper="Michael John", client="John Smith", sketch="cheese Shop sketch", nme="mani")
9ea6eb07f066bed0b90f7d193d2430b5f94bd844
Liu-Rundi-SDUWH/Applied-Time-Series-Analysis-in-Python
/作业二/pythonCode/3-Optimization.py
4,688
3.6875
4
''' Optimization with Python ''' import numpy as np import matplotlib.pylab as plt from scipy.optimize import minimize np.random.seed(1) n = 100 x = 1+7*np.random.rand(n) y = 1*np.random.randn(n) + 0.8 * x plt.plot(x,y,'o') plt.show() from scipy.optimize import minimize def myfu(args): x , y = args # v = (y - b*x)*(y - b*x) v = lambda b: np.sum((y - b*x)*(y - b*x)) return v args = (x,y) x0 = np.asarray((1)) # 初始猜测值 res = minimize(myfu(args), x0, method='SLSQP') print(res.fun) print(res.success) print(res.x) def myfu(args): x , y = args # v = (y - b*x)*(y - b*x) v = lambda b: np.sum((y - b*x)*(y - b*x)) # v = lambda b: np.sum(abs(y - b * x)) return v args = (x,y) x0 = np.asarray((1)) # 初始猜测值 res = minimize(myfu(args), x0, method='SLSQP') print(res.fun) print(res.success) print(res.x) ''' Exercise (unidimensional) ''' import numpy as np import matplotlib.pylab as plt np.random.seed(1224) x = [i/100 for i in range(1,101)] x = np.sin(np.array(x)) b = np.random.rand(1) y = -b *x + 0.03*(np.random.randn(len(x))) plt.plot(x,y,'ro') plt.show() def myfu(args): x , y = args v = lambda b: -(np.sum((y - b*x)*(y - b*x))) return v def con(args): bmin, bmax = args cons = ({'type': 'ineq', 'fun': lambda b: b - bmin},{'type': 'ineq', 'fun': lambda b: -b + bmax}) return cons args = (x,y) x0 = np.asarray((1)) # 初始猜测值 args1 = (-14,14) cons = con(args1) res = minimize(myfu(args), x0, method='SLSQP',constraints=cons) print(res.fun) print(res.success) print(res.x) np.random.seed(1224) x = [i/100 for i in range(1,101)] x = np.sin(np.array(x)) b = np.random.rand(1) y = -b *x + 0.03*(np.random.randn(len(x))) plt.plot(x,y,'ro') # plt.show() def myfu(args): x , y = args v = lambda b: -(np.sum((y - b*x)*(y - b*x))) return v def con(args): bmin, bmax = args cons = ({'type': 'ineq', 'fun': lambda b: b - bmin},{'type': 'ineq', 'fun': lambda b: -b + bmax}) return cons args = (x,y) x0 = np.asarray((1)) # 初始猜测值 args1 = (-14,14) cons = con(args1) res = minimize(myfu(args), x0, method='SLSQP',constraints=cons) print(res.fun) print(res.success) print(res.x) def fun(args): a, b = args v = lambda x: (a + x[0])**2 + (b + x[1])**2 return v # 定义常量值 args = (-2,4) # a,b,c,d # 设置初始猜测值 x0 = np.asarray((1,3)) res = minimize(fun(args), x0, method='SLSQP') print(res.fun) print(res.success) print(res.x) from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() #定义新的三维坐标轴 ax3 = plt.axes(projection='3d') #定义三维数据 xx = np.arange(-5,10,15/50) yy = np.arange(-11,2,13/50) X, Y = np.meshgrid(xx, yy) # print(X) Z = (-2+X)**2 + (4+Y)**2 #作图 ax3.plot_surface(xx,yy,Z,cmap='rainbow') # ax3.contour(xx,yy,Z, offset=-2,cmap='rainbow') #等高线图,要设置offset,为Z的最小值 plt.show() from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D #定义坐标轴 fig4 = plt.figure() ax4 = plt.axes(projection='3d') #生成三维数据 xx = np.arange(-5,5,0.1) yy = np.arange(-5,5,0.1) X, Y = np.meshgrid(xx, yy) Z = np.sin(np.sqrt(X**2+Y**2)) #作图 ax4.plot_surface(X,Y,Z,alpha=0.3,cmap='winter') #生成表面, alpha 用于控制透明度 ax4.contour(X,Y,Z,zdir='z', offset=-3,cmap="rainbow") #生成z方向投影,投到x-y平面 ax4.contour(X,Y,Z,zdir='x', offset=-6,cmap="rainbow") #生成x方向投影,投到y-z平面 ax4.contour(X,Y,Z,zdir='y', offset=6,cmap="rainbow") #生成y方向投影,投到x-z平面 #ax4.contourf(X,Y,Z,zdir='y', offset=6,cmap="rainbow") #生成y方向投影填充,投到x-z平面,contourf()函数 #设定显示范围 ax4.set_xlabel('X') ax4.set_xlim(-6, 4) #拉开坐标轴范围显示投影 ax4.set_ylabel('Y') ax4.set_ylim(-4, 6) ax4.set_zlabel('Z') ax4.set_zlim(-3, 3) plt.show() from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np n_radii = 8 n_angles = 36 radii = np.linspace(0.125, 1.0, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) x = np.append(0, (radii * np.cos(angles)).flatten()) y = np.append(0, (radii * np.sin(angles)).flatten()) z = np.sin(-x * y) fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True,cmap="rainbow") plt.show()
42291f05be5e674c88275383214f4e18ffd65ec4
joseph-leo/Python-Repositories
/Real-Python/invest.py
382
3.734375
4
def invest(amount, rate, time): print('principal amount:', '$' + str(amount)) print('annual rate of return:', str(rate)) float(amount) float(rate) for i in range(1, time + 1): amount = amount + (amount * rate) yearCount = i print('year', str(yearCount) + ':', '$' + str(amount)) invest(100, .05, 8) invest(2000, .025, 5)
11ae02c8c254786e81d7b85e0f8779ec53f94e64
sadOskar/courses
/lesson_10/math_funcs.py
202
3.859375
4
def sum_numbers(numbers): total = 0 for num in numbers: total += num return total def len_numbers(nums): total = 0 for num in nums: total += 1 return total
d0bd653d6f58f146af2b37be406b1a37e4613b60
aboyd20/python-exercises
/loop_vs_recursion.py
2,536
3.984375
4
def sumEvenLoop( n ): ''' return sum of even numbers from 0 to n; return 0 for n < 1 ''' total = 0 # identity for addition for i in range( 0, n+1, 2 ): total += i return total def sumEvenRecursive( n ): ''' return sum of even numbers from 0 to n; return 0 for n < 1 ''' print(n) if n < 1: # base case return 0 elif n%2 != 0: # recursive case return sumEvenRecursive( n-1 ) else: # recursive case: total = current n + remaining even integers < n return n + sumEvenRecursive( n-2 ) def prodLoop( lst ): ''' return product of numbers in lst; return 1 if lst is empty ''' prod = 1 for num in lst: prod *= num return prod def prodRecursive( lst ): ''' return product of numbers in lst; return 1 if lst is empty ''' if not lst: # lst == [] base case return 1 elif len( lst ) == 1: # base case return lst[ 0 ] else: # recursive case: prod = next item * product of remaining items return lst[0] * prodRecursive( lst[ 1: ] ) def factorialLoop( n ): ''' return factorial of number >= 0 ''' if n < 0: print( 'n must be a number >= 0' ) return fact = 1 for i in range( 2, n+1 ): fact = fact * i return fact def factorialRecursive( n ): 'return factorial of number >= 0' if n < 0: print( 'n must be a number >= 0' ) return if n == 0: # base case 0! = 1 return 1 else: # recursive case: n! = n * (n-1)! return n * factorialRecursive( n - 1 ) def palindromeLoop( word ): ''' return True if word is a palindrome; otherwise False ''' for i, char in enumerate( word ): if char != word[ -i-1 ]: return False return True def palindromeRecursive( word ): ''' return True if word is a palindrome; otherwise False ''' if len( word ) < 1: # word == '' base case return True else: if word[ 0 ] == word[ -1 ]: # recursive case: if first and last character match, is middle a palindrome return palindromeRecursive( word[ 1:-1 ] ) else: # if first and last character do not match, return false return False
d1a33cf87444dcf13122ffadc9d29173c8d387aa
smallgreycreatures/kth-programming1labs
/Lab3/lab3-3.py
1,622
3.71875
4
def is_prime(tal): # Funktionen returnerar True respektive False beroende på om "tal" är ett primtal primlist = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97) new_prime = [101] if tal == 2: return True # Sortera ut tal som är delbara med 2 eller lika med 1 if tal % 2 == 0 or tal == 1: return False # Sortera ut tal vi redan vet är primtal if tal in primlist or tal in new_prime: return True # Loopa från det största värdet i new_prime till värdet tal för att få med alla primtal därimellan, skippa jämna tal for i in range(new_prime[-1], tal+2, 2): # Loopa antalet tal som finns i primlist och new_prime for j in range(0, len(primlist) + len(new_prime)+1): # Så länge antalet varv är mindre än längden på primlist, utvärdera om talet är delbart med något i primlist if j < len(primlist): if tal % primlist[j] == 0: return False # Så länge antalet varv i < längden på primlist+new_prime, utvärdera om delbart med något i listorna elif j <= len(primlist) + len(new_prime): if tal % new_prime[j - len(primlist)-1] == 0: return False else: new_prime.append(j) return True tal1 = int(input("Från vilket tal: ")) tal2 = int(input("Till vilket tal: ")) print("Primtalen från", tal1, "till", tal2, "är:") for n in range(tal1, tal2): if is_prime(n): print(n)
56bdba404879c12714710415d2cd999239ad1ae1
ralsouza/python_object_oriented_programming
/t05_dunder_methods.py
1,317
4.4375
4
class Employee: """My employee class.""" # Instance variable. raise_amt = 1.04 # This is the constructor. def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + "@company.com" def full_name(self): return "{} {}".format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amt) def __repr__(self): """A string to recreate an object.""" return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay) def __str__(self): """Return the full name and e-mail.""" return "{} - {}".format(self.full_name(), self.email) def __add__(self, other): """Combine salaries of two employees, if comment this method an error will occur.""" return self.pay + other.pay def __len__(self): """Return count of full name.""" return len(self.full_name()) emp1 = Employee(first="Rafael", last="Lima", pay=50000) emp2 = Employee(first="Test", last="User", pay=60000) print(emp1 + emp2) print(emp1) print(emp1.__repr__()) print(emp1.__str__()) print(1+2) print(int.__add__(1,2)) print(str.__add__("a", "b")) print(len("test")) print("test".__len__()) print(len(emp1))
e5c3f873b8516359b51e7f5cb688645258668ed5
villancikos/realpython-book2
/sql/insert_cars.py
298
3.609375
4
import sqlite3 with sqlite3.connect('cars.db') as connection: c = connection.cursor() cars = [('Ford', 'Malibu', 2010), ('Ford', 'Mustang' , 2015), ('Ford', 'GT', 2020), ('Honda', 'Civic', 2010), ('Honda', 'Accord', 2010)] c.executemany("INSERT INTO inventory VALUES(?,?,?)",cars)