blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b5e51529e0c68b4c5d3879f9c034ce8540fadeab
itCatface/idea_python
/py_pure/src/catface/introduction/07_oo_senior/2_property.py
1,692
3.890625
4
# -@property[既能检查参数,又可以用类似属性这样简单的方式来访问类的变量] # 常规getter&setter class Student(object): def __init__(self): pass def set_score(self, score): if not isinstance(score, int): raise ValueError('score must be an integer') if score < 0 or score > 100: raise ValueError('score must between 0~100') self._score = score def get_score(self): return self._score s1 = Student() # s1.set_score('78') # s1.set_score(789) s1.set_score(78) print("s1's get_score:", s1.get_score()) # 使用@property将方法变成属性调用 class Animal(object): @property def age(self): return self._age @age.setter def age(self, age): if not isinstance(age, int): raise ValueError('age must be an integer') if age < 0: raise ValueError('age must > 0') self._age = age a1 = Animal() # a1.age = '12' # a1.age = -1 a1.age = 1 print("a1's age:", a1.age) # ex1. 利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution class Screen(object): @property def width(self): return self._width @width.setter def width(self, width): self._width = width @property def height(self): return self._height @height.setter def height(self, height): self._height = height # 只读属性==>只定义getter方法,不定义setter方法 @property def resolution(self): return self._width * self._height s = Screen() s.width = 768 s.height = 1024 print("s's resolution is:", s.resolution)
d2feee5ec35d4bf4575cf61a98bf6d62ef9fb771
itCatface/idea_python
/py_pure/src/catface/introduction/01_base/5_for.py
1,222
3.765625
4
# -循环 def test_for(): # for nums = (1, 2, 3, 4, 5) sum = 0 for x in nums: sum += x print(sum) # 15 for i, v in enumerate(nums): print('第%d个位置的值为%d' % (i, v)) # 第0个位置的值为1\n第1个位置的值为2... # range nums = list(range(10)) # range(x): 生成一个整数序列 | list(range(x)): 通过list()将整数序列转换为list print('range(5):', range(5), 'nums: ', nums) # range(0, 5) nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # while sum = 0 num = 100 while num > 0: sum += num num -= 1 print(sum) # 5050 # 练习:循环打印['zhangsan', ...] names = ['zhangsan', 'lisi', 'wanger', 'mazi'] for name in names: print('hi:', name) # break[提前退出循环] & continue[结束本轮循环,直接开始下一轮循环] n = 0 while n < 5: n += 1 if n > 3: # break可退出循环 break print(n) # 1 2 3 n = 0 while n < 6: n += 1 if n % 2 == 0: # continue结束本次循环并开始下一轮循环,通常配合if使用 continue print(n) # 1 3 5 test_for()
262604114db21368103f6c8e670fa17d1b640bed
dante092/Caesar-Cypher
/kassuro.py
5,718
4.3125
4
#!/usr/bin/python3 def encrypt(string, rotate): """ Encrypt given input string with the caeser cypher. args: string (str): string to encrypt. rotate (int): number by whiche the characters are rotated. returns: str: encrypted version of the input string. raises: TypeError: if word is not a string or rotate not an int. ValueError: if word is empty string or rotate is smaller than 1. """ if not isinstance(string, str) or not isinstance(rotate, int): raise TypeError elif not string or rotate < 1: raise ValueError else: encrypted_string = '' for char in string: if not char.isalpha(): encrypted_string += char else: char_code = ord(char) # check if rotated char code is bigger than char code of z if char_code + rotate > 122: # if so, compute left rotations after z and start from a char_code = 96 + (char_code + rotate - 122) # check if rotated char code is bigger than char code of Z but # smaller than char code of a elif char_code + rotate > 90 and char_code + rotate < 97: # if so, compute left rotations after Z and start from A char_code = 64 + (char_code + rotate - 90) else: char_code += rotate encrypted_string += chr(char_code) return encrypted_string def decrypt(string, rotate): """ Decrypt given input string with the caeser cypher. args: string (str): string to decrypt. rotate (int): number by whiche the characters are rotated. returns: str: decrypted version of the input string. raises: TypeError: if word is not a string or rotate not an int. ValueError: if word is empty string or rotate is smaller than 1. """ if not isinstance(string, str) or not isinstance(rotate, int): raise TypeError elif not string or rotate < 1: raise ValueError else: decrypted_string = '' for char in string: if not char.isalpha(): decrypted_string += char else: char_code = ord(char) # check if rotated char code is smaller than char code for a # but char code is bigger than char code for a - 1 if char_code - rotate < 97 and char_code > 96: # if true, than start over from z char_code = 123 - (rotate - (char_code - 97)) # check if rotated char code is smaller than A elif char_code - rotate < 65: # if ture, than start over from Z char_code = 91 - (rotate - (char_code - 65)) else: char_code -= rotate decrypted_string += chr(char_code) return decrypted_string if __name__ == '__main__': zen = "Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!" zen_encrypt = "Ilhbapmbs pz ilaaly aohu bnsf. Lewspjpa pz ilaaly aohu ptwspjpa. Zptwsl pz ilaaly aohu jvtwsle. Jvtwsle pz ilaaly aohu jvtwspjhalk. Msha pz ilaaly aohu ulzalk. Zwhyzl pz ilaaly aohu kluzl. Ylhkhipspaf jvbuaz. Zwljphs jhzlz hylu'a zwljphs luvbno av iylhr aol ybslz. Hsaovbno wyhjapjhspaf ilhaz wbypaf. Lyyvyz zovbsk ulcly whzz zpsluasf. Buslzz lewspjpasf zpslujlk. Pu aol mhjl vm htipnbpaf, ylmbzl aol altwahapvu av nblzz. Aolyl zovbsk il vul-- huk wylmlyhisf vusf vul --vicpvbz dhf av kv pa. Hsaovbno aoha dhf thf uva il vicpvbz ha mpyza buslzz fvb'yl Kbajo. Uvd pz ilaaly aohu ulcly. Hsaovbno ulcly pz vmalu ilaaly aohu *ypnoa* uvd. Pm aol ptwsltluahapvu pz ohyk av lewshpu, pa'z h ihk pklh. Pm aol ptwsltluahapvu pz lhzf av lewshpu, pa thf il h nvvk pklh. Uhtlzwhjlz hyl vul ovurpun nylha pklh -- sla'z kv tvyl vm aovzl!" print("Starting assert-tests:") print("encrypting tests:") assert encrypt('abcd', 1) == 'bcde' print('Test 01: passed') assert encrypt('xyz', 2) == 'zab' print('Test 02: passed') assert encrypt('ABC', 2) == 'CDE' print('Test 03: passed') assert encrypt('Hallo', 3) == 'Kdoor' print('Test 04: passed') assert encrypt('XYZ', 2) == 'ZAB' print('Test 05: passed') assert encrypt(zen, 7) == zen_encrypt print("Test 06: passed") print("decrypting tests:") assert decrypt('bcde', 1) == 'abcd' print('Test 07: passed') assert decrypt('zab', 2) == 'xyz' print('Test 08: passed') assert decrypt('CDE', 2) == 'ABC' print('Test 09: passed') assert decrypt('Kdoor', 3) == 'Hallo' print('Test 10: passed') assert decrypt('ZAB', 2) == 'XYZ' print('Test 11: passed') assert decrypt(zen_encrypt, 7) == zen print("Test 12: passed")
db18e85eb77c5d672ef397b4f21560e92a7ef5ad
johan-eriksson/advent-of-code-2019
/src/day7.py
5,242
3.5625
4
import itertools import math class Computer(): def __init__(self, phase): self.OPCODES = { 1: self.ADD, 2: self.MUL, 3: self.WRITE, 4: self.READ, 5: self.JNZ, 6: self.JEZ, 7: self.LT, 8: self.EQ, 99: self.EXIT } self.input = [] self.input.append(phase) self.phase = phase self.last_output = None self.input_index = 0 self.PC = 0 self.output_targets = [] self.running = True def read_from_file(self, file, delimiter=','): self.memory = [] with open(file) as f: self.memory.extend([x.strip() for x in f.read().split(',')]) def run(self): while self.running: if self.PC<len(self.memory): if self.PC<len(self.memory): mode = self.memory[self.PC][:-2] op = int(self.memory[self.PC][-2:]) result = self.OPCODES[op](mode) if result == -1: return False else: print("Ran through entire memory") self.running = False return True def add_output_target(self, f): self.output_targets.append(f) def pad_mode(self, mode, goal): while len(mode) < goal: mode = "0" + mode mode = mode[::-1] return mode def get_value(self, mode, value): # mode==1 is immediate mode, mode==0 is position mode if not mode or mode=="0": return self.memory[int(value)] elif mode=="1": return value print("ERROR: Got mode unsupported mode: "+str(mode)) return False def add_input(self, i): self.input.append(i) def send_output(self, out): self.last_output = out for f in self.output_targets: f(out) def ADD(self, mode): mode = self.pad_mode(mode, 3) operand0 = self.get_value(mode[0], self.memory[self.PC+1]) operand1 = self.get_value(mode[1], self.memory[self.PC+2]) operand2 = int(self.memory[self.PC+3]) self.memory[operand2] = str(int(operand0) + int(operand1)) self.PC += 4 def MUL(self, mode): mode = self.pad_mode(mode, 3) operand0 = self.get_value(mode[0], self.memory[self.PC+1]) operand1 = self.get_value(mode[1], self.memory[self.PC+2]) operand2 = int(self.memory[self.PC+3]) self.memory[operand2] = str(int(operand0) * int(operand1)) self.PC += 4 def WRITE(self, mode): if len(self.input) > self.input_index: operand0 = int(self.memory[self.PC+1]) self.memory[operand0] = self.input[self.input_index] self.input_index += 1 self.PC += 2 else: return -1 def READ(self, mode): operand0 = self.get_value(mode, self.memory[self.PC+1]) self.send_output(operand0) self.PC += 2 def JNZ(self, mode): mode = self.pad_mode(mode, 2) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) if operand0 == 0: self.PC += 3 else: self.PC = operand1 def JEZ(self, mode): mode = self.pad_mode(mode, 2) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) if operand0 == 0: self.PC = operand1 else: self.PC += 3 def LT(self, mode): mode = self.pad_mode(mode, 3) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) operand2 = int(self.memory[self.PC+3]) if operand0 < operand1: self.memory[operand2] = 1 else: self.memory[operand2] = 0 self.PC += 4 def EQ(self, mode): mode = self.pad_mode(mode, 3) operand0 = int(self.get_value(mode[0], self.memory[self.PC+1])) operand1 = int(self.get_value(mode[1], self.memory[self.PC+2])) operand2 = int(self.memory[self.PC+3]) if operand0 == operand1: self.memory[operand2] = 1 else: self.memory[operand2] = 0 self.PC += 4 def EXIT(self, mode): self.running = False self.PC += 1 return True def __repr__(self): return "Computer "+str(self.phase) class ResultComparer(): def __init__(self): self.best = 0 def check(self, thrust): thrust = int(thrust) if thrust > self.best: self.best = thrust def get_best(self): return self.best def solvepart1(): rc = ResultComparer() num_computers = 5 for p in itertools.permutations(range(num_computers)): cpus = [] for index, phase in enumerate(p): if index==0: cpu = Computer(str(phase)) cpu.add_input("0") cpus.append(cpu) else: cpus.append(Computer(str(phase))) for i in range(num_computers-1): cpus[i].add_output_target(cpus[i+1].add_input) cpus[num_computers-1].add_output_target(rc.check) for cpu in cpus: cpu.read_from_file('inputs/day7.txt') cpu.run() return rc.get_best() def solvepart2(): rc = ResultComparer() num_computers = 5 for p in itertools.permutations(range(5, 5+num_computers)): cpus = [] for index, phase in enumerate(p): if index==0: cpu = Computer(str(phase)) cpu.add_input("0") cpus.append(cpu) else: cpus.append(Computer(str(phase))) for i in range(num_computers-1): cpus[i].add_output_target(cpus[i+1].add_input) cpus[num_computers-1].add_output_target(cpus[0].add_input) for cpu in cpus: cpu.read_from_file('inputs/day7.txt') while any([cpu.running for cpu in cpus]): for cpu in cpus: cpu.run() rc.check(cpus[num_computers-1].last_output) return rc.get_best() if __name__=='__main__': print(solvepart1()) print(solvepart2())
80643111235604455d6372e409fa248db684da97
s56roy/python_codes
/python_prac/calculator.py
1,136
4.125
4
a = input('Enter the First Number:') b = input('Enter the Second Number:') # The entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions. sum = float(a)+float(b) print(sum) print('The sum of {0} and {1} is {2}'.format(a, b, sum)) print('This is output to the screen') print ('this is output to the screen') print ('The Sum of a & b is', sum) print('The sum is %.1f' %(float(input('Enter again the first number: '))+float(input('Enter again the second number: ')))) print(1,2,3,4) # Output: 1 2 3 4 print(1,2,3,4,sep='*') # Output: 1*2*3*4 print(1,2,3,4,sep='#',end='&') # Output: 1#2#3#4& print('I love {0} and {1}'.format('bread','butter')) # Output: I love bread and butter print('I love {1} and {0}'.format('bread','butter')) # Output: I love butter and bread print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John')) # Hello John, Goodmorning x = 12.3456789 print('The value of x is %3.2f' %x) # The value of x is 12.35 print('The value of x is %3.4f' %x) # The value of x is 12.3457 import math print(math.pi) from math import pi pi
b55313c576269b2fe93fc708e12bf74966886521
MColosso/Wesleyan.-Machine-Learning-for-Data-Analysis
/Week 4. Running a k-means Cluster Analysis.py
7,015
3.6875
4
# # Created on Mon Jan 18 19:51:29 2016 # # @author: jrose01 # Adapted by: mcolosso # from pandas import Series, DataFrame import pandas as pd import numpy as np import matplotlib.pylab as plt from sklearn.cross_validation import train_test_split from sklearn import preprocessing from sklearn.cluster import KMeans plt.rcParams['figure.figsize'] = (15, 5) # # DATA MANAGEMENT # #Load the dataset loans = pd.read_csv("./LendingClub.csv", low_memory = False) # LendingClub.csv is a dataset taken from The LendingClub (https://www.lendingclub.com/) # which is a peer-to-peer leading company that directly connects borrowers and potential # lenders/investors # # Exploring the target column # # The target column (label column) of the dataset that we are interested in is called # `bad_loans`. In this column 1 means a risky (bad) loan and 0 means a safe loan. # # In order to make this more intuitive, we reassign the target to be: # 1 as a safe loan and 0 as a risky (bad) loan. # # We put this in a new column called `safe_loans`. loans['safe_loans'] = loans['bad_loans'].apply(lambda x : 1 if x == 0 else 0) loans.drop('bad_loans', axis = 1, inplace = True) # Select features to handle # In this oportunity, we are going to ignore 'grade' and 'sub_grade' predictors # assuming those are a way to "clustering" the loans predictors = ['short_emp', # one year or less of employment 'emp_length_num', # number of years of employment 'home_ownership', # home_ownership status: own, mortgage or rent 'dti', # debt to income ratio 'purpose', # the purpose of the loan 'term', # the term of the loan 'last_delinq_none', # has borrower had a delinquincy 'last_major_derog_none', # has borrower had 90 day or worse rating 'revol_util', # percent of available credit being used 'total_rec_late_fee', # total late fees received to day ] target = 'safe_loans' # prediction target (y) (+1 means safe, 0 is risky) ignored = ['grade', # grade of the loan 'sub_grade', # sub-grade of the loan ] # Extract the predictors and target columns loans = loans[predictors + [target]] # Delete rows where any or all of the data are missing loans = loans.dropna() # Convert categorical text variables into numerical ones categorical = ['home_ownership', 'purpose', 'term'] for attr in categorical: attributes_list = list(set(loans[attr])) loans[attr] = [attributes_list.index(idx) for idx in loans[attr] ] print((loans.describe()).T) # # MODELING AND PREDICTION # # Standardize clustering variables to have mean=0 and sd=1 for attr in predictors: loans[attr] = preprocessing.scale(loans[attr].astype('float64')) # Split data into train and test sets clus_train, clus_test = train_test_split(loans[predictors], test_size = .3, random_state = 123) print('clus_train.shape', clus_train.shape) print('clus_test.shape', clus_test.shape ) # K-means cluster analysis for 1-9 clusters from scipy.spatial.distance import cdist clusters = range(1,10) meandist = list() for k in clusters: model = KMeans(n_clusters = k).fit(clus_train) clusassign = model.predict(clus_train) meandist.append(sum(np.min(cdist(clus_train, model.cluster_centers_, 'euclidean'), axis=1)) / clus_train.shape[0]) """ Plot average distance from observations from the cluster centroid to use the Elbow Method to identify number of clusters to choose """ plt.plot(clusters, meandist) plt.xlabel('Number of clusters') plt.ylabel('Average distance') plt.title('Selecting k with the Elbow Method') plt.show() # Interpret 5 cluster solution model = KMeans(n_clusters = 5) model.fit(clus_train) clusassign = model.predict(clus_train) # Plot clusters from sklearn.decomposition import PCA pca_2 = PCA(2) plot_columns = pca_2.fit_transform(clus_train) plt.scatter(x = plot_columns[:, 0], y = plot_columns[:, 1], c = model.labels_, ) plt.xlabel('Canonical variable 1') plt.ylabel('Canonical variable 2') plt.title('Scatterplot of Canonical Variables for 5 Clusters') plt.show() # # BEGIN multiple steps to merge cluster assignment with clustering variables to examine # cluster variable means by cluster # # Create a unique identifier variable from the index for the # cluster training data to merge with the cluster assignment variable clus_train.reset_index(level = 0, inplace = True) # Create a list that has the new index variable cluslist = list(clus_train['index']) # Create a list of cluster assignments labels = list(model.labels_) # Combine index variable list with cluster assignment list into a dictionary newlist = dict(zip(cluslist, labels)) newlist # Convert newlist dictionary to a dataframe newclus = DataFrame.from_dict(newlist, orient = 'index') newclus # Rename the cluster assignment column newclus.columns = ['cluster'] # Now do the same for the cluster assignment variable: # Create a unique identifier variable from the index for the cluster assignment # dataframe to merge with cluster training data newclus.reset_index(level = 0, inplace = True) # Merge the cluster assignment dataframe with the cluster training variable dataframe # by the index variable merged_train = pd.merge(clus_train, newclus, on = 'index') merged_train.head(n = 100) # cluster frequencies merged_train.cluster.value_counts() # # END multiple steps to merge cluster assignment with clustering variables to examine # cluster variable means by cluster # # FINALLY calculate clustering variable means by cluster clustergrp = merged_train.groupby('cluster').mean() print ("Clustering variable means by cluster") print(clustergrp) # Validate clusters in training data by examining cluster differences in SAFE_LOANS using ANOVA # first have to merge SAFE_LOANS with clustering variables and cluster assignment data gpa_data = loans['safe_loans'] # split safe_loans data into train and test sets gpa_train, gpa_test = train_test_split(gpa_data, test_size=.3, random_state=123) gpa_train1 = pd.DataFrame(gpa_train) gpa_train1.reset_index(level = 0, inplace = True) merged_train_all = pd.merge(gpa_train1, merged_train, on = 'index') sub1 = merged_train_all[['safe_loans', 'cluster']].dropna() import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi gpamod = smf.ols(formula = 'safe_loans ~ C(cluster)', data = sub1).fit() print (gpamod.summary()) print ('Means for SAFE_LOANS by cluster') m1 = sub1.groupby('cluster').mean() print (m1) print ('Standard deviations for SAFE_LOANS by cluster') m2 = sub1.groupby('cluster').std() print (m2) mc1 = multi.MultiComparison(sub1['safe_loans'], sub1['cluster']) res1 = mc1.tukeyhsd() print(res1.summary())
e890b55a98130e34004f3ad15e02b8993aadf55b
eudaimonious/LPTHW
/ex4.py
1,485
4
4
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car." ''' When I wrote this program the first time I had a mistake, and python told me about it like this: Traceback (most recent call last): File "ex4.py", line 8, in <module> average_passengers_per_car = car_pool_capacity / passenger NameError: name 'car_pool_capacity' is not defined Explain this error in your own words. Make sure you use line numbers and explain why. Here's more extra credit: I used 4.0 for space_in_a_car, but is that necessary? What happens if it's just 4? Remember that 4.0 is a "floating point" number. Find out what that means. Write comments above each of the variable assignments. Make sure you know what = is called (equals) and that it's making names for things. Remember _ is an underscore character. Try running python as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j. '''
1aaec58e360a3897542886686250694e7971b308
yesiamjulie/pyAlgorithm
/AlgoTest/Passing_bridge.py
617
3.53125
4
def solution(bridge_length, weight, truck_weights): answer =0 waiting = truck_weights length_truck = len(truck_weights) passed = [] passing = [] on_bridge = [] while len(passed) != length_truck: for i in range(len(passing)): passing[i] += - 1 if passing and passing[0] == 0: del passing[0] passed.append(on_bridge.pop(0)) if waiting and weight >= sum(on_bridge) + waiting[0]: on_bridge.append(waiting.pop(0)) passing.append(bridge_length) print(passing) answer += 1 return answer
145a53662de78fc1e68618010034705f73b44d62
yesiamjulie/pyAlgorithm
/AlgoTest/SumOfTwoN.py
518
3.59375
4
""" 서로 다른 자연수들로 이루어진 배열 arr와 숫자 n이 입력으로 주어집니다. 만약 배열 arr에 있는 서로 다른 2개의 자연수를 합하여 숫자 n을 만드는 것이 가능하면 true를, 불가능하면 false를 반환하는 함수를 작성하세요. """ def solution(arr, n): answer = False length = len(arr) for i in range(length - 1): for j in range(i + 1, length): if arr[i] + arr[j] == n: answer = True return answer
d1a4bffe153eaaffde01f1bc0f07bb9fe8646941
gurralaharika21/toy-problems
/LRU-oops/Lru_cache.py
1,290
3.5625
4
import collections # import OrderedDict class LRUCache: # dict = {} def __init__(self,capacity :int): self.capacity = capacity self.cache = collections.OrderedDict() def put(self,key:int,value:int): try: self.cache.pop(key) except KeyError: if len(self.cache) >= self.capacity: self.cache.popitem(last=False) # //first in first out self.cache[key] = value def get(self,key:int): try: value = self.cache.pop(key) self.cache[key] = value val = value # print(value) return value except KeyError: # print(-1) return -1 def get_cache(self): return self.cache # print(self.cache) # if __name__ == "__main__": # dict = LRUCache(4) # dict.put(1,10) # dict.put(2,11) # dict.put(3,12) # dict.put(3,13) # dict.put(4,13) # dict.get_cache() # dict.get(7) # self.key = key # self.value = value # cach = LRUCache(4) # dict.put(1,10) # dict.put(2,3) # # print(dict) # # cach = LRUcache(4) # cache.get(1) # capacity = 10 # put(1,10) # put(2,90) # get(2)
3a0af90aa6b19e7c73245e6724db18fb050aef7d
JinhuaShen/Python-Learning
/CalcCount.py
1,038
3.640625
4
import csv import re import sqlite3 def genInfos(file): csvfile = open(file, 'r') reader = csv.reader(csvfile) seeds = [] for seed in reader: seeds.append(seed) csvfile.close() return seeds def showInfos(infos): result = open("result.txt", 'w') tmplist = [] result.write("total count: " + str(len(infos)) + "\n") #print ("total count: " + str(len(infos))) for seed in infos: if seed in tmplist: continue tmplist.append(seed) result.write("unique count: " + str(len(tmplist)) + "\n") #print ("unique count: " + str(len(tmplist))) for seed2 in tmplist: line = str(seed2) + "\t\t\t\t" + str(infos.count(seed2)) + "\n" result.write(line) #print("%s %d" %(seed2,infos.count(seed2))) result.close(); def init(csv): infos = genInfos(csv) showInfos(infos) def main(): init("seed.csv") if __name__ == '__main__': main()
15b45688390a72bdb74852f76cee51101ef1193e
ykcai/Python_ML
/homework/week11_homework.py
679
3.890625
4
# Machine Learning Class Week 11 Homework # 1. An isogram is a word that has no repeating letters, consecutive or nonconsecutive. Create a function that takes a string and returns either True or False depending on whether or not it's an "isogram". # Examples # is_isogram("Algorism") ➞ True # is_isogram("PasSword") ➞ False # # Not case sensitive. # is_isogram("Consecutive") ➞ False # Notes: Ignore letter case (should not be case sensitive). All test cases contain valid one word strings. def is_isogram(word): pass is_isogram("Algorism") is_isogram("PasSword") is_isogram("Consecutive") # 2. What are the 4 different detection models that we covered in class?
69f49e0d03340dbbe2a4cdf5d489d884d2fe5b53
ykcai/Python_ML
/homework/week8_homework.py
599
3.890625
4
# Machine Learning Class Week 8 Homework import numpy as np # 1. Create an array of 10 zeros # 2. Create an array of 10 ones # 3. Create an array of 10 fives # 4. Create an array of the integers from 10 to 50 # 5. Create an array of all the even integers from 10 to 50 # 6. Create a 3x3 matrix with values ranging from 0 to 8 # 7. Create a 3x3 identity matrix # 8. Use NumPy to generate a random number between 0 and 1 # 9. Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution # 10. Create an array of 20 linearly spaced points between 0 and 1.
9060d68c59660d4ee334ee824eda15cc49519de9
ykcai/Python_ML
/homework/week5_homework_answers.py
2,683
4.34375
4
# Machine Learning Class Week 5 Homework Answers # 1. def count_primes(num): ''' COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number count_primes(100) --> 25 By convention, 0 and 1 are not prime. ''' # Write your code here # --------------------------------Code between the lines!-------------------------------- primes = [2] x = 3 if num < 2: # for the case of num = 0 or 1 return 0 while x <= num: for y in range(3, x, 2): # test all odd factors up to x-1 if x % y == 0: x += 2 break else: primes.append(x) x += 2 print(primes) return len(primes) # --------------------------------------------------------------------------------------- def count_primes2(num): ''' COUNT PRIMES FASTER ''' primes = [2] x = 3 if num < 2: return 0 while x <= num: for y in primes: # use the primes list! if x % y == 0: x += 2 break else: primes.append(x) x += 2 print(primes) return len(primes) # Check print(count_primes(100)) # 2. def palindrome(s): ''' Write a Python function that checks whether a passed in string is palindrome or not. Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. ''' # Write your code here # --------------------------------Code between the lines!-------------------------------- # This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces) s = s.replace(' ', '') return s == s[::-1] # Check through slicing # --------------------------------------------------------------------------------------- print(palindrome('helleh')) print(palindrome('nurses run')) print(palindrome('abcba')) # 3. def ran_check(num, low, high): ''' Write a function that checks whether a number is in a given range (inclusive of high and low) ''' # Write your code here # --------------------------------Code between the lines!-------------------------------- # Check if num is between low and high (including low and high) if num in range(low, high+1): print('{} is in the range between {} and {}'.format(num, low, high)) else: print('The number is outside the range.') # --------------------------------------------------------------------------------------- # Check print(ran_check(5, 2, 7)) # 5 is in the range between 2 and 7 => True
0629cc2ce905a9bcb6d02fdf4114394d8e9ab6dc
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/coinimport.py
599
3.8125
4
# This program imports the ocin module and creates an instance of the Coin Class # needs to be the file name or file path if in a different directory import coin def main(): # create an object from the ocin class # needs the filename.module my_coin = coin.Coin() # Display the side of the coin that is facing up print("This side is up: ", my_coin.get_sideup()) # Toss the coin print(" I am tossing the coin ten times: ") for count in range(10): my_coin.toss() print(count+1, my_coin.get_sideup()) # Call the main function main()
e25a8fc38ef3e98e5dc34aae30fbbea316e709c2
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/3.py
1,029
4.21875
4
# 3. Budget Analysis # Write a program that asks the user to enter the amount that he or she has budgeted for amonth. # A loop should then prompt the user to enter each of his or her expenses for the month, and keep a running total. # When the loop finishes, the program should display theamount that the user is over or under budget. def main(): budget = float(input("Enter the amount you have budgeted this month: ")) total = 0 cont = "Y" while cont == "Y" or cont == "y": expense = float(input("Enter the expense amount you want tabulated from the budget: ")) cont = str(input("Enter y to continue or any other key to quit: ")) total += expense if total < budget: bottom_line = budget - total print(f"You are {bottom_line:.2f} under budget.") elif total > budget: bottom_line = total - budget print(f"You are {bottom_line:.2f} over budget.") else: print("Your expenses matched your budget.") main()
2b1cf90a6ed89d0f5162114a103397c0f2a211e8
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/iter.py
612
4.25
4
# Python iterators # mylist = [1, 2, 3, 4] # for item in mylist: # print(item) # def traverse(iterable): # it = iter(iterable) # while True: # try: # item = next(it) # print(item) # except: StopIteration: # break l1 = [1, 2, 3] it = iter(l1) # print next iteration in list # print(it.__next__()) # print(it.__next__()) # print(it.__next__()) # print(it.__next__()) # or you can use this print(next(it)) print(next(it)) print(next(it)) # print(next(it)) # some objects are not itreable and will error iter(100)
b62ba48d92de96b49332b094f8b34a5f5af4a6cb
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/map.py
607
4.375
4
# The map() function # Takes in at least 2 args. Can apply a function to every item in a list/iterable quickly def square(x): return x*x numbers = [1, 2, 3, 4, 5] squarelist = map(square, numbers) print(next(squarelist)) print(next(squarelist)) print(next(squarelist)) print(next(squarelist)) print(next(squarelist)) sqrlist2 = map(lambda x : x*x, numbers) print(next(sqrlist2)) print(next(sqrlist2)) print(next(sqrlist2)) print(next(sqrlist2)) print(next(sqrlist2)) tens = [10, 20, 30, 40, 50] indx = [1, 2, 3, 4, 5] powers = list(map(pow, tens, indx[:3])) print(powers)
8abfe167d6fa9e524df27f0adce9f777f4e2df58
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/5.py
1,278
4.5625
5
# 5. Average Rainfall # Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. # The program should first ask for the number of years. The outer loop will iterate once for each year. # The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. # After all iterations,the program should display the number ofmonths, the total inches of rainfall, and the average rainfall per month for the entire period. monthdict = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } months = 0 years = int(input("Enter a number of years to enter rainfall data for: ")) total_rainfall = 0 for i in range(years): for key in monthdict: rainfall = float(input(f"Enter the rainfall for {monthdict.get(key):}: ")) total_rainfall += rainfall months += 1 average = total_rainfall / months print(f"The total rainfall per for {months:} months is", total_rainfall, "\n" f"The average rainfall a month is {average:}" )
60f890e1dfb13d2bf8071374024ef673509c58b2
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 1.py
1,870
4.59375
5
""" 1. Employee and ProductionWorker Classes Write an Employee class that keeps data attributes for the following pieces of information: • Employee name • Employee number Next, write a class named ProductionWorker that is a subclass of the Employee class. The ProductionWorker class should keep data attributes for the following information: • Shift number (an integer, such as 1, 2, or 3) • Hourly pay rate The workday is divided into two shifts: day and night. The shift attribute will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the night shift is shift 2. Write the appropriate accessor and mutator methods for each class. Once you have written the classes, write a program that creates an object of the ProductionWorker class and prompts the user to enter data for each of the object’s data attributes. Store the data in the object and then use the object’s accessor methods to retrieve it and display it on the screen. """ import worker def main(): shift1 = employees() shift2 = employees() shift3 = employees() displaystuff(shift1) displaystuff(shift2) displaystuff(shift3) def employees(): name = input('Enter the employees name: ') number = int(input('Enter the employee number: ')) shift = int(input('Enter the shift number for the employee, 1 - Days, 2 - Swings, 3 - Mids: ')) pay = float(input('Enter the hourly pay rate of the employee: ')) return worker.ProdWork(name, number, shift, pay) def displaystuff(thingy): print() print('Name: ', thingy.get_name()) print('Employee Number: ', thingy.get_number()) print('Employees Shift: ', thingy.get_shift()) print(f'Employees hourly pay rate ${thingy.get_pay()}') main()
d5b0d5d155c1733eb1a9fa27a7dbf11902673537
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/FunctionExercise/4.py
1,166
4.1875
4
# 4. Automobile Costs # Write a program that asks the user to enter the monthly costs for the following expenses incurred from operating his or her automobile: # loan payment, insurance, gas, oil, tires, andmaintenance. # The program should then display the total monthly cost of these expenses,and the total annual cost of these expenses loan = 0.0 insurance = 0.0 gas = 0.0 oil = 0.0 tire = 0.0 mx = 0.0 def main(): global loan, insurance, gas, oil, tire, mx print("Enter the monthly loan cost") loan = getcost() print("Enter the monthly insurance cost") insurance = getcost() print("Enter the monthly gas cost") gas = getcost() print("Enter the monthly oil cost") oil = getcost() print("Enter the monthly tire cost") tire = getcost() print("Enter the monthly maintenance cost") mx = getcost() total() def getcost(): return float(input()) def total(): monthly_amount = loan+insurance+gas+oil+tire+mx print("Your monthly costs are $", monthly_amount) annual_amount = monthly_amount*12 print("Your annual cost is $", annual_amount) main()
e51cbe700da1b5305ce7dfe9c1748ad3b2369690
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/Dictionaries and Sets/Sets/notes.py
2,742
4.59375
5
# Sets # A set contains a collection of unique values and works like a mathematical set # 1 All the elements in a set must be unique. No two elements can have the same value # 2 Sets are unordered, which means that the elements are not stored in any particular order # 3 The elements that are stored in a set can be of different data types # Creating a set my_set = set(['a', 'b', 'c']) print(my_set) my_set2 = set('abc') print(my_set2) # will remove the duplicates for us my_set3 = set('aabbcc') print(my_set3) # will error, set can only take one argument # my_set4 = set('one', 'two', 'three') # print(my_set4) # Brackets help my_set5 = set(['one', 'two', 'three']) print(my_set5) # find length print(len(my_set5)) # add and remove elements of a set # initialize a blank set new_set = set() new_set.add(1) new_set.add(2) new_set.add(3) print("New set", new_set) # Update works new_set.update([4, 5, 6]) print("After update: ", new_set) new_set2 = set([7, 8, 9]) new_set.update(new_set2) print(new_set) # cannot do 10 instead would use .discard discard will do nothing if it won't work as opposed to return an error new_set.remove(1) print(new_set) # using a for loop to iterate over a set new_set3 = set(['a', 'b', 'c']) for val in new_set3: print(val) # using in and not operator to test the value of a set numbers_set = set([1, 2, 4]) if 1 in numbers_set: print('The value 1 is in the set. ') if 99 not in numbers_set: print('The value 99 is not in the set. ') # Find the union of sets set1 = set([1, 2, 3, 4]) set2 = set([3, 4, 5, 6]) set3 = set1.union(set2) print('set3', set3) # the same as above set5 = set1 | set2 print('set5', set5) # Find the intersection of sets set4 = set1.intersection(set2) print('set 4', set4) # same as above set6 = set1 & set2 print('set6', set6) char_set = set(['abc']) char_set_upper = set(['ABC']) char_intersect = char_set.intersection(char_set_upper) print('character intersect upper and lower', char_intersect) char_union = char_set.union(char_set_upper) print('character union upper lower', char_union) # find the difference of sets set7 = set1.difference(set2) print('1 and 2 diff', set7) print('set 1', set1) print('set 2', set2) set8 = set2.difference(set1) print('set 8', set8) set9 = set1 - set2 print('set9', set9) # finding symmetric difference in sets set10 = set1.symmetric_difference(set2) print('set10', set10) set11 = set1 ^ set2 print('set11', set11) # find the subsets and supersets set12 = set([1,2,3,4]) set13 = set([1,2]) print(' is 13 a subset of 12', set13.issubset(set12)) print('is 12 a superset of 13', set12.issuperset(set13))
0ce57fc5296a09864fb1e75080a20c684bceef98
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/car_truck_suv_demo.py
1,521
4.1875
4
# This program creates a Car object, a truck object, and an SUV object import vehicles import pprint def main(): # Create a Car object car = vehicles.Car('Bugatti', 'Veyron', 0, 3000000, 2) # Create a truck object truck = vehicles.Truck('Dodge', 'Power Wagon', 0, 57000, '4WD') # Create an SUV object suv = vehicles.SUV('Jeep', 'Wrangler', 200000, 5000, 4) print('VEHICLE INVENTORY') print('=================') # Display the vehicles data print('\nmake', car.get_make()) print('model', car.get_model()) print('mileage', car.get_mileage()) print(f'price {car.get_price():.2f}') print('doors', car.get_doors()) print('\nmake', truck.get_make()) print('model', truck.get_model()) print('mileage', truck.get_mileage()) print(f'price {truck.get_price():.2f}') print('doors',truck.get_drive_type()) print('\nmake', suv.get_make()) print('model', suv.get_model()) print('mileage', suv.get_mileage()) print(f'price {suv.get_price():.2f}') print('doors', suv.get_pass_cap()) # shows cool info about the things # print(help(vehicles.SUV)) # shows if an object is an instance of a class print(isinstance(suv, vehicles.Automobile)) # shows if an object is a subclass of another print(issubclass(vehicles.SUV, vehicles.Automobile)) # print or set object as the dictionary of the items bob = suv.__dict__ pprint.pprint(bob, sort_dicts = False) main()
8a747dfb6d959c1e4774543b9dd4fa42eeda228a
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Tkinter/tkinter_intro.py
1,459
3.890625
4
''' GUI - a graphical user interface allows the user to interact with the operating system and other programs using graphical elements such as icons, buttons, and dialog boxes. In python you can use the tkinter module to create simple GUI programs There are other GUI modules available but tkinter comes with Python ******* tkinter widgets ******** Button - A button that can cuase an action to occur when it is clicked Canvas - Rectangular area that can be used to display graphics Checkbutton - A button that may be in either the 'on' or 'off' position Entry - An area in which the user may type a single line of input from the keyboard Frame - A container that can hold other widgets Label - An area that displays one line of text or an image Listbox - A list from which the user may select an item Menu - A list of menu choices that are displayed when the user clicks a Menubutton widget Menubutton - A menu that is displayed on the screen and may be clicked by the user Radio - A widget that can be either selected or deselected. Can choose one option in a group Scale - A widget that allows the user to select a value by moving a slider along a track Scrollbar - Can be used with some other types of widgets to provide scrolling capability Text - A widget that allows the user to enter multiple lines of text input Toplevel - A container, like a Frame but displayed in its own window IDLE is built using Tkinter '''
d2e06b65113045bf009e371c53cc73750f8184a7
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Recursion/Practice/7.py
1,181
4.21875
4
""" 7. Recursive Power Method Design a function that uses recursion to raise a number to a power. The function should accept two arguments: the number to be raised and the exponent. Assume that the exponent is a nonnegative integer. """ # define main def main(): # Establish vars int1 = int(input("Enter the first integer: ")) int2 = int(input("Enter the second integer: ")) # pass to function exp(int1, int2, 1) # define exponent # def exp(x, y, z, a): # if z is greater than the exponent then print the formatted number # if z > y: # print(f'{a:,.2f}') # # If not cal lthe function again passing z, y and z plus 1 and the total times the base number # else: # return exp(x, y, z + 1, a * x) # A better way less lines, simpler def exp(x, y, a): # While y is greater than 0 call the function again passing x, y - 1 and a (the total) times the base number while y > 0: return exp(x, y - 1, a * x) print(f'{a:,.2f}') # call main main() # 7. # def power(x,y): # if y == 0: # return 1 # else: # return x * power(x, y - 1) # print(power(3,3))
fafa7582c917c253c46b4e773ebe8ea1c0e84af7
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/vehicles.py
3,642
4.4375
4
# The Automobile class holds general data about an auto in inventory class Automobile: # the __init__ method accepts arguments for the make, model, mileage, and price. It initializes the data attributes with these values. def __init__(self, make, model, mileage, price): self.__make = make self.__model = model self.__mileage = mileage self.__price = price # The following methods are mutators for the class's data attributes. def set_make(self, make): self.__make = make def set_model(self, model): self.__model = model def set_mileage(self, mileage): self.__mileage = mileage def set_price(self, price): self.__price = price # The following methods are the accessors for the class's data attributes. def get_make(self): return self.__make def get_model(self): return self.__model def get_mileage(self): return self.__mileage def get_price(self): return self.__price # The Car class represents a car. It is a subclass of the Automobile class class Car(Automobile): # The __init__ method accepts arguments for the cars make, model, mileage, price and doors def __init__(self, make, model, mileage, price, doors): # Call the superclass's __init__ method and pass the required arguments. Note # t we also have to pass self as an argument can do Automobile(Superclass name) # or can use super() without the self argument super().__init__(make, model, mileage, price) # Initialize the __doors attribute self.__doors = doors # The set_doors method is the mutator for the __doors attribute def set_doors(self, doors): self.__doors = doors # The get_doors method is the accessor for the __doors attribute def get_doors(self): return self.__doors # The Truck class represents a pickup truck. It is as subclass of the Automobile class class Truck(Automobile): # The __init__ method accepts arguments for the Truck's make, model, mileage, price, and drive type def __init__(self, make, model, mileage, price, drive_type): # Call the superclass's __init__ and pass the required arguments. # Note that we also have to pass the reqd args super().__init__(make, model, mileage, price) # initialize the drive_type attribute self.__drive_type = drive_type # the set drive type method is the mutator for the __drive_type attribute def set_drive_type(self, drive_type): self.__drive_type = drive_type # the get drive type is the accessor for the __drive_type attribute def get_drive_type(self): return self.__drive_type # THe SUV class represents a sport utility vehicle. It is a subclass for the Automobile class class SUV(Automobile): # The __init__ method accepts arguments for the SUV's make, model, mileage, # price, and pass capacity def __init__(self, make, model, mileage, price, pass_cap): # Call the superclass's __init__ method and pass the reqd args super().__init__(make, model, mileage, price) # initialize the pass_cap attribute self.__pass_cap = pass_cap # define the set_pass_cap method that is the mutator for the __pass_cap attribute def set_pass_cap(self, pass_cap): self.__pass_cap = pass_cap # define the get_pass_cap method that is the accessor for the __pass_cap attribute def get_pass_cap(self): return self.__pass_cap
f149ee1bf7a78720f53a8688d83d226cb00dc5eb
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/Cars.py
2,383
4.8125
5
""" 2. Car Class Write a class named Car that has the following data attributes: • __year_model (for the car’s year model) • __make (for the make of the car) • __speed (for the car’s current speed) The Car class should have an __init__ method that accept the car’s year model and make as arguments. These values should be assigned to the object’s __year_model and __make data attributes. It should also assign 0 to the __speed data attribute. The class should also have the following methods: • accelerate The accelerate method should add 5 to the speed data attribute each time it is called. • brake The brake method should subtract 5 from the speed data attribute each time it is called. • get_speed The get_speed method should return the current speed. Next, design a program that creates a Car object, and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times. After each call to the brake method, get the current speed of the car and display it. """ # define the class of cars class Cars: # define the init with all the variables def __init__(self, year, make, model, speed): self.__year = year self.__make = make self.__model = model self.__speed = speed # def setting the year of the car def set_year(self, year): self.__year = year # def function to set the make of the car def set_make(self, make): self.__make = make # def function to set the model of the car def set_model(self, model): self.__model = model # def function to accelerate def accelerate(self): self.__speed += 5 return self.__speed # def function to begin braking def brake(self): self.__speed -= 5 return self.__speed # define a function to get the speed def get_speed(self): return self.__speed # return the year def get_year(self): return self.__year # returns the make def get_make(self): return self.__make # return the model def get_model(self): return self.__model
eaa53c820d135506b1252749ab50b320d11d53b5
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/5 - RetailItem.py
1,427
4.625
5
""" 5. RetailItem Class Write a class named RetailItem that holds data about an item in a retail store. The class should store the following data in attributes: item description, units in inventory, and price. Once you have written the class, write a program that creates three RetailItem objects and stores the following data in them: Description Units in Inventory Price Item #1 Jacket 12 59.95 Item #2 Designer Jeans 40 34.95 Item #3 Shirt 20 24.95 """ # import the important things import RetailItem # establish the dictionary with the data item_dict = {1 : { 'description' : 'Jacket', 'units' : 12, 'price' : 59.95}, 2 : { 'description' : 'Designer Jeans', 'units' : 40, 'price' : 34.95}, 3 : { 'description' : 'Shirt', 'units' : 20, 'price' : 24.95}} # define the main function def main(): # set the variable to call the class and use dictionary info to populate it item1 = RetailItem.RetailItem(item_dict[1]['description'], item_dict[1]['units'], item_dict[1]['price']) item2 = RetailItem.RetailItem(item_dict[2]['description'], item_dict[2]['units'], item_dict[2]['price']) item3 = RetailItem.RetailItem(item_dict[3]['description'], item_dict[3]['units'], item_dict[3]['price']) # display the data print(item1, item2, item3) # call main main()
b046b95c144bbe51ac2c77b5363814b8b5d2b5cc
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/6.py
503
4.46875
4
# 6. Celsius to Fahrenheit Table # Write a program that displays a table of the Celsius temperatures 0 through 20 and theirFahrenheit equivalents. # The formula for converting a temperature from Celsius toFahrenheit is # F = (9/5)C + 32 where F is the Fahrenheit temperature and C is the Celsius temperature. # Your programmust use a loop to display the table. fahr = [((9/5) * cel + 32) for cel in range(21)] for x, y in enumerate(fahr): print(f'{x:} celcius is {y:.2f} fahrenheit.')
6da08424b01dfcfcebb93cbeff93e76e72c53ea9
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Unit Testing and Multithreading/MultiThreading/Multithreadingclassdemo1/multithreading5.py
950
3.625
4
# For editing further without losing multithreading og file ''' Prove that these are actually coming in as they are completed Lets pass in a range of seconds Start 5 second thread first ''' import concurrent.futures import time start = time.perf_counter() def do_something(seconds): print(f'Sleeping {seconds} second....') time.sleep(seconds) return f'Done Sleeping....{seconds}' # using a context manager with concurrent.futures.ThreadPoolExecutor() as executor: seconds_list = [5, 4, 3, 2, 1] # map will apply the function do_something to every item in the seconds_list # insteatd of running the results as they complete, map returns in the order # that they were started results = executor.map(do_something, seconds_list) for result in results: print(result) finished = time.perf_counter() print(f'Our program finished in {finished - start:.6f} seconds.')
9e6bdd3adc3e850240f3c9a94dd766ecdd4abe97
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/FileExercises/9.py
1,013
4.28125
4
# 9. Exception Handing # Modify the program that you wrote for Exercise 6 so it handles the following exceptions: # • It should handle any IOError exceptions that are raised when the file is opened and datais read from it. # Define counter count = 0 # Define total total = 0 try: # Display first 5 lines # Open the file infile = open("numbers.txt", 'r') # Set readline line = infile.readline() while line != '': # Convert line to a float display = int(line) # Increment count and total count += 1 total += display # Format and display data print(display) # Read the next line line = infile.readline() print(f"\n The average of the lines is {total/count:.2f}") # If file doesn't exist, show this error message except: print(f"\n An error occured trying to read numbers.txt") if count > 0: print(f" to include line {count:} \n")
c7576a385b6019af0393ec97ebdd0cf3c5aee69e
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Algorithms and Data Structures/collections_lecture.py
2,840
3.8125
4
''' collection - a group of 0 or more items that can be treated as a conceptual unit. Things like strings, lists, tuples, dictionaries Other types of collections include stacks, queues, priority queues, binary search trees, heaps, graphs, and bags ************** Collection Types ************** linear collection - like people in a line, they are ordered by position, each item except athe first has a unique predecessor Hierarchical collection - ordered in a structure resembling an upside down tree. Each data item except the one at the top, (the root), has just one predecessor called its parent, but potentially has many successors called children Some examples include a file directory system, a company's organizational tree, and a books table of contents graph collection - also called graph, each item can have many predecessors and many successors. These are also called neighbors some examples include airline routes between cities, electrical wiring diagrams, and the world wide web unordered collections - these are not in any particular order, and its not possible to meaningfully speak of an item's predecessor or successor an example includes a bag of marbles ************** Operation Types ************** Determine the size - Use Python's len() function to obtain the number of items currently in the collection Test for item membership - Use Python's "in" operator to search for a given target item in the collection. Return's "True" if the item if found and "False" otherwise Traverse the collection - Use Python's "for" loop to visit each item in the collection. The order in which items are visited depends on the type of the collection Obtain a string representation - Use Python's str() function to obtain the string representation of the collection Test for equality - Use Python's "==" operator to determine whether the two collections are equal. Two collections are equal if they are of the same type and contain the same items. The order in which pairs of items are compared depends on the type of collection. Concatenate two collections - use Pyhton's "+" operator to obtain a new collection of the same type as the operands and containing the items in the two operands Convert to another type of collection - Create a new collection with the same items as a source collection Insert an item - Add the item to the collection, possibly at a given position Remove an item - Remove the item from the collection, possibly at a given position Replace an item - Combine removal and insertion into one operation Access or retrieve an item - Obtain an item, possibly at a given position '''
f1639f9b273a097c08d8e3d6236acf50befd9a99
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/regex/Practice/1.py
285
3.75
4
""" 1. Recognize the following strings: “bat”, “bit”, “but”, “hat”, “hit”, or “hut”. """ import re string = ''' bat bit but hat hit hut ''' pattern = re.compile(r'[a-z]{2}t') matches = pattern.finditer(string) for match in matches: print(match)
2118efbe7e15e295f6ceea7b4a4c26696b22edb1
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Unit Testing and Multithreading/MultiThreading/Multithreadingclassdemo1/multithreading.py
1,434
4.15625
4
''' RUnning things concurrently is known as multithreading Running things in parallel is known as multiprocessing I/O bound tasks - Waiting for input and output to be completed reading and writing from file system, network operations. These all benefit more from threading You get the illusion of running code at the same time, however other code starts running while other code is waiting CPU bound tasks - Good for number crunching Using CPU Data Crunching These benefit more from multiprocessing and running in parallel Using multiprocessing might be slower if you have overhead from creating and destroying files. ''' import threading import time start = time.perf_counter() def do_something(): print('Sleeping 1 second....') time.sleep(1) print('Done Sleeping....') # how we did it # do_something() # do_something() # create threads for new way t1 = threading.Thread(target=do_something) t2 = threading.Thread(target=do_something) #start the thread t1.start() t2.start() # make sure the threads complete before moving on to calculate finish time: t1.join() t2.join() finished = time.perf_counter() print(f'Our program finished in {finished - start:.6f} seconds.')
5c78846587a1485c8a39a77ef8f4ec10dfe0f2bb
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Test Stuff/First Test/study/knowledge_lists_and_tuples.py
3,523
4.15625
4
""" Multiple Choice 1. This term refers to an individual item in a list. a. element b. bin c. cubby hole d. slot 2. This is a number that identifies an item in a list. a. element b. index c. bookmark d. identifier 3. This is the first index in a list. a. -1 b. 1 c. 0 d. The size of the list minus one 4. This is the last index in a list. a. 1 b. 99 c. 0 d. The size of the list minus one 5. This will happen if you try to use an index that is out of range for a list. a. a ValueError exception will occur b. an IndexError exception will occur c. The list will be erased and the program will continue to run. d. Nothing—the invalid index will be ignored 6. This function returns the length of a list. a. length b. size c. len d. lengthof 7. When the * operator’s left operand is a list and its right operand is an integer, the operator becomes this. a. The multiplication operator b. The repetition operator c. The initialization operator d. Nothing—the operator does not support those types of operands. 8. This list method adds an item to the end of an existing list. a. add b. add_to c. increase d. append 9. This removes an item at a specific index in a list. a. The remove method b. The delete method c. The del statement d. The kill method 10. Assume the following statement appears in a program: mylist = [] Which of the following statements would you use to add the string 'Labrador' to the list at index 0? a. mylist[0] = 'Labrador' b. mylist.insert(0, 'Labrador') c. mylist.append('Labrador') d. mylist.insert('Labrador', 0) 11. If you call the index method to locate an item in a list and the item is not found, this happens. a. A ValueError exception is raised b. An InvalidIndex exception is raised c. The method returns -1 d. Nothing happens. The program continues running at the next statement. 12. This built-in function returns the highest value in a list. a. highest b. max c. greatest d. best_of 13. This file object method returns a list containing the file’s contents. a. to_list b. getlist c. readline d. readlines 14. Which of the following statements creates a tuple? a. values = [1, 2, 3, 4] b. values = {1, 2, 3, 4} c. values = (1) d. values = (1,) True or False: 1. Lists in Python are immutable. 2. Tuples in Python are immutable. 3. The del statement deletes an item at a specified index in a list. 4. Assume list1 references a list. After the following statement executes, list1 and list2 will reference two identical but separate lists in memory: list2 = list1 5. A file object’s writelines method automatically writes a newline ('\n') after writing each list item to the file. 6. You can use the + operator to concatenate two lists. 7. A list can be an element in another list. 8. You can remove an element from a tuple by calling the tuple’s remove method """
f1923bf1fc1a3ab94a7f5d32c929cd6914fc7605
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Test Stuff/First Test/shapes1.py
2,305
4.25
4
class GeometricObject: def __init__(self, color = "green", filled = True): self.color = color self.filled = filled def getColor(self): return self.color def setColor(self, color): self.color = color def isFilled(self): return self.filled def setFilled(self, filled): self.filled = filled def toString(self): return "color: " + self.color + " and filled: " + str(self.filled) ''' (The Triangle class) Design a class named Triangle that extends the GeometricObject class defined below. The Triangle class contains: - Three float data fields named side1, side2, and side3 to denote the three sides of the triangle. - A constructor that creates a triangle with the specified side1, side2, and side3 with default values 1.0. - The accessor methods for all three data fields. - A method named getArea() that returns the area of this triangle. - A method named getPerimeter() that returns the perimeter of this triangle. - A method named __str__() that returns a string description for the triangle. ''' class TriangleObject: def __init__(self, color = "green", filled = True, side1 = 1.0, side2 = 1.0, side3 = 1.0): super().__init__(color, filled) self.side1 = side1 self.side2 = side2 self.side3 = side3 def set_side1(self, side1): self.side1 = side1 def set_side2(self, side2): self.side2 = side2 def set_side3(self, side3): self.side3 = side3 def get_side1(self, side1): return self.side1 def get_side2(self, side2): return self.side2 def get_side3(self, side3): return self.side3 def getPerimeter(self): self.perimeter = (self.side1 + self.side2 + self.side3)/2 return self.perimeter def getArea(self): self.area = (self.perimeter * (self.perimeter - self.side1) * (self.perimeter - self.side2) * (self.perimeter - self.side3)) ** (1/2.0) return self.area def __str__(self): return f'A triangle is a 3 sided shape. The current sides have a length of {self.side1}, {self.side2}, and {self.side3}'
cd2b8237503c74dfc7864dd4ec64d7f334c9ecb0
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/8 - trivia.py
2,521
4.4375
4
""" 8. Trivia Game In this programming exercise you will create a simple trivia game for two players. The program will work like this: • Starting with player 1, each player gets a turn at answering 5 trivia questions. (There should be a total of 10 questions.) When a question is displayed, 4 possible answers are also displayed. Only one of the answers is correct, and if the player selects the correct answer, he or she earns a point. • After answers have been selected for all the questions, the program displays the number of points earned by each player and declares the player with the highest number of points the winner. To create this program, write a Question class to hold the data for a trivia question. The Question class should have attributes for the following data: • A trivia question • Possible answer 1 • Possible answer 2 • Possible answer 3 • Possible answer 4 • The number of the correct answer (1, 2, 3, or 4) The Question class also should have an appropriate __init__ method, accessors, and mutators. The program should have a list or a dictionary containing 10 Question objects, one for each trivia question. Make up your own trivia questions on the subject or subjects of your choice for the objects. """ question_dict = {"Blue, Black or Red?" : ['Blue', 'Red', 'Clear', 'Black'], "Yes or No?" : ['Yes', 'Maybe', 'True', 'No'], "Laptop or Desktop?" : ['Cell Phone', 'Tablet', 'Laptop', 'Desktop']} import trivia import random def main(): global question_dict questions = trivia.Trivia() questions.bulk_add(question_dict) for key in questions.get_questions(): print(key) # print(questions.get_questions()[key]) answerlist = [] answerlist2 = [] for i in questions.get_questions()[key]: answerlist.append(i) answerlist2.append(i) random.shuffle(answerlist2) print("1", answerlist) print("2", answerlist2) count = 0 for i in answerlist2: print(f"Number {count}: {i}") count += 1 choice = int(input("Enter the number choice for your answer: ")) if answerlist[3] == answerlist2[choice]: print("You got it right!") else: print("You got it wrong!") main()
2ae55026f82e336bd28809f87822da12d2a8f0a6
Hackman9912/PythonCourse
/NetworkStuff/09_NetworkingExtended/Practice/04 Modules/04-5.py
679
4.03125
4
''' ### Working With modules ( sys, os, subprocess, argparse, etc....) 5. Create a script that will accept a single integer as a positional argument, and will print a hash symbol that amount of times. ''' import os import sys import time import subprocess import argparse def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--integer', help="Set the number of octothorps to print by hitting -i (your number). ") return parser.parse_args() def print_octothorp(octo, numb): print('Getting this many octothorps: ' + numb + '\n' + str(octo)) options = get_arguments() octo = '#' * int(options.integer) print_octothorp(octo, options.integer)
1658b421c637ec8ab3524446baccd8f30da4470c
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/Lists/tuples.py
394
4.25
4
# tuples are like an immutable list my_tuple = (1, 2, 3, 4, 5) print(my_tuple) # printing items in a tuple names = ('Holly', 'Warren', 'Ashley') for n in names: print(n) for i in range(len(names)): print (names[i]) # Convert between a list and a tuple listA = [2, 4, 5, 1, 6] type(listA) tuple(listA) type(listA) tupA = tuple(listA) type(tupA)
8b72f14467bc40821bc0fb0c7c2ad9f05be58cd0
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 3.py
2,460
4.46875
4
""" 3. Person and Customer Classes Write a class named Person with data attributes for a person’s name, address, and telephone number. Next, write a class named Customer that is a subclass of the Person class. The Customer class should have a data attribute for a customer number and a Boolean data attribute indicating whether the customer wishes to be on a mailing list. Demonstrate an instance of the Customer class in a simple program. """ import assets import pprint pppl_lst = [] cust_lst = [] def main(): global pppl_lst, cust_lst pppl_num = int(input('Enter the number of people you need to add: ')) setthelist(pppl_num) print("Not Customers: ") print_list(pppl_lst) print("Customers: ") print_list(cust_lst) def setthelist(theamount): global pppl_lst, cust_lst for i in range(theamount): print("Person", i+1) customerinput = int(input('Is this person a customer? 1 for yes 0 for no: ')) if customerinput == 1: name = input('Enter the persons name: ') address = input('Enter the address: ') phone = input('Enter the phone number for the person: ') cust_num = int(input('Enter the customer number: ')) mail = 2 while mail != 0 and mail != 1: mail = int(input('Does the customer want to be on the mailing list? 1 = yes 0 = no: ')) print('mail', mail) customer = assets.Customer(name, address, phone, cust_num, bool(mail)) cust_lst.append(customer) elif customerinput == 0: name = input('Enter the persons name: ') address = input('Enter the address: ') phone = input('Enter the phone number for the person: ') notcustomer = assets.Person(name, address, phone) pppl_lst.append(notcustomer) def print_list(listss): if listss is pppl_lst: for i in listss: print('Name: ', i.get_name()) print('Address: ', i.get_address()) print('Phone: ', i.get_phone()) elif listss is cust_lst: for i in listss: print('Name: ', i.get_name()) print('Address: ', i.get_address()) print('Phone: ', i.get_phone()) print('Customer Number: ', i.get_cust_num()) print('Is on mailing address: ', i.get_mail()) main()
ab93e5065c94a86f8ed6c812a3292100925a1bb5
Hackman9912/PythonCourse
/Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/IfElsePractice/5.py
1,575
4.4375
4
# 5. Color Mixer # The colors red, blue, and yellow are known as the primary colors because they cannot be # made by mixing other colors. When you mix two primary colors, you get a secondary color, # as shown here: # When you mix red and blue, you get purple. # When you mix red and yellow, you get orange. # When you mix blue and yellow, you get green. # Design a program that prompts the user to enter the names of two primary colors to mix. # If the user enters anything other than “red,” “blue,” or “yellow,” the program should display an # error message. Otherwise, the program should display the name of the secondary color that results. def main(): color_one = color() checker(color_one) color_two = color() checker(color_two) blender(color_one, color_two) def checker(color): if color == "red" or color == "blue" or color == "yellow": print("You chose", color) else: print("Choose one of the primary colors!") exit() def color(): return input("Enter 'red', 'blue', or 'yellow'. ") def blender(first, second): if (first == "red" or second == "red") and (first == "blue" or second == "blue"): print("Your blend is purple") elif (first == "yellow" or second == "yellow") and (first == "blue" or second == "blue"): print("Your blend is green") elif (first == "red" or second == "red") and (first == "yellow" or second == "yellow"): print("Your blend is orange") else: print("Your colors were the same") main()
5a57c7b45ccb3df1adb3ebad30f2a4d2defba1d7
stephaniecheng1124/CIS-01
/InClassB.py
941
3.984375
4
# Stephanie Cheng # CIS 41B Spring 2019 # In-class assignment B # Problem B1 # # This program writes a script to perform various basic math and string operations. def string_count(): name = raw_input("Please enter your name: ") print(name.upper()) print(len(name)) print(name[3]) name2 = name.replace("o", "x") print(name2) print(name) print("\n") quote = "Believe you can and you're halfway there." print("Number of occurrences of letter 'a' in quote:") print(quote.count("a")) print("\n") print("Indices of letter 'a' in quote:") if quote.count("a") > 0: start = quote.find("a") print(start) if quote.count("a") > 1: start += 1 while quote.find("a", start) != -1: start = quote.find("a", start) print(start) start += 1 string_count()
d2d9ad0905e398f8509b6ad6e70f59ee578f0adc
stephaniecheng1124/CIS-01
/InClassC.py
871
3.6875
4
# Stephanie Cheng # CIS 41B Spring 2019 # In-class assignment C # Problem C1 # #List Script from copy import deepcopy def list_script(): list1 = [2, 4.1, 'Hello'] list2 = list1 list3 = deepcopy(list1) print("list1 == list2: " + str(list1==list2)) print("list1 == list3: " + str(list1==list3)) print("list2 == list3: " + str(list2==list3)) print("list1 is list2: " + str(list1 is list2)) print("list1 is list3: " + str(list1 is list3)) print("list2 is list3: " + str(list2 is list3)) print("list1 ID: " + str(id(list1))) print("list2 ID: " + str(id(list2))) print("list3 ID: " + str(id(list3))) list1.append(8) list2.insert(1, 'goodbye') del list3[0] print("list1 printed: " + str(list1)) print("list2 printed: " + str(list2)) print("list3 printed: " + str(list3)) list_script()
1821805f1bd83a8add850ac70f9ad17bf5a27431
shaamimahmed/MITx---6.00.1x
/BFS.py
700
3.859375
4
class node(): def __init__(self,value,left,right): self.value = value self.left = left self.right = right def __str__(self): return self.value def __repr__(self): return 'Node {}'.format(self.value) def main(): g = node("G", None, None) h = node("H", None, None) i = node("I", None, None) d = node("D", None, None) e = node("E", g, None) f = node("F", h, i) b = node("B", d, e) c = node("C", None, f) a = node("A", b, c) root = a BFS(root) def BFS(root): nexts = [root] while nexts != []: current = nexts.pop(0) if current.left: nexts.append(current.left) if current.right: nexts.append(current.right) print current, main()
1b2a7905075802782b7f57df0b08520ee13aaea4
shaamimahmed/MITx---6.00.1x
/recursion.py
730
3.828125
4
def iterPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' total= base if exp == 0: total = 1 for n in range(1, exp): total *= base return total def recurPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' if exp == 0: return 1 return base * recurPower(base, exp - 1) def recurPowerNew(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float; base^exp ''' if exp == 0: return 1 elif exp % 2 == 0: return recurPowerNew(base*base, exp/2) else: return base * recurPowerNew(base, exp - 1)
890f3be1a967335d2aa8f3c4d31a5c5d33626428
Kediel/DataScienceFromScratch
/chapter5.py
1,230
3.53125
4
# Statistics from collections import defaultdict, Counter num_friends = [100,49,41,40,25,21,21,19,19,18,18,16,15,15,15,15,14,14,13,13,13,13,12,12,11,10,10,10,10,10,10,10,10,10, 10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] def make_friend_counts_histogram(plt): friend_counts = Counter(num_friends) xs = range(101) ys = [friend_counts[x] for x in xs] plt.bar(xs, ys) plt.axis([0,101,0,25]) plt.title("Histogram of Friend Counts") plt.xlabel("# of friends") plt.ylabel("# of people") plt.show() num_points = len(num_friends) # 204 largest_value = max(num_friends) # 100 smallest_value = min(num_friends) # 1 sorted_values = sorted(num_friends) smallest_value = sorted_values[0] # 1 second_smallest_value = sorted_values[1] # 1 second_largest_value = sorted_values[-2] # 49
47332606f558cc9927e5f1d415dde6ce2ddfbf6d
smpss97058/c109156217
/4-2D座標判斷及計算離原點距離.py
860
3.84375
4
x=int(input("X軸座標:")) y=int(input("Y軸座標:")) a=0 if x>0: if y>0: a=x**2+y**2 print("該點位於第一象限,離原點距離為根號"+str(a)) elif y<0: a=x**2+y**2 print("該點位於第四象限,離原點距離為根號"+str(a)) else: a=x**2+y**2 print("該點位於X軸上,離原點距離為根號"+str(a)) if x<0: if y>0: a=x**2+y**2 print("該點位於第二象限,離原點距離為根號"+str(a)) elif y<0: a=x**2+y**2 print("該點位於第三象限,離原點距離為根號"+str(a)) else: a=x**2+y**2 print("該點位於X軸上,離原點距離為根號"+str(a)) if x==0: if y==0: print("該點位於原點") else: a=x**2+y**2 print("該點位於Y軸上,離原點距離為根號"+str(a))
77acd1d223437c765fa54b6c2148332653bbe731
smpss97058/c109156217
/32新公倍數.py
252
3.71875
4
n=int(input("輸入一整數:")) while n<11 or 1000<n: n=int(input("輸入一整數(11<=n<=1000):")) if n%2==0 and n%11==0: if n%5!=0 and n%7!=0: print(str(n)+"為新公倍數?:Yes") else: print(str(n)+"為新公倍數?:No")
fcf81e26402c78334170997fe6b6f4f98807d47e
elizamakkt1218/CSVFileCombination
/main.py
4,241
4.03125
4
import tkinter as tk from tkinter.filedialog import askdirectory import csv import os import utilities absolute_file_paths = [] def get_file_path(): """ Prompts user to select the folder for Combining CSV files :parameter: None :return: The relative paths of all files contained in the folder :exception: 1. UnspecifiedFolderError 2. EmptyFolderError 3. AbsenceOfCSVFileError """ tk.Tk().withdraw() folder_path = '' try: folder_path = askdirectory(title='Select Folder') # Raise UnspecifiedFolderError when user did not select a folder if folder_path == '/': raise utilities.UnspecifiedFolderError('Please select a folder.') # Return None and stop the program when user click "Cancel" elif folder_path == '': return None except utilities.UnspecifiedFolderError: print('Please select a folder.') get_file_path() relative_file_paths = [] try: relative_file_paths = os.listdir(folder_path) # Raise EmptyFolderError when the folder is empty if not relative_file_paths: raise utilities.EmptyFolderError('Empty Folder!') # The index of the two lists: relative_file_paths and absolute_file_paths are the same for files in relative_file_paths: ext = files.rpartition('.')[-1] if ext != 'csv': relative_file_paths.remove(files) continue absolute_file_paths.append(folder_path + '/' + files) # Raise AbsentOfCSVFileError when no csv file exists if not absolute_file_paths: raise utilities.AbsentOfCSVFileError('No CSV File Exists.') except utilities.EmptyFolderError: print(folder_path + '\n' + 'The folder is empty.') except utilities.AbsentOfCSVFileError: print('No CSV File Exists.') return relative_file_paths def read(): """ Reads all the CSV files and save the data as lists :parameter: None :return: a list of csv_reader objects(converted into lists) :exception: None """ # Call get_file_path Method # if it returns none, return to its caller relative_file_paths = get_file_path() if not relative_file_paths: return # Convert all the csv_reader objects into lists and save them to a list index = 0 file_reader = [] for file in absolute_file_paths: with open(file, newline='') as csv_file: file_reader.append(list(csv.reader(csv_file))) # Rename the column name into filenames if index >= 1: # Skip the first column if the files are loaded as the second one or onwards for row in file_reader[index]: row.pop(0) file_reader[index][0][0] = os.path.splitext(relative_file_paths[index])[0] else: file_reader[index][0][1] = os.path.splitext(relative_file_paths[index])[0] index += 1 return file_reader def write(): """ Writes all the data into a new CSV file called 'output.csv' :return: None :parameter: None :exception: None """ # Call read Method file_reader = read() if not file_reader: return # Write the data to the "output.csv" file count = 0 while count < len(file_reader): if count == 0: with open('output.csv', 'w', newline='')as csv_file: writer = csv.writer(csv_file) for row in file_reader[0]: writer.writerow(row) csv_file.close() count += 1 else: length = 0 with open('output.csv', 'r', newline='') as input_file: reader = list(csv.reader(input_file)) with open('output.csv', 'w', newline='')as append_file: writer = csv.writer(append_file) for input_row in reader: writer.writerow(input_row + file_reader[count][length]) length += 1 append_file.close() count += 1 print('Output file has been saved to the current directory.') def main(): write() if __name__ == "__main__": main()
dc1bbcc31eb28b89d15dac95bf107b5627667593
JianyanLiang/SkyDrive
/Server/查看当前用户.py
149
3.609375
4
import sqlite3 conn = sqlite3.connect('Users.db') cur = conn.cursor() sql = 'select * from users' cur.execute(sql) print(cur.fetchall()) a = input()
d63f59488d65ba81d647da41c15424a0901d18b4
DimitrisMaskalidis/Python-2.7-Project-Temperature-Research
/Project #004 Temperature Research.py
1,071
4.15625
4
av=0; max=0; cold=0; count=0; pl=0; pres=0 city=raw_input("Write city name: ") while city!="END": count+=1 temper=input("Write the temperature of the day: ") maxTemp=temper minTemp=temper for i in range(29): av+=temper if temper<5: pl+=1 if temper>maxTemp: maxTemp=temper if temper<minTemp: minTemp=temper temper=input("Write the temperature of the day: ") print "The differance between highest and lowest temperature is",maxTemp-minTemp av=av/30.0 if count==1: max=av if av>max: max=av maxname=city if av>30: pres+=1 if pl==30: cold+=1 pl=0 city=raw_input("Write city name: ") print "The percentage of the cities with average temperature more than 30 is",count/pres*100,"%" print "The city with the highest average temperature is",maxname,"with",max,"average temperature" if cold>0: print "There is a city with temperature below 5 every day"
bafeb62820714891cf4f2082f45487e8d3db63a0
treylitefm/euler
/misc-algos/tictactoe.py
1,605
3.65625
4
#arr = [['x','x','x'],['o','o','x'],['x','o','o']] #rr = [['x','o','x'],['o','o','o'],['x','o','o']] #arr = [['x','o','x'],['o','x','o'],['x','o','x']] #arr = [['a','o','x'],['b','x','o'],['c','o','x']] arr = [['a','b','g'],['d','g','f'],['g','h','i']] def print_grid(grid): for row in grid: print row def sol(grid): tmp = None for i in range(3): # tests down across top row for k in range(3): if tmp is None: tmp = grid[i][k] elif tmp is grid[i][k]: if range(3)[-1] is k: # then we're done and there is indeed a win return True else: # tells us that current element doesnt match last element tmp = None break tmp = None for j in range(3): # tests down across top row for l in range(3): if tmp is None: tmp = grid[l][j] elif tmp is grid[l][j]: if range(3)[-1] is k: # then we're done and there is indeed a win return True else: # tells us that current element doesnt match last element tmp = None break tmp = grid[0][0] for m in range(3): if tmp is grid[m][m]: if m is range(3)[-1]: return True else: break tmp = grid[-1][0] for n1,n2 in zip(range(2,-1,-1),range(3)): if tmp is grid[n1][n2]: if n1 is range(2,-1,-1)[-1]: return True else: break print_grid(arr) print sol(arr)
7592ee5998b54cc6e7b4f7773c45e960d0b1e80c
viniciuskurt/LetsCode-PracticalProjects
/2-AdvancedStructures/Inserindo_Novo_Valor_Lista.py
313
3.53125
4
# podemos inserir novos valores através do METODO INSERT cidades = ['São Paulo', 'Brasilia', 'Curitiba', 'Avaré', 'Florianópolis'] print(cidades) cidades.insert(0, 'Osasco') print(cidades) # Inserido vários valores cidades.insert(1, 'Bogotá'); print(cidades) cidades.insert(4, 'Manaus') print(cidades)
0e878016fadab1f137f3dd61c37197ecafa4511e
viniciuskurt/LetsCode-PracticalProjects
/2-AdvancedStructures/Listas_com_While.py
438
4.09375
4
# Uma forma inteligente de trabalhar é combinar Listas com Whiles numeros = [1, 2, 3, 4, 5] #Criando e atribuindo valores a lista indice = 0 #definindo contador no índice 0 while indice < 5: #Definindo repetição do laço enquanto menor que 5 print(numeros[indice]) #Exibe posição de determinado índice da lista indice = indice + 1 #Incrementa mais um a cada volta no laço
4d1e19c830d0f41e51c4837a8792b8a054ee6655
viniciuskurt/LetsCode-PracticalProjects
/1-PythonBasics/aula04_Operadores.py
1,578
4.40625
4
''' OPERADORES ARITMETICOS Fazem operações aritméticas simples: ''' print('OPERADORES ARITMÉTICOS:\n') print('+ soma') print('- subtração') print('* multiplicacao') print('/ divisão') print('// divisão inteira') #não arredonda o resultado da divisão, apenas ignora a parte decimal print('** potenciação') print('% resto da divisão\n') x = 2 y = 5 m = x * y print('x * y = ',m) s = x + y print('x + y = ',s) sub = x - y print('x - y = ',sub) d = x / y print('y / x = ',d) di = x // y print('x // y = ',di) p = x ** y print('x ** y = ',p) rd = x % y print('x % y = ',rd) print('--' *30 ) print('OPERADORES LÓGICOS:\n') print('OR - resultado Verdadeiro se UMA ou AMBAS expressões for verdadeira') print('AND - resultado Verdadeiro somente se AMBAS as expressões forem verdadeiras') print('NOT - inverte o valor lógico de uma expressão (negação)\n') tem_cafe = True tem_pao = False #OR print(tem_cafe or tem_pao) print(tem_cafe or tem_cafe) print(tem_pao or tem_pao) #AND print(tem_cafe and tem_pao) print(tem_cafe and tem_cafe) #NOT print(not tem_cafe) print(not tem_pao) print('--' *30 ) print('OPERADORES RELACIONAIS:\n') #O Python possui 6 operadores relacionais print('Maior que: >') print('Maior ou Igual: >=') print('Menor que: <') print('Menor ou Igual: <=') print('Igual: ==') print('Diferente: != \n') comparador1 = 5 comparador2 = 3 print(comparador1 > comparador2) print(comparador1 >= comparador2) print(comparador1 < comparador2) print(comparador1 <= comparador2) print(comparador1 == comparador2) print(comparador1 != comparador2)
298f3dd303082910f64b333d378934a1184f2694
viniciuskurt/LetsCode-PracticalProjects
/1-PythonBasics/Laco_Rep_Loop_Infinito.py
534
4.09375
4
""" Laço de repetição com loop infinito e utilizando break NÃO É RECOMENDADO UTILIZAR ESSA FORMA. """ contador = 0 # while contador < 10: while True: # criando loop infinito if contador < 10: # se a condição passar da condição, é executado tudo de novo contador = contador + 1 if contador == 1: print(contador, "item limpo") else: print(contador, "itens limpos") else: break # aqui quebramos o loop mais recente print("Fim da repetição do bloco while")
e2f5debc42e10a689eeb1836901ce285481da9ce
viniciuskurt/LetsCode-PracticalProjects
/1-PythonBasics/Validacao_Entrada.py
207
3.984375
4
# Exemplo básico de validação de senha de acesso texto = input("Digite a sua entrada: ") while texto != 'LetsCode': texto = input("Senha inválida. Tente novamente\n") print('Acesso permitido')
5a008394476ccf00e21f8de67622c2c683f933fc
maxicraftone/informatics
/shortest_path.py
13,569
4.15625
4
#!/usr/bin/python import math import time import sys class Node: def __init__(self, name: str) -> None: """ Node class. Just holds the name of the node :param name: Name/ Title of the node (only for representation) """ self.name = name # Set string representation of node to just its name def __repr__(self) -> str: return self.name # Set comparation between nodes to happen between their names # (Only secondary after sorting by the distance later) def __gt__(self, node2) -> bool: return self.name > node2.name class Edge: def __init__(self, node1: Node, node2: Node, distance: int, direction: int) -> None: """ Edge class for connecting nodes through edges with distances and directions :param node1: First node :param node2: Second node :param distance: Weight of the edge :param direction: Direction of the connection: 0 = both, 1 = in direction of the first node, 2 = in direction of the second node """ self.node1 = node1 self.node2 = node2 self.distance = distance self.direction = direction def facing(self) -> tuple: """ Returns the node(s) being faced by the edge :return: Nodes """ # If facing both nodes if self.direction == 0: return (self.node1, self.node2) # If facing the first node elif self.direction == 1: return (self.node1,) # If facing the second node elif self.direction == 2: return (self.node2,) def set_node1(self, node1: Node) -> None: """ Set the node1 parameter of the edge :param node1: Value for node1 """ self.node1 = node1 def set_node2(self, node2: Node) -> None: """ Set the node2 parameter of the edge :param node2: Value for node2 """ self.node2 = node2 def set_distance(self, distance: int) -> None: """ Set the distance parameter of the edge :param distance: Value for distance/ weight of the edge """ self.distance = distance def set_direction(self, direction: int) -> None: """ Set the direction parameter of the edge :param direction: Value for direction of the edge: 0 = both directions, 1 = in direction of the first node, 2 = in direction of the second node """ self.direction = direction def is_first(self, node: Node) -> bool: """ Checks whether the given node is node1 :param node: Given node :return: True if node == node1; False if node != node1 """ return node == self.node1 def is_second(self, node: Node) -> bool: """ Checks whether the given node is node2 :param node: Given node :return: True if node == node2; False if node != node2 """ return node == self.node2 # Set string representation of the edge def __repr__(self) -> str: # If the edge is facing both nodes if self.direction == 0: return self.node1.name + ' <-----> ' + self.node2.name # If the edge is facing the first node elif self.direction == 1: return self.node1.name + ' <------ ' + self.node2.name # If the edge is facing the second node elif self.direction == 2: return self.node1.name + ' ------> ' + self.node2.name class Graph: def __init__(self) -> None: """ Graph class containing nodes and edges with methods of path finding """ # Define nodes and edges lists self.nodes = [] self.edges = [] def add_node(self, node: Node) -> None: """ Add node to graph :param node: Node to be added """ self.nodes.append(node) def add_nodes(self, nodes: list) -> None: """ Add nodes to graph :param nodes: List of nodes to be added """ self.nodes.extend(nodes) def set_nodes(self, nodes: list) -> None: """ Set nodes of the graph :param nodes: List of nodes to be set """ self.nodes = nodes def add_edge(self, edge: Edge) -> None: """ Add a new edge to the graph :param edge: Edge to be added """ self.edges.append(edge) def add_edges(self, edges: list) -> None: """ Add edges to graph :param edges: List of edges to be added """ self.edges.extend(edges) def set_edges(self, edges: list) -> None: """ Set edges of the graph :param nodes: List of edges to be set """ self.edges = edges def get_neighbors(self, node: Node) -> dict: """ Get all neighbors of a node, with the corresponding edges :param node: Node to get neighbors of :return: Dictionary with {<node>: <edge>, ...} """ neighbors = {} # For all nodes if node in self.nodes: # For all edges for e in self.edges: # If the node is the first in the edge declaration if e.is_first(node): # Add the other node to the dictionary of neighbors neighbors[e.node2] = e # If the node is the second in the edge declaration elif e.is_second(node): # Add the other node to the dictionary of neighbors neighbors[e.node1] = e return neighbors def find_path(self, start: Node, end: Node, algorithm: str = 'dijkstra') -> list: """ Find the shortest path from start node to end node using the Dijkstra or Bellman-Ford algorithm :param start: Node to start from :param end: Node to end at :return: Path from start to end [[<nodes_passed>], <length>] """ if start in self.nodes and end in self.nodes: # Init path path = {} # Set all node distances to infinity and the start distance to 0 for node in self.nodes: path[node] = [math.inf, None] path[start] = [0, None] # Calc path if algorithm == 'bellman-ford': path = self.bellman_ford(start, path) elif algorithm == 'dijkstra': path = self.dijkstra(start, path) else: print('Wrong algorithm provided, using Dijkstra ...') path = self.dijkstra(start, path) if path is None: return None # Create list of passed notes in the path path_nodes = [end] n = end while n != start: path_nodes.append(path[n][1]) n = path[n][1] path_nodes.reverse() # Return list with passed notes and length of the path return [path_nodes, path[end][0]] elif start not in self.nodes: print('Start node not in graph') elif end not in self.nodes: print('End node not in graph') def dijkstra(self, start: Node, path: dict) -> dict: """ Calculates the shortest possible path from a given start node using the Dijkstra-Algorithm :param start: Start Node :param path: Dictionary of {Node: [distance, previous_node], ...} to describe the path :return: Modified path dictionary with calculated distances """ nodes = path distances = {} while len(nodes) > 0: # Sort by ascending distances nodes = self.sort_dict(nodes) # Get the node with the smallest distance u = list(nodes.keys())[0] # Remove that node from the dict nodes.pop(u) neighbors = self.get_neighbors(u) # For all neighbors of this node for n in neighbors: # If the neighbor was not already calculated and can be accessed by the edge if n in nodes and n in neighbors[n].facing(): if u in distances: # If the new distance would be smaller than the current one if nodes[n][0] > neighbors[n].distance + distances[u][0]: # Set new distance nodes[n] = [neighbors[n].distance + distances[u][0], u] distances[n] = nodes[n] # Only happens if the node is a neighbor of the start node else: # Set initial distance nodes[n] = [neighbors[n].distance, u] distances[n] = nodes[n] return distances def bellman_ford(self, start: Node, path: dict) -> dict: """ Calculates the shortest possible path from a given start node using the Bellman-Ford-Algorithm :param start: Start Node :param path: Dictionary of {Node: [distance, previous_node], ...} to describe the path :return: Modified path dictionary with calculated distances """ for i in range(len(self.nodes)-1): # Iterate over all nodes for u in self.nodes: # Iterate over all neighbors of the current node neighbors = self.get_neighbors(u) for n in neighbors: # If the new distance would be smaller than the current one and the edge is facing the right direction if (path[u][0] + neighbors[n].distance) < path[n][0] and n in neighbors[n].facing(): # Change the current distance to the new one path[n] = [path[u][0] + neighbors[n].distance, u] # Check if there are remaining smaller distances for u in self.nodes: neighbors = self.get_neighbors(u) for n in neighbors: if (path[u][0] + neighbors[n].distance) < path[n][0]: # If there are any, there might be negative weight loops if n in neighbors[n].facing(): print('Negative weight loop found') return None return path @staticmethod def sort_dict(dictionary: dict) -> dict: """ Function used to sort a dictionary by its values :param dictionary: The dictionary to be used :return: The sorted dictionary """ return {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1])} def benchmark(function) -> None: """ Prints the time used to execute the given function :param function: Function to be measured """ time_before = time.time_ns() function() time_delta = (time.time_ns() - time_before) print('Benchmark: ' + str(time_delta/1000000) + ' ms') if __name__ == '__main__': graph = Graph() mue = Node('München') frb = Node('Freiburg') stg = Node('Stuttgart') fkf = Node('Frankfurt') kbl = Node('Koblenz') kln = Node('Köln') dsd = Node('Düsseldorf') brm = Node('Bremen') hmb = Node('Hamburg') kil = Node('Kiel') swr = Node('Schwerin') bln = Node('Berlin') drs = Node('Dresden') lpg = Node('Leipzig') eft = Node('Erfurt') hnv = Node('Hannover') mgd = Node('Magdeburg') graph.set_nodes([mue, frb, stg, fkf, kbl, kln, dsd, brm, hmb, kil, swr, bln, drs, lpg, eft, hnv, mgd]) graph.set_edges([ Edge(mue, frb, 280, 1), Edge(frb, stg, 140, 1), Edge(stg, mue, 240, 1), Edge(stg, fkf, 100, 1), Edge(fkf, kbl, 70, 1), Edge(kln, kbl, 70, 1), Edge(kln, dsd, 70, 2), Edge(kbl, dsd, 150, 1), Edge(kbl, eft, 120, 2), Edge(dsd, eft, 160, 1), Edge(fkf, eft, 90, 1), Edge(fkf, mue, 290, 2), Edge(eft, mue, 320, 1), Edge(lpg, mue, 530, 2), Edge(lpg, eft, 300, 0), Edge(dsd, lpg, 450, 1), Edge(dsd, brm, 230, 2), Edge(brm, eft, 330, 2), Edge(hmb, brm, 130, 2), Edge(kil, hmb, 130, 1), Edge(swr, kil, 320, 1), Edge(bln, swr, 190, 1), Edge(bln, lpg, 160, 2), Edge(drs, lpg, 70, 1), Edge(drs, bln, 150, 2), Edge(lpg, mgd, 150, 2), Edge(mgd, hnv, 100, 2), Edge(hnv, bln, 190, 0), Edge(hmb, bln, 220, 0), Edge(eft, hnv, 300, 2), Edge(dsd, hnv, 270, 2), Edge(hnv, brm, 130, 2), Edge(hnv, hmb, 140, 2), #33 Edges ]) nodes = {} for node in graph.nodes: nodes[node.name.lower()] = node # Script callable with args -> "python shortest_path.py <node1> <node2> [algorithm]" # node1 and node2 have to be names of nodes of the graph (can be lowercase or uppercase) # algorithm is optional and can either be 'dijkstra' or 'bellman-ford', default is 'dijkstra' args = sys.argv[1:] if len(args) == 2: node1 = nodes[args[0].lower()] node2 = nodes[args[1].lower()] benchmark(lambda: print(graph.find_path(node1, node2))) elif len(args) == 3: node1 = nodes[args[0].lower()] node2 = nodes[args[1].lower()] algorithm = args[2].lower() benchmark(lambda: print(graph.find_path(node1, node2, algorithm)))
8faa0216ee950c7fbfd1dec6cb28a47d9c5aff7f
DCTyxx/opencv_study
/class25_分水岭算法.py
2,272
3.53125
4
#分水岭变换 #基于距离变换 #分水岭的变换 输入图像->灰度化(消除噪声)->二值化->距离变换->寻找种子->生成Marker->分水岭变换->输出图像->end import cv2 as cv import numpy as np def watershed_demo(): print(src.shape) blurred = cv.pyrMeanShiftFiltering(src,10,100)#边缘保留滤波 gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY) ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)#二值图像 cv.namedWindow("binary-image", cv.WINDOW_NORMAL) cv.imshow("binary-image",binary) #形态学操作 kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))#结构元素 mb = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel,iterations=2)#连续俩次进行开操作 sure_bg = cv.dilate(mb,kernel,iterations=3)#使用特定的结构元素来扩展图像 拓展三次 cv.namedWindow("mor-opt", cv.WINDOW_NORMAL) cv.imshow('mor-opt',sure_bg) #距离变化 dist = cv.distanceTransform(mb,cv.DIST_L2,3)#L2 为欧几里得距离,为此移动大小为3 dist_output = cv.normalize(dist,0,1.0,cv.NORM_MINMAX)#规范化数组的范数或值范围 当normType = NORM_MINMAX时(仅适用于密集数组) #cv.imshow("distance-t",dist_output*50)#显示距离变化的结果 ret,surface = cv.threshold(dist,dist.max()*0.6,255,cv.THRESH_BINARY)#该函数通常用于从灰度图像中获取双级(二值)图像 #获得种子 #cv.imshow("surface-bin",surface) surface_fg = np.uint8(surface) unknown = cv.subtract(sure_bg,surface_fg)#除了种子以外的区域 ret,markers = cv.connectedComponents(surface_fg)#连通区域 print(ret) #分水岭变化 markers = markers+1 markers[unknown==255] = 0 markers = cv.watershed(src,markers=markers)#分水岭 src[markers==-1]=[0,0,255] #将值为0的区域 赋值为255 cv.namedWindow("result", cv.WINDOW_NORMAL) cv.imshow("result",src) #读取图片,读取的数据为numpy的多元数组 src = cv.imread('F:\software\pic\Aluminum_alloy\pic\pic/3-2.jpg') #opencv命名 cv.namedWindow("input image",cv.WINDOW_NORMAL) #显示图片 cv.imshow("input image",src) watershed_demo() #等待用户响应 cv.waitKey(0) #释放所有的类层 cv.destroyAllWindows()
9bf5a15c654b19ab6457ad83a3d0a763bb301892
wangyunge/algorithmpractice
/eet/Restore_IP_Addresses.py
1,293
3.90625
4
''' Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example: Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) Subscribe to see which companies asked this question Show Tags ''' class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ #Constraint: #1.Less than 255. 2.Start with non-zero element. self.res = [] self.s = s stack = [] Depth = 0 index =0 self.DFS(stack,index,Depth) return self.res def DFS(self,stack,index,Depth): if Depth == 4: if index == len(self.s): self.res.append(".".join(stack)) return None if index < len(self.s) and self.s[index] == "0": self.DFS(stack+["0"],index+1,Depth+1) else: for i in xrange(0,3): if index+i < len(self.s) and int(self.s[index:index+i+1]) <= 255: self.DFS(stack+[self.s[index:index+i+1]],index+i+1,Depth+1) def main(): sol = Solution() example = "25525511135" res = sol.restoreIpAddresses(example) print res if __name__ == '__main__': main()
e8116a0ec63ed32ab24c42650a5e9c51789b5cd8
wangyunge/algorithmpractice
/int/389_Valid_Sudoku.py
858
3.890625
4
''' Determine whether a Sudoku is valid. The Sudoku board could be partially filled, where empty cells are filled with the character .. Notice A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. Have you met this question in a real interview? Yes Clarification What is Sudoku? http://sudoku.com.au/TheRules.aspx https://zh.wikipedia.org/wiki/%E6%95%B8%E7%8D%A8 https://en.wikipedia.org/wiki/Sudoku http://baike.baidu.com/subview/961/10842669.htm Example The following partially filed sudoku is valid. Valid Sudoku ''' class Solution: def isValidSudoku(self, board): seen = sum(([(c, i), (j, c), (i/3, j/3, c)] for i, row in enumerate(board) for j, c in enumerate(row) if c != '.'), []) return len(seen) == len(set(seen))
79db945c27a3797a29b9de46201352fa9e4f0a1b
wangyunge/algorithmpractice
/int/110_Minimum_Path_Sum.py
888
3.859375
4
''' Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Notice You can only move either down or right at any point in time. Have you met this question in a real interview? Yes ''' class Solution: """ @param grid: a list of lists of integers. @return: An integer, minimizes the sum of all numbers along its path """ def minPathSum(self, grid): if not grid: return 0 for i in xrange(1,len(grid)): grid[i][0] = grid[i-1][0]+grid[i][0] for j in xrange(1,len(grid[0])): grid[0][j] = grid[0][j-1]+grid[0][j] for i in xrange(1,len(grid)): for j in xrange(1,len(grid[0])): grid[i][j] = min(grid[i-1][j],grid[i][j-1]) + grid[i][j] return grid[len(grid)-1][len(grid[0])-1]
352bf4ce999b1f9d03c6b96f79e8cdbb2f7230bf
wangyunge/algorithmpractice
/int/98_Sorted_List.py
1,324
3.953125
4
''' Sort a linked list in O(n log n) time using constant space complexity. Have you met this question in a real interview? Yes Example Given 1->3->2->null, sort it to 1->2->3->null. ''' """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of the linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """ def sortList(self, head): if not head: return head slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next h2 = self.sortList(slow.next) slow.next = None return self.merge(self.sortList(head),h2) def merge(self,leftHead,righHead): helper = ListNode(0,None) index = helper while leftHead and righHead: if leftHead.val <= righHead: index.next = leftHead leftHead = leftHead.next else: index.next = righHead righHead = righHead.next index = index.next index.next = leftHead if leftHead else righHead return helper.next
1bd27fbaa4aa4a3017d24929b4698cf48c3c1dbb
wangyunge/algorithmpractice
/int/82_Single_Number.py
476
3.65625
4
''' Given 2*n + 1 numbers, every numbers occurs twice except one, find it. Have you met this question in a real interview? Yes Example Given [1,2,2,1,3,4,3], return 4 ''' class Solution: """ @param A : an integer array @return : a integer """ def singleNumber(self, A): res = 0 for number in A: res = res ^ number return res ''' Note: 1. Exclusive or produce 1 when two bits are different and 0 when they are same. '''
6e34a6e1dcf7b985b56e0b928a27b284d0c96c99
wangyunge/algorithmpractice
/eet/Best_Time_to_Buy_and_Sell_Stock_IV.py
1,809
4.0625
4
''' Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Example 1: Input: [2,4,1], k = 2 Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. Example 2: Input: [3,2,6,5,0,3], k = 2 Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.''' class Solution(object): def maxProfit(self, k, prices): """ :type k: int :type prices: List[int] :rtype: int """ """ Note: 1. You can Sell and Buy at the same day. 2. Keep recording the max profit while holding the stocks(means you can sell the next day), when you take last transcation. t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax); # Sell before or Sell now tmpMax = Math.max(tmpMax, t[i - 1][j] - prices[j]); # Buy before or buy now """ class Solution(object): def maxProfit(self, k, prices): """ :type k: int :type prices: List[int] :rtype: int """ dp = [[0 for _ in range(prices)] for _ in range(k)] b_max = float('-inf') for j in range(1,len(prices)): dp[0][j] = max(dp[0][j-1], b_max + prices[j]) b_max = max(b_max, 0-prices[j]) for i in range(1,k): for j in range(1, len(prices)): dp[i][j] = max(dp[i][j-1], b_max + prices[j]) b_max = max(b_max, dp[i-1][j]-prices[j]) return dp[-1][-1]
ea76677bfc6bfc1c602ddd530ccc593258bd27c0
wangyunge/algorithmpractice
/eet/01_Matrix.py
526
4
4
""" Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. Example 1: Input: [[0,0,0], [0,1,0], [0,0,0]] Output: [[0,0,0], [0,1,0], [0,0,0]] Example 2: Input: [[0,0,0], [0,1,0], [1,1,1]] Output: [[0,0,0], [0,1,0], [1,2,1]] """ class Solution(object): def updateMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ for i in range(len(matrix)):
431e4b3687f6e41381331f315f13108fc029d396
wangyunge/algorithmpractice
/eet/Check_Completeness_of_a_Binary_Tree.py
1,354
4.21875
4
""" Given the root of a binary tree, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example 1: Input: root = [1,2,3,4,5,6] Output: true Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. Example 2: Input: root = [1,2,3,4,5,null,7] Output: false Explanation: The node with value 7 isn't as far left as possible. """ # 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 isCompleteTree(self, root): """ :type root: TreeNode :rtype: bool """ self.max_val = 0 self.sum = 0 def _dfs(node, value): if node: self.max_val = max(self.max_val, value) self.sum += value _dfs(node.left, 2 * value) _dfs(node.right, 2 * value + 1) _dfs(root, 1) return self.sum == self.max_val/2 * (1+self.max_val)
d9cdb986d5d7d796156e0ef1cc51c21cd096f9b7
wangyunge/algorithmpractice
/eet/Longest_Increasing_Path_in_a_Matrix.py
3,306
4.125
4
""" Given an integer matrix, find the length of the longest increasing path. From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed). Example 1: Input: nums = [ [9,9,4], [6,6,8], [2,1,1] ] Output: 4 Explanation: The longest increasing path is [1, 2, 6, 9]. Example 2: Input: nums = [ [3,4,5], [3,2,6], [2,2,1] ] Output: 4 Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. """ class Solution(object): def longestIncreasingPath(self, matrix): """ :type matrix: List[List[int]] :rtype: int """ if not matrix: return 0 if len(matrix[0]) == 0: return 0 dec_DP = [[1 for _ in range(len(matrix[0]))] for _ in range(len(matrix))] inc_DP = [[1 for _ in range(len(matrix[0]))] for _ in range(len(matrix))] for j in range(1, len(matrix[0])): if matrix[0][j] > matrix[0][j-1]: dec_DP[0][j] = dec_DP[0][j-1] + 1 for j in range(0, len(matrix[0])-1)[::-1]: if matrix[0][j] > matrix[0][j+1]: inc_DP[0][j] = inc_DP[0][j+1] + 1 for i in range(1, len(matrix)): if matrix[i][0] > matrix[i-1][0]: dec_DP[i][0] = dec_DP[i-1][0] + 1 for i in range(0, len(matrix[0])-1)[::-1]: if matrix[i][0] > matrix[i+1][0]: inc_DP[i][0] = inc_DP[i+1][0] + 1 for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i][j] > matrix[i-1][j] : last_up = dec_DP[i-1][j] else: last_up = 0 if matrix[i][j] > matrix[i][j-1] : last_left = dec_DP[i][j-1] else: last_left = 0 dec_DP[i][j] = max(last_left, last_up) + 1 for i in range(0, len(matrix)-1)[::-1]: for j in range(0, len(matrix[0])-1)[::-1]: if matrix[i][j] > matrix[i+1][j] : last_up = inc_DP[i+1][j] else: last_up = 0 if matrix[i][j] > matrix[i][j+1] : last_left = inc_DP[i][j+1] else: last_left = 0 inc_DP[i][j] = max(last_left, last_up) + 1 res = 0 for i in range(0, len(matrix)): for j in range(0, len(matrix[0])): res = max(res, inc_DP[i][j] + dec_DP[i][j] -1 ) return res def longestIncreasingPath(self, matrix): def dfs(i, j): if not dp[i][j]: val = matrix[i][j] dp[i][j] = 1 + max( dfs(i - 1, j) if i and val > matrix[i - 1][j] else 0, dfs(i + 1, j) if i < M - 1 and val > matrix[i + 1][j] else 0, dfs(i, j - 1) if j and val > matrix[i][j - 1] else 0, dfs(i, j + 1) if j < N - 1 and val > matrix[i][j + 1] else 0) return dp[i][j] if not matrix or not matrix[0]: return 0 M, N = len(matrix), len(matrix[0]) dp = [[0] * N for i in range(M)] return max(dfs(x, y) for x in range(M) for y in range(N))
597bdffceea740761f6280470d81b9deaf73f400
wangyunge/algorithmpractice
/int/517_Ugly_Number.py
926
4.125
4
''' Write a program to check whether a given number is an ugly number`. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. Notice Note that 1 is typically treated as an ugly number. Have you met this question in a real interview? Yes Example Given num = 8 return true Given num = 14 return false ''' class Solution: # @param {int} num an integer # @return {boolean} true if num is an ugly number or false def isUgly(self, num): if num < 1: return False while True: if num % 2 == 0: num = num/2 elif num % 3 == 0: num = num/3 elif num % 5 == 0: num = num/5 else: break if num != 1: return False else: return True
6ae3a55543601626d59949db457edce81a02b2b9
wangyunge/algorithmpractice
/eet/Add_Two_Numbers_II.py
1,225
4.03125
4
""" You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Follow up: What if you cannot modify the input lists? In other words, reversing the lists is not allowed. Example: Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ def _reverse(l1): prev = None while l1: tmp = l1.next l1.next = prev prev = l1 l1 = tmp return prev l1 = _reverse(l1) l2 = _reverse(l2) carry = 0 while l1 and l2: carry = (l1.val+l2.val) // 10 if __name__ == '__main__': main()
53b1b4043d4949f1aec2b18d909993cc049772e8
wangyunge/algorithmpractice
/cn/572.py
978
3.890625
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 isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ def _check(source, target): if source and target: if source.val == target.val: return _check(source.left, target.left) and _check(source.right, target.right) else: return False elif not source and not target: return True else: return False def _dfs(a, b): if a: if _check(a, b): return True return _check(a.left, b) or _check(a.right, b) if not t: return True return _dfs(s, t)
2e3a39178816c77f9f212cb1629a8f17950da152
wangyunge/algorithmpractice
/int/171_Anagrams.py
692
4.34375
4
''' Given an array of strings, return all groups of strings that are anagrams. Notice All inputs will be in lower-case Have you met this question in a real interview? Yes Example Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"]. Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"]. ''' class Solution: # @param strs: A list of strings # @return: A list of strings def anagrams(self, strs): table = {} res = [] for word in strs: setOfWord = set(word) if setOfWord not in table: table[setOfWord] = word else: res.append(word) return res
f99cf09f6bdb40dd270f2a7845f6aa530f614795
wangyunge/algorithmpractice
/eet/Find_K_Pairs_with_Smallest_Sums.py
1,749
3.875
4
""" You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u,v) which consists of one element from the first array and one element from the second array. Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums. Example 1: Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]] Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] Example 2: Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [1,1],[1,1] Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] Example 3: Input: nums1 = [1,2], nums2 = [3], k = 3 Output: [1,3],[2,3] Explanation: All possible pairs are returned from the sequence: [1,3],[2,3] """ from heapq import * class Solution: def kSmallestPairs(self, nums1, nums2, k): if not nums1 or not nums2: return [] visited = [] heap = [] output = [] heappush(heap, (nums1[0] + nums2[0], 0, 0)) visited.append((0, 0)) while len(output) < k and heap: val = heappop(heap) output.append((nums1[val[1]], nums2[val[2]])) if val[1] + 1 < len(nums1) and (val[1] + 1, val[2]) not in visited: heappush(heap, (nums1[val[1] + 1] + nums2[val[2]], val[1] + 1, val[2])) visited.append((val[1] + 1, val[2])) if val[2] + 1 < len(nums2) and (val[1], val[2] + 1) not in visited: heappush(heap, (nums1[val[1]] + nums2[val[2] + 1], val[1], val[2] + 1)) visited.append((val[1], val[2] + 1)) return output
cbc345e64aaa1883a5626e834e998addae622309
wangyunge/algorithmpractice
/int/488_Happpy_Number.py
979
3.78125
4
''' Write an algorithm to determine if a number is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Have you met this question in a real interview? Yes Example 19 is a happy number 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 ''' class Solution: # @param {int} n an integer # @return {boolean} true if this is a happy number or false def isHappy(self, n): table = {} while n not in table: if n == 1: return True table[n] = 1 nextN = 0 while n > 0: nextN += pow(n%10,2) n = n/10 n = nextN return False
14e00c017aa35b3d0901ec3b9f83bf5d51c345be
wangyunge/algorithmpractice
/cn/234.py
653
3.671875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ stack = [] cur = head while cur: stack.append(cur.val) cur = cur.next cnt = 0 cur = head L = len(stack) while cnt < L // 2: if stack.pop() != cur.val: return False cur = cur.next cnt += 1 return True
1f4cd6fa5f100f5fec1f7ebcadf8eb99dbf09fe6
wangyunge/algorithmpractice
/eet/Counting_Bits.py
1,765
3.765625
4
""" Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example 1: Input: 2 Output: [0,1,1] Example 2: Input: 5 Output: [0,1,1,2,1,2] Follow up: It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? Space complexity should be O(n). Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. """ class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ even = 0 odds = 0 tmp = 1 for i in range(34): if i % 2 == 0: even += tmp if i % 2 == 1: odds += tmp tmp = tmp * 2 res = [0 for _ in range(len(num))] for i in range(len(num)): a = even & item b = odds & item res[i] = res[a] + res[b] return res """ Notes: Dynamic Programming: Current numbers has one more 1 than the one minus the highest postion 1000 1 1101 -- 0 1101 1 0001 -- 0 0001 """ 0 1 res[0] +1 01 2 res[0] + 1 10 3 res[1] + 1 4 res[2] + 1 5 6 7 8 class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ k = 0 idx = 1 res = [0] * num res[1] = 1 while idx <= num: offset = 0 while idx < pow(2,k+1): res[idx] = res[idx-pow(2,k)] + 1 idx += 1 offset += 1 k += 1 return res
c730b160e62fd19ed56a4dbd8740dceed38583c2
wangyunge/algorithmpractice
/eet/Android_Unlock_Patterns.py
1,583
4
4
""" 我们都知道安卓有个手势解锁的界面,是一个 3 x 3 的点所绘制出来的网格。用户可以设置一个 “解锁模式” ,通过连接特定序列中的点,形成一系列彼此连接的线段,每个线段的端点都是序列中两个连续的点。如果满足以下两个条件,则 k 点序列是有效的解锁模式: 解锁模式中的所有点 互不相同 。 假如模式中两个连续点的线段需要经过其他点,那么要经过的点必须事先出现在序列中(已经经过),不能跨过任何还未被经过的点。   以下是一些有效和无效解锁模式的示例:   无效手势:[4,1,3,6] ,连接点 1 和点 3 时经过了未被连接过的 2 号点。 无效手势:[4,1,9,2] ,连接点 1 和点 9 时经过了未被连接过的 5 号点。 有效手势:[2,4,1,3,6] ,连接点 1 和点 3 是有效的,因为虽然它经过了点 2 ,但是点 2 在该手势中之前已经被连过了。 有效手势:[6,5,4,1,9,2] ,连接点 1 和点 9 是有效的,因为虽然它经过了按键 5 ,但是点 5 在该手势中之前已经被连过了。 给你两个整数,分别为 ​​m 和 n ,那么请你统计一下有多少种 不同且有效的解锁模式 ,是 至少 需要经过 m 个点,但是 不超过 n 个点的。 两个解锁模式 不同 需满足:经过的点不同或者经过点的顺序不同。 """ class Solution(object): def numberOfPatterns(self, m, n): """ :type m: int :type n: int :rtype: int """
1ae166cb04757e11a8ca03fe3c83cbd2e3c602f1
wangyunge/algorithmpractice
/int/106_Convert_Sorted_List_to_Balanced_BST.py
1,193
3.890625
4
''' Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. Have you met this question in a real interview? Yes Example 2 1->2->3 => / \ 1 3 ''' """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param head: The first node of linked list. @return: a tree node """ def sortedListToBST(self, head): if not head: return None if not head.next: return TreeNode(head.val) index = head.next mid = head while index: if index.next and index.next.next: index = index.next.next else: break mid = mid.next root = TreeNode(mid.next.val) right = mid.next.next mid.next = None root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(right) return root
3e5582033c67af1213ba003cff4b3095dabb15b5
wangyunge/algorithmpractice
/eet/Lowest_Common_Ancestor_of_a_Binary_Tree.py
2,220
4.0625
4
""" Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. Note: All of the nodes' values will be unique. p and q are different and both values will exist in the binary tree. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ self.p = p self.q = q res, _, _ = self._dfs(root) return res def _dfs(self, root): if not root: return None, False, False left_res, left_p, left_q = self._dfs(root.left) right_res, right_p, right_q = self._dfs(root.right) cur_p = True if root.val == p.val else False cur_q = True if root.val == q.val else False if left_res is not None: return left_res, True, True if right_res is not None: return right_res, True, True find_p = False if cur_p or left_p or right_p: find_p = True find_q = False if cur_q or left_q or right_q: find_q = True if find_p and find_q: return root, True, True return None, find_p, find_q """ Note: Recurring can pass message back by using return. So we don't need to do the dfs twice(Check and Search) """
854d5d19c39b60ed8b67150778a4bb015918c88b
wangyunge/algorithmpractice
/eet/Nth_Digit.py
852
3.9375
4
""" Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... Note: n is positive and will fit within the range of a 32-bit signed integer (n < 231). Example 1: Input: 3 Output: 3 Example 2: Input: 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. """ class Solution(object): def findNthDigit(self, n): """ :type n: int :rtype: int """ carry = 9 incre = 1 def _move(): carry = (carry + 1) * 10 -1 incre += 1 idx = 0 last_idx = 0 number = 1 while idx < n: if number > carry: _move idx += incre number += 1 return str(number-1)[(n-(idx-incre))]
e39cd00b68b6eff21de3d1b8364de609b687a309
wangyunge/algorithmpractice
/int/392_House_Robber.py
1,002
3.625
4
''' You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Have you met this question in a real interview? Yes Example Given [3, 8, 4], return 8. ''' class Solution: # @param A: a list of non-negative integers. # return: an integer def houseRobber(self, A): if not A: return 0 DP = [[0,0] for i in xrange (len(A))] DP[0][0] = 0 DP[0][1] = A[0] for i in xrange(1,len(A)): DP[i][0] = max(DP[i-1]) DP[i][1] = DP[i-1][0] + A[i] return max(DP[len(A)-1])
e3ee7499abf955e0662927b7341e93fa81843620
wangyunge/algorithmpractice
/eet/Arithmetic_Slices.py
960
4.15625
4
""" An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array. Example 1: Input: nums = [1,2,3,4] Output: 3 Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. Example 2: Input: nums = [1] Output: 0 """ class Solution(object): def numberOfArithmeticSlices(self, nums): """ :type nums: List[int] :rtype: int """ diff = [nums[i] - num[i-1] for i in range(1, len(nums))] consecutive = [0] * len(nums) for i in range(2, len(nums)): consecutive[i] = 2 * consecutive[i-1] - consecutive[i-2] + 1 for i in range(diff):
6c899e296237b144ba623fbbab473202cd0410ca
wangyunge/algorithmpractice
/eet/Insertion_Sorted_List.py
887
3.9375
4
''' Sort a linked list using insertion sort. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ newHead = ListNode(float("-inf")) while head: curr = head head = head.next L = newHead while L: if L.next: if curr.val <= L.next.val: tmp = L.next L.next = curr curr.next = tmp break else: L.next = curr curr.next = None break L = L.next return newHead.next
36039a9ac17ee24da100aebe9dd7b00cd17ab7f3
wangyunge/algorithmpractice
/eet/Palindrome_Partitioning_II.py
1,029
3.859375
4
""" Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example 1: Input: s = "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. Example 2: Input: s = "a" Output: 0 Example 3: Input: s = "ab" Output: 1 Constraints: 1 <= s.length <= 2000 s consists of lower-case English letters only. """ class Solution(object): def minCut(self, s): """ :type s: str :rtype: int """ # build the palindrme end for every start reach = [[] for _ in range(len(s))] for i in range(len(s)): for j in range(i, len(s))[::-1]: if _check(i, j): reach[j].append(j) dp = [idx for idx in range(len(s))] dp.append(0) # rr-1 = -1 for i in range(1, len(s)): for rr in reach[i]: dp[i] = min(dp[i] , dp[rr-1] + 1) return dp[-2]
9735ec4ad9479d0b9fe83a05b0f7a597d2b0ddd7
wangyunge/algorithmpractice
/int/408_Add_Binary.py
1,126
3.671875
4
''' Given two binary strings, return their sum (also a binary string). Have you met this question in a real interview? Yes Example a = 11 b = 1 Return 100 ''' class Solution: # @param {string} a a number # @param {string} b a number # @return {string} the result def addBinary(self, a, b): longS = a if len(a) >= len(b) else b shortS = b if len(a) >= len(b) else a index = 1 carry = 0 res = [] while index <= len(longS): if index <= len(shortS): cal = int(longS[-index]) + int(shortS[-index]) + carry else: cal = int(longS[-index]) + carry if cal == 0: add = '0' carry = 0 if cal == 1: add = '1' carry = 0 if cal == 2: add = '0' carry = 1 if cal == 3: add = '1' carry = 1 index += 1 res.append(add) if carry == 1: res.append('1') res.reverse() return ''.join(res)
9495b0f644bec8ff8727429271b3b4ffd1f11bbc
wangyunge/algorithmpractice
/int/426_Restore_IP_Address.py
1,307
3.875
4
''' Given a string containing only digits, restore it by returning all possible valid IP address combinations. Have you met this question in a real interview? Yes Example Given "25525511135", return [ "255.255.11.135", "255.255.111.35" ] Order does not matter. ''' class Solution: # @param {string} s the IP string # @return {string[]} All possible valid IP addresses def restoreIpAddresses(self, s): self.s = s start = 0 self.res = [] if not s: return [] if self.s[0] == '0': self.DFS('0',1,1) else: for i in xrange(start+1,len(self.s)+1): if int(self.s[start:i]) <= 255: self.DFS(self.s[start:i],i,1) else: break return self.res def DFS(self,res,start,dot): if start == len(self.s) and dot == 4: self.res.append(res) elif start != len(self.s) and dot != 4: if self.s[start] == '0': self.DFS(res +'.0',start+1,dot+1) else: for i in xrange(start+1,len(self.s)+1): if int(self.s[start:i]) <= 255: self.DFS(res+'.'+self.s[start:i],i,dot+1) else: break
6eb1182dc9674ff9514f860b80c6eacaa3b54487
wangyunge/algorithmpractice
/eet/Recover_Binary_Search_Tree.py
3,165
3.8125
4
''' Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? Subscribe to see which companies asked this question Show Tags ''' # 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 recoverTree(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead. """ self.left = None self.right = None self.prev = None def _inorder_traverse(node): if node: _inorder_traverse(node.left) if self.prev and self.prev.val > node.val: if not self.left: self.left = self.prev else: self.right = node _inorder_traverse(node.right) _inorder_traverse(root) self.left.val, self.right.val = self.right.val, self.left.val # 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 recoverTree(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead. """ self.left = None self.right = None def _search_left(node): if node: _search_left(node.left) if self.left and self.left.val > node.val: return self.left self.left = node _search_left(node.right) def _search_right(node): if node: _search_right(node.right) if self.right and self.right.val < node.val: return self.right self.right = node _search_right(node.right) _search_left(root) _search_right(root) self.left.val, self.right.val = self.right.val, self.left.val # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def recoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ self.last = float("-inf") self.swapped = [] if root: self.inOrderTraversal(root) self.swapped[0].val,self.swapped[1] = self.swapped[1],self.swapped[0] def inOrderTraversal(self,root): if root.left: self.inOrderTraversal(root.left) if self.last > root.val: self.swapped.append(root) else: self.last = root.val if root.right: self.inOrderTraversal(root.right)
3859966faca648ffe0b7e83166049c07676ba93b
wangyunge/algorithmpractice
/eet/Maximum_Units_on_a_Truck.py
2,304
4.125
4
""" You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i. numberOfUnitsPerBoxi is the number of units in each box of the type i. You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck. Example 1: Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 Output: 8 Explanation: There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8. Example 2: Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 Output: 91 """ class Solution(object): def maximumUnits(self, boxTypes, truckSize): """ :type boxTypes: List[List[int]] :type truckSize: int :rtype: int """ if truckSize < 0: return 0 last_dp = [0 for _ in range(truckSize+1)] dp = [0 for _ in range(truckSize+1)] for i in range(len(boxTypes)): for j in range(1, truckSize+1): for num in range(1, boxTypes[i][0]+1): spare_track = j - num if spare_track >= 0: dp[j] = max(dp[j],last_dp[spare_track]+num*boxTypes[i][1]) last_dp = dp[:] return dp[-1] """ Notes: last dp and dp, need two states. """ class Solution(object): def maximumUnits(self, boxTypes, truckSize): """ :type boxTypes: List[List[int]] :type truckSize: int :rtype: int """ order_box = sorted(boxTypes, key=lambda x: x[1]) space = 0 res = 0 for box_num, box_unit in order_box: for num in range(1, box_num+1): if 1 + space <= truckSize: space += 1 res += box_unit return res
fd3f8f5c834978e65253411de28c9177994120f9
wangyunge/algorithmpractice
/int/186_Max_Points_on_a_Line.py
1,782
3.609375
4
''' Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Example Given 4 points: (1,2), (3,6), (0,0), (1,3). The maximum number is 3. ''' # Definition for a point. # class Point: # def __init__(self, a=0, b=0): # self.x = a # self.y = b class Solution: # @param {int[]} points an array of point # @return {int} an integer def maxPoints(self, points): res = 0 for i in xrange(len(points)): table = {} table['v'] = 1 same = 0 for j in xrange(i+1,len(points)): if points[i].x == points[j].x and points[i].y == points[j].y: same +=1 elif points[i].x == points[j].x: table['v'] += 1 else: slope = 1.0 * (points[i].y - points[j].y)/(points[i].x - points[j].x) if slope in table: table[slope] += 1 else: table[slope] = 1 localMax = max(table.values()) + same res = max(res,localMax) return res def maxPoints(self, points): l = len(points) m = 0 for i in range(l): dic = {'i': 1} same = 0 for j in range(i+1, l): tx, ty = points[j].x, points[j].y if tx == points[i].x and ty == points[i].y: same += 1 continue if points[i].x == tx: slope = 'i' else:slope = (points[i].y-ty) * 1.0 /(points[i].x-tx) if slope not in dic: dic[slope] = 1 dic[slope] += 1 m = max(m, max(dic.values()) + same) return m
76c084094d90c838b553d1e58b78252f55852e3d
wangyunge/algorithmpractice
/eet/Contiguous_Array.py
893
4.0625
4
""" Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. Note: The length of the given binary array will not exceed 50,000. """ class Solution(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ B = [1 if item==1 else -1 for item in nums] table = {0:-1} res = 0 level = 0 for idx in range(len(B)): level += B[idx] if level in table: res = max(res, idx - table[level]) else: table[level] = idx return res
181bd6428a741980af6e7ce9d2947b88a579cc8e
wangyunge/algorithmpractice
/eet/Pairs_of_Songs_With_Total_Durations_Divisible_by_60.py
1,133
3.8125
4
""" You are given a list of songs where the ith song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0. Example 1: Input: time = [30,20,150,100,40] Output: 3 Explanation: Three pairs have a total duration divisible by 60: (time[0] = 30, time[2] = 150): total duration 180 (time[1] = 20, time[3] = 100): total duration 120 (time[1] = 20, time[4] = 40): total duration 60 Example 2: Input: time = [60,60,60] Output: 3 Explanation: All three pairs have a total duration of 120, which is divisible by 60. """ class Solution(object): def numPairsDivisibleBy60(self, time): """ :type time: List[int] :rtype: int """ table = {} res = 0 for idx in range(len(time)): offset = time[idx] % 60 key = 60 - offset if offset != 0 else 0 res += table.get(key, 0) cnt = table.get(offset, 0) table[offset] = cnt + 1 return res
e8f4d5ca11f339e1fa8c13b85ae55e7de66c0bcd
wangyunge/algorithmpractice
/int/73_Construct_Binary_Tree_from_Preorder_and_Inorder_Travesal.py
1,895
3.921875
4
''' Given preorder and inorder traversal of a tree, construct the binary tree. Notice You may assume that duplicates do not exist in the tree. Have you met this question in a real interview? Yes Example Given in-order [1,2,3] and pre-order [2,1,3], return a tree: 2 / \ 1 3 ''' """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param preorder : A list of integers that preorder traversal of a tree @param inorder : A list of integers that inorder traversal of a tree @return : Root of a tree """ def buildTree(self, preorder, inorder): if not preorder: return None root = TreeNode(preorder[0]) for j in xrange(len(inorder)): if inorder[j] == preorder[0]: break self.DFS(preorder[1:],inorder[:j],root,True) self.DFS(preorder[1:],inorder[j+1:],root,False) return root def DFS(self,preorder,inorder,parent,left): found = False for i in xrange(0,len(preorder)): for j in xrange(0,len(inorder)): if inorder[j] == preorder[i]: found = True break if found: break if found: root = TreeNode(inorder[i]) if left: parent.left = root else: parent.right = root self.DFS(preorder[i+1:],inorder[:j],root,True) self.DFS(preorder[i+1:],inorder[j+1:],root,False) def buildTree(self, preorder, inorder): if inorder: ind = inorder.index(preorder.pop(0)) root = TreeNode(inorder[ind]) root.left = self.buildTree(preorder, inorder[0:ind]) root.right = self.buildTree(preorder, inorder[ind+1:]) return root
d620071842e6003015b2a9f34c72b85a64e00a04
wangyunge/algorithmpractice
/eet/Multiply_Strings.py
1,183
4.125
4
""" Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Constraints: 1 <= num1.length, num2.length <= 200 num1 and num2 consist of digits only. Both num1 and num2 do not contain any leading zero, except the number 0 itself. """ class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ l1 = len(num1) l2 = len(num2) res = [0] * (l1 + l2 +1) for i in range(l1)[::-1]: for j in range(l2)[::-1]: pdc = int(num1[i]) * int(num2[j]) plus = res[i+j] + pdc res[i+j] += pdc % 10 res[i+j+1] = pdc / 10 res = map(res, lambda x: str(x)) if res[0] == '0': return ''.join(res[1:]) else: return ''.join(res)
b956afb98967e9ca2fb6c320bcd360691e20b9f0
wangyunge/algorithmpractice
/cn/29.py
558
3.546875
4
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ sign = 1 if dividend * divisor > 0 else -1 divisor = abs(divisor) dividend = abs(dividend) def _sub(res): x = divisor if res < divisor: return 0 ans = 1 while 2 * x <= res: x = 2 * x ans = 2 * ans return ans + _sub(res-x) return _sub(dividend)
bdfc9caa3090f7727fd227548a83aaf19bf66c14
wangyunge/algorithmpractice
/eet/Unique_Binary_Search_Tree_II.py
1,269
4.25
4
''' Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 Subscribe to see which companies asked this question ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ def generateByList(self,list): root = TreeNode(list[0]) for i in xrange(1,len(list)): self.BSTappend(root,list[i]) return root def BSTappend(self,root,num): parent = root while root: parent = root if root.val < num: root = root.right else: root = root.left if parent.val < num: parent.right = TreeNode(num) else: parent.left = TreeNode(num)
9eba4c97143250a68995688a62b41145ab39485f
wangyunge/algorithmpractice
/int/165_Merge_Two_Sorted_Lists.py
944
4.125
4
''' Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order. Have you met this question in a real interview? Yes Example Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null. ''' z""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param two ListNodes @return a ListNode """ def mergeTwoLists(self, l1, l2): helper = ListNode(0,None) index = helper while l1 and l2: if l1.val <= l2.val: index.next = l1 l1 = l1.next else: index.next = l2 l2 = l2.next index = index.next index.next = l1 if l1 else l2 return helper.next
1ed697d41f7a62305a2bb7d82c3e945e47ac65b4
wangyunge/algorithmpractice
/int/167_Add_Two_Numbers.py
894
3.859375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param l1: the first list # @param l2: the second list # @return: the sum list of l1 and l2 def addLists(self, l1, l2): # write your code here helper = ListNode(0) head = helper digit=1 plus=0 while l1 or l2: if l1: a = l1.val l1 = l1.next else: a = 0 if l2: b = l2.val l2 = l2.next else: b = 0 levelRes = (a+b+plus)%10 plus = (a+b+plus)/10 head.next = ListNode(levelRes) head = head.next if plus==1: head.next = ListNode(1) return helper.next
a1e44328e89eccd44eccdf0f5bcad629ac9c4688
wangyunge/algorithmpractice
/cn/445.py
1,087
3.640625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ s1 = [] s2 = [] while l1: s1.append(l1.val) l1 = l1.next while l2: s2.append(l2.val) l2 = l2.next carry = 0 res = [] while s1 and s2: a1 = s1.pop() a2 = s2.pop() a3 = a1+a2+carry res.append(a3 % 10) carry = a3 // 10 rest = s1 if s1 else s2 while rest: a1 = rest.pop() a3 = a1+carry res.append(a3 % 10) carry = a3 // 10 if carry > 0: res.append(carry) dummy = ListNode(0) cur = dummy while res: cur.next = ListNode(res.pop()) cur = cur.next return dummy.next
8bbc714ce6bbf0420e2d320b0f9bccef01187ae8
wangyunge/algorithmpractice
/eet/First_Unique_Character_in_a_String.py
771
3.859375
4
""" Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode" return 2. Note: You may assume the string contains only lowercase English letters. """ class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ res = len(s) table = {} for idx in range(len(s)): last_id, cnt = table.get(s[idx], (len(s), 0)) table[s[idx]] = (min(last_id, idx), cnt+1) for last_id, cnt in table.keys(): if cnt == 1: res = min(res, last_id) if res == len(s): return -1 else: return res
c09cd743358e384ed520289eb8c09dab719ca8b3
wangyunge/algorithmpractice
/int/101_Remove_Duplicates_from_Sorted_Array.py
543
3.859375
4
''' Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. ''' class Solution: """ @param A: a list of integers @return an integer """ def removeDuplicates(self, A): if len(A) < 2: return len(A) pos = 1 for i in xrange(2,len(A)): if A[i] != A[pos-1]: pos += 1 A[pos] = A[i] return pos+1