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
b33e6d93be650bfcfe25852ffd17b411915c7d4f
ghmkt/3th_EDU
/Session03_Python_element_3/Session03_Quest_answer_3.py
1,838
3.609375
4
# 클래스 연습문제 class stock_analysis: def __init__(self, code): try: with open("c:\\Users\\LYJ\\Desktop\\파이썬세션데이터\\{0}.csv".format(code)) as f: self.lines = f.readlines() except FileNotFoundError: print("{0} 파일을 로드하는데 실패했습니다".format(code)) else: self.len = len(self.lines) self.latest_close = int(self.lines[-1].split(',')[4]) self.latest_open = int(self.lines[-1].split(',')[1]) self.latest_low = int(self.lines[-1].split(',')[2]) self.latest_high = int(self.lines[-1].split(',')[3]) def close_mean(self): close = [int(line.split(',')[4]) for line in self.lines[1:]] return (sum(close) // len(close)) def close_variance(self): return sum([(int(line.split(',')[4]) - self.close_mean())**2 for line in self.lines[1:]]) / len(self.lines[1:]) def close_std(self): return self.close_variance()**0.5 def volume_mean(self): volume = [int(line.split(',')[5].strip()) for line in self.lines[1:]] return (sum(volume) // len(volume)) def MA5(self): MA5_dict = {} for i in range(5,self.len): MA5_dict[self.lines[i].split(',')[0]] = sum([int(self.lines[i].split(',')[4]) for i in range(i-4,i+1)]) / 5 return MA5_dict # 판다스 연습문제 import pandas as pd df = pd.read_csv("c:\\Users\\LYJ\\Desktop\\파이썬세션데이터\\네이버_new.csv", engine='python') # 1번 df["종가"] = df["종가"].apply(lambda x: x*(-1)) # 2번 df['상승폭'] = ((df['종가'] - df['시가'])/df['시가']) * 100 # 3번 # 범위에 맞게 적절히 수정 print(df['종가'][30:60]) # 4번 vol_mean = df['거래량'].mean() print(df[df['거래량'] > vol_mean * 1.5]['종가'].mean())
5c9da03dc72008401f422d092f27b27bedd28177
AspenH/K-Nearest-Neighbor-Algorithm
/knn.py
3,625
3.78125
4
# Programmed by Aspen Henry # This program uses two .csv files within its directory (trainging data and test sample data) # to classify test samples using the K Nearest Neighbor algorithm. import math #This function is used to preformat the csv files for use #It assumes that the csv is in the form [class_label, a1, a2, ..., an] #with the first row of data in the csv being lables for columns def preformat(fileName): with open(fileName) as file: contents = file.readlines() for i in range(len(contents)): contents[i] = contents[i][:-1] contents[i] = contents[i].split(',') for i in range(1, len(contents)): for j in range(len(contents[i])): contents[i][j] = int(contents[i][j]) return contents #Function for calculating the Euclidean Distance def getDistance(x1, x2): distance = 0 for i in range(1, len(x1)): distance += math.pow((x1[i] - x2[i]), 2) return math.sqrt(distance) #Function for getting the output class of the test sample with KNN def KNN(trainingData, tup, k): neighborDistances = [20000]*k neighborClasses = [None]*k #Calculating the k closest distances and storing the corresponding classes for data in trainingData: if(isinstance(data[0], str)): continue distance = getDistance(tup, data) if(all(i < distance for i in neighborDistances)): continue else: del neighborClasses[neighborDistances.index(max(neighborDistances))] neighborClasses.append(data[0]) neighborDistances.remove(max(neighborDistances)) neighborDistances.append(distance) #Calculating the votes (weights) for each class by using a summation of (1 / distance) classVotes = {} for i in range(len(neighborClasses)): if (neighborClasses[i] not in classVotes.keys()): classVotes[neighborClasses[i]] = (1 / neighborDistances[i]) else: classVotes[neighborClasses[i]] += (1 / neighborDistances[i]) for cj, weight in classVotes.items(): if (weight == max(classVotes.values())): return cj #Driver function for performing the analysis and classification def main(): trainingFileName = "MNIST_train.csv" trainingData = preformat(trainingFileName) testFileName = "MNIST_test.csv" testData = preformat(testFileName) k = 7 #Classifying test data and finding statistics for analysis desiredClasses = [] computedClasses = [] for test in testData: if(isinstance(test[0], str)): continue desiredClasses.append(test[0]) computedClasses.append(KNN(trainingData, test, k)) correctClassifications = 0; totalClassifications = 0; for i in range(len(desiredClasses)): totalClassifications += 1 if (desiredClasses[i] == computedClasses[i]): correctClassifications += 1 accuracy = (correctClassifications / totalClassifications) * 100 missedClassifications = totalClassifications - correctClassifications #Printing the output print("\nK = " + str(k) + '\n') for i in range(len(desiredClasses)): print("Desired class: " + str(desiredClasses[i]) + " computed class: " + str(computedClasses[i])) print("\nAccuracy rate: " + str(accuracy) + "%" +'\n') print("Number of misclassified test samples: " + str(missedClassifications) + '\n') print("total number of test samples: " + str(totalClassifications)) #print(KNN(trainingData, testData[34], k)) if __name__ == "__main__": main()
df3157fb21a7d9d35fdd8ce4550733a859f3a64c
Potrik98/plab2
/proj5/fsm/utils.py
166
3.625
4
# # Check if a string is an integer # def is_int(string: str) -> bool: try: int(string) return True except ValueError: return False
c259e8f8f0be2ae221e13062855d370df14d9691
Potrik98/plab2
/proj3/crypto/AffineCipher.py
1,281
3.5
4
from crypto.SimpleCipher import SimpleCipher from crypto.Cipher import Cipher, alphabet, alphabet_length from crypto.MultiplicationCipher import MultiplicationCipher from crypto.CaesarCipher import CaesarCipher class AffineCipher(SimpleCipher): class Key(Cipher.Key): def __init__(self, caesar_key: CaesarCipher.Key, multiplication_key: MultiplicationCipher.Key): self._caesar_key = caesar_key self._multiplication_key = multiplication_key def __str__(self): return "Affine key: %s %s" % (str(self._caesar_key), str(self._multiplication_key)) def __init__(self): super().__init__() self._caesar_cipher = CaesarCipher() self._multiplication_cipher = MultiplicationCipher() def set_key(self, key: Key): self._caesar_cipher.set_key(key._caesar_key) self._multiplication_cipher.set_key(key._multiplication_key) def _encrypt_character(self, char): return self._caesar_cipher._encrypt_character( self._multiplication_cipher._encrypt_character(char)) def _decrypt_character(self, char): return self._multiplication_cipher._decrypt_character( self._caesar_cipher._decrypt_character(char))
ec44a59c2bfda5f812b86363dd4ad98c114361a1
yashmalik23/python-domain-hackerrank
/the minion game.py
339
3.515625
4
def minion_game(s): vowels = 'AEIOU' kev = 0 stu = 0 for i in range(len(s)): if s[i] in vowels: kev += (len(s)-i) else: stu += (len(s)-i) if kev > stu: print ("Kevin", kev) elif kev < stu: print ("Stuart", stu) else: print ("Draw")
7ebd2319068650b767db0961f553832b4af556b1
PythonHacker199/Bargraph-3d-
/main.py
541
4.09375
4
# Hi gus #welcome to hacker python channel # today we will learn how to make bar graph #we need to install matplotlib package from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig=plt.figure() ax1=fig.add_subplot(111,projection='3d') xpos=[1,2,3,4,5,6,7,8,9,10] ypos=[1,2,3,4,5,1,6,8,2,1] zpos=[0,0,0,0,0,0,0,0,0,0] num_elements=len(xpos) dx=np.ones(10) dy=np.ones(10) dz=[2,4,1,6,4,8,0,2,3,2] ax1.bar3d(xpos,ypos,zpos,dx,dy,dz,color='#26ffe6') plt.show() # so guys thank you and have a great day
2b908cba6c3ff6eea86011228e03224a22bec643
Kenneth-Fries/Kenneth_Fries
/Pairs 2-25-19 best path.py
5,195
4.25
4
"""The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. -2 (K) -3 3 -5 -10 1 10 30 -5 (P) Note: The knight's health has no upper bound. Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. """ import itertools import time dungeon1 = [[-2,-3,3],[-5,-10,1],[10,30,-5]] dungeon2 = [[1,-4,5,-99],[2,-2,-2,-1]] dungeon4 = [[-2,-3,3,-4],[-5,-10,1,2],[10,30,-5,-3]] dungeon5 = [[-2,-3,3,3,5],[-5,-10,1,-3,-2],[10,30,-5,5,3],[10,30,-5,5,3],[10,30,-5,5,3]] dungeon6 = [[-2,-3,3,3,5,6],[-5,-10,1,-3,-2,3],[10,30,-5,5,3,-1],[10,30,-5,5,3,-4],[10,30,-5,5,3,-19],[11,20,-5,5,3,-19]] dungeon7 = [[-2,-3,3,3,5,6,5],[-5,-10,1,-3,-2,3,84,-6],[10,30,-5,5,3,-1,-11,-10],[10,30,-5,5,3,-4,10,-3],[10,30,-5,5,3,-19,5,-5],[-12,7,11,20,-5,5,3,-19],[-4,7,11,20,-5,5,3,-19]] dungeon8 = [[0,-74,-47,-20,-23,-39,-48],[37,-30,37,-65,-82,28,-27],[-76,-33,7,42,3,49,-93],[37,-41,35,-16,-96,-56,38],[-52,19,-37,14,-65,-42,9],[5,-26,-30,-65,11,5,16],[-60,9,36,-36,41,-47,-86],[-22,19,-5,-41,-8,-96,-95]] """This is the slow brute force method. Faster method below.""" def calculateMinimumHP(dungeon): start = time.time() #so slow I was timing it width = len(dungeon)-1 height = len(dungeon[0])-1 direction_instructions = str() #producing a list of binary instructions for _ in range (width): direction_instructions += '1' #1 will mean go right for _ in range (height): direction_instructions += '0' #0 will mean go down direction = set() #get rid of duplicates using a set [direction.add(i) for i in itertools.permutations(direction_instructions, height + width)] direction = list(direction) #Make it iterable #the following goes through every path and calculates the life hit result_set = set() counter = 0 for x in direction: i = 0 j = 0 life = 0 trial = set() life += dungeon[i][j] #starting Square trial.add(life) #each amount of life gets updated to the trial list for y in x: counter += 1 #just to keep track of how many iterations for curiosity print(counter) if y == '1': # if the instruction is a 1 we go down i+= 1 else: #if the instruction is 0 we go right j += 1 #life starts at zero, and is life += dungeon[i][j] #updated every step trial.add(life) #trial value is added to a list or set result_set.add(min(trial)) #The min value is key to remember if max(result_set) > 0: #If you won't die going through maze print( 1) #The min start value would be 1 print(1-max(result_set)) #Otherwise it's this value. end = time.time() print("time = ",end - start) #This is for curiosity #calculateMinimumHP(dungeon1) #This take forever for large dungeons """The following second take at this challange produced a faster algorithm. I learned a better way of looking at his type of problem. """ def calculateMinimumHP2(dungeon): start = time.time() width = len(dungeon[0])-1 height = len(dungeon)-1 for i in range(height,-1,-1): for j in range(width,-1,-1): print('i',i,'j',j,'width',width,'height',height) [print(x) for x in dungeon] print('dungeon[i][j] = ',dungeon[i][j]) if i == height and j == width: dungeon[i][j] = max([1,1-dungeon[i][j]]) elif i == height: dungeon[i][j] = max([1,dungeon[i][j+1] - dungeon[i][j]]) elif j == width: dungeon[i][j] = max([1,dungeon[i+1][j] - dungeon[i][j]]) else: tempi = dungeon[i][j+1] - dungeon[i][j] tempj = dungeon[i+1][j] - dungeon[i][j] dungeon[i][j] = max(1,min([tempi,tempj])) end = time.time() print("time = ",end - start) #This is for curiosity return dungeon[0][0] calculateMinimumHP2(dungeon8)
27fd01141cf75a31a087b5fa5b47e7b203b0bdbd
FuelRats/pipsqueak3
/src/packages/utils/autocorrect.py
1,450
3.578125
4
""" autocorrect.py - Methodology to attempt auto-correcting a typo'd system name. Copyright (c) 2019 The Fuel Rat Mischief, All rights reserved. Licensed under the BSD 3-Clause License. See LICENSE.md This module is built on top of the Pydle system. """ import re def correct_system_name(system: str) -> str: """ Take a system name and attempt to correct common mistakes to get the true system name. Args: system (str): The system name to check for corrections. Returns: str: The system name with any corrections applied, uppercased. """ system = system.upper() match_regex = re.compile(r"(.*)\b([A-Z01258]{2}-[A-Z01258])\s+" r"([A-Z01258])\s*([0-9OIZSB]+(-[0-9OIZSB]+)?)\b") replacements = {k: v for k, v in zip('01258', 'OIZSB')} # Check to see if the provided system name follows the procedural format. matched = match_regex.match(system) if matched: sector = matched.group(1).strip() letters = f"{matched.group(2)} {matched.group(3)}" numbers = matched.group(4) for letter, number in replacements.items(): letters = letters.replace(letter, number) numbers = numbers.replace(number, letter) # Re-format the string to ensure no extraneous spaces are included. return f"{sector} {letters}{numbers}" # Don't try and correct a system that isn't procedurally named. return system
7c967ec0e9a7286ab5569133662f8966efcfd80b
coder-kiran/pythonCalculator
/pythonCalculatorByKK.py
10,311
3.625
4
# Python Calculator by Kiran K K from tkinter import * from tkinter.messagebox import * import math window = Tk() window.geometry("230x350") window.title("I Calculate") window.configure(bg='#000066') window.resizable(0,0) s0 = s1 = s2 = "" famous="" equalClickedOn = False font=('verdana',10) #------------------ function definitions------------------ def num0Clicked(): global famous global val global s0, s2, s1 if s1 != "": s2="" s2 = s2 + "0" famous=famous+s2 else: s0="" s0 = s0 + "0" famous=famous+s0 labelid.set(famous) def num1Clicked(): global famous global s0,s2,s1 if s1 != "": s2 = "" s2 = s2 + "1" famous = famous + s2 else: s0 = "" s0 = s0 + "1" famous = famous + s0 labelid.set(famous) def num2Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "2" famous = famous + s2 else: s0 = "" s0 = s0 + "2" famous = famous + s0 labelid.set(famous) def num3Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "3" famous = famous + s2 else: s0 = "" s0 = s0 + "3" famous = famous + s0 labelid.set(famous) def num4Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "4" famous = famous + s2 else: s0 = "" s0 = s0 + "4" famous = famous + s0 labelid.set(famous) def num5Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "5" famous = famous + s2 else: s0 = "" s0 = s0 + "5" famous = famous + s0 labelid.set(famous) def num6Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "6" famous = famous + s2 else: s0 = "" s0 = s0 + "6" famous = famous + s0 labelid.set(famous) def num7Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "7" famous = famous + s2 else: s0 = "" s0 = s0 + "7" famous = famous + s0 labelid.set(famous) def num8Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "8" famous = famous + s2 else: s0 = "" s0 = s0 + "8" famous = famous + s0 labelid.set(famous) def num9Clicked(): global famous global s0, s2, s1 if s1 != "": s2 = "" s2 = s2 + "9" famous = famous + s2 else: s0 = "" s0 = s0 + "9" famous = famous + s0 labelid.set(famous) def dotClicked(): global famous global s0, s2, s1 if s1 != "": s2="" s2 = s2 + "." famous = famous + s2 else: s0="" s0 = s0 + "." famous = famous + s0 labelid.set(famous) def addClicked(): global famous global s1 s1 = "+" famous=famous+s1 labelid.set(famous) def minusClicked(): global famous global s1 s1 = "-" famous = famous + s1 labelid.set(famous) def multClicked(): global famous global s1 s1 = "*" famous = famous + s1 labelid.set(famous) def divClicked(): global famous global s1 s1 = "/" famous = famous + s1 labelid.set(famous) def powerClicked(): global famous global s1 s1 = "^" famous=famous+s1 labelid.set(famous) def equalClicked(): try: global s0,s2 if s1 == "^": labelid.set(pow(int(s0),int(s2))) s0=s2="" else: global equalClickedOn answer=eval(famous) labelid.set("") labelid.set(answer) equalClickedOn = True except Exception as e: showerror("Error",e) def clearClicked(): global famous,s0,s1,s2 s0=s1=s2=famous="" labelid.set(famous) def backSpaceClicked(): global famous if equalClickedOn == False: lengthOfFamous = len(famous) - 1 newfamous = famous[0:lengthOfFamous] famous = newfamous labelid.set(famous) else: famous = "" labelid.set(famous) def squareRoot(): labelid.set(math.sqrt(int(labelid.get()))) def darkClicked(): window.config(bg="#000000") b0.config(bg='#663300') b1.config(bg='#000000') b2.config(bg='#000000') b3.config(bg='#000000') b4.config(bg='#000000') b5.config(bg='#000000') b6.config(bg='#000000') b7.config(bg='#000000') b8.config(bg='#000000') b9.config(bg='#000000') ba.config(bg='#333') bs.config(bg='#333') bd.config(bg='#333') bm.config(bg='#333') beq.config(bg='#006600') bc.config(bg='#660000') bdot.config(bg='#000000') bback.config(bg='#660000') bdark.config(bg='#000000') blight.config(bg='#000000') bsqrt.config(bg='#660000') bpower.config(bg='#000000') label.config(bg='#fff',fg='#333333') def lightClicked(): window.config(bg='#000066') b0.config(bg='#cc3300') b1.config(bg='#000066') b2.config(bg='#000066') b3.config(bg='#000066') b4.config(bg='#000066') b5.config(bg='#000066') b6.config(bg='#000066') b7.config(bg='#000066') b8.config(bg='#000066') b9.config(bg='#000066') ba.config(bg='#0066ff') bs.config(bg='#0066ff') bd.config(bg='#0066ff') bm.config(bg='#0066ff') beq.config(bg='#009900') bc.config(bg='#003399') bdot.config(bg='#000066') bback.config(bg='#003399') bdark.config(bg='#000066') blight.config(bg='#000066') bsqrt.config(bg='#003399') bpower.config(bg='#000066') label.config(bg='#fff') #------------------creating a text field------------------ labelid = StringVar() label = Label(window, text="", width=20, height=2,textvariable=labelid,padx=5,pady=10,anchor='e',font='verdana 12 ',fg='#000066') # ------------------creating buttons------------------ b0 = Button(window, text="0", width=5, height=2, command=num0Clicked,activebackground='#0000ff', activeforeground='#000000',bg='#cc3300',borderwidth=0,foreground='#fff',font=font) b1 = Button(window, text="1", width=5, height=2, command=num1Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b2 = Button(window, text="2", width=5, height=2, command=num2Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b3 = Button(window, text="3", width=5, height=2, command=num3Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b4 = Button(window, text="4", width=5, height=2, command=num4Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b5 = Button(window, text="5", width=5, height=2, command=num5Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b6 = Button(window, text="6", width=5, height=2, command=num6Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b7 = Button(window, text="7", width=5, height=2, command=num7Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b8 = Button(window, text="8", width=5, height=2, command=num8Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') b9 = Button(window, text="9", width=5, height=2, command=num9Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bd = Button(window, text="/", width=5, height=2,command=divClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bm = Button(window, text="x", width=5, height=2,command=multClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') ba = Button(window, text="+", width=5, height=2, command=addClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bs = Button(window, text="-", width=5, height=2,command=minusClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') beq = Button(window, text="=", width=5, height=2, command=equalClicked,bg='#009900',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bc = Button(window, text="C", width=5, height=2,command=clearClicked,bg='#003399',borderwidth=0,foreground='#fff',font=font ,activebackground='#0033ff') bdot = Button(window, text=".", width=5, height=2, command=dotClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bback = Button(window,text="back",width=5, height=2, command=backSpaceClicked,bg='#003399',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bpower = Button(window,text="^",width=5, height=2, command=powerClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bsqrt = Button(window,text="√",width=5, height=2, command=squareRoot,bg='#003399',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') bdark = Button(window,text="DARK",width=11, height=2, command=darkClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') blight = Button(window,text="LIGHT",width=11, height=2, command=lightClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff') #------------------ applying grid system to all elements------------------ label.grid(row=2, columnspan=4,pady=30,padx=7) bc.grid(row=4,column=0) bback.grid(row=4,column=1,) bsqrt.grid(row=4,column=2) bd.grid(row=4, column=3) b7.grid(row=5, column=0) b8.grid(row=5, column=1) b9.grid(row=5, column=2) bm.grid(row=5, column=3) b4.grid(row=6, column=0) b5.grid(row=6, column=1) b6.grid(row=6, column=2) bs.grid(row=6, column=3) b1.grid(row=7, column=0) b2.grid(row=7, column=1) b3.grid(row=7, column=2) ba.grid(row=7, column=3) b0.grid(row=8, column=1) bdot.grid(row=8, column=0) bpower.grid(row=8,column=2) beq.grid(row=8, column=3) bdark.grid(row=9,column=0,columnspan=2) blight.grid(row=9,column=2,columnspan=2) #------------------ execution of calculator ends here------------------ window.mainloop()
331ea7efc532c4d9f09da6b6497be679c91de9ff
layanabushaweesh/math-series
/tests/serises_test.py
1,828
3.65625
4
# testing fibonacci function :) from math_serises.serise import fibonacci def test_fib_0(): expected=0 actual=fibonacci(0) assert actual == expected def test_fib_1(): expected=1 actual=fibonacci(1) assert actual == expected def test_fib_2(): expected=1 actual=fibonacci(2) assert actual == expected def test_fib_3(): expected=2 actual=fibonacci(3) assert actual == expected # testing lucas function from math_serises.serise import lucas def test_luc_0(): excepted=2 actual=lucas(0) assert actual==excepted def test_luc_1(): excepted=1 actual=lucas(1) assert actual==excepted def test_luc_2(): excepted=3 actual=lucas(2) assert actual==excepted def test_luc_3(): excepted=4 actual=lucas(3) assert actual==excepted def test_luc_4(): excepted=7 actual=lucas(4) assert actual==excepted # testing sum function from math_serises.serise import sum_series # 1- Calling this function with no optional parameters will produce numbers from the fibonacci series. def test_sum_0(): excepted=0 actual=sum_series(0) assert actual == excepted def test_sum_1(): excepted=1 actual=sum_series(1) assert actual == excepted def test_sum_2(): excepted=1 actual=sum_series(2) assert actual == excepted # 2- Calling it with the optional arguments 2 and 1 will produce values from the lucas. def test_sum_lucas_0(): excepted=2 actual=sum_series(0,2,1) assert actual == excepted def test_sum_lucas_1(): excepted=1 actual=sum_series(1,2,1) assert actual == excepted def test_sum_lucas_2(): excepted=3 actual=sum_series(2,2,1) assert actual == excepted # 3- Other values for the optional parameters will produce other series. def test_sum_other_2(): actual=sum_series(2,2,3) excepted=5 # i gess assert actual == excepted
b6a2e295b45e45114c947f339cfae96b8faa8229
rompe/adventofcode2020
/src/day02.py
503
3.71875
4
#!/usr/bin/env python import itertools import sys def solution(input_file): """Solve today's riddle.""" lines = open(input_file).read().splitlines() valids = 0 for line in lines: count, char, password = line.split() char = char[0] lowest, highest = count.split('-') if (password[int(lowest) - 1] == char) ^ (password[int(highest) - 1] == char): valids += 1 print(valids) if __name__ == "__main__": sys.exit(solution(sys.argv[1]))
d0bca1738a9a21e3888084c65786e73bff22fe7d
CodecoolBP20161/python-pair-programming-exercises-4th-tw-miki_gyuri
/3-phone-numbers/main.py
1,266
3.796875
4
import csv import sys from person import Person def open_csv(file_name): with open(file_name, 'r') as phone_number: names_n_numbers = [line.split(",") for line in names_n_numbers.readlines()] numbers = [] numbers = numbers.digits for element in names_n_numbers: for i in element[1]: # get phone numbers from list elements # remove every non-digit characters return names_n_numbers def get_csv_file_name(argv_list): to_return = argv_list[1] # might need to tell that it's a string return to_return def format_output(person): # implent this function pass # delete this def get_person_by_phone_number(person_list, user_input_phone_number): for element in person_list: if user_input_phone_number == element[1]: return element[0] def main(): file_name = get_csv_file_name(sys.argv) if file_name is None: print('No database file was given.') sys.exit(0) person_list = open_csv(file_name) user_input_phone_number = input('Please enter the phone number: ') match_person = get_person_by_phone_number(person_list, user_input_phone_number) print(format_output(match_person)) if __name__ == '__main__': main()
f62b64433ab03f57cc107b63c7c853590be44a9f
koiku/nickname-generator
/main.py
1,028
3.640625
4
""" * 0 - Vowel letter * * 1 - Consonant letter """ import random VOWELS = ['a', 'e', 'i', 'o', 'u', 'y'] CONSONANTS = [ 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z' ] MIN_LEN = 3 MAX_LEN = 8 def main(): length = random.randint(MIN_LEN, MAX_LEN) nickname = "" prev_letter = -1 two_vowels = False for letter in range(length): if letter == 0: letter_type = random.randint(0, 1) prev_letter = letter_type if letter_type == 0: nickname += random.choice(VOWELS) two_vowels = False else: nickname += random.choice(CONSONANTS) two_vowels = False continue if prev_letter == 1: nickname += random.choice(VOWELS) prev_letter = 0 elif prev_letter == 0: letter_type = random.randint(0, 1) if letter_type == 0 and not two_vowels: nickname += random.choice(VOWELS) two_vowels = True else: nickname += random.choice(CONSONANTS) two_vowels = False print(nickname) if __name__ == "__main__": main()
d924bcfa89f8453db0f96e452469e2bbd15c21d3
ScottRWilson11/WebScrapingHW
/webscraping.py
889
3.546875
4
import pandas as pd from bs4 import BeautifulSoup import requests url1="https://www.nasa.gov/feature/jpl/nasas-next-mars-mission-to-investigate-interior-of-red-planet" r = requests.get(url1) data = r.text soup = BeautifulSoup(data, features="html.parser") news_title = soup.title.text print(news_title) tags = soup.find(attrs={"name":"dc.description"}) news_p = tags.get('content') print(news_p) url1 = "https://space-facts.com/mars/" page = requests.get(url1) data = page.text soup = BeautifulSoup(data, 'html.parser') table = soup.find_all("table") for mytable in table: table_body = mytable.find('tbody') rows = table_body.find_all('tr') for tr in rows: print ("<tr>") cols = tr.find_all('td') for td in cols: print ("<td>",td.text, "</td>") print ("</tr>") #df = pd.read_html(str(table))
64b86298ac0017b88bf25e6d658a6bc9b4c22d0a
panwuying/homework5
/work6.py
203
3.53125
4
a="4 4 213 123 124 1 123 " a=a.split() a=[int(x) for x in a] def all_list(b): c = min(b) for i in range(len(b)): if c==b[i]: print(i) break all_list(a)
96aa4c549c9a5341a565699832cdbbf30ff406e7
liweinan/hands_on_ml
/sort_class.py
982
4.125
4
from collections import OrderedDict class Student: def __init__(self, name, order): self.name = name self.order = order tom = Student("Tom", 0) jack = Student("Jack", 0) rose = Student("Rose", 1) lucy = Student("Lucy", 2) users = OrderedDict() users[rose.name] = rose users[lucy.name] = lucy users[jack.name] = jack users[tom.name] = tom # 接下来是转化users,让order变成key,然后让value是student数组 users2 = OrderedDict() for k, v in users.items(): if v.order not in users2.keys(): users2[v.order] = [] users2[v.order].append(v) # 然后是sort这个数组,生成一个新的dict: sorted_users = OrderedDict() sorted_keys = sorted(users2) for k in sorted_keys: for v in users2[k]: print(str(v.order) + ", " + v.name) sorted_users[v.name] = v # 这样,我们就得到了sorted_users: print("-=-=-=-=-=-=-=-=-=-=-=-=-=-") for k, v in sorted_users.items(): print(str(v.order) + ", " + k)
6c112be7a3443ebd31b68bfe73f424af50ca34af
abhishekshrestha008/Binary-and-Linear-Search-Algorithms
/searchMain.py
1,242
3.84375
4
import random from search import linear_search, binary_search from time import time import matplotlib.pyplot as plt elapsed_linear = [] elapsed_binary = [] x = [] for i in range(10000, 100000, 10000): #Data data = random.sample(range(i), i) sorted_data = sorted(data) random_number = random.randint(0,len(data)-1) #For Linear Search start_linear = time() index_linear = linear_search(data, random_number) end_linear = time() elapsed_linear.append((end_linear - start_linear)) #For Binary Search start_binary = time() index_binary = binary_search(sorted_data, 0, len(data)-1, random_number) end_binary = time() elapsed_binary.append((end_binary - start_binary)) x.append(i) plt.plot(x, elapsed_linear, label="linear_search") plt.plot(x, elapsed_binary, label="binary_search") plt.xlabel('Input size') plt.ylabel('Execution time') plt.title('Input size vs Execution-time graph') plt.legend() plt.show() print("The best case for linear_search is: {} ".format(min(elapsed_linear))) print("The worst case for linear_search is: {} ".format(max(elapsed_linear))) print("The best case for binary search is: {} ".format(min(elapsed_binary))) print("The worst case for binary search is: {} ".format(max(elapsed_binary)))
ebb33953daccc725fab8383a652c8fd60c181ff1
ferdirn/hello-python
/python_min.py
185
3.65625
4
#!/usr/bin/env python list1, list2 = ['xyz', 'abc', 'opq'], [8, 9, 3, 5, 6] print 'list1', list1 print 'list2', list2 print 'min(list1)', min(list1) print 'min(list2)', min(list2)
be66511c268ce38ea8d4e3ce561894c390bccbc2
ferdirn/hello-python
/hari.py
349
3.84375
4
#!/usr/bin/env python nama_hari = raw_input('Masukkan nama hari : ') if nama_hari == 'sabtu' or nama_hari == 'minggu': print 'Weekends' elif nama_hari == 'senin' or nama_hari == 'selasa' or nama_hari == 'rabu' or nama_hari == 'kamis': print 'Weekdays' elif nama_hari == "jum'at": print 'TGIF' else: print 'Nama hari tidak dikenal'
7937dba17b2af72fcedc087ce51375b73258e3e0
ferdirn/hello-python
/yourname.py
195
3.875
4
#!/usr/bin/env python firstname = raw_input('Your first name is ').strip() lastname = raw_input('Your last name is ').strip() print "Hello {} {}! Nice to see you...".format(firstname, lastname)
4de4ba9a0b6507c01147f52527413bfbf0305982
ferdirn/hello-python
/ternaryoperator.py
231
4.1875
4
#!/usr/bin/env python a = 1 b = 2 print 'a = ', a print 'b = ', b print '\n' #ternary operator print 'Ternary operator #1' print 'a > b' if (a > b) else 'b > a' print '\nTernary operator #2' print (a > b) and 'a > b' or 'b > a'
fc7b4eb2b4ffe1f9021b3cf27842600cdc88e098
ferdirn/hello-python
/bitwiseoperators.py
337
3.796875
4
#!/usr/bin/env python print 'binary of 5 is', bin(5)[2:] print 'binary of 12 is', bin(12)[2:] print '5 and 12 is', bin(5&12)[2:] print '5 or 12 is', bin(5|12)[2:] print '5 xor 12 is', bin(5^12)[2:] print 'not 5 is', bin(~5) print '2 shift left 5 is', bin(5<<2)[2:], ' or ', 5<<2 print '2 shift right 5 is', bin(5>>2)[2:], ' or ', 5>>2
986e29934e3ad5528978247f8eaf1be4173e10e3
ferdirn/hello-python
/comparison_operators.py
411
3.546875
4
#!/usr/bin/env python print 'is equal' print '10 == 20 ' + str(10 == 20) print '\nis not equal' print '10 != 20 ' + str(10 != 20) print '10 <> 20 ' + str(10 <> 20) print '\ngreater than' print '10 > 20 ' + str(10 > 20) print '\nless than' print '10 < 20 ' + str(10 < 20) print '\ngreater than or equal to' print '10 >= 20 '+ str(10 >= 20) print '\nless than or equal to' print '10 <= 20 ' + str(10 <= 20)
683501e8b36347e0fc89b461d33ca8ade2457895
ferdirn/hello-python
/kelvintofahrenheit.py
294
3.796875
4
#!/usr/bin/env python def KelvinToFahrenheit(temperature): assert (temperature >= 0), "Colder than absolute zero!" return ((temperature-273)*1.8)+32 try: print KelvinToFahrenheit(273) print KelvinToFahrenheit(-5) except AssertionError, e: print e.args print str(e)
4da324086fd2415baf3a247e24841560fc29a8b1
sharpvik/python-libs
/search.py
2,353
3.640625
4
# # ================================== BBBBBB YY YYY MMMM MMMM RRRRRR VV VVV RRRRRR # = THE = BBB BB YY YYY MMMMM MMMMM RRR RR VV VVV RRR RR # ===> Search functions library <=== BBBBBB YYYYY MMM MM MMM RRRRRR VV VVV RRRRRR # = (25.04.2018) = BBB BBB YYY MMM MMM RRR R VVVVV RRR R # ================================== BBBBBBBB YYY MMM MMM RRR RR VVV RRR RR # # My github --> https://www.github.com/sharpvik <-- # # functions ## --> binary search def binary(array, element): # array(list) -- list of numbers; element(int / float) -- number you are searching for; # --> function returns index of element if found, ohterwise returns -1; array.sort() # sort the array just in case; low = 0 # low(int) -- lowest searching limit; high = len(array) - 1 # high(int) -- highest searching limit; index = -1 # index(int) -- index of the element if found, otherwise = -1; position = high // 2 # position(int) -- the index we're testing; while low < high: if element == array[position]: index = position return index elif element < array[position]: high = position - 1 else: low = position + 1 position = (high - low) // 2 + low else: if low == high and element == array[low]: index = low return index ## binary search <-- ## --> linear search def linear(array, element, count=1): # array(list) -- any list; element(any type) -- element you are searching for; # count(int) -- number of indexes saved before returning the answer; indexes = [] i = 0 while i < len(array) and len(indexes) < count: if array[i] == element: indexes.append(i) i += 1 if len(indexes) == 0: return -1 elif len(indexes) == 1: return indexes[0] else: return indexes ## linear search <--
fb89441290c0ebb8992bbe6ac22ef88da84b0afd
sharpvik/python-libs
/graphD.py
5,155
3.734375
4
# # =============================== BBBBBB YY YYY MMMM MMMM RRRRRR VV VVV RRRRRR # = THE = BBB BB YY YYY MMMMM MMMMM RRR RR VV VVV RRR RR # ===> Graph class <=== BBBBBB YYYYY MMM MM MMM RRRRRR VV VVV RRRRRR # = (10.05.2018) = BBB BBB YYY MMM MMM RRR R VVVVV RRR R # =============================== BBBBBBBB YYY MMM MMM RRR RR VVV RRR RR # # My github --> https://www.github.com/sharpvik <-- # from stackD import Stack from queueD import Queue class Graph: # undirected graph; no values for the edges; def __init__(self): self.nodes_dict = dict() def node_add(self, name): # name(int / str) -- name of the node; if name not in self.nodes_dict: self.nodes_dict.update( { name : list() } ) return name def node_del(self, name): # name(int / str) -- name of the node; self.nodes_dict.pop(name, None) for each in self.nodes_dict: try: self.nodes_dict[each].remove(name) except ValueError: print( "WARNING: {} does not exist!".format(name) ) return name def connection_add(self, one, two): # one(int / str) and two(int / str) -- two nodes you want to connect; if two not in self.nodes_dict[one]: self.nodes_dict[one].append(two) if one not in self.nodes_dict[two]: self.nodes_dict[two].append(one) return [one, two] def connection_del(self, one, two): # one(int / str) and two(int / str) -- two nodes you want to disconnect; try: self.nodes_dict[one].remove(two) except ValueError: print( "WARNING: {} does not have a connection to {}!".format(two, one) ) try: self.nodes_dict[two].remove(one) except ValueError: print( "WARNING: {} does not have a connection to {}!".format(one, two) ) return [one, two] def nodes_count(self): # --> function returns the number of nodes in the graph; return len(self.nodes_dict) def nodes_return(self): # --> function returns the whole dict containing nodes and their connections; return self.nodes_dict def node_con_return(self, name): # name(int / str) -- name of the node you're checking; # --> function returns connections of the given node; return self.nodes_dict[name] # search ## --> breadth first search using class Queue def bfs( self, final, queue=Queue(None), checked=list() ): # final(int / str) -- name of the node you're trying to establish connection with; # queue(class Queue) -- Queue containing the element you are beginning with (format: element); # checked(list) -- leave empty *** internal use ***; # --> function returns True if the two nodes are connected, otherwise it returns False; _checked = list(checked) if queue.is_empty(): return False temp = queue.pop() if temp == final: return True else: _checked.append(temp) for child in self.node_con_return(temp): if child not in _checked and not queue.inside(child): queue.push(child) return self.bfs(final, queue, _checked) ## breadth first search using class Queue <-- ## --> depth first serach using class Stack def dfs( self, final, stack=Stack(None), checked=list() ): # final(int / str) -- name of the node you're trying to establish connection with; # stack(class Stack) -- Stack containing the element you are beginning with (format: element); # checked(list) -- leave empty *** internal use ***; # --> function returns True if the two nodes are connected, otherwise it returns False; _checked = list(checked) if stack.is_empty(): return False temp = stack.pop() if temp == final: return True else: _checked.append(temp) for child in self.node_con_return(temp): if child not in _checked and not stack.inside(child): stack.push(child) return self.dfs(final, stack, _checked) ## depth first serach using class Stack <--
55075c4e6d4561690da93b466a2f1a7c2319be64
MMahoney6713/cs50
/pset6-Python/credit.py
243
3.640625
4
card = input('Card Number? ') var = 0 for i in range(1, length(card), 2): value = int(card(i)) * 2 if value > 9: value = str(value) value = int(value[1]) + int(value([2]) var += value print(f"{round_1_sum}")
4b089ecb061076b81df93e125f0b86f259b3197d
bognan/training_python
/guess the random namber/random number from computer.py
1,121
3.703125
4
import random number = random.randint(1, 100) users_count = int(input('Введите количество игроков: ')) users_list = [] for i in range(users_count): user_name = (input(f'Введите имя игрока {i}: ')) users_list.append(user_name) count = 1 levels = {1: 10, 2: 5, 3: 3} level = int(input('Выбирете уровень сложности: ')) max_count = levels[level] is_winner = False winner_name = None while not is_winner: count += 1 if count > max_count: print('Все игроки проиграли') break for user in users_list: print(f'Ход игрока {user}') user_number = int(input(f'{user} введите ваше число: ', )) if number == user_number: is_winner = True winner_name = user break elif number < user_number: print('Ваше число больше') else: print('Ваше число меньше') else: print(f'Вы угадали число c {count} попыток. {winner_name} победил!')
2bc2bbc4f60dddbef026efbc41a63ab24182cd25
bognan/training_python
/HW/HW№2.py
234
4.03125
4
number = int(input('Введите любое число: ',)) while (number > 10) or (number < 0): number = int(input('Побробуйте еще: ',)) else: if number <= 10: print('Результат:', number ** 2)
4415824dde9566902bf6a7bb9015764785597c02
mateusPreste/Testing
/Testing/Plot.py
202
3.65625
4
from matplotlib.pyplot import * import numpy as np def f(t): return t**2*np.exp(-t**2) t = np.linspace(0, 3, 310) y = np.zeros(len(t)) for i in range(len(t)): y[i] = f(t[i]) plot(t, y) show()
6b94e8638f16b58df5460af29cb8f13e2a8e53bc
mittalpranjal12/Basic-Python-Codes
/swap_two_numbers.py
312
4.09375
4
#swap two numbers x = int(input("Enter first number: x= ")) y = int(input("Enter second number: y= ")) print("Value of x and y before swapping is {0} and {1}" .format(x,y)) #swapping using temp temp = x x = y y = temp print("\nThe value of x and y after swapping is {0} and {1}" .format(x ,y))
9392258cba43a64ce272d77ab90b889c020946d9
LorenBristow/module3
/ch04_UnitTesting/is_prime.py
1,237
3.875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 10:00:27 2019 @author: loren """ #### TASK 1 - PRIME NUMBERS to FAIL & TASK 2 - to PASS #### def is_prime(number): '''Return True if number is a prime number''' if number <= 1: return False elif number > 1:#to prevent div by 0 error for each in range(2,number): if number % each == 0 and number != each: print("false") return False return True else: print("weird") def print_next_prime(number): ##something still wrong here. '''If number is prime, provide next prime number''' next_number = number while is_prime(number) == True: next_number += 1 if is_prime(next_number) == True: print("After {}, the next prime number is {}".format(number, next_number)) return number ### TASK 4 - Count Words ### def wordcount(text): wordcount_dictionary = {} words = text.split() for word in words: if word in wordcount_dictionary: wordcount_dictionary[word] = wordcount_dictionary[word] + 1 else: wordcount_dictionary[word] = 1 return wordcount_dictionary wordcount('foo bar foo')
771b2e1c61a2466875e9b9ed32ba91d9c7625e01
ChChLance/sc_project
/stancode_project/boggle_game_solver/boggle.py
3,669
3.90625
4
""" File: boggle.py Name: ---------------------------------------- TODO: """ # This is the file name of the dictionary txt file # we will be checking if a word exists by searching through it FILE = 'dictionary.txt' word_lst = [] bog_lst = [] ans_lst = [] legal_edge = [] record_lst = [] look_up_dict = {} def main(): """ TODO: """ read_dictionary() legal_edge_setup() for i in range(1, 5): row = input(str(i) + " row of letters: ") row_lst = row.lower().split() if check_illegal(row_lst) is False: print('Illegal input') break bog_lst.append(row_lst) if i == 4: built_dict() boggle() def boggle(): for x in range(0, 4): # Start from every point for y in range(0, 4): # Take out letter location and append into record_lst start_point = (y, x) record_lst.append(start_point) boggle_helper(y, x) print("There are " + str(len(ans_lst)) + " words in total.") def boggle_helper(y, x): for i in range(-1, 2): # Search toward all direction for j in range(-1, 2): if (y+i, x+j) not in record_lst: # Check whether we already passed the location if legal_edge_check((y+i, x+j)): # Check whether the location excess the edge record_lst.append((y+i, x+j)) # Append letter into the record list cur_word = take_record_lst_str(record_lst) # Take out string in the record list if len(cur_word) >= 4: # Check prefix & ans at the same time only if length of word >= 4 if has_prefix_and_find_ans(cur_word) == 'with_ans': if cur_word not in ans_lst: # Just keep a unique answer ans_lst.append(cur_word) print("Found: ", cur_word) boggle_helper(y + i, x + j) else: # No prefix -> no wat to go -> pop(go back to previous selected point) record_lst.pop() else: # Only check prefix when length of word < 4 if has_prefix(cur_word): boggle_helper(y + i, x + j) else: # No prefix -> no wat to go -> pop(go back to previous selected point) record_lst.pop() # Completed search for all direction -> no wat to go -> pop(go back to previous selected point) record_lst.pop() def check_illegal(row_lst): for letter in row_lst: if len(letter) != 1: return False def built_dict(): for x in range(0, 4): for y in range(0, 4): look_up_dict[(y, x)] = bog_lst[y][x] def take_record_lst_str(lst): """ :param lst: list, the record list :return: str, the string which is taken from the record list """ cur_word = '' for tpl in lst: cur_word = cur_word + look_up_dict[tpl] return cur_word def legal_edge_setup(): for i in range(0, 4): for j in range(0, 4): legal_edge.append((i, j)) def legal_edge_check(cur_point): if cur_point in legal_edge: return True else: return False def read_dictionary(): """ This function reads file "dictionary.txt" stored in FILE and appends words in each line into a Python list """ with open(FILE, 'r') as f: for line in f: line = line.split() if len(line[0]) >= 4: word_lst.append(line[0]) def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for i in word_lst: if i.startswith(sub_s): return True return False def has_prefix_and_find_ans(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for i in word_lst: if i.startswith(sub_s): if sub_s == i: return "with_ans" else: return "no_ans" return False if __name__ == '__main__': main()
0d6582833054a0596747ea349f9d714deeb5b355
fxyan/data-structure
/code/反转链表.py
214
3.859375
4
def reverseList(head): """ :type head: ListNode :rtype: ListNode """ q = None while head is not None: p = head head = head.next p.next = q q = p return q
9185b85e3286d25f7e59612585b183302cb81b47
fxyan/data-structure
/queue.py
813
4.0625
4
class Node(object): def __init__(self, element=None, next=None): self.element = element self.next = next def __repr__(self): return str(self.element) class Queue(object): def __init__(self): self.head = Node() self.tail = self.head def empty(self): return self.head.next is None def append(self, element): node = Node(element) self.tail.next = node self.tail = node def pop(self): node = self.head.next if not self.empty(): self.head = self.head.next return node def test(): q = Queue() q.append(1) q.append(2) q.append(3) q.append(4) print(q.pop()) print(q.pop()) print(q.pop()) print(q.pop()) if __name__ == '__main__': test()
e86aed6b3987db89dd58700410da0a25a030f5f7
fxyan/data-structure
/code/剑指/删除链表中重复的节点.py
1,226
3.96875
4
""" 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留。 样例1 输入:1->2->3->3->4->4->5 输出:1->2->5 样例2 输入:1->1->1->2->3 输出:2->3 这个题是比较绕的,思路有些清奇 首先先设定一个虚拟节点 None 将他的next连到头结点上去 p永远是前一个节点 q是p的下一个节点 while 如果让q等于p.next 直到q的值为一个新的节点的值 然后拿 p的第二个节点对比如果相等那么p直接下移 如果不等那么将p的next指向q """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def deleteDuplication(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: return head new_head = ListNode(0) p = new_head while p.next: q = p.next while q and q.val == p.next.val: q = q.next if p.next.next == q: p = p.next else: p.next = q return new_head.next
99bad259f692251137282ccf7b168ba6a67d1ac0
fxyan/data-structure
/code/lookup_array.py
654
3.6875
4
""" 二维数组查找数据 首先确定行数和列数 将左下角第一个数设为n 如果这个整数比n大,那么就排除这一行 向上查询 如果这个整数比n小,那么就排除这一列像右查询 """ class Solution: # array 二维列表 def Find(self, target, array): # write code here rows = len(array) - 1 cols = len(array[0]) - 1 i = rows j = 0 while j <= cols and i >= 0: if array[i][j] > target: i -= 1 elif array[i][j] < target: j += 1 else: return True return False """ """
97b3f526a267e916bb6ae64e4a1db6b5d5bb372d
fxyan/data-structure
/code/剑指/机器人移动范围.py
1,394
3.578125
4
""" 地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。 一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。 但是不能进入行坐标和列坐标的数位之和大于 k 的格子。 请问该机器人能够达到多少个格子? 样例1 输入:k=7, m=4, n=5 输出:20 样例2 输入:k=18, m=40, n=40 输出:1484 解释:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。 但是,它不能进入方格(35,38),因为3+5+3+8 = 19。 这里还是用了深搜 """ class Solution(object): def movingCount(self, threshold, rows, cols): """ :type threshold: int :type rows: int :type cols: int :rtype: int """ self.rows = rows self.cols = cols self.dict = set() self.search(threshold, 0, 0) return len(self.dict) def judge(self, threshold, c, r): return sum(map(int, list(str(c)))) + sum(map(int, list(str(r)))) <= threshold def search(self, threshold, c, r): if not self.judge(threshold, c, r) or (c, r) in self.dict: return self.dict.add((c, r)) if c < self.cols - 1: self.search(threshold, c+1, r) if r < self.rows - 1: self.search(threshold, c, r+1)
d926c569be01e185ea52383e988360694ec1809c
fxyan/data-structure
/Array.py
602
3.96875
4
# 定长的列表 class Array(object): def __init__(self, size=8): self._size = size self._item = [None] * size def __len__(self): return self._size def __getitem__(self, index): return self._item[index] def __setitem__(self, key, value): self._item[key] = value def clear(self, value=None): for i in range(len(self._item)): self._item[i] = value def __iter__(self): for item in self._item: yield item def __repr__(self): return '列表值: {}'.format(self._item) print(Array())
348fd28791be8033b293c27087b6861ec35b6989
fxyan/data-structure
/exercise.py
12,479
4.0625
4
""" 冒泡排序 首先从第一个数循环到倒数第二个数 n-1 最后一个数已经被安排了 内层循环开始从第一个数开始循环 n-1-i次,因为i也被安排了 边界检测如果为没有数 def bubble_sort(array): if array is None or len(array) < 2: return array for i in range(len(array)-1): for j in range(len(array)-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] def test_bubble(): array = [4, 2, 1, 7, 5, 3, 2, 4] array2 = [4, 4, 1] bubble_sort(array) bubble_sort(array2) print(array) print(array2) """ """ 选择排序 就是直接定义第一个数是最小值,然后开始循环找到真正最小值的坐标然后两个交换 不需要检查最后一个因为最后一个会在自动排序完成 def select_sort(array): if array is None or len(array) < 2: return array for i in range(len(array)-1): index = i for j in range(i+1, len(array)): if array[index] > array[j]: index = j if index != i: array[i], array[index] = array[index], array[i] def test_select(): array = [4, 2, 1, 7, 5, 3, 2, 4] array2 = [4, 4, 1] select_sort(array) select_sort(array2) print(array) print(array2) """ """ 插入排序 将一个数据插入到已经排好序的数组中 判断他的值是不是最小的如果不是就一直前移 def insert_sort(array): for i in range(1, len(array)): index = i value = array[i] while index > 0 and value < array[index-1]: array[index] = array[index-1] index -= 1 if index != i: array[index] = value def test_insert(): array = [4, 2, 1, 7, 5, 3, 2, 4] array2 = [4, 4, 1] insert_sort(array) insert_sort(array2) print(array) print(array2) """ """ 快排 使用了递归的排序 基本思路就是找到一个中间点,然后将自己的数组分成两部分左部分右部分和中间点,然后递归回去 import random def quick_sort(array): if len(array) < 2 or array is None: return array return quick(array, 0, len(array)-1) def quick(array, l, r): if l < r: ran = random.randint(l, r) print(l, r) print(ran) array[ran], array[r] = array[r], array[ran] q = partition(array, l, r) print(q) quick(array, l, q[0]) quick(array, q[1], r) def partition(array, l, r): left = l-1 right = r while l < right: if array[l] < array[r]: left += 1 array[left], array[l] = array[l], array[left] l += 1 elif array[l] > array[r]: right -= 1 array[l], array[right] = array[right], array[l] else: l += 1 array[r], array[l] = array[l], array[r] q = [left, right+1] return q def test_quick(): array = [4, 2, 1, 7, 5, 3, 2, 4] array2 = [4, 4, 1] quick_sort(array) quick_sort(array2) print(array) print(array2) """ """ 归并排序 def merge_sort(array): if len(array) < 2 or array is None: return array return sort_process(array, 0, len(array)-1) def sort_process(array, l, r): if l == r: return None else: mid = (l+r)//2 sort_process(array, l, mid) sort_process(array, mid+1, r) merge(array, l, mid, r) def merge(array, l, mid, r): help = [] left = l right = mid+1 while left <= mid and right <= r: if array[left] < array[right]: help.append(array[left]) left += 1 else: help.append(array[right]) right += 1 while left <= mid: help.append(array[left]) left += 1 while right <= r: help.append(array[right]) right += 1 for i in range(len(help)): array[l+i] = help[i] def test_merge(): array = [4, 2, 1, 7, 5, 3, 2, 4] array2 = [4, 4, 1] merge_sort(array) merge_sort(array2) print(array) print(array2) """ """ 堆排序 def heap_sort(array): if len(array) < 2 or array is None: return array size = len(array) build_max(array, size) for i in range(size-1, -1, -1): array[i], array[0] = array[0], array[i] heap_insert(array, 0, i) def build_max(array, size): for i in range((size-2)//2, -1, -1): heap_insert(array, i, size) def heap_insert(array, root, size): left = root * 2 + 1 while left < size: largest = left+1 if left+1 < size and array[left+1] > array[left] else left if array[root] < array[largest]: array[root], array[largest] = array[largest], array[root] root = largest left = root * 2 + 1 else: return def test_heap(): array = [4, 2, 1, 7, 5, 3, 2, 4] array2 = [4, 4, 1] heap_sort(array) heap_sort(array2) print(array) print(array2) """ """ 判断数组中有没有三个数相加等于 你输入的整数 # 三重循环的辣鸡写法 def equal1(seq, n): if len(seq) < 3: return False for i in range(len(seq) - 2): for j in range(i + 1, len(seq) - 1): for x in range(j + 1, len(seq)): print(x) if seq[i] + seq[j] + seq[x] == n: return True return False # 通过指针优化的写法 def equal(seq, n): if len(seq) < 3: return False for i in range(len(seq) - 2): j = i + 1 k = len(seq) - 1 while j != k: if seq[i] + seq[j] + seq[k] < n: j += 1 elif seq[i] + seq[j] + seq[k] > n: k -= 1 elif seq[i] + seq[j] + seq[k] == n: return True return False """ """ 判断排序之后数组的相邻的最大差值,使用非比较排序 时间复杂度为O(N) def maxgap(array): if len(array) < 2 or array is None: return array smax = max(array) smin = min(array) if smax == smin: return 0 size = len(array) min_size = [None] * (size + 1) max_size = [None] * (size + 1) bool_size = [False] * (size + 1) for i in range(len(array)): bid = backsize(array[i], size, smax, smin) max_size[bid] = array[i] if max_size[bid] is None or max_size[bid] < array[i] else max_size[bid] min_size[bid] = array[i] if min_size[bid] is None or min_size[bid] > array[i] else min_size[bid] bool_size[bid] = True res = 0 print(min_size, max_size) lastmax = max_size[0] for i in range(len(min_size)): if bool_size[i]: res = max(res, max_size[i] - lastmax) lastmax = max_size[i] return res def backsize(num, size, smax, smin): return (num - smin) * size // (smax - smin) def test_max(): array = [4, 2, 1, 7, 5, 3, 2, 4, 17] array2 = [4, 4, 1] print(maxgap(array)) print(maxgap(array2)) """ """ 数组结构实现大小固定的队列和栈 class Stack(object): def __init__(self, size): self.stack = [None] * size self.size = size self.len = 0 def push(self, value): if self.len >= self.size: print('栈已经满了') else: self.stack[self.len] = value self.len += 1 def get_min(self): if self.len == 0: return None return self.stack[self.len-1] def pop(self): if self.len < 0: print('无数据可以出栈') else: self.len -= 1 value = self.stack[self.len] # print(value) return value def test_stack(): stack = Stack(3) stack.push(7) stack.push(8) stack.push(6) stack.push(77) stack.pop() stack.pop() stack.pop() class Queue(object): def __init__(self, size): self.queue = [None] * size self.size = size self.end = 0 self.start = 0 self.index = 0 def push(self, value): if self.index < self.size: print(self.index) self.queue[self.end] = value self.end = 0 if self.end + 1 == self.size else self.end + 1 self.index += 1 else: print('队列已满') def pop(self): if self.index > 0: print(self.queue[self.start]) self.start = 0 if self.start + 1 == self.size else self.start + 1 self.index -= 1 else: print('队列无数据') def test_queue(): queue = Queue(3) queue.push(5) queue.push(4) queue.push(3) queue.push(2) queue.pop() queue.pop() queue.pop() queue.pop() class Steak2(): def __init__(self, size): self.stack3 = Stack(size) self.stack4 = Stack(size) def push(self, value): self.stack3.push(value) if self.stack3.get_min() is None or value < self.stack3.get_min() : self.stack4.push(value) else: self.stack4.push(self.stack3.get_min()) def pop(self): self.stack4.pop() return self.stack3.pop() def get_min(self): return self.stack4.get_min() def test_steak2(): steak = Steak2(3) steak.push(5) steak.push(4) steak.push(3) steak.pop() steak.pop() print(steak.get_min()) """ """ 矩阵转圈打印 def order_print(array): tR = 0 tC = 0 dR = len(array) - 1 dC = len(array[0]) - 1 while tR <= dR and tC <= dC: print_edge(array, tR, tC, dR, dC) tR += 1 tC += 1 dR -= 1 dC -= 1 def print_edge(array, tR, tC, dR, dC): if tC == dC: while tR <= dR: print(array[tR][tC], end=' ') tR += 1 elif tR == dR: while tC <= dC: print(array[tR][tC], end=' ') tC += 1 else: curR = tR curC = tC while tC < dC: print(array[tR][tC], end=' ') tC += 1 while tR < dR: print(array[tR][tC], end=' ') tR += 1 while dC > curC: print(array[dR][dC], end=' ') dC -= 1 while dR > curR: print(array[dR][dC], end=' ') dR -= 1 while dC > curC: print(array[dR][dC], end=' ') dC -= 1 def test_order(): array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] array2 = [[1, 2, 3, 4]] array3 = [[1], [2], [3]] # order_print(array) order_print(array2) order_print(array3) """ """ 将矩阵的数字转换90度 1 2 4 1 4 5 5 2 def rotate(array): tR = 0 tC = 0 dR = len(array) - 1 dC = len(array[0]) - 1 while tR < dR or tC < dC: rotate_edge(array, tR, tC, dR, dC) tR += 1 tC += 1 dR -= 1 dC -= 1 def rotate_edge(array, tR, tC, dR, dC): size = dC - tC for i in range(size): time = array[tR][tC+i] print(i) array[tR][tC+i] = array[dR-i][tC] array[dR-i][tC] = array[dR][dC-i] array[dR][dC-i] = array[tR+i][dC] array[tR+i][dC] = time def test_rotate(): array = [[1, 2, 3], [3, 4, 5], [6, 7, 8]] rotate(array) print(array) """ """ 之字形打印矩阵 """ def print_zhi(array): tR = 0 tC = 0 dR = 0 dC = 0 endR = len(array) - 1 endC = len(array[0]) - 1 bool_1 = True while tR <= endR and dC <= endC: print_level(array, tR, tC, dR, dC, bool_1) tR = 0 if tC < endC else tR + 1 tC = tC + 1 if tC < endC else tC dC = 0 if dR < endR else dC + 1 dR = dR + 1 if dR < endR else dR bool_1 = False if bool_1 is True else True def print_level(array, tR, tC, dR, dC, bool_1): if bool_1 is True: while dR >= tR and dC <= tC: print(array[dR][dC]) dR -= 1 dC += 1 else: while tR <= dR and tC >= dC: print(array[tR][tC]) tR += 1 tC -= 1 def test_level(): array = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print_zhi(array) if __name__ == '__main__': # test_bubble() # test_select() # test_insert() # test_quick() # test_merge() # test_heap() # test_max() # test_stack() # test_queue() # test_steak2() # test_order() # test_rotate() test_level()
8880877537ac0e945bde820806c56cb008125b9f
leox64/ADT
/Array.py
1,087
3.78125
4
#array class Array: def __init__(self,n): self.data=[] for i in range(n): self.__data.append(None) def get_length(self): return len(self.__data) def set_item(self,index,value): if index >= 0 and index < len(self.__data): self.__data[index] = value else: print("Fuera de rango") def get_item (self,index): if index >= 0 and index < len(self.__data): return self.__data[index] else: print("Fuera de rango") def clearing (self,valor): for index in range(len(self.__data)): self.__data[index] = valor def to_string(self): print(self.__data) #main def main(): arreglo = Array(10) arreglo.to_string() print(f"El tamaño es de {arreglo.get_length()}") arreglo.set_item(1,10) arreglo.to_string() arreglo.set_item(12,10) print (f"El elemento 1 es {arreglo.get_item(1)}") arreglo.get_item(20) arreglo.clearing(5) arreglo.to_string() main()
ffc2780064c17ff9d45e2b817fbd0c4208c330a9
Anthonywilde1/pythonpractice
/practice.py
814
3.828125
4
# Fibonacci series: # the sum of two elements defines the next a, b = 0, 1 while a < 1000: print(a) a, b = b, a+b letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] name = letters[0] + letters[13] + letters[19] + letters[7] + letters[14] + letters[13] + letters[-2] print(name) x = int(input("Please enter an integer: ")) # input requires user input seems like stating the variable required #outside the brackets, in this case int for integer. if x < 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More') # Measure some strings: words = ['cat', 'window', 'defenestrate', 'Wowowowowowowow'] for w in words: print(w, len(w))
91764a0218ca3632eac11064e1312c30e1ead470
SrCarlangas1/Practica7
/Exercici_06.py
233
3.828125
4
print "Dime un nombre" prime=raw_input() pepe=list(prime) print pepe print "Dime un caracter" susti=raw_input() if susti in pepe: print "El caracter esta en tu nombre" else: print "El caracter no esta en tu nombre"
c3bc1f9db4fd2ab9b4ba40ce7e8d69b0da87fd42
lior20-meet/meet2018y1lab2
/MEETinTurtle.py
972
4.15625
4
import turtle turtle.penup() #Pick up the pen so it doesn’t #draw turtle.goto(-200,-100) #Move the turtle to the #position (-200, -100) #on the screen turtle.pendown() #Put the pen down to start #drawing #Draw the M: turtle.goto(-200,-100+200) turtle.goto(-200+50,-100) turtle.goto(-200+100,-100+200) turtle.goto(-200+100,-100) turtle.penup() turtle.goto (-50,100) turtle.pendown() turtle.goto(-50,-100) turtle.goto(50,-100) turtle.penup() turtle.goto(-50,100) turtle.pendown() turtle.goto(50,100) turtle.penup() turtle.goto(-50,0) turtle.pendown() turtle.goto(50,0) turtle.penup() turtle.goto(100,100) turtle.pendown() turtle.goto(100,-100) turtle.goto(200,-100) turtle.penup() turtle.goto(100,100) turtle.pendown() turtle.goto(200,100) turtle.penup() turtle.goto(100,0) turtle.pendown() turtle.goto(200,0) turtle.penup() turtle.goto(250,100) turtle.pendown() turtle.goto(350,100) turtle.goto(300,100) turtle.goto(300,-100)
7235257c51e5a1af67454306e76c5e58ffd2a31c
VeronikaA/user-signup
/crypto/helpers.py
1,345
4.28125
4
import string # helper function 1, returns numerical key of letter input by user def alphabet_position(letter): """ Creates key by receiving a letter and returning the 0-based numerical position of that letter in the alphabet, regardless of case.""" alphabet = string.ascii_lowercase + string.ascii_uppercase alphabet1 = string.ascii_lowercase alphabet2 = string.ascii_uppercase i = 0 for c in alphabet: key = 0 c = letter if c in alphabet1: ascii_value = ord(c) c = ascii_value key = (c - 97) % 26 elif c in alphabet2: ascii_value = ord(c) c = ascii_value key = (c - 65) % 26 elif c not in alphabet: key = ord(c) return key # helper funtion 2 def rotate_character(char, rot): """Receives a character 'char', and an integer 'rot'. Returns a new char, the result of rotating char by rot number of places to the right.""" a = char a = alphabet_position(a) rotation = (a + rot) % 26 if char in string.ascii_lowercase: new_char = rotation + 97 rotation = chr(new_char) elif char in string.ascii_uppercase: new_char = rotation + 65 rotation = chr(new_char) elif char == char: rotation = char return rotation
ed3c20641bdad8b23f85153994fef6345af81de5
echibe/Projects
/Python/Scrape.py
660
3.796875
4
#Elliot Chibe #September 15th, 2016 #Given a YouTube video link this will output the title, description, and user of the video #Uses BeautifulSoup and requests for Python import requests from bs4 import BeautifulSoup url = raw_input("What is the URL: ") r = requests.get(url) soup = BeautifulSoup(r.content, "lxml") titles = soup.find_all("title") print("") print ("-----Title:") for t in titles: print t.text print("") print ("-----Description:") desc = soup.find_all("div", {"id": "watch-description-text"}) for d in desc: print d.text print("") print ("-----User:") user = soup.find_all("div", {"class": "yt-user-info"}) for u in user: print u.text
a87fe2d7477098d5cb41c018fccc47b787b1ff8d
rlazarev/powerunit
/powerunit.py
1,048
3.65625
4
#!/usr/bin/env python # Import the modules to send commands to the system and access GPIO pins. from subprocess import call import RPi.GPIO as GPIO from time import sleep # Map PinEleven and PinThirteen on the Power.unit PCB to chosen pins on the Raspberry Pi header. # The PCB numbering is a legacy with the original design of the board. PinEleven = 11 PinThirteen = 13 GPIO.setmode(GPIO.BOARD) # Set pin numbering to board numbering. GPIO.setup(PinEleven, GPIO.IN) # Set up PinEleven as an input. GPIO.setup(PinThirteen, GPIO.OUT, initial=1) # Setup PinThirteen as output for the LED. while (GPIO.input(PinEleven) == True): # While button not pressed GPIO.wait_for_edge(PinEleven, GPIO.RISING) # Wait for a rising edge on PinSeven sleep(0.1); # Sleep 100ms to avoid triggering a shutdown when a spike occured if (GPIO.input(PinEleven) == True): GPIO.output(PinThirteen,0) # Bring down PinThirteen so that the LED will turn off. call('poweroff', shell=False) # Initiate OS Poweroff else: call('reboot', shell=False) # Initiate OS Reboot
3f4b48b07ce6785b6a30ab7651d62ab2b730adc3
MBScott1997-zz/Python_Projects
/Scott_MarvelMart.py
7,535
3.640625
4
''' Python Project - Marvel Mart Project Michael Scott Due: March 10, 2020 ''' import csv import numpy as np import pandas as pd import collections from collections import defaultdict pd.set_option('display.float_format', lambda x: '%.3f' % x) #Part 1: Cleaning the data #Cleaning ints out of Country mart = pd.read_csv('DataSamples/Marvel_Mart_Sales_clean.csv', delimiter=',') for index, row in mart.iterrows(): try: result = float(row.loc["Country"]) #if it can be converted to a float that's bad mart.loc[float(index), "Country"] = "NULL" #so change it to null except: 1==1 #cleaning blanks out of item type & priority mart["Item Type"].fillna("NULL", inplace=True) #fill blanks with null mart["Order Priority"].fillna("NULL", inplace=True) #fill blanks with null #cleaning strings from order id for index, row in mart.iterrows(): try: placeholder = row.loc["Order ID"] * 2 #if it can be multiplied by two that's good except: mart.loc[int(index), 'Order ID'] = 0 #if it can't change it to zero # Part 2: General Statistics #1A print("\n-2.A-") print("Countries Most Sales:") data = mart.groupby(["Country"],sort=True)["Units Sold"].sum().reset_index() #group by country and sum units sold data = data.sort_values(by = ['Units Sold'], ascending=[False]) #sort units sold sums topTenSales = data.head(10) #top ten values print(topTenSales) print("\nThe country we should build our shipping center is Cape Verde because they are our third biggest customer by Units Sold") #1B print("\n-2.1.B-") offline = collections.Counter() #counter variable with open('DataSamples/Marvel_Mart_Sales_clean.csv') as input_file: for row in csv.reader(input_file, delimiter=','): offline[row[3]] += 1 #everytime "offline" is in row[3] count it print('Number of offline sales: %s' % offline['Offline']) online = collections.Counter() #counter variable with open('DataSamples/Marvel_Mart_Sales_clean.csv') as input_file: for row in csv.reader(input_file, delimiter=','): online[row[3]] += 1 #everytime "online" is in row[3] count it print('Number of online sales: %s' % online['Online']) if online['Online'] > offline['Offline']: #if more online sales print("We have more online sales") #print there's more online sales else: print("We have more offline sales") #if not, tell us there's more offline sales #C print("\n-2.1.C-") mart['year'] = pd.DatetimeIndex(mart['Order Date']).year #adding a year column to make the rest easier print("Best Years:") data = mart.groupby(["year"],sort=True)["Total Profit"].sum().reset_index() #group by year and sum total profits data = data.sort_values(by = ['Total Profit'], ascending=[False]) #sort total profit desc data1 = data.head(3) #top 3 values print(data1) print("\nWorst Years:") data = mart.groupby(["year"],sort=True)["Total Profit"].sum().reset_index() #group by year and sum total profits data = data.sort_values(by = ['Total Profit'], ascending=[True]) #sort total profit asc data2 = data.head(3) #top (bottom) three values print(data2) print("\nWe sold the most in 2011") with open('DataSamples/Marvel_Mart_Rankings.txt', 'w+') as reader: reader.write("-2.A-") reader.write("\nCountries Most Sales: ") reader.write("\n") topTenSales.to_string(reader) reader.write("\n") reader.write("\nThe country we should build our shipping center is Cape Verde because they are our third biggest customer by Units Sold") reader.write("\n") reader.write("\n-2.1.B-") reader.write("\n") reader.writelines(str(onlinePrint)) reader.write("\n") reader.writelines(str(offlinePrint)) reader.write("\n") reader.write("We have more online sales") reader.write("\n") reader.write("\n-2.1.C-") reader.write("\n") data1.to_string(reader) reader.write("\n") reader.write("\n") data2.to_string(reader) reader.write("\n") reader.write("\nWe sold the most in 2011") #making a nicely formatted .txt file :) #2A print("\n-2.2.A-") print("Sums:") totalUnits = mart['Units Sold'].sum() #summing units sold sum1 = "Units Sold: " + str(totalUnits) #print var print(sum1) totalUnits = mart['Unit Cost'].sum() sum2 = "Unit Cost: " + str(totalUnits) print(sum2) totalUnits = mart['Total Revenue'].sum() sum3 = "Total Revenue: " + str(totalUnits) print(sum3) totalUnits = mart['Total Cost'].sum() sum4 = "Total Cost: " + str(totalUnits) print(sum4) totalUnits = mart['Total Profit'].sum() sum5 = "Total Profit: " + str(totalUnits) print(sum5) print("\nAverages:") totalUnits = mart['Units Sold'].mean() #averaging column avg1 = "Units Sold: " + str(totalUnits) #print variable print(avg1) totalUnits = mart['Unit Cost'].mean() avg2 = "Unit Cost: " + str(totalUnits) print(avg2) totalUnits = mart['Total Revenue'].mean() avg3 = "Total Revenue: " + str(totalUnits) print(avg3) totalUnits = mart['Total Cost'].mean() avg4 = "Total Cost: " + str(totalUnits) print(avg4) totalUnits = mart['Total Profit'].mean() avg5 = "Total Profit: " + str(totalUnits) print(avg5) print("\nMaximums:") totalUnits = mart['Units Sold'].max() #finding the max value from the column max1 = "Units Sold: " + str(totalUnits) #print variable print(max1) totalUnits = mart['Unit Cost'].max() max2 = "Unit Cost: " + str(totalUnits) print(max2) totalUnits = mart['Total Revenue'].max() max3 = "Total Revenue: " + str(totalUnits) print(max3) totalUnits = mart['Total Cost'].max() max4 = "Total Cost: " + str(totalUnits) print(max4) totalUnits = mart['Total Profit'].max() max5 = "Total Profit: " + str(totalUnits) print(max5) with open('DataSamples/Marvel_Mart_Calc.txt', 'w+') as reader: reader.write("-3-") reader.write("\n") reader.write("Sum: ") reader.write("\n") reader.writelines(sum1) reader.write("\n") reader.writelines(sum2) reader.write("\n") reader.writelines(sum3) reader.write("\n") reader.writelines(sum4) reader.write("\n") reader.writelines(sum5) reader.write("\n") reader.write("Averages: ") reader.write("\n") reader.writelines(avg1) reader.write("\n") reader.writelines(avg2) reader.write("\n") reader.writelines(avg3) reader.write("\n") reader.writelines(avg4) reader.write("\n") reader.writelines(avg5) reader.write("\n") reader.write("Maximums: ") reader.write("\n") reader.writelines(max1) reader.write("\n") reader.writelines(max2) reader.write("\n") reader.writelines(max3) reader.write("\n") reader.writelines(max4) reader.write("\n") reader.writelines(max5) # making another nicely formatted .txt for you :) #Part 3: Cross-Reference Statistics #1 print("\n-3.1.A") dictOfLists = {} #empty dict for i in mart.Region.unique(): #for each unique region dictOfLists[i] = mart[mart.Region == i].Country.unique().tolist() #put the corresponding unique country into a list and the list as a value to the region key df=pd.DataFrame.from_dict(dictOfLists,orient='index').transpose() #dict to dataframe df.to_csv('DataSamples/Countries_By_Region.csv', encoding='utf-8', index=False) #dataframe to csv for i in dictOfLists: #printing the keys of the dict of lists print(i) #printing the regions line by line
237cbd779d44ac9cdc04edd467647769c4781c97
andxu282/poker_engine
/models/rank.py
510
3.546875
4
""" The rank of the card (2 through Ace). The rank is represented by a single character string (the number itself for 2-9 and T, J, Q, K, A for 10, Jack, Queen, King, and Ace respectively. """ from helpers.constants import rank_dict class Rank(): def __init__(self, rank_str): self.rank_str = rank_str def __str__(self): return rank_dict[self.rank_str] def __eq__(self, other): return self.rank_str == other.rank_str def get_rank(self): return self.rank_str
22f0b036d436b9d8b3021b349c612f7322720db3
sayalijo/my_prog_solution
/hacker_rank/Algorithms/Warmup/min_max_sum/min_max_sum.py
243
3.796875
4
#!/bin/python3 import sys def miniMaxSum(arr): # Complete this function x = sum(arr) print (x-(max(arr)), (x-(min(arr)))) if __name__ == "__main__": arr = list(map(int, input().strip().split(' '))) miniMaxSum(arr)
ff2c1fc5723a4c3309b97226e849bd0c7f824210
sayalijo/my_prog_solution
/geeks_for_geeks/Algorithms/Searching/binary_search/binary_search.py
566
4.0625
4
def binary_search(arr, x, start_index, end_index): if end_index >= 1: mid_index = start_index + (end_index - start_index)//2 if arr[mid_index] == x: return mid_index elif arr[mid_index] > x: return binary_search(arr, x,start_index, mid_index - 1) else: return binary_search(arr, x, mid_index+1, end_index) else: return -1 x = int(input()) arr = list(map(int, input().split(" "))) result = binary_search(arr, x, 0, len(arr)-1) if result != -1: print("Element found at position", result) else: print("Element not present in the given array")
c4d7076b3ef58086aa5b0d53c3168d5292e57836
sayalijo/my_prog_solution
/geeks_for_geeks/Arrays/arrangements/move_all_zeros_end/move_all_zeros_end.py
368
3.78125
4
# arr[] = {1, 2, 0, 0, 0, 3, 6} # Output : 1 2 3 6 0 0 0 def rearrange(ar): i,j = -1, 0 for j in range(len(ar)): if ar[j] > 0: i += 1 ar[i], ar[j] = ar[j], ar[i] return ar array = list(map(int, input("Enter your array:\t").split(" "))) result = rearrange(array) print("Now your array is:\n", " ".join(map(str,result)))
b5fe57756695c05b2f96eb62de309d88a45fb40f
sayalijo/my_prog_solution
/hacker_rank/Algorithms/Implementation/manasa_and_stones/manasa_and_stones.py
753
3.515625
4
#!/bin/python3 import sys def stones(n, a, b): a,b = min(a,b), max(a,b) diff = b - a stones = n - 1 current_stone = a * stones max_stone = b * stones #result = [] if a == b: #result.append(current_stone) yield current_stone return result else: while current_stone <= max_stone: #result.append(current_stone) yield current_stone current_stone += diff #return result if __name__ == "__main__": T = int(input().strip()) for a0 in range(T): n = int(input().strip()) a = int(input().strip()) b = int(input().strip()) result = stones(n, a, b) print(" ".join(map(str, result)))
4db6f63da2c03590a2765d346707db7667d82d36
jaykumarvaghela/python-for-fun
/printfunction.py
138
3.640625
4
n = int(input()) list = [] i = 1 while (i <= n): list.append(i) i = i + 1 for j in range(n): print(list[j], end="")
c3607404f5ac3cc66c9a3222fd122c7e05789569
k5tuck/Digital-Crafts-Classes
/end_of_lesson_exercises/lrg_exercises/python/lrg_exercise2.py
970
3.96875
4
num = int(input("What number would you like to factor?: ")) if num % 2 == 0: print("%i is a positive number" %num) even_list = [] p = 1 while p <= num: if num % p == 0: q = num / p even_list.append(p) even_list.append(int(q)) p += 1 else: p += 1 print("These are the factors for %i:" %num) dup_list = set(even_list) even_sorted = sorted(dup_list) for i in range(len(even_sorted)): print(even_sorted[i]) else: print("%i is a negative number" %num) odd_list = [] p = 1 while p <= num: if num % p == 0: q = num / p odd_list.append(p) odd_list.append(int(q)) p += 1 else: p += 1 print("These are the factors for %i:" %num) odd_dup_list = set(odd_list) odd_sorted = sorted(odd_dup_list) for i in range(len(odd_sorted)): print(odd_sorted[i])
1b658c4f93e2273d593ad60070c170d88b147ce0
k5tuck/Digital-Crafts-Classes
/python/wk_1/comparisons1.py
249
3.90625
4
my_number = 29 compare1 = 18 compare2 = 7 compare3 = 29 if my_number == compare1: print(True) elif my_number == compare2: print(True) elif my_number == compare3: print(True) else: print("This number is equal to none of the above")
bcde179facbf825efb934e779b2257e2e608d211
k5tuck/Digital-Crafts-Classes
/end_of_lesson_exercises/small_exercises/python/wk2_exercise5.py
254
3.875
4
# Exercise 5 numbers = [-23, -52, 0, -1.6, 56, 231, 86, 20, 11, 17, 9] for num in numbers: if num > 0: print(num) # Exercise 6 new_numbers = [] for num in numbers: if num > 0: new_numbers.append(num) print(sorted(new_numbers))
b775e2235930821da179884ff859d592d3d5ada7
k5tuck/Digital-Crafts-Classes
/end_of_lesson_exercises/small_exercises/python/wk2_exercise2.py
246
4.09375
4
numbers = [6,7,8,4,312,109,878] biggest = 0 for num in numbers: if biggest < num: biggest = num else: pass print(biggest) #Alternative using sort method numbers.sort() print(numbers[-1]) #Alternative print(max(numbers))
fe219eb50f78b4c717b8a4a17567073ddb435621
k5tuck/Digital-Crafts-Classes
/end_of_lesson_exercises/small_exercises/python/exercise3.py
310
3.9375
4
print("Please fill in the blanks below:\n") print("____(name)____ loves ____(activity)____ whenever possible!\n") name = input("What is your name? ") activity = input("What is %s's favorite activity to do whenever they get the opportunity? " %name) print("%s loves %s whenever possible!" %(name, activity))
9bdbbea001d9ddbc0c7330ab7b71fc575ac467ce
sankarmanoj/CTE-Python
/second/rand.py
743
3.78125
4
import random import copy randomArray = [random.randint(0,100) for x in range(10)] print "Random Array =",randomArray #Sort Array randomArray.sort() print "Sorted Array = ",randomArray #Largest Element print "Largest Element In Array = ",max(randomArray) #Smallest Element print "Smallest Element in Array = ",min(randomArray) #Create New Array From the Existing Array newArray = randomArray anotherArray = newArray[:] # anotherArray = copy.deepcopy(randomArray) anotherArray = list(randomArray) #Update Starting Value newArray[0]=666 #Print Old Array print "randomArray =",randomArray," newArray = ",newArray #Update Starting Value anotherArray[1]=333 #Print Old Array print "randomArray =",randomArray," anotherArray = ",anotherArray
7ec2ef1c7ecdc53dadc8c11a3a57fd6da40c1920
sankarmanoj/CTE-Python
/third/third.py
197
3.859375
4
a = range(3) b = range(10,13) c = [] for x in a: for y in b: c.append((x,y)) print c c = [(x,y) for x in a for y in b] print c import itertools c = itertools.product(a,b) print list(c)
0d81f91728bed2c804208f94df5311a26d27df1e
sankarmanoj/CTE-Python
/recur.py
172
3.703125
4
def insertion(a): if len(a)==2: if a[0]>a[1]: a[0],a[1] = a[1],a[0] return a else: return a
c5366570917b06ef617db8abd9c478cbf2c79628
JohnVonNeumann/selenium-py
/custom_logger.py
892
3.53125
4
import inspect #allows users to get info from live objects import logging # the purpose of this file is to act as something of a module that we can # call when needed, it sets itself a name, file and other params. def customLogger(logLevel): # Gets the name of the class / method from where this method is called loggerName = inspect.stack()[1][3] logger = logging.getLogger(loggerName) # By default, log all messages logger.setLevel(logging.DEBUG) fileHandler = logging.FileHandler("{0}.log".format(loggerName), mode='w') # gives the log file its own named based on method calling it fileHandler.setLevel(logLevel) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) return logger
01412ba71dea158f097e6da5e831c0c7cea44d50
iabok/sales-tracker
/web/sales_app/apps/helpers/processProductSales.py
2,650
3.609375
4
''' Process the product sales fields ''' from collections import namedtuple import operator class ProductSales: """ Product process class """ def __init__(self, product_name, quantity, price): ''' constructor ''' self.product_name = product_name self.quantity = quantity self.price = price self.fields = None self.productRecord = namedtuple('Product', 'name, quantity, \ unit_price, station_id, sales_date, sales') def mapFields(self): """ process the fields """ if not isinstance(self.product_name, list) \ or not isinstance(self.quantity, list) \ or not isinstance(self.price, list): return False self.fields = zip(self.product_name, self.quantity, self.price) def getMapFields(self): """ get the fields """ return self.fields def totalProductSales(self): """ Returns the total of all product sales Returns an integer """ if not isinstance(self.quantity, list) \ or not isinstance(self.price, list): return False quantity = list(map(int, self.quantity)) price = list(map(int, self.price)) return sum(map(lambda x: operator.mul(*x), zip(quantity, price))) def getProductInsertFields(self, missingFields): """ Inserts the missing fields and cleans up the product sales \ ready for insertion missingFields = [sales_id, station_id, sales_date] """ if not isinstance(missingFields, list): return False self.mapFields() if self.getMapFields() is not None: upackedFields = list(map(list, self.getMapFields())) return map(lambda field: field + missingFields, upackedFields) return False def getProudctInsertData(self, missingFields, model): """ returns a namedtuple for database insertion """ listOfFields = [] fields = self.getProductInsertFields(missingFields) for product in map(self.productRecord._make, list(fields)): listOfFields.append(model['productSales']( product_id=product.name, quantity=product.quantity, unit_price=product.unit_price, station_id=product.station_id, sales_date=product.sales_date, sales=product.sales)) return listOfFields
272adc9f1c787a36e7702e6ee2caa36ae8a547d8
RagingTiger/MontyHallProblem
/montyhall.py
4,080
4.1875
4
#!/usr/bin/env python # libs import random # classes class MontyHall(object): """A class with various methods for simulating the Monty Hall problem.""" def lmad(self): """Interactive version of Monty Hall problem (i.e. Lets Make A Deal).""" # start game print('Let\'s Make A Deal') try: # how many doors ndoors = int(input('How many doors: ')) # which door would you like first_choice = int(input('Choose one door out of {}: '.format(ndoors))) # now the host calculates results = self.simulate(ndoors, first_choice) # would you like to switch switch = input('Would you like to switch doors [y/n]: ') # converst switch to true/false switch = True if switch in {'y', 'Y', 'yes', 'Yes', 'YES'} else False # check switch final_choice = results['second_choice'] if switch else first_choice # prepare results results['final_choice'] = final_choice # return results return results except EOFError or KeyboardInterrupt: # do nothing but end silently pass @staticmethod def predict(ndoors): """Calculate the predicted probabilities of no switch vs. switch. Args: ndoors (int): The number of doors to use. Returns: ndoors (int): The number of doors used. noswitch (float): Probability of winning if players does not switch. switch (float): Probability of winning if player switches. """ # calculate probabilities no_switch = 1.0 / float(ndoors) switch = 1.0 - no_switch # return results dictionary return { 'ndoors': ndoors, 'noswitch': no_switch, 'switch': switch } @staticmethod def simulate(ndoors, first_choice): """Non-interactive version of Monty Hall problem. Args: ndoors (int): The number of doors to use. first_choice (int): The first door the player chooses. Returns: first_choice (int): The first door the player chooses. second_choice (int): The second door the player can switch to. car (int): The door hiding the car. """ # get random number in range of ndoors (representing the car to be won) car = random.randint(1, ndoors) # get second_choice (i.e. 2nd door to choose from) if first_choice != car: second_choice = car else: while True: second_choice = random.randint(1, ndoors) if second_choice != car: break # return results return { 'first_choice': first_choice, 'second_choice': second_choice, 'car': car } def experiment(self, ndoors, first_choice, ngames): """Run multiple games of Monty Hall problem. Args: ndoors (int): The number of doors to use. first_choice (int): The first door the player chooses. ngames (int): The number of games to run. Returns: noswitch (float): Experimental percent of winning without switching. switch (float): Experimental percent of winning with switching. """ # setup initial values switch, noswitch = 0, 0 # setup loop for _ in range(ngames): # get results of game game = self.simulate(ndoors, first_choice) # update statistics if game['first_choice'] == game['car']: noswitch += 1.0 else: switch += 1.0 # calculate results return { 'noswitch': noswitch / (switch + noswitch), 'switch': switch / (switch + noswitch) } # executable only if __name__ == '__main__': # libs import fire # bang bang fire.Fire(MontyHall)
802f19a0bbe365b4fba2cb6c6d3fbba1db803066
qilinchang70/oh-yeah
/028 星座.py
1,551
3.921875
4
n=eval(input()) for i in range(0,n,1): [month,date]= input().split() month= eval(month) date= eval(date) if month==1 and date >=21: print("Aquarius") elif month==2 and date <=19: print("Aquarius") elif month==2 and date >19: print("Pisces") elif month==3 and date <=20: print("Pisces") elif month==3 and date >20: print("Aries") elif month==4 and date <=19: print("Aries") elif month==4 and date >=20: print("Taurus") elif month==5 and date <=20: print("Taurus") elif month==5 and date >=21: print("Gemini") elif month==6 and date <=21: print("Gemini") elif month==6 and date >21: print("Cancer") elif month==7 and date <=22: print("Cancer") elif month==7 and date >=23: print("Leo") elif month==8 and date <=22: print("Leo") elif month==8 and date >=23: print("Virgo") elif month==9 and date <=22: print("Virgo") elif month==9 and date >=23: print("Libra") elif month==10 and date <=23: print("Libra") elif month==10 and date >=24: print("Scorpio") elif month==11 and date <=21: print("Scorpio") elif month==11 and date >=22: print("Sagittarius") elif month==12 and date <=20: print("Sagittarius") elif month==12 and date >=21: print("Capricorn") elif month==1 and date <=20: print("Capricorn")
c47734a966d5996428b2ae19beeb8a396a3c734f
Gouenji/Dynamic-Programming
/Weighted Job Scheduling Dynamic Programming.py
1,699
3.625
4
def doNotOverlap(job1,job2): if job1[0] < job2[0] and job2[1] < job1[1] : return 0 if job2[0] < job1[0] and job1[1] < job2[1] : return 0 if job1[1] > job2[0] and job1[0]<job2[0]: return 0 if job2[1] > job1[0] and job2[0]<job1[0]: return 0 else: return 1 from operator import itemgetter def WeightedJobScheduling(Jobs): sorted(Jobs,key=itemgetter(1)) temp_array=[] temp_locator=[] for k in range(len(Jobs)): temp_array.append(Jobs[k][2]) temp_locator.append(0) i=1 j=0 while(i<len(Jobs)): while(i!=j): temp_tracker=temp_array[i] if doNotOverlap(Jobs[i],Jobs[j]): temp_array[i]=max(temp_array[i],temp_array[j]+Jobs[i][2]) if temp_array[i] != temp_tracker: temp_locator[i]=j j+=1 i+=1 j=0 maxCost=max(temp_array) index=temp_array.index(maxCost) temp_maxCost=maxCost jobsindices=[] jobs=[] while temp_maxCost>0: jobsindices.append(index) temp_maxCost-=Jobs[index][2] index=temp_locator[index] jobsindices.reverse() for itr in range(len(jobsindices)): jobs.append(Jobs[jobsindices[itr]]) return jobs,maxCost Jobs=[] n=int(raw_input("Enter the No of Jobs:\n")) print "Enter jobs Start-Time End-Time Cost" for i in range(n): jobs=map(int,raw_input().strip().split(" ")) Jobs.append(jobs) jobs,maxCost = WeightedJobScheduling(Jobs) for itr in range(len(jobs)): print "Start Time: " + str(jobs[itr][0]) + " End Time: " + str(jobs[itr][1]) + " Cost: "+str(jobs[itr][2]) print "Total Cost: "+str(maxCost)
1b775b3d85e54f9c236f1a4ba71409e99a4ab1d3
Gouenji/Dynamic-Programming
/Maximum Sum Increasing Subsequence Dynamic Programming.py
1,478
3.890625
4
print ("Enter the array to find Maximum Sum Increasing Subsequence (space separated)") a=map(int,raw_input().strip(' ').split(' ')) from copy import copy def MaximumSumIncreasingSubsequence(array): max_sum_array=copy(array) actual_sequence=[] for i in range(len(array)): actual_sequence.append(i) j=0 i=1 while(i<len(array)): while(j!=i): temp=max_sum_array[i] if array[j]<array[i]: max_sum_array[i]=max(array[i]+max_sum_array[j],max_sum_array[i]) if max_sum_array[i]!=temp: actual_sequence[i]=j j+=1 j=0 i+=1 maxSum=max(max_sum_array) temp_sum=maxSum position_max_sum=max_sum_array.index(maxSum) #print actual_sequence #print max_sum_array sequence=[] while(temp_sum > 0): sequence.append(array[position_max_sum]) temp_sum-=array[position_max_sum] position_max_sum=actual_sequence[position_max_sum] sequence.reverse() print "1.To print Maximum Sum Increasing Subsequence and Max Sum\n2.Return the values of Max Sum and Maximum Sum Increasing Subsequence " choice=int(raw_input()) if choice == 1: print "\nMax Sum: "+str(maxSum) print "Sequence:" for i in range (len(sequence)): print " "+str(sequence[i]), elif choice == 2: print "Returned" return sequence,maxSum MaximumSumIncreasingSubsequence(a)
7b709a867ddc325c7f905dcee39dc8a0001ed6b5
prajwaldhore/pythonlab
/ams.py
161
3.65625
4
x=int(input(' enter the number ' )) p=(x//10) q=(x%10) s=(p//10) r=(p%10) z=(s**3+q**3+r**3) if x==z: print('amstrong') else: print('not')
de07a3442ceabc74bbebe758ac77672f8d8441e0
RiderBR/Desafios-Concluidos-em-Python
/Python/Desafio 002.py
250
3.78125
4
#RiderBR-TEKUBR dia = int(input("Qual o dia que você nasceu? ")) mes = str(input("Qual o mês de seu nascimento? ")) ano = int(input("Qual o ano de seu nascimento? ")) print("Você nasceu em {} de {} de {}. Estou correto?".format(dia, mes, ano))
01113ddaf86fac3d3c169ce261a1789ee2731516
RiderBR/Desafios-Concluidos-em-Python
/Python/Desafio 045.py
843
3.84375
4
import random lista = ['Pedra', 'Papel', 'Tesoura'] print('-='*13) print('''Escolha uma das opções: [ 1 ] - Pedra [ 2 ] - Papel [ 3 ] - Tesoura''') print('-='*13) jogador = int(input('Sua escolha: ')) print('-='*13) print('Vez do computador.') pc = random.choice(lista) print('O computador escolheu {}.'.format(pc)) print('-='*13) if jogador == 1: if pc == 'Pedra': print('EMPATE') elif pc == 'Tesoura': print('VOCÊ GANHOU') else: print('VOCÊ PERDEU.') elif jogador == 2: if pc == 'Pedra': print('VOCÊ GANHOU') elif pc == 'Papel': print('EMPATE') else: print('VOCÊ PERDEU') else: if pc == 'Pedra': print('VOCÊ PERDEU') elif pc == 'Papel': print('VOCÊ GANHOU') else: print('EMPATE')
e6fa51b5a6851f3536f05d31d4ed14d9394e2e9e
wjdghrl11/repipe
/sbsquiz6.py
418
3.6875
4
# 문제 : 99단 8단을 출력해주세요. # 조건 : 숫자 1 이외의 값을 사용할 수 없습니다. 소스코드를 수정해주세요. # 조건 : while문을 사용해주세요. # """ # 출력 양식 # == 8단 == # 8 * 1 = 8 # 8 * 2 = 16 # 8 * 3 = 24 # 8 * 4 = 32 # 8 * 5 = 40 # 8 * 6 = 48 # 8 * 7 = 56 # 8 * 8 = 64 # 8 * 9 = 72 # """ # 수정가능 시작 num = int(input("8을 입력해 주세요"))
bc1f578d4254a5a6d336acceeb1e0e90bebcdd3a
wjdghrl11/repipe
/sbsquiz5.py
107
3.640625
4
# 반복문을 이용해 1 ~ 10까지 출력해주세요. num = 1 while num <= 10: print(num) num += 1
a2b9d9b20dacdbcf9650b924e27b2be4a55bad61
wjdghrl11/repipe
/quiz8.py
676
3.65625
4
# 1 ~ 10 까지 수 리스트 선언 list1 = [1,2,3,4,5,6,7,8,9,10] print(list1) # 리스트 값 짝수만 가져오기 print(list1[0]) print(list1[1]) print(list1[3]) print(list1[5]) print(list1[7]) print(list1[9]) i = 0 while i < 10 : if list1[i] % 2 == 0 : print(list1[i]) i += 1 # 리스트에 11,13,15 추가하기 list1.append(11) list1.append(13) list1.append(15) print(list1) # 리스트의 짝수번째 값 1증가시키기 list1[0] += 1 list1[2] += 1 list1[4] += 1 list1[6] += 1 list1[8] += 1 list1[8] += 1 print(list1) i = 0 while i < 13 : if i % 2 == 0 : list1[i] += 1 i += 1 # 리스트에서 세번째 값 지우기 del list1[2] print(list1)
0e509745b1acc82ae4142d6b2daafdfde2861533
wjdghrl11/repipe
/4.py
431
3.515625
4
# # 삼자택일, 삼지선다 # a = 0 # if a < 0 : # print("음수") # elif a == 0 : # print("0") # else : # 위에서 조건을 다 끝내고서 맨 마지막 # print("양수") b = 15 if b < 1 : print("1보다 작습니다.") elif b < 3 : print("3보다 작습니다.") elif b < 5 : print("5보다 작습니다.") elif b < 10 : print("10보다 작습니다") else : print("10보다 크거나 같습니다.")
714077f21c473536d8f64b6ba9c1f11c968d172b
wonderfullinux/work
/calculator_challenge2.py
929
3.546875
4
#!/usr/bin/env python3 import sys def calculator(gz): yn = gz - 0.165 * gz - 5000 if yn <= 0: ns = 0 elif yn <= 3000: ns = yn * 0.03 elif yn <= 12000: ns = yn * 0.1 - 210 elif yn <= 25000: ns = yn * 0.2 - 1410 elif yn <= 35000: ns = yn * 0.25 - 2660 elif yn <= 55000: ns = yn * 0.3 - 4410 elif yn <= 80000: ns = yn * 0.35 - 7160 else: ns = yn * 0.45 - 15160 sh = gz - 0.165 * gz - ns return sh if __name__ == '__main__': if len(sys.argv) == 1: print("Parameter Error") exit() dict1 = {} for arg in sys.argv[1:]: key, value = arg.split(':') try: dict1[int(key)] = int(float(value)) except ValueError: print("Parameter Error") exit() for gh, gz in dict1.items(): print("{}:{:.2f}".format(gh, calculator(gz)))
15d38f06d05b2330c9d0269c4882c701d371eb69
DiggidyDev/euleriser
/graph.py
7,852
3.671875
4
import random from interface import Interface from node import Node __author__ = "DiggidyDev" __license__ = "MIT" __version__ = "1.0.1" __maintainer__ = "DiggidyDev" __email__ = "35506546+DiggidyDev@users.noreply.github.com" __status__ = "Development" class Graph: """ Graph is an object which represents a series of nodes, their connections and identifiers. It is used for Eulerian-style graphs and is capable of solving them using a Depth-First Search algorithm with the hope of implementing a real-time visualisation of said solution in the future. It is currently still under development, but is hopefully going to serve some sort of use in the future. """ def __init__(self, nodes: int = None): """ Default initialisation function. :param nodes: """ self.current_node = None self.image = None self.interface = None self.nodes = [] self.odd_nodes = [] self.path_count = 0 self.previous_node = None self.travelled = {k + 1: [] for k in range(nodes)} @property def node_count(self): """ Returns the number of nodes in the graph, connected or not. :return: """ return len(self.travelled.keys()) @property def paths(self): """ Returns a dict containing all paths as keys, and their connected nodes (see self.node_links) as the values. :return: """ return {k: c.connections for k, c in enumerate(self.nodes, 1)} def __len__(self): """ Returns the number of paths in a graph. :return: """ return self.path_count def __str__(self): """ Shows graph as an image. Used to visualise the nodes and paths. :return: """ for count in range(1, self.node_count + 1): self.image = self.interface.draw_node(self.get_node(count), self.get_node(count).centre, 20) self.image.show() return "Graph successfully loaded!" def _dfs(self, solution): """ Performs a depth-first search on the graph from a set starting position. Returns a list containing the solution. :param solution: :return: """ for neighbour in self.paths[self.current_node.identifier]: if neighbour not in self.travelled[self.current_node.identifier] and not self.paths == self.travelled: solution.append(self.current_node.identifier) self.previous_node = self.current_node self.current_node = self.get_node(neighbour) self.travelled[self.current_node.identifier].append(self.previous_node.identifier) self.travelled[self.previous_node.identifier].append(self.current_node.identifier) self._dfs(solution) for node in self.travelled.values(): node.sort() return solution def add_path(self, start, end): """ Creates and draws a path between two defined nodes, start and end. :param start: :param end: :return: """ if not (0 < start <= self.node_count) or not (0 < start <= self.node_count): raise IndexError(f"Please provide valid values between the lower and upper bounds, inclusively: (1-{self.node_count})") try: start_node = self.get_node(start) end_node = self.get_node(end) start_node.connect_to(end_node) self.image = self.interface.draw_path(start_node.centre, end_node.centre, action="add") self.path_count += 1 except Exception as e: print(f"{type(e).__name__}: {e}") def analysis(self): """ Analyses the graph for the number of nodes, number of odd, even nodes, whether it's Eulerian, semi-Eulerian or invalid. In future will also highlight the path in real-time for the solution to the graph. :return: """ PAD = 14 self.odd_nodes = [str(node) for node in self.paths.keys() if len([c for c in self.paths[node]]) % 2 == 1] if len(self.odd_nodes) == 2: graph_type = "Semi-Eulerian path" elif len(self.odd_nodes) == 0: graph_type = "Eulerian cycle" else: graph_type = "Invalid graph type" print(f"\n{'Nodes':{PAD}}: {self.node_count} ({'Even' if self.node_count % 2 == 0 else 'Odd'})") print(f"{'Odd nodes':{PAD}}: {', '.join(self.odd_nodes)} (Possible starting nodes)") print(f"{'Graph type':{PAD}}: {graph_type}\n") def del_path(self, start, end): """ Deletes a path between two defined nodes, start and end. This will both conceptually and visually delete said path. :param start: :param end: :return: """ if not (0 < start <= self.node_count) or not (0 < start <= self.node_count): raise IndexError(f"Please provide valid values between the lower and upper bounds, inclusively: (1-{self.nodes})") try: start_node = self.get_node(start) end_node = self.get_node(end) start_node.disconnect_from(end_node) self.image = self.interface.draw_path(start_node.centre, end_node.centre, action="remove") self.path_count -= 1 except Exception as e: print(f"{type(e).__name__}: {e}") def get_node(self, identifier): """ Returns the node object from the given identifier. For when you wish to interact with a node. :param identifier: :return: """ for node in self.nodes: if identifier == node.identifier: return node def init_gui(self): """ Initialises the Interface object, enabling drawing. :return: """ gui = Interface(self.node_count) self.interface = gui for i in range(len(self.travelled.keys())): node = Node(i + 1, self.interface) node.set_radius(20) self.nodes.append(node) self.interface.graph = self w = self.interface.dimensions[0] h = self.interface.dimensions[1] for node in range(1, self.node_count + 1): radius = self.get_node(node).radius self.get_node(node).set_position(random.randint(radius, (w - radius)), random.randint(radius, h - radius)) while self.get_node(node).distance_from() < radius * 2.5: self.get_node(node).set_position(random.randint(radius, (w - radius)), random.randint(radius, h - radius)) return self.interface def node_links(self, node=None): """ Returns the connecting nodes from a given node as a list. :param node: :return: """ if node is None: node = self.current_node print(f"'Node {node}' has {len(self.paths[node])} linked nodes: {', '.join([str(v) for v in self.paths[node]])}") return self.paths[node] def search(self, start): """ Runs the depth-first search algorithm, returning the validity of the graph, and route if valid. :param start: :return: """ if not isinstance(start, Node): self.current_node = self.get_node(start) else: self.current_node = start solve_order = ' -> '.join([str(node) for node in self._dfs([])]) solve_order += f" -> {self.current_node.identifier}" for node in self.travelled.values(): node.sort() if self.travelled == self.paths: print(f"Solved!\n{solve_order}") else: print("Not possible from this position!")
d67990ec50f962766c1017b19e5b89f5798fa710
otmaneattou/OOP_projects
/calories_app/temperature.py
1,679
3.625
4
from selectorlib import Extractor import requests class Temperature(): """ A scraper that uses an yaml file to read the xpath of a value It needs to extract from timeanddate.com/weather/ url """ headers = { 'pragma': 'no-cache', 'cache-control': 'no-cache', 'dnt': '1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', } base_url = 'https://www.timeanddate.com/weather/' yaml_path = 'temperature.yaml' def __init__(self, country, city): self.country = country self.city = city def _build_url(self): """Build the url string adding country and city""" url = self.base_url + self.country + "/" + self.city return url def _scrape(self): """Extracts a value as instructed by the yaml file and returns a dictionary""" r = requests.get(self.base_url(), headers=self.headers) full_content = r.text extractor = Extractor.from_yaml_file(self.yaml_path) raw_content = extractor.extract(full_content) return raw_content def get(self): """Cleans the output of _scrape""" scraped_content = self._scrape return float(scraped_content['temp'].replace("°C","").strip()) if __name__ == "__main__": temperature = Temperature(country="usa", city="san francisco") print(temperature.get())
ab9343311a6c6d43501b8e2196b1682e3d0398f6
panoptes/PEAS
/peas/PID.py
2,683
3.546875
4
from datetime import datetime class PID: ''' Pseudocode from Wikipedia: previous_error = 0 integral = 0 start: error = setpoint - measured_value integral = integral + error*dt derivative = (error - previous_error)/dt output = Kp*error + Ki*integral + Kd*derivative previous_error = error wait(dt) goto start ''' def __init__(self, Kp=2., Ki=0., Kd=1., set_point=None, output_limits=None, max_age=None): self.Kp = Kp self.Ki = Ki self.Kd = Kd self.Pval = None self.Ival = 0.0 self.Dval = 0.0 self.previous_error = None self.set_point = None if set_point: self.set_point = set_point self.output_limits = output_limits self.history = [] self.max_age = max_age self.last_recalc_time = None self.last_interval = 0. def recalculate(self, value, interval=None, reset_integral=False, new_set_point=None): if new_set_point: self.set_point = float(new_set_point) if reset_integral: self.history = [] if not interval: if self.last_recalc_time: now = datetime.utcnow() interval = (now - self.last_recalc_time).total_seconds() else: interval = 0.0 # Pval error = self.set_point - value self.Pval = error # Ival for entry in self.history: entry[2] += interval for entry in self.history: if self.max_age: if entry[2] > self.max_age: self.history.remove(entry) self.history.append([error, interval, 0]) new_Ival = 0 for entry in self.history: new_Ival += entry[0] * entry[1] self.Ival = new_Ival # Dval if self.previous_error: self.Dval = (error - self.previous_error) / interval # Output output = self.Kp * error + self.Ki * self.Ival + self.Kd * self.Dval if self.output_limits: if output > max(self.output_limits): output = max(self.output_limits) if output < min(self.output_limits): output = min(self.output_limits) self.previous_error = error self.last_recalc_time = datetime.utcnow() self.last_interval = interval return output def tune(self, Kp=None, Ki=None, Kd=None): if Kp: self.Kp = Kp if Ki: self.Ki = Ki if Kd: self.Kd = Kd
dd45a9660cfd3f30085b148fbbdc2c57691be9a9
hpvo37/PyGame-games
/GameEffects/ShadowForText.py
1,636
4
4
""" example non-animated entry for the pygame text contest if you would like to change this for your own entry, modify the first function that renders the text. you'll also probably want to change the arguments that your function used. simply running the script should show some sort of example for your text rendering """ import os, sys, pygame, pygame.font, pygame.image from pygame.locals import * def textDropShadow(font, message, offset, fontcolor, shadowcolor): base = font.render(message, 0, fontcolor) size = base.get_width() + offset, base.get_height() + offset img = pygame.Surface(size, 16) base.set_palette_at(1, shadowcolor) img.blit(base, (offset, offset)) base.set_palette_at(1, fontcolor) img.blit(base, (0, 0)) return img entry_info = 'YASSSSSSSSSSS' #this code will display our work, if the script is run... if __name__ == '__main__': pygame.init() #create our fancy text white = 255, 255, 255 grey = 100, 100, 100 bigfont = pygame.font.Font(None, 60) text = textDropShadow(bigfont, entry_info, 3, white, grey) #create a window the correct size win = pygame.display.set_mode(text.get_size()) winrect = win.get_rect() win.blit(text, (0, 0)) pygame.display.flip() #wait for the finish while 1: event = pygame.event.wait() if event.type is KEYDOWN and event.key == K_s: #save it name = os.path.splitext(sys.argv[0])[0] + '.bmp' print ('Saving image to:', name) pygame.image.save(win, name) elif event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN): break
549659b57129e8bb0b85738015f4f4d6d4e7ebc0
Machine-builder/python-uno
/scripts/game_logic.py
5,222
3.5625
4
from . import card_logic class UnoPlayer(): def __init__(self): self.hand = [] class UnoGame(): def __init__(self): # create a shuffled uno deck self.deck = card_logic.make_deck() self.players = [] self.players_turn = 0 self.turn_direction = 1 self.upfacing_card = None self.debug = False self.stacked_plus = 0 self.winner = None def debug_msg(self, msg=''): if self.debug: print(msg) def start_game(self, players: int = 5, hand_size: int = 7): """start a game and deal hands""" _ = self.deal_hands(players, hand_size) while 1: if self.upfacing_card is not None: self.put_card(self.upfacing_card) self.upfacing_card = self.take_card() if self.upfacing_card is not None: if self.upfacing_card[0] != '_' and not self.upfacing_card[1] in 'srp': break def deal_hands(self, players: int = 5, size: int = 7): """deals cards from the deck to players returns a list of lists representing each player's hand, also saves UnoPlayer instances in .players attribute""" if players*size > len(self.deck): size = int(len(self.deck)/players) hands = [] for i in range(players): hand = [] for j in range(size): hand.append(self.take_card()) hands.append(hand) new_player = UnoPlayer() new_player.hand = hand self.players.append(new_player) return hands def take_card(self, card=None) -> str: """get the top card off the deck, or a specific card from the deck""" if len(self.deck) == 0: self.deck.extend(card_logic.make_deck()) if card is None: return self.deck.pop(0)[:2] self.deck.remove(card) def put_card(self, card): """put a card into the end of the deck""" self.deck.append(card) def take_turn(self, player_index: int, turn: tuple) -> bool: """let a player take a turn turn[0] can be either 'play' or 'pickup' if turn[0] is 'play', turn[1] must be the card name""" if 0 > player_index >= len(self.players): # player does not exist return False if not turn[0] in ('play', 'pickup'): # turn not valid return False if turn[0] == 'play' and len(turn) != 2: # no card name provided with 'play' turn return False player_obj = self.players[player_index] print(f'[{player_index}] : {turn}') if turn[0] == 'play': card_name = card_logic.real_card_name(turn[1]) if not card_name in player_obj.hand: # player doesn't have card return False if not card_logic.card_playable(card_name, self.upfacing_card): # card not playable return False card_type = card_logic.card_type(card_name) used_plus = False is_special = card_type == 'special' if is_special: if card_name[1] == 'p': # a plus card plus_count = 2 if card_name[0] == '_': plus_count = 4 self.stacked_plus += plus_count used_plus = True if used_plus or self.stacked_plus==0: self.put_card(self.upfacing_card) self.upfacing_card = turn[1] player_obj.hand.remove(card_name) if is_special: if card_name[1] == 's': # a skip card self.players_turn += self.turn_direction elif card_name[1] == 'r': # a reverse card self.turn_direction *= -1 else: for i in range(self.stacked_plus): player_obj.hand.append(self.take_card()) self.stacked_plus = 0 self.players_turn += self.turn_direction self.players_turn %= len(self.players) return True elif turn[0] == 'pickup': if self.stacked_plus == 0: top_card = self.take_card() player_obj.hand.append(top_card) else: for i in range(self.stacked_plus): player_obj.hand.append(self.take_card()) self.stacked_plus = 0 self.players_turn += self.turn_direction self.players_turn %= len(self.players) return True def check_winner(self): for player in self.players: if len(player.hand) == 0: self.winner = player return True if len(self.players) == 1: self.winner = self.players[0] return True return False
43f6c58538bb2bef37b90e942489e7075af2807c
ah4d1/anoapycore
/src/anoapycore/data/null/__init__.py
1,550
3.65625
4
import numpy as __np import pandas as __pd def count (a_data) : """ Count null in dataframe. You can also use a_data[a_column] or a_data[[a_column1,a_column2,...]] """ return a_data.isnull().sum() def fill (a_data,a_columns,b_fill_with='NA') : a_data[a_columns] = a_data[a_columns].fillna(b_fill_with) return a_data # check in any rows had more null than specific number # def greater_than (a_data,a_max_null) : # return a_data[a_data.isnull().sum(axis=1) > a_max_null] def percentage (a_data) : missing_info = __pd.DataFrame(__np.array(a_data.isnull().sum().sort_values(ascending=False).reset_index())\ ,columns=['Columns','Missing_Percentage']).query("Missing_Percentage > 0").set_index('Columns') return 100*missing_info/a_data.shape[0] def replace (a_data,a_column,b_method='mean') : """ Replace null value with another value. The options of b_method are 'mean' (default), 'median'. This function has no return. """ if b_method == 'mean' : a_data[a_column].fillna(a_data[a_column].mean(),inplace=True) elif b_method == 'median' : a_data[a_column].fillna(a_data[a_column].median(),inplace=True) def replace_text (a_data,a_column,a_text) : """ Replace null value (which stated by string or text) with another value. This function has no return. """ a_data[a_column].replace(a_text,__np.nan,inplace=True) a_data[a_column].fillna(a_data[a_column].mode()[0],inplace=True)
aaa05eaea50ea34481a5a79b59d4350b747579e6
kdm1171/programmers
/python/programmers/level2/P_땅따먹기.py
1,138
3.78125
4
# https://programmers.co.kr/learn/courses/30/lessons/12913 # DP 문제 # 첫번째 리스트와 두번째 리스트를 비교해서 갈 수 있는 가장 큰 값을 찾고, 두 값을 더한 리스트를 반환하여 마지막 리스트에서 가장 큰 값을 찾음 def getNextList(list1, list2): result = [] for i in range(len(list2)): e = 0 for j in range(len(list1)): if i == j: continue if e < list1[j]: e = list1[j] result.append(list2[i] + e) return result def solution(land): resultList = land[0] for i in range(1, len(land)): resultList = getNextList(resultList, land[i]) answer = max(resultList) return answer if __name__ == '__main__': print(solution([[1, 2, 3, 5], [5, 6, 7, 8], [4, 3, 2, 1]])) # 16 print(solution([[1, 2, 3, 4], [5, 6, 7, 10], [4, 3, 2, 1]])) # 17 print(solution([[1, 2, 3, 4], [5, 6, 7, 10], [5, 6, 7, 10], [4, 3, 2, 1]])) # 25
79457ef52eb3f8bc1de24b46048bdd915b7e95e9
kdm1171/programmers
/python/programmers/level2/P_행렬의_곱셈.py
541
3.6875
4
# https://programmers.co.kr/learn/courses/30/lessons/12949 def solution(arr1, arr2): m = len(arr1) # row n = len(arr2[0]) # col l = len(arr1[0]) answer = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): for k in range(l): answer[i][j] += arr1[i][k] * arr2[k][j] return answer if __name__ == '__main__': print(solution([[1, 4], [3, 2], [4, 1]], [[3, 3], [3, 3]])) print(solution([[2, 3, 2], [4, 2, 4], [3, 1, 4]], [[5, 4, 3], [2, 4, 1], [3, 1, 1]]))
034168d792c48d2c2117d1f89e5a914487485ab1
kdm1171/programmers
/python/programmers/level2/P_뉴스_클러스터링.py
1,324
3.8125
4
# https://programmers.co.kr/learn/courses/30/lessons/17677 import re def solution(str1, str2): pattern = '[A-Z|a-z]' multiSet1 = [] multiSet2 = [] for i in range(1, len(str1)): s = ''.join(str1[i - 1:i + 1]).upper() if len(re.findall(pattern, s)) == 2: multiSet1.append(s) for i in range(1, len(str2)): s = ''.join(str2[i - 1:i + 1]).upper() if len(re.findall(pattern, s)) == 2: multiSet2.append(s) sorted(multiSet1) sorted(multiSet2) intersections = [] unions = [] for i in multiSet1: if i in multiSet2: intersections.append(i) multiSet2.remove(i) unions.append(i) for i in multiSet2: unions.append(i) a = len(intersections) b = len(unions) if a == b: return 65536 return int(a / b * 65536) if __name__ == '__main__': print(solution("FRANCE", "french")) print(solution("french", "FRANCE")) print() print(solution("handshake", "shake hands")) print(solution("shake hands", "handshake")) print() print(solution("aa1+aa2", "AAAA12")) print(solution("AAAA12", "aa1+aa2")) print() print(solution("E=M*C^2", "e=m*c^2")) print(solution("e=m*c^2", "E=M*C^2")) print(solution("AABBCCDD", "ABCDDCC"))
0a74706da29946c50e28d4ffe12a16f25a243d22
kdm1171/programmers
/python/programmers/level2/P_스킬트리.py
584
3.53125
4
# https://programmers.co.kr/learn/courses/30/lessons/49993 def solution(skill, skill_trees): answer = 0 for skill_tree in skill_trees: skill_comp = [i for i in skill] isMatched = False for s in skill_tree: if s in skill_comp: e = skill_comp.pop(0) if e != s: isMatched = False break isMatched = True if isMatched: answer += 1 return answer if __name__ == '__main__': print(solution("CBD", ["BACDE", "CBADF", "AECB", "BDA"]))
8584992389409fee8982a810415847603a5d7728
kdm1171/programmers
/python/programmers/level2/P_전화번호_목록.py
502
3.65625
4
# https://programmers.co.kr/learn/courses/30/lessons/42577 def solution(phone_book): l = sorted(phone_book, key=lambda x: len(str(x))) for i, a in enumerate(l): for j, b in enumerate(l): if i == j: continue if str(b).startswith(str(a)): return False return True if __name__ == '__main__': print(solution([119, 97674223, 1195524421])) print(solution([123, 456, 789])) print(solution([12, 123, 1235, 567, 88]))
07d0e6234ff5ea5faa2b45699616270713889447
Pride7K/Python
/Listas/lista_exercicio8.py
261
3.71875
4
vetor = [] media = 0; for i in range(0,4): vetor.append(int(input("Digite a nota: "))); print(""); for i in vetor: media += i media = media /4 print(f'{vetor[0]} {vetor[1]} {vetor[2]} {vetor[3]} equivale a média = {media}');
4918e2a6e919cbaefc031bdf611398a5a085438a
Pride7K/Python
/Exercicios/for.py
244
3.5
4
contador = 0; for i in range(1,500): validador = 0; validador2 = 0; validador = i % 3; validador2 = i % 2; if validador == 0: if validador2 != 0: contador = contador + i; print(contador);
0e44d31802705bb1c7082d846f7ae35ff161229c
Pride7K/Python
/Listas/lista_exercicio5.py
374
3.90625
4
contador = 0; print("Checando se uma expressão é valida através dos parenteses \n"); expressao = input("Digite a expressão: "); print(""); for i in expressao: if i == "(" or i == ")": contador = contador + 1 contador = contador % 2 if contador == 0: print("Expressão valida !"); else: print("Expressão invalida !");
a609dd67af83c1bf8302578ec639d3bdfe6fcb8a
Pride7K/Python
/Dicionario/dicionario_exercicio2.py
1,069
4.09375
4
from datetime import datetime pessoa = {} now = datetime.now(); now = now.year pessoa["nome"] = input("Digite o seu nome: "); pessoa["ano de nascimento"] = int(input("Digite o seu ano de nascimento: ")); pessoa["cdt"] = int(input("Digite o sua carteira de trabalho(caso nao tenha digite 0): ")); if(pessoa["cdt"] !=0): pessoa["ano_contrato"] = int(input("Digite o ano de sua contratação: ")); pessoa["salario"] = int(input("Digite o seu salario: ")); pessoa["aposentar"] = pessoa["ano_contrato"] + 35; print(""); print(f'O seu nome é {pessoa["nome"]} \n'); print(f'A sua idade é {now - pessoa["ano de nascimento"]} \n'); print(f'A sua carteira de trabalho é {pessoa["cdt"]} \n'); print(f'A sua contratação foi em {pessoa["ano_contrato"]} \n'); print(f'O seu salario é {pessoa["salario"]} \n'); print(f'O Você ira se aposentar em {pessoa["aposentar"]} \n'); else: print(f'O seu nome é {pessoa["nome"]} \n'); print(f'A sua idade é {now - pessoa["ano de nascimento"]} \n');
9ef4f0332e5bdf6d72be3bc23ef5d5dcc7ae8038
Pride7K/Python
/Listas/lista_exercicio7.py
148
3.90625
4
vetor = [] for i in range(0,10): vetor.append(float(input("Digite um numero: "))); print(""); print(sorted(vetor,reverse=True));
f7c61b747436cfcd105a925edd695ac3c8d97279
ksheetal/python-codes
/hanoi.py
654
4.1875
4
def hanoi(n,source,spare,target): ''' objective : To build tower of hanoi using n number of disks and 3 poles input parameters : n -> no of disks source : starting position of disk spare : auxillary position of the disk target : end position of the disk ''' #approach : call hanoi function recursively to move disk from one pole to another assert n>0 if n==1: print('Move disk from ',source,' to ',target) else: hanoi(n-1,source,target,spare) print('Move disk from ',source,' to ',target) hanoi(n-1,spare,source,target)
1ad945d852351c2fed94dc05e75eade79aff7c48
austonnn/ucsd_bio_2
/bio 2 week 4/1.3.4.py
1,106
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 21 15:23:09 2018 @author: xiangyin """ """ Spectral Convolution Problem: Compute the convolution of a spectrum. Input: A collection of integers Spectrum. Output: The list of elements in the convolution of Spectrum. If an element has multiplicity k, it should appear exactly k times; you may return the elements in any order. """ def Convolution_Spectrum(Spectrum): ans_list = [] tmp_list = [0] tmp_list.extend(Spectrum) for i in tmp_list: for j in Spectrum: if i > j: ans_list.append(i - j) pass ans_list = sorted(ans_list) return ans_list with open('dataset_104_4.txt') as handle: Spectrum = handle.read() #.splitlines() Spectrum = Spectrum.split() tmp_list = [] for item in Spectrum: tmp_list.append(int(item)) Spectrum = tmp_list ans = Convolution_Spectrum(Spectrum) #print(ans) text = '' for item in ans: text += str(item) text += ' ' print(text) with open('output.txt', 'w') as handle: handle.write(text)
baf66093d37d83826dd906d458484c653e804597
austonnn/ucsd_bio_2
/bio 2 week 3/1.5.py
2,198
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 14 11:57:07 2018 @author: xiangyin """ #Counting Peptides with Given Mass Problem: Compute the number of peptides of given mass. # Input: An integer m. # Output: The number of linear peptides having integer mass m. aminoAcid = ['G', 'A', 'S', 'P', 'V', 'T', 'C', 'I', 'N', 'D', 'K', 'E', 'M', 'H', 'F', 'R', 'Y', 'W'] aminoAcidMass = [ 57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186] aminoAcid_dict = dict(zip(aminoAcid, aminoAcidMass)) def get_seqs(total_mass): #tmp_num = 0 #mass_dict = {} text_list = [] for i in aminoAcid: tmp_text = '' tmp_text += i if total_mass - aminoAcid_dict[i] < 0: #print(tmp_text) break #print(total_mass - aminoAcid_dict[i]) elif total_mass - aminoAcid_dict[i] > 0: for item in get_seqs(total_mass - aminoAcid_dict[i]): tmp_item = tmp_text + item text_list.append(tmp_item) elif total_mass - aminoAcid_dict[i] == 0: #text_list.append(tmp_text) #print(i) #print(tmp_num) text_list.append(tmp_text) return text_list return text_list mass_dict = {} def count_seqs(total_mass): tmp_num = 0 #text_list = [] for i in aminoAcid: if (total_mass - aminoAcid_dict[i]) in mass_dict.keys(): tmp_num += mass_dict[(total_mass - aminoAcid_dict[i])] elif total_mass - aminoAcid_dict[i] < 0: #print(tmp_text) #mass_dict[(total_mass - aminoAcid_dict[i])] = 0 break #print(total_mass - aminoAcid_dict[i]) elif total_mass - aminoAcid_dict[i] == 0: #text_list.append(tmp_text) #print(i) #print(tmp_num) tmp_num += 1 return tmp_num elif total_mass - aminoAcid_dict[i] > 0: tmp_num += count_seqs(total_mass - aminoAcid_dict[i]) mass_dict[total_mass] = tmp_num return tmp_num total_mass = 1334 ans_num = count_seqs(total_mass) print(ans_num)
c94f35aaf3c6231e4b07cccc6133fb5f5e490566
psmith586/directory-parsing-python
/filewalker.py
1,877
4.09375
4
#Author: Phillip Smith #recursive keyword search/directory data display #using os library to walk the directory import os #using matplotlib to create xy graph of data import matplotlib.pyplot as plt #init root dir and keyword vars from user root_dir = input("Please enter directory path: ") keyword = input("Please enter keyword: ") #this method will be used to accumulate files with the keyword and populate array def CheckKey(r, k): #will accumulate number of files with keyword total = 0 #populate array with the sub dirs and the number of files with keyword arr = {} #check dirs/subdirs for files for fname in os.listdir(r): #use join to create the new path to check on each iteration newPath = os.path.join(r, fname) #this will confirm an object in the dir is a txt file to be read if os.path.isfile(newPath): #strip the file name out to check if it contains keyword s = newPath.split('\\')[-1].split('.')[0] #if the keyword is in the current file name and contents increment total if k in s and k in open(newPath, 'r').read(): total += 1 #add the number value to associate with the dir key arr[r] = total #return each key/value object tot final array return arr[r] #init new array to recursively add results finalArr = {} #use os walk and searchkey to search through dirs, subdirs, files for root, dirs, files in os.walk(root_dir): finalArr[root] = CheckKey(root, keyword) #display final array print("Number of Files Containing Keyword by Directory: ", finalArr) #break finalArr into a seperate arrays #x = keys, y = values x = [] y = [] #iterate through each key/value pair and append to new arrays for key, value in finalArr.items(): x.append(key) y.append(value) #use matplotlib to display line graph of data plt.plot(x,y) plt.show()
de64db2e733e592558b5459e7fb4fcfd695abd1b
moogzy/MIT-6.00.1x-Files
/w2-pset1-alphabetic-strings.py
1,220
4.125
4
#!/usr/bin/python """ Find longest alphabetical order substring in a given string. Author: Adrian Arumugam (apa@moogzy.net) Date: 2018-01-27 MIT 6.00.1x """ s = 'azcbobobegghakl' currloc = 0 substr = '' sublist = [] strend = len(s) # Process the string while the current slice location is less then the length of the string. while currloc < strend: # Append the character from the current location to the substring. substr += s[currloc] # Our base case to ensure we don't try to access invalid string slice locations. # If current location is equal to the actual length of the string then increment # the current location counter and append the substring to our list. if currloc == strend - 1: currloc += 1 sublist.append(substr) # Continute processing the substring as we've still got slices in alphabetical order. elif s[currloc+1] >= s[currloc]: currloc += 1 # Current slice location broken the alphabetical order requirement. # Append the current substring to our list, reset to an empty substring and increment the current location. else: sublist.append(substr) substr = '' currloc += 1 print("Longest substring in alphabetical order is: {}".format(max(sublist, key=len)))
abb1b3042edbbf6dee7201817177000cb9bc7d39
theworldcitizen/Web-2021
/cycle3.py
128
3.59375
4
a = int(input()) b = int(input()) for i in range(a, b + 1): if(i**(1/2) == round(i**(1/2))): print(i, end=" ")
5cd4cd9e965fdce1148584357b0fc9e2fc1709df
theworldcitizen/Web-2021
/cycle11.py
98
3.5
4
ans = 0 n = int(input()) for i in range(n): a = int(input()) ans = ans + a print(ans)
65882ab6d3f039036a778f6763725231dc69458c
jadsonpp/ordenacao
/src/PersonHandler.py
954
3.703125
4
class Person: def __init__(self,email,gender,uid,birthdate,height,weight): self.email = email self.gender = gender self.uid = uid self.birthdate = birthdate self.height = height self.weight = weight def showData(self): print("E-mail: "+self.email) print("Gender: "+self.gender) print("Uid: "+self.uid) print("birthdate: "+self.birthdate) print("height: "+self.height) print("weight: "+self.weight) def showUid(self): print("uid:"+ self.uid) #Compare two classes and return -1 if p1 is lower, 0 if both are equals, 1 if p1 is higher def compareTo(p1:Person , p2:Person): if(p1.uid > p2.uid): return 1 elif (p1.uid < p2.uid): return -1 #caso não ache. return 0 def showUids(persons:list): for person in persons: person.showUid()