blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
7907574293ccefef00b3a19517699f3b97caf46c
IvanPLebedev/TasksForBeginer
/Task8.py
480
3.953125
4
''' Напишите проверку на то, является ли строка палиндромом. Палиндром — это слово или фраза, которые одинаково читаются слева направо и справа налево ''' def polindrom(string): return string == string[::-1] a = 'asdfdsa' b = 'reewer' for x in [a,b]: if polindrom(x): print(x,': polindrom') else: print(x,': don,t polindrom')
e804e54379de9827b7a521ef0627afbc270982bd
agin0634/my-leetcode
/solution-python/1000-1499/1013-partition-array-into-three-parts-with-equal-sum.py
412
3.5
4
class Solution(object): def canThreePartsEqualSum(self, A): """ :type A: List[int] :rtype: bool """ target = sum(A)/3 temp,part = 0,0 for a in A: temp += a if temp == target: temp = 0 part += 1 if part >= 3: return True else: return False
b8a84b7f2c8fa026b8004ae443a465e6e12cb8e4
agin0634/my-leetcode
/solution-python/0000-0499/0143-reorder-list.py
958
3.890625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. """ if not head or not head.next: return head stack = [] while head.next.next: stack.append(head.next.val) head.next = head.next.next r = temp = ListNode(0) c = 0 while stack: if c == 0: n = stack[0] del stack[0] temp.next = ListNode(n) temp = temp.next c = 1 else: n = stack.pop() temp.next = ListNode(n) temp = temp.next c = 0 head.next.next = r.next
4ace81cf22287a59177ccc3b70b5bb1a258115d3
agin0634/my-leetcode
/solution-python/0000-0499/0019-remove-nth-node-from-end-of-list.py
624
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ temp, size = head, 0 while temp: size += 1 temp = temp.next l = size - n if l == 0: return head.next res = head for i in range(1,l): head = head.next head.next = head.next.next return res
62e43748e944ce09643e3c4c943e3efe88e9e92b
agin0634/my-leetcode
/solution-python/0500-0999/0500-keyboard-row.py
387
3.5
4
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ roa, res = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')], [] for w in words: word = set(w.lower()) for i in roa: if word.issubset(i): res.append(w) return res
4e5399de763865da945d2157ec2ab5737e104a9e
agin0634/my-leetcode
/solution-python/0000-0499/0113-path-sum-ii.py
761
3.75
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def pathSum(self, root, s): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ res = [] def helper(node, tmp): if not node: return if not node.left and not node.right: tmp += [node.val] if sum(tmp) == s: res.append(tmp) return helper(node.left, tmp + [node.val]) helper(node.right, tmp + [node.val]) helper(root, []) return res
bf92d64a05ccf277b13dd50b1e21f261c5bba43c
NikitaBoers/improved-octo-sniffle
/averagewordlength.py
356
4.15625
4
sentence=input('Write a sentence of at least 10 words: ') wordlist= sentence.strip().split(' ') for i in wordlist: print(i) totallength= 0 for i in wordlist : totallength =totallength+len(i) averagelength=totallength/ len(wordlist) combined_string= "The average length of the words in this sentence is "+str(averagelength) print(combined_string)
0de13dc0bcc711f7dbc68efdfd0aee2cdbaf94af
NikitaBoers/improved-octo-sniffle
/studentsdictionary2.py
618
3.546875
4
import json filename = 'students (1).csv' students= {} with open(filename) as file: file.readline() for line in file: split= line.strip().split(',') other= {} other['LastName']=split [1] other['Adjective']=split[0] other['Email']=split [3] students[split[2]] = other print(students) with open ('studentdictionary.json', 'w' ) as file: json.dump(students, file, indent=4) #adjective, last_name, first_name, email=line.split(',') #students[first_name.strip()]= #other={} #other['LastName']=last_name #other[Adjective]=adjective #other['email']=email
ca820fc2d0a2ee0dee559ca8185ef4ede2620c65
maximrufed/Mirrows
/geoma.py
3,820
3.765625
4
import math eps = 1e-7 class point: x: float y: float def __init__(self, x_init, y_init): self.x = x_init self.y = y_init def set(self, x, y): self.x = x self.y = y def len(self): return math.sqrt(self.x * self.x + self.y * self.y) def normalize(self, len): tek_len = self.len() self.x = self.x / tek_len * len self.y = self.y / tek_len * len def to_arr(self): return [round(self.x), round(self.y)] def rotate(self, angle): x1 = self.x y1 = self.y self.x = x1 * math.cos(angle) - y1 * math.sin(angle) self.y = x1 * math.sin(angle) + y1 * math.cos(angle) def __add__(self, other): return point(self.x + other.x, self.y + other.y) def __sub__(self, other): return point(self.x - other.x, self.y - other.y) def show(self): print("x: " + str(self.x) + " y: " + str(self.y)) def scal(a: point, b: point): # cos return a.x * b.x + a.y * b.y def vect(a: point, b: point): # sin return a.x * b.y - a.y * b.x class otr: def __init__(self, a: point, b: point): self.a = a self.b = b def set(self, a: point, b: point): self.a = a; self.b = b; def to_vec(self): return self.b - self.a class line: def set(self, a, b, c): self.a = a self.b = b self.c = c def __init__(self, p1: point, p2: point): self.a = p2.y - p1.y self.b = p1.x - p2.x self.c = p1.x * (p1.y - p2.y) + p1.y * (p2.x - p1.x) def show(self): print("a: " + str(self.a)) print("b: " + str(self.b)) print("c: " + str(self.c)) def get_angle(a: point, b: point): return math.atan2(vect(a, b), scal(a, b)) def rotate_vector_vector(a: point, b: point): # start_len = b.len() angle = get_angle(a, b) * 2 print("angle: " + str(angle)) a.show() a.rotate(angle) a.show() # b.normalize(start_len) return a def sign(a): if (a < 0): return -1 if (a > 0): return 1 return 0 def check_inter_ray_otr(ray: otr, mir: otr): a = ray.a - mir.a; b = mir.b - mir.a c = ray.b - mir.a return ((vect(a, b) * vect(a, c)) > 0) and (sign(vect(ray.to_vec(), mir.a - ray.a)) != sign(vect(ray.to_vec(), mir.b - ray.a))) def len_pt_line(p: point, o: otr): l = line(o.a, o.b) return ((l.a * p.x + l.b * p.y + l.c) / math.sqrt(l.a * l.a + l.b * l.b)) def inter_point(ray: otr, mir: otr): if not(check_inter_ray_otr(ray, mir)): return -1 else: d1 = len_pt_line(ray.a, mir) d2 = len_pt_line(ray.b, mir) tek_vec = ray.b - ray.a # check for div fo zero tek_vec.normalize(tek_vec.len() * d1 / (d1 - d2)) ray.b = ray.a + tek_vec; return ray def dist_pt_otr(p: point, o: otr): ab = o.b - o.a ba = o.a - o.b ap = p - o.a bp = p - o.b if ((scal(ab, ap) >= 0) and (scal(ba, bp) >= 0)): return abs(len_pt_line(p, o)) else: return min(ap.len(), bp.len()) def inside_pt_otr(p: point, o: otr): ab = o.b - o.a ba = o.a - o.b ap = p - o.a bp = p - o.b if ((scal(ab, ap) >= 0) and (scal(ba, bp) >= 0)): return 0 else: if (ap.len() < bp.len()): return 1 else: return 2 def pt_to_line(a: point, o: otr): return (vect(o.a - a, o.b - a) == 0) def otr_inter(a: otr, b: otr): if (pt_to_line(a.a, b) and pt_to_line(a.b, b)): if (((max(a.a.x, a.b.x) < min(b.a.x, b.b.x)) or ((min(a.a.x, a.b.x) > max(b.a.x, b.b.x)))) or ((max(a.a.y, a.b.y) < min(b.a.y, b.b.y)) or ((min(a.a.y, a.b.y) > max(b.a.y, b.b.y))))): return 0 else: return 1 t = a.b - a.a t2 = b.b - b.a return (sign(vect(t, b.a - a.b)) != sign(vect(t, b.b - a.b))) and (sign(vect(t2, a.a - b.a)) != sign(vect(t2, a.b - b.a))) def line_inter(l1: line, l2: line): return point((l1.b * l2.c - l2.b * l1.c) / (l1.a * l2.b - l2.a * l1.b), (l1.a * l2.c - l2.a * l1.c) / (l2.a * l1.b - l1.a * l2.b)) def perp_line_pt(l: line, p: point): a = line(point(0, 0), point(0, 0)) a.set(-l.b, l.a, -(p.x * -l.b + p.y * l.a)) return a
292ad196eaee7aab34dea95ac5fe622281b1a845
LJ1234com/Pandas-Study
/06-Function_Application.py
969
4.21875
4
import pandas as pd import numpy as np ''' pipe(): Table wise Function Application apply(): Row or Column Wise Function Application applymap(): Element wise Function Application on DataFrame map(): Element wise Function Application on Series ''' ############### Table-wise Function Application ############### def adder(ele1, ele2): return ele1 + ele2 df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) print(df) df2 = df.pipe(adder, 2) print(df2) ############### Row or Column Wise Function Application ############### print(df.apply(np.mean)) # By default, the operation performs column wise print(df.mean()) print(df.apply(np.mean,axis=1)) # operations can be performed row wise print(df.mean(1)) df2 = df.apply(lambda x: x - x.min()) print(df2) ############### Element wise Function Application ############### df['col1'] = df['col1'].map(lambda x: x * 100) print(df) df = df.applymap(lambda x:x*100) print(df)
e45c11a712bf5cd1283f1130184340c4a8280d13
LJ1234com/Pandas-Study
/21-Timedelta.py
642
4.125
4
import pandas as pd ''' -String: By passing a string literal, we can create a timedelta object. -Integer: By passing an integer value with the unit, an argument creates a Timedelta object. ''' print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds')) print(pd.Timedelta(6,unit='h')) print(pd.Timedelta(days=2)) ################## Operations ################## s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ]) df = pd.DataFrame(dict(A = s, B = td)) print(df) ## Addition df['C']=df['A'] + df['B'] print(df) ## Subtraction df['D']=df['C']-df['B'] print(df)
3d9b7186764bfd5dd51a24a6e23769f229b8b9e8
LJ1234com/Pandas-Study
/01-Series.py
1,531
4.03125
4
import pandas as pd import numpy as np ''' Series is a one-dimensional labeled array capable of holding data of any type. The axis labels are collectively called index. A pandas Series can be created using the following constructor: pandas.Series( data, index, dtype, copy) - data: data takes various forms like ndarray, list, constants - index: Index values must be unique and hashable, same length as data. Default np.arrange(n) if no index is passed. - dtype: dtype is for data type. If None, data type will be inferred - copy: Copy data. Default False ''' ################### Create Series ################### # Create an Empty Series s = pd.Series() print(s) # Create a Series from ndarray data = np.array(['a', 'b', 'c', 'd']) s = pd.Series(data) print(s) s = pd.Series(data, index=[10, 11, 12, 13]) print(s) # Create a Series from dict data = {'a': 1, 'b': 2, 'c': 3, 'd': 4} s = pd.Series(data) # Dict keys are used to construct index. print(s) data = {'a': 0., 'b': 1., 'c': 2.} s = pd.Series(data,index=['b','c','d','a']) # Index order is persisted and the missing element is filled with NaN print(s) # Create a Series from Scalar s = pd.Series(5, index=[0, 1, 2, 3]) print(s) ################### Accessing Series ################### # Accessing Data from Series with Position s = pd.Series([1, 2, 3, 4, 5], index=['a','b','c','d', 'e']) print(s) print(s[0]) print(s[[0, 2, 4]]) print(s[:3]) print(s[-3:]) # Accessing Data Using Label (Index) print(s['a']) print(s[['a', 'c', 'd']])
4c4d5e88fde9f486210ef5bd1595775e0adce53c
aiworld2020/pythonprojects
/number_99.py
1,433
4.125
4
answer = int(input("I am a magician and I know what the answer will be: ")) while (True): if answer < 10 or answer > 49: print("The number chosen is not between 10 and 49") answer = int(input("I am choosing a number from 10-49, which is: ")) continue else: break factor = 99 - answer print("Now I subtracted my answer from 99, which is " + str(factor)) friend_guess = int(input("Now you have to chose a number from 50-99, which is: ")) while (True): if friend_guess < 50 or friend_guess > 99: print("The number chosen is not between 50 and 99") friend_guess = int(input("Now you have to chose a number from 50-99, which is: ")) continue else: break three_digit_num = factor + friend_guess print("Now I added " + str(factor) + " and " + str(friend_guess) + " to get " + str(three_digit_num)) one_digit_num = three_digit_num//100 two_digit_num = three_digit_num - 100 almost_there = two_digit_num + one_digit_num print("Now I added the hundreds digit of " + str(three_digit_num) + " to the tens and ones digit of " + str(three_digit_num) + " to get " + str(almost_there)) final_answer = friend_guess - almost_there print("Now I subtracted your number, " + str(friend_guess) + " from " + str(almost_there) + " to get " + str(final_answer)) print("The final answer, " + str(final_answer) + " is equal to my answer from the beginning, " + str(answer))
6f240b1f578b18a0e3572187fa31e2bf5d48f772
a1a1a2a4/100knock
/otani/python/1/05.py
285
3.71875
4
from pprint import pprint def Ngram(string, num): ngram = [0 for i in range(len(string) - num + 1)] # 初期化 for i in range(len(string) - num + 1): ngram[i] = string[i:(i + num)] return ngram string = "ketsugenokamisama" ngram = Ngram(string, 3) pprint(ngram)
d8e1ab0778a17030a2ee03eccba776743384747f
Bolodeoku1/PET328_2021_Class
/group 6 project new.py
503
3.625
4
B_comp = float (input('What is the bit cost?')) CR_comp = float (input('What is the rig cost per hour?')) t_comp = float (input('What is the drilling time?')) T_comp = float (input('What is the round trip time?')) F_comp = float (input('What is the footage drill per bit?')) # convert inputs to numerals # the formula for drilling cost per foot drilling_cost_per_foot =(B_comp + CR_comp * (t_comp + T_comp))/(F_comp) print('The drilling cost per foot is {0:.2f} $' .format (drilling_cost_per_foot))
de46cb4081b386006c47ad7f16849cd0c95d4e30
lamolivier/EPFL-MLBD-Project
/notebooks/helper_functions.py
743
4
4
import pickle def save_to_pickle(var, filename, path_write_data): """ Parameters ---------- var : any python variable variable to be saved filename : string Name of the pickle we will create path_write_data : string Path to the folder where we write and keep intermediate results """ with open(path_write_data + filename + '.pickle', 'wb') as f: pickle.dump(var, f) f.close() def load_pickle(path_data): """ Parameters: ---------- path_data : string Path to the file to be loaded Returns ---------- var : The loaded object """ with open(path_data, 'rb') as f: var = pickle.load(f) f.close() return var
a71c9875f51651370970f8c61280d7305bfad02f
klaundal/lompe
/lompe/model/data.py
12,751
4.03125
4
""" Lompe Data class The data input to the Lompe inversion should be given as lompe.Data objects. The Data class is defined here. """ import numpy as np import warnings class ShapeError(Exception): pass class ArgumentError(Exception): pass class Data(object): def __init__(self, values, coordinates = None, LOS = None, components = 'all', datatype = 'none', label = None, scale = None, iweight = None, error = 0): """ Initialize Data object that can be passed to the Emodel.add_data function. All data should be given in SI units. The data should be given as arrays with shape (M, N), where M is the number of dimensions and N is the number of data points. For example, for 3D vector valued data, M is 3, and the rows correspond to the east, north, and up (ENU) components of the measurements, in that order. See documentation on specific data types for details. The coordinates should be given as arrays with shape (M, N) where M is the number of dimensions and N is the number of data points. For example, ground magnetometer data can be provided with a (2, N) coordinate array with N values for the longitude and latitude, in degrees in the two rows. The order of coordinates is: longitude [degrees], latitude [degrees], radius [m]. See documentation on specific data types for details. You must specify the data type. Acceptable types are: 'ground_mag': Magnetic field perturbations on ground. Unless the components keyword is used, values should be given as (3, N) arrays, with eastward, northward and upward components of the magnetic field perturbation in the three rows, in Tesla. The coordinates can be given as (2, N) arrays of the magnetometers' longitudes and latitudes in the two rows (the radius is then assumed to be Earth's radius), OR the coordinates can be given as (3, N) arrays where the last row contains the geocentric radii of the magnetometers. An error (measurement uncertainty) can be given as an N-element array, or as a scalar if the uncertainty is the same for all data points in the dataset. An alternative way of specifying 'ground_mag', if you do not have full 3D measurements, is to provide it as (M, N) values, where M < 3, and the rows correspond to the directions that are measured. Specify which directions using the components keyword (see documentation for that keyword for details). 'space_mag_fac': Magnetic field perturbations in space associated with field-aligned currents. Unless the components keyword is used, values should be given as (3, N) arrays, with eastward, northward and upward components of the magnetic field perturbation in the three rows, in Tesla. Note that the upward component is not used for this parameter, since field-lines are assumed to be radial and FACs therefore have no vertical field (it must still be given). The coordinates should be given as (3, N) arrays with the longitudes, latitudes, and radii of the measurements in the three rows. 'space_mag_full': Magnetic field perturbations in space associated with field-aligned currents and horizontal divergence-free currents below the satellite. This is useful for low-flying satellites with accurate magnetometers (e.g., Swarm, CHAMP). The format is the same as for 'space_mag_fac'. 'convection': Ionospheric convection velocity perpendicular to the magnetic field, mapped to the ionospheric radius. The values should be given as (2, N) arrays, where the two rows correspond to eastward and northward components in m/s. The coordinates should be given as (2, N) arrays where the rows are longnitude and latitude in degrees. For line-of-sight measurements, the values parameters should be an N element array with velocities in the line-of-sight direction. The line-of-sight direction must be specified as a (2, N) array using the LOS keyword. The (2, N) LOS parameter should contain the eastward and northward components of the line-of-sight vector in the two rows. 'Efield': Ionospheric convection electric field, perpendicular to B and mapped to the ionospheric radius. The values should be given in [V/m], with the same format as for 'convection'. The LOS keyword can be used for this parameter also, if only one component of the electric field is known. 'fac': Field-aligned electric current density in A/m^2. It must be provided as a K_J*K_J element array, where the elements correspond to the field-aligned current density at the Lompe inner grid points, in the order that they will have after a flatten/ravel operation. Values passed to coordinates will be ignored. This parameter is only meant to be used with large-scale datasets or simulation output that can be interpolated to the Lompe model grid. This is different from all the other datatypes used in Lompe. Note ---- One purpose of this class is to collect all data sanity checks in one place, and to make sure that the data which is passed to Lompe has the correct shape, valid values etc. We're not quite there yet, so be careful! :) Parameters ---------- values: array array of values in SI units - see specific data type for details coordinates: array array of coordinates - see specific data types for details datatype: string datatype should indicate which type of data it is. They can be: 'ground_mag' - ground magnetic field perturbation (no main field) data 'space_mag_full' - space magnetic field perturbation with both FAC and divergence-free current signal 'space_mag_fac' - space magnetic field perturbation with only FAC signal 'convection' - F-region plasma convection data - mapped to R 'Efield' - electric field - mapped to R label: string, optional A name for the dataset. If not set, the name will be the same as the datatype. Setting a label can be useful for distinguishing datasets of the same type from different sources (e.g. DMSP and SuperDARN) LOS: array, optional if the data is line-of-sight (LOS), indicate the line-of-sight using a (2, N) array of east, north directions for the N unit vectors pointing in the LOS directions. By default, data is assumed to not be line-of-sight. Note that LOS is only supported for Efield and convection, which are 2D data types. components: int(s), optional indicate which components are included in the dataset. If 'all' (default), all components are included. If only one component is included, set to 0, 1, or 2 to specify which one: 0 is east, 1 is north, and 2 is up. If two components are included, set to a list of ints (e.g. [0, 2] for east and up). NOTE: If LOS is set, this keyword is ignored scale: float, optional DEPRECATED. Use iweight and error instead. Previous description: set to a typical scale for the data, in SI units. For example, convection could be typically 100 [m/s], and magnetic field 100e-9 [T]. If not set, a default value is used for each dataset. iweight: float, optional importance weight of the data ranging from 0 to 1. For example, since ground magnetometer measurements can only indirectly influence the calculation of ionospheric convection via conductance, one might set iweight=0.3 for ground magnetometer data and iweight=1.0 for ionospheric convection measurements. Keep in mind that this weight is directly applied to the a priori inverse data covariance matrix, so the data error is effectively increased by a factor of 1/sqrt(iweight). error: array of same length as values, or float, optional Measurement error. Used to calculate the data covariance matrix. Use SI units. """ self.isvalid = False datatype = datatype.lower() if datatype not in ['ground_mag', 'space_mag_full', 'space_mag_fac', 'convection', 'efield', 'fac']: raise ArgumentError(f'datatype not recognized: {datatype}') return(None) errors = {'ground_mag':10e-9, 'space_mag_full':30e-9, 'space_mag_fac':30e-9, 'convection':50, 'efield':3e-3, 'fac':1e-6} iweights = {'ground_mag':0.5, 'space_mag_full':0.5, 'space_mag_fac':0.5, 'convection':1.0, 'efield':1.0, 'fac':1.0} assert scale is None,"'scale' keyword is deprecated! Please use 'iweight' (\"importance weight\") instead" if error == 0: error = errors[datatype] warnings.warn(f"'error' keyword not set for datatype '{datatype}'! Using error={error}", UserWarning) if iweight is None: iweight = iweights[datatype] warnings.warn(f"'iweight' keyword not set for datatype '{datatype}'! Using iweight={iweight}", UserWarning) self.label = datatype if label is None else label self.datatype = datatype self.values = values if coordinates is not None: if datatype.lower() == 'fac': warnings.warn('Warning: FAC data must be defined on the whole Emodel.grid_J, but this is not checked.', UserWarning) if coordinates.shape[0] == 2: self.coords = {'lon':coordinates[0], 'lat':coordinates[1]} if coordinates.shape[0] == 3: self.coords = {'lon':coordinates[0], 'lat':coordinates[1], 'r':coordinates[2]} else: self.coords = {} assert datatype.lower() == 'fac', "coordinates must be provided for all datatypes that are not 'fac'" self.isvalid = True if np.ndim(self.values) == 2: self.N = self.values.shape[1] # number of data points if np.ndim(self.values) == 1: self.N = self.values.size if (LOS is not None) & (datatype in ['convection', 'efield']): self.los = LOS # should be (2, N) east, north components of line of sight vectors self.components = [0,1] #2021-10-29: jreistad added this to work with how components is used in model.py. Could avoid this slightly non-inututuve value by modifying model.py instead. else: self.los = None if type(components) == str and components == 'all': self.components = [0, 1, 2] else: # components is specified as an int or a list of ints self.components = np.sort(np.array(components).flatten()) assert np.all([i in [0, 1, 2] for i in self.components]), 'component(s) must be in [0, 1, 2]' # make data error: if np.array(error).size == 1: self.error = np.full(self.N, error) else: self.error = error # assign importance weight self.iweight = iweight # check that number of data points and coordinates match: if self.coords['lat'].size != np.array(self.values, ndmin = 2).shape[1]: raise ShapeError('not the same number of coordinates and data points') # remove nans from the dataset: iii = np.isfinite(self.values) if iii.ndim > 1: iii = np.all(iii, axis = 0) self.subset(iii) def subset(self, indices): """ modify the dataset so that it only contains data points given by the passed indices. The indices are 1D, so if the dataset is vector-valued, indices refer to the column index; it selects entire vectors, you can not select only specific components """ self.values = np.array(self.values , ndmin = 2)[:, indices].squeeze() self.error = self.error[indices] for key in self.coords.keys(): self.coords[key] = self.coords[key][indices] if self.los is not None: self.los = self.los[:, indices] # update number of data points: if np.ndim(self.values) == 2: self.N = self.values.shape[1] if np.ndim(self.values) == 1: self.N = self.values.size return self def __str__(self): return(self.datatype + ': ' + str(self.values)) def __repr__(self): return(str(self))
d65ac8ccbf22813eb3be92d127b316cb3b735e9d
tammytdo/SP2018-Python220-Accelerated
/Student/tammyd_Py220/Py220_lesson09/concurrency.py
1,014
4.0625
4
import threading import time import random # simple threading def func(n): for i in range(n): print("hello from thread %s" % threading.current_thread().name) time.sleep(random.random() * 2) # run a bunch of fuctions at the same time threads = [] for i in range(3): thread = threading.Thread(target=func, args=(i+2)) thread.start() threads.append(thread) # start and append thread. for thread in threads: print("Joining thread: ", thread.name) thread.join() # to know when it is done print("all threads finished.") func(10) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` # # race conditions # import threading # import time # class shared: # val = 1 # def func(): # y = shared.val # time.sleep(0.001) # y += 1 # shared.val = y # threads = [] # for i in range(100): # thread = threading.Thread(target=func) # threads.append(thread) # thread.start() # for thread in threads: # thread.join() # print(shared.val)
4c118860c69f31cc8d10182c9f7bb3027c5942be
tammytdo/SP2018-Python220-Accelerated
/Student/tammyd_Py220/Py220_lesson07/assignment7/mailroom_model.py
1,821
4
4
""" Simple database example with Peewee ORM, sqlite and Python Here we define the schema Use logging for messages so they can be turned off """ import logging from peewee import * logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("One off program to build the classes from the model in the database") logger.info("Here we define our data (the schema)") logger.info("First name and connect to a database (sqlite here)") logger.info("The next 3 lines of code are the only database specific code") database = SqliteDatabase("mailroom.db") database.connect() database.execute_sql("PRAGMA foregn_keys = ON") # needed for sqlite only logger.info("Connected to database") class BaseModel(Model): class Meta: database = database class Donors(BaseModel): """ this class defines Donor, which maintains details of someone who has made a donation """ logger.info("Donors class model created") donor_id = CharField(primary_key = True, max_length = 10) #primary_key = True means every person has to have a unique name donor_name = CharField(max_length = 40) donor_city = CharField(max_length = 40, null = True) #donor may have no city donor_phone = CharField(max_length= 13, null = True) #donor may not have/give contact info logger.info("Successfully logged Donors") class Donations(BaseModel): """ this class defines Donations, which maintains details of someone's donation """ logger.info("Donations class model created") donation_amount = DecimalField(decimal_places = 2) donation_date = DateField(formats = "YYYY-MM-DD") donation__donor_id = ForeignKeyField(Donor) logger.info("Successfully logged Donations") database.create_tables([ Donors, Donations, ]) database.close()
053294e9f40e9d67b652c013c84cc443106a6187
obryana/data-science-projects
/Google FooBar/google_fuel_injection.py
975
3.625
4
def peek(num_pellets): operations_peek = 1 while num_pellets % 2 == 0: num_pellets /= 2 operations_peek += 1 return (operations_peek, num_pellets) def answer(num_pellets): num_pellets = int(num_pellets) operations = 0 while num_pellets > 1: if num_pellets % 2 == 0: num_pellets /= 2 operations += 1 else: peek_add = peek(num_pellets+1) peek_sub = peek(num_pellets-1) if peek_add[1] == peek_sub[1]: operations += min(peek_add[0],peek_sub[0]) num_pellets = peek_add[1] else: if peek_add[0] > peek_sub[0]: operations += peek_add[0] num_pellets = peek_add[1] else: operations += peek_sub[0] num_pellets = peek_sub[1] return operations print(answer(47)) print(answer(4)) print(answer(15))
5608d39b85560dc2ea91e943d60716901f5fe88b
longroad41377/selection
/months.py
337
4.4375
4
monthnames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] month = int(input("Enter month number: ")) if month > 0 and month < 13: print("Month name: {}".format(monthnames[month-1])) else: print("Month number must be between 1 and 12")
b84a8ac32b9e866639fdf804a1acc3f561863339
artem-chyrkov/hist-detector
/base/ring_list.py
922
3.609375
4
class RingList: def __init__(self): self._max_size = 0 self._ring_list = [] self._index_to_replace = -1 def init(self, max_size): self._max_size = max_size self.clear() def add(self, x): # TODO optimize if len(self._ring_list) < self._max_size: # usual adding self._ring_list.append(x) else: # len(self._ring_list) == self._max_size --> ring-style adding self._index_to_replace += 1 if self._index_to_replace >= self._max_size: self._index_to_replace = 0 self._ring_list[self._index_to_replace] = x def clear(self): self._ring_list.clear() self._index_to_replace = -1 def get(self): return self._ring_list def get_actual_size(self): return len(self._ring_list) def get_index_to_replace(self): return self._index_to_replace
21219f7ddb8f074e9f811f4c5d3bcdb34712a761
da1x/cs50-2018
/pset6/mario/mario.py
535
3.921875
4
from cs50 import get_int while True: # prompt user height = get_int("Height: ") # Make sure the number is more then 0 and less then 24 if height < 24 and height >= 0: break # Print for i in range(height): # First part for j in range(height - i - 1): print(" ", end="") for k in range(i + 1): print("#", end="") # Middle two spaces for l in range(2): print(" ", end="") # End part for m in range(i + 1): print("#", end="") print("\n", end="")
182e95b294e0c4341a8e6dc9fb90b61885bf2022
ccsourcecode/python-data-analysis
/00原始代码【无笔记纯享版】/00-01-3pandas常用内容速成简记/demo04筛选DataFrame中的数据/demo04-4布尔索引:补充示例/example布尔索引-04-4-1筛最高评分中的最低价格/example布尔索引-04-4-1.py
876
3.59375
4
import pandas as pd from pandas import DataFrame resourceFile = "bestsellers.csv" # 取出表数据 data = pd.read_csv(filepath_or_buffer=resourceFile) # Index(['书名', '作者', '评分', '被查看次数', '价格', '年份', '体裁'], dtype='object') # print(data.columns) # 最高评分“中”的最低价格(基于最高评分接着细粒度筛,千万注意这里不是重新筛) # 筛选数据结果result从原始data开始。深拷贝,不是浅拷贝。 result = data # 筛出最高评分 result = result[result["评分"] == result["评分"].max()] # 在最高评分的基础上,筛出最低价格 result = result[result["价格"] == result["价格"].min()] # 下面这样做是不对的,看似可以实际报错 # result = result[result["评分"] == result["评分"].max()][result["价格"] == result["价格"].min()] # 输出结果 print(result)
f8679f7a1aa887cbd492d94ffdcc54bbc1c05fc1
ccsourcecode/python-data-analysis
/00原始代码【无笔记纯享版】/00-09线性回归预测分析/补充案例/00-09-1单一自变量线性回归预测分析/demo_singleLR1-自热火锅价格销量相关性分析/demo_singleLR1.py
402
3.515625
4
import pandas as pd from pandas import DataFrame # 探究价格与销量的关联系数 # 读取文件 df = pd.read_excel(io="自热火锅.xlsx", sheet_name=0) # type: DataFrame # print(df.columns) # Index(['category', 'goods_name', 'shop_name', 'price', 'purchase_num', 'location'], dtype='object') # 计算相关系数 corrPriceNum = df["price"].corr(other=df["purchase_num"]) print(corrPriceNum)
4adb4a10b451e7c7e41c85d5f59d7ab0732f56ef
Letthemknow/school
/Stanford/CS109/cs109_pset3.py
3,303
3.5
4
# Name: # Stanford email: ########### CS109 Problem Set 3, Question 1 ############## """ ************************IMPORTANT************************ For all parts, do NOT modify the names of the functions. Do not add or remove parameters to them either. Moreover, make sure your return value is exactly as described in the PDF handout and in the provided function comments. Remember that your code is being autograded. You are free to write helper functions if you so desire. Do NOT rename this file. ************************IMPORTANT************************ """ # Do not add import statements. # Do not remove this import statement either. from numpy.random import rand # part (a) - completed for you def simulate_bernoulli(p=0.4): if rand() < p: return 1 return 0 # part (b) def simulate_binomial(n=20, p=0.4): count = 0 for _ in range(n): if rand() < p: count += 1 return count # part (c) def simulate_geometric(p=0.03): num_trials = 1 r = rand() while r >= p: num_trials += 1 r = rand() return num_trials # part (d) def simulate_neg_binomial(r=5, p=0.03): count = 0 successes = 0 while successes <= r: count += 1 if rand() < p: successes += 1 return count # Note for parts (e) and (f): # Since `lambda` is a reserved word in Python, we've used # the variable name `lamb` instead. Do NOT use the word # `lambda` in your code. It won't do what you want! # part (e) def simulate_poisson(lamb=3.1): time_increments = 60000 prob = lamb / time_increments count = 0 for _ in range(time_increments): if rand() < prob: count += 1 return count # part (f) def simulate_exponential(lamb=3.1): time_increments = 60000 prob = lamb / time_increments r = rand() time_steps = 1 while r >= prob: time_steps += 1 r = rand() return time_steps / time_increments def main(): """ We've provided this for convenience. Feel free to modify this function however you like. We won't grade anything in this function. """ print("Bernoulli:", simulate_bernoulli()) ########### CS109 Problem Set 3, Question 13 ############## """ *********** Article submission ********** If you choose to submit an article for extra credit, it should be in a function named article_ec: - this function should take 0 arguments - edit the string variable sunetid to be your SUNetID, e.g., "yanlisa" - edit the string variable title to be your article title, e.g., "10 Reasons Why Probability Is Great" - edit the string variable url to be a URL to your article, e.g., "http://cs109.stanford.edu/" - you should not modify the return value """ def article_ec(): sunetid = "agalczak" # your sunet id here. title = "Carnival Probability of Bankruptcy" # your article title here url = "https://www.macroaxis.com/invest/ratio/CCL--Probability-Of-Bankruptcy" # a link to your article here return sunetid, title, url ############################################################ # This if-condition is True if this file was executed directly. # It's False if this file was executed indirectly, e.g. as part # of an import statement. if __name__ == "__main__": main()
d0df4da84b7a6d75240e62c41569c4b471b2699e
Letthemknow/school
/Stanford/CS109/cs109_pset5_coursera.py
7,343
3.703125
4
# Do NOT add any other import statements. # Don't remove these import statements. import numpy as np import copy import os # Name: # Stanford email: ########### CS109 Problem Set 5, Question 8 ############## def get_filepath(filename): """ filename is the name of a data file, e.g., "learningOutcomes.csv". You can call this helper function in all parts of your code. Return a full path to the data file, located in the directory datasets, e.g., "datasets/learningOutcomes.csv" """ return os.path.join("datasets", filename) """ Assembled by Lisa Yan and Past CS109 TA Anand Shankar *************************IMPORTANT************************* For part_a and part_b, do NOT modify the name of the functions. Do not add or remove parameters to them either. Moreover, make sure your return value is exactly as described in the PDF handout and in the provided function comments. Remember that your code is being autograded. You are free to write helper functions if you so desire. Do NOT rename this file. *************************IMPORTANT************************* """ def part_a(filename): """ filename is the name of a data file, e.g. "learningOutcomes.csv". You must use the filename variable. Do NOT alter the filename variable, and do NOT hard-code a filepath; if you do, you'll likely fail the autograder. You can use the helper function defined above, get_filepath(). Return the difference in sample means (float) as described in the handout. """ data = np.genfromtxt(get_filepath(filename), names = ['id', 'activity', 'score'], dtype=[('id', np.int32), ('activity', np.dtype('U9')), ('score', np.int32)], delimiter=',') activity1, activity2 = data[data['activity'] == "activity1"], data[data['activity'] == "activity2"] a1_scores, a2_scores = [row[2] for row in activity1], [row[2] for row in activity2] return abs(np.mean(a1_scores) - np.mean(a2_scores)) def part_b(filename, seed=109): """ filename is the name of a data file, e.g. "learningOutcomes.csv". You must use the filename variable. Do NOT alter the filename variable, and do NOT hard-code a filepath; if you do, you'll likely fail the autograder. You MUST use np.random.choice with replace=True to draw random samples. You may NOT use any other function to draw random samples. See assignment handout for details. Return the p-value (float) as described in the handout. """ np.random.seed(seed) # DO NOT ALTER OR DELETE THIS LINE ### BEGIN YOUR CODE FOR PART (B) ### data = np.genfromtxt(get_filepath(filename), names = ['id', 'activity', 'score'], dtype=[('id', np.int32), ('activity', np.dtype('U9')), ('score', np.int32)], delimiter=',') activity1, activity2 = data[data['activity'] == "activity1"], data[data['activity'] == "activity2"] a1_scores, a2_scores = [row[2] for row in activity1], [row[2] for row in activity2] true_diff = part_a(filename) # 1. Create universal sample with two samples. universal_sample = a1_scores + a2_scores # 2. Repeat bootstrapping procedure 10000 times. num_greater_diffs = 0 iters = 10000 for i in range(iters): resample1 = resample(universal_sample, len(a1_scores)) resample2 = resample(universal_sample, len(a2_scores)) diff = abs(np.mean(resample1) - np.mean(resample2)) if diff > true_diff: num_greater_diffs += 1 p_val = num_greater_diffs / iters return p_val ### END YOUR CODE FOR PART (B) ### def resample(data, n): return np.random.choice(data, n, replace=True) def optional_function(): """ We won't autograde anything you write in this function. But we've included this function here for convenience. It will get called by our provided main method. Feel free to do whatever you want here, including leaving this function blank. We won't read or grade it. """ np.random.seed(109) data_scores = np.genfromtxt(get_filepath('learningOutcomes.csv'), names=['id', 'activity', 'score'], dtype=[('id', np.int32), ('activity', np.dtype('U9')), ('score', np.int32)], delimiter=',') data_back = np.genfromtxt(get_filepath('background.csv'), names=['id', 'background'], dtype=[('id', np.int32), ('background', np.dtype('U7'))], delimiter=',') activity1, activity2 = data_scores[data_scores['activity'] == "activity1"], data_scores[data_scores['activity'] == "activity2"] a1_scores, a2_scores = [row[2] for row in activity1], [row[2] for row in activity2] back_less, back_avg, back_more = data_back[data_back['background'] == 'less'], data_back[data_back['background'] == 'average'], data_back[data_back['background'] == 'more'] backs = [back_less, back_avg, back_more] # Loop over all the backgrounds and get a difference in means between act1 and act2. Similar to part a. for back in backs: act1_scores = [] act2_scores = [] for row in back: id = row['id'] score_row = data_scores[data_scores['id'] == id] score = score_row['score'] if score_row['activity'] == "activity1": act1_scores.append(score) else: act2_scores.append(score) back_mean = abs(np.mean(act1_scores) - np.mean(act2_scores)) # Calculate p-val, exact same code as in part_b universal_sample = (act1_scores + act2_scores) # This returns a list of arrays for some reason. Need to flatten it. universal_sample = [element for sublist in universal_sample for element in sublist] num_greater_diffs = 0 iters = 10000 for i in range(iters): resample1 = resample(universal_sample, len(act1_scores)) resample2 = resample(universal_sample, len(act2_scores)) diff = abs(np.mean(resample1) - np.mean(resample2)) if diff > back_mean: num_greater_diffs += 1 p_val = num_greater_diffs / iters print("Background: {} mean: {:.2f} p-value: {}".format(back[0]['background'], back_mean, p_val)) def main(): """ We've provided this for convenience, simply to call the functions above. Feel free to modify this function however you like. We won't grade anything in this function. """ print("****************************************************") print("Calling part_a with filename 'learningOutcomes.csv':") print("\tReturn value was:", part_a('learningOutcomes.csv')) print("****************************************************") print("****************************************************") print("Calling part_b with filename 'learningOutcomes.csv':") print("\tReturn value was:", part_b('learningOutcomes.csv')) print("****************************************************") print("****************************************************") print("Calling optional_function:") print("\tReturn value was:", optional_function()) print("****************************************************") print("Done!") # This if-condition is True if this file was executed directly. # It's False if this file was executed indirectly, e.g. as part # of an import statement. if __name__ == "__main__": main()
718944b33bc36198a7942be3db1204adec0b47ac
joseluisquisan/hello-world
/devnet/devnet/data_estructures.py
485
3.53125
4
def legalAges(): lifeEvent = { "drivingAge": 16, "votingAge": 18, "drinkingAge": 21, "retirementAge": 65 } print("The legal driving age is " + str(lifeEvent["drivingAge"]) + ".") print("The legal voting age is " + str(lifeEvent["votingAge"]) + ".") print("The legal drinking age is " + str(lifeEvent["drinkingAge"]) + ".") print("The legal retirement age is " + str(lifeEvent["retirementAge"]) + ".") legalAges()
e821232eb26f19e46699cec48e7165e461f14578
joseluisquisan/hello-world
/python_basico/disccionarios.py
636
3.90625
4
def run(): mi_diccionario = { 'llave1': 1, 'llave2': 2, 'llave3': 3, } # print(mi_diccionario['llave1']) # print(mi_diccionario['llave2']) # print(mi_diccionario['llave3']) población_paises = { 'Argentina': 44_938_712, 'Brasil': 210_147_125, 'Colombia': 50_372_424 } # print(población_paises['Argentina']) # print(población_paises['Bolivia']) # for pais in población_paises.values(): # print(pais) for pais,poblacion in población_paises.items(): print(pais, 'tiene', poblacion, "habitantes") if __name__ == '__main__': run()
65280e232d355a12c8bbb7122a17a0be72f381fd
joseluisquisan/hello-world
/codigocurso/bohemian.py
336
3.9375
4
# def run(): # for i in range(6): # if i == 3: # print("Figarooo") # continue # print("Galileo") def run(): for contador in range(101): if contador % 2 != 0: print("Impar") continue print("Par ", contador, "") if __name__ == '__main__': run()
c56b0a62664f03485da1fb9bd35f119e26dfe008
rajeshwerkushwaha/python_learning
/file_readwrite/file_readwrite.py
720
3.75
4
# read all at one shot f = open('sample.txt', 'r') print(f.read()) # read line by line when file is small f = open('sample.txt', 'r') for line in f: print(line) # read line by line when file is big f = open('sample.txt', 'r') while True: line = f.readline() print(line) if ("" == line): break; # new file create move f = open('sample1.txt', 'x') f.write('This msg writes through f.write()') f = open('sample1.txt', 'r') print(f.read()) # append mode f = open('sample.txt', 'a') f.write('\nThis line written by f.write() in append mode') # write mode f = open('sample2.txt', 'w') f.write('\nThis line written by f.write() in wite mode (overwrite mode)') # delete a file import os os.remove('sample1.txt')
4ca20b2b026a7985dbb4e0fe140c458d87625132
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D8_NeedRevision/Convert_BST_to_Greater_Tree_NeedRevision/Solution_naive.py
1,186
3.859375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from Y2017.TreeNode import TreeNode class Solution(object): #TLEed. Passed 211/212 test cases. #A naive method that wasted the feature of BST. def convertBST(self, root): list=[] self.getAllNode(root,list) list=sorted(list,reverse=True) self.convertTree(root,list) return root """ :type root: TreeNode :rtype: TreeNode """ def getAllNode(self,root,list): if root: list.append(root.val) self.getAllNode(root.left,list) self.getAllNode(root.right,list) def convertTree(self,root,list): if root: val=root.val for num in list: if num>val: root.val+=num if num<=val: break self.convertTree(root.left, list) self.convertTree(root.right, list) t1=TreeNode(5) t2=TreeNode(2) t3=TreeNode(13) t1.left=t2 t1.right=t3 obj=Solution() print(obj.convertBST(t1))
6f8546778e855972ede401231ae059607e306ca2
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D11/Find_Mode_in_Binary_Search_Tree_NeedRevision/Solution_improved_dict.py
887
3.640625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from Y2017.TreeNode import TreeNode class Solution(object): # Runtime: 108ms Beats or equals to 40% (Fastest) def findMode(self, root): if not root: return [] dict = {} self.traverse(root) modeCount = max(dict.values()) return [k for k, v in dict.iteritems() if v==modeCount] def traverse(self, root): if root: dict[root.val] = dict.get(root.val, 0) + 1 self.traverse(root.left) self.traverse(root.right) """ :type root: TreeNode :rtype: List[int] """ # Runtime: ms Beats or equals to % t = TreeNode(2147483647) solution = Solution() print(solution.findMode(t))
0950827093e06c37a71d0b016c73b174b787ce79
AllanWong94/PythonLeetcodeSolution
/Y2017/M9/D5/Increasing_Triplet_Subsequence/Solution.py
875
3.515625
4
# Runtime: 39ms Beats or equals to 55% class Solution(object): def increasingTriplet(self, nums): val1=[] val2=None for i in nums: if not val1 or i>val1[-1]: val1.append(i) if len(val1)==3: return True elif val1: if len(val1)==1: val1[0]=i else: if val1[0]<i<val1[1]: val1[1]=i else: if not val2 or val2>i: val2=i else: val1=[val2,i] val2=None return False """ :type nums: List[int] :rtype: bool """ solution = Solution() print(solution.increasingTriplet([5,1,5,5,2,5,4]))
6d814302839f5517aeb31a243085f1ecf451d1cf
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D19_NeedRevision/Subtree_of_Another_Tree/Solution_naive.py
541
3.546875
4
# Runtime: 442ms Beats or equals to 32% # Reference: https://discuss.leetcode.com/topic/88520/python-straightforward-with-explanation-o-st-and-o-s-t-approaches class Solution(object): def isMatch(self, s, t): if not (s and t): return s is t return s.val == t.val and self.isMatch(s.left, t.left) and self.isMatch(s.right, t.right) def isSubtree(self, s, t): if self.isMatch(s, t): return True if not s: return False return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
bb101b61facff7835475f521e96043e58ccbcf11
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D19_NeedRevision/Subtree_of_Another_Tree/Solution.py
1,408
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from Y2017.TreeNode import TreeNode #TLEed. class Solution(object): def isSubtree(self, s, t): return self.helper(s,t,False,t) def helper(self,s,t,root_found,origin_t): if root_found: if s and s.val==origin_t.val: if self.helper(s.left,origin_t.left, True, origin_t) and self.helper(s.right,origin_t.right, True, origin_t): return True if (not s and t) or (s and not t): return False if (not s and not t): return True return self.helper(s.left,t.left, True, origin_t) and self.helper(s.right,t.right, True, origin_t) else: if not s or not t: return False if s.val==t.val: return self.helper(s.left, t.left, True, origin_t) and self.helper(s.right, t.right, True, origin_t) return self.helper(s.left, t, False, origin_t) or self.helper(s.right, t, False, origin_t) """ :type s: TreeNode :type t: TreeNode :rtype: bool """ # Runtime: ms Beats or equals to % t1=TreeNode(1) t2=TreeNode(1) t3=TreeNode(1) t1.left=t2 solution = Solution() print(solution.isSubtree(t1,t3))
087a85027a5afa03407fed80ccb82e466c4f46ed
ch-bby/R-2
/ME499/Lab_1/volumes.py
2,231
4.21875
4
#!\usr\bin\env python3 """ME 499 Lab 1 Part 1-3 Samuel J. Stumbo This script "builds" on last week's volume calculator by placing it within the context of a function""" from math import pi # This function calculates the volumes of a cylinder def cylinder_volume(r, h): if type(r) == int and type(h) == int: float(r) float(h) if r < 0 or h < 0: return None # print('you may have entered a negative number') else: volume = pi * r ** 2 * h return volume elif type(r) == float and type(h) == float: if r < 0 or h < 0: return None else: volume = pi * r ** 2 * h return volume else: # print("You must have entered a string!") return None # This function calculates the volume of a torus def volume_tor(inner_radius, outer_radius): if type(inner_radius) == int and type(outer_radius) == int: float(inner_radius) float(outer_radius) if inner_radius < 0 or outer_radius < 0: return None else: if inner_radius > outer_radius: return None elif inner_radius == outer_radius: return None else: r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section volume = (pi * r_circle ** 2) * (2 * pi * r_mid) return volume elif type(inner_radius) == float and type(outer_radius) == float: if r < 0 and h < 0: return None else: if inner_radius > outer_radius: return None elif inner_radius == outer_radius: return None else: r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section volume = (pi * r_circle ** 2) * (2 * pi * r_mid) return volume else: return None if __name__ == '__main__': print(cylinder_volume(3, 1)) print(volume_tor(-2, 7))
c2c12efe187c133fee08b987e911772b0054fcbd
ch-bby/R-2
/ME499/Lab_1/words.py
461
3.765625
4
#!\usr\bin\env python3 """ME 499 Lab 1 Part 5 Samuel J. Stumbo 13 April 2018""" def letter_count(string_1, string_2): count = 0 string_1 = str(string_1).lower() string_2 = str(string_2).lower() for i in string_1: #print(i) # Print for debugging purposes if i == string_2: count += 1 return count if __name__ == '__main__': print(letter_count('supercalafragalisticexpialidocious', 1))
39bebab706b7e5bccee7fe7ae212831fe5279e5e
ch-bby/R-2
/ME499/lab2/filters.py
1,312
3.921875
4
#!/usr/bin/env python3 """ ME 499: Lab 2 Samuel J. Stumbo 20 April 2018 Filters Function This function reads in random data (or any data, really) and normalizes it """ from sensor import * import numpy as np import matplotlib.pyplot as plt def mean_filter(l1, width = 3): unfiltered = [] w = width // 2 for n in l1: unfiltered.append(n) filtered = [] for i in range(w, len(l1)-w): filtered.append(sum(unfiltered[i - w : i + w + 1]) / width) return unfiltered, filtered def median_filter(l1, width=3): filtered = [] w = width for i in range(len(l1) - w + 1): filtered.append(np.median(unfiltered[i: i + w])) return filtered if __name__ == '__main__': data = generate_sensor_data() width = 5 l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] unfiltered, mean = mean_filter(data, width) median = median_filter(data,width) print_sensor_data(unfiltered, 'unfiltered.txt') print_sensor_data(mean, 'mean.txt') print_sensor_data(median, 'median.txt') # red dashes, blue squares and green triangles plt.plot(range(len(mean)), mean, 'r--', range(len(median)), median, 'g', range(len(data)), data) plt.show() # print(filtered) # print(median_filter(l1, n)) # fin = open('words.txt') # print(fin.readline())
d571d28325d7278964d45a25a4777cf8f121f0ce
ch-bby/R-2
/ME499/Lab4/shapes.py
1,430
4.46875
4
#!/usr/bin/env python3# # -*- coding: utf-8 -*- """ **************************** ME 499 Spring 2018 Lab_4 Part 1 3 May 2018 Samuel J. Stumbo **************************** """ from math import pi class Circle: """ The circle class defines perimeter, diameter and area of a circle given the radius, r. """ def __init__(self, r): if r <= 0: raise 'The radius must be greater than 0!' self.r = r def __str__(self): return 'Circle, radius {0}'.format(self.r) def area(self): return pi * self.r ** 2 def diameter(self): return 2 * self.r def perimeter(self): return 2 * pi * self.r class Rectangle: """ The rectangle class has attributes of a rectangle, perimeter and area """ def __init__(self, length, width): if length <= 0 or width <= 0: raise 'The length and width must both be positive values.' self.length = length self.width = width def __str__(self): return 'Rectangle, length {0} and width {1}'.format(self.length, self.width) def area(self): return self.length * self.width def perimeter(self): return self.length * 2 + self.width * 2 if __name__ == '__main__': c = Circle(1) r = Rectangle(2, 4) shapes = [c, r] for s in shapes: print('{0}: {1}, {2}'.format(s, s.area(), s.perimeter()))
fbe33499711988c0d0f888d1dfc6626fe90c017a
yvvyoon/learn-python
/multi_pro1.py
239
3.640625
4
import time start_time = time.time() def count(name): for i in range(1, 200001): print(f'{name}: {i}') num_list = ['p1', 'p2', 'p3', 'p4'] for num in num_list: count(num) print(f'*** {time.time() - start_time} ***')
79531c1658c717a945851ef9bf19bca4d70d6118
yvvyoon/learn-python
/team-study/generator/generator04.py
988
3.96875
4
class Tree(object): def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def inorder(self): if self.left: for x in self.left.inorder(): yield x yield self if self.right: for x in self.right.inorder(): yield x def __iter__(self): return self.inorder() def __repr__(self, level=0, indent=' '): s = level * indent + self.data if self.left: s = f'{s}\n{self.left.__repr__(level+1, indent)}' if self.right: s = f'{s}\n{self.right.__repr__(level+1, indent)}' return s def tree(List): n = len(List) if n == 0: return None i = n / 2 return Tree(List[i], tree(List[:i]), tree(List[i + 1:])) if __name__ == '__main__': t = tree('abcdef') print(t) print() for el in t.inorder(): print(el.data)
9c9ae4a120558d23b1f70f1e581b08cb5112f6cc
soja-soja/LearningHTML
/Python/Session-1.py
565
3.890625
4
print('\n============ Output ===========') # condition if-else a = int(input('please enter A:')) b = int(input('please enter B:')) c = input('enter the operator:') if c == '+': # b == 0 b<0 b>0 b<=0 b>=0 b!=0 print('A+B is: {} '.format(a+b) ) else: print('A-B is: {} '.format(a-b) ) # a = 1 # integer # a = 2 # a = 3 # a = 1.5 # float # a = 'SOJA.ir' # string # a = 'S' # character - char # ctrl + / ---> to commend out a line # '100' 100 # int --> str # 100 --> '100' # str(100) --> '100' # str --> int # '100' --> 100 # int('100') --> 100
b47ed30acdcc89e7fca0545648aca5e0511f9585
xychen1015/leetcode
/offer/27.py
1,014
3.859375
4
# -*- coding: utf-8 -*- # @Time : 2020/9/24 上午11:36 # @Author : cxy # @File : 27.py # @desc: """ 方法一:递归。不需要使用额外的变量存储结果,直接就地进行翻转。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def mirrorTree(self, root: TreeNode) -> TreeNode: if not root: return None root.left,root.right=self.mirrorTree(root.right),self.mirrorTree(root.left) return root """ 方法二:使用栈.先把cur的左右子节点放入到栈中,然后交换cur的左右子节点 """ class Solution: def mirrorTree(self, root: TreeNode) -> TreeNode: if not root: return None stack=[root] while stack: cur=stack.pop() if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) cur.left,cur.right=cur.right,cur.left return root
486253055276e69f69bc83f3180f7339908d0c75
xychen1015/leetcode
/offer/59.py
1,469
3.75
4
# -*- coding: utf-8 -*- # @Time : 2020/9/3 下午3:13 # @Author : cxy # @File : 59.py # @desc: """ 由于题目要求max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。因此不能直接使用max方法,需要使用一个暂存数组来存放当前元素之后的最大元素的值 """ class MaxQueue: def __init__(self): from collections import deque self.q = deque() self.mx = deque() def max_value(self) -> int: return self.mx[0] if self.mx else -1 """ 依次插入[2,5,3,4,6,6] q:[2], mx:[2] q:[2,5], mx:[5],弹出2并插入5 q:[2,5,3], mx:[5,3],不弹出并插入3 q:[2,5,3,4], mx:[5,4],弹出3并插入4 q:[2,5,3,4,6], mx:[6],弹出4 5并插入6 q:[2,5,3,4,6,6], mx:[6,6],不弹出并插入6,因为6<=6 """ def push_back(self, value: int) -> None: self.q.append(value) while self.mx and self.mx[-1]<value: self.mx.pop() # 当新插入的元素大于暂存数组中的末端元素时,则弹出末端 self.mx.append(value) # 直到大于等于value,则插入到暂存数组中 def pop_front(self) -> int: if not self.q: return -1 ans = self.q.popleft() if ans == self.mx[0]: self.mx.popleft() return ans # Your MaxQueue object will be instantiated and called as such: # obj = MaxQueue() # param_1 = obj.max_value() # obj.push_back(value) # param_3 = obj.pop_front()
3a6a87ea881449029996ce4d5603be93a85854bf
subin97/python_basic
/exercise/gugudan.py
310
3.703125
4
while True: print('구구단 몇 단을 계산할까요(1~9)?') num = int(input()) if num not in range(1, 10): print('구구단 게임을 종료합니다.') break print(f'구구단 {num}단을 계산합니다.') for i in range(1, 10): print(f'{num} X {i} = {num*i}')
8497d12e91e7e5964459332a8cc28ace8e101980
subin97/python_basic
/mycode/10_pythonic/list_comprehension.py
173
3.640625
4
result = [x for x in range(10) if x%2 == 0] print(result) my_str1 = "Hello" my_str2 = "World" result = [i+j for i in my_str1 for j in my_str2 if not (i==j)] print(result)
ea3348c0dd35ba8c60d8dc3b75f04703501931d2
retropleinad/Chess
/pieces/knight.py
1,697
3.828125
4
from pieces.piece import Piece class Knight(Piece): # Inherited constructor # Update the piece value def __init__(self, color, column, row, picture): super().__init__(color, column, row, picture) self.val = 3 # Is the square in a 2 by 3 or a 3 by 2? # Is there a friendly piece in that square? # Otherwise, it can move. def can_move(self, board, column, row): if column >= len(board) or row >= len(board) or column < 0 or row < 0 or \ (board[column][row] is not None and board[column][row].color == self.color): return False elif (self.column + 2 == column and self.row + 1 == row) or \ (self.column + 2 == column and self.row - 1 == row) or \ (self.column - 2 == column and self.row + 1 == row) or \ (self.column - 2 == column and self.row - 1 == row) or \ (self.column + 1 == column and self.row + 2 == row) or \ (self.column + 1 == column and self.row - 2 == row) or \ (self.column - 1 == column and self.row + 2 == row) or \ (self.column - 1 == column and self.row - 2 == row): return True return False # Returns a list of available moves that a piece may make, given a particular board def available_moves(self, board): moves = [] i = 2 while i > -3: j = 2 while j > -3: if self.can_move(board, self.column + i, self.row + j): moves.append((self.column + i, self.row + j)) j -= 1 i -= 1 return moves
4211efe86175e8a6425c117f4869ca5239b15727
ytxka/nowcode-codes
/二叉搜索树的后序遍历序列.py
1,256
3.546875
4
# -*- coding:utf-8 -*- class Solution: def VerifySquenceOfBST(self, sequence): # 二叉搜索树的后序遍历,最后一个元素为root,前面必可以分为两部分 # 一部分(左子树)小于root,一部分(右子树)大于root # 递归判断左右子树 if not sequence: return False if len(sequence) == 1: return True root = sequence[-1] index = 0 while sequence[index] < root: index += 1 # 下面这种for循环写法有误,上述while循环正确 # 问题在于:假设只有左子树,则剩余元素均大于最后一个,则index=0,意为没有左子树,显然不对 # for i in sequence[:-1]: # if i > root: # index = sequence.index(i) # break left = sequence[:index] right = sequence[index:-1] leftIs = True rightIs = True for j in right: if j < root: return False if left: leftIs = self.VerifySquenceOfBST(left) if right: rightIs = self.VerifySquenceOfBST(right) return leftIs and rightIs
82d094ce4f9018cd3f2b6777e68ce691a2436c3e
ytxka/nowcode-codes
/二叉搜索树的第k个结点.py
608
3.765625
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here self.res = [] self.MidSearch(pRoot) if 0 < k <= len(self.res): return self.res[k - 1] else: return None def MidSearch(self, root): if not root: return self.MidSearch(root.left) self.res.append(root) self.MidSearch(root.right)
13238ec3b96e2c1297fa1548f14d19860fbe222d
GeeB01/Codigos_guppe
/objetos.py
1,007
4.3125
4
""" Objetos -> São instancias das classe, ou seja, após o mapeamento do objeto do mundo real para a sua representação computacional, devemos poder criar quantos objetos forem necessarios. Podemos pensar nos objetos/instancia de uma classe como variaveis do tipo definido na classe """ class Lampada: def __init__(self, cor, voltagem, luminosidade): self.__cor = cor self.__voltagem = voltagem self.__luminosidade = luminosidade def mostra_cor(self): print(self.__cor) class ContaCorrente: contador = 1234 def __init__(self, limite, saldo): self.__numero = ContaCorrente.contador + 1 self.__limite = limite self.__saldo = saldo ContaCorrente.contador = self.__numero class Usuario: def __init__(self, nome, sobrenome, email, senha): self.__nome = nome self.__sobrenome = sobrenome self.__email = email self.__senha = senha lamp1 = Lampada('qazu', '110', 'aaa') lamp1.mostra_cor()
94c0aa3a85162c6642450b3eb51fbf258b9a2f64
GeeB01/Codigos_guppe
/sistema_de_arquivos_manipulação.py
874
3.578125
4
""" Sistema de Arquivo - manipulação # Descobrindo se um arquivo ou diretorio existe #paths relativos print(os.path.exists('texto.txt')) print(os.path.exists('gb')) print(os.path.exists('gb/gabriel1.py')) #paths absolutos print(os.path.exists('C:\\Users\\Gabriel')) # criando arquivo # forma 1 open('aruivo_teste.txt', 'w').close() # forma 2 open('arquivo2.txt', 'a').close() # forma 3 with open('arquivo3.txt', 'w') as arquivo: pass # criando arquivo os.mknod('aruivo_teste2.txt') os.mknod('C:\\Users\\Gabriel\\PycharmProjects\\guppe\\arquivo_teste3.txt') # criando diretorio os.mkdir('novo') # a função cira um diretorio se este nao existir. Caso exista, teremos FileExistsError # criando multi diretorios os.makedirs('outro/mais/um') """ import os os.rename('frutas2.txt', 'frutas3.txt') os.rename('outro/mais/um/teste.txt', 'outro/mais/um/teste2.txt')
a99fc4de820a1c0ac22c88be6b3ee4317a9234e7
GeeB01/Codigos_guppe
/leitura_de_arquivos.py
561
4.0625
4
""" Leitura de arquivos para ler o conteúdo de um arquivo em Python, utilizamos a função integrada open(), que literalmente significa abrir open() -> Na forma mais simples de utilização nos passamos apenas um parametro de entrada, que neste caso é o caminho para o arquivo à ser lido. Essa função retorna um _io.TextIOWrapper e é com ele que trabalhamos então # Por padrao a função open(), abre o arquivo para leitura. Este arquivo deve existir, ou entao teremos o erro FileNotFoundError """ arquivo = open('pacotes.py') print(arquivo.read())
a5a1bd8efaf5d8bbed35197d34a402acb5a46084
GeeB01/Codigos_guppe
/len_abs_sum_round.py
698
4
4
""" len, abs, sum, round #len len() retorna o tamanho(ou seja, o numeor de itens) de um iteravel print(len('Gabriel')) #abs ela retorna o valor absoluto de um numero inteiro ou real, de forma basica , seria o seu valor real sem o sinal print(abs(-5)) print(abs(3.53)) #sum recebe como parametro um iteravel podendo receber um valor inical e retorna a soma total dos elementos incluindo o valor inicial print(sum([1, 2, 3, 4, 5])) print(sum([1, 2, 3, 4, 5], 10)) #round retorna um numero arredondado para n digito de precisao apos a casa decimal se a precisao nao for informada retrona o inteiro mais proximo da entrada """ print(round(12.123124)) print(round(5.789)) print(round(7.97561254125))
219a68a96463790053489586c1714b7a27f66388
Reiji-A/python_package
/正規表現re/test.py
1,321
3.625
4
import re regex = r"ab+" text = "abbabbabaaabb" pattern = re.compile(regex) matchObj = pattern.match(text) matchObj matchObj = re.match(regex,text) matchObj # matchのサンプルコード data = "abcdefghijklmn" # パターン式の定義(aで始まりcで終わる最短の文字列) pattern = re.compile(r"a.*?c") match_data = pattern.match(data) print(match_data.group()) # searchのサンプルコード # パターン式の定義(dで始まりgで終わる最短の文字列) pattern = re.compile(r"d.*?g") match_data = pattern.search(data) # 一致したデータ print(match_data.group()) # 一致した開始位置 print(match_data.start()) # 一致した終了位置 print(match_data.end()) # 一致した位置を表示 print(match_data.span()) # findallのサンプルコード # パターン式の定義(dで始まりgで終わる最短の文字列) pattern = re.compile(r"d.*?g") match_data = pattern.findall(data) print(match_data) # finditerのサンプルコード # パターン式の定義(dで始まりgで終わる最短の文字列) data = "abcdefghijklmnabcdefghijklmn" pattern = re.compile(r"d.*?g") match_datas = pattern.finditer(data) print(match_datas) for match in match_datas: print(match.group()) print(match.start()) print(match.end()) print(match.span())
2ccfacec48b1716f13ca9bd75dd39008c749b0f4
aryanguptaSG/Data_Structure
/data_structures/dequeue/dequeue_using_array.py
839
3.953125
4
class dequeue(): """docstring for dequeue""" def __init__(self, size=5): self.size = size self.front = self.rear = -1 self.array = size*[None] def pushfront(self,value): if(self.front-1==self.rear): print("dequeue is full") return 0; elif(self.front ==-1): self.front=self.size-1 else: self.front-=1 self.array[self.front]=value print(value," is added in dequeue") print("front is : ",self.front) def pushback(self,value): if(self.rear+1==self.front or self.rear==self.size-1): print("dequeue is full") return 0; else: self.rear+=1 self.array[self.rear]=value print(value," is added in dequeue") print("rear is : ",self.rear) dequ = dequeue() dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10)
d8e32ee5aed3b8c943bbaf05545f547e2f27d464
AnnKuz1993/Python
/lesson_02/example_03.py
1,893
4.25
4
# Пользователь вводит месяц в виде целого числа от 1 до 12. # Сообщить к какому времени года относится месяц (зима, весна, лето, осень). # Напишите решения через list и через dict. month_list = ['зима', 'весна', 'лето', 'осень'] month_dict = {1: 'зима', 2: 'весна', 3: 'лето', 4: 'осень'} num_month = int(input("Введите номер месяца от 1 до 12 >>> ")) if num_month == 1 or num_month == 2 or num_month == 12: print("Время года для этого месца >>> ", month_dict.get(1)) elif num_month == 3 or num_month == 4 or num_month == 5: print("Время года для этого месца >>> ", month_dict.get(2)) elif num_month == 6 or num_month == 7 or num_month == 8: print("Время года для этого месца >>> ", month_dict.get(3)) elif num_month == 9 or num_month == 10 or num_month == 11: print("Время года для этого месца >>> ", month_dict.get(4)) else: print("Ввели неверное число! Такого месяца не существует!") if num_month == 1 or num_month == 2 or num_month == 12: print("Время года для этого месца >>> ", month_list[0]) elif num_month == 3 or num_month == 4 or num_month == 5: print("Время года для этого месца >>> ", month_list[1]) elif num_month == 6 or num_month == 7 or num_month == 8: print("Время года для этого месца >>> ", month_list[2]) elif num_month == 9 or num_month == 10 or num_month == 11: print("Время года для этого месца >>> ", month_list[3]) else: print("Ввели неверное число! Такого месяца не существует!")
62e23d990a25f1115e87984698d4af54ab11b3e1
AnnKuz1993/Python
/lesson_04/example_06.py
465
3.875
4
# итератор, генерирующий целые числа, начиная с указанного from itertools import count for el in count (3): if el > 10: break else: print(el) # итератор, повторяющий элементы некоторого списка, определенного заранее from itertools import cycle c = 0 for el in cycle("ABBY"): if c > 7: break print(el) c += 1
96cd937cfe7734c8fae5348b53517271e3c59321
AnnKuz1993/Python
/lesson_03/example_01.py
791
4.125
4
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def num_division(): try: a = int(input("Введите первое число: ")) b = int(input("Введите второе число: ")) return print("Результат деления первого числа на второе →",a / b) except ZeroDivisionError: return "На 0 делить нельзя!" except ValueError: return "Ввели неверное значение!" num_division()
3bb991b7c0d7cd43ff00f35c15e114792246bc8e
AnnKuz1993/Python
/lesson_01/example_06.py
324
3.953125
4
a = float(input("Введи результат пробежки в 1-ый день: ")) b = float(input("Введи желаемый результат пробежки: ")) day = 0 while a < b: a = a * 1.1 day += 1 print("Ты достигнешь желаемого результата на ",day,"-й день")
1bba11b294f8ab6e4c63481028eeb7ed4ad69f92
AreebaKhalid/ComputerVisionPractis
/Program7Rotations.py
715
3.59375
4
import cv2 import numpy as np image = cv2.imread('./images/input.jpg') height, width = image.shape[:2] #cv2.getRotationMatrix2D(rotation_center_x, rotation_center_y,angle_of_rotation,scale) #angle is anti clockwise #image is cropped by putting scale = 1 #put = .5 it will not crop rotation_matrix = cv2.getRotationMatrix2D((width/2,height/2),90,.5) #new width and height in warp_affine function rotated_image = cv2.warpAffine(image, rotation_matrix,(width,height)) cv2.imshow("Rotated Image",rotated_image) #method-2 image = cv2.imread('./images/input.jpg') rotated_image = cv2.transpose(image) cv2.imshow("Rotated Image - Method 2",rotated_image) cv2.waitKey() cv2.destroyAllWindows()
1d519743918f89d13492af1c920356e056787ddd
pythonclaire/pythonpractice
/financing_assistant.py
3,514
3.625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from sys import exit #终值计算器 def finalassets(): print("信息输入样式举例") print(""" 请输入本金<元>:10000 请输入年化收益率<如5%>:5% 请输入每月追加投入金额<元>:1000 请输入投资年限:30 """) A=int(input("请输入本金<元>:")) r=input("请输入年化收益率<如5%>:") m=int(input("请输入每月追加投入金额<元>:")) n=int(input("请输入投资年限:")) for i in range(1,12*n+1): A=int((A+m)*(1+float(r.strip('%'))/100/12)) if i%12==0: print(f"第{int(i/12)}年总资产:{A}") #达到目标的最低年化收益率 def yield_rate(): print("年化收益率以0.05%递增") print("信息输入样式举例") print(""" 请输入理财目标<万元>:100 请输入本金<元>:10000 请输入每月追加投入金额<元>:1000 请输入投资年限:30 """) g=int(input("请输入理财目标<万元>:")) AA=int(input("请输入本金<元>:")) m=int(input("请输入每月追加投入金额<元>:")) n=int(input("请输入投资年限:")) r=0.005 A=AA while A<g*10000: A=AA for i in range(1,12*n+1): A=int((A+m)*(1+r/12)) r=r+0.005 print(f"最终总资产:{A}") print(f"最低年化收益率:{round((r-0.005)*100,1)}%") #达到目标的最低月投入金额 def monthly_invest(): print("月投入金额以100元递增") print("信息输入样式举例") print(""" 请输入理财目标<万元>:100 请输入本金<元>:10000 请输入年化收益率<如5%>:5% 请输入投资年限:30 """) g=int(input("请输入理财目标<万元>:")) AA=int(input("请输入本金<元>:")) r=input("请输入年化收益率<如5%>:") n=int(input("请输入投资年限:")) m=100 A=AA while A<g*10000: A=AA for i in range(1,12*n+1): A=int((A+m)*(1+float(r.strip('%'))/100/12)) m=m+100 print(f"最终总资产:{A}") print(f"最低月投入金额:{m-100}") def expenditure(): income=int(input("请输入您的月可支配收入: ")) exp={} n=int(input("请输入支出项目数量: ")) print("\n请逐个输入项目及权重(权重之和如超过1,将按占比重新分配)") print(""" 举例: 项目1:投资 权重1:0.4 """) for i in range(1,n+1): item=input(f"项目{i}: ") weight=float(input(f"权重{i}: ")) exp[item]=weight print("\n以下为您各项支出及权重") print(exp) sum=0 for value in exp.values(): sum=sum+value print("\n以下为您各项支出的分配金额:") for key in exp: print(f"{key}:{int(exp[key]/sum*income)}") print("\n") def start(): print("欢迎使用理财小助手!") print("希望能够帮助您达成理财目标,优化支出结构,实现财务自由!") print(""" 理财小助手能够帮助您: 1. 计算固定投资下,最终获得的总资产 2. 计算达成既定理财目标,每月需要的最低投入的金额 3. 计算达成既定理财目标,需要的最低年化收益率 4. 按既定权重,分配月可支配收入 """ ) while True: print("请输入您想咨询的问题编号,输入其他任意内容退出") q=input("> ") if q=='1': finalassets() elif q=='2': monthly_invest() elif q=='3': yield_rate() elif q=='4': expenditure() else: exit(0) start()
393dffa71a0fdb1a5ed69433973afd7d6c73d9ff
neelismail01/common-algorithms
/insertion-sort.py
239
4.15625
4
def insertionSort(array): # Write your code here. for i in range(1, len(array)): temp = i while temp > 0 and array[temp] < array[temp - 1]: array[temp], array[temp - 1] = array[temp - 1], array[temp] temp -= 1 return array
0e81f90bd31a9a378d2d4923176d4705d9d0f84a
jpecci/algorithms
/graphs/bfs.py
1,454
3.734375
4
from collections import deque from sets import Set def bfs(graph, start): explored={} #store the distance queue=deque() queue.append(start) explored[start]=0 while len(queue)>0: tail=queue.popleft() #print "%s -> "%(tail), for head, edge in graph.outBounds(tail).items(): if head not in explored: queue.append(head) explored[head]=explored[tail]+1 return explored def connected_components(graph): count_components=0 components={} visited=Set() # this is across all the bfs calls for node in graph: if node not in visited: # start a new bfs in this component count_components+=1 components[count_components]=1 queue=Queue() queue.put(node) visited.add(node) while not queue.empty(): v=queue.get() for w in graph[v]: if w not in visited: queue.put(w) visited.add(w) components[count_components]+=1 return components if __name__=='__main__': from graph import Graph, Edge, Vertex g=Graph() g.addEdge(Edge(Vertex('s'),Vertex('a')),False) g.addEdge(Edge(Vertex('b'), Vertex('s')),False) g.addEdge(Edge(Vertex('b'), Vertex('c')),False) g.addEdge(Edge(Vertex('c'), Vertex('a')),False) g.addEdge(Edge(Vertex('c'), Vertex('d')),False) print "graph: \n",g start=Vertex('s') dist=bfs(g, start) print "dists:" for to in sorted(dist.items(), key=lambda p:p[1]): print "%s->%s: dist= %d"%(start,to[0],to[1]) #print "components ",connected_components(g)
da3e119bb80133d329bedf3cde0cae09f12d4866
jpecci/algorithms
/graphs/dfs.py
827
3.75
4
from Queue import Queue from sets import Set def dfs(graph, start): explored=set() #store the distance stack=[] stack.append(start) explored.add(start) while len(stack)>0: tail=stack.pop() #print "%s -> "%(tail), for head, edge in graph.outBounds(tail).items(): if head not in explored: stack.append(head) explored.add(head) return explored if __name__=='__main__': from graph import Graph, Edge, Vertex g=Graph() g.addEdge(Edge(Vertex('s'),Vertex('a')),False) g.addEdge(Edge(Vertex('b'), Vertex('s')),False) g.addEdge(Edge(Vertex('b'), Vertex('c')),False) g.addEdge(Edge(Vertex('c'), Vertex('a')),False) g.addEdge(Edge(Vertex('c'), Vertex('d')),False) g.addEdge(Edge(Vertex('e'),Vertex('d')),False) print "graph: \n",g start=Vertex('s') explored=dfs(g, start) print explored
dc1116924017c9359798f1bb89e5f12424d21a93
jpecci/algorithms
/sorting/bubblesort.py
309
4
4
def swap(a,i,j): temp=a[i] a[i]=a[j] a[j]=temp def bubble_sort(a): for i in range(len(a)): swapped=False for j in range(1, len(a)-i): if a[j-1]>a[j]: swap(a, j-1, j) swapped=True #print a if not swapped: break if __name__=="__main__": v=[0,5,2,8,3,4,1] bubble_sort(v) print v
4af657b9bc471f8e6750e3c263e1a4ec43c5086a
vonkoper/pp3
/zadania domowe/trojkat.py
807
3.84375
4
''' Napisać program który sprawdzi czy z podanych przez użytkownika długości boków jest możliwość stworzenia trójkąta i oblicza jego pole. ''' a=float(input("Podaj dlugosc pierwszego boku trojkata: ")) b=float(input("Podaj dlugosc drugiego boku: ")) c=float(input("Podaj dlugosc trzeciego boku: ")) dlugosci_bokow = [a, b, c] x=max(dlugosci_bokow) dlugosci_bokow.remove(x) print(dlugosci_bokow) if sum(dlugosci_bokow) > x: answer=input("Z takich odcinkow da sie zbudowac trojkat, czy chcesz policzyc jego powierzchnie? (y/n) ") if answer == "y": ob=0.5*(a+b+c) pole=(ob*(ob-a)*(ob-b)*(ob-c))**0.5 print("Pole trojkata wynosi: ", pole) if answer == "n": print("Koniec") else: print("Z takich odcinkow nie da sie zbudowac trojkata.")
1862fd92995dbb1f72b17543ba52fa53c1c65e82
Czarne-Jagodki/labs
/lab1/ex1.py
4,802
4.4375
4
def print_matrix(matrix): """ Function shows a matrix of neighbourhood of graph. :param list: it's a not empty array of arrays :return: None """ i = 0 for row in matrix: i = i + 1 print(i, end='. ') print(row) def print_list(list): """ Function shows a list of neighbourhood of graph. It show appropriate vertex and other vertexes connected with it :param list: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge :return: None """ for key, value in list.items(): print(key, end=' -> ') print(value) neighbour_list = { 1 : [2, 5], 2 : [1, 3, 5], 3 : [2, 4], 4 : [3, 5], 5 : [1, 2, 4] } def from_list_to_matrix_neighbour(list): """ Function converts neighbourhood list to neighbourhood matrix :param list: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge :return: array of arrays which represents graph """ matrix = [] length = len(list) for elements in list.values(): row = [] for i in range(1, length + 1): if i in elements: row.append(1) else : row.append(0) matrix.append(row) print_matrix(matrix) return matrix #from_list_to_matrix_neighbour(neighbour_list) def from_matrix_neighbour_to_list(matrix): """ Function converts neighbourhood matrix to neighbourhood list :param matrix: not empty array of arrays which represents graph :return: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge """ list = {} i = 0 for row in matrix: i += 1 row_list = [] lenght = len(row) for j in range(lenght): if row[j] == 1: row_list.append(j + 1) list[i] = row_list return list #from_matrix_neighbour_to_list(from_list_to_matrix_neighbour(neighbour_list)) def transpone_matrix(matrix): """ Function to transpone matrix It's needed, beceuse functions associated with incidence returned not appropriate results :param matrix: not empty array of arrays :return: array of arrays but transponed """ import numpy as np n = np.matrix(matrix) n = n.transpose() length = len(n) new_matrix = [] n = np.array(n) for row in n: new_matrix.append(row) return new_matrix def from_list_to_incidence_matrix(list): """ Function converts list of neighbourhood to incidence matrix :param list: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge :return: it's a array of arrays which represents incidence matrix of graph """ matrix = [] for key, value in list.items(): ranger = key #ranger check if we do not use element used # in previous iterations to prevent from doubling same row for elem in value: if ranger < elem: row = [0] * len(list) row[key - 1] = 1 row[elem - 1] = 1 matrix.append(row) #print_matrix(matrix) matrix = transpone_matrix(matrix) return matrix print_matrix(from_list_to_incidence_matrix(neighbour_list)) def from_incidence_matrix_to_list(matrix): """ Function converts incidence matrix to list of neighbourhood :param matrix: it's a not empty array of arrays represents incidence matrix of graph, the matrix must be transponed on the input if it does not become from functions from this module The best way to do it is by our previous function :return: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge """ matrix = transpone_matrix(matrix) list = {} for row in matrix: i = -1 j = -1 for k in range(len(row)): if row[k] == 1: if i != -1: j = k + 1 else: i = k + 1 if i in list: list[i].append(j) else: list[i] = [j] if j in list: list[j].append(i) else: list[j] = [i] l = {} for key in sorted(list): l[key] = list[key] list = l return list print_list(from_incidence_matrix_to_list(from_list_to_incidence_matrix(neighbour_list)))
39012923982f1cca9660d1cea01faac7cef24257
cw02048/python-numpy-pandas
/test4.py
368
3.96875
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 21 19:19:18 2019 @author: cw020 """ def main(): n_list = [] n = int(input()) i = 0 while i < n: tmp = input() n_list.append(tmp[0:len(tmp)-3]) i += 1 for n in sorted(n_list): print(n) main()
3b087e39202ceefc8516e889161b06de68fd45d3
Anastasijap91/RTR105
/test20191010.py
307
3.8125
4
inp = raw_input("Enter a number between 0.0 and 1.0:") score = float(inp) if (score >=1.0): print("Jus nepildat instrukcijas:") exit() elif (score >=0.9): print("A") elif (score >=0.8): print("B") elif (score >=0.7): print("C") elif (score>=0.6): print("D") else: print("F")
a57688d3afbc2a044eae489a2a475db55bddbfe3
orcl/coding
/algorithm/Stack/queueWithStack/queueWithStack.py
670
3.828125
4
class Queue: #initialize your data structure here. def __init__(self): self.inbox = [] self.outbox = [] #@param x, an integer #@return nothing def push(self,x): self.inbox.append(x) #@return nothing def pop(self): if len(self.outbox) == 0: while len(self.inbox) > 0: self.outbox.append(self.inbox.pop()) self.outbox.pop() #@return an integer def peek(self): if len(self.outbox) == 0: while len(self.inbox) > 0: self.outbox.append(self.inbox.pop()) return self.outbox[len(self.outbox)-1] #@return an boolean def empty(self): return len(self.inbox) == 0 and len(self.outbox) == 0
5b9f9de8f78a512a5a023539fbe770e54c0679e6
orcl/coding
/algorithm/Stack/stackWithQueue/stackWithQueues.py
1,805
3.96875
4
#!/usr/bin/python # # class Stack: #initialize your data structure here. def __init__(self): self.queue1 = [] self.queue2 = [] #@param x, an integer #@return nothing def push(self,x): if not self.queue1: self.queue2.append(x) else: self.queue1.append(x) #@return nothing def pop(self): size = 0 if not self.queue1: #queue1 is empty, shift queue2 to queue1, remove the last from queue2 tmp = 0 size = len(self.queue2) while tmp < size - 1: self.queue1.append(self.queue2.pop(0)) tmp = tmp + 1 self.queue2.pop(0) else: #queue2 is empty, shift queue1 to queue2, remove the last from queue1 tmp = 0 size = len(self.queue1) while tmp < size - 1: self.queue2.append(self.queue1.pop(0)) tmp = tmp + 1 self.queue1.pop(0) #@return an integer def top(self): result = 0 size = 0 if not self.queue1: #queue1 is empty, shift queue2 to queue1, remove the last from queue2 tmp = 0 size = len(self.queue2) while tmp < size - 1: self.queue1.append(self.queue2[0]) self.queue2.pop(0) tmp = tmp + 1 result = self.queue2[0] self.queue2.pop(0) self.queue1.append(result) else: #queue2 is empty, shift queue1 to queue2, remove the last from queue1 tmp = 0 size = len(self.queue1) while tmp < size -1: self.queue2.append(self.queue1[0]) self.queue1.pop(0) tmp = tmp + 1 result = self.queue[0] self.queue1.pop(0) self.queue2.append(result) return result #@return an boolean def empty(self): return len(self.queue1) == 0 and len(self.queue2) == 0 def main(): print "hello" if __name__ == "__main__": main()
730901965676d61fb26179be80b1e8ab0a6bbcc9
ryankapler/Statbook
/Rando.py
355
3.875
4
#Random number generator #to be done amount = raw_input("How many random numbers do you need: ") Num_max = raw_input("What is the max value you need: ") Num_min = raw_input("What is the min value you need: ") num_list = [] from random import randint for i in range(int(amount)): num_list.append(randint(int(Num_min), int(Num_max))) print num_list
81bf34bd0e8841eb9dba5da8b1c2cfc8005cfb24
vagerasimov-ozn/python18
/Lessons/lesson 6/class_testing/AninimSurvey.py
738
3.53125
4
class AnonimSurvey: """Собирает анонимные ответы на опросник""" def __init__(self,question): """Содержит вопрос, и подготавливает список для ответа""" self.question = question self.responses = [] def show_question(self): """Показать вопрос""" print(self.question) def store_response(self, new_response): """Сохраняет у нас ответ""" self.responses.append(new_response) def show_results(self): print("результаты нашего опроса следующие:") for response in self.responses: print(f"- {response}")
5b550f916aa21eb985c444582751b57c3baf9ec6
vagerasimov-ozn/python18
/test.py
149
3.515625
4
spi = ['volvo','suzuki','bmv'] #for i in range(5): # print(barsuk) #for i in range(len(spi)): # print(spi[i]) for car in spi: print(car)
fa021815ff156a454f6f8a2c18fa7720aa536d95
vagerasimov-ozn/python18
/rusruletka.py
624
3.640625
4
# Давайте напишем программу русской рулетки import random amount_of_bullets = int(input("Сколько патронов? ")) baraban = [0,0,0,0,0,0] # 0 - пустое гнездо # 1 - гнездо с патроном for i in range(amount_of_bullets): baraban[i] = 1 print("Посмотрите на барабан", baraban) how_much = int(input("сколько раз вы собираетесь нажать на курок? ")) for i in range(how_much): random.shuffle(baraban) if baraban[0] == 1: print("бабах") else: print("щелк")
3530861eb47f9b665eb10a3ddc24f65c886f7288
rihu897/study-03-desktop-01-master
/search.py
1,072
3.578125
4
import pandas as pd import eel ### デスクトップアプリ作成課題 ### 課題6:CSV保存先をHTML画面から指定可能にする def kimetsu_search(word, csv): # トランザクション開始 try : # 検索対象取得 df=pd.read_csv("./" + csv) source=list(df["name"]) # 検索結果 result = "" # 検索 if word in source: result = "『{}』はあります".format(word) else: result = "『{}』はありません".format(word) # 追加 #add_flg=input("追加登録しますか?(0:しない 1:する) >> ") #if add_flg=="1": source.append(word) # 検索結果をコンソールに出力 print(result) # CSV書き込み df=pd.DataFrame(source,columns=["name"]) df.to_csv("./" + csv,encoding="utf_8-sig") print(source) except : result = "ERROR:CSVファイルが見つかりません" # 検索結果を返却 return result
4e50b816c598d0e1b226da7a067cf5cd7cd0764e
ijekel2/projects
/StoneQuest/StoneQuest/scenes/Introduction.py
921
3.75
4
from sys import exit class Introduction(object): def enter(self): ## ## Print the game title and description. print("\n\n\n\n\n\n\n\n\n\n") print(" *****************") print(" ** STONE QUEST **") print(" *****************") print("----------------------------------------------------------------------") print("In this thrilling adventure, you will guide Harry, Ron, and Hermione") print("through several deadly challenges in a quest to save the Sorcerer's") print("Stone from the clutches of the evil and power-hungry Severus Snape.") print("----------------------------------------------------------------------\n") ## ## Ask the user if they want to play the game. print("Would you like to play?") answer = input("[y/n]> ") if answer == "y": return 'Fluffy' else: print("Goodbye!") exit(1)
b56b3f5d3c9b9ffd5aaee009288e30f908045249
ijekel2/projects
/StoneQuest/StoneQuest/scenes/MirrorOfErised.py
5,185
3.75
4
class MirrorOfErised(object): def enter(self): ## ## Print the introductory narrative for Level 6 print("\n") print(" *************************************") print(" ** LEVEL SIX: THE MIRROR OF ERISED **") print(" *************************************") print("----------------------------------------------------------------------") print("You, Harry, having passed through the flames, find yourself standing") print("at the top a staircase that runs around the small chamber as if ") print("cajoling all potentional occupants to descend into the center of the ") print("room and toward the dangers that await. Indeed at the foot of the") print("stairs you see the profile of a full grown man standing transfixed") print("before a beautiful yet terrible full length mirror. However, moving") print("forward, you observe not the greasy visage of the long-expected Snape,") print("but the lanky form of Professor Quirrel, his eyes staring madly into") print("the mirror, and his turban quivering with frustration. \n") print("\"Ah! The ever-meddlesome Potter has arrived at last! Just as you") print("predicted, my master. But now... how to obtain the stone?!\"\n") print("You are not sure who Quirrell is talking to, but you are filled with") print("righteous indignation upon discoving the true identity of your enemy.\n") print("\"QUIRREL! You murderous snake,\" you begin as you descend the steps.") print("\"How I have desired to meet you face to face, to be the instrument ") print("of your comeuppance! Too long have you oppressed the weak and gorged") print("yourself on the fear of the powerless! Too long have you sipped the") print("blood of unicorns and wiped your lips with the lush velvet of your") print("sinister turban! TODAY THIS ENDS!\"\n") input("Press Enter to continue...") print("") print("Quirrell is temporarily stunned by your hitherto unsuspected fiery") print("eloquence. You take the opportunity to push him aside and plant") print("yourself firmly in front of the mirror.\n") print("You recognize this mirror from your previous nighttime jaunts around") print("the castle. It is the Mirror of Erised, and to those who gaze into") print("its depths it reflects visions of their hearts' deepest desires.") print("As you position yourself in front of the mirror, you see a reflected") print("Harry placing the Sorcerer's Stone into his pocket. You feel an") print("object in your own pocket that certainly was not there a moment") print("before.\n") print("Quirrell's face changes slowly from surprise to cunning curiosity.") print("You realize that you have obtained the stone, but now you must invent") print("a convincing lie to tell Quirrell when he asks you what you have seen.") print("Luckily, Dumbledore forsaw that the savior of the stone would need to") print("furnish a quality fib. You see writing appear in the mirror:\n") print(" LSMFYE OLEOWN FOAI COSSK HKCIT ESE LONGHDI IRAP\n") print("\"What do you see in the mirror, boy?\"") print("----------------------------------------------------------------------\n") ## ## Get the user's input in response to Quirrell's question.' print("Respond to Quirrell with a convincing lie. Make sure to use correct") print("punctuation so as not to arouse suspicion.") lie = input("[fib]>") if lie == "I see myself holding a pair of thick, woolen socks.": print("----------------------------------------------------------------------") print("Quirrell is entirely convinced, but suddenly you hear a high, cold") print("voice emanating from his turban.\n") print("\"He liieeeesss!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'Voldemort' elif "," not in lie: print("----------------------------------------------------------------------") print("Quirrell is a stickler for punctuation, and your missing comma rouses") print("his suspicion.\n") print("\"Turn out your pockets, Potter!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'DeathToChess' elif "." not in lie: print("----------------------------------------------------------------------") print("Quirrell is a stickler for punctuation, and your missing period rouses") print("his suspicion.\n") print("\"Turn out your pockets, Potter!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'DeathToChess' else: print("----------------------------------------------------------------------") print("Quirrell does not find your lie plausible and his suspicion is roused.\n") print("\"Turn out your pockets, Potter!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'DeathToChess'
ffc720c4cc661893ee61c92899e255f3a093ef24
DimmeGz/green_lantern
/lantern/tdd/lonely_robot.py
4,943
3.765625
4
class Asteroid: def __init__(self, x, y): self.x = x self.y = y class Robot: compass = ['N', 'E', 'S', 'W'] def __init__(self, x, y, asteroid, direction, obstacle): self.x = x self.y = y self.asteroid = asteroid self.direction = direction self.obstacle = obstacle self.health = 100 self.battery = 100 if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise MissAsteroidError('The robot flew beside asteroid') if self.x == obstacle.x and self.y == obstacle.y: raise ObstacleCrashError('The robot crashed into an obstacle') def turn_left(self): if self.direction in self.compass: self.battery -= 1 self.battery_check() self.direction = self.compass[self.compass.index(self.direction) - 1] def turn_right(self): if self.direction in self.compass: self.battery -= 1 self.battery_check() self.direction = self.compass[(self.compass.index(self.direction) + 1) % 4] def battery_check(self): if self.battery == 0: raise LowBatteryError('Battery is empty') def move_forward(self): move_ffwd_dict = {'W': (self.x - 1, self.y), 'E': (self.x + 1, self.y), 'S': (self.x, self.y - 1), 'N': (self.x, self.y + 1)} self.x, self.y = move_ffwd_dict[self.direction] self.battery -= 1 self.battery_check() if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise RobotCrashError('The robot fell down from the asteroid') if self.x == self.obstacle.x and self.y == self.obstacle.y: self.health -= 10 if self.health == 0: raise RobotCrashError('Robot is destroyed') self.move_backward() self.forward_detour() def forward_detour(self): if (self.direction == 'N' and self.x != self.asteroid.x) or \ (self.direction == 'E' and self.y != 0) or \ (self.direction == 'S' and self.x != 0) or \ (self.direction == 'W' and self.y != self.asteroid.y): self.turn_right() self.move_forward() self.turn_left() for _ in range(2): self.move_forward() self.turn_left() self.move_forward() self.turn_right() else: self.turn_left() self.move_forward() self.turn_right() for _ in range(2): self.move_forward() self.turn_right() self.move_forward() self.turn_left() def move_backward(self): move_back_dict = {'W': (self.x + 1, self.y), 'E': (self.x - 1, self.y), 'S': (self.x, self.y + 1), 'N': (self.x, self.y - 1)} self.x, self.y = move_back_dict[self.direction] self.battery -= 1 self.battery_check() if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise RobotCrashError('The robot fell down from the asteroid') if self.x == self.obstacle.x and self.y == self.obstacle.y: self.health -= 10 if self.health == 0: raise RobotCrashError('Robot is destroyed') self.move_forward() self.backward_detour() def backward_detour(self): if (self.direction == 'N' and self.x != 0) or \ (self.direction == 'E' and self.y != self.asteroid.y) or \ (self.direction == 'S' and self.x != self.asteroid.x) or \ (self.direction == 'W' and self.y != 0): self.turn_right() self.move_backward() self.turn_left() for _ in range(2): self.move_backward() self.turn_left() self.move_backward() self.turn_right() else: self.turn_left() self.move_backward() self.turn_right() for _ in range(2): self.move_backward() self.turn_right() self.move_backward() self.turn_left() def self_destroy(self): del self try: self except NameError: raise RobotCrashError('Robot is self destroyed') class Obstacle: def __init__(self, x, y, asteroid): self.x = x self.y = y self.asteroid = asteroid if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise MissAsteroidError('Obstracle is not on asteroid') class MissAsteroidError(Exception): pass class RobotCrashError(Exception): pass class ObstacleCrashError(Exception): pass class LowBatteryError(Exception): pass
51640e43dbe3038b807c52fb2d65462cad9e226b
ultimabugger/python_homework
/func_num.py
463
3.609375
4
def div(*args): try: arg_1 = float(input("Укажите число x: ")) arg_2 = float(input("Укажите число y: ")) res = arg_1 / arg_2 except ValueError: return "Что-то пошло не так :) Попробуйте еще раз" except ZeroDivisionError: return "На ноль делить нельзя!" return res print(f"Результат деления: {div()}")
6a1bd810422f098ca321fab3dfe9afa4a284e9a0
lukkwc-byte/CSReview
/Queues.py
894
3.84375
4
#Init of a Queue #Enqueue #Dequeing from LinkedLists import * class QueueLL(): def __init__(self): self.LL=LL() def __str__(self): return str(self.LL) def Enqueue(self, node): LL.AddTail(self.LL, node) return def Dequeue(self): ret=self.LL.head self.LL.RemoveHead() return ret class QueueArray(): def __init__(self): self.q=[] def __str__(self): ret="" for i in range(len(self.q)): ret+=str(self.q[i])+" " return ret def Enqueue(self, node): self.q.append(node) return def Dequeue(self): return self.q.pop(0) NodeD=LLNode("D") NodeC=LLNode("C") NodeB=LLNode("B") NodeA=LLNode("A") test=QueueArray() test.Enqueue(NodeA) test.Enqueue(NodeB) test.Enqueue(NodeC) test.Enqueue(NodeD) print(test.Dequeue()) print(test)
f308cd2e7a7c979ab741b91fdc859b338ec453c9
sency90/allCode
/acm/python/1850.py
157
3.515625
4
def gcd(b,s): if s==0: return int(b) else: return gcd(s,b%s) a,b = map(int, input().split()) g = gcd(a,b) i = 0 for i in range(g): print(1, end='')
721e5d6a05f065535b8fdec251e728310ecb9748
neeraj1909/100-days-of-challenge
/project_euler/problem-1.py
448
3.796875
4
#!/bin/python3 import sys def sum_factors_of_n_below_k(k, n): m = (k -1) //n return n *m *(m+1) //2 t = int(input().strip()) for a0 in range(t): n = int(input().strip()) total = 0 #for multiple of 3 total = total + sum_factors_of_n_below_k(n, 3) #for multiple of 5 total = total + sum_factors_of_n_below_k(n, 5) #for multiple of 15 total = total - sum_factors_of_n_below_k(n, 15) print("%s" % total)
02a7e4eafa99a2c99c8c54e45846ef23e6358522
konnomiya/algorithm021
/Week_02/589.N-ary_Tree_Preorder_Traversal.py
553
3.578125
4
class Solution: # iteration def preorder(self, root: 'Node') -> List[int]: stack, res = [root,], [] while stack: node = stack.pop() if node: res.append(node.val) stack.extend(node.children[::-1]) return res # recursive def preorder2(self, root: 'Node') -> List[int]: res = [] if not root: return res res.append(root.val) for child in root.children: res.extend(self.preorder(child)) return res
08e72c506ad7c81b8295b6e3a2d16ff46cb3236d
sayanm-10/py-modules
/main.py
3,660
3.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- __author__ = "Sayan Mukherjee" __version__ = "0.1.0" __license__ = "MIT" import unittest import os from datetime import datetime, timedelta from directory_analyzer import print_dir_summary, analyze_file def datetime_calculator(): ''' A helper to demonstrate the datetime module ''' start_date_1 = 'Feb 27, 2000' start_date_2 = 'Feb 27, 2017' start_date_1 = datetime.strptime(start_date_1, '%b %d, %Y') end_date_1 = start_date_1 + timedelta(days=3) print("The date three days after Feb 27, 2000 is", end_date_1.strftime('%b %d, %Y'), "\n") start_date_2 = datetime.strptime(start_date_2, '%b %d, %Y') end_date_2 = start_date_2 + timedelta(days=3) print("The date three days after Feb 27, 2017 is", end_date_2.strftime('%b %d, %Y'), "\n") date_diff_start = datetime.strptime('Jan 1, 2017', '%b %d, %Y') date_diff_end = datetime.strptime('Oct 31, 2017', '%b %d, %Y') date_diff = date_diff_end - date_diff_start print("{} days passed between Jan 1, 2017 and Oct 31, 2017".format(date_diff.days)) def file_reader(path, field_num, sep, header=False): ''' a generator function to read text files and return all of the values on a single line on each call to next() ''' try: fp = open(path, 'r') except FileNotFoundError: print("\n\nError while opening {} for reading".format(os.path.basename(path))) else: with fp: # skip the first line if header is true if header: next(fp) for line_num, line in enumerate(fp): fields = line.strip().split(sep) if (len(fields) < field_num): raise ValueError('\n\n {} has {} fields on line {} but expected {}'.format(os.path.basename(path), len(fields), line_num + 1, field_num)) else: # return fields from 0:field_num as tuple yield tuple(fields[:field_num]) class FileOpsTest(unittest.TestCase): ''' Includes all test cases for file operations ''' def test_file_reader(self): ''' test file_reader() ''' # test ValueError is raised if expected number # of fields exceeds the actual fields with self.assertRaises(ValueError) as context: for fields in file_reader('test_file_reader.txt', 6, '|', False): print(fields) self.assertTrue('Caught error' in str(context.exception)) # match the first returned tuple expected_result = ('John ', ' Doe ', ' 102000 ', ' Age: 36 ', ' NJ') self.assertEqual(next(file_reader('test_file_reader.txt', 5, '|', True)), expected_result) def test_print_dir_summary(self): ''' test individual o/p of print_dir_summary ''' try: fp = open('main.py', 'r') except FileNotFoundError: print('Unit test needs to run on main.py') else: classes, funcs, lines, chars = analyze_file(fp) self.assertEqual(classes, 1) self.assertEqual(funcs, 4) self.assertEqual(lines, 100) self.assertTrue(chars > 1) if __name__ == "__main__": ''' This is executed when run from the command line ''' print("\n\n************************* Problem 1 ******************************\n\n") datetime_calculator() print("\n\n************************* Problem 3 ******************************\n\n") print_dir_summary(os.getcwd()) print("\n\n************************* Unit Tests ******************************\n\n") unittest.main(exit=False, verbosity=2)
df11433519e87b3a52407745b274a6db005d767c
jtquisenberry/PythonExamples
/Interview_Cake/hashes/inflight_entertainment_deque.py
1,754
4.15625
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/inflight-entertainment?section=hashing-and-hash-tables&course=fc1 # Use deque # Time = O(n) # Space = O(n) # As with the set-based solution, using a deque ensures that the second movie is not # the same as the current movie, even though both could have the same length. def can_two_movies_fill_flight(movie_lengths, flight_length): # Determine if two movie runtimes add up to the flight length # And do not show the same movie twice. lengths = deque(movie_lengths) while len(lengths) > 0: current_length = lengths.popleft() second_length = flight_length - current_length if second_length in lengths: return True return False # Tests class Test(unittest.TestCase): def test_short_flight(self): result = can_two_movies_fill_flight([2, 4], 1) self.assertFalse(result) def test_long_flight(self): result = can_two_movies_fill_flight([2, 4], 6) self.assertTrue(result) def test_one_movie_half_flight_length(self): result = can_two_movies_fill_flight([3, 8], 6) self.assertFalse(result) def test_two_movies_half_flight_length(self): result = can_two_movies_fill_flight([3, 8, 3], 6) self.assertTrue(result) def test_lots_of_possible_pairs(self): result = can_two_movies_fill_flight([1, 2, 3, 4, 5, 6], 7) self.assertTrue(result) def test_only_one_movie(self): result = can_two_movies_fill_flight([6], 6) self.assertFalse(result) def test_no_movies(self): result = can_two_movies_fill_flight([], 2) self.assertFalse(result) unittest.main(verbosity=2)
e7d72e428f84364bde9130e8bcecc818ee628a94
jtquisenberry/PythonExamples
/Interview_Cake/arrays/merge_meetings.py
2,921
4.09375
4
import unittest # https://www.interviewcake.com/question/python/merging-ranges?course=fc1&section=array-and-string-manipulation # Sort ranges of tuples # Time: O(n * lg(n)) because of the sorting step. # Space: O(n) -- 1n for sorted_meetings, 1n for merged_meetings. # First, we sort our input list of meetings by start time so any meetings that might # need to be merged are now next to each other. # Then we walk through our sorted meetings from left to right. At each step, either: # We can merge the current meeting with the previous one, so we do. # We can't merge the current meeting with the previous one, so we know the previous meeting can't be merged with any # future meetings and we throw the current meeting into merged_meetings. def merge_ranges(meetings): if len(meetings) < 1: return meetings # Sort by start time n*log(n) sorted_meetings = sorted(meetings) # Initialize merged_meetings with the earliest meeting # The for loop requires comparison with the latest meeting in the list, # so there needs to be a latest meeting in the list. merged_meetings = [sorted_meetings[0]] # Use this alternative for less space use # meetings.sort() for current_start, current_end in sorted_meetings[1:]: merged_start, merged_end = merged_meetings[-1] if current_start <= merged_end: # Overlapping meeting merged_meetings[-1] = (merged_start, max(merged_end, current_end)) else: # Non-overlapping meeting merged_meetings.append((current_start, current_end)) return merged_meetings # Tests class Test(unittest.TestCase): def test_meetings_overlap(self): actual = merge_ranges([(1, 3), (2, 4)]) expected = [(1, 4)] self.assertEqual(actual, expected) def test_meetings_touch(self): actual = merge_ranges([(5, 6), (6, 8)]) expected = [(5, 8)] self.assertEqual(actual, expected) def test_meeting_contains_other_meeting(self): actual = merge_ranges([(1, 8), (2, 5)]) expected = [(1, 8)] self.assertEqual(actual, expected) def test_meetings_stay_separate(self): actual = merge_ranges([(1, 3), (4, 8)]) expected = [(1, 3), (4, 8)] self.assertEqual(actual, expected) def test_multiple_merged_meetings(self): actual = merge_ranges([(1, 4), (2, 5), (5, 8)]) expected = [(1, 8)] self.assertEqual(actual, expected) def test_meetings_not_sorted(self): actual = merge_ranges([(5, 8), (1, 4), (6, 8)]) expected = [(1, 4), (5, 8)] self.assertEqual(actual, expected) def test_sample_input(self): actual = merge_ranges([(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]) expected = [(0, 1), (3, 8), (9, 12)] self.assertEqual(actual, expected) if __name__ == '__main__': unittest.main(verbosity=2)
8eeff2df65c400e2ae316070389736e46dc1fc2b
jtquisenberry/PythonExamples
/Jobs/bynder_isomorphic_strings.py
1,227
3.609375
4
import unittest def is_isomorphic(str1, str2): if len(str1) != len(str2): return False character_map = dict() seen_values = set() for i in range(len(str1)): if str1[i] in character_map: if str2[i] != character_map[str1[i]]: return False else: character_map[str1[i]] = str2[i] if str2[i] in seen_values: return False seen_values.add(str2[i]) return True class Test(unittest.TestCase): def setUp(self): pass def test_1(self): str1 = 'egg' str2 = 'app' result = is_isomorphic(str1, str2) self.assertTrue(result) def test_2(self): str1 = 'cow' str2 = 'app' result = is_isomorphic(str1, str2) self.assertFalse(result) def test_3(self): str1 = 'egs' str2 = 'add' result = is_isomorphic(str1, str2) self.assertFalse(result) def test_4(self): str1 = 'paper' str2 = 'title' result = is_isomorphic(str1, str2) self.assertTrue(result) if __name__ == '__main__': unittest.main()
dbfbd24fa14eeef9f495b3e6c08b428e8274159f
jtquisenberry/PythonExamples
/Simple_Samples/list_comprehension_multiple.py
104
3.578125
4
X = [['a','b','c'],['z','y','x'],['1','2','3']] aaa = [word for words in X for word in words] print(aaa)
e1c7953b7d1f52122d545583785a842e187a7bd7
jtquisenberry/PythonExamples
/Simple_Samples/array_to_tree.py
2,656
3.734375
4
import math from collections import deque class Node(): def __init__(self, value, left_child = None, right_child = None): self.value = value self.left = None self.right = None def __str__(self): return str(self.value) nodes = [1,2,3,4,5,6,7,8] current_index = 0 unlinked_nodes = [] max_power = math.log(len(nodes) + 1, 2) if max_power == int(max_power): # No change - already an integer. max_power = int(max_power) else: max_power = int(max_power) + 1 for power_of_two in range(0,max_power): items_to_place = 2 ** power_of_two items_placed = 0 current_list = [] while (items_placed < items_to_place) and (current_index < len(nodes)): current_list.append(Node(nodes[current_index])) items_placed += 1 current_index += 1 unlinked_nodes.append(current_list) print(current_list) for level in unlinked_nodes: print([l.value for l in level]) for level_number in range(0, len(unlinked_nodes)): #Start with the second-to-last level and work up. print('level', level_number) if level_number < len(unlinked_nodes) - 1: level = unlinked_nodes[level_number] child_index = 0 for node_number in range(0,len(level)): node = level[node_number] print('current_node_number', node_number) for child_node_number in [node_number * 2, node_number * 2 + 1]: print('child_node_number', child_node_number) #print(len(unlinked_nodes[level_number + 1])) if child_node_number < len(unlinked_nodes[level_number + 1]): if child_node_number % 2 == 0: print('even') node.left = unlinked_nodes[level_number + 1][child_node_number] else: print('odd') node.right = unlinked_nodes[level_number + 1][child_node_number] root = unlinked_nodes[0][0] print('root', root) print('root.left', root.left) print('root.right', root.right) print('root.left.left', root.left.left) print('root.left.right', root.left.right) print('root.right.left', root.right.left) print('root.right.right', root.right.right) print('root.left.left.left', root.left.left.left) # Print tree using bread-first search visited_nodes = deque() visited_nodes.append(root) while len(visited_nodes) > 0: current_node = visited_nodes.popleft() print(current_node) node = current_node.left if node is not None: visited_nodes.append(node) node = current_node.right if node is not None: visited_nodes.append(node)
5e5c7d41a7344b9eb94f9f9dbde5dbe48390b5f6
jtquisenberry/PythonExamples
/Interview_Cake/trees_and_graphs/graph_coloring.py
6,495
4.3125
4
import unittest # https://www.interviewcake.com/question/python/graph-coloring?section=trees-graphs&course=fc1 # We go through the nodes in one pass, assigning each node the first legal color we find. # How can we be sure we'll always have at least one legal color for every node? In a graph with maximum degree DDD, each node has at most DDD neighbors. That means there are at most DDD colors taken by a node's neighbors. And we have D+1D+1D+1 colors, so there's always at least one color left to use. # When we color each node, we're careful to stop iterating over colors as soon as we find a legal color. # Space = O(D), where D is the number of colors. The only data structure is `used_nodes`, which contains # at most D colors. # Time = O(N + M) N because we must look at each node in the list. M is the number of edges # because we must check the color of each neighbor. Each neighbor is at the end of an edge. # We add the color of each neighbor to used_colors. class GraphNode: def __init__(self, label): self.label = label self.neighbors = set() self.color = None def color_graph(graph, colors): # Create a valid coloring for the graph # Color one node at a time. # Handle each node in the list, rather than traversing # the graph. This avoids problems with nodes with no # edges and cycles other than loops. for node in graph: # Check whether there is a loop. If there is a loop, then # a single node is at both ends of an edge. Then, the node # cannot have the same color as itself. if node in node.neighbors: raise Exception('A loop was encountered') # Create a list of used nodes - nodes that have already # been allocated to neighbors. used_colors = set() for neighbor in node.neighbors: # Add the color of each neighbor to the set used_colors.add(neighbor.color) # Apply the first available color to the current node. for color in colors: if color not in used_colors: node.color = color break # Tests class Test(unittest.TestCase): def setUp(self): self.colors = frozenset([ 'red', 'green', 'blue', 'orange', 'yellow', 'white', ]) def assertGraphColoring(self, graph, colors): self.assertGraphHasColors(graph, colors) self.assertGraphColorLimit(graph) for node in graph: self.assertNodeUniqueColor(node) def assertGraphHasColors(self, graph, colors): for node in graph: msg = 'Node %r color %r not in %r' % (node.label, node.color, colors) self.assertIn(node.color, colors, msg=msg) def assertGraphColorLimit(self, graph): max_degree = 0 colors_found = set() for node in graph: degree = len(node.neighbors) max_degree = max(degree, max_degree) colors_found.add(node.color) max_colors = max_degree + 1 used_colors = len(colors_found) msg = 'Used %d colors and expected %d at most' % (used_colors, max_colors) self.assertLessEqual(used_colors, max_colors, msg=msg) def assertNodeUniqueColor(self, node): for adjacent in node.neighbors: msg = 'Adjacent nodes %r and %r have the same color %r' % ( node.label, adjacent.label, node.color, ) self.assertNotEqual(node.color, adjacent.color, msg=msg) def test_line_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_d = GraphNode('d') node_a.neighbors.add(node_b) node_b.neighbors.add(node_a) node_b.neighbors.add(node_c) node_c.neighbors.add(node_b) node_c.neighbors.add(node_d) node_d.neighbors.add(node_c) graph = [node_a, node_b, node_c, node_d] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_separate_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_d = GraphNode('d') node_a.neighbors.add(node_b) node_b.neighbors.add(node_a) node_c.neighbors.add(node_d) node_d.neighbors.add(node_c) graph = [node_a, node_b, node_c, node_d] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_triangle_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_a.neighbors.add(node_b) node_a.neighbors.add(node_c) node_b.neighbors.add(node_a) node_b.neighbors.add(node_c) node_c.neighbors.add(node_a) node_c.neighbors.add(node_b) graph = [node_a, node_b, node_c] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_envelope_graph(self): node_a = GraphNode('a') node_b = GraphNode('b') node_c = GraphNode('c') node_d = GraphNode('d') node_e = GraphNode('e') node_a.neighbors.add(node_b) node_a.neighbors.add(node_c) node_b.neighbors.add(node_a) node_b.neighbors.add(node_c) node_b.neighbors.add(node_d) node_b.neighbors.add(node_e) node_c.neighbors.add(node_a) node_c.neighbors.add(node_b) node_c.neighbors.add(node_d) node_c.neighbors.add(node_e) node_d.neighbors.add(node_b) node_d.neighbors.add(node_c) node_d.neighbors.add(node_e) node_e.neighbors.add(node_b) node_e.neighbors.add(node_c) node_e.neighbors.add(node_d) graph = [node_a, node_b, node_c, node_d, node_e] tampered_colors = list(self.colors) color_graph(graph, tampered_colors) self.assertGraphColoring(graph, self.colors) def test_loop_graph(self): node_a = GraphNode('a') node_a.neighbors.add(node_a) graph = [node_a] tampered_colors = list(self.colors) with self.assertRaises(Exception): color_graph(graph, tampered_colors) unittest.main(verbosity=2)
fcbb62045b3d953faf05dd2b741cd060376ec237
jtquisenberry/PythonExamples
/Jobs/maze_runner.py
2,104
4.1875
4
# Alternative solution at # https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/ # Maze Runner # 0 1 0 0 0 # 0 0 0 1 0 # 0 1 0 0 0 # 0 0 0 1 0 # 1 - is a wall # 0 - an empty cell # a robot - starts at (0,0) # robot's moves: 1 step up/down/left/right # exit at (N-1, M-1) (never 1) # length(of the shortest path from start to the exit), -1 when exit is not reachable # time: O(NM), N = columns, M = rows # space O(n), n = size of queue from collections import deque import numpy as np def run_maze(maze): rows = len(maze) cols = len(maze[0]) row = 0 col = 0 distance = 1 next_position = deque() next_position.append((row, col, distance)) # successful_routes = list() while len(next_position) > 0: array2 = np.array(maze) print(array2) print() current_row, current_column, current_distance = next_position.popleft() if current_row == rows - 1 and current_column == cols - 1: return current_distance # successful_routes.append(current_distance) maze[current_row][current_column] = 8 if current_row > 0: up = (current_row - 1, current_column, current_distance + 1) if maze[up[0]][up[1]] == 0: next_position.append(up) if current_row + 1 < rows: down = (current_row + 1, current_column, current_distance + 1) if maze[down[0]][down[1]] == 0: next_position.append(down) if current_column > 0: left = (current_row, current_column - 1, current_distance + 1) if maze[left[0]][left[1]] == 0: next_position.append(left) if current_column + 1 < cols: right = (current_row, current_column + 1, current_distance + 1) if maze[right[0]][right[1]] == 0: next_position.append(right) return -1 if __name__ == '__main__': maze = [ [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0]] length = run_maze(maze) print(length)
ba8395ab64f7ebb77cbfdb205d828aa552802505
jtquisenberry/PythonExamples
/Interview_Cake/arrays/reverse_words_in_list_deque.py
2,112
4.25
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1 # Solution with deque def reverse_words(message): if len(message) < 1: return message final_message = deque() current_word = [] for i in range(0, len(message)): character = message[i] if character != ' ': current_word.append(character) if character == ' ' or i == len(message) - 1: # Use reversed otherwise extend puts characters in the wrong order. final_message.extendleft(reversed(current_word)) current_word = [] if i != len(message) - 1: final_message.extendleft(' ') for i in range(0, len(message)): message[i] = list(final_message)[i] return list(final_message) # Tests class Test(unittest.TestCase): def test_one_word(self): message = list('vault') reverse_words(message) expected = list('vault') self.assertEqual(message, expected) def test_two_words(self): message = list('thief cake') reverse_words(message) expected = list('cake thief') self.assertEqual(message, expected) def test_three_words(self): message = list('one another get') reverse_words(message) expected = list('get another one') self.assertEqual(message, expected) def test_multiple_words_same_length(self): message = list('rat the ate cat the') reverse_words(message) expected = list('the cat ate the rat') self.assertEqual(message, expected) def test_multiple_words_different_lengths(self): message = list('yummy is cake bundt chocolate') reverse_words(message) expected = list('chocolate bundt cake is yummy') self.assertEqual(message, expected) def test_empty_string(self): message = list('') reverse_words(message) expected = list('') self.assertEqual(message, expected) unittest.main(verbosity=2)
37506921175e5dfec216a7b8c0433d421e0cdbd1
jtquisenberry/PythonExamples
/numpy_examples/multiplication.py
365
3.703125
4
import numpy as np X = \ [ [3, 2, 8], [3, 3, 4], [7, 2, 5] ] Y = \ [ [2, 3], [4, 2], [5, 5] ] X = np.array(X) Y = np.array(Y) print("INPUT MATRICES") print("X") print(X) print("Y") print(Y) print() print("DOT PRODUCT") print(np.dot(X, Y)) print() print("CROSS PRODUCT") print(np.cross(X, Y))
8236247559f5951c95d1bd1a5074393c8feb8967
jtquisenberry/PythonExamples
/Leetcode/triangle4.py
488
3.640625
4
from functools import lru_cache triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] class Solution: def minimumTotal(self, triangle): @lru_cache() def dfs(i, level): if level == len(triangle): return 0 left = triangle[level][i] + dfs(i, level + 1) right = triangle[level][i] + dfs(i + 1, level + 1) return min(left, right) return dfs(0, 0) solution = Solution() print(solution.minimumTotal(triangle))
6abe6859f0ce87b6a8d6cdd400a0c910246b0f0d
jtquisenberry/PythonExamples
/Leetcode/1342_number_of_steps_to_reduce_a_number_to_zero.py
408
3.71875
4
from typing import * class Solution: def numberOfSteps(self, num: int) -> int: steps = 0 while num > 0: # print(num, bin(num)) if num & 1: steps += 1 steps += 1 num = num >> 1 # print(steps) if steps - 1 > -1: return steps - 1 return 0 # Input #14 #8 #123 # Output #6 #4 #12
83cf3df4820c5d6a21118a51a2869080067a7870
jtquisenberry/PythonExamples
/Interview_Cake/combinatorics/find_duplicated_number_set.py
1,037
3.984375
4
import unittest # https://www.interviewcake.com/question/python/which-appears-twice?course=fc1&section=combinatorics-probability-math # Find the number that appears twice in a list. # This version is not the recommended version. This version uses a set. # Space O(n) # Time O(n) def find_repeat(numbers_list): # Find the number that appears twice number_set = set() for number in numbers_list: if number in number_set: return number else: number_set.add(number) return # Tests class Test(unittest.TestCase): def test_short_list(self): actual = find_repeat([1, 2, 1]) expected = 1 self.assertEqual(actual, expected) def test_medium_list(self): actual = find_repeat([4, 1, 3, 4, 2]) expected = 4 self.assertEqual(actual, expected) def test_long_list(self): actual = find_repeat([1, 5, 9, 7, 2, 6, 3, 8, 2, 4]) expected = 2 self.assertEqual(actual, expected) unittest.main(verbosity=2)
9adfabfbc83b97a11ee5b2f23cea5ec2eb357dd5
jtquisenberry/PythonExamples
/Interview_Cake/sorting/merge_sorted_lists3.py
1,941
4.21875
4
import unittest from collections import deque # https://www.interviewcake.com/question/python/merge-sorted-arrays?course=fc1&section=array-and-string-manipulation def merge_lists(my_list, alices_list): # Combine the sorted lists into one large sorted list if len(my_list) == 0 and len(alices_list) == 0: return my_list if len(my_list) > 0 and len(alices_list) == 0: return my_list if len(my_list) == 0 and len(alices_list) > 0: return alices_list merged_list = [] my_index = 0 alices_index = 0 while my_index < len(my_list) and alices_index < len(alices_list): if my_list[my_index] < alices_list[alices_index]: merged_list.append(my_list[my_index]) my_index += 1 else: merged_list.append(alices_list[alices_index]) alices_index += 1 if my_index < len(my_list): merged_list += my_list[my_index:] if alices_index < len(alices_list): merged_list += alices_list[alices_index:] return merged_list # Tests class Test(unittest.TestCase): def test_both_lists_are_empty(self): actual = merge_lists([], []) expected = [] self.assertEqual(actual, expected) def test_first_list_is_empty(self): actual = merge_lists([], [1, 2, 3]) expected = [1, 2, 3] self.assertEqual(actual, expected) def test_second_list_is_empty(self): actual = merge_lists([5, 6, 7], []) expected = [5, 6, 7] self.assertEqual(actual, expected) def test_both_lists_have_some_numbers(self): actual = merge_lists([2, 4, 6], [1, 3, 7]) expected = [1, 2, 3, 4, 6, 7] self.assertEqual(actual, expected) def test_lists_are_different_lengths(self): actual = merge_lists([2, 4, 6, 8], [1, 7]) expected = [1, 2, 4, 6, 7, 8] self.assertEqual(actual, expected) unittest.main(verbosity=2)
2950d12a2c1981f470e285bb6af54e51bdc6fa94
jtquisenberry/PythonExamples
/Pandas_Examples/groupby_unstack.py
1,464
3.890625
4
import pandas as pd import matplotlib.pyplot as plt # https://stackoverflow.com/questions/51163975/pandas-add-column-name-to-results-of-groupby # There are two ways to give a name to an aggregate column. # It may be necessary to unstack a compound DataFrame first. # Initial DataFrame d = {'timeIndex': [1, 1, 1, 9, 1, 1, 1, 2, 2, 2], 'isZero': [0, 0, 0, 1, 1, 1, 1, 0, 1, 0]} df = pd.DataFrame(data=d) print(df) print() # Group by one column # The sum aggregate function creates a series # notice that the sum does not have a column header df_agg = df.groupby('timeIndex', as_index=False)['isZero'].sum() print(type(df_agg)) print(df_agg) print() # Unstack OPTION 1, set as_index=False df_agg = df.groupby('timeIndex', as_index=False)['isZero'].sum() print(type(df_agg)) print(df_agg) print() data = { 'FirstName':['Tom', 'Tom', 'David', 'Alex', 'Alex', 'Tom'], 'LastName': ['Jones', 'Jones', 'Smith', 'Thompson', 'Thompson', 'Chuckles'], 'Number': [1,18,24,81,63,6] } df = pd.DataFrame(data) # This format creates a compound DataFrame df_agg = df.groupby(['FirstName']).agg({'Number': sum}) print(df_agg) print() # Unstack OPTION 1, set as_index=False df_agg = df.groupby(['FirstName'], as_index=False).agg({'Number': sum}) print(df_agg) print() # Unstack OPTION 2, use to_frame # The argument of to_frame is the name of the new field. df2 = df.groupby(['FirstName'])['Number'].sum().to_frame('Number_Sum').reset_index() print(df2)