blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
325c4e623b8503ef0ec256f098017b267c8e042f
maiphuong1809/nguyemaiphuong-fundamental-c4t4
/session03/Homework/sum_b.py
221
3.78125
4
num = int(input("Enter a number: ")) Sum = 0 for i in range (1, num+1): m=1 for p in range(1,i+1): m=m*p Sum=Sum+1/m print("S = 1/1! + 1/2! + ... + 1/{0}{1}{2}".format(num,"! = ",Sum))
ef469699554b40fdcc01a86579f809c72a2d4c81
maiphuong1809/nguyemaiphuong-fundamental-c4t4
/session03/document/login.py
265
3.578125
4
import getpass username = input("User Name:") if username == "Maiphuong": password = getpass.getpass() if password == "1809": print ("Welcome MP") else: print ("Incorrect password") else: print ("You are not the user")
2ef1c534ba2f148c6d3c4ecef46a20ecf559702a
maiphuong1809/nguyemaiphuong-fundamental-c4t4
/session04/btvn04.py/turtle02.py
171
3.5
4
from turtle import* speed (-1) color("blue") for i in range (50): for _ in range (4): forward (20+i*4) left (90) right (350) mainloop()
870ecd7b02371c23199c478e9e553396c283cba0
gracenng/Salam-Technica
/data_process.py
3,172
3.5
4
import requests import pandas as pd import csv from google.cloud import bigquery import jwt def convert(): import PyPDF2 # creating a pdf file object pdfFileObj = open('tax1.pdf', 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pageObj = pdfReader.getPage(0) # extracting text from page print(pageObj.extractText()) # closing the pdf file object pdfFileObj.close() def get_url(): search_url = "https://projects.propublica.org/nonprofits/api/v2/search.json" URL = 'https://projects.propublica.org/nonprofits/api/v2/organizations/:{}.json' name = 'Wal Mart' # "Wal Mart" returns the Wal-Mart foundation # "Walmart" returns WALMART INC ASSOCIATES HEALTH AND WELFARE PLAN PARAMS = {'q': name} # sending get request and saving the response as response object search_result = requests.get(url=search_url, params=PARAMS).json() # Obtain ein number ein = search_result['organizations'][0]['ein'] form = requests.get(url=URL.format(ein), ).json() print(form) # Obtain URL of tax file pdf_url = form['filings_with_data'][0]['pdf_url'] print(pdf_url) # PDF is scanned, not able to parse :( # Another approach would be to download XML files from https://s3.amazonaws.com/irs-form-990/index_2013.json # If pdf is parsable, we convert to text file next # MAIN # p = pdf() # p.convert() # We'll be using artificial data to substitute # Read and convert to csv from tx black_list = ["ACT for America", "Center for Security Policy", "Family Security Matters","Middle East Forum", "Society of Americans for National Existence","Jihad Watch","Foundation for Defense of Democracies", "Global Faith Institute Inc","Conservative Forum of Silicon Valley"] white_list = ["Islamic Relief Canada","Muslim Advocates","Council On American-Islamic Relations", "American-Arab Anti-Discrimination Committee", "Muslim Legal Fund Of America"] output = pd.read_csv(r'C:\Users\nhung\PycharmProjects\salam\company3.txt') output= output.to_csv(r'C:\Users\nhung\PycharmProjects\salam\company3.csv', index=None) with open('company3.csv','r+') as csvinput: writer = csv.writer(csvinput, lineterminator='\n') reader = csv.reader(csvinput) all = [] for row in reader: print(row) if row[0] in black_list: row.append("FALSE") all.append(row) elif row[0] in white_list: row.append("TRUE") all.append(row) csvinput.truncate(0) writer.writerows(all) client = bigquery.Client() table_id = "technica-293603.technica_dataset.technica_table" job_config = bigquery.LoadJobConfig( source_format=bigquery.SourceFormat.CSV, skip_leading_rows=1, autodetect=True, ) with open('company1.csv', "rb") as source_file: job = client.load_table_from_file(source_file, table_id, job_config=job_config) source_file.close() job.result() # Waits for the job to complete. table = client.get_table(table_id) # Make an API request. print( "Loaded {} rows and {} columns to {}".format( table.num_rows, len(table.schema), table_id ) )
bc57deeabb754244531d8c1f808539a32deea385
x0rk/python-projects
/linear-undeterminate-equation.py
431
3.5
4
# Enter the coefficients of the linear indeterminate equation in the following format # ax + by + c = 0 a = int(input("Enter the value of a: ")) b = int(input("Enter the value of b: ")) c = int(input("Enter the value of c: ")) n = int(input("Enter the number of solutions needed: ")) soln = [] x = 0 while n > 0: y = -(a*x+c)/b if y - int(y) == 0: print("\nValue of x: ",x) print("Value of y: ",int(y)) n -= 1 x += 1
6201df60093b11437ff5d8697aa337f679dfbbdc
x0rk/python-projects
/3x+1.py
266
3.875
4
n = int(input("Enter a number: ")) c = 0 n1 = n while n != 1: if n%2 == 0: n/=2 else: n=3*n + 1 print('\n'+n+'\n') g = n1 if n1 > n and else n c+=1 print("Number of Loops: ",c) print("The greatest number attained is {}".format(g))
64fe2091fc3fcec1bcaf73e9c73a1d3a8669965f
x0rk/python-projects
/String_wave.py
343
3.890625
4
from time import sleep str1 = input("Enter a string: ") str1 = str1.upper() #str1 = 'COMPUTER' for i in range(5): index=1 for i in str1: print(str1[:index]) index+=1 sleep(0.1) ind=len(str1)-1 for i in str1: print(str1[:ind]) ind-=1 sleep(0.1)
b6dc25781beab01f24fc77946d4f2dbf36a74d6b
maheshhingane/HackerRank
/Algorithms/Implementation/MinumumSwaps.py
801
3.796875
4
""" https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays """ #!/bin/python3 import math import os import random import re import sys def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] def isSorted(arr): return arr == sorted(arr) def minimumSwaps(arr): swaps = 0 l = len(arr) while not isSorted(arr): for i in range(l): if arr[i] != i+1: swap(arr, i, arr[i]-1) swaps += 1 return swaps if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = list(map(int, input().rstrip().split())) res = minimumSwaps(arr) fptr.write(str(res) + '\n') fptr.close()
6edf756b810736d44def93847adefb86891d1173
maheshhingane/HackerRank
/Algorithms/Implementation/Timeouts/ClimbingTheLeaderboard.py
1,619
3.78125
4
""" https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem """ import sys def find_rank(scores, score, carry): if len(scores) == 0: return carry + 1 mid_index = len(scores) // 2 mid_score = scores[mid_index] if mid_score == score: return carry + mid_index + 1 elif mid_score < score: return find_rank(scores[:mid_index], score, carry) elif mid_score > score: return find_rank(scores[mid_index + 1:], score, carry + mid_index + 1) def climbingLeaderboard(scores, alice_scores): result = [] unique_scores = [] min_score = sys.maxsize max_score = -1 for s in scores: if s not in unique_scores: unique_scores.append(s) if s > max_score: max_score = s if s < min_score: min_score = s total_unique_scores = len(unique_scores) for alice_score in alice_scores: if alice_score < min_score: result.append(total_unique_scores + 1) elif alice_score == min_score: result.append(total_unique_scores) elif alice_score >= max_score: result.append(1) else: alice_rank = find_rank(unique_scores, alice_score, 0) result.append(alice_rank) return result if __name__ == '__main__': scores_count = int(input()) scores = list(map(int, input().rstrip().split())) alice_count = int(input()) alice_scores = list(map(int, input().rstrip().split())) result = climbingLeaderboard(scores, alice_scores) print('\n'.join(map(str, result)))
22e73cc81c0d6b8282d2a87348372e53cbec2082
maheshhingane/HackerRank
/Algorithms/Implementation/2DArray.py
970
3.703125
4
""" https://www.hackerrank.com/challenges/2d-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays """ #!/bin/python3 import math import os import random import re import sys # Complete the hourglassSum function below. def hourglassSum(arr): maxHourGlassSum = 0 for row in range(len(arr)-2): for column in range(len(arr[row])-2): hourGlassSum = arr[row][column] + arr[row][column+1] + arr[row][column+2] + arr[row+1][column+1] + arr[row+2][column] + arr[row+2][column+1] + arr[row+2][column+2] if hourGlassSum > maxHourGlassSum: maxHourGlassSum = hourGlassSum return maxHourGlassSum if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') arr = [] for _ in range(6): arr.append(list(map(int, input().rstrip().split()))) result = hourglassSum(arr) fptr.write(str(result) + '\n') fptr.close()
562650643b326ea605c81912aac9f8c2aea3030d
ozzi7/Hackerrank-Solutions
/Python/Regex and Parsing/validating-uid.py
355
3.5625
4
import re for i in range(int(input())): s = input().strip() m1 = re.search(r'(?=(.*[A-Z]){2})', s) m2 = re.search(r'(?=(.*\d){3})', s) m3 = not re.search(r'[^a-zA-Z0-9]', s) m4 = not re.search(r'(.)(.*\1){1}', s) m5 = (len(s) == 10) if (m1 and m2 and m3 and m4 and m5): print("Valid") else: print("Invalid")
b6460431b2fc27c7dc8ed8708ade77f8fa5457d4
ozzi7/Hackerrank-Solutions
/Algorithms/Implementation/electronics-shop.py
494
3.609375
4
#!/bin/python3 import sys import itertools def getMoneySpent(keyboards, drives, s): l = list(filter(lambda z : z <= s, [x+y for (x,y) in itertools.product(keyboards,drives)])) if(len(l) > 0): return max(l) else: return -1 s,n,m = input().strip().split(' ') s,n,m = [int(s),int(n),int(m)] keyboards = list(map(int, input().strip().split(' '))) drives = list(map(int, input().strip().split(' '))) moneySpent = getMoneySpent(keyboards, drives, s) print(moneySpent)
b5f81b79fc0c990f44822af8bbc8f23a916eeaf8
behrouzan/py-test
/src/001.py
3,264
3.78125
4
import pandas as pd # this is a fucking test comment # nba = pd.read_csv('files/nba_data.csv') # print(type(nba)) # print(len(nba)) # len() is python built-in func # print(nba.shape) # shape is an attribute of DataFrame # The result is a tuple containing the number of rows and columns # print(nba.head) # print(nba.tail) # print(nba.info()) # ================================================= # pandas has int64, float64 and object as data types # there is also categorical data type which is more complicated # object is “a catch-all for columns that Pandas doesn’t recognize as any other specific type.” # In practice, it often means that all of the values in the column are strings. # ================================================= # print(nba.describe()) # print(nba['gameorder'].describe()) # .describe() only analyzes numeric columns by default # but you can provide other data types if you use the include parameter # print(nba.describe(include=np.object)) # above code uses np.object which is now a part of python built in commands # we can use object itself # looks like without 'object' it also works for object columns # print(nba["game_id"].describe(include=object)) # print(nba["game_id"].describe()) # .describe() won’t try to calculate a mean or a standard deviation for the object columns # since they mostly include text stri # print(nba.loc[nba["fran_id"] == "Lakers", "team_id"]) # select on column # print(nba.loc[nba["fran_id"] == "Lakers", ("team_id", "date_game")]) # select multiple column # print(nba.loc[nba["fran_id"] == "Lakers"].value_counts()) # selects all columns # print(nba.loc[nba["team_id"] == "MNL", "date_game"].min()) # print(nba.loc[nba["team_id"] == "MNL", "date_game"].max()) # print(nba.loc[nba["team_id"] == "MNL", "date_game"].agg(("min", "max"))) # pandas Series vs numpy array # pd_arr = pd.Series([3, 4, 5, 6]) # np_arr = np.array([3, 4, 5, 6]) # print(pd_arr) # this is a numpy 2-D array # print(np_arr) # print(pd_arr.values) # this is a numpy array # print(pd_arr.index) # the values of a Series object are actually n-dimensional arrays # pandas uses numpy behind the scenes # a pandas Series has both abilities in indexing ==>> by numeric index is default # series1 = pd.Series([1, 2, 3, 4], index=["one", "two", "three", "four"]) # print(series1[1]) # print(series1["two"]) # creating pandas series using python dictionary # series2 = pd.Series({"Amsterdam": 5, "Tokyo": 8}) # ere we can pass a dictionary # print(series2["Tokyo"]) # print(series2[0]) # we can use dictionary functions in series # print(series2.keys()) # print("Tokyo" in series2) # combine Series to create DataFrame city_employee_count = pd.Series({"Amsterdam": 5, "Tokyo": 8, "Shiraz": 12}) city_revenues = pd.Series([4200, 8000, 6500], index=["Amsterdam", "Toronto", "Tokyo"]) city_data = pd.DataFrame({"revenue": city_revenues, "employee_count": city_employee_count}) print(city_data) print(city_employee_count.index) # index for Series print(city_data.index) # index for dataFrame print(city_data.values) print(city_data.axes) # get axes of a Data Frame print(city_data.axes[0]) print(city_data.axes[1]) print(city_revenues.axes) # these are numpy ==>> get axes of a Series
451052f0b6fda97fb3119e1bdca69f9d7fff6957
dkhachatrian/openmplab
/quick_stats.py
958
3.84375
4
import re import sys #recognize command line args import __future__ #in case using Python 2 def main(): """ Takes in input string of file in current directory. Calculates average numbers and appends to end of file. """ if len(sys.argv) != 2: print("Not the correct number of arguments!") return f_string = sys.argv[1] with open(f_string, 'r+') as inf: f_sum = 0 t_sum = 0 i = 0 for line in inf: line = re.sub(r'\s', r'', line) parts = line.split(':') # how it's formatted num = float(parts[-1]) if parts[0] == 'FUNCTIME': i+=1 f_sum += num elif parts[0] == 'TOTALTIME': t_sum += num f_ave, t_ave = f_sum/i, t_sum/i inf.seek(0,2) #be at end of file inf.write('\n') inf.write("Number of iterations: {0}\n".format(i)) inf.write("Average for FUNC TIME: {0}\n".format(f_ave)) inf.write("Average for TOTAL TIME: {0}".format(t_ave)) print("Statistics appended to {0}".format(f_string)) return main()
820abce4f9d2ca4f8435512d9ad69873abb106b3
Vani-start/python-learning
/while.py
553
4.28125
4
#while executes until condition becomes true x=1 while x <= 10 : print(x) x=x+1 else: print("when condition failes") #While true: # do something #else: # Condifion failed #While / While Else loops - a while loop executes as long as an user-specified condition is evaluated as True; the "else" clause is optional #x = 1 #while x <= 10: # print(x) #x += 1 #else: # print("Out of the while loop. x is now greater than 10") #result of the above "while" block #1 2 3 4 5 6 7 8 9 10 #Out of the while loop. x is now greater than 10
276371d9a0d71eaaa40a582f4a55c9a7e15d220f
Vani-start/python-learning
/bubble.py
295
4.03125
4
def BubbleSort(arr): n=len(arr) for i in range(n): print(i) for j in range(0,n-i-1): print(j) print(range(0,n-i-1)) print(arr) if arr[j]>arr[j+1]: temp=arr[j] arr[j]=arr[j+1] arr[j+1]=temp print(arr) arr=[21,12,34,67,13,9] BubbleSort(arr) print(arr)
495429537628e1b51b144775abb34d060034ac20
Vani-start/python-learning
/convertdatatype.py
980
4.125
4
#Convet one datatype into otehr int1=5 float1=5.5 int2=str(int1) print(type(int1)) print(type(int2)) str1="78" str2=int(str1) print(type(str1)) print(type(str2)) str3=float(str1) print(type(str3)) ###Covert tuple to list tup1=(1,2,3) list1=list(tup1) print(list1) print(tup1) set1=set(list1) print(set1) ####bin, dec,hex number=10 num_to_bin=bin(number) print(num_to_bin) num_to_hex=hex(number) print(num_to_hex) num_from_bin=int(num_to_bin,2) print(num_from_bin) num_from_hex=int(num_to_hex,16) print(num_from_hex) #Conversions between data types #str() #converting to a string #int() #converting to an integer #float() #converting to a float #list() #converting to a list #tuple() #converting to a tuple #set() #converting to a set #bin() #converting to a binary representation #hex() #converting to a hexadecimal representation #int(variable, 2) #converting from binary back to decimal #int(variable, 16) #converting from hexadecimal back to decimal
1ce19d5cb26da9746196f25e75b1e160882ecdfb
mozshen/FundammentalsOfProgramming2020
/Set2/S2Q5/S2Q5.py
314
3.9375
4
n = int(input()) isPrime = True for i in range(2, n): if n % i == 0: isPrime = False break if n == 1: isPrime = False if isPrime: print('*' * n) for i in range(n - 2): print('*' + (' ' * (n - 2)) + '*') print('*' * n) else: for i in range(n): print('*' * n)
ad2a60dc45edb022f18621011eb951d489e5eb3b
PND22/PND69
/PND69/studentclass.py
2,050
3.75
4
#studentclass.py class Student: def __init__(self,name): self.name = name self.exp = 0 self.lesson = 0 #Call function #self.AddExp(10) def Hello(self): print('สวัสดีจร้าาาาาาา เราชื่อ{}'.format(self.name)) def Coding(self): print('{}: กำลังเขียน coding ..'.format(self.name)) self.exp += 5 self.lesson += 1 def Showexp(self): print('- {} มีประสบการณ์ {} exp'.format(self.name,self.exp)) print('- เรียนไป {} ครั้งแล้ว'.format(self.lesson)) def AddExp(self, score): self.exp += score # self.exp = self.exp + score self.lesson += 1 class SpecialStudent(Student): def __init__(self,name,father): super().__init__(name) self.father = father mafia = ['Big Tuu','Big Pom'] if father in mafia: self.exp += 100 def AddExp(self,score): self.exp += (score * 3) self.lesson +=1 def AskEXP(self,score=10): print('ครู!! ขอคะแนนพิเศษให้ผมหน่อยสิสัก {} EXP'.format(score)) self.AddExp(score) if __name__ == '__main__': print('=======1 Jan =======') student0 = SpecialStudent('Uncle Phol','Big Tuu') student0.AskEXP() student0.Showexp() student1 = PND69('pepper') print(student1.name) student1.Hello() print('----------') student2 = PND69('tukta') print(student2.name) student2.Hello() print('=======2 Jan =======') print('----ใครอยากเรียน coding บ้าง---(10 exp)---') student1.AddExp(10) # student1.exp = student1.exp + 10 print('=======3 Jan =======') student1.name = 'pepper ch' print('ตอนนี้ exp ของแต่ล่ะคนได้เท่าไรกันแล้ว') print(student1.name, student1.exp) print(student2.name, student2.exp) print('=======4 Jan =======') for i in range (5): student1.Coding() student1.Showexp() student2.Showexp()
133c52aa66c9f8570d39762fd3d48a1ae40921aa
miriban/data-structure
/BFS.py
1,716
3.921875
4
""" Breadth First Search Implementation We are implementing an indirect Graph """ class Graph: verticies = {} def addVertex(self,v): if v not in self.verticies: self.verticies[v] = [] def addEdge(self,u,v): if u in self.verticies and v in self.verticies: self.verticies[u].append(v) self.verticies[v].append(u) def BFS(self,s): level = {s:0} # setting the level of starting vertex to 0 parent = {s:None} # setting the starting vertex parent to be None frontier = [s] i = 1 # because we have set the frontier that we are visiting in level 0 while frontier: next = [] for u in frontier: for v in self.verticies[u]: if v not in level: level[v] = i parent[v] = u next.append(v) frontier = next i = i + 1 # We reach the end of BFS return parent def printShortestPath(self,parent,s,v): if v == s: print s return print v self.printShortestPath(parent,s,parent[v]) def printGraph(self): for u in self.verticies: print u," => ", self.verticies[u] # Testing g = Graph() g.addVertex("s") g.addVertex("a") g.addVertex("x") g.addVertex("z") g.addVertex("d") g.addVertex("c") g.addVertex("f") g.addVertex("v") g.addEdge("s","a") g.addEdge("s","x") g.addEdge("a","z") g.addEdge("x","d") g.addEdge("x","c") g.addEdge("d","f") g.addEdge("d","c") g.addEdge("c","f") g.addEdge("c","v") parents = g.BFS("z") g.printShortestPath(parents,"z","v") #g.printGraph()
876792dac3431422495d8b71eb97b5faf662f201
risabhmishra/parking_management_system
/Models/Vehicle.py
931
4.34375
4
class Vehicle: """ Vehicle Class acts as a parent base class for all types of vehicles, for instance in our case it is Car Class. It contains a constructor method to set the registration number of the vehicle to registration_number attribute of the class and a get method to return the value stored in registration_number attribute of the class. """ def __init__(self, registration_number): """ This constructor method is used to store the registration number of the vehicle to registration_number attribute of the class. :param registration_number: str """ self.registration_number = registration_number def get_registration_number(self): """ This method is used to return the value stored in the registration_number attribute of the class. :return: registration_number:str """ return self.registration_number
1e8c82926310308f2bee8e88db6f8cd8d37fdee2
MdAbuZehadAntu/MachineLearning
/Regression/SimpleLinearRegression/SimpleLinearRegression.py
841
3.796875
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset=pd.read_csv("Salary_Data.csv") X=dataset.iloc[:,:-1].values y=dataset.to_numpy()[:,-1] from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0) from sklearn.linear_model import LinearRegression linreg=LinearRegression() linreg.fit(X_train,y_train) y_pred=linreg.predict(X_test) # print(y_pred.shape) # print(y_test.shape) diff=y_pred-y_test print(diff.shape) # quit() diff=diff.reshape(diff.shape[0],1) print(diff) print() print(linreg.predict([[7.5]])[0]) # plt.scatter(X_train,y_train,color="blue") plt.plot(X_train,linreg.predict(X_train),color="red") plt.show() plt.scatter(X_test,y_test,color="black") plt.plot(X_test,linreg.predict(X_test),color="red") plt.show()
68942d5915f9c4e3817d4148908a3973d7e74b23
ryanwolters/pythonpdftools
/PDF Reverser.py
510
3.828125
4
import PyPDF2 as pp sourceName = input("Name of the file you want to reverse (without .pdf): ") sourceObj = open(sourceName + '.pdf','rb') pdfReader = pp.PdfFileReader(sourceObj) pdfWriter = pp.PdfFileWriter() numPages = pdfReader.getNumPages() for x in range(numPages): page = pdfReader.getPage((numPages - 1) - x) pdfWriter.addPage(page) newObj = open(sourceName + ' backwards.pdf','wb') pdfWriter.write(newObj) newObj.close() sourceObj.close() input("Press enter to close ")
4599ac546c4b04f6ea4fe36cfd32a64db8922756
MasterOfBrainstorming/Python2.7
/Simple_FTP_Client_Server/server.py
6,971
3.546875
4
import os import sys import socket import logging #if len(sys.argv) < 2: # print "Usage: python ftp_server.py localhost, port" # sys.exit(1) logging.basicConfig(filename="server_log.txt",level=logging.DEBUG) methods = [ "LIST", "LISTRESPONSE", "DOWNLOAD", "FILE", "ERROR" ] class FOLDER_ERROR(Exception): pass #FOLDER ERROR RESPONSE CODE IS 1 class PARAMETER_ERROR(Exception): pass #PARAMETER ERROR RESPONSE CODE IS 2 class FILE_ERROR(Exception): pass #PARAMETER ERROR RESPONSE CODE IS 3 class FTP_ERROR(Exception): pass def list_response(request): if len(request[0]) == 1: print "Request is error:", request return request logging.info(request) else: print "LIST RESPONSE", request logging.warning(request) lenght = 0 for r in request: x = len(r) lenght+=x items = len(request) body = request item_list = "\r\n".join(request) response = "%s %s %s\r\n%s" % ("LISTRESPONSE", lenght, items, item_list) return response logging.info(response) def parse_list_request(request): parts = request.split(" ") if parts[2] == ".": server_list = os.listdir(os.getcwd()) return server_list print "Server list: ", server_list elif parts[2] != ".": try: search_folder(parts[2]) return search_folder(parts[2]) except Exception as e: print e for x in e: if "1" in x: return "1" elif "2" in x: return "2" elif "3" in x: return "3" else: return "ERROR" #return search_folder(parts[2]) def search_folder(folder): folder_list = os.listdir(os.getcwd()) print folder if folder not in folder_list: raise FOLDER_ERROR("1: Listing folder contents error, folder not found") else: lista = os.listdir(folder) return lista def get_file_contents(file): print "Get file contents",file f = open(file, "r") body = "" for j in f: body+=j body+="\n" size = len(j) return body, size def parse_download_request(request): parts = request.split(" ") file = parts[2] print parts #valid_file = search_file(file) try: search_file(file) file_contents = get_file_contents(file) file_lenght = file_contents[1] file_contents_to_string = "%s" % (file_contents[0]) response = "%s %s %s %s %s %s" % ("FILE", str(file_lenght), search_file(file),"\r\n", file_contents_to_string,"\n") return response except Exception as e: for x in e: if "1" in x: return "1" elif "2" in x: return "2" elif "3" in x: return "3" else: return "ERROR" logging.warning(e) #return e def find_from_folder(line): items = line.split("/") directory = items[0] file = items[1] print "Dir:", directory, "File:", file if directory not in os.listdir(os.getcwd()): raise FOLDER_ERROR("1: Folder not found or it is a file") return 1 elif "." not in file: raise PARAMETER_ERROR("2: Given parameter is a folder, cannot download") return 2 elif file not in os.listdir(directory): raise FILE_ERROR("3: File not found") return 3 else: return file def find_file(line): if line not in os.listdir(os.getcwd()): raise FILE_ERROR("3: File not found") return 3 elif "." not in line: raise PARAMETER_ERROR("2: Given parameter is a folder") return 2 else: return line def search_file(line): if "/" in line: fff = find_from_folder(line) return fff else: ff = find_file(line) return ff def check_validation(line): parts = line.split(" ") if parts[0] not in methods: raise FTP_ERROR("Not a valid FTP method") elif len(parts) < 3 or len(parts) !=3: raise FTP_ERROR("request lenght not valid") elif int(parts[1]) !=0: close_connection() raise FTP_ERROR("non-zero body lenght") status = True return line, status def parse_request(request): try: check_validation(request) code = check_validation(request)[1] except Exception, e: print e #check = check_validation(request) #code = check[1] parts = request.split(" ") method = parts[0] if method == "LIST" and code == True: lista = parse_list_request(request) print "parsen palautus:", lista response = list_response(lista) return response elif method == "DOWNLOAD" and code == True: down = parse_download_request(request) return down def ftp_server(): #host = sys.argv[1] #port = int(sys.argv[2]) host = "localhost" port = 1222 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: server.bind((host, port)) server.listen(5) print "Listening on port", port, "@", host except Exception, e: print e (client, addr) = server.accept() request = client.recv(1024) while request != "": print addr, "Requested", request response = parse_request(request) logging.info(response) print "Response to", addr, "is:",response client.send(str(response)) request = "" server.close() while True: ftp_server()
32f0ac37600331beea535f75ea72f357d60f372c
jiangjunjie/study
/ahoCorasick/python/AhoCorasick.py
4,271
3.546875
4
#!/usr/bin/env python #coding=gbk ''' hashmapʵACԶ֧Ϊunicodeõƥ䵥pattern ''' import sys import time class Node(): def __init__(self): self.word = None self.fail = None self.end = False self.next = {} class AhoCorasick(): def __init__(self): self.root = Node() def insert(self, word): ''' query ''' word = word.strip() ## մ if not word: return p = self.root ## pָroot for w in word: ## ѭÿ if w in p.next: ## Ѳָ p = p.next[w] else: ## ½ڵ㣬ָ½ڵ q = Node() ##½ڵ p.next[w] = q p = q p.word = word ## еʶ˽㣬ĩ㴦дwordend p.end = True def fix(self): ''' failָ ''' self.root.fail = None queue = [self.root] ## ȱָ while len(queue) != 0: parent = queue[0] queue.pop(0) ## for w in parent.next: ## ÿ child = parent.next[w] failp = parent.fail while failp != None: if w in failp.next: ## Ҹfailָ룬Ƿеǰӣָ򼴿 child.fail = failp.next[w] break failp = failp.fail ## 򲻶Ҹfailָ if failp == None: ## ָroot˵޷ҵǰӵfailָroot child.fail = self.root queue.append(child) ## Уȴ def search(self, word): ''' ƥӴ ''' result = [] p = self.root ## Ӹ㿪ʼ for i, w in enumerate(word): ## ָ벻ǰ while p != None and not w in p.next: ## ǰ㲻ڸõʣfailָǷڸõ p = p.fail if p == None: ## ݹrootڵˣ˵ûҵpָroot p = self.root else: ## ˵ҵˣpָΪõʵĽ p = p.next[w] q = p ## жϸõʽ㼰һfailǷijpatternĩβ while q != None: if q.end: ## ǣظģʽɼģʽеͷβλ result.append(((i + 1 - len(q.word), i + 1), q.word)) q = q.fail ## Ѱfail㣬ֱݹroot return result def main(): aho = AhoCorasick() patternLst = [u'', u'', u''] ms = u'첥' for pattern in patternLst: aho.insert(pattern) aho.fix() for pos, word in aho.search(ms): print pos, word.encode('gbk') '''t1 = time.time() aho = AhoCorasick() for i, line in enumerate(sys.stdin): if i % 10000 == 0: print >> sys.stderr, i line = line.strip() aho.insert(line.decode('gbk', 'ignore')) t2 = time.time() print >> sys.stderr, 'insert time: %f' % (t2 - t1) aho.fix() t3 = time.time() print >> sys.stderr, 'build fail time: %f' % (t2 - t1) testLst = [] fin = open(sys.argv[1]) for i, line in enumerate(fin): line = line.strip() testLst.append(line.decode('gbk', 'ignore')) if i > 100000: break fin.close() t4 = time.time() for line in testLst: for pos, word in aho.search(line): print pos, word.encode('gbk', 'ignore') print '==================' t5 = time.time() print >> sys.stderr, 'search time: %f' % (t5 - t4) print >> sys.stderr, 'search ave time: %f' % ((t5 - t4) * 1.0 / len(testLst)) print >> sys.stderr, 'will exit!''' if __name__ == "__main__": main()
314bf18bb3b34897553034e709cdeb76387ce6ce
shantanu609/BFS-1
/Problem1.py
1,556
3.8125
4
# Time Complexity : O(n) # Space Complexity : O(h) Space | O(n) worst case. # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach class Node: def __init__(self,x): self.val = x self.left = None self.right = None class Solution: result = None def levelOrder(self,root): self.result = [] if not root: return self.result self.dfs(root,0) return self.result # def bfs(self,root): # q = [root] # while q: # size = len(q) # temp = [] # for _ in range(size): # node = q.pop(0) # if node.left: # q.append(node.left) # if node.right: # q.append(node.right) # temp.append(node.val) # self.result.append(temp) # return self.result def dfs(self,root,level): # edge case if not root: return # Logic if len(self.result) == level: temp = [] self.result.append(temp) self.result[level].append(root.val) self.dfs(root.left,level+1) self.dfs(root.right,level+1) if __name__ == "__main__": s = Solution() n = Node(3) n.left = Node(9) n.right = Node(20) n.right.left = Node(15) n.right.right = Node(7) res = s.levelOrder(n) print(res)
4f0436db5cb69c1f7cfa05baf51f38259d49918b
david8z/project_euler_problems
/problem2.py
917
4.0625
4
""" Link: https://projecteuler.net/problem=2 Author: David Alarcón Segarra ---------------------------------------- Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ import itertools def fibonacci(n): if(n<2): return n else: return fibonacci(n-1) + fibonacci(n-2) # The fibonacci numbers that give positive results are the following # 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48... # I've noticed that they follow a sequence of +3 so we can use this to make it # more efficient. res = 0 for i in itertools.count(): aux = fibonacci(i*3) if( aux > 4000000): break else: res += aux print (res)
27e8ec33ff0f380bf54428032445ab8905d3164f
detjensrobert/cs325-group-projects
/ga1/assignment1.py
2,273
4.40625
4
""" This file contains the template for Assignment1. You should fill the function <majority_party_size>. The function, recieves two inputs: (1) n: the number of delegates in the room, and (2) same_party(int, int): a function that can be used to check if two members are in the same party. Your algorithm in the end should return the size of the largest party, assuming it is larger than n/2. I will use <python3> to run this code. """ def majority_party_size(n, same_party): """ n (int): number of people in the room. same_party (func(int, int)): This function determines if two delegates belong to the same party. same_party(i,j) is True if i, j belong to the same party (in particular, if i = j), False, otherwise. return: The number of delegates in the majority party. You can assume more than half of the delegates belong to the same party. """ return majority_party_size_helper([i for i in range(n)], same_party)[1] def majority_party_size_helper(delegates, same_party): # PARAM: delegates[] = indexes of delegates to check # RETURN: tuple(index of majority party candidate, size of majority party) if len(delegates) >= 2: # recursively check each half of our delegate list to find the majority party of each half mid = int(len(delegates) / 2) (left_delegate, _) = majority_party_size_helper(delegates[:mid], same_party) (right_delegate, _) = majority_party_size_helper(delegates[mid:], same_party) # Count up the size of each half's majority party for the whole chunk left_party_size = 0 right_party_size = 0 for i in delegates: if same_party(left_delegate, i): left_party_size += 1 if same_party(left_delegate, i): right_party_size += 1 # who's bigger? if left_party_size > right_party_size: maj_delegate = left_delegate maj_size = left_party_size else: maj_delegate = right_delegate maj_size = right_party_size return (maj_delegate, maj_size) else: # Base case: single delegate -- only one possible majority here! return (delegates[0], 1)
58e59338d5d1fc79374d0ce438582c4d73185949
Neethu-Mohan/python-project
/projects/create_dictionary.py
1,091
4.15625
4
""" This program receives two lists of different lengths. The first contains keys, and the second contains values. And the program creates a dictionary from these keys and values. If the key did not have enough values, the dictionary will have the value None. If Values that did not have enough keys will be ignored. """ from itertools import chain, repeat keys = [] def get_list(): keys = [item for item in input("Enter the first list items : ").split()] values = [item for item in input("Enter the second list items : ").split()] dictionary_ouput = create_dictionary(keys, values) print(dictionary_ouput) def create_dictionary(keys, values): difference = compare_length(keys, values) if difference <= 0: dic_value = dict(zip(keys, values)) return dic_value elif difference > 0: dic_value = dict(zip(keys, chain(values, repeat(None)))) return dic_value def compare_length(keys, values): difference = check_length(keys) - check_length(values) return difference def check_length(item): return len(item)
354a3b788af8b631b14b0389896dbb3a47e0a36d
SayedBhuyan/learning-python
/list.py
999
4.03125
4
presents = ["Sayed", "Tareq", "Sultan", "Hassan", "Alim", "Sohel", 'Rakib'] # came on time presents.append("Muhammad") # coming late presents.sort() # presents.reverse() presents.insert(0, "Teacher") # teacher came and set before everyone else # presents.pop(-2) # presents.remove("Teacher") # teacher or anyone can leave libraryPresents = presents.copy() # students moved to library libraryPresents.append("Abdul") # abdul also joined in library libraryPresents.append("Hassan") # two students same name in the same class print("Library Presents", libraryPresents) print(libraryPresents.index("Rakib")) # check the position of a student in class print(libraryPresents.count("Hassan")) presents.clear() # class finish print(presents) print(len(presents)) # print((presents + ['|']) * 3) #print(students[2:]) # print(students[-1]) # isPresent = input("Who you wan't to call in class?") # print(isPresent in presents) '''i = 0; while i < 4: print(students[i]) i = i+1'''
8d7f256e42b25c9e70abb0d9a8f96ddddf15cce1
SayedBhuyan/learning-python
/userInput.py
230
3.71875
4
name = input("Enter student name: ") age = input("Enter student age: ") gpa = input("Enter student GPA: ") print("Student Information") print("-------------------") print("Name: " + name) print("Age: " + age) print("GPA: " + gpa)
a99612c8ed99a9d0596c7a9f342e8831c21d0b63
SayedBhuyan/learning-python
/if else.py
781
4.1875
4
#mark = int(input("Enter Mark: ")) # if else mark = 85 if mark >= 80: print("A+") elif mark >= 70: print("A") elif mark >= 60: print("A-") elif mark >= 50: print("B+") elif mark >= 40: print("B") elif mark >= 33: print("B-") else: print("Fail") ''' if (mark % 2) == 0: print("Even") else : print("Odd") ''' # nested if statement if 5 > 2: if 7 > 2: print("good") else: print("Not matched") else : print("Not a even") num1 = int(input("Enter first number")) num2 = int(input("Enter second number")) num3 = int(input("Enter third number")) if num1 > num2: if num1 > num3: print(num1) else: print(num3) else: if num2 > num3: print(num2) else : print(num3)
d6745c80fffeaf847daffb8c6ead53f2bec67b9c
SayedBhuyan/learning-python
/some range math.py
130
4.125
4
# Factorial n! n = int(input("Enter factorial number: ")) sum = 1 for x in range(1, n + 1, 1) : sum = sum * x print(sum)
488675687a2660c01e9fd7d707bdf212f94abb62
NM20XX/Python-Data-Visualization
/Simple_line_graph_squares.py
576
4.34375
4
#Plotting a simple line graph #Python 3.7.0 #matplotlib is a tool, mathematical plotting library #pyplot is a module #pip install matplotlib import matplotlib.pyplot as plt input_values = [1,2,3,4,5] squares = [1,4,9,16,25] plt.plot(input_values, squares, linewidth = 5) #linewidth controls the thickness of the line that plot() generates. #Title and label axes plt.title("Square Numbers", fontsize = 24) plt.xlabel("Value", fontsize = 14) plt.ylabel("Square of value", fontsize = 14) #Set size of tick labels plt.tick_params(axis ='both', labelsize = 14) plt.show()
83b59d267f64a9ea622498ffa254021848763bb2
R1gp4/LearnX
/6001x/ansguess.py
792
4.09375
4
print("Please think of a number between 0 and 100!") high = 100 low = 0 num_guesses = 0 flag = True while flag == True: guess = (high + low)/2.0 print('Is your secret number', int(guess), ' ?') print("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ",end='') answer = input() answer = str(answer) if answer == 'h': high = (high + low)/ 2.0 num_guesses += 1 if answer == 'l': low = (high + low)/2.0 num_guesses += 1 if answer == 'c': print("Game over. Your secret number was:", int(guess)) break else: #answer != 'c' or 'l' or 'h': print("Sorry, I did not understand your input.")
2bfe26f13d9f1d92ea90d94a379ac0d805b342e2
saelbakr/python-challenge
/PyFinances/main.py
2,280
3.609375
4
import os import csv csvpath = os.path.join("Finances.csv") Date = [] Profits_Losses = [] with open(csvpath, encoding="utf8") as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: Date.append(row[1]) Profits_Losses.append(int(row[0])) ## Sum of all the Profits/Losses in the file: total = sum(Profits_Losses) #print(f' ${sum(Profits_Losses)}') ## Total of all the months included in the file: Month_Year = (list(set(Date))) total_months = len(Month_Year) #print(total_months) #print(range(len(Profits_Losses))) total_diff = 0 range_of_differences = [] for i in range(len(Profits_Losses)-1): #print(i) diff = Profits_Losses[i+1]-Profits_Losses[i] total_diff = total_diff + diff range_of_differences.append(diff) ## Here I am finding the Max and Min of the range in differences and using their indexes locate there dates' locations: ##Index of the max and min first index_increase = range_of_differences.index(max(range_of_differences)) index_decrease = range_of_differences.index(min(range_of_differences)) ## Corresponding name with each value found prior: Greatest_Decrease_In_Profits = Date[index_decrease+1] Greatest_Increase_In_Profits = Date[index_increase+1] #print(range_of_differences) average_change = total_diff/(len(Profits_Losses)-1) #print(round(average_change,2)) ## Now to add all of these values into their own csv file with titles, etc. output_path = os.path.join("Financial_Analysis_Summary.csv") with open(output_path, 'w') as datafile: # Initialize csv.writer csvwriter = csv.writer(datafile, delimiter=",") csvwriter.writerow(["FINANCIAL ANALYSIS:"]) csvwriter.writerow(["-----------------------------------------------"]) csvwriter.writerow(["TOTAL MONTHS: "f'${total_months}']) csvwriter.writerow(["TOTAL AMOUNT OF PROFITS/LOSSES: "f'${total}']) csvwriter.writerow(["AVERAGE CHANGE: "f'${round(average_change,2)}']) csvwriter.writerow(["GREATEST INCREASE IN PROFITS: "f'{Greatest_Increase_In_Profits} (${max(range_of_differences)})']) csvwriter.writerow(["GREATEST DECREASE IN PROFITS: "f'{Greatest_Decrease_In_Profits} (${min(range_of_differences)})'])
74afc1b709da9c42b3b44766dc6738baefa692b2
tanker0212/dailyCoding
/src/dc_181112/Solution.py
887
3.53125
4
NUM_LEN = 3; def solution(baseball): answer = 0 for i in range(123, 988): if dup_check(i): point = 0 for guess in baseball: if (guess[1], guess[2]) == point_check(i, guess[0]): point += 1 if point == len(baseball): answer += 1; return answer def point_check(answer, guess): strike , ball= 0, 0; answer = str(answer) guess = str(guess) for i in range(NUM_LEN): for j in range(NUM_LEN): if answer[i] == guess[j]: if i == j: strike += 1 else: ball += 1 return strike, ball def dup_check(num): a = int(num%10) b = int((num/10)%10) c = int(num/100) if a == b or a == c or b == c or a == 0 or b == 0 or c == 0: return 0 else: return 1
35af5afe90a21ccac83503ccd6dd7cfa7fa4889f
josue-avila/OTS-ATP1
/products.py
9,049
3.875
4
import os from categories import Categories class Product: name: str description: str price: float weigth: float length: float heigth: float width: float list_products: list = [] list_product: list = ['','',''] categories: list = [] def menu(self) -> int: print('') print("MENU DE PRODUTOS:") print('') print('1 - Adicionar novo produto') print('2 - Ver produtos cadastrados') print('3 - Editar produto') print('4 - Deletar produto') print('0 - Sair') print('') self.option = int(input('Digite a opção escolhida (use os números): -> ')) return self.option def add(self): name= input("Digite o nome do novo produto: ") c = Categories() if any(name in list for list in self.list_products): print('') print('O PRODUTO JÁ EXISTE!') print('') pass else: self.categories = [] categorie =[] while categorie != '0': print('') print('Selecione as categorias à que o novo produto pertence:') print('') for j in c.categories: for i in range(len(j)): if i == 0: print('') print(j[i]) else: print(' '+str(j[i])) categorie = input('Escreva uma de cada vez e quando estiver pronto digite 0 (zero) -> ') if any(categorie in list for list in c.categories): self.categories.append(categorie) elif categorie == '0': pass else: print('') print('CATEGORIA NÃO CADASTRADA') print('') pass description = input("Inclua uma breve descrição: ") while len(description) < 20: print('A decrição deve ter pelo menos 20 caracteres!') description = input("Inclua uma breve descrição: ") try: price = float(input("Adicione o preço (em R$): ")) while price <=0: price = float(input("O valor precisa ser maior que zero. Digite o valor: ")) except ValueError as err: print("O valor adicionadno é inválido, é preciso usar números") else: try: weigth = float(input("Adicione o peso do produto (em Kg): ")) print("O valor adicionadno é inválido, é preciso usar números") print('') print("DIMENSÕES - Entre com as medidas do novo produto (em centímetros) ") length = float(input("Comprimento: ")) height = float(input("Altura: ")) width = float(input("Largura: ")) dimensions = [length, height ,width] self.list_product = [name,description,price, weigth, dimensions, self.categories] self.list_products.append(self.list_product) print('PRODUTO ADICIONADO!') print('') pass except ValueError as err: print('') print("O valor adicionadno é inválido.É preciso usar números nos campos: PREÇO, PESEO, E DIMENSÕES") def get_products(self): print('') print('LISTA DE PRODUTOS: ') for i in range(len(self.list_products)): print('') for j in range(6): if j == 0: print(str(i + 1) +' - Nome: ', self.list_products[i][j]) elif j == 1: print(' Descrição: ', self.list_products[i][j]) elif j == 2: print(' Preço: R$ ' + str(self.list_products[i][j])) elif j == 3: print(' Peso: ' + str(self.list_products[i][j])+"Kg") elif j == 4: print(' Dimensões: ' + str(self.list_products[i][j][0])+'cm x '+str(self.list_products[i][j][1]) +'cm x '+str(self.list_products[i][j][2])+'cm' ) else: print('') print(' Categorias: ') print(' '+' '.join(self.list_products[i][j])) print('') def delete(self): print('') element = input('Digite o nome do produto que deseja excluir: ') if any(element in list for list in self.list_products): index = [i for i, j in enumerate(self.list_products) if element in j][0] self.list_products.pop(index) self.categories.pop(index) print('') print('ITEM EXCLUIDO!') print('') pass else: print('') print('PRODUTO NÃO CADASTRADO!') print('') def edit_products(self): c = Categories() print('') element = input('Digite o nome do produto que deseja editar: ') if any(element in list for list in self.list_products): index = [i for i, j in enumerate(self.list_products) if element in j][0] index1 = self.list_products[index].index(element) name = input('Digite o novo nome do produto: ') if name == '': pass else: if any(name in list for list in self.list_products): print('') print('PRODUTO JÁ EXISTE!') print('') pass else: self.list_products[index][index1] = name pass categorie = [] while categorie != '0': print('') print('Selecione as novas categorias à que esse produto pertence:') print('') for j in c.categories: for i in range(len(j)): if i == 0: print('') print(j[i]) else: print(' '+str(j[i])) categorie = input('Escreva uma de cada vez e quando estiver pronto digite 0 (zero) -> ') if any(categorie in list for list in c.categories): self.categories.append(categorie) elif categorie == '0': pass else: print('') print('CATEGORIA NÃO CADASTRADA') print('') pass description = input('Digite a nova descrição do produto: ') if description == '': pass else: while len(description) < 20: print('A decrição deve ter pelo menos 20 caracteres!') description = input("Inclua uma breve descrição: ") self.list_products[index][index1+1] = description pass price = input('Digite o novo preço do produto: ') if price == '': pass else: self.list_products[index][index1+2] = price pass weigth = input('Digite o novo peso do produto: ') if weigth == '': pass else: self.list_products[index][index1+3] = weigth pass length = input('Digite o novo comprimento do seu produto: ') if length == '': pass else: self.list_products[index][index1+4][0] = length pass heigth = input('Digite a nova altura do produto: ') if heigth== '': pass else: self.list_products[index][index1+4][1] = heigth pass weigth = input('Digite a nova altura do produto: ') if weigth == '': pass else: self.list_products[index][index1+4][2] = weigth pass else: print('') print('PRODUTO NÃO CADASTRADO!') print('')
b83f8959434d6ad11c371a680a742e0f394c0c8a
Patrick5455/InterviewPractice
/leetCode/PythonSolutions/27.py
195
3.6875
4
def removeElement(nums, val): """ :type nums: List[int] :type val: int :rtype: int """ m_set = set(nums) return len(m_set) test = [3,3] print(removeElement(test, 3))
a9b49b0f5fa13d3392bdbaefb26416a028adf5e9
Patrick5455/InterviewPractice
/leetCode/PythonSolutions/temp.py
2,294
3.515625
4
class Solution: def spiralOrder(self, matrix): if matrix is None or len(matrix) == 0: return [] else: self.m = matrix curDir = "right" visited = [[False for i in range(len(matrix[0]))] for j in range(len(matrix))] totalCell = 0 for r in matrix: for cell in r: totalCell += 1 r = 0 c = 0 visitedCount = 0 result = [] while visitedCount < totalCell: if visitedCount == totalCell - 1 and not visited[r][c]: result.append(matrix[r][c]) return result if curDir == "right": if (not self.inBounds(r, c + 1)) or visited[r][c + 1]: curDir = "down" else: result.append(matrix[r][c]) visited[r][c] = True c += 1 visitedCount += 1 elif curDir == "down": if (not self.inBounds(r + 1, c)) or visited[r + 1][c]: curDir = "left" else: result.append(matrix[r][c]) visited[r][c] = True r += 1 visitedCount += 1 elif curDir == "left": if (not self.inBounds(r, c - 1)) or visited[r][c - 1]: curDir = "up" else: result.append(matrix[r][c]) visited[r][c] = True c -= 1 visitedCount += 1 elif curDir == "up": if (not self.inBounds(r - 1, c)) or visited[r - 1][c]: curDir = "right" else: result.append(matrix[r][c]) visited[r][c] = True r -= 1 visitedCount += 1 else: return result return result def inBounds(self, r, c): if r < 0 or c < 0: return False if r >= len(self.m): return False if c >= len(self.m[0]): return False return True if __name__ == '__main__': s = Solution() print(s.spiralOrder([[1,2,3],[4,5,6],[7,8,9]]))
e5d0634de86cac0cd99e2f395b85327c441f907f
Patrick5455/InterviewPractice
/leetCode/PythonSolutions/BasicIO.py
1,039
3.65625
4
def file_io(): r_text = open("wuhao4u.txt", 'r') for line in r_text: print(line) r_text.close() with open("wuhao4u.txt", 'r') as r_file: with open("test.txt", 'w') as w_file: for line in r_file: w_file.write(line.strip()) def console_io(): m_str = input() print(m_str) def console_multiple_lines(): print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.") contents = [] while True: try: line = input() except EOFError: print(' '.join(contents)) break contents.append(line) def split_string(m_str): print(m_str.split()) print(m_str.split(',')) print(m_str.split("'")) def length(whatever): print(len(whatever)) def two_d_arrays(): two_d = [[]] def cmd_line_args(): pass if __name__ == "__main__": # file_io() # console_io() # console_multiple_lines() # split_string("I'm a string with spaces, and comma.") length("length")
d1016e22ac19862a11837a2e5a01c55c6a8b12b3
Patrick5455/InterviewPractice
/nineChapters/SearchForARange.py
2,314
3.5
4
class Solution: """ @param A : a list of integers @param target : an integer to be searched @return : a list of length 2, [index1, index2] """ def searchRange(self, A, target): if len(A) == 0: return [-1, -1] start, end = 0, len(A) - 1 while start + 1 < end: mid = start + int((end - start) / 2) if A[mid] < target: start = mid else: end = mid if A[start] == target: leftBound = start elif A[end] == target: leftBound = end else: return [-1, -1] start, end = leftBound, len(A) - 1 while start + 1 < end: mid = start + int((end - start) / 2) if A[mid] <= target: start = mid else: end = mid if A[end] == target: rightBound = end else: rightBound = start return [leftBound, rightBound] def searchRange_slow(self, A, target): # write your code here if len(A) == 0: return [-1,-1] start = 0 end = len(A) - 1 while (start + 1) < end: mid = start + (end - start) / 2 if A[mid] == target: end = mid elif A[mid] < target: start = mid else: end = mid ret_left = -1 ret_right = -1 if A[start] == target: ret_left = start ret_right = start if A[end] == target: ret_left = end ret_right = end while ret_left > 0 and A[ret_left-1] == target: ret_left -= 1 while (ret_right < len(A) - 1) and A[ret_right + 1] == target: ret_right += 1 return [ret_left, ret_right] def test(self): tests = [ ([5,7,7,8,8,10], 8, [3,4]), ([5,7,7,8,8,8,8,10], 8, [3,6]), ([5,7,7,8,8,8,8,10], 0, [-1,-1]), ([0,1,2,3,4], 0, [0,0])] for t in tests: ans = self.searchRange(t[0], t[1]) print("------sol------") print(ans) print("------expected ans----") print(t[2]) if __name__ == '__main__': s = Solution() s.test()
df93b766db65419e0d4d70867a8dcaad28c83cf1
Patrick5455/InterviewPractice
/reverseString.py
257
3.6875
4
def reverseWords(s): temp = [] counter = 0 res = '' s = s.split() for i in s: counter = counter + 1 temp.append(i) while counter > 0: counter = counter - 1 res = res + temp[counter] + ' ' return res.strip() reverseWords("the sky is blue")
12f4f9d67668cb09028421727ff1df56ebc94cab
tristaaa/learnpy
/professorTrial.py
771
3.90625
4
#! /usr/bin/env python3 # -*- coding:utf-8 -*- # from MITPersonTrial import MITPerson class Professor(MITPerson): def __init__(self, name, department): MITPerson.__init__(self, name) self.department = department def speak(self, utterance): new = 'In course ' + self.department + ' we say ' return MITPerson.speak(self, new + utterance) def lecture(self, topic): return self.speak('it is obvious that ' + topic) # Professor usage example faculty = Professor('Doctor Arrogant', 'six') print() print('---Professor usage example---') print(faculty.speak('hi there')) # shows Arrogant says: In course six we say hi there print(faculty.lecture('hi there')) # shows Arrogant says: In course six we say it is obvious that hi there
859feadf6786c485248a9b30b5fca937543a81a5
tristaaa/learnpy
/getLowestPaymentBisection.py
1,221
3.921875
4
#! /usr/bin/env python3 # -*- coding:utf-8 -*- balance = 320000 annualInterestRate = 0.2 def increment(): def getLowestPaymentBisection(balance, annualInterestRate): ''' using bisection search return: the lowest payment to pay off the balance within 12 months will be the multiple of $0.01 ''' def getRemainingBalance(balance, annualInterestRate, monthlyPayment): monthlyUnpaidBalance = balance - monthlyPayment monthlyUpdatedBalance = monthlyUnpaidBalance * \ (1 + annualInterestRate / 12) return monthlyUpdatedBalance low = balance / 12 high = (balance * (1 + annualInterestRate / 12.0)**12) / 12.0 monthlyPayment = (low + high) / 2 epsilon = 0.01 balance0 = balance while (high - low) / 2 >= epsilon: balance = balance0 for m in range(1, 13): balance = getRemainingBalance( balance, annualInterestRate, monthlyPayment) if balance > 0: low = monthlyPayment else: high = monthlyPayment monthlyPayment = (low + high) / 2 print('Lowest Payment:', round(monthlyPayment, 2)) getLowestPaymentBisection(balance, annualInterestRate)
9ed2d0f9f15fde3e123ea8f30c2ffa714db1460a
tristaaa/learnpy
/getRemainingBalance.py
819
4.125
4
#! /usr/bin/env python3 # -*- coding:utf-8 -*- balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 def getMonthlyBalance(balance, annualInterestRate, monthlyPaymentRate): ''' return: the remaining balance at the end of the month ''' minimalPayment = balance * monthlyPaymentRate monthlyUnpaidBalance = balance - minimalPayment interest = monthlyUnpaidBalance * annualInterestRate / 12 return monthlyUnpaidBalance + interest def getFinalBalance(balance, annualInterestRate, monthlyPaymentRate): for m in range(12): balance = getMonthlyBalance( balance, annualInterestRate, monthlyPaymentRate) remainingBalance = round(balance, 2) print('Remaining balance:', remainingBalance) getFinalBalance(balance, annualInterestRate, monthlyPaymentRate)
6df041ded350202d4e74f98a104fd3470e21683d
tristaaa/learnpy
/bisectionSearch_3.py
910
4.46875
4
#! /usr/bin/env python3 # -*- coding:utf-8 -*- # use bisection search to guess the secret number # the user thinks of an integer [0,100). # The computer makes guesses, and you give it input # - is its guess too high or too low? # Using bisection search, the computer will guess the user's secret number low = 0 high = 100 guess = (low+high)//2 print('Please think of a number between 0 and 100!') while True: print('Is your secret number '+str(guess)+'?') is_secret_num = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if is_secret_num =='l': low = guess elif is_secret_num =='h': high = guess elif is_secret_num =='c': break else: print('Sorry, I did not understand your input.') guess = (low+high)//2 print('Game over. Your secret number was:',guess)
478b3a83db292657743bcf383fff15d80a75514a
MAKMoiz23/DSA-codes
/scape_goat_tree_19B-028-069-CS.py
9,569
3.921875
4
import math class TreeNode: def __init__(self, data, parent=None, left=None, right=None): self.data = data self.parent = parent self.left = left self.right = right class ScapegoatTree: def __init__(self, root=None): self.scape_goat = None self.root = root self.n = self.q = 0 self.alpha = 2/3 #Insert function which then calls the main InsertNode function to insert the the value in tree #Takes tree node and value to insert as an argument def Insert(self, x, value): self.InsertNode(x, value) #if rebalanced is called and scapegoat is found then after re-balancing we have to set scapegoat node to None if self.scape_goat: self.scape_goat = None #Insert Node which takes root and value to insert as an argument it then traverse and approaches the appropriate #position to insert as in binary search the only difference is that if our tree in not alpha balanced then it #search scapegoat node then it runs in order traversal from our scapegoat node and then stores it in array. #After storing elements in array it the sets the children of the scapegoat parent whose child is scapegoat #to none and then runs re-build tree from scapegoat parent. def InsertNode(self, x, value): if self.root is None: self.n += 1 self.q += 1 self.root = TreeNode(value) return if value == x.data: return if value > x.data: #go right if x.right: self.InsertNode(x.right, value) else: self.n += 1 self.q += 1 x.right = TreeNode(value) x.right.parent = x return elif value < x.data: #go left if x.left: self.InsertNode(x.left, value) else: self.n += 1 self.q += 1 x.left = TreeNode(value) x.left.parent = x return if not self.Balanced(): if self.scape_goat: #if scape goat is already found then we have to skip further search return self.scape_goat = self.Scape_Goat_Search(x) #search for the scape gaot in tree if self.scape_goat: print('Rebuilt starting for insertion..') sorted_arr = self.InOrder(x.parent) self.n -= len(sorted_arr) self.q -= len(sorted_arr) re_built_tree_node = x.parent.parent if re_built_tree_node.left == x.parent: re_built_tree_node.left = None if re_built_tree_node.right == x.parent: re_built_tree_node.right = None self.rebuild_tree_inorder_tvr(re_built_tree_node, sorted_arr) #A simple search function same as BST which returns the node having data same as value searched def Search(self, x, value): if value == x.data: return x if value > x.data: # go right if x.right: self.InsertNode(x.right, value) elif value < x.data: # go left if x.left: self.InsertNode(x.left, value) #Takes tree node which is parent of scapegoat and an array containing elements in sorted form then insert #the mid element of array dividing it into two halves halves and then doing the same till al the mid elements #of divided arrays are inserted def rebuild_tree_inorder_tvr(self, node, arr): start=0 end=len(arr) if start >= end: return mid = start+end//2 mid_ele = arr[mid] left = arr[:mid] right = arr[mid+1:] self.InsertNode(node, mid_ele) self.rebuild_tree_inorder_tvr(node, left) self.rebuild_tree_inorder_tvr(node, right) #Returns pre order traversal of tree same as in BST def PreOrder(self, x): ele=[] ele.append(x.data) if x.left: ele += self.PreOrder(x.left) if x.right: ele += self.PreOrder(x.right) return ele #Returns In order traversal of tree same as in BST def InOrder(self, x): ele = [] if x.left: ele += self.InOrder(x.left) ele.append(x.data) if x.right: ele += self.InOrder(x.right) return ele #Returns Post order of tree same as in BST def PostOrder(self, x): ele = [] if x.left: ele += self.PostOrder(x.left) if x.right: ele += self.PostOrder(x.right) ele.append(x.data) return ele #To calculate height of tree takes a node as parameter goes to the leaf node and then return the one plus #value of each node either left or right if its length is greater than the other root height is 1 so is #called from other function. def Calculate_height(self, x): if x is None: return 0 else: lDepth = self.Calculate_height(x.left) rDepth = self.Calculate_height(x.right) if (lDepth > rDepth): return lDepth + 1 else: return rDepth + 1 #Return -1 from the height so that the root node height is cancelled. def Height(self, root): h_tree = self.Calculate_height(root) return h_tree-1 #Returnes number of node under that particular node. def sizeOfSubtree(self, node): if node == None: return 0 return 1 + self.sizeOfSubtree(node.left) + self.sizeOfSubtree(node.right) #function to check whether the tree is alpha balanced or not returns true if not then false #Height < log (1/alpha) * n for a balanced tree. def Balanced(self): if (self.Height(self.root)) > (math.log(self.n, (1/self.alpha))): return False return True #Scapegoat search function checks if size(x)/size(x.parent) is greater than alpha if so then its scapegoat node def Scape_Goat_Search(self, x): try: chk = self.sizeOfSubtree(x)/self.sizeOfSubtree(x.parent) if chk > self.alpha: return x.parent except ZeroDivisionError: return #returns the minimum node form the given tree node def MinNode(self, x): if x is None: return while x: if x.left is None: return x x = x.left #Delete function to call Delete node which then deleted node from the tree and then delete function checks if #after deletion n is smaller that half of q if so then rebuilds tree in same way as insert by storing it in #array and adding mid elements using build form tree in order traversal. def delete(self, root, x): self.Delete_Node(root, x) if self.n < self.q/2: print('Rebuild starting for deletion..') sorted_array=self.InOrder(self.root) self.root = None self.root = TreeNode(sorted_array[(len(sorted_array)//2)]) print(sorted_array) self.q = self.n = 1 self.rebuild_tree_inorder_tvr(self.root, sorted_array) #Deletes node from the given node of tree or tree by finding the node then copying its right node minimum #node and the deleting that node. def Delete_Node(self, root, x): if root is None: return root if x < root.data: root.left = self.Delete_Node(root.left, x) elif (x > root.data): root.right = self.Delete_Node(root.right, x) else: if root.left is None: self.n -= 1 temp = root.right root = None return temp elif root.right is None: self.n -= 1 temp = root.left root = None return temp temp = self.MinNode(root.right) root.data = temp.data root.right = self.Delete_Node(root.right, temp.data) return root if __name__=='__main__': b = ScapegoatTree() b.Insert(b.root, 12) b.Insert(b.root, 11) b.Insert(b.root, 13) b.Insert(b.root, 10) b.Insert(b.root, 14) b.Insert(b.root, 7) b.Insert(b.root, 6) b.Insert(b.root, 9) b.Insert(b.root, 5) b.Insert(b.root, 8) # print(b.Search(b.root, 12)) print(b.InOrder(b.root)) # print(f'pre order {b.PreOrder(b.root)}') # print(b.n) # print(b.q) print(f"The height before is :{b.Height(b.root)}") print(f"Is a balanced tree :{b.Balanced()}") "''____Rebuild Insert Value____''" b.Insert(b.root, 8.5) # b.delete(b.root, 7) # b.delete(b.root, 10) # b.delete(b.root, 6) # b.delete(b.root, 14) # b.delete(b.root, 9) # # "''____Rebuild Delete Value____''" # b.delete(b.root, 5) print(b.InOrder(b.root)) # print(f'pre order {b.PreOrder(b.root)}') print(f"The height after is :{b.Height(b.root)}") print(f"Is a balanced tree :{b.Balanced()}") # print(b.n) # print(b.q)
10d1145cc06d7213e50f70feea379dff8aa968c7
sashaneo/tkinter
/1.py
1,438
3.75
4
import builtins import tkinter as tk def calculate_discount_percentage(total): discount = 0 if total >= 100: discount = 20 elif total > 0 and total < 100: discount = 10 return discount def calculate_discount(total): discount_percentage = calculate_discount_percentage(total) discount = total - total / 100 * discount_percentage return discount def get_bill_total(): entered_bill_total = entry_box.get() try: bill_total = float(entered_bill_total) except ValueError: textbox["text"] = "Incorrect value entered" return final_total = format(calculate_discount(bill_total), '.02f') textbox["text"] = "USD" + final_total window = tk.Tk() window.geometry("400x210") window.title("Billing Programme") label = tk.Label(text="Enter Bill Total:") label.place(x = 10, y = 20, height= 25) label.config(bg="lightgreen", padx=0) entry_box = tk.Entry(text="") entry_box.place(x =10, y = 40, width= 110, height = 25) button = tk.Button(text= "Calc Bill", command = get_bill_total) button.config(font="16") button.place(x = 10, y = 170, width = 380, height = 35) label2 = tk.Label(text="Total Price (after discount):") label2.place(x = 140, y = 20) label2.config(bg="lightgreen", padx=0) textbox = tk.Message(text="USD 0.00", width=200, font="16") textbox.config(bg="lightgreen", padx=0) textbox.place(x = 140, y = 40) window.mainloop()
bcb7483e42583c33679376039e2665996125dd88
uzuran/AutomaticBoringStuff
/Loops/fiveTimes.py
289
4.0625
4
# We use for i in range to print Jimmy print five times #print('My name is') #for i in range(5): # print('Jimmy Five times(' + str(i) + ')') # Here we used while to print the same thing print('My name is') i = 0 while i < 5: print('Jimmy Five times(' + str(i) + ')') i = i + 1
3be3d138268f4ebd54c28b119598324e76ab913a
uzuran/AutomaticBoringStuff
/Listst/list_To_str.py
174
3.78125
4
def list_to_string(some_of_list): str1 = ', ' return (str1.join(some_of_list)) some_of_list = ['apples','bananas','tofu','cats'] print(list_to_string(some_of_list))
9626b538db9a129e0de190538bb381a2222cb31c
uzuran/AutomaticBoringStuff
/TestDrive/e_Shop_try/e_Shop.py
2,748
3.859375
4
# Python version 3.9.2 # Practice with some loops,dictionaries and json import json import os.path import sys storage = {"CPU": 10, "GPU": 10, "HDD": 10, "SSD": 10, "MB": 10, "RAM": 10, "PSU": 10, "CASE": 10} addToStock = {"CPU": 100, "GPU": 100, "HDD": 100, "SSD": 100, "MB": 100, "RAM": 100, "PSU": 100, "CASE": 100} customerOrder = {} dataFile = 'orders.json' # function which load orders and transfer value to str def loadOrders(): if os.path.isfile(dataFile): try: with open(dataFile) as d: customerOrder = json.load(d) print(customerOrder) customerOrder = {} for i, order in customerOrder.items(): customerOrder[int(i)] = order print(customerOrder) return customerOrder except: return {} else: return {} # this function save some orders from input to customerOrders dictionaries def saveOrders(): with open(dataFile, 'w') as d: json.dump(customerOrder, d) # this function add or preorder some supplies if it is not in storage def addSupplies(): for item in storage: if storage[item] == 0: storage[item] += addToStock[item] def displayStorage(): for item in storage: print(item + ' ' + str(storage[item])) def createOrders(): displayStorage() print('Our current offer is this: ') while True: y = 0 order = input('\n' + 'To select order, please write name from our offer, ' 'or write exit to end the program: ').upper() if order == 'EXIT': print('Program is end') sys.exit() elif order not in storage: print('We don\'t have any of your inquiry, please write item from offer') continue if order != '': print('We have Storage' + ' ' + order + ': ' + str(storage[order])) # ???? storage[order] ??? break def quantityNumber(message): while True: try: userInput = int(input(message)) except ValueError: print("Not an integer! Try again.") continue else: return userInput while True: quantity = quantityNumber('How much you need ? ') storage[order] -= quantity addSupplies() if order in customerOrder: customerOrder[order] += quantity else: customerOrder[order] = quantity break if len(customerOrder) > 0: y += 1 customerOrder[y] = customerOrder displayStorage() loadOrders() createOrders()
bed49525959742ff33513021cd308f5b78ed3b8f
willemhscott/CSCI-3104
/homework7.py
1,993
3.828125
4
class Graph(): def __init__(self, adjacency_matrix): """ Graph initialized with a weighted adjacency matrix Attributes ---------- adjacency_matrix : 2D array non-negative integers where adjacency_matrix[i][j] is the weight of the edge i to j, with 0 representing no edge """ self.adjacency_matrix = adjacency_matrix # Add more class variables below as needed, such as n: # self.N = len(adjacency_matrix) def Prim(self): """ Use Prim-Jarnik's algorithm to find the length of the minimum spanning tree starting from node 0 Returns ------- int Weighted length of tree """ nodes = {i: float('inf') for i in range(len(self.adjacency_matrix)) } nodes[0] = 0 cost = 0 mst = [] parents = {} while len(mst) != len(self.adjacency_matrix): vert = min(nodes, key=lambda x: (x in mst, nodes[x])) mst.append(vert) cost += nodes[vert] for j, edge in enumerate(self.adjacency_matrix[vert]): if edge: if edge < nodes[j]: nodes[j] = edge parents[j] = vert #print(nodes, mst, parents) return cost G = Graph([[0, 10, 11, 33, 60], [10, 0, 22, 14, 57], [11, 22, 0, 11, 17], [33, 14, 11, 0, 9], [60, 57, 17, 9, 0]]) g = G.Prim() #print(g) #assert g == 41 G = Graph([ [0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [0, 3, 0, 0, 7], [6, 8, 0, 0, 9], [0, 5, 7, 9, 0]] ) #print(G.Prim()) G = Graph([[0,7,4,3,0,0], [7,0,8,1,0,9], [4,8,0,0,5,2], [3,1,0,0,6,-1], [0,0,5,6,0,10], [0,9,2,-1,10,0]]) #print(G.Prim())
87b1994cd10f98420c37a92626af829ee21b0afc
ynonp/gitlab-demos
/28-generators/03_comprehension.py
194
3.625
4
import itertools as it def fib(): x, y = 1, 1 while True: yield x x, y = y, x + y sqr_fib = (x * x for x in fib()) for val in it.islice(sqr_fib, 10): print(val)
78ab19aa0d8932af345b7c8b99e1456a3945945d
Nick-Feldman/PythonExamples
/exercise6_9.py
162
3.828125
4
#Please write a program which prints all permutations of [1,2,3] from itertools import permutations perm = permutations([1,2,3]) print(len(list(perm)))
975470a53911f363dc8c39e40f9702b356d7551e
Nick-Feldman/PythonExamples
/exercise5_15.py
169
3.75
4
''' Please write a program to shuffle and print the list [3,6,7,8]. ''' from random import shuffle numbers = [3, 6, 7, 8] shuffle(numbers) print(numbers)
089215ea56d457043a141725898e84b5c78d4a02
Nick-Feldman/PythonExamples
/exercise5_6.py
168
3.78125
4
''' Please generate a random float where the value is between 5 and 95 using a Python math module. ''' import random num = random.uniform(5, 95) print(num)
b404567086112e97274ef5f8ee4950b7241020f7
Nick-Feldman/PythonExamples
/exercise5_11.py
418
3.703125
4
''' Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7, between 1 and 1000 inclusive. ''' import random li = [] def ranGenerator(): for i in range(5): x = 1 while not(x % 5 == 0 and x % 7 == 0): x = random.randint(1, 1000) yield x gen = ranGenerator() for i in gen: li.append(i) print(li)
e42df4e0004243511bde5d9d4bf50f6250ab5394
Nick-Feldman/PythonExamples
/exercise6_2.py
105
3.640625
4
theList = [12, 24, 35, 24, 88, 120, 155] newList = [x for x in theList if x != 24] print(newList)
32590a15e47f9ef40272430aa7090a75362699a6
isradesu/israel-poo-info-p7
/atividades/presenca/atividade2linklist.py
1,709
4.03125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self._size = 0 def append(self, elem): if self.head: # inserção quando a lista j tem elemt pointer = self.head while pointer.next: pointer = pointer.next pointer.next = Node(elem) else: # primeira inserção self.head = Node(elem) self._size = self._size + 1 def __len__(self): # retorna o tamanho da lista return self._size def __getitem__(self, index): pointer = self.head for i in range(index): if pointer: pointer = pointer.next else: raise IndexError("Indice da lista fora do alcance") if pointer: return pointer.data else: raise IndexError("Indice da lista fora do alcance") def __setitem__(self, index, elem): pointer = self.head for i in range(index): if pointer: pointer = pointer.next else: raise IndexError("Indice da lista fora do alcance") if pointer: pointer.data = elem else: raise IndexError("Indice da lista fora do alcance") def index(self, elem): # Retorna indice do elemento na lista pointer = self.head i = 0 while pointer: if pointer.data == elem: return i pointer = pointer.next i = i + 1 raise ValueError("{} não está na lista".format(elem))
86df8e8b9a2353a6dfcea830f6a1d7bb2bf5e0ed
jsterner73/MITx---6.00.1x
/PayingDebtOffInAYear.py
532
3.671875
4
balance = 3926 annualInterestRate = 0.2 lowestPayment = 10 while True: monthlyInterestRate = annualInterestRate / 12.0 totalPaid = 0 previousBalance = balance for x in range(1,13): monthlyUnpaidBalance = previousBalance - lowestPayment previousBalance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) totalPaid += lowestPayment if previousBalance > 0: lowestPayment += 10 else: break print 'Lowest Payment: ' + str(lowestPayment)
83300d7433cdb8e4c83731394a8fa5f4fddb1c06
anagorko/csg
/src/constraint.py
1,062
3.734375
4
#!/usr/bin/env python class Constraint(object): LT = 1 GT = 2 EQ = 3 def __init__(self): self.type = Constraint.LT self.bound = 0.0 self.var = {} def addVariable(self, var, val): # TODO: check if var exists and adjust accordingly self.var[var] = val def setBound(self, val): self.bound = val def setType(self, type): assert(type == Constraint.LT or type == Constraint.GT or type == Constraint.EQ) self.type = type def __str__(self): s = '' first = True for var, val in self.var.iteritems(): if not first: s += ' + ' else: first = False s += str(val) + ' ' + var if self.type == Constraint.EQ: s += ' = ' elif self.type == Constraint.LT: s += ' <= ' elif self.type == Constraint.GT: s += ' >= ' s += str(self.bound) return s
bcd481d7bfd7c667f806a65f5cdbe14f04c06205
sp00ks-L/LeetCode-Problems
/minStack.py
669
3.640625
4
from collections import deque class MinStack: ''' Design a stack that supports push, pop, top and get_min in constant time ''' def __init__(self): """ Initialise data structure Originally had stack=deque() as default arg but it threw wrong answers during submission """ self.stack = deque() def __del__(self): print("Destructor called, Stack deleted") def push(self, x: int) -> None: self.stack.appendleft(x) def pop(self) -> None: self.stack.popleft() def top(self) -> int: return self.stack[0] def getMin(self) -> int: return min(self.stack)
19740d81e52aa421501c411105bbda801f613768
sp00ks-L/LeetCode-Problems
/jumpGame.py
512
3.9375
4
class BackTracking: def canJump(self, pos, nums): ''' Where each int in nums[] is the maximum jump length is it possible to reach the last index ''' n = len(nums) if pos == n - 1: return True farthestJump = min(pos + nums[pos], n - 1) for i in range(farthestJump, pos, -1): if self.canJump(i, nums): return True return False def jumpGame(self, nums): return self.canJump(0, nums)
eb37a9e228f492ae7055c0945cb7a37d7c280ac5
sp00ks-L/LeetCode-Problems
/moveZeroes.py
530
3.703125
4
class Solution: def move_zeros(self, nums): """ Takes an array of ints and moves zeroes to the end of the array while maintaining the order of the remaining ints :param nums: List[int] [0, 1, 0, 3, 12] :return: List[int] [1, 3, 12, 0, 0] """ n = len(nums) nxt = 0 for num in nums: if num != 0: nums[nxt] = num nxt += 1 for i in range(nxt, n): nums[i] = 0 return nums
3fe52541a718c44adf355ee92c4695128e36eabc
tachyon777/PAST
/PAST_1/D.py
518
3.71875
4
#第一回 アルゴリズム実技検定 #D import sys from collections import defaultdict dic1 = defaultdict(int) readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 n = int(readline()) lst1 = [] for i in range(n): dic1[int(readline())] += 1 ans = [0,0] flag = 0 for i in range(1,n+1): if dic1[i] != 1: flag = 1 if dic1[i] == 0: ans[1] = i else: ans[0] = i if flag: print(*ans) else: print("Correct")
682648dfae59da573cdd3a221eba8acb592a44f8
tachyon777/PAST
/PAST_3/L_short.py
2,286
3.515625
4
#第三回 アルゴリズム実技検定 #L(書き直し) """ 優先度付きキューのリストを3つ用意することでこの問題は解くことができる。 1.手前から1個だけ見たとき(a=1)のheap(hp1) 2.手前から2個見たとき(a=2)のheap(hp2) 3.hp1から使用されたものであって、hp2にはまだあるもの(hpres) もう一つ、以下のヒープがあってもよいが、無いほうが簡単のため省略 (4.hp2から使用されたものであって、hp1にはまだあるもの) 場合分けをしっかり考えないと、辻褄が合わなくなるので注意。 """ import sys import heapq readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 hpify = heapq.heapify push = heapq.heappush pop = heapq.heappop n = int(readline()) K = [] hp1 = [] hp2 = [] hpres = [] hpify(hp1) hpify(hp2) hpify(hpres) for i in range(n): lst1 = list(map(int,readline().split())) push(hp1,(-lst1[1],i)) push(hp2,(-lst1[1],i)) if lst1[0] >= 2: push(hp2,(-lst1[2],i)) else: push(hp2,(0,i)) K.append(lst1 +[0]*2) m = int(readline()) A = list(map(int,readline().split())) now = [2]*n #hp2にちょうど追加してあるところ(0要素目の要素数を考慮) for i in range(m): if A[i] == 1: val,idx = pop(hp1) print(-val) push(hpres,val) push(hp1,(-K[idx][now[idx]],idx)) push(hp2,(-K[idx][now[idx]+1],idx)) now[idx] += 1 else: while True: #hp1で消化済みだった場合ループする val,idx = pop(hp2) if not hpres: break res_val = pop(hpres) if val == res_val: continue else: push(hpres,res_val) break print(-val) hp1_val,hp1_idx = pop(hp1) #hp1に入っているかいないかで分岐 if hp1_val != val: push(hp1,(hp1_val,hp1_idx)) push(hp2,(-K[idx][now[idx]+1],idx)) now[idx] += 1 else: push(hp1,(-K[idx][now[idx]],idx)) push(hp2,(-K[idx][now[idx]+1],idx)) now[idx] += 1
f8e7e90a9dd5fb877b4374e970831c9344cd77c8
tachyon777/PAST
/PAST_1/L.py
2,398
3.546875
4
#第一回 アルゴリズム実技検定 #L """ 最小全域木 但し、達成すれば良いのは大きい塔のみ。 よって、各小さい塔を使う/使わないをbit全探索して、O(2**5) 全体のコストの最小値が答え。 各プリム法を用いた探索時間はO(ElogV)なので、 E=35**2,V=35として全体は O(2**m*((n+m)**2)*log(n+m))となる """ import sys import math from copy import deepcopy readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 n,m = map(int,readline().split()) xyc = [] for i in range(n+m): xyc.append(list(map(int,readline().split()))) #O(ElogV) import heapq def prim_heap(edge): used = [True] * len(edge) #True:不使用 edgelist = [] for e in edge[0]: heapq.heappush(edgelist,e) used[0] = False res = 0 while len(edgelist) != 0: minedge = heapq.heappop(edgelist) if not used[minedge[1]]: continue v = minedge[1] used[v] = False for e in edge[v]: if used[e[1]]: heapq.heappush(edgelist,e) res += minedge[0] return res edge = [[] for _ in range(n)] for i in range(n-1): for j in range(i+1,n): a = xyc[i] b = xyc[j] res = math.sqrt(((a[0]-b[0])**2+(a[1]-b[1])**2)) if a[2] != b[2]: res *= 10 edge[i].append([res,j]) edge[j].append([res,i]) ans = 10**18 for i in range(1<<m): edge2 = deepcopy(edge) count = 0 bit = [] for j in range(m): if i>>j&1: #1ならば使う edge2.append([]) for k in range(n): a = xyc[k] b = xyc[n+j] res = math.sqrt(((a[0]-b[0])**2+(a[1]-b[1])**2)) if a[2] != b[2]: res *= 10 edge2[k].append([res,n+count]) edge2[n+count].append([res,k]) for k in range(count): a = bit[k] b = xyc[n+j] res = math.sqrt(((a[0]-b[0])**2+(a[1]-b[1])**2)) if a[2] != b[2]: res *= 10 edge2[n+k].append([res,n+count]) edge2[n+count].append([res,n+k]) bit.append(b) count += 1 ans = min(ans,prim_heap(edge2)) print(ans)
141ef23be3dc60cf8f7fd5dcbdacbc64722a0d0d
EduGame3/Experiment
/1.py
260
4
4
print('COMPARADOR DE NÚMEROS') a = float(input('Escriba un número: ')) #¿cómo hacer para que acepte el 1/2? b = float(input('Escriba otro número: ')) if (a < b): print("hola") elif (a > b): print("adios") else: print('Los dos números son iguales')
39a54895a5bca11af5dd898533334de559fa0840
MarineJoker/AlgorithmQIUZHAO
/Week_01/min-stack.py
844
4
4
class MinStack: # 线性的话就要利用多一个栈去存当前栈内最小值 # 由于栈先进后出的特性栈中每个元素可以用作保存从自身到内部的那个阶段的状态 def __init__(self): # self.index = 0 self.list = [] self.heap = [float('inf')] """ initialize your data structure here. """ def push(self, x: int) -> None: self.list.append(x) self.heap.append(min(x, self.getMin())) def pop(self) -> None: self.list.pop(-1) self.heap.pop(-1) def top(self) -> int: return self.list[-1] def getMin(self) -> int: return self.heap[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
67419b66475d1d64d889f3c1a757494556307dcc
VoraciousFour/VorDiff
/VorDiff/nodes/scalar.py
6,417
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 15 13:09:28 2019 @author: weiruchen """ import numpy as np class Scalar(): """ Implements the interface for user defined variables, which is single value in this case. So the scalar objects have a single user defined value (or it can be a single function composition) and a derivative. For the single valued scalar case, the jacobian matrix is just simply the derivative. """ def __init__(self, value, *kwargs): """ Return a Scalar object with user defined value and derivative. If no user defined derivative is defined, then just return a Scalar object with user defined value. INPUTS ======= val: real valued numeric type der: real valued numeric type RETURNS ======= Scalar object NOTES ====== User can access and modify _val and _der class variables directly. To access these two variables, user can call the get method in the Scalar class. """ self._val = value if len(kwargs) == 0: self._der = 1 else: self._der = kwargs[0] def get(self): """ Return the value and derivative of the self Scalar object. INPUTS ======= self: Scalar object RETURNS ======= self._val: value of the user defined variable or value of the function represented by the self Scalar object self._der: the derivative of the self Scalar object with respect to the single variable """ return self._val, self._der def __add__(self, other): """ Return a Scalar object whose value is the sum of self and other when other is a Scalar object. INPUTS ======= self: Scalar object other: Scalar object RETURNS ======= a new Scalar object whose value is the sum of the values of the Scalar self and other and whose derivative is the new derivative of the function that sums up these two values with respect to the single variable. """ try: return Scalar(self._val+other._val, self._der+other._der) except AttributeError: return self.__radd__(other) def __radd__(self, other): """ Return a Scalar object whose value is the sum of self and other when other is a numeric type constant. """ return Scalar(self._val+other, self._der) def __mul__(self, other): """ Return a Scalar object whose value is the product of self and other when other is a Scalar object. INPUTS ======= self: Scalar object other: Scalar object RETURNS ======= a new Scalar object whose value is the product of the values of the Scalar self and other and whose derivative is the new derivative of the function that multiplies these two values with respect to the single variable. """ try: return Scalar(self._val*other._val, self._der*other._val+self._val*other._der) except AttributeError: return self.__rmul__(other) def __rmul__(self, other): """ Return a Scalar object whose value is the product of self and other when other is a numeric type constant. """ return Scalar(self._val*other, self._der*other) def __sub__(self, other): """Return a Scalar object with value self - other""" return self + (-other) def __rsub__(self, other): """Return a Scalar object with value other - self""" return -self + other def __truediv__(self, other): """ Scalar value is returned from one user defined variable created by the quotient of self and other. INPUTS ======= self: Scalar object other: either a Scalar object or numeric type constant RETURNS ======= a new Scalar object whose value is the quotient of the values of the Scalar self and other and whose derivative is the new derivative of the function that divides Scalar self by other with respect to the single variable. """ try: return Scalar(self._val/other._val, (self._der*other._val-self._val*other._der)/(other._val**2)) except AttributeError: return Scalar(self._val/other, self._der/other) def __rtruediv__(self, other): """ Return a Scalar object whose value is the quotient of self and other when other is a numeric type constant. """ return Scalar(other/self._val, other*(-self._der)/(self._val)**2) def __pow__(self, other): """ INPUTS ======= self: Scalar object other: either a Scalar object or numeric type constant RETURNS ======= Scalar object whose value is self raised to the power of other NOTES ====== This method returns a Scalar object that is calculated from the self Scalar class instance raised to the power of other """ try: return Scalar(self._val**other._val, np.exp(other._val*np.log(self._val))*(other._der*np.log(self._val)+other._val/float(self._val))) except AttributeError: return Scalar(self._val**other, other*(self._val**(other-1))*self._der) def __rpow__(self, other): """Return a Scalar object that is calculated from other raised to the power of the Scalar class instance""" return Scalar(other**self._val, self._der*np.log(other)*other**self._val) def __neg__(self): """ INPUTS ======= self: Scalar object RETURNS ======= A Scalar object that is the negation of self. NOTES ====== The Scalar Object that is returned from this method comes from a new Scalar Object that is the negation of self. """ return Scalar((-1)*self._val, (-1)*self._der)
6aadd7fb383338cf30be946ec7b1db91e278f990
AnnapurnaThakur/python_code
/anu2.py
63
3.625
4
a=input("enter your number :") print(a) print("you enter :",a)
b2bd2562584bc6c4966ea227428ff82a014d633b
AnnapurnaThakur/python_code
/bookS/ch2/bs2.py
138
3.75
4
my_dict={} my_dict[(1,2,4)]=8 my_dict[(4,2,1)]=10 my_dict[(1,2)]=12 sum=0 for k in my_dict: sum+=my_dict[k] print(sum) print(my_dict)
25f09a2e54803140fcadac4daeb38572a232954f
AnnapurnaThakur/python_code
/All projects/anu15.py
634
3.96875
4
#nested for loop sum=0 for i in range (1,6): i2=str(i) x1=input("enter the marks of subject number " + i2 +" : " ) x=int(x1) if x==45: print("pass") elif x<45: print("fail") else : print("pass") sum=sum+x print("the total value is :" , sum) c=sum if c >280 and c<320: print("Grade B") if c<280: print("You are FAIL") print("total marks :" ,c) elif c>320 and c<400: print("Grade A") elif c>400 and c<500: print("Grade A+") elif c>550 and c<599: print("AA") elif c>599: print("not possible")
0dc00b065c4e8460cb7e85db60d3bfea2189803a
AnnapurnaThakur/python_code
/anubreak19.py
600
4.3125
4
# for x in range (1,5): # for i in range(1,5): # if i==3: # print("Sorry") # print("loop2") # break # print("loop1") # print("end") ####2nd example: for x in range (1,5): for i in range(1,5): if i==3: print("Sorry") break print("loop2") print("loop1") print("end") ######3rd example: # for x in range (1,5): # for i in range(1,7): # if i==3: # print("sorry") # continue # print("loop i= " , i , "and loop i =" ,x) # print("loop completed x" , x) # print("end")
3b4184877f79b34315fb843b3faeb4cc9a27ecd2
AnnapurnaThakur/python_code
/Nested_forLoop/nested_forloop10.py
277
3.96875
4
a=int(input("Enter a number : ")) for i in range(a,1,-1): for j in range(1,i+1): print(" " , end="") for k in range(i-1,a,1): print(k , end="") print() # Enter a number : 7 # 6 # 56 # 456 # 3456 # 23456 # 123456
9f708afd701c2a1d7a0b6ed36606d30b5924e8ca
AnnapurnaThakur/python_code
/Modules/str_join1.py
260
3.796875
4
# a="/".join("138") # print(a) a=int(input("Your date : ")) b=int(input("Your date : ")) for a in range (a,b+1): d=str(a) m="9" y="2020" a1="/".join((d,m,y)) print(a1) # if a>30: # print("error") # else: # print()
830687650d4b117cf56618de30d2b62926d37835
AnnapurnaThakur/python_code
/anu20.py
1,020
4.0625
4
# a=int(input("Enter a number : ")) # for i in range (0,6): # for j in range(0,i): # print(j) # print(i) # a=int(input("Enter a number : ")) # for i in range(1,a+1,2): # for j in range(1,i+2,2): # print(j, end=" ") # print() # a=int(input("Enter a number : ")) # for i in range(0,a+1): # for j in range(0,i,1): # print(i, end=" ") # print() # a=int(input("enter a number : ")) # for i in range (a,0,-1): # for j in range(1,i+1): # print(a, end="") # print() # a=5+-3 # print(a) # a=4 # for i in range(1,a+1): # for j in range(1,i+1): # print (j, end="") # print() # b=3 # for h in range(b,0,-1): # for k in range(1,h+1): # print(k , end="") # print() # a=int(input("Enter a number : ")) # b=1 # for i in range(a): # for j in range(1,6): # print(b, end="") # print() # b=b+1 a=int(input("Enter a number : ")) for i in range(a,0,-1): for j in range(i): print(i, end="") print()
63d9745d1c449ac7c2f945516848d35d62d2b70d
AnnapurnaThakur/python_code
/List/list6.py
462
3.609375
4
# a=["Anu", "Anjali", "Ankita", "Sumit", "Sanjay"] # print(a) # print() # b=["Thakur", "Sharma", "Singh", "Sinha", "Roy"] # # add=(name[0])+(t[0]),(name[2])+(t[2]) # # print(add) # add=(a[0])+(b[0]),(a[2])+(b[2]) # print(add) # c=[] # d=a[0:]+b # print(d) a=[1, 2, 3, 4] print(a) print() b=[6,8,9,8] [] print(b) for i in range(0,len(a)): add=a[i]*b[i] print(add, end=" ") # add=(a[3])*(b[3]),(a[2])*(b[2]) # print(add) # c=[] # d=a[0:]+b # print(d)
5bc2cd695264159aa44814e38a6e1f5db14e0584
AnnapurnaThakur/python_code
/All projects/anubating.py
713
3.796875
4
import sys while True: a=int(input("How many amount you want add : ")) c=0 while True: if a>0: b=int(input("how many amount you want invest : ")) if a>=b: a=a-b print("your aval. bal : ",a) c=c+b print("total investment :", c) else: print("insuficiant balance") else: d=input("You want to continue : (Y/N)") if d=='Y' or d=='y': break else: sys.exit(0)
29240ab6e69652738d220283183acb439879ada0
utsav-195/python-assignment
/problem1.py
1,003
3.875
4
def validate(password): condition = [0, 0, 0, 0, 1] # for testing all the four criterias for i in password: if ord(i) >= ord('A') and ord(i) <= ord('Z'): # checking for capital alphabet condition[0] = 1 elif ord(i) >= ord('a') and ord(i) <= ord('z'): # charcking for small alphabet condition[1] = 1 elif i.isdigit(): # checking for digit condition[2] = 1 elif i == '$' or i == '#' or i == '@': # checking for special symbols condition[3] = 1 else: # if character other then the mentioned conditionsL condition[4] = 1 # print(condition) if 0 in condition: print("not valid") else: if len(password) >= 6 and len(password) <= 12: print("valid") else: print("Password too long!!") return def main(): s = raw_input("Enter password: ") validate(s) if __name__ == '__main__': main()
f1c745b6786930254c938f7be7afbab341253872
roguishmountain/dailyprogrammer
/challenge228.py
536
3.75
4
lwords = ['billowy', 'biopsy', 'chinos', 'defaced', 'chintz', 'sponged', 'bijoux', 'abhors', 'fiddle', 'begins', 'chimps', 'wronged'] for word in range(len(lwords)): bInOrder = True bRInOrder = True for char in range(len(lwords[word])-1): if lwords[word][char] > lwords[word][char+1]: bInOrder = False elif lwords[word][char] < lwords[word][char+1]: bRInOrder = False if bInOrder: print lwords[word], 'IN ORDER' elif bRInOrder: print lwords[word], 'REVERSE IN ORDER' else: print lwords[word], 'NOT IN ORDER'
6e39b7628ea2e62d8a0da616c94ccb8195d73cc6
MalachiBlackburn/CSC121new
/functions.py
1,597
4.0625
4
def addition(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) add=first+second print(first, "+", second, "=", add) def subtraction(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) sub=first-second print(first, "-", second, "=", sub) def multiplication(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) mult=first*second print(first, "*", second, "=", mult) def division(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) div=first/second print(first, "/", second, "=", div) def integerdivision(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) intdiv=first//second print(first, "//", second, "=", intdiv) def torus(): majorradius=float(input("Enter your major radius: ")) minorradius=float(input("Enter your minor radius: ")) if majorradius <= minorradius: print("Major radius must be larger than the minor radius") torus() else: torusminor=(math.pi)*((minorradius)*(minorradius)) torusmajor=(2*math.pi)*(majorradius) torusfinal= (torusminor)*(torusmajor) print("The volume of the torus is:", torusfinal) def square(): side=int(input("Enter the length of one side of the square: ")) squarearea=side*side print("The area of the square is: ", squarearea)
ed0df19d54dd286b6996146454fa108b3d73adf3
tinayating/Leetcode
/Python/121. Best Time to Buy and Sell Stock.py
465
3.53125
4
import math class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) == 0: return 0 minPrice, maxProfit = prices[0], -math.inf for p in prices: minPrice = min(p, minPrice) profit = p - minPrice maxProfit = max(profit, maxProfit) return maxProfit
195d83bbefa65c664cbbbc9446984ba007e3d81c
valerio-oliveira/edx_cd50_python_javascript
/03_python/loops.py
78
3.734375
4
# a basic loop #for i in [0,1,2,3,4,5]: for i in range(10,15): print (i)
46af2af08a021f4a646df6debfe9a6fd28843d0d
awstown/PHYS200
/Chapter12/Chapter12.py
1,983
4.0625
4
# -*- coding: utf-8 -*- # Chapter 12 Exercises: 12.1, 12.2, 12.3 # Dwight Townsend # Phys 400 - Spring 2012 - Cal Poly Physics # imports import random # Exerise 12.1 def sumall(*args): return sum(args) print sumall(1, 3, 5, 7, 9) # Exercise 12.2 def sort_by_length(words): t = [] for word in words: t.append((len(word), random.random(), word)) t.sort(reverse=True) res = [] for length, rand, word in t: res.append(word) return res print sort_by_length(['hello','world', 'it', 'is', 'hot', 'in', 'here']) # Exercise 12.3 english = 'Buddhism can be confusing to begin with, especially if you come from a Christian, Islamitic or Jewish background. You may be unfamiliar with concepts such as karma, rebirth, emptiness and the practice of meditation. On top of that, the presentation of Buddhism in the various traditions can vary quite a bit, so if you read materials from different traditions, it is easy to lose track.' german = 'Buddhismus kann verwirrend sein, zu beginnen, besonders wenn Sie aus einer christlichen, jdischen oder islamitischen Hintergrund kommen. Sie drfen nicht vertraut sein mit Begriffen wie Karma, Wiedergeburt, "Leere" und die Praxis der Meditation. Hinzu kommt, dass kann der Prsentation des Buddhismus in den verschiedenen Traditionen variieren ziemlich viel, wenn Sie also Materialien von' french = 'Le bouddhisme peut tre source de confusion, pour commencer, surtout si vous venez d\'un chrtien, fond Islamitic ou juive. Vous pouvez ne pas tre familiers avec des concepts tels que le karma, la renaissance, vide et la pratique de la mditation.' def histogram(s): d = dict() for c in s: d[c] = d.get(c,0) + 1 return d def most_frequent(string): d = histogram(string) t = [] for key, val in d.items(): t.append((val, key)) t.sort(reverse=True) res = [] for occur, letter in t: res.append(letter) print res most_frequent(german)
537ddca25824fd995727cbb026fecefa5bdcaf8b
wkomari/Lab_Python_04
/data_structures.py
1,383
4.40625
4
#lab 04 # example 1a groceries = ['bananas','strawberries','apples','bread'] groceries.append('champagne') print groceries # example1b groceries = ['bananas','strawberries','apples','bread'] groceries.append('champagne') # add champagne to the list of groceries groceries.remove('bread') # remove bread from the list of groceries print groceries # example 1c groceries = ['bananas','strawberries','apples','bread'] groceries.append('champagne') # add champagne to the list of groceries groceries.remove('bread') # remove bread from the list of groceries groceries.sort() print groceries # example 2a print 'Dictionary would be used as the data type' dict = {'Apples':'7.3','Bananas':'5.5','Bread':'1.0','Carrot':'10.0','Champagne':'20.90','Strawberries':'32.6'} print 'Apple is', dict['Apples'] dict['Strawberries'] = 63.43 print 'The price of Strawberries in winter now is', dict['Strawberries'] # updated strawberries price dict['chicken'] = 6.5 print dict # prints all entries in the dictionary print 'Hehe customers we have chicken now in stock at', dict['chicken'] #example3 in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries') always_in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries') print 'Come to shoprite! We always sell:\n', always_in_stock[0:6] for i in always_in_stock: print i #example4
39c80f04366d2381fa04b4b851cca2ba58a1cb26
Only8Bytes/Python-Programs
/Final Project.py
1,837
3.703125
4
import operator def palindrome(a): if str(a) == str(a)[::-1]: return "yes" return "no" def nearPrime(a): val = 0 for i in range(2, int(a) - 1): if (int(a)/i) % 1 == 0 and int(a)/i != i: val += 1 if val > 2: return "no" return "yes" def upNum(a): a = list(a) val = None for x in a: if val == None or int(x) >= val: val = int(x) else: return "no" return "yes" def downNum(a): a = list(a) val = None for x in a: if val == None or int(x) <= val: val = int(x) else: return "no" return "yes" def upDownNum(a): a = list(a) val = None i = -1 for x in a: i += 1 if val == None or int(x) >= val: val = int(x) elif downNum(str.join("", a[i:len(a)])) == "yes": return "yes" else: return "no" return "no" def getScore(a, pal, nprime, nice): val = int(a) if pal: val *= 2 if nprime: val *= 2 if nice: val *= 3 return val Scores = {} Nums = str.split(input("Enter an integer: "), ",") for num in Nums: pal = False nprime = False nice = False if palindrome(num) == "yes": pal = True if nearPrime(num) == "yes": nprime = True if upNum(num) == "yes" or downNum(num) == "yes" or upDownNum(num) == "yes": nice = True score = getScore(num, pal, nprime, nice) if num not in Scores: Scores[num] = score else: Scores[str(num) + "Dupe"] = score SortedScores = sorted(Scores.items(), key = operator.itemgetter(1)) for x in SortedScores: print(str(x[0]) + "," + str(x[1]))
566a189b7b5fff577335764813be64f9dabfaaee
jayson-s/csci1030u
/Test1_Question4.py
278
3.546875
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 19 11:12:52 2017 @author: Jayson """ def drawParallelogram(numRows, numCols): for rows in range(numRows, 0, -1): print(' ' * (numRows - rows) + '*' * (numRows)) drawParallelogram(10, 8)
3c4f2f635ffb56ddec52a1ea4b0fb59fc9dafad5
jayson-s/csci1030u
/Test2_Question1a.py
769
3.796875
4
#Name: Jayson Sandhu #Student ID: 100659589 #Question 1a import math class Rectangle: def __init__(self, width, length): self.width = width self.length = length def getLength(self): return self.length def getWidth(self): return self.width def getArea(self): return self.width * self.length def getPerimeter(self): return self.width * 2 + self.length * 2 class Circle: def __init__(self,radius): self.radius = radius def getRadius(self): return self.radius def getArea(self): return math.pi * pow(self.radius,2) def getPerimeter(self): return 2 * math.pi * self.radius def main(): if __name__ == "__main__": main()
fcd2821ec8109d3270d9c73e4c06ace969bb7782
jayson-s/csci1030u
/Jayson_Lab6.py
5,276
3.921875
4
#Jayson Sandhu, 100659589 #Declare Variables and Initialize with values partyNames = ['Krogg', 'Glinda', 'Geoffrey'] partyHP = [180, 120, 150] partyAttack = [20, 5, 15] partyDefense = [20, 20, 15] partyDead = [False, False, False] bossAttack = 25 bossDefense = 25 bossHP = 500 round = 1 class Character: """ Character This class represents all of the data and behaviour of a character in our game. """ def __init__(self, name, hp, xpGained, attack, defense, magic=0): """ __init__(self, name, hp, attack, defense, magic) This constructor initializes all of the instance variables of our class @arg self The character object being initialized @arg name The name of the character @arg hp The remaining hitpoints of the character @arg xp The amount of xp that has been collected so far, which is initialized to 0 @arg xpGained The XP that would be gained by defeating the character @arg attack The attack power of the character @arg defense The defense power of the character @arg magic The magic power of the character (optional, default: 0) @arg level The current level of the character, which is initialized to 1 """ self.name = name self.hp = hp self.xp = 0 self.xpGained = xpGained self.maxhp = hp self.attackpower = attack self.defensepower = defense self.magic = magic self.level = 1 #Output round sequences while the HP for the Boss is greater than 0 while (bossHP > 0 or partyHP == 0): print ("Round", round) round = round + 1 print ("Krogg does", partyAttack [0], " points of damage to Boss") bossHP = bossHP - partyAttack [0] print ("Geoffrey does", partyAttack [2], " points of damage to Boss") bossHP = bossHP - partyAttack [2] partyHP  = partyHP + 5 isPartyDead(partyHP[]) #Once Boss HP is less than 0, output the following statements based in which case is true if (bossHP <= 0): print ("The boss is dead. You are victorious!") else: print ("Your whole party is dead. You lose.") def isPartyDead(party[]): """ isPartyDeadDead(party[]) This function returns True if the party is dead @arg party[] The Party's HP in the array we want to check """ if (party[] <= 0): return true else: return false def isDead(partyHP[]): """ isDead(partyHP[]) This function returns True if the character is dead @arg partyHP[] The character's HP in the party we want to check """ i=0 if partyHP[i] <= 0: return True else: return False def attack(self, otherCharacter): """ attack(self, otherCharacter) This function simulates an attack from this character ('self') to 'otherCharacter'. The other character's HP is updated with the damage taken. @arg self The character that is attacking @arg otherCharacter The target of the attack """ if self.isDead(): print(self.name, 'cannot attack because he/she is dead.') else: damage = self.attackpower - otherCharacter.defensepower otherCharacter.hp -= damage if otherCharacter.hp < 0: otherCharacter.hp = 0 print(self.name, 'does', damage, 'points of damage to', otherCharacter.name) def heal(self, party): """ heal(self, party) This function simulates a healing spell. The HP of the entire party is updated. @arg self The character that is healing @arg party The list of party members being healed """ if self.isDead(): print(self.name, 'cannot heal because he/she is dead.') else: for partyMember in party: if not partyMember.isDead(): partyMember.hp += self.magic if partyMember.hp > partyMember.maxhp: partyMember.hp = partyMember.maxhp print(self.name, 'heals', self.magic, 'hp for', partyMember.name) def __str__(self): """ __str__(self) This function returns a string representation of our character @arg self The character that is being represented @return The string representation of the character """ return self.name + ' has ' + str(self.hp) + ' HP.' return self.name + ' has ' + str(self.maxhp) + ' max HP.' return self.name + ' has ' + str(self.attackpower) + ' attack power.' return self.name + ' has ' + str(self.defensepower) + ' defense power.' return self.name + ' has ' + str(self.magic) + ' magic points.' return self.name + ' has gained ' + str(self.xpGained) + ' XP.'
fcbe70e27eaba61f35abb918ffcb7cc55bd11066
nhan1361992/python
/helloworld.py
137
3.671875
4
print ("begin") arrs = [] for i in range(20,35) : if ((i%7 == 0) and (i%5 != 0)) : arrs.append(str(i)) print(','.join(arrs))
84e31e9c440bdcc0b6e101ee8739a721f388ce07
GurmanBhullar/hactoberfest-Projects-2020
/Hackerrank-Python/designerdoormat.py
512
3.890625
4
# Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: # Mat size must be X. ( is an odd natural number, and is times .) # The design should have 'WELCOME' written in the center. # The design pattern should only use |, . and - characters. n, m = map(int, input().split()) for i in range(1, n, 2): print((".|."*i).center(m, "-")) print(("WELCOME").center(m, "-")) for i in range(n-2, -1, -2): print((".|."*i).center(m, "-"))
555913911bc903f7d407f39009ac136e3e281f72
GurmanBhullar/hactoberfest-Projects-2020
/Hackerrank-Python/Find angle MBC.py
210
3.96875
4
from math import acos, degrees, sqrt AB = int(input()) BC = int(input()) AC = sqrt(AB*AB + BC*BC) BM = AC / 2 angel = round(degrees(acos((BC * BC + BM * BM - BM * BM) / (2.0 * BM * BC)))) print(str(angel)+'°')
075c6e5733adf3dec09c3337f42806a51ed524ad
mohamed-minawi/KNN-LLS
/KNN.py
1,310
3.84375
4
import numpy as np class KNN(object): def __init__(self): pass def train(self, Data, Label): """ X is N x D where each row is an example. Y is 1-dimension of size N """ # the nearest neighbor classifier simply remembers all the training data self.train_data = Data self.train_labels = Label def predict(self, test_data, l='L1', k=1): """ X is N x D where each row is an example we wish to predict label for """ num_test = test_data.shape[0] # lets make sure that the output type matches the input type Ypred = np.zeros(num_test, dtype=self.train_labels.dtype) # loop over all test rows for i in range(num_test): # find the nearest training example to the i'th test example if l == 'L1': # using the L1 distance (sum of absolute value differences) distances = np.sum(np.abs(self.train_data - test_data[i, :]), axis=1) else: distances = np.sqrt(np.sum(np.square(self.train_data - test_data[i, :]),axis=1)) closelabels = self.train_labels[distances.argsort()[:k]] count = np.bincount(closelabels); Ypred[i] = np.argmax(count) print(k,": Test ", i," done ") return Ypred
db7b6be5a8c25fff421436696ad1d332fa367a66
CamiloSaboA-csv/problemas_HackerRank
/Strings_Making_Anagrams.py
352
3.609375
4
def makeAnagram(a, b): # Write your code here from collections import Counter a,b=list(sorted(a)),list(sorted(b)) a_count=Counter(a) b_count=Counter(b) x=((b_count-a_count)+(a_count-b_count)).values() x=sum(x) return x a,b= 'faacrxzwscanmligyxyvym','jaaxwtrhvujlmrpdoqbisbwhmgpmeoke' #a,b='aaaaaaabc','aaaaabde' x=100000000 x=makeAnagram(a,b) print(x)
262ec8a9fc2241422d79720605e903e873c25d4e
BLOODMAGEBURT/exercise100
/data-structure/sort-search/5.9.插入排序.py
1,522
3.96875
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: 5.9.插入排序 Description : Author : Administrator date: 2019/10/12 0012 ------------------------------------------------- Change Activity: 2019/10/12 0012: ------------------------------------------------- """ def insertion_sort(alist): size = len(alist) # 先循环获取从第二项到最后一项 for i in range(1, size): current_value = alist[i] for j in range(i - 1, -1, -1): # 将值依次与前方的数字做比较, 如果比前一项小,则前一项往后移一位,直到比前一项大为止 if alist[j] > current_value: alist[j + 1] = alist[j] # 需要注意如果比第一项大的时候 if j == 0: alist[0] = current_value else: alist[j + 1] = current_value break return alist def insertion_sort2(alist): """ 使用while的方式 :param alist: :return: """ for index in range(1, len(alist)): current_value = alist[index] position = index while position > 0 and alist[position - 1] > current_value: alist[position] = alist[position - 1] position -= 1 alist[position] = current_value return alist if __name__ == '__main__': alist = [45, 20, 15, 30, 25, 10] print(insertion_sort2(alist))
b1ab6571086c0867dabdfee9970348aee716dbe5
BLOODMAGEBURT/exercise100
/exercise/exercise5.py
532
3.9375
4
# -*- coding: utf-8 -*- def sort_method(alist): """ 给一个list排序,从小到大 :param alist: :return: """ assert isinstance(alist, list) new_list = sorted(alist) return new_list if __name__ == '__main__': print(sort_method([2, 7, 5, 10, 4])) """ 按学生年龄大小排队,从小到大 """ students = [('burt', 20), ('tom', 23), ('jean', 21), ('jack', 19)] sorted_students = sorted(students, key=lambda x: x[1]) print('sorted_students:', sorted_students)
3fb4a522861fca51b2f54d48c9cc9c28120280aa
BLOODMAGEBURT/exercise100
/exercise/exercise12.py
988
3.921875
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: exercise12 Description : Author : burt date: 2018/11/7 ------------------------------------------------- Change Activity: 2018/11/7: ------------------------------------------------- """ import math def count_su(x, y): """ 计算x,y之间有多少个素数 素数定义:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数 :param x: :param y: :return: """ prime_num = [] for i in range(x, y): count = 0 for j in range(2, int(math.sqrt(i)) + 1): if i % j == 0: count += 1 break if count == 0: prime_num.append(i) return prime_num, len(prime_num) if __name__ == '__main__': result = count_su(100, 200) print(result[0], '共有%d个' % (result[1],))
4712a8abf07cb2927fbb8695e3764f0590e87dd9
BLOODMAGEBURT/exercise100
/exercise/exercise7.py
583
3.75
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: exercise7 Description : Author : burt date: 2018/11/6 ------------------------------------------------- Change Activity: 2018/11/6: ------------------------------------------------- """ def list_copy(): """ 复制alist 到 blist 中 :return: """ if __name__ == '__main__': list_a = [1, 2, 3, 4] list_b = list_a[:] list_a.append(5) print('list_a是:{}-------list_b是:{}'.format(list_a, list_b))