blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a5e5efe03ed53f1b77a231c5440cf3395cf2504a
Al-ImranRony/Algorithms
/kadanesAlgo.py
524
3.75
4
''' Tech Interview Prep Group task - Session 3. Maximum SubArray in Python Uising kadane's Algo Time complexity: O(N) ''' import sys def maxSubArray(nums: list) -> int: ln = len(nums) sum = 0 maxSubSum = -sys.maxsize - 1 if ln<2: return ln for i in range(ln): sum += nums[i] if (sum > maxSubSum): maxSubSum = sum if sum < 0 : sum = 0 return maxSubSum print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4])) print(maxSubArray([2, -3, 4, 1, 1]))
611cda680c1f1faa6f3d312561dadf3c334a63f4
flopez-APSL/TutPython
/ficheros_de_texto.py
631
3.984375
4
#f = open('textfile.txt', 'r+') # r+ lee y escribe. with open('textfile.txt') as f: read_data = f.read() print(read_data) f.closed with open('textfile.txt') as f: read_data = f.readline() print(read_data) f.closed print('------------------------------------------------------------------') with open('textfile.txt', 'a') as f: f.write(' Esto, está demás... ') # para escribir al final.. ..sin borrar. f.closed with open('textfile.txt') as f: read_data = f.readline() print(read_data) with open('textfile.txt') as f: for line in f: print(line, end='') f.closed
6df7628bd1b7c309cfad75779ab8b39ec986868d
IGalascapova/codefirstgit
/homework.py
318
3.609375
4
a=1 a=a+1 print a b = "hello" print b c = b.title() print b print c d = "hello" e = d.title() print d print e name = "Dave" f = "Hello {0}! ".format(name) print f name = "Sarah" print f print f *5 myName = int(input ("What's your name?")) a = int(input("Num 1 ")) b = int(input("Num 2: ")) c = int(input("Num 3: "))
85af3835caa2044d085b9fc665b0361811726537
marcusgsta/search_engine
/pageRank.py
1,449
3.609375
4
#!/usr/bin/python3 import os from urllib.parse import unquote def createLinkIndex(dictOfDicts): """ Creates a searchable index from a list of wikipedia articles. Loops through list of files and stores a dict of dictionaries with urls, links and pageRanks (set to inital value of 1.0) """ for url, dict in dictOfDicts.items(): links = readfile('wikipedia/Links/' + url) dict['links'] = links return dictOfDicts def readfile(file): links = [] for link in open(file): link = link.strip('\n') link = unquote(link) links.append(link) return links # Iterate over all pages for a number of iterations def calculatePageRank(pages): """ @param dict of dictionaries """ MAX_ITERATIONS = 20 for i in range(MAX_ITERATIONS): for url, dict in pages.items(): # every page url is checked with all links in all pages # to find inbound links pr = iteratePR(url, pages) dict['pageRank'] = pr return pages def iteratePR(this_url, pages): # Calculate page rank value pr = 0 for url, dict in pages.items(): # if url != this_url: link_url = "/wiki/" + unquote(this_url).split('/')[1] if link_url in dict['links']: pr += dict['pageRank'] / len(dict['links']) # pr += 0.85 * dict['pageRank'] / len(dict['links']) return 0.85 * pr + 0.15
ad60f7383eace5f3ddae5a61d1baf9f7a1409806
ahammadshawki8/Standard-Libraries-of-Python
/01. exploring modules and library.py
3,737
3.953125
4
# importing module and exploring standerd library. # module can be of 3 types. # first one is standerd libraries. they are default built in modules of python. # second one is third party libraries. Very good developers make this libraries for a certain use. # third is own module. right now, the file we are working on, is one kind of module of our own. # we can find all the modules and standerd libraries which we can use in python in this link- #https://docs.python.org/3/library/index.html # to import a module, we have to- import helpers courses=["math", "physics", "comsci", "ict", "english"] index=helpers.found_index(courses,"comsci")# we need to tell python first that we are wanting the index variable to work with the found_index function which is situated in helpers module. print(index) # but if we work with this function several times, we have to write down the module name for several time. # to ignore this, we can set a short name for our module. # we can do this by- import helpers as h courses=["math", "physics", "comsci", "ict", "english"] index=h.found_index(courses,"comsci")# now we are using h for helpers module. print(index) # we can even import the function itself- from helpers import found_index courses=["math", "physics", "comsci", "ict", "english"] index=found_index(courses,"comsci")# we do not write the module name. print(index) # here we accessed the function but we did not access the variable in helpers. # to access the variables from helpers, we can- from helpers import found_index, shawki courses=["math", "physics", "comsci", "ict", "english"] index=found_index(courses,"comsci") print(index) print(shawki) # if we want to import everything from helpers, we can- from helpers import * courses=["math", "physics", "comsci", "ict", "english"] index=found_index(courses,"comsci") print(index) print(shawki) # when we import a module,python checks multiple location. # the location that it checks is within a list called sys.path. # we can actually see this list if we import sys module. from helpers import found_index, shawki import sys courses=["math", "physics", "comsci", "ict", "english"] index=found_index(courses,"comsci") print(index) print(shawki) print(sys.path) # if sys.path doesn't find our module, we get an error. # to avoid this error we can append our module location to sys.path as it is a list. # we can do this- # import sys # sys.path.append(module location) # but it is hard to write module location every time we want to use. # we can set this path to python path environment variable. # we can set this in following location in windows. # settings/advance system settings/environment variable/new # sys is a standard library. It means we do not have to download additional library from internet. It is a default library. # we can import random library. import random courses=["math", "physics", "comsci", "ict", "english"] # if we wnt to grab a random value from our course list. # we can write- random_courses=random.choice(courses) print(random_courses) # we can also import math library import math # we can convert degrees to radian using radians function in the math library. rad=math.rad(90) print(rad) # we can also sin this radian by using sin function print(math.sin(rad)) # we can also import calendar library import calendar year=calendar.isleap(2017)# finding if the year is leapyear or not. print(year) # it will give us a boolean. # we can also import os library. import os # we can find which directory we are working currently by getcwd method(cwd=current working directory) print(os.getcwd()) # all this libraries/modules are files itself. # we can find its location by using __file__ attribute. print(os.__file__)
b49e031ff5b347ccc0eaad9ce0243d4f56d71768
Ibarra11/TicTacToe
/tic_tac_toe.py
4,055
3.921875
4
def game(): markers = [[],[]] player = 0 board = [['','',''] , ['','',''], ['','','']] remainingPositions = 9 hasWon = False def init(): markers[0] = input('Player 1 choose your marker: ').upper() markers[1] = input('Player 2 choose your marker: ').upper() def placeInputOnBoard(position): if position <= 3: if board[0][position-1] == '': board[0][position - 1] = markers[player] else: print('The position is already occupied on the board. Please try again!') position = getUserMarkerLocation() placeInputOnBoard(position) elif position <= 6: if board[1][position-4] == '': board[1][position-4] = markers[player] else: print("That space on the board is already occupied") position = getUserMarkerLocation() placeInputOnBoard(position) elif position <= 9: if board[2][position-7] == '': board[2][position-7] = markers[player] else: print("That space on the board is already occupied") position = getUserMarkerLocation() placeInputOnBoard(position) else: print("Sorry that position is out of range of the board. Please try again") position = getUserMarkerLocation() placeInputOnBoard(position) def checkGame(): wonGame = False if board[0][0] == markers[player] and board[0][1] == markers[player] and board[0][2] == markers[player]: wonGame = True elif board[0][0] == markers[player] and board[1][1] == markers[player] and board[2][2] == markers[player]: wonGame = True elif board[0][2] == markers[player] and board[1][1] == markers[player] and board[2][0] == markers[player]: wonGame = True elif board[0][0] == markers[player] and board[1][0] == markers[player] and board[2][0] == markers[player]: wonGame = True elif board[0][1] == markers[player] and board[1][1] == markers[player] and board[2][1] == markers[player]: wonGame = True elif board[0][2] == markers[player] and board[1][2] == markers[player] and board[2][2] == markers[player]: wonGame = True elif board[1][0] == markers[player] and board[1][1] == markers[player] and board[1][2] == markers[player]: wonGame = True elif board[2][0] == markers[player] and board[2][1] == markers[player] and board[2][2] == markers[player]: wonGame = True return wonGame def printBoard(l): for row in l: colIndex = 0 for col in row: if colIndex < 2: print(col, '|', end="") colIndex += 1 else: print(col, end="") print() def getUserMarkerLocation(): return int(input("Player {} please choose a location to place your marker".format(player + 1))) init() while remainingPositions > 0: pos = getUserMarkerLocation() remainingPositions -= 1 print('-------------------------------------') placeInputOnBoard(pos) if checkGame() == True: hasWon = True break printBoard(board) print('-------------------------------------') if player == 0: player = 1 else: player = 0 ''' If there are no more positions on the board left then check if there isnt a winner. The check game checks the last user to place a marker on the board since ''' if hasWon == True: print('Congratulations player ', player + 1, ' you just have won the game') printBoard(board) print('-------------------------------------') elif remainingPositions == 0 and hasWon != True: print('The game ended in a tie') printBoard(board) game()
3931f946e58fccbc5e1fe228e952dc89a37887c3
pflun/advancedAlgorithms
/intersection.py
442
3.515625
4
class Solution: # @param {int[]} nums1 an integer array # @param {int[]} nums2 an integer array # @return {int[]} an integer array def intersection(self, nums1, nums2): results = [] Set1 = set(nums1) Set2 = set(nums2) for i in Set1: if i in Set2: results.append(i) return results test = Solution() print test.intersection([1, 2, 2, 1, 8], [8, 2, 2, 1, 3])
3043e605829b4cc3b3a68ebd10d7aea12d59e56b
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hamming/4c47a64657294080936c5ee6869abb1b.py
283
3.84375
4
def hamming(first, second): firstList = list(first) secondList = list(second) ham_distance = abs(len(firstList) - len(secondList)) for i, val in enumerate(firstList): if i > len(secondList) - 1: pass elif val != secondList[i]: ham_distance += 1 return ham_distance
5fbbdc986271605050f59280488eab2b631d17bf
joshuabhk/methylsuite
/sim/__init__.py
2,009
3.625
4
from random import randrange, getrandbits, gauss, random, choice def random_nucleotide( nuc, nucleotide_pool = ['A','C','G','T'] ) : if nuc.islower() : nuc = nuc.upper() #make sure newnuc is different from nuc newnuc = choice( nucleotide_pool ) while newnuc == nuc : newnuc = choice( nucleotide_pool ) return newnuc.lower() else : newnuc = choice( nucleotide_pool ) while newnuc == nuc : newnuc = choice( nucleotide_pool ) return newnuc def choice_with_N( quality_score, nucleotide_pool=['A','C','G','T'] ) : #select N or other randomly selected nulceotides. #print "choice_with_N", if quality_score <= 4 : if random() < 0.00185 : return 'N' else : return choice(nucleotide_pool) elif quality_score == 5 : if random() < 0.577 : return 'N' else : return choice(nucleotide_pool) elif quality_score == 6 : if random() < 0.0863 : return 'N' else : return choice(nucleotide_pool) elif quality_score == 7 : if random() < 0.00508 : return 'N' else : return choice(nucleotide_pool) elif quality_score == 8 : if random() < 0.0000163 : return 'N' else : return choice(nucleotide_pool) else : choice( nucleotide_pool ) def random_nucleotide2( nuc, nucleotide_pool = ['A','C','G','T'] ) : #introdue N if quality score is less than 9. #the N introduction rate is determined by my little experiment. if nuc.islower() : #make sure newnuc is different from nuc newnuc = choice( nucleotide_pool ) return newnuc.lower() else : newnuc = choice( nucleotide_pool ) return newnuc
a4aaaa535b14289561344212efd535d82de7dddf
xiaoxiaojiangshang/LeetCode
/leetcode_python/recover_Binary_Search_Tree_99.py
2,206
3.875
4
#-*-coding:utf-8-*- # 作者:jgz # 创建日期:2018/11/28 9:55 # IDE:PyCharm import numpy as np # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution1(object): def recursive(self,root,inorder_traversal): if root.left != None: self.recursive(root.left,inorder_traversal) inorder_traversal.append(root.val) if root.right != None: self.recursive(root.right,inorder_traversal) def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ inorder_traversal = [] if root: self.recursive(root,inorder_traversal) return inorder_traversal def recoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ ### 先中序遍历,判断谁错了,再更改过来o(2*n) inorder_traversal = self.inorderTraversal(root) wrong = [] inorder_sort = sorted(inorder_traversal) for i in range(len(inorder_traversal)): if inorder_traversal[i] != inorder_sort[i]: wrong.append(inorder_traversal[i]) result, stack = [], [(root, False)] while stack: cur, visited = stack.pop() if cur: if visited: if cur.val == wrong[0]: cur.val = wrong[1] elif cur.val == wrong[1]: cur.val = wrong[0] else: stack.append((cur.right, False)) stack.append((cur, True)) stack.append((cur.left, False)) inorder_traversal = self.inorderTraversal(root) print(inorder_traversal) if __name__ == '__main__': input_data = [1,0] list_node = [] for data in input_data: list_node.append(TreeNode(data)) list_node[2].left = list_node[0] list_node[2].right = list_node[3] list_node[3].left = list_node[1] Solution1().recoverTree(list_node[2])
69dfcc8ae1df677f7bba9d2951cf32ca23fa1761
SneyderHOL/holbertonschool-higher_level_programming
/0x0A-python-inheritance/3-is_kind_of_class.py
461
3.828125
4
#!/usr/bin/python3 """ Module for function is_kind_of_class """ def is_kind_of_class(obj, a_class): """is_kind_of_class: function that returns True if the object is an instance of, or if the object is an instance of a class that inherited from, the specified class; otherwise False Args: obj (strin): The object to operate a_class (class): The class to compare """ return isinstance(obj, a_class)
5f4bd02ff99abf56b7fcf1927d8164509478bee5
veretrum/2019ProgrammingPortfolio
/Bottles/99Bottles.py
434
3.890625
4
#!/usr/bin/python3 Bottles = 99 while (Bottles > 1): print (Bottles, 'bottles of root beer on the wall,', Bottles, 'bottles of root beer') Bottles = Bottles - 1 print ('Take one down and pass it around', Bottles, 'bottles of root beer') if Bottles == 1: print ('Take one down and pass it around', Bottles, 'bottle of root beer') print (Bottles, 'bottle of root beer on the wall,', Bottles, 'bottle of root beer')
9ca947782d30798c183325670f1b16504ebdefc8
Gotek12/Python
/z10/10_3.py
1,335
3.953125
4
#!/usr/bin/python3 # -*- coding: iso-8859-2 -* class Stack: def __init__(self, size=10): self.items = size * [None] # utworzenie tablicy self.n = 0 # liczba elementw na stosie self.size = size self.itemsTest = size * [0] def top(self): return self.items[self.n - 1] def is_empty(self): return self.n == 0 def is_full(self): return self.size == self.n def push(self, data): if self.size >= data >= 1 and self.itemsTest[data - 1] == 0: self.itemsTest[data - 1] = 1 self.items[self.n] = data self.n += 1 def pop(self): if self.is_empty(): print("Pusty stos") else: self.itemsTest[self.top() - 1] = 0 data = self.items[self.n - 1] self.items[self.n - 1] = None # usuwam referencj self.n -= 1 return data stos = Stack(5) stos.push(1) stos.push(1) stos.push(5) stos.push(4) stos.push(3) stos.push(3) stos.push(2) stos.pop() stos.pop() stos.pop() stos.pop() stos.pop() print(stos.top()) stos.push(5) print(stos.top()) stos.push(1) print(stos.top()) stos.push(2) print(stos.top()) stos.pop() stos.pop() stos.pop() stos.pop() print(stos.top())
a99d5ec0c2d1d9f87eefff9ec8f39f06dede7f6a
trzyha/paper_scissor_rock
/paper_sissor_rock.py
3,273
3.703125
4
import tkinter from random import randint playerPoint = 0 oponentPoint = 0 #settings main window root = tkinter.Tk() root.title("Paper rock scissor game") root.minsize(600,400) root.geometry("750x600") root.columnconfigure(0, minsize=250) root.columnconfigure(1, minsize=250) root.columnconfigure(2, minsize=250) root.rowconfigure(0, minsize=250) root.rowconfigure(1, minsize=250) root.rowconfigure(2, minsize=100) # def oponentScore(oponentChoice): global oponentPoint oponentPoint += 1 labelScore2["text"] = ("OPONENT POINTS: " + str(oponentPoint)) if oponentChoice == 1: labelGameBoard["image"] = img1 elif oponentChoice == 2: labelGameBoard["image"] = img2 elif oponentChoice == 3: labelGameBoard["image"] = img3 def playerScore(oponentChoice): global playerPoint playerPoint += 1 labelScore1["text"] = ("YOUR POINTS: " + str(playerPoint)) if oponentChoice == 1: labelGameBoard["image"] = img1 elif oponentChoice == 2: labelGameBoard["image"] = img2 elif oponentChoice == 3: labelGameBoard["image"] = img3 def draw(oponentChoice): if oponentChoice == 1: labelGameBoard["image"] = img1 elif oponentChoice == 2: labelGameBoard["image"] = img2 elif oponentChoice == 3: labelGameBoard["image"] = img3 print("draw") def gameMechanics(x): global oponentChoice oponentChoice = randint(1,3) print(oponentChoice) if x==1 and oponentChoice==1: print("draw") draw(oponentChoice) elif x==1 and oponentChoice==2: playerScore(oponentChoice) elif x==1 and oponentChoice==3: oponentScore(oponentChoice) elif x==2 and oponentChoice==1: oponentScore(oponentChoice) elif x==2 and oponentChoice==2: draw(oponentChoice) elif x==2 and oponentChoice==3: playerScore(oponentChoice) elif x==3 and oponentChoice==1: playerScore(oponentChoice) elif x==3 and oponentChoice==2: oponentScore(oponentChoice) elif x==3 and oponentChoice==3: draw(oponentChoice) #GAME GUI labelGameBoard = tkinter.Label(root, text="PAPER ROCK SCISSORS GAME PRESS BUTTON TO START", fg="green", font="Helvetica 16 bold italic", justify="center", width=20, height=10) labelGameBoard.grid(column=0, row=0, columnspan=2, sticky="WENS") labelScore1 = tkinter.Label(root, bg="red", text=("YOUR POINTS: " + str(playerPoint)), width=10, height=10) labelScore1.grid(column=0, row=2, sticky="WENS") labelScore2 = tkinter.Label(root, text="OPPONENT POINTS: " + str(oponentPoint)) labelScore2.grid(column=2, row=2, sticky="WENS") img1 = tkinter.PhotoImage(file="paper.png") button1 = tkinter.Button(root, image=img1, text="Paper(1)", command=lambda: gameMechanics(1)) button1.grid(column=0, row=1, sticky="WENS") img2 = tkinter.PhotoImage(file="rock.png") button2 = tkinter.Button(root, image=img2, text="Rock(2)", command=lambda: gameMechanics(2)) button2.grid(column=1, row=1, sticky="WENS") img3 = tkinter.PhotoImage(file="scissors.png") button3 = tkinter.Button(root, image=img3, text="Paper(1)", command=lambda: gameMechanics(3)) button3.grid(column=2, row=1, sticky="WENS") if __name__=="__main__": root.mainloop()
e4c3c710977ddc8bd539dd095359b0baddedb478
ngupta23/more
/build/lib/more/viz_helper/plot_data.py
4,301
3.59375
4
import matplotlib.pyplot as plt import seaborn as sns import warnings import math def plot_data(data, kind='dist', rows=None, cols=None, kde=False, bins=None, figsize=None, xrot=0, yrot=0): """ data = Dataframe to plot kind = 'dist'. Specifies kind of plot, Options are 'dist' (default), 'count' rows = 3. Specifies number of rows in the plots rows = 3. Specifies number of columns in the plots kde = False. If kind = 'dist', should the KDE be plotted? bins = If kind = 'dist', this argument specifies the number of bins that should be plotted figsize = Overall figure size for the plot matrix. Autocalculated by default. xrot = 0. Degrees to rotate the X label by yrot = 0. Degrees to rotate the Y label by """ """ TODO: Add checks for variable types for each type of plot """ if (kind == 'dist'): cat_columns = data.select_dtypes( include=['object', 'category']).columns data = data.select_dtypes(include=['number']) if (len(cat_columns) > 0): warnings.warn( "The data has categorical columns {} for which a distribution " "will not be plotted".format(cat_columns)) elif (kind == 'count'): num_columns = data.select_dtypes(include=['number']).columns data = data.select_dtypes(include=['object', 'category']) if (len(num_columns) > 0): warnings.warn( "The data has numeric columns {} for which a count plot will " "not be plotted".format(num_columns)) else: raise Exception("kind = " + str(kind) + " is not supported yet") num_columns = len(data.columns) # Both are None, then code decides if ((rows is None) and (cols is None)): if (num_columns % 5 == 0): cols = 5 elif (num_columns % 4 == 0): cols = 4 elif (num_columns % 3 == 0): cols = 3 elif (num_columns % 2 == 0): cols = 2 else: cols = 1 rows = math.ceil(num_columns/cols) # If number of rows is none, then number of columns gets decided by code elif (rows is None): rows = math.ceil(num_columns/cols) # If number of columns is none, then number of rows gets decided by code elif (cols is None): cols = math.ceil(num_columns/rows) # When both are specified by user elif (rows * cols < num_columns): warnings.warn( "Number of rows and columns specified is less than number of " "scatter plots to be plotted. Some scatterplots will be omitted") num_plots_requested = rows * cols if (figsize is None): if (cols > 2): loWidth = 4 * cols loHeight = 4 * rows else: loWidth = 4 * cols loHeight = 4 * rows figsize = (loWidth, loHeight) fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=figsize) cols_to_plot = data.columns for i, column in enumerate(cols_to_plot): if i < num_plots_requested: if (rows == 1 and cols == 1): axis = axes elif ((rows == 1 and cols != 1) or (cols == 1 and rows != 1)): axis = axes[i] else: axis = axes[i//cols, i % (cols)] if (kind == 'dist'): ax = sns.distplot(data[data[column].notna()] [column], kde=kde, bins=bins, ax=axis) ax.set_xticklabels(ax.get_xticklabels(), rotation=xrot) # , fontsize = 8 ax.set_yticklabels(ax.get_yticklabels(), rotation=yrot) # , fontsize = 8 elif (kind == 'count'): ax = sns.countplot(x=column, data=data, ax=axis) ax.set_xticklabels(ax.get_xticklabels(), rotation=xrot) # , fontsize = 8 ax.set_yticklabels(ax.get_yticklabels(), rotation=yrot) # , fontsize = 8 else: pass plt.tight_layout()
7eead0fce78a434adb5dddd4180285aeedb16409
adrigo/Python
/Ejercicios/EjerciciosPython/calculadora.py
1,838
3.8125
4
import os def suma(): os.system('clear') print("SUMA") print("Escribe el primer numero:") i = int(input()) print("Escribe el segundo numero:") j = int(input()) print("-------------------------") print("La suma es: " + str( i + j )) print("-------------------------") print("") def resta(): os.system('clear') print("RESTA") print("Escribe el primer numero:") i = int(input()) print("Escribe el segundo numero:") j = int(input()) print("-------------------------") print("La resta es: " + str( i - j )) print("-------------------------") print("") def multiplicacion(): os.system('clear') print("MULTIPLICACION") print("Escribe el primer numero:") i = int(input()) print("Escribe el segundo numero:") j = int(input()) print("-------------------------") print("La multiplicacion es: " + str( i * j )) print("-------------------------") print("") def division(): os.system('clear') print("DIVISION") print("Escribe el primer numero:") i = int(input()) print("Escribe el segundo numero:") j = int(input()) print("-------------------------") print("La division es: " + str( i / j )) print("-------------------------") print("") while True: # os.system('clear') print("CALCULADORA") print("Pulsa el numero de la operacion que quieras realizar:") print("1 - Suma") print("2 - Resta") print("3 - Multiplicacion") print("4 - Division") print("5 - Cerrar") print("Numero: ") operacion = int(input()) if operacion == 1: suma() elif operacion == 2: resta() elif operacion == 3: multiplicacion() elif operacion == 4: division() elif operacion == 5: print("Cerrando...") exit()
c5b3dc5b01f78e7ec8d6b1cc1debc60c982c6978
XinZhaoFu/leetcode_moyu
/557反转字符串中的单词III.py
470
3.859375
4
""" 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 示例: 输入:"Let's take LeetCode contest" 输出:"s'teL ekat edoCteeL tsetnoc" """ class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ res = [] for element in s.split(' '): res.append(element[::-1]) return ' '.join(res)
a1d75831b07ba3dd5ae0ff44ff9fef17b8f88255
Deepbiogroup/affiliation_parser
/affiliation_parser/parser/parse_zipcode.py
651
3.765625
4
import re def parse_zipcode(affil_text: str): """ Parse zip code from given affiliation text https://github.com/unicode-org/cldr/blob/release-26-0-1/common/supplemental/postalCodeData.xml """ zip_code_res = [ r"\d{7}", r"\d{6}", r"\d{5}(-\d{4})?", r"\d{3}(-\d{4})?", r"\d{4}", r"\d{3}[ ]\d{2}", r"\d{2}[ -]\d{3}", ] zip_code = "" for code_re in zip_code_res: zip_code = re.search(code_re, affil_text) if zip_code: break zip_code_group = "" if zip_code: zip_code_group = zip_code.group() return zip_code_group
9aa51936e84dfb578b591c7202d2527adb5ecbd0
Escarzaga/calculator
/main.py
472
4.34375
4
calculate1 = int(input("Tell me a number: ")) calculate2 = int(input("Tell me a second number: ")) operation = input("Which arithmetic operation should I use: +, -, * or /?: ") if operation == "+": print(calculate1 + calculate2) elif operation == "-": print(calculate1 - calculate2) elif operation == "*": print(calculate1 * calculate2) elif operation == "/": print(calculate1 / calculate2) else: print("Operation not valid, please try again!")
83c30a6a3ebdfea64a120036d654c9fe1c283192
kevivforever/pythonWorkspace
/Learn python the hard way/ex34.py
212
3.9375
4
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] print "The animal at 1: " + animals[0] for animal in animals: print animal print for i in range(len(animals)): print animals[i]
52a28119e63254ba4560cb35288fe92097a28193
buelmanager/python_edu
/level4/day9_exception_1.py
958
4.15625
4
# 예외처리 # print ("나누기 전용 프로그램") # try: # num1 = int ( input("첫 번째 숫자를 입력하세요.")) # num2 = int ( input("두 번째 숫자를 입력하세요.")) # print ( "{0} / {1} = {2}".format(num1 , num2 , num1/num2)) # except ValueError: # print (" 에러! 잘못된 값을 입력하였습니다.") # except ZeroDivisionError as err: # print (err) ## 예외처리 2 print ("나누기 전용 프로그램") try: nums = [] nums.append(int ( input("첫 번째 숫자를 입력하세요."))) nums.append(int ( input("두 번째 숫자를 입력하세요."))) #nums.append(nums[0]/nums[1]) # 에러발생 print ( "{0} / {1} = {2}".format(nums[0] , nums[1] , nums[2])) except ValueError: print (" 에러! 잘못된 값을 입력하였습니다.") except ZeroDivisionError as err: print (err) except Exception as err: print("알수없는 에러 발생 ! ") print(err)
54ee5e013ec5b2707d38c43792a4d45fc07c42aa
WangYue1998/Algorithms-and-Data-Structures
/project5/p5.py
5,051
4.125
4
""" # Project 5 # Name: Yue Wang # PID: A54267282 """ """implement a circular queue. A queue is an abstract data type where the first item in is the first item out. A circular queue is one that uses an underlying list and uses modulo arithmetic to allow for reuse of space after enqueues and dequeues. """ class CircularQueue(): # DO NOT MODIFY THESE METHODS def __init__(self, capacity=4): """ Initialize the queue with an initial capacity :param capacity: the initial capacity of the queue """ self.capacity = capacity self.size = 0 self.data = [None] * capacity self.head = 0 self.tail = 0 def __eq__(self, other): """ Defines equality for two queues :return: true if two queues are equal, false otherwise """ if self.capacity != other.capacity: return False for i in range(self.capacity): if self.data[i] != other.data[i]: return False return self.head == other.head and self.tail == other.tail and self.size == other.size # -----------MODIFY BELOW-------------- def __str__(self): ''' This method is solely for development purposes for you and will not be tested. :return: the data in self.data ''' if self.size == 0: return "Empty Stack" output = [] for i in range(self.size): output.append(str(self.data[i])) return "{} Capacity: {}".format(output, str(self.capacity)) def is_empty(self): """ check if the queue is empty O(1) time complexity, O(1) space complexity :return: Returns whether or not is empty (bool) """ return self.size == 0 def __len__(self): """ get the length of queue O(1) time complexity, O(1) space complexity :return: Returns the size of the queue """ return self.size def first_value(self): """ get the first value of queue O(n) time complexity, O(1) space complexity :return: Returns the front of the queue """ if not self.is_empty(): return self.data[self.head] return None def enqueue(self, val): """ add the val to the queue O(1)* time complexity, O(1)* space complexity :param val: Add a number to the back of the queue :return: Return None """ if self.size+1 == self.capacity: self.grow() # double the array size #avail = (self.head + self.size) % len(self.data) self.data[self.tail] = val self.size += 1 self.tail = (self.tail + 1) % self.capacity return None def dequeue(self): """ delete the front value of queue O(1)* time complexity, O(1)* space complexity Remove an element from the front of a queue if not empty, do nothing otherwise :return: Return element popped """ if not self.is_empty(): answer = self.data[self.head] self.data[self.head] = None # help garbage collection self.head = (self.head + 1) % self.capacity self.size -= 1 if self.size <= self.capacity//4 and self.capacity > 4: self.shrink() return answer return None def grow(self): """ double the capacity of queue O(n) time complexity, O(n) space complexity Moves the head to the front of the newly allocated list Doubles the capacity of the queue immediately when capacity is reached to make room for new elements :return: no return """ old = self.data # keep track of existing list self.capacity = self.capacity*2 self.data = [None] * (self.capacity) # allocate list with new capacity walk = self.head for k in range(self.size): # only consider existing elements self.data[k] = old[walk] # intentionally shift indices walk = (1 + walk) % len(old) # use old size as modulus self.head = 0 # front has been realigned def shrink(self): """ half the capacity of queue Halves the capacity of the queue if the size is 1/4 of the capacity Capacity should never go below 4 Moves the head to the front of the newly allocated list O(n) time complexity, O(n) space complexity :return: no return """ old = self.data # keep track of existing list self.capacity = self.capacity // 2 self.data = [None] * (self.capacity) # allocate list with new capacity walk = self.head for k in range(self.size): # only consider existing elements self.data[k] = old[walk] # intentionally shift indices walk = (1 + walk) % len(old) # use old size as modulus self.head = 0 # front has been realigned self.tail = self.size
4a15231674ae1829cf1c7fccca70d72926349d08
joelhrobinson/Python_Code
/queue_popleft_pop.py
731
4.125
4
#Importing the library from collections import deque #Creating a Queue print ("DEQUE creates a FIFO queue") myQueue = deque([1,5,8,9]) #Enqueuing elements to the Queue print ("myQueue.append(99) & myQueue.appendleft(66)") myQueue.append(99) # put value on DEFAULT side of queue (RIGHT) myQueue.appendleft(66) # put value on LEFT side of queue print("print queue:", myQueue) #Dequeuing elements from the Queue print ("myQueue.POPLEFT removes from queue") ii = myQueue.popleft() #[5,8,9,7,0] jj = myQueue.pop() # POP RIGHT print ("FIFO= ", ii) print ("FIFO= ", jj) #Printing the elements of the Queue print("print queue:", myQueue) x = len(myQueue) print ("length of queue:", x )
bfbafbeb89522b1675b539e2e74c8e81bc326001
Haseeb-Sha/Npci-Training
/Python/day 4 code 1.py
412
3.546875
4
class project: project=["p1","p2","p3"] class user(project): users=["u1","u2","u3"] def operation(self): pro_user=["p1","P1","p2","P2","p3","P3"] salary={"u3":5000,"u1":2000,"u2":3000} print(sorted(salary)) lst_dct={pro_user[i]:pro_user[i+1] for i in range(0 , 6 ,2)} print(lst_dct) ob=user() print(ob.project) print(ob.users) ob.operation()
61ca729a4d4ba69e12b409e975068a7d1aa05f69
Maaduu/guess_a_number
/guess_a_number_V3.py
713
4.03125
4
from random import randint number_to_guess = randint(1, 25) number_try = 5 i = 0 i = int(i) while i < number_try: attempt = input('Enter a number ({0} attempt): '.format(i + 1)) attempt = int(attempt) if attempt < number_to_guess: print('The number to guess is bigger than {0}'.format(attempt)) elif attempt > number_to_guess: print('The number to guess is smaller than {0}'.format(attempt)) elif attempt == number_to_guess: print('Bravooo! You have won in {0} attempt(s)'.format( i + 1)) break i += 1 if attempt != number_to_guess: print('You lost.') print('The number to guess was: {0}'.format(number_to_guess)) print('Game over.')
4cf739aff331824529a6e6009a5a531a0a91d7dd
abishekravi/guvipython
/h95.py
489
3.859375
4
#a import math def isprime(x): if(x ==2): return True elif(x%2 == 0): return False else: for j in range(2,int(math.sqrt(x)+1)): if(x%j == 0): return False return True n = int(input("")) prime = [] for i in range(2,n): if(isprime(i)): prime.append(i) if(len(prime)>0): if(prime[-1] == 97): print(" ".join(map(str,prime)),"") else: print(" ".join(map(str,prime))) else: print(0)
de522cec22d3df58447dc73e77b80bc2ab5a8e80
nandansn/pythonlab
/durgasoft/chapter71/example-4.py
131
3.59375
4
import re pattern = input('enter pattern:') text = input('enter test:') listObjs = re.split(pattern,text) print(listObjs)
f3f8bf9ab914e8c753c6898a8c5aaadf9139ce2d
jiwon11/pythonProgramming
/student_input.py
422
3.9375
4
studentNumber = input('학번 :') name = input('이름: ') firstNum = int(input('첫번째 수: ')) secondNum = int(input('두번째 수: ')) str1 = studentNumber+name print(str1[0],str1[1],str1[2],str1[3],str1[4],str1[5],str1[6],str1[7],str1[8],str1[9],str1[10],str1[11]) print(str1[-1],str1[-2],str1[-3],str1[-4],str1[-5],str1[-6],str1[-7],str1[-8],str1[-9],str1[-10],str1[-11],str1[-12]) print(str1[firstNum:secondNum])
a7adf983ca48f2bd9d08422c2a6214177b453747
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_74/205.py
2,894
3.59375
4
#/usr/bin/env python import sys DEBUG = False def debug(string): if DEBUG: print string def other(robot): if robot == "O": return "B" elif robot == "B": return "O" else: raise Error def find_next_target(movs, info, robot): idx = info[robot]["next_idx"] if idx == len(movs) - 2: info[robot]["next"] = -1 info[robot]["next_idx"] = -1 return False for i in range(idx+2, len(movs), 2): if movs[i] == robot: info[robot]["next"] = movs[i + 1] info[robot]["next_idx"] = i return True info[robot]["next"] = -1 info[robot]["next_idx"] = -1 return False def next_action(movs, info, robot): if info[robot]["next"] == -1: msg = "Finished" else: if str(info[robot]["cur"]) == str(info[robot]["next"]): if info["gen"]["current_idx"] == info[robot]["next_idx"]: info["gen"]["next_idx"] = info["gen"]["current_idx"] + 2 info["gen"]["current_idx"] = -10 msg = "Push " + str(info[robot]["cur"]) find_next_target(movs, info, robot) else: msg = "Stay at " + str(info[robot]["cur"]) else: msg = "Move from %s to %s" % (str(info[robot]["cur"]), str(info[robot]["next"])) if int(info[robot]["next"]) > int(info[robot]["cur"]): info[robot]["cur"] += 1 else: info[robot]["cur"] -= 1 return msg def print_status(seconds, action_o, action_r): return "%s | %s | %s" % (seconds, action_o, action_r) in_file = sys.argv[1] fp = open(in_file) for case in range (1, int(fp.readline())+1): debug("Case %s: " % (case)) seconds = 0 movs = fp.readline().split() debug(movs) debug("T | Orange | Blue") movs_number = int(movs[0]) info = { "gen": { "current_idx": 1, "next_idx": -1 }, "O": { "cur": 1, "next": -1, "next_idx": -1 }, "B": { "cur": 1, "next": -1, "next_idx": -1 } } find_next_target(movs, info, "O") find_next_target(movs, info, "B") while(True): seconds +=1 action_o = next_action(movs, info, "O") action_r = next_action(movs, info, "B") if info["gen"]["current_idx"] == -10: info["gen"]["current_idx"] = info["gen"]["next_idx"] info["gen"]["next_idx"] = -10 debug(print_status(seconds, action_o, action_r)) if info["O"]["next_idx"] == -1 and info["B"]["next_idx"] == -1: break # For testing purposes #if seconds == 10: # break print "Case #%s: %s" % (str(case), seconds) # For testing purposes #if case == 1: # break debug("")
a71d663205a17020b7241fff0c0a5e175c74c6ea
debiprasadmishra50/100-Python-Projects
/Intermediate Projects/22_Spirograph_and_Hirst_Painting/spirograph.py
603
3.953125
4
from turtle import Turtle, Screen import random, turtle as t size = int(input("Enter the gap size in degrees(10-30 for better view): ")) t.colormode(255) def random_color(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) new_color = (r, g, b) return new_color tim = Turtle() tim.speed(speed=0) def draw_spirograph(size_of_gap): for _ in range(360 // size_of_gap): tim.color(random_color()) tim.circle(100) tim.setheading(tim.heading() + size_of_gap) draw_spirograph(size) screen = Screen() screen.exitonclick()
68791138916a31f46bc4df873dfeaafaa824ede6
dragevil007/pro-c-97
/pro c-97/guessingGame.py
470
4.21875
4
import random number=random.randint(1,9) chances=0 print("guess a number between 1 and 9") while chances<5: guess=int(input("enter you guess")) if guess==number: print("congratulation you won") elif guess< number: print("your guess was too low",guess) else: print("your guess was too high",guess) chances += 1
aa4df7e737b92bd092a3206c568cd79a77e60ff9
Matteomnd/TP11
/EXERCICE3.py
1,751
3.71875
4
class Rational : def __init__(self, numerator, denominator=1): self.__numerator = numerator self.__denominator = denominator def get_numerator(self): return self.__numerator def get_denominator(self): return self.__denominator def __add__(self, f1): if isinstance(f1, Rational): if self.__denominator==0 or f1.__denominator==0 : return 'erreur : division par 0' return Rational(int(self.__numerator*f1.__denominator + self.__denominator*f1.__numerator)/int(self.__denominator*f1.__denominator)) else : print('no instance of f1') def __sub__(self,f1): if isinstance(f1, Rational): if self.__denominator==0 or f1.__denominator==0 : return 'erreur : division par 0' return Rational((self.__numerator*f1.__denominator - self.__denominator*f1.__numerator)/(self.__denominator*f1.__denominator)) else : print('no instance of f1') def __eq__(self,f1): if isinstance(f1, Rational): if self.__denominator==0 or f1.__denominator==0: return self.__numerator, f1.__numerator else : reste1 = self.__numerator % self.__denominator reste2 = f1.__numerator % f1.__denominator return (self.__numerator / reste1)==(f1.__numerator/reste2), (self.__denominator/reste1)==(f1.__denominator/reste2) def __str__(self): return 'fraction 1 :'+str(self.__numerator)+'/'+str(self.__denominator) if __name__ == '__main__' : f1 = Rational(3,2) f2 = Rational(1,2) f3 = f1 + f2 f4= f1 -f2 f5 = f1 == f2 print(f3) print (f4) print (f5)
c69b81da47524aa9f13738e0ec77f61758159e78
youthcodeman/self-learning-python
/org.hzg.pyLearn/函数/simpleFunction.py
2,246
3.734375
4
#_*_ coding:utf-8 _*_ # def pName() : # # 声明函数的功能 # print("这是一个函数") # # # pName() # # # def pName1(userName) : # print("我叫%s"%username) # # # pName1("zhangsan") # def pname2(num1,num2) : # a = num1 + num2 # print("求和结果:%d"%a) # # # # pname2(25,50) # pname2(num2=5888,num1=9999) #关键字参数,在调用的时候添加参数的关键字 # def pname2(num1,num2 = 56) : # a = num1 + num2 # print("求和结果:%d"%a) # # # pname2(25,50) # pname2(8688) #默认值,在函数声明的时候声明默认值,这样在调用的时候可以不用传该参数 #不定长参数 # def pname2(num1,num2,*args,**args1) : # a = num1 + num2 # print("求和结果:%d"%a) # print(args) # print(args1) # # # pname2(25,50) # #不定长参数,当用*args则表示接受所有未命名的参数,且是一个元组,用**args则表示接受除了必须参数外的所有已经命名的参数,且是一个字典 # pname2(8688,1,'9876','666','7777','45','2',name="zhangsan",age=19,address="浙江省") #可变对象和不可变对象,可以类比java的值传递和引用传递,传递不可变对象类似于值传递,相当于参数值复制一遍,对原值不会影响 # def temp(str1) : # str1 = "hello world" # print(str1) # # a = "begin" # print(a) # temp(a) # print(a) #可变对象,相当于传递对象本身,函数中操作该可变对象,则其在内存中的值真实的会发生改变 # def temp(args): # args[0] = 2333; # print(args) # # a = [1,2,3,4,5,6] # print(a) # temp(a) # print(a) #返回值 # def max(x,y): # if x > y : # return x # else: # return y # # print(max(5,8)) # # def temp(x,y): # return x,y # # num1 = temp(65,86) # print(num1) # num2,num3 = temp(65,86) # print(num2) # print(num3) #yield 迭代器 # def temp(a) : # i = 0 # while i < a: # yield i # i +=1 # # b = temp(20) # for c in b: # print(c) # a = [x for x in range(100000000)] # print(a) # a = (x for x in range(1000)) # print(a) # for i in a: # print(i) # list1 = [1,2,3,4,5] # a = iter(list1) # for i in list1: # print(i) for i in range(10000): print("i love you")
c5ba8f1e39a86eff16f48d375802942102c7c96c
ErikBuchholz/kidsMathQuiz
/kidsMathQuiz/user_interface.py
1,626
3.78125
4
# # # # # # # def display_dialogue(prob_text, question_num): print("\n") display_problem(prob_text, question_num) user_answer = get_answer() return user_answer # # # # # def display_problem(prob_text, question_num): print("Question #%d: %s" % (question_num, prob_text)) # # # # # def get_answer(): answer = input("> Your answer: ") return answer # # # # def display_result(question_pass_fail, user_answer, correct_answer): if (question_pass_fail == True) : feedback = "Job well done!" else: feedback = "You will have to practice this problem again." # Handle blank answers if user_answer == '': result_string = "You failed to provide any answer at all." else: result_string = "Result: " + str(question_pass_fail) + ", you entered " + \ str(user_answer) + " and the correct answer is " + \ str(correct_answer) + "." print(result_string) print(feedback) return 0 # display_test_summary() # # Args: (float) percent_correct # (int) total_num_correct # (int) total_questions # (int) total_num_tries # Rets: def display_test_summary(percent_correct, total_num_correct, total_questions, total_num_tries): print("\n#########################################") print(" Test Summary") print(" %.2f%% correct the first time" % percent_correct) print(" %d correct of %d questions" % (total_num_correct, total_questions)) print(" %d total tries (including repeats)" % total_num_tries) print("#########################################")
d235a9369335941d768cbd9ede73033df1154813
prashant133/Labwork
/Lab4/question9.py
208
4.34375
4
''' 9.Write a program to find the factorial of a number. ''' num = int(input("enter the value: ")) factorial = 1 while num > 0 : factorial = num * factorial num = num -1 print('factorial:',factorial,)
bc6e24c0924b0370e62b84535ee7fe939cf5a611
scorourk/PBD_SOR
/CA_3/car.py
3,149
4.125
4
#CA 3 Programming for Big data. B8IT105 (B8IT105_1617_TMD3) #Stuart O'Rourke #Student Number: 10334192 #DBS Car Rental. #Object is blue print, methods pass arguement to Class object. #Determination of the objects that make up the system. class Car(object):#Class definitions for car objects Petrol, Electric, Diesel, Hybrid. # initiate the objects as above, associate attributes. #Private instance variables of a class begin with two underscore characters (e.g., __colour) and cannot be directly accessed def __init__(self):#Things an object knows about itself are called instance variables. An object will present an interface to other objects to allow interaction. self.__colour = ''#class variable atrributes colour, hidden/private, self by convention. self.__make = ''# class variable make hidden/private self.__mileage = 0 # class variable mileage/private self.engineSize = ''# classs variable engine size/not hidden def getColour(self):#The things an object can do are called methods. Set and get are ways of accessing Private instance variables. return self.__colour # get methods colour, make, milage. A method is a function that belongs to an object and passes arguements to the object def getMake(self): return self.__make def getMileage(self): return self.__mileage def setColour(self, colour):#set method, colour, make, milage. self.__colour = colour def setMake(self, make): self.__make = make def setMileage(self, mileage): self.__mileage = mileage class ElectricCar(Car):#sub class of object, inherits from Class Object blueprint. def __init__(self): Car.__init__(self) self.__numberOfFuelCells = 4 def getNumberOfFuelCells(self): #set number of fuel cells return self.__numberOfFuelCells def setNumberOfFuelCells(self, value): # set number of fuel cells self.__numberOfFuelCells = value class PetrolCar(Car):#sub class of object, inherits from Class Object blueprint. def __init__(self): Car.__init__(self) self.__cubic_capacity = 1 # number of litres or cubic capacity in Cubic centimetres CC def getCubicCapacity(self): return self.__cubic_capacity def setCubicCapacity(self, value): self.__CubicCapacity = value #Set cubic capacity of engine class DieselCar(Car):#sub class of object, inherits from Class Object blueprint. def __init__(self):# Define cubic capacity Diesel Car.__init__(self) self.__cubicCapacityD = 2.6 def getCubicCapacityD(self): return self.__CubicCapacityD # Return value of Cubic capacity def setCubicCapacityD(self, value): self.__CubicCapacityD = value class HybridCar(Car):##sub class of object, inherits from Class Object blueprint. def __init__(self): Car.__init__(self) self.__CubicCapacityH = 2.2 #Normal petrol engine in Hybrid, coupled with fuel cells, def getCubicCapacityH(self): return self.__CubicCapacityH def setCubicCapacityH(self, value): self.__CubicCapacityH = value
7508e0bff3e609c78f20b973bf4c9849c952212d
gabriellaec/desoft-analise-exercicios
/backup/user_383/ch34_2019_03_21_22_35_56_976243.py
226
3.640625
4
contador = 1 deposito_inicial=float(input('Qual o valor do depósito inicial?')) taxa_juros=float(input('Qual a taxa de juros da poupança?')) while contador<=24: print(deposito_inicial*taxa_juros*contador) contador+=1
ae8087e6c0ab6d86e6abdf3327a08417c5c13181
izdomi/python
/exercise6.py
327
4.40625
4
# Ask the user for a string and print out whether this string is a palindrome or not. string = input("the word: ") i = 0 while i in range(len(string)-1): if string[i] != string[len(string)-1-i]: print("The word is not a palindrome!") break else: print("The word is a palindrome!") break
b923d1984830fafd1caebe85e9bfff3083cf24f8
noorah98/python1
/Session28B.py
1,260
4.03125
4
import pandas as pd nums1 = [10, 20, 30, 40, 50] nums2 = [11, 22, 33, 44, 55] emp1 = {"name": "John", "age": 22, "salary": 30000} emp2 = {"name": "Fionna", "age": 24, "salary": 45000} emp3 = {"name": "Dave", "age": 26, "salary": 54000} emp4 = {"name": "Kia", "age": 28, "salary": 59000, "email": "kia@example.com"} frame1 = pd.DataFrame([nums1, nums2]) frame2 = pd.DataFrame([emp1, emp2, emp3, emp4]) print(frame1) print("-----") print(frame2) print("--Access Data in DataFrame--") # Fetch data Column Wise :) print(frame1[0]) print(frame2["name"]) print(frame1[1][1]) print(frame2["salary"][2]) print("--Apply Slicing on Data in DataFrame--") print(frame1[0:1]) # print(frame1[0:]) print(frame2[0:2]) print("--Delete Data in DataFrame--") # del frame1[0] # print(frame1) # Deleting a Row or Column # drop -> either axis=0 (ROW) or axis=1(Column) # This operation is IMMUTABLE i.e. will generate a new DataDrame :) print("--drop--") # frame3 = frame1.drop(0, axis=0) # print(frame1) # No Change :( # print(frame3) # With Changes :) # Changes will be done in the same DataFrame frame1.drop(0, axis=0, inplace=True) print(frame1) # Deleting a Value in DataFrame print("--Update Data in DataFrame--") # frame1[1][1] = 111 frame1[1] = 111 print(frame1)
5128c3f14b31157065f5c140a59a7c69244c6123
niteshkrsingh51/hackerRank_Python_Practice
/itertools/itertools_combinations.py
493
3.734375
4
from itertools import combinations_with_replacement string,length = input().split() length = int(length) my_list = list(combinations_with_replacement(sorted(string),length)) print(my_list) def join_tuple_strings(my_list): return ' '.join(my_list) my_Iterator = map(join_tuple_strings, my_list) result_list = list(my_Iterator) my_list_2 = [] print(result_list) for items in result_list: my_list_2.append(items.replace(' ','')) for items2 in my_list_2: print(items2)
363d018bd56f4d8371417a82d823108d49ca1ab6
hechty/datastructure
/5.9-insertionsort.py
590
4.09375
4
#! /usr/bin/env python3 def insertion_sort(alist): orded_list = alist[:1] for i in range(len(alist)-1): new_data = alist[i+1] orded_list = insertion(new_data, orded_list) return orded_list def insertion(new_data, orded_list): posi = 0 for i in range(len(orded_list) - 1, -1, -1): if new_data >= orded_list[i]: posi = i + 1 break orded_list.insert(posi, new_data) return orded_list ls = input("input a list of num: ").split() ls = [int(x) for x in ls] sorted_ls = insertion_sort(ls) print(sorted_ls)
a6d0215634786fc26a19e54c916479c7dca842fa
seenaimul/OpenCV_Course_freecodecamp
/Advance/smoothing.py
725
3.921875
4
import cv2 as cv img = cv.imread('Resources/Photos/cats.jpg') cv.imshow('Cats',img) # We smooth an image when it has a lot of noise # reduce noise / smooth the image using blur technique # kernel size is number of rows and columns # 1. Averaging average = cv.blur(img, (3,3)) # The more the kernel size the more blur the image will be cv.imshow('Average Blur',average) # 2. Gaussian Blur gaussian = cv.GaussianBlur(img,(3,3),0) # 0 is the sigmaX or Standard Diviation in the X direction cv.imshow('Gaussian Blur',gaussian) # 3. Median Blur median = cv.medianBlur(img,3) cv.imshow('Median Blur',median) # 4. Bilateral Blur bilateral = cv.bilateralFilter(img,5,15,15) cv.imshow('Bilateral Blur',bilateral) cv.waitKey(0)
39aeb3a0d655fc0f074025c8188f052dd7661dd5
Thalrod/Yatwog
/game/shape/rectangle.py
1,644
3.640625
4
import pygame class Rectangle(): def __init__(self, screen, x, y, width, height, color): self.screen = screen self.x = x self.y = y self.width = width self.height = height self.color = color self.rectangle = pygame.Rect(self.x, self.y, self.width, self.height) self.obj = self def get(self, attrib): """ :param attrib: str """ try: return eval("self." + attrib) except: print(attrib + "is not attribute of Ractangle() there is: screen, x, y, width, height, color or rectangle") def update(self, attrib, value): """ :param attrib: str """ try: var = eval("self." + attrib) var = value except: print(attrib + "is not attribute of Rectangle() there is: screen, x, y, width, height, color or rectangle") def getInfo(self): return self.screen, self.x, self.y, self.width, self.height, self.color def draw(self, color=None): if color is None: color = self.color width = self.width height = self.height x0 = width * self.x y0 = height * self.y x1 = width * (self.x + 1) y1 = height * (self.y + 1) vertexCoord = (((x0, y0), (x1, y0), (x0, y1)), ((x1, y0), (x1, y1), (x0, y1))) pygame.draw.polygon(self.screen, color, vertexCoord[0]) pygame.draw.polygon(self.screen, color, vertexCoord[1]) def changeColor(self, color): self.color = color def highlight(self, color): self.draw(color=color)
b443ebf83b3a064a8bd5da2e9d46aaa49d9ee6b1
fdr896/keyboard
/keyboard
2,300
3.59375
4
#!/bin/python3 import sys, subprocess def Help(): print("""Usage: keyboard <command> [options] Commands: on turns on embeded keyboard off turns off embeded keyboard Options: -n, --name <"name"> turns on/off keyboard with received name [default: AT Translated Set 2 keyboard] Use "keyboard --help" to see usage guide.""") def GetDeviceList(): devices = subprocess.run(['xinput', 'list'], stdout=subprocess.PIPE).stdout.decode('utf-8') return devices.split('\n') argv = sys.argv if len(argv) in [2, 4]: mode = argv[1] keyboard_name = 'AT Translated Set 2 keyboard' if len(argv) == 4: if mode in ['on', 'off'] and argv[2] == '-n' or argv[2] == '--name': keyboard_name = argv[3] else: Help() exit(0) if mode == 'on': devices = GetDeviceList() found = False switched = False for device in devices: if device.find(keyboard_name) != -1: found = True if device.find('∼ ' + keyboard_name) != -1: i = device.find('id') id = device[i + 3:i + 5] subprocess.run(['xinput', 'reattach', id, '3']) print('Keyboard turned on') switched = True break if not(found): print("""No such keyboard found Use "xinput list" to see list of devices""") elif not(switched): print('Keyboard is already turned on') elif mode == 'off': devices = GetDeviceList() found = False switched = False for device in devices: if device.find(keyboard_name) != -1: found = True if device.find('↳ ' + keyboard_name) != -1: i = device.find('id') id = device[i + 3:i + 5] subprocess.run(['xinput', 'float', id]) print('Keyboard turned off') switched = True break if not(found): print("""No such keyboard found Use "xinput list" to see list of devices""") elif not(switched): print('Keyboard is already turned off') elif mode == '--help': Help() else: Help() else: Help()
54d81fcf7e6d327e7368df9924335c1e64e64113
roger6blog/LeetCode
/SourceCode/Python/Problem/00904.Fruit Into Baskets.py
2,161
3.984375
4
''' Level: Medium You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array fruits, return the maximum number of fruits you can pick. Example 1: Input: fruits = [1,2,1] Output: 3 Explanation: We can pick from all 3 trees. Example 2: Input: fruits = [0,1,2,2] Output: 3 Explanation: We can pick from trees [1,2,2]. If we had started at the first tree, we would only pick from trees [0,1]. Example 3: Input: fruits = [1,2,3,2,2] Output: 4 Explanation: We can pick from trees [2,3,2,2]. If we had started at the first tree, we would only pick from trees [1,2]. Constraints: 1 <= fruits.length <= 10^5 0 <= fruits[i] < fruits.length ''' class Solution(object): def totalFruit(self, fruits): """ :type fruits: List[int] :rtype: int """ from collections import deque, Counter if len(fruits) <= 2 or len(Counter(fruits)) <= 2: return len(fruits) queue = deque() ans = 0 for f in fruits: queue.append(f) c = Counter(queue) while len(c) > 2: queue.popleft() c = Counter(queue) ans = max(ans, len(queue)) print(ans) return ans fruits = [1,2,3,2,2] Solution().totalFruit(fruits) fruits = [0,1,2,2] Solution().totalFruit(fruits) fruits = [3,3,3,1,2,1,1,2,3,3,4] assert 5 == Solution().totalFruit(fruits) fruits = [3,3,3,3,3,3] assert 6 == Solution().totalFruit(fruits)
bde04f1e7839bee2f0f752d289977d2585ea6baf
jkirubakaran/python-learn
/scratch/fib.py
262
3.828125
4
import time def fib(num): if num < 3: return 1 a = b = 1 for i in range(2,num): a, b = b, a+b return b def fibRecursive(num): if num < 3: return 1 return fibRecursive(num - 1) + fibRecursive(num - 2) #print(fib(40)) print(fibRecursive(40))
ef138fa3c22a5219b688383b662881d54b3055d4
luisbenitez02/Codeaccademy
/python/19-listas_Array_(nuevos_metodos).py
902
3.921875
4
lenguajes_geniales=["python", "Ruby On Rails", "Javascript", "Swift", "Java", "node.js"] print("Esta era la lista antes de modificarla: \n",lenguajes_geniales) #FUNCION index() busca un string dentro del array y me devuelve su posicion en un int me_gusta= lenguajes_geniales.index("Javascript") print("Este el el numero de indice donde se ubica Javascript, dentro del array: \n ", me_gusta) #agregaremos un nuevo elemento al Array PERO EN LA MITAD DE ESTE #tomaremos el valor que devuelve la funcion index() y lo cambiaremos por otro string #todo esto usando la funcion insert() añade un elemento en el lugar que deseemos lenguajes_geniales.insert(me_gusta,"HTML5") #me_gusta contiene un numero entero NO una variable completa de tipo array nam[i] print("Ahora que modificamos la lista, se ve asi: \n", lenguajes_geniales) print("Viste como agregamos HTML5 en la mitad de toda esa lista? Genial!")
1019c4591a3f1526ceb5fe027949b2f7667beac0
krishnanunni-pr/Pyrhon-Django
/PYTHON_COLLECTIONS/List/pop function.py
132
3.859375
4
# pop fuction is used to remove last element from a list lst=[1,2,3,4,5,6,7] lst.pop()# removes last element that is 7 print(lst)
11a7641848efccc92738d6cbe69018d8c36fdd8e
betty29/code-1
/recipes/Python/576533_script_calculating_simple/recipe-576533.py
247
4
4
print "all amounts should be in dollars!" while True: P=float(raw_input("enter Principal:")) i=float(raw_input("enter Percentage of interest rate:")) t=float(raw_input("enter Time(in years):")) I=P*t*(i/100) print "Interest is", I,"dollars"
fb86b1b77a10d5277d86c5c9041fba24571da14e
project-anuvaad/anuvaad
/anuvaad-etl/anuvaad-extractor/file_translator/etl-file-translator/Nudi/nudi_font.py
14,817
4.21875
4
import re def process_vattakshara(letters, t): """ Current char is t, which is ASCII code of vattakshara Rearrangement of string needed, If prev char is dependent vowel then it has to be moved after vattakshara If no dependent vowel then it is "ಅ" kaara, Ex: ಕ, ಗ Vattakshara shares same code as of base letter, but halant is added before Ex: ತಿಮ್ಮಿ in ASCII: ತಿ + ಮಿ + ma_vattu in Unicode: ತ + dependent vowel ಇ + ಮ + halant + ಮ + dependent vowel ಇ """ # Default values last_letter = "" second_last = "" op = "" # If atleast one letter in letters, to find the last letter value if len(letters) > 0: last_letter = letters[-1] # If atleast two letters in letters, to find the second last letter value if len(letters) > 1: second_last = letters[-2] if last_letter in dependent_vowels: # If last letter/prev letter to vattakshara is dependent vowel # add dependent vowel at the end, after halant + base letter(=vattakshara) letters[-1] = "್" letters.append(vattaksharagalu[t]) letters.append(last_letter) else: # If "ಅ" kaara, just append halant + base letter # No worry about rearranging letters.append("್") letters.append(vattaksharagalu[t]) # Return converted return letters def process_arkavattu(letters, t): """ Example: ವರ್ಷ in ASCII ವ + ಷ + arkavattu in Unicode ವ + ರ + halant + ಷ """ last_letter = "" second_last = "" # If atleast one letter in letters, to find the last letter value if len(letters) > 0: last_letter = letters[-1] # If atleast two letters in letters, to find the second last letter value if len(letters) > 1: second_last = letters[-2] # Rearrangement according to above example if last_letter in dependent_vowels: letters[-2] = ascii_arkavattu[t] letters[-1] = "್" letters.append(second_last) letters.append(last_letter) else: letters[-1] = ascii_arkavattu[t] letters.append("್") letters.append(last_letter) # Return converted return letters def process_broken_cases(letters, t): """ Since ASCII mapping are based on shapes some of the shapes give trouble with direct conversion Ex: ಕೀರ್ತಿ and ಕೇಳಿ In ASCII: deerga has same code in both but in Unicode both are different, So if prev char is "ಇ" kaara then behave differently and also with "ಎ" kaara Look at the prev char and also current char t and decide on the single unicode dependent vowel and substitute. Note prev char + current char = new char (Except ಉ kaara, ಕು = ಕ + ಉ kaara) since prev char is not dependent vowel """ # Defaults last_letter = "" second_last = "" # If atleast one letter in letters, to find the last letter value if len(letters) > 0: last_letter = letters[-1] # Get dependent vowel mapping with respect to input "t" broken_case_mapping = broken_cases[t]["mapping"] if last_letter in broken_case_mapping: # If mapping exists letters[-1] = broken_case_mapping[last_letter] else : # For ಉ kaara, no mapping, substitute the value letters.append(broken_cases[t]["value"]) # Return the converted return letters def find_mapping(op, txt, current_pos): """ Finds mapping in reverse order, For Example if input string is abcde then itteration will be for abcde, abcd, abc, ab, a Only when mapping available the index jumps, say if mapping availabale for ab then subtract length of ab while processing next """ # Combination length, if length remaining is less than max len then # Consider length remaining as max length # remaining length = len(txt) - current_pos max_len = 4 remaining = len(txt)-current_pos if remaining < 5: max_len = (remaining - 1) # Number of letters found mapping, will be returned to caller and # used to jump the index (Zero if one char found mapping) n = 0 # Loop 4 to 0 or max to 0 # Controller which checks direct mapping, # arkavattu, vattaksharagalu and broken cases for i in range(max_len,-1,-1): substr_till = current_pos + i + 1 t = txt[current_pos:substr_till] if t in mapping: # If prev char is halant and current char is not vattakshara? # then it must be seperated using ZWJ, so that it will not # mix with prev char. if len(op) > 0 and re.search("್$", op[-1]) != None: zwj = "‍" op.append(zwj) # Direct mapping case op.append(mapping[t]) # Update Jump by number n = i # Break and return to caller since we found the mapping # for given input break else: # Try without processing till reaches to last char if i > 0: continue op = list(''.join(op)) # # If Last in this batch if t in ascii_arkavattu: # Arkavattu op = process_arkavattu(op, t) elif t in vattaksharagalu: # Vattakshara op = process_vattakshara(op, t) elif t in broken_cases: # Broken cases op = process_broken_cases(op, t) else: # No match op.append(t) return [n, op] def process_line(line): """Splits the line into words and processes each word """ print('lines-----',line) # Clean the input # line = line.strip() #----------------- changed # Into words words = line.split(' ') # To stote converted words op_words = [] # Process and append to main array for word in words: op_words.append(process_word(word)) print('done',op_words) # Return converted line return ' '.join(op_words) def process_word(word): """Main program to process the word letter by letter """ # Initiate and output Array i = 0 max_len = len(word) op = [] while i < max_len: # For each letter in word, jump if data[0] is more than zero # If additional chars used in ASCII to improve readability, # which doesn't have any significant in Unicode if word[i] in ignore_list: i += 1 continue # print('word',word) # Find the mapping data data = find_mapping(op, word, i) # print('data-----------',data) # Add to final list op = data[1] # Jump if data[0]>0 which means found a match for more than # one letter combination i += (1 + data[0]) # Return processed return ''.join(op) def process_line(line): """Splits the line into words and processes each word """ # print('lines-----',line) # Clean the input # line = line.strip() #----------------- changed # Into words words = line.split(' ') # To stote converted words op_words = [] # Process and append to main array for word in words: op_words.append(process_word(word)) # print('done',op_words) # Return converted line return ''.join(op_words) mapping = { "C" : "ಅ", "D" : "ಆ", "E" : "ಇ", "F" : "ಈ", "G" : "ಉ", "H" : "ಊ", "IÄ" : "ಋ", "J" : "ಎ", "K" : "ಏ", "L" : "ಐ", "M" : "ಒ", "N" : "ಓ", "O" : "ಔ", "A" : "ಂ", "B" : "ಃ", "Pï" : "ಕ್", "PÀ" : "ಕ", "PÁ" : "ಕಾ", "Q" : "ಕಿ", "PÉ" : "ಕೆ", "PË" : "ಕೌ", "Sï" : "ಖ್", "R" : "ಖ", "SÁ" : "ಖಾ", "T" : "ಖಿ", "SÉ" : "ಖೆ", "SË" : "ಖೌ", "Uï" : "ಗ್", "UÀ" : "ಗ", "UÁ" : "ಗಾ", "V" : "ಗಿ", "UÉ" : "ಗೆ", "UË" : "ಗೌ", "Wï" : "ಘ್", "WÀ" : "ಘ", "WÁ" : "ಘಾ", "X" : "ಘಿ", "WÉ" : "ಘೆ", "WË" : "ಘೌ", "k" : "ಞ", "Zï" : "ಚ್", "ZÀ" : "ಚ", "ZÁ" : "ಚಾ", "a" : "ಚಿ", "ZÉ" : "ಚೆ", "ZË" : "ಚೌ", "bï" : "ಛ್", "bÀ" : "ಛ", "bÁ" : "ಛಾ", "c" : "ಛಿ", "bÉ" : "ಛೆ", "bË" : "ಛೌ", "eï" : "ಜ್", "d" : "ಜ", "eÁ" : "ಜಾ", "f" : "ಜಿ", "eÉ" : "ಜೆ", "eË" : "ಜೌ", "gÀhiï" : "ಝ್", "gÀhÄ" : "ಝ", "gÀhiÁ" : "ಝಾ", "jhÄ" : "ಝಿ", "gÉhÄ" : "ಝೆ", "gÉhÆ" : "ಝೊ", "gÀhiË" : "ಝೌ", "Y" : "ಙ", "mï" : "ಟ್", "l" : "ಟ", "mÁ" : "ಟಾ", "n" : "ಟಿ", "mÉ" : "ಟೆ", "mË" : "ಟೌ", "oï" : "ಠ್", "oÀ" : "ಠ", "oÁ" : "ಠಾ", "p" : "ಠಿ", "oÉ" : "ಠೆ", "oË" : "ಠೌ", "qï" : "ಡ್", "qÀ" : "ಡ", "qÁ" : "ಡಾ", "r" : "ಡಿ", "qÉ" : "ಡೆ", "qË" : "ಡೌ", "qsï" : "ಢ್", "qsÀ" : "ಢ", "qsÁ" : "ಢಾ", "rü" : "ಢಿ", "qsÉ" : "ಢೆ", "qsË" : "ಢೌ", "uï" : "ಣ್", "t" : "ಣ", "uÁ" : "ಣಾ", "tÂ" : "ಣಿ", "uÉ" : "ಣೆ", "uË" : "ಣೌ", "vï" : "ತ್", "vÀ" : "ತ", "vÁ" : "ತಾ", "w" : "ತಿ", "vÉ" : "ತೆ", "vË" : "ತೌ", "xï" : "ಥ್", "xÀ" : "ಥ", "xÁ" : "ಥಾ", "y" : "ಥಿ", "xÉ" : "ಥೆ", "xË" : "ಥೌ", "zï" : "ದ್", "zÀ" : "ದ", "zÁ" : "ದಾ", "¢" : "ದಿ", "zÉ" : "ದೆ", "zË" : "ದೌ", "zsï" : "ಧ್", "zsÀ" : "ಧ", "zsÁ" : "ಧಾ", "¢ü" : "ಧಿ", "zsÉ" : "ಧೆ", "zsË" : "ಧೌ", "£ï" : "ನ್", "£À" : "ನ", "£Á" : "ನಾ", "¤" : "ನಿ", "£É" : "ನೆ", "£Ë" : "ನೌ", "¥ï" : "ಪ್", "¥À" : "ಪ", "¥Á" : "ಪಾ", "¦" : "ಪಿ", "¥É" : "ಪೆ", "¥Ë" : "ಪೌ", "¥sï" : "ಫ್", "¥sÀ" : "ಫ", "¥sÁ" : "ಫಾ", "¦ü" : "ಫಿ", "¥sÉ" : "ಫೆ", "¥sË" : "ಫೌ", "¨ï" : "ಬ್", "§" : "ಬ", "¨Á" : "ಬಾ", "©" : "ಬಿ", "¨É" : "ಬೆ", "¨Ë" : "ಬೌ", "¨sï" : "ಭ್", "¨sÀ" : "ಭ", "¨sÁ" : "ಭಾ", "©ü" : "ಭಿ", "¨sÉ" : "ಭೆ", "¨sË" : "ಭೌ", "ªÀiï" : "ಮ್", "ªÀÄ" : "ಮ", "ªÀiÁ" : "ಮಾ", "«Ä" : "ಮಿ", "ªÉÄ" : "ಮೆ", "ªÀiË" : "ಮೌ", "AiÀiï" : "ಯ್", "AiÀÄ" : "ಯ", "0iÀÄ" : "ಯ", "AiÀiÁ" : "ಯಾ", "0iÀiÁ" : "ಯಾ", "¬Ä" : "ಯಿ", "0iÀÄÄ" : "ಯು", "AiÉÄ" : "ಯೆ", "0iÉÆ" : "ಯೊ", "AiÉÆ" : "ಯೊ", "AiÀiË" : "ಯೌ", "gï" : "ರ್", "gÀ" : "ರ", "gÁ" : "ರಾ", "j" : "ರಿ", "gÉ" : "ರೆ", "gË" : "ರೌ", "¯ï" : "ಲ್", "®" : "ಲ", "¯Á" : "ಲಾ", "°" : "ಲಿ", "¯É" : "ಲೆ", "¯Ë" : "ಲೌ", "ªï" : "ವ್", "ªÀ" : "ವ", "ªÁ" : "ವಾ", "«" : "ವಿ", "ªÀÅ" :"ವು", "ªÀÇ" :"ವೂ", "ªÉ" :"ವೆ", "ªÉÃ" :"ವೇ", "ªÉÊ" :"ವೈ", "ªÉÆ" :"ಮೊ", "ªÉÆÃ" :"ಮೋ", "ªÉÇ" :"ವೊ", "ªÉÇÃ" :"ವೋ", "ªÉ " : "ವೆ", "¥ÀÅ" : "ಪು", "¥ÀÇ" : "ಪೂ", "¥sÀÅ" : "ಫು", "¥sÀÇ" : "ಫೂ", "ªË" : "ವೌ", "±ï" : "ಶ್", "±À" : "ಶ", "±Á" : "ಶಾ", "²" : "ಶಿ", "±É" : "ಶೆ", "±Ë" : "ಶೌ", "µï" : "ಷ್", "µÀ" : "ಷ", "µÁ" : "ಷಾ", "¶" : "ಷಿ", "µÉ" : "ಷೆ", "µË" : "ಷೌ", "¸ï" : "ಸ್", "¸À" : "ಸ", "¸Á" : "ಸಾ", "¹" : "ಸಿ", "¸É" : "ಸೆ", "¸Ë" : "ಸೌ", "ºï" : "ಹ್", "ºÀ" : "ಹ", "ºÁ" : "ಹಾ", "»" : "ಹಿ", "ºÉ" : "ಹೆ", "ºË" : "ಹೌ", "¼ï" : "ಳ್", "¼À" : "ಳ", "¼Á" : "ಳಾ", "½" : "ಳಿ", "¼É" : "ಳೆ", "¼Ë" : "ಳೌ" } # These when joined will be broken as per unicode broken_cases = { "Ã":{ "value": "ೀ", "mapping": { "ಿ": "ೀ", "ೆ": "ೇ", "ೊ": "ೋ" } }, "Ä":{ "value": "ು", "mapping": { } }, "Æ":{ "value": "ೂ", "mapping": { "ೆ":"ೊ" } }, "È":{ "value": "ೃ", "mapping": { } }, "Ê":{ "value": "ೈ", "mapping": { "ೆ":"ೈ" } } } # Halant and dependent vowels dependent_vowels = ["್", "ಾ", "ಿ", "ೀ", "ು", "ೂ", "ೃ", "ೆ", "ೇ", "ೈ", "ೊ", "ೋ", "ೌ"] # Spacing chars in ASCII, can be ignored while converting to Unicode ignore_list = {"ö": "", "÷": ""} # ASCII vattaksharagalu and Unicode replacements vattaksharagalu = { "Ì" : "ಕ", "Í" : "ಖ", "Î" : "ಗ", "Ï" : "ಘ", "Õ" : "ಞ", "Ñ" : "ಚ", "Ò" : "ಛ", "Ó" : "ಜ", "Ô" : "ಝ", "Ö" : "ಟ", "×" : "ಠ", "Ø" : "ಡ", "Ù" : "ಢ", "Ú" : "ಣ", "Û" : "ತ", "Ü" : "ಥ", "Ý" : "ದ", "Þ" : "ಧ", "ß" : "ನ", "à" : "ಪ", "á" : "ಫ", "â" : "ಬ", "ã" : "ಭ", "ä" : "ಮ", "å" : "ಯ", "æ" : "ರ", "è" : "ಲ", "é" : "ವ", "ê" : "ಶ", "ë" : "ಷ", "ì" : "ಸ", "í" : "ಹ", "î" : "ಳ", "ç" : "ರ" } # Arkavattu and Unicode replacement ascii_arkavattu = { "ð": "ರ" }
a40120fbb5a436cc0ce4a929d20fd233db4bcd89
xblh2018/LintCodePython
/BinaryTreePostorderTraversal/Solution2.py
1,073
3.890625
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution2: """ @param root: The root of binary tree. @return: Postorder in ArrayList which contains node values. """ def postorderTraversal(self, root): # write your code here res = [] if root is None: return res stack = [] stack.append(root) curr = root prev = None while len(stack) > 0: curr = stack[-1] if prev is None or prev.left == curr or prev.right == curr: if curr.left is not None: stack.append(curr.left) elif curr.right is not None: stack.append(curr.right) elif curr.left == prev: if curr.right is not None: stack.append(curr.right) else: res.append(curr.val) stack.pop() prev = curr return res
eb55f274b76a27f0eb496428a1e81f72f341be70
opensciencegrid/osg-pki-tools
/osgpkitools/ExceptionDefinitions.py
1,808
3.578125
4
""" This script contains all the exception classes and would be exclusively used for handling exceptions""" class Exception_500response(Exception): """Exception raised for 500 response. Attributes: status -- Status of the response message -- explanation of the error """ def __init__(self, status, message): self.status = status self.message = message def __str__(self): return str(self.message) class FileNotFoundException(Exception): """ Exception raised when a file is not found Attributes: filename -- Name of the file that is not found message -- message to be printed for this exception """ def __init__(self, filename, message): self.filename = filename self.message = message def __str__(self): return str(self.message) class BadPassphraseException(Exception): """ This Exception occurs when the passphrase entered for the private key file does not match the stored passphrase of the key file. Attributes: message -- message to be displayed """ def __init__(self, message): self.message = message def __str__(self): return str(self.message) class FileWriteException(Exception): """This exception is raised when the user does not have permission to write in the current directory""" def __init__(self, message): self.message = message def __str__(self): return str(self.message) class AuthenticationFailureException(Exception): """This exception is raised when the credentials provided by the user are invalid""" def __init__(self, status, message): self.status = status self.message = message def __str__(self): return str(self.message)
f371492ceb8cc5d1dd5958fb002eb0117bba4055
sandergl/rosebotics2
/src/sanders.py
2,816
3.828125
4
""" Capstone Project. Code written by Garrett Sanders. Fall term, 2018-2019. """ import rosebotics_new as rb import time def main(): """ Runs YOUR specific part of the project """ # movement_experiment() # degree_experiment() # test_go_inches() # test_spin_degree() # turn_degree_experiment() # test_turn_degrees() # test_polygon() # test_calibrate() # test_raise_and_close() # test_move_arm_to_position() big_test() def test_go_inches(): robot = rb.Snatch3rRobot() robot.drive_system.go_straight_inches(10) def movement_experiment(): robot = rb.Snatch3rRobot() robot.drive_system.start_moving(100, 100) time.sleep(1) robot.drive_system.stop_moving() print(robot.drive_system.left_wheel.get_degrees_spun()) # 9.6in,831 9.6in,826 9.6in,823 # 86.39 degrees per inch in one sec def test_spin_degree(): robot = rb.Snatch3rRobot() for k in range(4): robot.drive_system.spin_in_place_degrees(90) time.sleep(.5) time.sleep(3) def degree_experiment(): robot = rb.Snatch3rRobot() robot.drive_system.start_moving(-50, 50) time.sleep(1.75) robot.drive_system.stop_moving() print(robot.drive_system.left_wheel.get_degrees_spun()) # 475, 90degrees,452, 90degrees, 465, 90degrees # 5.18 degrees spun per degree # def test_turn_degrees(): def turn_degree_experiment(): robot = rb.Snatch3rRobot() robot.drive_system.start_moving(50, 0) time.sleep(3.555) robot.drive_system.stop_moving() print(robot.drive_system.left_wheel.get_degrees_spun()) # 989, 90 degrees 965, 90 degrees 974, 90 degrees # 10.84 degrees spun per degree def test_turn_degrees(): robot = rb.Snatch3rRobot() robot.drive_system.turn_degrees(90) time.sleep(.5) robot.drive_system.turn_degrees(-90) time.sleep(3) def polygon(n): s8n = rb.Snatch3rRobot() angle = 360 / n for k in range(n): s8n.drive_system.go_straight_inches(18) time.sleep(1) s8n.drive_system.spin_in_place_degrees(angle) time.sleep(1) def test_polygon(): polygon(4) def test_raise_and_close(): robot = rb.Snatch3rRobot() robot.arm.raise_arm_and_close_claw() def test_calibrate(): robot = rb.Snatch3rRobot() time.sleep(3) def test_move_arm_to_position(): robot = rb.Snatch3rRobot() robot.arm.move_arm_to_position(360 * 10) def big_test(): robot = rb.Snatch3rRobot() robot.drive_system.go_straight_inches(10, -100) #robot.drive_system.go_straight_inches(10) #time.sleep(3) #robot.drive_system.spin_in_place_degrees(90) #time.sleep(3) #robot.drive_system.turn_degrees(-90) #time.sleep(3) #robot.arm.calibrate() #time.sleep(3) #robot.arm.move_arm_to_position(360*10) main()
b1da642d1c88e251b67dd0debd63efd3e6bc7cd2
smallsharp/mPython
/基础篇/面向对象/描述器定义方式1.py
964
4.34375
4
""" 描述器的定义方式之一: 使用 property 关键字 """ class Person(object): def __init__(self): self.__age = 18 def get_age(self): print("get") return self.__age def set_age(self, value): print("set") self.__age = value def del_age(self): print("de1") del self.__age # 这里传递的是 方法名称 age = property(get_age, set_age, del_age) p1 = Person() p1.age = 20 print(p1.age) del p1.age # print(help(Person)) print("-" * 50) class Person2(object): def __init__(self): self.__age = 18 @property def age(self): print("get") return self.__age @age.setter # 注意方法名称 要和 属性名称对应 def age(self, value): print("set") self.__age = value @age.deleter def age(self): print("del") del self.__age p2 = Person2() p2.age = 22 print(p2.age) del p2.age
c4737aac0d2eef4e7888af80016c640e3e40d0ed
biamila/Passwords
/Gui_sql.py
8,836
3.578125
4
import pygame, sqlite3 class Input_text: def __init__(self, x, y, w, h): self.name = pygame.Rect(x, y, w, h) self.active = False self.text = "" self.colour = (225, 225, 225) def check_collision(self, event): if self.name.collidepoint(event.pos[0], event.pos[1]): self.active = not self.active else: self.active = False if self.active: self.colour = (0, 0, 255) else: self.colour = (255, 255, 255) def writting(self, event): if self.active: if event.key == pygame.K_BACKSPACE: self.text = self.text[:-1] else: self.text += event.unicode def printscreen(self, new_screen, font): surface = font.render(self.text, True, (0, 0, 0)) new_screen.blit(surface, (self.name.x + 5, self.name.y + 5)) pygame.draw.rect(new_screen, self.colour, self.name, 2) def boxfilled(self): if self.text != "": return True else: return False def get_values(self): return self.text def gui_inputs(*args): answers = [] new_screen = pygame.display.set_mode((400, 300)) font = pygame.font.Font(None, 28) length = len(args) first_input = Input_text(60, 60, 140, 35) second_input = Input_text(60, 135, 140, 35) if length == 3: third_input = Input_text(60, 210, 140, 35) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: mousex, mousey = pygame.mouse.get_pos() if mousex >= 310 and mousex <= 310 + 80 and mousey >= 265 and mousey <= 265 + 30: return answers if mousex >= 310 and mousex <=310+80 and mousey >= 225 and mousey <= 225+30: if first_input.boxfilled() and second_input.boxfilled(): if length == 3 and third_input.boxfilled(): answers.append(first_input.get_values()) answers.append(second_input.get_values()) answers.append(third_input.get_values()) return answers elif length == 2: answers.append(first_input.get_values()) answers.append(second_input.get_values()) return answers first_input.check_collision(event) second_input.check_collision(event) if length == 3: third_input.check_collision(event) if event.type == pygame.KEYDOWN: first_input.writting(event) second_input.writting(event) if length == 3: third_input.writting(event) new_screen.fill((135, 206, 235)) first_input.printscreen(new_screen, font) second_input.printscreen(new_screen, font) if length == 3: third_input.printscreen(new_screen, font) pygame.time.Clock().tick(30) pygame.draw.rect(new_screen, (95, 166, 195), (310, 265, 80, 30)) new_screen.blit(font.render("Back", True, (0, 0, 0)), (325, 270)) pygame.draw.rect(new_screen, (95, 166, 195), (310, 225, 80, 30)) new_screen.blit(font.render("Done", True, (0, 0, 0)), (325, 230)) new_screen.blit(font.render(args[0], True, (0, 0, 0)), (50, 40)) new_screen.blit(font.render(args[1], True, (0, 0, 0)), (50, 115)) if length == 3: new_screen.blit(font.render(args[2], True, (0, 0, 0)), (50, 190)) pygame.display.update() def error_message(text, login=False): pop_screen = pygame.display.set_mode((400, 100)) font = pygame.font.Font(None, 28) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if login: pop_screen.fill((195, 225, 225)) pop_screen.blit(font.render(text, True, (46, 109, 225)), (30, 10)) pop_screen.blit(font.render("Have a nice day :)", True, (112, 155, 225)), (120, 50)) else: pop_screen.fill((50, 50, 50)) pop_screen.blit(font.render(text, True, (225, 225, 225)), (10, 10)) pygame.display.update() def add_new(): done = False while not done: answers = gui_inputs("Name", "User", "Password") print(answers) if answers != []: name = answers[0] user = answers[1] password = answers[2] c.execute("""SELECT * FROM Passwords WHERE user = ?""", (user,)) results = c.fetchall() if len(results) == 0: c.execute("""INSERT INTO Passwords VALUES(?, ?, ?)""", (user, name, password,)) print("item added") break else: print("username used") error_message("Sorry this username is taken") else: break db.commit() def update(): password = "" checkpasssword = " " while password != checkpasssword: answers = gui_inputs("User", "Password", "Password Again") if answers != []: print(answers) user = answers[0] password = answers[1] checkpasssword = answers[2] if password != checkpasssword: error_message("Sorry, password incorrectly typed") else: c.execute("""UPDATE Passwords SET password = ? WHERE user = ? """, (password, user,)) db.commit() else: break def delete(): done = False while not done: answers = gui_inputs("User", "Password") if answers != []: user = answers[0] password = answers[1] try: c.execute("""DELETE FROM Passwords WHERE user = ? and password = ?""", (user, password,)) db.commit() done = True except: error_message("No account found with such details") else: done = True def log_in(): done = False while not done: answers = gui_inputs("User", "Password") if answers != []: user = answers[0] password = answers[1] c.execute("""SELECT password from Passwords WHERE user = ?""", (user,)) result = c.fetchone() try: for i in result: if i == password: error_message("You've have successfully logged in!", True) else: error_message("Log in has failed!") except: error_message("User not recognized") else: done = True def button(screen, x, y, w, h, font, text, func): xpos, ypos = pygame.mouse.get_pos() light = (240, 248, 255) dark = (255, 0, 0) click = pygame.mouse.get_pressed() if xpos >= x and xpos <= x + w and ypos >= y and ypos <= y + h: pygame.draw.rect(screen, dark, (x, y, w, h)) if click[0] == 1: func() else: pygame.draw.rect(screen, light, (x, y, w, h)) screen.blit(font.render(text, True, (0, 0, 0)), (x + 10, y + 10)) def main_window(): global c, db db = sqlite3.connect("passwords.db") c = db.cursor() c.execute("""CREATE TABLE IF NOT EXISTS Passwords (user text, name text, password text)""") screen = pygame.display.set_mode((400, 300)) font = pygame.font.SysFont('Arial', 20) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((135, 206, 235)) screen.blit(font.render("What would you like to do", True, (0, 0, 0)), (100, 30)) button(screen, 60, 70, 80, 70, font, "Register", add_new) button(screen, 160, 70, 80, 70, font, "Update", update) button(screen, 260, 70, 80, 70, font, "Delete", delete) button(screen, 160, 160, 80, 70, font, "Log in", log_in) pygame.display.update() db.close() if __name__ == "__main__": pygame.init() main_window() pygame.quit()
01c5e814075e70e82686a4c2dc078a1b15476651
CSUBioinformatics1801/Python_Bioinformatics_ZYZ
/Exp3.py
4,956
3.5
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 13:10:08 2020 @author: pc """ # ============================================================================= # a,b=eval(input("key in 2 numbers as a,b:")) # print(a,'+',b,'=',a+b) # print(a,'-',b,'=',a-b) # print(a,'*',b,'=',a*b) # print(a,'/',b,'=',round(a/b,2)) # ============================================================================= # ============================================================================= # a=eval(input('input a int less than 255')) # print('binary:{08b}'.format(a)) # ============================================================================= # ============================================================================= # insulin_seq="MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGGGPGAGSLQPLALEGSLQKRGIVEQCCTSICSLYQLENYCN" # for amino_acid in "ACDEFGHIKLMNPQRSTVWTY": # number=insulin_seq.count(amino_acid) # print(amino_acid,number) # ============================================================================= # ============================================================================= # a=eval(input("Input a int between 0,255:")) # print(bin(a)+'\n'+hex(a)+'\n'+oct(a)) # ============================================================================= # ============================================================================= # a="a b c d e" # print(a) # print(a.replace(' ','\n')) # ============================================================================= # ============================================================================= # a='123456789' # n=len(a) # m=2 # while m<=n: # print(' '*(21-m),end='') # print('{}{}'.format(a[:m], a[m-2::-1])) # m+=1 # ============================================================================= # ============================================================================= # n=5;m=6 # while n>=1: # print('{}{}'.format(''*m,'*'*(2*n-1))) # n-=1 # m+=1 # ============================================================================= # ============================================================================= # temp='rfh4289ogiqwhg21r9w8hg[0843hB4Gm20mrdiewruwuf2inut24n89n34803' # macchar=max(list(temp)) # print(macchar) # templist=[] # for i in range(len(temp)): # if temp[i]==macchar: # templist.append(str(i)) # print(templist) # ============================================================================= # ============================================================================= # a=input('Input a word:') # print('{:*^30}'.format(a)) # ============================================================================= # ============================================================================= # ATP=3.5;ADP=1.8;Pi=5.0;R=0.00831;T=298;ΔG0=-30.5; # import math # print('ΔG=%.2f kcal/mol'%float((ΔG0+R*T*math.log(ADP*Pi/ATP))/4.184)) # ============================================================================= import requests import re from bs4 import BeautifulSoup sch_gene_name=input('Input a homo gene name you wanna search:') sch_url='https://www.ncbi.nlm.nih.gov/gene?term=(homo%5BOrganism%5D)%20AND%20'+sch_gene_name+'%5BGene%20Name%5D#reference-sequences' print('Searching...\nThis may take few centuries...') res = requests.get(sch_url) res.encoding='gbk' soup = BeautifulSoup(res.text,"html.parser") match_pts_url = re.findall(r'/protein/NP_[0-9]+.[0-9]?',res.text) print('matched protein number: ') print(len(match_pts_url)) pt_name=[] for i in range(len(match_pts_url)): pt_name.append(re.search(r'NP_\S+', match_pts_url[i]).group()) print(pt_name) print('Start downloading protein sequences') for t in range(len(match_pts_url)): print('Searching protein sequences...protein name= '+pt_name[i]) pt_sch_url='https://www.ncbi.nlm.nih.gov'+match_pts_url[t] pt_res = requests.get(pt_sch_url) pt_res.encoding='gbk' match_pts = re.findall(r'<span class="ff_line" id="'+pt_name[i]+'_[0-9]+">\S+</span>',pt_res.text) #print(match_pts) match_pts=(re.search(r'(?<=<meta name="ncbi_uidlist" content=")[0-9]+(?=" />)',pt_res.text)).group() pt_sch_url_re='https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?id='+match_pts+'&db=protein&report=genpept&conwithfeat=on&show-cdd=on&retmode=html&withmarkup=on&tool=portal&log$=seqview&maxdownloadsize=1000000' pt_res_re = requests.get(pt_sch_url_re) pt_res_re.encoding='gbk' match_ptseqs=re.findall(r'<span class="ff_line" id="\S+_\S+">[a-z\s]+(?=</span>)', pt_res_re.text) match_ptseqs_new=[] for i in range(len(match_ptseqs)): latarrow=match_ptseqs[i].find('>') match_ptseqs_new.append(match_ptseqs[i][latarrow+1:]) seq_content="".join(match_ptseqs_new) seq_content=seq_content.replace(' ','') seq_content=seq_content.upper() print(seq_content) for amino_acid in "ACDEFGHIKLMNPQRSTVWTY": number=seq_content.count(amino_acid) print(amino_acid,number)
2deeba00745f22ff134083a47fe8454a93c80c25
HPRIOR/DS-Algo-Zoo
/DynamicProgramming/kadanes_algo.py
1,167
3.8125
4
# max_subarray(nums) -> maximum contiguous sub array def max_subarray(nums: [int]) -> int: # this will store the maximum subarray for each index if len(nums) == 1: return nums[0] if not nums: return 0 memo = {0: nums[0]} global_max = nums[0] for i in range(1, len(nums)): current_max = max(memo[i-1] + nums[i], nums[i]) if current_max > global_max: global_max = current_max memo[i] = current_max return global_max print(max_subarray([1, -3, 2, 1, -1])) # As with all dp problems the solution entails keeping a cumulative record of sub problems, which we can # use as we progress through the solution. In this case, as we move through the array, we tally the the # the maximum value between the current index itself, and adding this index to the previously largest subarray. # Hence at each stage we are sorting the maximum sub array up to that point, and using this as a basis for the # next index. At the same time we are keeping a global maximum value, which to compare each index, current_max # that is above this will be the new global_max. This is what is reterned at the end
f36dc8d4fa1eb3191c3a48c7c073cfeaca024c81
JFantasia/POO
/BD/pgdatabase.py
3,290
3.8125
4
import sys # https://www.psycopg.org/install/ import psycopg2 from psycopg2 import Error # TABLA DE LA BASE DE DATOS # # CREATE TABLE public.profesor ( # dni varchar(8) NOT NULL, # nombre varchar(40) NOT NULL, # mail varchar(50) NULL, # CONSTRAINT profesor_pk PRIMARY KEY (dni) # ); class DB(): def __init__(self, parent=None): self.cursor = self.db_connect() def cargar(self): self.cursor.execute("SELECT * FROM profesor ORDER BY DNI asc;") # Fetch result records = self.cursor.fetchall() for row in records: dni = row[0] nombre = row[1] correo = row[2] print(dni + " " + nombre + " " + correo) def editarDatos(self): ids = input("Ingrese el identificador: ") nombre = input("Ingrese el nombre: ") correo = input("Ingrese el correo: ") try: # Executing a SQL query self.cursor.execute("UPDATE profesor " "set nombre = '" + nombre + "' , " "mail = '" + correo + "' " "where dni = '" + ids + "'; ") self.connect.commit() self.cargar() except (Exception, Error) as error: print("Mapea error") self.connect.rollback() print("Error while update to PostgreSQL", error) def insertarDatos(self): ids = input("Ingrese el identificador: ") nombre = input("Ingrese el nombre: ") correo = input("Ingrese el correo: ") try: # Executing a SQL query self.cursor.execute("INSERT INTO profesor " "(dni, nombre, mail) " "VALUES ('" + ids + "', '" + nombre + "', '" + correo + "');") self.connect.commit() self.cargar() except (Exception, Error) as error: print("Mapea error") self.connect.rollback() print("Error while insert to PostgreSQL", error) def eliminarDatos(self): ids = input("Ingrese el identificador a eliminar: ") try: # Executing a SQL query self.cursor.execute("DELETE FROM profesor where dni = '" + ids + "';") self.connect.commit() self.cargar() except (Exception, Error) as error: self.connect.rollback() print("Error while delete to PostgreSQL", error) def db_connect(self): try: # Connect to an existing database connection = psycopg2.connect(user="postgres", password="postgres", host="127.0.0.1", port="5432", database="poo") # Create a cursor to perform database operations self.connect = connection cursor = connection.cursor() return cursor except (Exception, Error) as error: print("Error while connecting to PostgreSQL", error) if __name__ == '__main__': base = DB() base.cargar() base.eliminarDatos() base.insertarDatos() base.editarDatos()
53b3dc004678f9e214fc158ae2075429d2c5a27f
DARRENSKY/COMP9021
/lecture/Lecture_6/iterative_hanoi.py
1,839
3.875
4
# Written by Eric Martin for COMP9021 ''' Iterative solution to the towers of Hanoi puzzle. ''' def move_towers(n, start_position, end_position, intermediate_position): ''' Move a tower of n disks from start_position to end_position, with intermediate_position available. ''' smallest_disk_position = 0 direction = 1 - n % 2 * 2 stacks = list(range(n, 0, -1)), [], [] for i in range(2 ** n - 1): if i % 2 == 0: new_smallest_disk_position = (smallest_disk_position + direction) % 3 print(f'Move smallest disk from {smallest_disk_position} to ' f'{new_smallest_disk_position}' ) stacks[new_smallest_disk_position].append(stacks[smallest_disk_position].pop()) smallest_disk_position = new_smallest_disk_position else: other_positions = (smallest_disk_position + 1) % 3, (smallest_disk_position + 2) % 3 if not stacks[other_positions[0]]: from_position, to_position = other_positions[1], other_positions[0] elif not stacks[other_positions[1]]: from_position, to_position = other_positions[0], other_positions[1] elif stacks[other_positions[0]][-1] < stacks[other_positions[1]][-1]: from_position, to_position = other_positions[0], other_positions[1] else: from_position, to_position = other_positions[1], other_positions[0] stacks[to_position].append(stacks[from_position].pop()) print(f'Move disk of size {stacks[to_position][-1]} from {from_position} to ' f'{to_position}' ) move_towers(4, 0, 2, 1)
5bc1ac477c8a242a6f6042b798f230ccfc148499
fpiikt/date-to-text-SonicCreeper
/main.py
8,368
3.84375
4
""" Автор: Кашпур Николай, группа №P3355 """ class DateToTextClass(): def __init__(self, date): splitted = date.split(' ') self.date = splitted[0].split('.') self.time = splitted[1].split(':') def convert(self): """ Transforms date in numerical format into russian text. Returns (str): russian text """ day = self.date[0] month = self.date[1] year = self.date[2] return self.convertDay(day) + ' ' + self.convertMonth(month) + ' ' + self.convertYear(year) + self.convertTime(self.time) def convertTime(self, time): """ Transforms time in numerical format into russian text. Args: time (str[]): contains hours, minutes and seconds as elements of an array, should be ['HH', 'MM', 'SS'] Returns (str): russian text """ unitDict = { '0': 'ноль', '1': 'одна', '2': 'две', '3': 'три', '4': 'четыре', '5': 'пять', '6': 'шесть', '7': 'семь', '8': 'восемь', '9': 'девять', } x = [{ 'num': time[0], 'word1': ' часов', 'word2': ' час', 'word3': ' часа', 'unic': {'1': 'один', '2': 'два'} }, { 'num': time[1], 'word1': ' минут', 'word2': ' минута', 'word3': ' минуты' }, { 'num': time[2], 'word1': ' секунд', 'word2': ' секунда', 'word3': ' секунды' }] res = '' for i in x: num = i['num'] if num[0] == '1': res += ' ' + self.get10Word(num, 1) + i['word1'] elif num[1] == '0' and num[0] != '0': res += ' ' + self.getDozenWord(num[0], 1) + i['word1'] else: unic = i.get('unic') unit = unic and unic.get(num[1]) or unitDict.get(num[1]) if unit == 'один' or unit == 'одна': numWord = i['word2'] else: numWord = i['word1'] if unit[-1] == 'ь' else i['word3'] dozen = self.getDozenWord(num[0], 1) res += ' ' + (dozen and (dozen + ' ' + unit + numWord) or (unit + numWord)) return res def convertDay(self, day): """ Transforms day in numerical format into russian text. Args: day (str): should be in format DD Returns (str): russian text """ res = '' unitDict = { '1': 'первое', '2': 'второе', '3': 'третье', '4': 'четвертое', '5': 'пятое', '6': 'шестое', '7': 'седьмое', '8': 'восьмое', '9': 'девятое', } unit = unitDict.get(day[1]) if day[0] == '0': return unit elif day[0] == '1': return self.get10Word(day, 2) elif day[1] == '0': return self.getDozenWord(day[0], 2) else: res = self.getDozenWord(day[0], 1) return res != '' and res + ' ' + unit or unit def convertYear(self, year): """ Transforms year in numerical format into russian text. Args: year (str): should be in format YYYY Returns (str): russian text """ unitDict = { '0': '', '1': 'первого', '2': 'второго', '3': 'третьего', '4': 'четвертого', '5': 'пятого', '6': 'шестого', '7': 'седьмого', '8': 'восьмого', '9': 'девятого', } if year[2] == '1': res = self.get10Word(year[-2:], 3) else: res = unitDict.get(year[3]) if res == '': res = self.getDozenWord(year[2], 3) else: dozen = self.getDozenWord(year[2], 1) res = dozen and (dozen + ' ' + res) or res if res == '': res = self.getHundredWord(year[1], 2) else: hundred = self.getHundredWord(year[1], 1) res = hundred and (hundred + ' ' + res) or res if res == '': res = self.getThousandWord(year[0], 2) else: thousand = self.getThousandWord(year[0], 1) res = thousand and (thousand + ' ' + res) or res return res + ' года' def convertMonth(self, month): """ Transforms month in numerical format into russian text. Args: month (str): should be in format MM Returns (str): russian text """ monthDict = { '01': 'января', '02': 'февраля', '03': 'марта', '04': 'апреля', '05': 'мая', '06': 'июня', '07': 'июля', '08': 'августа', '09': 'сентября', '10': 'октября', '11': 'ноября', '12': 'декабря', } return monthDict.get(month) def getThousandWord(self, num, mod = 1): """ Transforms number of thousands into russian text. Args: num (str): number of thousands mod (number): defines type of noun Returns (str): russian text """ dictOfThousand = { '0': '', '1': 'тысяча/тысячного', '2': 'две тысячи/двухтысячного' } words = dictOfThousand.get(num) and dictOfThousand.get(num).split('/') if mod == 2: return words[1] else: return words[0] def getHundredWord(self, num, mod): """ Transforms number of hundreds into russian text. Args: num (str): number of hundreds mod (number): defines type of noun Returns (str): russian text """ dictOfHundred = { '0': '/', '1': 'сто/', '2': 'двести/двух', '3': 'триста/трёх', '4': 'четыреста/четырёх', '5': 'пятьсот/пяти', '6': 'шестьсот/шести', '7': 'семьсот/семи', '8': 'восемьсот/восьми', '9': 'девятьсот/девяти', } words = dictOfHundred.get(num) and dictOfHundred.get(num).split('/') if mod == 2: pre = words[1] return pre and pre + 'сотого' or pre else: return words[0] def getDozenWord(self, num, mod): """ Transforms number of dozens into russian text. Args: num (str): number of dozens mod (number): defines type of noun Returns (str): russian text """ dictOfDozens = { '0': '', '2': 'двадцат', '3': 'тридцат', '4': 'сорок', '5': 'пятьдесят', '6': 'шестьдесят', '7': 'семьдесят', '8': 'восемьдесят', '9': 'девяносто', } res = dictOfDozens.get(num) if res and res != None: if mod == 1: return res[-2] == 'а' and res + 'ь' or res elif mod == 2: return res + 'ое' else: return num == '4' and res + 'ового' or res.replace('ь', 'и').replace('восеми', 'восьми') + 'ого' else: return res def get10Word(self, num, mod): """ Transforms number in range from 10 to 19 into russian text. Args: num (str): number of dozens mod (number): defines type of noun Returns (str): russian text """ dictOf10 = { '10': 'десят', '11': 'одиннадцат', '12': 'двенадцат', '13': 'тринадцат', '14': 'четырнадцат', '15': 'пятнадцат', '16': 'шестнадцат', '17': 'семнадцат', '18': 'восемнадцат', '19': 'девятнадцат', } post = 'ое' if mod == 2 else 'ого' res = dictOf10.get(num) if res != 'error': if mod == 1: return res + 'ь' else: return res + post else: return res if __name__ == '__main__': assert DateToTextClass('25.09.2019 08:17:59').convert() == "двадцать пятое сентября две тысячи девятнадцатого года восемь часов семнадцать минут пятьдесят девять секунд", 'ошибка в тестовом примере 1' assert DateToTextClass('20.01.1901 10:21:39').convert() == "двадцатое января тысяча девятьсот первого года десять часов двадцать одна минута тридцать девять секунд", 'ошибка в тестовом примере 2' assert DateToTextClass('02.03.1800 15:11:50').convert() == "второе марта тысяча восьмисотого года пятнадцать часов одиннадцать минут пятьдесят секунд", 'ошибка в тестовом примере 3' assert DateToTextClass('11.12.2000 23:52:22').convert() == "одиннадцатое декабря двухтысячного года двадцать три часа пятьдесят две минуты двадцать две секунды", 'ошибка тестовом примере 4'
43f6644ce0a0ce0e55c310817843128b1b52fa1d
tmuweh/tutorial.py
/restaurant.py
1,020
3.875
4
class Restaurant(object): """docstring for Restaurant""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): """prints information about restaurant""" print("Name: " + self.restaurant_name) print("Cuisine Type: " + self.cuisine_type) def open_restaurant(self): """display information whether restaurant is open""" print(self.restaurant_name + " is open now") def set_number_served(self, number_served): """sets a new number serve for restaurant class""" if self.number_served <= number_served: self.number_served = number_served else: pass def increment_number_sesrved(self, increment): """increments number_served by increment""" self.number_served += increment restaurant = Restaurant("restau", "general") restaurant.set_number_served(40) print(restaurant.number_served) restaurant.increment_number_sesrved(10) print(restaurant.number_served)
c387ad2714f1f72025a65d52ee6cb8426a5186e6
uniqstha/PYTHON
/questions of day6/Q3.py
492
4.3125
4
#Write a Python function that takes a number as a parameter and check the number is prime or not. num= int(input("Enter any number: ")) # prime number is always greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: print(f"{num}is not a prime number") break else: print(f"{num} is a prime number") # if the entered number is less than or equal to 1 # then it is not prime number else: print(f"{num}is not a prime number")
93f5f25f8c984256fcf7e4d678350296672905eb
AkashSharma93/English-Dictionary--web-crawler-
/Word.py
808
3.671875
4
class Word: def __init__(self, new_word, definitions, pronunciation, synonyms, related_forms): self._word = new_word self._definitions = definitions self._pronunciation = pronunciation self._synonyms = synonyms self._related_forms = related_forms def get_word(self): """Returns the word associated with the current Word object.""" return self._word def get_definitions(self): """Returns the definitions associated with the word.""" return self._definitions def get_pronunciation(self): """Returns pronunciation of the word.""" return self._pronunciation def get_synonyms(self): """Returns synonyms of the word.""" return self._synonyms def get_related_forms(self): """Returns related forms of the word.""" return self._related_forms
8ebfe5b8435e7faff33c730d15407ce7db02f16b
hridhi/data-structures-and-algorithms-
/patterns/pascals_triangle.py
441
3.75
4
#code #pattern formation #pascals triangle rows=3 list1=[] for i in range(rows): temp=[] for j in range(i+1): if j==0 or j==i: temp.append(1) else: temp.append(list1[i-1][j-1]+list1[i-1][j]) list1.append(temp) #print(list1) for i in range(rows): for j in range(rows-i-1): print("",end=" ") for j in range(i+1): print(list1[i][j],end=" ") print()
965a7c0cfde0c3064d7574776fd06b457a92cb99
Iverance/leetcode
/073.set-matrix-zeroes.py
1,686
3.8125
4
# # [73] Set Matrix Zeroes # # https://leetcode.com/problems/set-matrix-zeroes # # Medium (35.93%) # Total Accepted: # Total Submissions: # Testcase Example: '[[0]]' # # # Given a m x n matrix, if an element is 0, set its entire row and column to 0. # Do it in place. # # # click to show follow up. # # Follow up: # # # Did you use extra space? # A straight forward solution using O(mn) space is probably a bad idea. # A simple improvement uses O(m + n) space, but still not the best solution. # Could you devise a constant space solution? # # # class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ row, col = len(matrix), len(matrix[0]) firstRowZero = firstColZero = False for i in range(row): for j in range(col): if matrix[i][j] == 0: firstRowZero = True if i == 0 else firstRowZero firstColZero = True if j == 0 else firstColZero matrix[0][j] = 0 matrix[i][0] = 0 for i in range(1, row): for j in range(1, col): if matrix[i][j] and (matrix[0][j] == 0 or matrix[i][0] == 0): matrix[i][j] = 0 if firstRowZero: matrix[0] = [0] * col if firstColZero: for i in range(row): matrix[i][0] = 0 print(matrix) if __name__ == "__main__": sol = Solution() sol.setZeroes([[0,0,0,5],[4,3,1,4],[0,1,1,4],[1,2,1,3],[0,0,1,1]])
d4eed585cac597a5b44c7fb27ae54f8186726ad8
denemorhun/Python-Problems
/Hackerrank/Recursive and DP/fibonacci_dp.py
400
3.71875
4
''' Fibonacci with DP ''' def fib_dp(n) -> int: # base case if n == 0 == 1: return 1 # declare array # insert base case into array nums = [None]*(n+1) nums[0] = 1 nums[1] = 1 for i in range(2, n+1): nums[i] = nums[i-2] + nums[i-1] return nums # return dp prev case fib_dp(n-2) + fib_dp(n-1) if __name__ == '__main__': print(fib_dp(5))
d2c4eaf568b7cb2ff22e7353a3291bc9c39fd126
baloooo/coding_practice
/tree_base.py
3,824
4.0625
4
# -*- coding: utf-8 class Node: def __repr__(self): if self is None: return "None" else: return "{0} -> {1}".format(self.val, self.next) def __init__(self, x, **kwargs): self.left = None self.right = None self.next = None self.val = x # To allow arbitrary items to be set on Node for key, value in kwargs.items(): self.key = value def print_tree_dfs(root): if root is None: return print root.val print_tree_dfs(root.left) print_tree_dfs(root.right) def array_to_tree(arr): """ Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation. Input: parent[] = {1, 5, 5, 2, 2, -1, 3} Output: 5 / \ 1 2 / / \ 0 3 4 / 6 """ node_map = {} root = None for index, ele in enumerate(arr): if node_map.get(index) is None: cur_node = Node(index) else: cur_node = node_map[index] node_map[index] = cur_node if ele == -1: root = cur_node continue if node_map.get(ele) is None: node_map[ele] = Node(ele) if node_map[ele].left is None: node_map[ele].left = cur_node else: node_map[ele].right = cur_node return root def construct_tree_from_levelorder_inorder(inorder, levelorder): pass def level_order_array_to_tree(arr): """ Tree will be constructed in a row major order from the arr with None depicting absence of nodes. [100, 50, 150, inf, 75, 125, inf] 100 / \ 50 150 / \ / \ inf 75 125 inf Note: It has to be complete binary tree like above example. 100 \ 150 \ 175 won't work. """ node_object_list = [False]*len(arr) for index, ele in enumerate(arr): if ele is None: continue if isinstance(node_object_list[index], Node): cur_node = node_object_list[index] elif not node_object_list[index]: cur_node = Node(ele) node_object_list[index] = cur_node else: continue for i in range(1, 3): if 2*index+i > (len(arr)-1): # left child of cur_node out of bounds. break if arr[2*index+i] is None: # subsituting node_obj_list with boolean instead of more # descriptive val to preserve space. node_object_list[2*index+i] = True else: child_node = Node(arr[2*index+i]) if i % 2: cur_node.left = child_node else: cur_node.right = child_node node_object_list[2*index+i] = child_node # if 2*index+2 > (len(arr)-1): # break # if arr[2*index+2] is None: # node_object_list[2*index+2] = True # else: # right_node = Node(arr[2*index+2]) # cur_node.right = right_node # node_object_list[2*index+2] = right_node return node_object_list[0] if __name__ == '__main__': arr = [1, 2, 3, None, None, 4, None, None, 5] arr = [100, None, 150, None, 175] root = level_order_array_to_tree(arr) print_tree_dfs(root) import ipdb; ipdb.set_trace()
6bd55565775e19e3a13ba9fcb8f56f815ffce710
huyngopt1994/python-Algorithm
/bigo/day-16-disjoin-set-union/simple_case.py
978
3.859375
4
MAX = 20 parent = [] ranks = [] def make_set(): """ Build a make set for initial state build parent is itself. O(n) :return: """ global parent parent = [i for i in range(MAX + 5)] ranks = [0 for _ in range(MAX + 5)] def find_set(u): """find the representative of a set. Bad case is O(n)""" if u == parent[u]: return u return find_set(parent[u]) def union_set(u, v): """Try to add an element into a set or combine 2 sets together.If 2 elements wered associated we bypass. O(n)""" up = find_set(u) vp = find_set(v) parent[up] = vp if __name__ == '__main__': q = int(input()) make_set() for i in range(q): u, v, q = map(int, input().split()) if q == 1: union_set(u, v) elif q == 2: parent_u = find_set(u) parent_v = find_set(v) if parent_u == parent_v: print('1') else: print('0')
1cb5f91003ad22a25eb67c1bae5a09c7c4c0501e
adam147g/ASD_exercises_solutions
/Obligatory tasks/Obligatory_task_02/02.01_exercise.py
1,063
3.78125
4
# Tablica T jest długości n, ale zawiera tylko ceil(logn) różnych wartości. Proszę zaproponować # jak najszybszy algorytm sortujący taką tablicę. def counting_sort_letters(T, index): C = [0]*10 B = [0]*len(T) for i in range(len(T)): idx = int(T[i][index]) C[idx] += 1 for i in range(1, 10): C[i] += C[i-1] for i in range(len(T)-1, -1, -1): idx = int(T[i][index]) C[idx] -= 1 B[C[idx]] = T[i] for i in range(len(T)): T[i] = B[i] def radix_sort_letters(T, columns): for col in range(columns-1, -1, -1): counting_sort_letters(T, col) return T def sort(T): max_length = 0 for i in range(len(T)): T[i] = str(T[i]) max_length = max(max_length, len(T[i])) for i in range(len(T)): if len(T[i]) < max_length: T[i] = "0"*(max_length-len(T[i])) + T[i] radix_sort_letters(T, max_length) for i in range(len(T)): T[i] = int(T[i]) T = [365, 45137, 12, 45137, 12, 12, 45137, 365, 12] sort(T) print(T)
8ddc20fd30a8de2ce4fb0e06a3c56b6c27cc4abc
szabgab/slides
/python/examples/strings/no_break_continue.py
115
3.78125
4
i = 2 n = 3*5*7 while i < n: if (n / i) * i == n: print('{:2} divides {}'.format(i, n)) i = i + 1
3c4bb7216d21575e030478ea58a6654435ee369a
jiewu-stanford/leetcode
/230. Kth Smallest Element in a BST.py
1,891
3.9375
4
''' Title : 230. Kth Smallest Element in a BST Problem : https://leetcode.com/problems/kth-smallest-element-in-a-bst/ ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' iterative solution use deque Reference: https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63734/O(k)-space-O(n)-time-10%2B-short-lines-3-solutions ''' import collections class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: queue = collections.deque() while root or queue: while root: queue.append(root) root = root.left root = queue.pop() if k == 1: return root.val k -= 1 root = root.right ''' iterative solution using stack instead Reference: https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63829/Python-Easy-Iterative-and-Recursive-Solution ''' class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() if k == 1: return root.val k -= 1 root = root.right ''' DFS recursive helper function to exhause the entire tree Reference: https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63660/3-ways-implemented-in-JAVA-(Python)%3A-Binary-Search-in-order-iterative-and-recursive ''' class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: count = [] self.helper(root, count) return count[k-1] def helper(self, node, count): if not node: return self.helper(node.left, count) count.append(node.val) self.helper(node.right, count)
647edc0b0795ae8efdd95fbdd7a81439d142c039
Luciana1012/Term-5
/exponentialsearch.py
433
3.84375
4
from binary import binarySearch def exponentialSearch(array, x): startingIndex = 0 endingIndex = 0 if array[startingIndex] == x: return startingIndex else: endingIndex +=1 while endingIndex < len(array) and array[endingIndex] <= x: endingIndex *= 2 return binarySearch(array, startingIndex, endingIndex, x) a = [1,2,3,4,5,6,7,8,9,10] print (exponentialSearch(a, 6))
6acb88f93fb322196a025926940139992ac1854c
lilaboc/hackerrank
/python2/re-split.py
214
3.609375
4
# https://www.hackerrank.com/challenges/re-split # Enter your code here. Read input from STDIN. Print output to STDOUT import re for i in re.split('[\.,]', raw_input()): if re.match('\d+$', i): print i
2d58a12f876325c0de649d0f98d9b36237a2f3fc
prabhatv96/Testpython
/Pattern/left_start.py
202
3.6875
4
n=int(input("Enter number of lines: ")) k=n*2-2 for i in range(n): print(end=" "*k) print("* "*(i+1)) k=k-2 for i in range(n,-1,-1): print(end=" "*(k+4)) print("* "*(i-1)) k=k+2
85b875ad4b830958c3a075e057fbe1a4af94538e
zy2424/python_columbia_class
/lecture_one/assignment_versus_equality.py
144
3.546875
4
# assignment - "assigns a value to a variable" x = 4 # equality - "checks the value of a variable" print(x == 5) print(locals()["x"] is 4)
f66c2417cfea724e6b14b7595bca03e320e02f0c
a3huang/dsp
/python/advanced_python_regex.py
760
3.640625
4
from collections import Counter import string, re with open('faculty.csv') as f: degrees = list() titles = list() email = list() lastnames = list() f.readline() for line in f: data = line.strip().split(',') d = data[1].strip().split() d = [s.translate(string.maketrans('',''), string.punctuation) for s in d] degrees.extend(d) t = data[2].strip() t = re.search(r'.*Professor', t).group() titles.append(t) e = data[3].strip() email.append(e) domains = {re.search(r'(.*)@(.*)',s).group(2) for s in email} d = data[0].strip().split() lastnames.append(d[len(d)-1]) if __name__ == '__main__': print Counter(degrees) print Counter(titles) print email print domains print lastnames
64570df49134eda7322352c8184e9cd4047379bb
tonyhqanguyen/2DMarioKart
/Node.py
1,861
3.625
4
""" Node class that is used in the Genome class. """ from typing import List from math import exp class Node: """ A node in the neural network. """ number: int input_sum: float output_value: float outgoing_connections: List[Gene] layer: int def __init__(self, number: int) -> None: """ Initializes a node. """ self.number = number self.input_sum, self.output_value = 0, 0 self.outgoing_connections = [] self.layer = 0 def engage(self) -> None: """ For each node that this node is connected to, this node will send its output to the connecting nodes """ if self.layer != 0: self.output_value = 1 + exp(-4.9 * self.input_sum) for outgoing_connection in self.outgoing_connections: if outgoing_connection.enabled: # The weighted output of this node is added to the input sum of the outgoing connection outgoing_connection.ending_node.input_sum += outgoing_connection.weight * self.output_value def is_connected_to(self, node: "Node") -> bool: """ Return whether or not this node is connected to <node>. """ if self.layer == node.layer: return False if self.layer < node.layer: for outgoing_connection in node.outgoing_connections: if outgoing_connection.ending_node == self: return True else: for outgoing_connection in self.outgoing_connections: if outgoing_connection.ending_node == node: return True return False def clone(self) -> "Node": """ Return a clone of this node. """ clone = Node(self.number) clone.layer = self.layer return clone
e72a2516d744959108fefee0ebd8d0cabac8c839
DevejyaRaghuvanshi/Python_DataClean_UWcoop_Loblaws
/SKUpriceswithDates(forTimeSeries).py
7,433
4.0625
4
''' Create an Excel file and add a table to one sheet with the most valuable berry products and their price over time. Dates are constantly increasing day by day instead of showing only the days at which transactions were made. ''' #import required libraries import pandas as pd from functools import reduce #reduce works like filter and map #Helper function for appending dataframes to an excel file def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None, truncate_sheet=False, **to_excel_kwargs): """ Append a DataFrame [df] to existing Excel file [filename] into [sheet_name] Sheet. If [filename] doesn't exist, then this function will create it. Parameters: filename : File path or existing ExcelWriter (Example: '/path/to/file.xlsx') df : dataframe to save to workbook sheet_name : Name of sheet which will contain DataFrame. (default: 'Sheet1') startrow : upper left cell row to dump data frame. Per default (startrow=None) calculate the last row in the existing DF and write to the next row... truncate_sheet : truncate (remove and recreate) [sheet_name] before writing DataFrame to Excel file to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()` [can be dictionary] Returns: None """ from openpyxl import load_workbook import pandas as pd # ignore [engine] parameter if it was passed if 'engine' in to_excel_kwargs: to_excel_kwargs.pop('engine') writer = pd.ExcelWriter(filename, engine='openpyxl') # Python 2.x: define [FileNotFoundError] exception if it doesn't exist try: FileNotFoundError except NameError: FileNotFoundError = IOError try: # try to open an existing workbook writer.book = load_workbook(filename) # get the last row in the existing Excel sheet # if it was not specified explicitly if startrow is None and sheet_name in writer.book.sheetnames: startrow = writer.book[sheet_name].max_row # truncate sheet if truncate_sheet and sheet_name in writer.book.sheetnames: # index of [sheet_name] sheet idx = writer.book.sheetnames.index(sheet_name) # remove [sheet_name] writer.book.remove(writer.book.worksheets[idx]) # create an empty sheet [sheet_name] using old index writer.book.create_sheet(sheet_name, idx) # copy existing sheets writer.sheets = {ws.title:ws for ws in writer.book.worksheets} except FileNotFoundError: # file does not exist yet, we will create it pass if startrow is None: startrow = 0 # write out the new sheet df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs) # save the workbook writer.save() #Set display size and number of showed columns in the terminal output pd.set_option('display.max_columns', None) pd.set_option('display.expand_frame_repr', False) pd.set_option('max_colwidth', -1) #filename f='MostValuableSKU.xlsx' #read in the data from the sheets of the excel file into dataframes dfs_1=pd.read_excel(f,sheet_name='straw-1',header=0, parse_dates=['DELV_DT']) dfs_2=pd.read_excel(f,sheet_name='straw-2',header=0, parse_dates=['DELV_DT']) dfs_3=pd.read_excel(f,sheet_name='straw-3',header=0, parse_dates=['DELV_DT']) dfba_1=pd.read_excel(f,sheet_name='black-1',header=0, parse_dates=['DELV_DT']) dfba_2=pd.read_excel(f,sheet_name='black-2',header=0, parse_dates=['DELV_DT']) dfba_3=pd.read_excel(f,sheet_name='black-3',header=0, parse_dates=['DELV_DT']) dfbu_1=pd.read_excel(f,sheet_name='blue-1',header=0, parse_dates=['DELV_DT']) dfbu_2=pd.read_excel(f,sheet_name='blue-2',header=0, parse_dates=['DELV_DT']) dfbu_3=pd.read_excel(f,sheet_name='blue-3',header=0, parse_dates=['DELV_DT']) dfr_1=pd.read_excel(f,sheet_name='rasp-1',header=0, parse_dates=['DELV_DT']) dfr_2=pd.read_excel(f,sheet_name='rasp-2',header=0, parse_dates=['DELV_DT']) dfr_3=pd.read_excel(f,sheet_name='rasp-3',header=0, parse_dates=['DELV_DT']) dfc_1=pd.read_excel(f,sheet_name='cherries-1',header=0, parse_dates=['DELV_DT']) dfc_2=pd.read_excel(f,sheet_name='cherries-2',header=0, parse_dates=['DELV_DT']) dfc_3=pd.read_excel(f,sheet_name='cherries-3',header=0, parse_dates=['DELV_DT']) #zip the price and time columns together to make the required dataframes with Time and Price per unit for SKU columns #This is important because when we merge the dataframes, we will want different column names for different SKUs dfs1 = pd.DataFrame(list(zip(dfs_1['DELV_DT'], dfs_1['price_per_unit'])), columns=['Time', 'price_per_unit_straw-1']) dfs2 = pd.DataFrame(list(zip(dfs_2['DELV_DT'], dfs_2['price_per_unit'])), columns=['Time', 'price_per_unit_straw-2']) dfs3 = pd.DataFrame(list(zip(dfs_3['DELV_DT'], dfs_3['price_per_unit'])), columns=['Time', 'price_per_unit_straw-3']) dfba1 = pd.DataFrame(list(zip(dfba_1['DELV_DT'], dfba_1['price_per_unit'])), columns=['Time', 'price_per_unit_blackberry-1']) dfba2 = pd.DataFrame(list(zip(dfba_2['DELV_DT'], dfba_2['price_per_unit'])), columns=['Time', 'price_per_unit_blackberry-2']) dfba3 = pd.DataFrame(list(zip(dfba_3['DELV_DT'], dfba_3['price_per_unit'])), columns=['Time', 'price_per_unit_blackberry-3']) dfbu1 = pd.DataFrame(list(zip(dfbu_1['DELV_DT'], dfbu_1['price_per_unit'])), columns=['Time', 'price_per_unit_blueberry-1']) dfbu2 = pd.DataFrame(list(zip(dfbu_2['DELV_DT'], dfbu_2['price_per_unit'])), columns=['Time', 'price_per_unit_blueberry-2']) dfbu3 = pd.DataFrame(list(zip(dfbu_3['DELV_DT'], dfbu_3['price_per_unit'])), columns=['Time', 'price_per_unit_blueberry-3']) dfr1 = pd.DataFrame(list(zip(dfr_1['DELV_DT'], dfr_1['price_per_unit'])), columns=['Time', 'price_per_unit_raspberry-1']) dfr2 = pd.DataFrame(list(zip(dfr_2['DELV_DT'], dfr_2['price_per_unit'])), columns=['Time', 'price_per_unit_raspberry-2']) dfr3 = pd.DataFrame(list(zip(dfr_3['DELV_DT'], dfr_3['price_per_unit'])), columns=['Time', 'price_per_unit_raspberry-3']) dfc1 = pd.DataFrame(list(zip(dfc_1['DELV_DT'], dfc_1['price_per_unit'])), columns=['Time', 'price_per_unit_cherries-1']) dfc2 = pd.DataFrame(list(zip(dfc_2['DELV_DT'], dfc_2['price_per_unit'])), columns=['Time', 'price_per_unit_cherries-2']) dfc3 = pd.DataFrame(list(zip(dfc_3['DELV_DT'], dfc_3['price_per_unit'])), columns=['Time', 'price_per_unit_cherries-3']) #list of dataframes to merge data_frames = [dfs1,dfs2,dfs3,dfba1,dfba2,dfba3,dfbu1,dfbu2,dfbu3,dfr1,dfr2,dfr3,dfc1,dfc2,dfc3] #merging the dataframes into one dataframe over the Time column df_merged = reduce(lambda left,right: pd.merge(left,right,on=['Time'], how='outer'), data_frames) #Set Time column as index df_merged= df_merged.set_index('Time') #Upscale the time index to daily frequency and using the mean price if the same SKU is sold on the same date df_merged = df_merged.resample('D').mean() df_merged = df_merged.fillna(value=0) #Fill NaN values with 0 print (df_merged.head()) append_df_to_excel('MostValuableSKU-Time-Price.xlsx', df_merged,sheet_name='Sheet-1') #append merged dataframe to the Excel file
5cbef282bfefb0a087b7712efce625b8539cbe51
mjustinz86/CIS2348JustinoCortez
/Homework_1/Coding Prob 1.py
419
3.96875
4
# Justino Cortez ID:1615245 print('Birthday Calculator', '\n Current day') month = int(input('Month: ')) day = int(input('Day: ')) year = int(input('Year: ')) print('Birthday') B_month = int(input('Month: ')) B_day = int(input('Day: ')) B_year = int(input('Year: ')) age = year - B_year if (month + day) > (B_month + B_day): age = age else: age = (year - B_year) - 1 print('You are', age, 'years old')
bd74494d5e335e035f08eb3e3cf5950de21055b8
SlaviGigov/PythonAdvanced
/Lists_as_Stacks_and_Queues/pythonProject/lab/lab_water_dispenser.py
534
3.71875
4
from collections import deque queue = deque() water = int(input()) while True: name = input() if name == "Start": break else: queue.append(name) while True: do = input() if do == "End": print(f"{water} liters left") break elif do[0] == "r": do = do.split() water += int(do[1]) else: if water >= int(do): print(f"{queue.popleft()} got water") water -= int(do) else: print(f"{queue.popleft()} must wait")
d2d6f31a39738bea0cf4d46166a166b9ec4180ce
ykytutou/python-learning
/test1.py
711
3.828125
4
# -*- coding : UTF-8 -*- # @Time : 2020/7/14 0014 4:36 25 PM # @Author : OliverYin # @File : test1.py # @Software : PyCharm import random a = int(input("请输入数字:剪刀(0)、石头(1)、布(2):")) b = random.randint(0, 2) x = "" y = "" if a == 0: x = "剪刀" elif a == 1: x = "石头" elif a == 2: x = "布" print("你出的是:%s(%d)" % (x, a)) if b == 0: y = "剪刀" elif b == 1: y = "石头" elif b == 2: y = "布" print("电脑出的是:%s(%d)" % (y, b)) if a == b: print("平局!") elif ((a - b) == 1) or ((b - a) > 1): print("恭喜,你赢了!") elif ((b - a) == 1) or ((a - b) > 1): print("哈哈,你输了!")
7aab52b16f70d68326bc9b96165a4238dfbfd63d
theChad/ThinkPython
/chap13/markov.py
3,602
4.03125
4
import random import analyze_book # Exercise 13.8 # 13.8.1 def read_wordlist(filename="book.txt"): """Read wordlist from filename """ words = [] fin = open(filename) for line in fin: words.extend(line.split()) return words def create_prefix_map(filename="book.txt", len_prefix=2, len_suffix=1): """Create a dictionary of prefixes to possible suffixes from any prefix """ words = read_wordlist(filename) prefix_map = dict() # Store prefix and suffix lengths in prefix map prefix_map[None] = [len_prefix, len_suffix] for i in range(len(words)-len_prefix-len_suffix+1): # Put the first len_prefix words at this point into prefix, # and the next len_suffix words into suffix. Make them tuples, so # we can use them as keys for dictionaries and sets. prefix = tuple(words[i:i+len_prefix]) suffix = tuple(words[i+len_prefix:i+len_prefix+len_suffix]) # Using sets for suffixes. If we haven't encountered this prefix before, # initialize with an empty dictionary. Do setdefault on *that* dictionary # also, to build up a histogram of suffixes. An entry might look like # {('this', 'is'): # {('a',): 34, ('the',): 23, ('my'): 10}} # The keys (prefixes and suffixes) are all tuples. A tuple with length one # is written like (<value>,). suffix_hist = prefix_map.setdefault(prefix, {}) suffix_hist[suffix] = suffix_hist.get(suffix, 0) + 1 #prefix_map.setdefault(prefix, {})[suffix] = (suffix,0) += 1 return prefix_map # 13.8.2 def generate_random_text(prefix_map, num_words_to_generate=100): """Generate random text from a dictionary of prefixes to suffixes """ # We've stored the prefix and suffix lengths in the map. # Get those, then delete the entry so we don't run into # it when picking random prefixes len_prefix = prefix_map[None][0] len_suffix = prefix_map[None][1] del(prefix_map[None]) # Get all prefixes so we can choose one at random when no # possible suffixes exist. prefix_list = list(prefix_map.keys()) generated_text = random.choice(prefix_list) i=0 while i < num_words_to_generate: # Get a prefix from the text generated so far prefix = generated_text[i:i+len_prefix] # Only try to generate the suffix if the prefix is # in our prefix map. if prefix in prefix_map: # Generate a random suffix from the possiblities # choose_from_hist, from analyze_book.py, choose items # randomly based on a histogram. It returns them as a list, # one item in our case, so we'll use [0] to get the item. # Which will be a tuple of the suffix word(s), of length # len_suffix. suffix = analyze_book.choose_from_hist(prefix_map[prefix])[0] generated_text+=suffix i += len(suffix) # If prefix is not in the map, generate a new prefix. # I think this should only happen if we reached unique # text at the very end of the original file. E.g. 'The End.' # No suffix to predict after that. else: new_text = random.choice(prefix_list) generated_text+=new_text i += len(new_text) generated_text_string = ' '.join(generated_text) return generated_text_string def test_markov(): text = generate_random_text(create_prefix_map('double.txt',2,1),1000) print(text) if __name__=='__main__': test_markov()
b14a4014227864c6c9b7592de4393c44af599ec4
agonzalezcurci/class-work
/debugging8.py
234
3.625
4
t = ["b", "d", "a","c"] # make copies orig = t[:] t.sort() print(t) # correct t.append("x") print(t) t = t + ["y"] print(t) # wrong t.append(["q"]) print(t) t = t.append("n") print(t) t = t + x print(t) t + ["t"] print(t)
097c6e350e80ef4c1631e0f66786d3a49a10b45a
agamyafe10/secret
/secret_message_server.py
1,088
3.59375
4
from scapy.all import * def is_without_data(packet): """checking if the pacekts includes data for insuring this is the packet we want Args: packet (packet): Returns: true if there is no data else return false """ if packet['UDP'].len == 8:# length 8 is the equivilent length for no data return True return False def is_udp(packet): """checks if the packet is UDP Args: packet (packet) Returns: true if udp else false """ if 'UDP' in packet: return True return False def valid(packet): """checks if the packet is the one we want Args: packet (packet) Returns: true if stands the conditions else false """ if is_udp(packet) and is_without_data(packet): return True return False print("Started Sniffing...") print("The message is: ") while True:# keep sniffing because we have no length limit packets = sniff(count=1, lfilter = valid)# gets the wanted packet print(chr(packets[0]['UDP'].dport), end = "")# prints the letter according to the port the packets was sent to
23ade0836e06cae873067b44143e4b012128632e
TomasBahnik/pslib
/python/alp/lectures/permutation.py
253
3.6875
4
import random def permutation(n): """Create a random permutation of integers 0..n-1""" p = list(range(n)) for i in range(n - 1): r = random.randrange(i, n) temp = p[r] p[r] = p[i] p[i] = temp return (p)
7285c1d46fd1423ae38e25134c414c6872efbe21
isabel-lombardi/workbook_python
/chap_8/ex_180.py
652
3.9375
4
# String edit Distance def string_distance(s, t): if len(s) == 0: return len(t) elif len(t) == 0: return len(s) else: cost = 0 if s[len(s) - 1] != t[len(t) - 1]: cost += 1 d1 = string_distance(s[0: len(s) - 1], t) + 1 d2 = string_distance(s, t[0: len(t) - 1]) + 1 d3 = string_distance(s[0: len(s) - 1], t[0: len(t) - 1]) + cost return min(d1, d2, d3) def main(): txt1 = input("Enter the first word: ") txt2 = input("Enter the second word:") print("The edit distance between {} and {} is: {}".format(txt1, txt2, string_distance(txt1, txt2))) main()
bf8c64d44372cdc2a6e85dca6343707c6da0fd6b
Pandey-Noah-3816/SWE-HW-4
/HW4/volume.py
176
3.546875
4
def volume(a,b,c): try: vol = int(a)*int(b)*int(c) if vol <= 0: return("bad inputs result was negative") except ValueError: return TypeError return vol
e55afd5bcae9bb61b1fa105804628294bb4788b3
trenator/PfCB
/chapter_2/Ex2_1.py
1,137
3.671875
4
# counting vowels # what proportion of this sentence is made up of the vowels (a e i o u) sentence = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only." low_sentence = sentence.lower() length_sentence = (len(sentence)) a_count = low_sentence.count('a') e_count = low_sentence.count('e') i_count = low_sentence.count('i') o_count = low_sentence.count('o') u_count = low_sentence.count('u') # print(a_count, e_count, i_count, o_count, u_count) count_vowels = (a_count + e_count + i_count + o_count + u_count) pc_vowels = (count_vowels / length_sentence) print(pc_vowels)
13fb38c4a1b5e39c8780ebbe9d72e4a2ffcbe190
Aden-Q/LeetCode
/code/456.132-Pattern.py
391
3.65625
4
class Solution: def find132pattern(self, nums: List[int]) -> bool: s = [] # 递减栈 third = -float('inf') for i in range(len(nums)-1, -1, -1): if nums[i] < third: return True else: while s and nums[i] > s[-1]: third = s.pop() s.append(nums[i]) return False
2deaff3b425201237542025c6defb5c27b0fd041
SWATISIGNATURE/Python
/Codeacademy_Projects/Carly's_Clippers.py
763
3.546875
4
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"] prices = [30, 25, 40, 20, 20, 35, 50, 35] last_week = [2, 3, 5, 8, 4, 4, 6, 2] total_price = 0 for price in prices: total_price += price average_price = total_price/len(prices) print("Average Haircut Price:", average_price) new_prices = [] for price in prices: new_prices.append(price -5) print(new_prices) total_revenue = 0 for i in range(len(hairstyles)): total_revenue = prices[i] * last_week[i] print("Total Revenue:",total_revenue) average_daily_revenue = total_revenue / len(hairstyles) print(average_daily_revenue) cuts_under_30 = [] for i in range(len(new_prices)): if i < 30: cuts_under_30.append(hairstyles[i]) print(cuts_under_30)
1353efea377a1a94d35025b441bcf4f38068ac2d
davejlin/treehouse
/python/quiz-timed/quiz.py
1,755
3.796875
4
import datetime import random from questions import Add, Multiply class Quiz: questions = [] answers = [] def __init__(self): question_types = (Add, Multiply) for i in range(10): a = random.randint(0,10) b = random.randint(0,10) question = random.choice(question_types)(a, b) self.questions.append(question) def take_quiz(self): start_time = datetime.datetime.now() for question in self.questions: result, start, end = self.ask(question) if result: print("You got it right!") else: print("Woops, the correct answer is: ", str(question.answer)) self.output_timediff("I took you {} to solve the question.", start, end) self.answers.append(result) end_time = datetime.datetime.now() self.summary(start_time, end_time) def ask(self, question): start = datetime.datetime.now() answer = input("What is: {} > ".format(question.text)) end = datetime.datetime.now() return int(answer) == question.answer, start, end def summary(self, start, end): n_questions = len(self.questions) n_correct = len(list(filter(lambda x: x, self.answers))) print("\nYou got {} out of {} correct.".format(n_correct, n_questions)) self.output_timediff("It took you {} to answer all the questions.", start, end) return def output_timediff(self, text, start, end): diff = end-start total_seconds = diff.total_seconds() hours, remainder = divmod(total_seconds, 3600) minutes, seconds = divmod(remainder, 60) if hours > 0: time_str = "{} hr {} min {} sec".format(hours, minutes, seconds) elif minutes > 0: time_str = "{} min {} sec".format(minutes, seconds) else: time_str = "{} sec".format(seconds) print(text.format(time_str)) quiz = Quiz() quiz.take_quiz()
9523937419888a88eb065c0a52011a4d822346e5
sadOskar/courses
/lesson_7/ex_8.py
1,010
3.78125
4
# def gcd(a, b): # while b: # a, b = b, a % b # return a # # # print(gcd(24, 36)) # # t = [[1, 2], [3], [4, 5, 6]] # # # def nested_sum(t): # total = 0 # for item in t: # a = sum(item) # total += a # return total # # print(nested_sum(t)) # # massages = ["Python", "Java", "Android"] # # def show_massages(massages): for item in massages: print(item) return massages show_massages(massages) def send_massages(massages): sent_massages = [] for item in massages: sent_massages.append(item) return massages, sent_massages print(send_massages(massages)) # def total_numbers(a, b, c): # sum_numbers = 0 # if a == b == c: # sum_numbers = a + b + c # else: # sum_numbers = (a + b + c) ** 2 # return sum_numbers # # # print(total_numbers(1, 2, 3)) # def showEmployee(name, wages=9000): # # print(name, wages) # # # name = input() # wages = int(input()) # showEmployee(name)
608d738c404ede2d18f452cbfd334832afa851e6
udoy382/Module
/csv_4.py
2,364
4.21875
4
# GeeksforGeeks / from web # Reading a CSV file ''' # importing csv module import csv # csv file name filename = "user.csv" # initializing the titles and rows list fields = [] rows = [] # reading csv file with open (filename, 'r') as csvfile: # creating a csv reader object csvreader = csv.reader(csvfile) # extracting field names through first row fields = next(csvreader) # extracting each data row one by one for row in csvreader: rows.append(row) # get total number of rows print("Total no. of rows: %d"%(csvreader.line_num)) # printing first 5 rows print('\nfirst 5 rows are:\n') for row in rows: # parsing each column of a row for col in row: print("%10s"%col), print('\n') ''' # Writing to a CSV file ''' # importing the csv module import csv # field names fields = ['Name', 'Branch', 'Year', 'CGPA'] # data rows of csv file rows = [ ['Udoy', 'COE', '2', 9.0], ['Maryam', 'COE', '2', 9.5], ['Fariha', 'IT', '1', 8.0], ['Mitu', 'SE', '2', 9.0], ['Amy', 'MCE', '1', 7.4], ['Nadiya', 'EP', '2', 9.1] ] # name of csv file filename = "collage_records.csv" with open(filename, 'w') as csvfile: # creating a csv writer object csvweiter = csv.writer(csvfile) # writing the fields csvweiter.writerow(fields) # writing the data rows csvweiter.writerows(rows) ''' # Writing a dictionary to a CSV file ''' # importing the csv module import csv # my data rows as dictionary objects mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] # field names fields = ['name', 'branch', 'year', 'cgpa'] # name of csv file filename = "collage_records.csv" # writing to csv file with open(filename, 'w') as csvfile: # creating a csv dict writer object weiter = csv.DictWriter(csvfile, fieldnames = fields) # writing headers (field names) weiter.writeheader() # writing data rows weiter.writerows(mydict) '''
3ebe14d6e3fe0402160226a942e93c8104312dc5
AndrewKoch/ciphers
/utils.py
1,036
3.671875
4
import logging def check_validity(crib): if not crib.isalpha(): raise Exception("Letters only.") def format_input(crib): "Removes whitespace, verifies characters are letters, and capitalizes them." crib = crib.replace(" ", "") check_validity(crib) crib = crib.upper() return crib def format_output(ciphertext): "Seperates a string into blocks of five characters" logger = logging.getLogger() logger.debug("Length of ciphertext is %s", len(ciphertext)) if len(ciphertext) <= 5: return ciphertext blocks = len(ciphertext) // 5 logger.debug("Number of blocks: %s", blocks) block_index = 5 blocked_cipher = ciphertext[:5] while (block_index / 5) < blocks: blocked_cipher += " " + ciphertext[block_index:block_index+5] block_index += 5 if (len(ciphertext) % 5) != 0: blocked_cipher += " " + ciphertext[block_index:len(ciphertext)] logger.debug("Returning blocked ciphertext as %s", blocked_cipher) return blocked_cipher
b610ee36b813df9bcd56d50aee57d60ddaa3269c
1026237416/Python
/algorithm/句子反转.py
483
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/19 22:10 # @Author : liping # @File : 句子反转.py # @Software: PyCharm def get_reverse(strings): result = "" result_list = [] str_split = strings.split() while len(str_split): result_list.append(str_split.pop()) result = " ".join(result_list) return result if __name__ == '__main__': user_input = raw_input("").strip() res = get_reverse(user_input) print res
4f9008526370c6ba1e5d87046ec9def61df8aa62
mjmikulski/code_snippets
/python/pround/test_pround.py
1,486
3.53125
4
import unittest from math import sqrt from random import uniform from statistics import mean from python.pround.pround import pround class TestElegantNumbers(unittest.TestCase): do_print = True def test_255(self): S = 255 N = 10 ** 2 xs = [uniform(0, S) for _ in range(N)] ys = [pround(x) for x in xs] m_x = mean(xs) m_y = mean(ys) delta = 2 * S / sqrt(N) if TestElegantNumbers.do_print: print('mean x: {}\nmean y: {}'.format(m_x, m_y)) print('delta:', delta) self.assertAlmostEqual(m_x, m_y, delta=delta) def test_0_6(self): C = 0.6 N = 10 ** 3 xs = [C for _ in range(N)] ys = [pround(x) for x in xs] m_x = mean(xs) m_y = mean(ys) delta = 2 * C / sqrt(N) if TestElegantNumbers.do_print: print('mean x: {}\nmean y: {}'.format(m_x, m_y)) print('delta:', delta) self.assertAlmostEqual(m_x, m_y, delta=delta) def test_1(self): S = 1 N = 10 ** 4 xs = [uniform(0, S) for _ in range(N)] ys = [pround(x) for x in xs] m_x = mean(xs) m_y = mean(ys) delta = 2 * S / sqrt(N) if TestElegantNumbers.do_print: print('mean x: {}\nmean y: {}'.format(m_x, m_y)) print('delta:', delta) self.assertAlmostEqual(m_x, m_y, delta=delta) if __name__ == '__main__': unittest.main()
fe1a5117b96266dde6653c312c41801586d493d2
vinigrator/python-practice
/pract/ex2.py
278
3.5
4
def count_names(): names = {} with open('names.txt', 'r') as f: for line in f: line = line[:-1] if names.get(line) == None : names[line] = 0 else : names[line] += 1 f.close() for key, value in names.items(): print key + " " + str(value) count_names()
6f4977a0b8f0050dedf2e6b8dd08149fb37be2f7
giseledoan/Election_analysis
/PyPoll.py
4,600
3.90625
4
#The data we need to retrieve. #1. The total number of votes cast #2. A complete list of candidates who received votes. #3. The percentage of votes each candidate won. #4. The total number of votes each candidate won. #5. The winner of the election based on popular vote. #use datetime module to get today's date import datetime now = datetime.datetime.now() print("The time right now is", now) #Open file by direct path ##Assign a variable for the file to load and the path. file_to_load = 'C:\\Users\\trang doan\\OneDrive\\Desktop\\Analysis projects\\Election_analysis\\Resources\\election_results.csv' ##Open the election results and read the file. with open(file_to_load) as election_data: ##To-do: Perform analysis. print(election_data) #Print total votes, candidate's name & votes ##Add dependencies. import csv import os ##Assign a variable "file to load" for "election_result.csv" by indirect path. file_to_load = os.path.join(".","Resources","election_results.csv") ##Assign a variable "file to save" to save output file (after creating analysis folder) file_to_save = os.path.join("analysis", "election_analysis.txt") ##Create election_analysis.txt with open(file_to_save,"w") as txt_file: ###Write some data to the txt. txt_file.write("Counties in the election\n") txt_file.write("Arapahoe\nDenver\nJefferson\n") ##Initialize a total vote counter. total_votes = 0 ##Declare a new list "candidate_options" for candidate's name candidate_options = [] ##Declare a new dictionary "candidate_votes" for candidate's votes candidate_votes = {} ##Declare variable to count winning candidate, winning count & winning % winning_candidate = " " winning_count = 0 winning_percentage = 0 ##Open the "file to load" (election_results.csv) and read the file. with open(file_to_load) as election_data: file_reader = csv.reader(election_data) ###Read the header row to skip it in votes count. headers = next(file_reader) ###Print each row in the CSV file. for row in file_reader: #(file_reader is csv file) #### Add to the total vote count. total_votes +=1 #variable increase by 1 when we read each row #### Print the candidate name from each row candidate_name = row [2] #### if candidate name has not been added to list, add it. if candidate_name not in candidate_options: ##### Add it to the list of candidate_options candidate_options.append(candidate_name) ##### Track that candidate's vote count, start w 0 candidate_votes[candidate_name] = 0 #### Add a vote to each candidate's count, increase 1 when we read each candidate name. candidate_votes[candidate_name] +=1 ### Save the results to our text file. with open(file_to_save, "w") as txt_file: #Print final vote count to the terminal election_results = (f"\nElection Results\n" f"------------------\n" f"Total Votes: {total_votes:,}\n" f"-------------------\n") print(election_results, end="") #Save the final vote count to the text file. txt_file.write(election_results) ##Print the candidate vote dictionary (inclde name & votes) print(candidate_votes) #Calculate percentage of votes ##Iterate through the candidate list dictionary to get their name: for candidate_name in candidate_votes: ### retrieve vote count of a candidate, can_name = row [2] votes = candidate_votes[candidate_name] ### calcuate percentage of votes vote_percentage = float(votes) / float(total_votes) *100 #Print the candiate name, vote count & percentage of votes candidate_results = (f"{candidate_name}: received {vote_percentage:.1f}% ({votes:,})\n") print(candidate_results) txt_file.write(candidate_results) #Determine if votes > winning count: if (votes > winning_count) and (vote_percentage > winning_percentage): #If true, set winning_count = votes and winning % = vote % winning_count = votes winning_percentage = vote_percentage #Set winning candidate = candidate name winning_candidate = candidate_name #Print out the winning candidate summary winning_candidate_summary = (f"------------------\n" f"Winner:{winning_candidate}\n" f"Winning Vote Count:{winning_count:,}\n" f"Winning Percentage:{winning_percentage:.1f}%\n" f"-------------\n") print(winning_candidate_summary) #Save the winning candidate's result to the txt file txt_file.write(winning_candidate_summary)
3fb06fd18c9a4e4018aae47d3e9178b2cd8c1759
Radizzt/Python3-Fundamental
/04 Syntax/syntax-functions.py
440
3.515625
4
#!/usr/bin/python3 # syntax.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC def main(): foo(2); foo(3); foo(4); foo(); #assigning a parameter makes it default def foo(a=8): for i in range(a, 10): print(i, end=' '); print(); if __name__ == "__main__": main(); #let you call function after their call
081d2eae2c149f4422a73a1bb307e67b8e72c62a
carlosafdz/pensamiento_computacional_python
/algoritmos/enumeracion.py
251
3.953125
4
a = int(input("numero entero: ")) respuesta = 0 while respuesta**2 < a: respuesta += 1 print(respuesta) if respuesta**2 == a: print(f'la raiz cuadrada de {a} es {respuesta}') else: print(f'respuesta no tiene raiz cuadrada exacta')