blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
fb689544fb8d2c7267a2eea35063279182cce32f
emanuelrv/avc
/p11.py
212
3.671875
4
numbers = range(1, 21) print numbers ##test sum = 0 for counter in numbers: sum = sum + counter print "la suma" , sum my_names = {"Joe", "Bob", "Ned"} print my_names[0] print my_names[2] print my_names[3]
51f9c23d2637cf1b8746f45720d73b3fbf543cb3
disCCoRd1/Machine-Learning---Basis
/statistical_methods_for_machine_learning/code/chapter_12/03_correlation.py
560
3.75
4
# calculate the pearson's correlation between two variables from numpy.random import randn from numpy.random import seed from scipy.stats import pearsonr # seed random number generator seed(1) # prepare data data1 = 20 * randn(1000) + 100 data2 = data1 + (10 * randn(1000) + 50) # calculate Pearson's correlation corr, p = pearsonr(data1, data2) # display the correlation print('Pearsons correlation: %.3f' % corr) # interpret the significance alpha = 0.05 if p > alpha: print('No correlation (fail to reject H0)') else: print('Some correlation (reject H0)')
484bf5426bc66fac06ed3d08460f9b5fafb5f522
myfairladywenwen/cs5001
/hw09/word_ladder_no_extra_solution/word_ladder.py
1,722
3.90625
4
from queue import Queue from stack import Stack class WordLadder: """A class providing functionality to create word ladders""" def __init__(self, w1, w2, wordlist): self.word1 = w1 self.word2 = w2 self.valid_words_set = wordlist self.myqueue = Queue() self.mystack = Stack() self.word_visited_set = set() def make_ladder(self): if len(self.word1) != len(self.word2): return None else: self.mystack.push(self.word1) self.myqueue.enqueue(self.mystack) self.word_visited_set.add(self.word1) alpha_list = self.generate_alphe_list() while not self.myqueue.isEmpty(): curr_stack = self.myqueue.dequeue() curr_word = curr_stack.peek() for i in range(len(curr_word)): for letter in alpha_list: new_word = curr_word[:i] + letter + curr_word[i+1:] if (new_word in self.valid_words_set and new_word not in self.word_visited_set): self.word_visited_set.add(new_word) new_stack = curr_stack.copy() new_stack.push(new_word) if new_word == self.word2: return new_stack else: self.myqueue.enqueue(new_stack) return None def generate_alphe_list(self): alphe_list = [] for each in range(ord('a'), ord('a')+26): alphe_list += [chr(each)] return alphe_list
c2a80c99f8e11e6ec7bb29ad9df2f59dca25df08
Dipesh13/doc-classification
/extract_text.py
884
3.703125
4
# encoding=utf8 import PyPDF2 import os # filename = 'Frankenstein.pdf' def text_ext(filename): """ Function to extract text from pdf and save it in txt format :param filename: :return: """ dump = '' pdfFileObj = open(filename, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) for i in range(pdfReader.numPages): pageObj = pdfReader.getPage(i) # print(pageObj.extractText()) dump += pageObj.extractText() with open(filename[0:-4]+'.txt','wb') as fo: fo.write(dump.encode('utf-8')) for (dirname, dirs, files) in os.walk('.'): # walk the finance directory or the parent dir to convert pdfs to txts for filename in files: if filename.endswith('.pdf') : thefile = os.path.join(dirname,filename) text_ext(thefile) print("Finished processing {}".format(thefile))
bff1ac93bbda37435a2df3337b4a4b8f794164d3
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/phone-number/c38910c17dc94006afa9ebb06148a586.py
388
3.65625
4
class Phone: def __init__(self, s): s = "".join(c for c in s if c.isnumeric()) self.number = (s[-10:] if len(s) == 10 or len(s) == 11 and s[0] == "1" else "0" * 10) def area_code(self): return self.number[:3] def pretty(self): return "({}) {}-{}".format( self.number[:3], self.number[3:6], self.number[6:])
fcfa717f0b15f54e166b56c96687dcbe789c1a6e
StianHanssen/RockPaperScissors
/game.py
2,028
3.671875
4
from action import Action __author__ = 'Stian R. Hanssen' class SingleGame(): def __init__(self, player1, player2): self.__player1 = player1 self.__player2 = player2 self.__point1 = 0 self.__point2 = 0 self.__pick1 = None self.__pick2 = None def execute_game(self): self.__pick1 = self.__player1.pick_action() self.__pick2 = self.__player2.pick_action() self.__point1 = 1 if self.__pick1 > self.__pick2 else (1/2 if self.__pick1 == self.__pick2 else 0) self.__point2 = 1 if self.__pick1 < self.__pick2 else (1/2 if self.__pick1 == self.__pick2 else 0) self.__player1.recieve_result(self.__pick2, self.__point1) self.__player2.recieve_result(self.__pick1, self.__point2) def __str__(self): if self.__pick1 is None and self.__pick2 is None: return "Game has not been executed" res = self.__point1 - self.__point2 winner = "No one" if res == 0 else (self.__player1 if res > 0 else self.__player2) feedback = "[" + str(self.__player1) + ": " + str(self.__pick1) + "] VS [" feedback += str(self.__player2) + ": " + str(self.__pick2) feedback += "] -> " + str(winner) + " won!" return feedback class Turnament(): def __init__(self, player1, player2, num_games): self.__player1 = player1 self.__player2 = player2 self.__num_games = num_games self.__single_game = SingleGame(player1, player2) def execute__single_game(self): self.__single_game.execute_game() print(self.__single_game) def execute_turnament(self): for i in range(self.__num_games): self.execute__single_game() total_points = self.__player1.get_points() + self.__player2.get_points() print(self.__player1, "got", str(100 * self.__player1.get_points() / total_points) + "% of the points") print(self.__player2, "got", str(100 * self.__player2.get_points() / total_points) + "% of the points")
7544cd1bed43dd52fe078359bd35d3be57c83857
bhawnagurjar27/CodeForces-Problems-Solution
/Word Capitalization/Word Capitalization.py
350
3.75
4
number_of_testcases = 1 #int(input()) for _ in range(number_of_testcases): given_string = input() given_string = list(given_string) if ord(given_string[0]) >= 97: given_string[0] = chr(ord(given_string[0]) - 32) answer = "" for char in given_string: answer += char print(answer)
ece2405adbebc7b93bf9f7e1be0a0d70610bf22b
pfalcon/pycopy
/tests/basics/subclass_native6.py
183
3.609375
4
# Calling native base class unbound method with subclass instance. class mylist(list): pass l = mylist((1, 2, 3)) assert type(l) is mylist print(l) list.append(l, 4) print(l)
5cba7fef05646ffa7a250172dd8cdc8501e56ce5
python20180319howmework/homework
/caixiya/20180328/3.py
449
3.921875
4
''' 定义一个函数,计算给定的整型数是否为质数 ''' def isprime(num): if num>=2: for i in range(2,num//2+1): if(num%i==0): return False else: return True else: #print("{}是质数".format(num)) return True else: #print("{}不是质数".format(num)) return False num=int(input("请输入一个整型数:")) if isprime(num): print("{}是质数".format(num)) else: print("{}不是质数".format(num))
7768e0c5d9296c50c9655c55ae15156fd582e614
prabhatpal77/Complete-core-python-
/intplusstring.py
151
3.53125
4
#int+string x="prabhatpal" print(x) y="python" z="1234" print(z) p=1000 print(p) print(x+y) print(x+z) print(x+str(p)) print(int(z)+p) print(z+str(p))
39a96e86355a2a5b8ffdb2f26aed985b537810de
zelzhan/Challenges-and-contests
/Python-Hackerrank/polar-coordinates.py
578
4
4
'''You are given a complex . Your task is to convert it to polar coordinates.''' import cmath print(*cmath.polar(complex(input())), sep='\n') # polar = [c for c in input() if c not in "+j"] # indexes = [i for i in range(len(polar)) if polar[i] == '-'] # if len(polar) > 2: # polar = map(int, [c for c in polar if c not in "-"]) # print(*polar) # polar = [-polar[i] for i in range(2) if indexes[i] == '-'] # print(polar) # polar = list(map(int, polar)) # print(polar) # print(abs(complex(polar[0], polar[1]))) # print(cmath.phase(complex(polar[0], polar[1])))
0e6fc731688307bd2e3581d8177327379c492f8d
rehman20/python
/python_sandbox_starter/files.py
454
3.84375
4
# Python has functions for creating, reading, updating, and deleting files. myFile=open('name.txt','w') print('Name of File: '+myFile.name) print('Mode of Operation: '+myFile.mode) myFile.write('My name is Rehman Aziz.\n') myFile.write('I am 23 years old.') myFile.close() myFile=open('name.txt','a') myFile.write('\nI like python and djando\n') myFile.close() myFile=open('name.txt','r') strContent=myFile.read(100) print(strContent) myFile.close()
9285766eedce90df6678f25e1fb766386403ac62
divad417/sandbox
/kalman/kalman.py
2,716
3.703125
4
#!/usr/local/bin/python3 # Python class to implement a Kalman Filter import numpy as np import matplotlib.pyplot as plt from random import random from math import * class kalman(): # Init assuming 2d problem with no control input or process noise def __init__(self, t0, dx): self.t = t0 # Measurement function self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) # Measurement uncertainty self.R = np.array([[dx, 0], [0, dx]]) # Initialize state self.x = np.zeros([4,1]) # Initialize variance self.P = 1000 * np.identity(4) def step(self, t, z): dt = t - self.t self.t = t # State function with new dt self.F = np.identity(4) self.F[0,2] = dt self.F[1,3] = dt # Update y = z - np.dot(self.H, self.x) S = np.dot(self.H, np.dot(self.P, self.H.transpose())) + self.R K = np.dot(np.dot(self.P, self.H.transpose()), np.linalg.inv(S)) self.x = self.x + np.dot(K, y) self.P = np.dot((np.identity(4) - np.dot(K, self.H)), self.P) # Predict self.x = np.dot(self.F, self.x) self.P = np.dot(self.F, np.dot(self.P, self.F.transpose())) x = self.x P = self.P return(x, P) def line(n, dx): x0 = 0 y0 = 0 theta = pi/4 v = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9.5, 9, 8.5, 8, 7, 6, 5, 4, 2, 1, 0.5] dt = 0.1 t = np.linspace(0, 10, 101) pos = np.empty([n, 2]) for i in range(n): x_new = np.random.normal(x0 + t[i] * v[i] * cos(theta), dx) y_new = np.random.normal(y0 + t[i] * v[i] * sin(theta), dx) pos[i,:] = [x_new, y_new] return(t, pos) def main(): # Initialize the kalman filter dx = 0.2 # measurement uncertainty k = kalman(0, dx) n = 21 t, truth = line(n, dx) filt_pos = np.empty([n, 4]) filt_spd = np.empty(n) spd_var = np.empty(n) for i in range(n): # Prepare the measurement input z = np.array(truth[i,:], ndmin=2).transpose() # Run the Kalman Filter x, P = k.step(t[i], z) # Record the output filt_pos[i,:] = np.transpose(x) filt_spd[i] = np.linalg.norm([x[2][0], x[3][0]]) spd_var[i] = np.linalg.norm([P[2][2], P[3][3]]) # Plot the results plt.subplot(2,1,1) plt.plot(truth[:,0],truth[:,1],'+') plt.plot(filt_pos[:,0],filt_pos[:,1],'--') plt.axis('equal') plt.subplot(2,1,2) plt.plot([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9.5, 9, 8.5, 8, 7, 6, 5, 4, 2, 1, 0.5]) plt.plot(filt_spd) plt.plot(spd_var) plt.axis([0, 50, 0, 15]) plt.show() main()
67967e704ce17dad07f28ac5c292a817f57a1b18
pbcquoc/coding-interview-python
/sort_algorithm/shell_sort.py
535
3.765625
4
def shell_sort(arr): gap = len(arr)//2 while gap > 0: i = 0 j = gap while j < len(arr): if arr[i] > arr[j]: arr[i], arr[j] = arr[j], arr[i] i += 1 j += 1 print(i, j, gap) k = i while k - gap > -1: if arr[k - gap] > arr[k]: arr[k-gap], arr[k] = arr[k], arr[k-gap] k -= 1 gap //= 2 arr2 = [12, 34, 54, 2, 3] shell_sort(arr2) print(arr2)
f4ad96f88f426ba8d4bca05205c06ae345c2bb6e
aadithpm/leetcode
/Sprint/SumOfRootToLeafBinaryTreeNumbers.py
604
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: self.bin_sum = 0 def dfs(node, res): res += str(node.val) if node.left: dfs(node.left, res) if node.right: dfs(node.right, res) if not node.left and not node.right: self.bin_sum += int(res, 2) dfs(root, '') return self.bin_sum
18d198e72ed9a132a5a1c428eafbffaa255c5465
SomethingRandom0768/PythonBeginnerProgramming2021
/Chapter 6 ( Dictionaries )/Exercises/6-11cities.py
942
4.21875
4
cities = {'Gaborone' : { 'Country' : 'Botswana', 'Population' : "208,411", 'Fact' : "Home to the world's largest concentration of African elephants", }, 'Vilnius' : { 'Country' : 'Lithuania', 'Population' : "540,000", 'Fact' : "8% of all white storks in the world breed here ", }, 'Caracas' : { 'Country' : 'Venezuela', 'Population' : "2,946,000", 'Fact' : "Home to one of the largest financial districts in South America", } } for name, info_group in cities.items(): print(f"\nThe city's name is {name} and has the following information:") for label, info in info_group.items(): print(f"{label} : {info}")
1054f40a28ddc711f1833161a1775be66902f415
Datamine/Project-Euler
/Problems/006/solution.py
286
3.5625
4
#!/usr/bin/python3 def main(): sum_of_squares_accumulator = 0 for i in range(1,101): sum_of_squares_accumulator += i**2 square_of_sum = sum(range(1,101)) ** 2 return abs(square_of_sum - sum_of_squares_accumulator) if __name__=='__main__': print(main())
6c26f91218caf24cef355f23c5cc4e7bbac725b3
aijunbai/bandit
/python/bandit.py
1,829
3.890625
4
import random class Arm: "simulation of bendit's arm" def __init__(self, average): self.average = average def pull(self): """returns the result (1/0)""" if random.random() < self.average : return 1 else: return 0 def getAverage(self): """returns the arm's average""" return self.average class Bandit: "simulation of a bandit" def __init__(self, averageList): #initialize bandit's arms self.arms = [Arm(average) for average in averageList] #calculate the best arm average: self.bestArmAverage = max(averageList) def pullArm(self, armNum): """pulls the bandit's arm in the given index""" return self.arms[armNum].pull() def getArmsNum(self): """returns the numbers of arm in bandit""" return len(self.arms) def calcRegret(self, armIndex): """returns the regret of the arm in the given index""" return self.bestArmAverage - self.arms[armIndex].getAverage() def RandomBandit(numBandits): avgList = [random.uniform(0, 1) for _i in range(numBandits)] return Bandit(avgList) # def _test_bandit(): # semiBandit = Bandit([0.1, 0.5, 0.2, 0.4]) # assert semiBandit.calcRegret(0) == 0.4 # assert semiBandit.calcRegret(2) == 0.3 # # def _test_arm(): # one = Arm(2) # zero = Arm(-1) # assert one.getAverage() == 2 # assert one.pull()==1 # assert zero.pull()==0 # # def _test(): # _test_arm() # _test_bandit() # # _test() #if __name__ == "__main__": #averages = [0.4, 0.7, 0.1, 0.6] #semiBandit = Bandit(averages) #for i in range(0, 4): #print str(semiBandit.calcRegret(i)) ##print str(semiBandit.pullArm(i))
244c83ce42b8870c6a3a9456e99c077057899196
amete/MyAnalysis
/scripts/python_tools.py
1,808
3.5
4
#1/bin/bash/env python import os import glob import re def main(): print "Testing Tools" directory_with_subdir = 'LOCAL_inputs_LFV' directory_with_files = '/data/uclhc/uci/user/armstro1/SusyNt/analysis_n0232_run/scripts' list_of_subdirectories = get_list_of_subdirectories(directory_with_subdir) list_of_files = get_list_of_files(directory_with_files) print list_of_subdirectories print list_of_files list_of_files = strip_strings_to_substrings(list_of_files,'[aeiou]') print list_of_files # output list of directories in directory def get_list_of_subdirectories(directory,search_string='*/'): if not directory.endswith('/'): directory+='/' if not search_string.endswith('/'): search_string += '/' subdirectories = [(x.split('/')[-2]+'/') for x in glob.glob(directory+search_string)] if len(subdirectories)==0: print "WARNING: %s has no subdirectories"%directory return subdirectories # output list of files in directory def get_list_of_files(directory, search_string='*'): if not directory.endswith('/'): directory+='/' files = [x.split('/')[-1] for x in glob.glob(directory+search_string)] if len(files)==0: print "WARNING: %s has no files"%directory return files # strip input string list into substring list def strip_strings_to_substrings(string_list,substring): substring_list = [] for s in string_list: substring_list.append(strip_string_to_substring(s,substring)) if all(x == '' for x in substring_list): print "WARNING: %s not found in any entry"%substring return substring_list def strip_string_to_substring(string,substring): match = re.search(r'%s'%(substring),string) if match: return match.group() else: return '' if __name__ == '__main__': main()
58deb07656c17374fbe0136a45abd61ec7daa9f3
CloudLouis/algorithm_python_implementation
/golden_section_search.py
891
3.59375
4
import math def f_function(x): res = (4*x*x*x) - (60*x*x) + 25*x - 7 return res def golden_ratio(xu, xl): res = ((math.sqrt(5)-1)/2)*(xu-xl) return res def golden_section_search(xu, xl): d = golden_ratio(xu, xl) print("\niteration ", v + 1) print("d: ", d) print("xl: ", xl) print("xu: ", xu) x1 = xl + d print("x1: ", x1) x2 = xu - d print("x2: ", x2) f_xl = f_function(xl) print("f_xl: ", f_xl) f_xu = f_function(xu) print("f_xu: ", f_xu) f_x1 = f_function(x1) print("f_x1: ", f_x1) f_x2 = f_function(x2) print("f_x2 ", f_x2) if f_x1 > f_x2: new_xu = xu new_xl = x2 elif f_x2 > f_x1: new_xl = xl new_xu = x1 return new_xu, new_xl if __name__ == "__main__": xl = -10 xu = 10 for v in range(0, 5): xu, xl = golden_section_search(xu, xl)
778390bb9e7055402c0d55bd63d14c4e2086a827
soldierloko/Curso-em-Video
/Ex_44.py
1,267
3.765625
4
#Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: #A vista Dinheiro ou Cheque: 10% de Desconto #A vista no cartão: 5% de Desconto #2x No cartão: preço normal #3x ou mais no cartão: 20% de juros vProduto = float(input('Digite o valor do Produto: ')) vCondicao = int(input('Digite a condiçaõ de Pagamento:' '\n1 à vista (Dinheiro/Cheque)' '\n2 à vista no cartão' '\n3 2 x no cartão' '\n4 3 x ou mais no cartão ')) if vCondicao == 4: print('Valor total do produto {}' '\nValor do Acrescimo {} ' '\nNo parcelamento acima de 2x Acrescenta-se 20%!'.format(vProduto+(vProduto*0.2),(vProduto*0.2))) elif vCondicao == 3: print('Valor total do produto {}!'.format(vProduto)) elif vCondicao == 2: print('Valor total do produto {}' '\nValor do Desconto {}' '\nÀ Vista no Cartão 5% de Desconto!'.format(vProduto-(vProduto*0.05),(vProduto*0.05))) else: print('Valor total do produto {}' '\nValor do Desconto {}' '\nÀ Vista no Cartão 10% de Desconto!'.format(vProduto-(vProduto*0.1),(vProduto*0.1)))
0278554da3e17273fcb004165b562ae18e917175
huragok/LeetCode-Practce
/11 - Container With Most Water/cwmw.py
669
3.6875
4
#!/usr/bin/env python class Solution: # @return an integer def maxArea(self, height): n = len(height) # number of lines l = 0 r = n - 1 v_max = 0 while l < r: if height[l] > height[r]: # Right wall is the bottle neck, next left wall need not to be checked! v_max = max((v_max, height[r] * (r - l))) # update v_max r -= 1 else: v_max = max((v_max, height[l] * (r - l))) # update v_max l += 1 return v_max if __name__ == "__main__": height = [2, 5, 3, 4, 6] print(Solution().maxArea(height))
90d0de828d589a37d170011af8e1a7ea07fcb6a3
codio-content/Python_Maze-Algorithms_conditional_statements
/public/py/py-4.py
170
3.5625
4
def keyPressedEvent(keyCode): if keyCode == 'LEFT': moveLeft() elif keyCode == 'RIGHT': moveRight() else: showMessage('Left or Right was NOT pressed')
1579d662365a8987ead4dbd7ea7d219571a645d2
Abhishek-IOT/Data_Structures
/DATA_STRUCTURES/Array/SearchinBitonic.py
1,846
4.125
4
""" Search an Element in Bitonic Array.Bitonic Array is first increasing and then decreasing. So we will find the Peak ELement and then we will divide the array and have binary search for increasing and decreasing array. """ def PeakELement(arr): low=0 high=len(arr)-1 while(low<high): mid=low+(high-low)//2 if mid>0 and mid<high-1: if arr[mid]>arr[mid+1] and arr[mid]>arr[mid-1]: return mid elif arr[mid-1]>arr[mid]: high=mid-1 else: low=mid+1 elif mid==0: if arr[0]>arr[1]: return 0 else: return 1 elif mid==high-1: if arr[high-1]>arr[high-2]: return high-1 else: return high-2 def BinarSearch(arr,low,high,x): print(arr[low],arr[high]) if arr[low]<arr[high]: while(low<=high): mid=low+(high-low)//2 print(mid,"YO is is") if arr[mid]==x: return 1 elif arr[mid]>x: high=mid-1 elif arr[mid]<x: low=mid+1 else: while (low <= high): mid = low + (high - low) // 2 if arr[mid] == x: return 1 elif arr[mid] > x: low=mid+1 elif arr[mid] < x: high=mid-1 return 0 if __name__ == '__main__': arr=[1,3,8,12,4,2] yo=PeakELement(arr) print(yo) # print(arr[:yo-1]) # print(arr[yo:]) x=1 print(arr[yo:len(arr)]) first=BinarSearch(arr,0,yo-1,x) second=BinarSearch(arr,yo,len(arr)-1,x) if first==1 or second==1: print("Yes Found") else: print("Not Found")
ee58b369b6ae8dfc2781d34856ee3d2cde83c95a
kesch9/Alg_Data_Structur_Python_Homework
/lesson_2/task1.py
1,626
3.609375
4
# Написать программу, которая будет складывать, вычитать, умножать или делить два числа. # Числа и знак операции вводятся пользователем. После выполнения вычисления программа # не должна завершаться, а должна запрашивать новые данные для вычислений. Завершение # программы должно выполняться при вводе символа '0' в качестве знака операции. # Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), то программа # должна сообщать ему об ошибке и снова запрашивать знак операции. Также сообщать пользователю # о невозможности деления на ноль, если он ввел 0 в качестве делителя. while True: print("Введите первое число: a = ") a = int(input()) print("Введите первое число: b = ") b = int(input()) print("Выберите операцию '+', '-', '*', '/' или '0' - выйти") key= str(input()) if key == '0': break choices = {'+': a + b, '-': a - b, '*': a * b, '/': "Делить на ноль нельзя" if b == 0 else a / b} result = choices.get(key, 'Введен знак не из списка') print(result)
6d467b9feccb818394169ff03993f8d39140ae39
NeilWangziyu/Leetcode_py
/asteroidCollision.py
2,102
3.546875
4
class Solution: def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ if not asteroids: return [] keep = True while(keep): keep = False new_star = [] i = 0 while(i<len(asteroids)-1): print(i) if (asteroids[i] * asteroids[i+1]>0) or (asteroids[i]<0 and asteroids[i+1]>0): new_star.append(asteroids[i]) i += 1 else: keep = True if abs(asteroids[i]) > abs(asteroids[i+1]): new_star.append(asteroids[i]) elif abs(asteroids[i]) < abs(asteroids[i+1]): new_star.append(asteroids[i+1]) else: pass i += 2 if i == len(asteroids) - 1: new_star.append(asteroids[i]) asteroids = new_star print(asteroids) if len(asteroids) == 1: return asteroids return asteroids def asteroidCollision2(self, asteroids): # 利用stark来进行判断! stack = [] for a in asteroids: if a > 0: stack.append(a) else: if not stack: stack.append(a) else: while (stack): if stack[-1] > abs(a): break elif stack[-1] == abs(a): stack.pop() break elif stack[-1] < 0: stack.append(a) break else: stack.pop() if not stack: stack.append(a) break return stack s = Solution() print(s.asteroidCollision2([-2,1,-2,-2]))
2c062c5f5e7347202acfb5b1307ec72f76fd3586
brandonharris177/Python-Practice
/scratch.py
4,497
3.96875
4
from room1 import Room from player1 import Player # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons."), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""") } # Link rooms together room['outside'].n_to = room['foyer'] room['foyer'].s_to = room['outside'] room['foyer'].n_to = room['overlook'] room['foyer'].e_to = room['narrow'] room['overlook'].s_to = room['foyer'] room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] player = Player('outside') # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) while not user == "q": if user in ["n", "s", "e", "w"]: player.move_room(user) user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) print("Game Ended thank you for playing") # from player1 import Player # class Room: # def __init__(self, name, description, n_to = False, s_to = False, e_to = False, w_to = False): # self.name = name # self.description = description # self.n_to = n_to # self.s_to = s_to # self.e_to = e_to # self.w_to = w_to # def __repr__(self): # return "{self.name}, {self.description}".format(self=self) # room = { # 'outside': Room("Outside Cave Entrance", # "North of you, the cave mount beckons"), # 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty # passages run north and east."""), # 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling # into the darkness. Ahead to the north, a light flickers in # the distance, but there is no way across the chasm."""), # 'narrow': Room("Narrow Passage", """The narrow passage bends here from west # to north. The smell of gold permeates the air."""), # 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure # chamber! Sadly, it has already been completely emptied by # earlier adventurers. The only exit is to the south."""), # } # room['outside'].n_to = room['foyer'] # room['foyer'].s_to = room['outside'] # room['foyer'].n_to = room['overlook'] # room['foyer'].e_to = room['narrow'] # room['overlook'].s_to = room['foyer'] # room['narrow'].w_to = room['foyer'] # room['narrow'].n_to = room['treasure'] # room['treasure'].s_to = room['narrow'] # player = Player(room['outside']) # user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) # print(f"you find yourself in the {player.current_room.name} {player.current_room.description} ") # while not user == "q": # print(f"you find yourself in the {player.current_room.name} {player.current_room.description} ") # if user in ["n", "s", "e", "w"]: # direction = user # player.move(direction) # else: # print("incorrect input") # user = input("\n Options for travel are: \n\n [n] - north \n [s] - south \n [e] - east \n [w] - west \n [q] - quit \n\n In what direction would you like to travel: " ) # print("Game Ended thank you for playing")
3c7c3d524b665ddb94be976967dbf98c42f2edae
lmhavrin/python-crash-course
/chapter-ten/f_num_rem.py
1,027
3.890625
4
# Exercise 10-12: Favorite Number Remembered import json def favorite_number(): """Prompts for a users favorite number""" while True: f_number = input("What is your favorite number? ") prompt = print("Enter q to quit.") if f_number == "q": break else: try: f_number = int(f_number) filename = "favorite_num.json" with open(filename, "w") as f_obj: json.dump(f_number, f_obj) except ValueError: print("Please enter a number or 'q' to quit.") def read_number(): """Get stored number if available""" try: filename = "favorite_num.json" with open(filename) as f_obj: number = json.load(f_obj) print("I know your favorite number, its " + str(number) + "!") except FileNotFoundError: print("This file was not found..") favorite_number() read_number() # same code, combined into two files per exercise 10-12
d4a4e09d895996a9ac41d84e8189977fc20ce4df
nguyenbienthuy/nguyenbienthuy.github.io
/mymodule/fun_assistant.py
360
3.6875
4
import datetime def last_of_date(str_date): yy = int(str_date[0:4]) mm = int(str_date[5:7]) dd = int(str_date[8:10]) day_str = datetime.date(yy, mm, dd) - datetime.timedelta(1) last_day = day_str.strftime('%Y-%m-%d') return last_day def datetime_to_string(d): if isinstance(d, datetime.datetime): return d.__str__()
5d201b1d2f594931d70420a6c8c3e881c3c32563
democraciaconcodigos/election-2013
/scripts/geocode.py
2,213
3.65625
4
#!/usr/bin/python import csv import json import urllib2 """ Convert CSV file with format: "id","mesa_hasta","codigo_distrito","mesa_desde","codigo_postal","cant_mesas","direccion","seccion","circuito","localidad","distrito","establecimiento","dne_distrito_id","dne_seccion_id" To output CSV file: "Id","Lat","Lng" Using Google Geocoding HTTP API to get GPS coordinates. """ def convertCSV(filepath): """ does the whole conversion from full csv to id-lat-lng csv """ csvList = fileToCSVList(filepath) name = filepath if filepath.endswith('.csv'): name = name[:-4] outFile = filepath.rstrip('.csv') + '.coords.csv' with open(outFile,'wb') as csvFile: writer = csv.writer(csvFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) writer.writerow(['Id','Lat','Lng']) writer.writerows(csvList) def makeGoogleUrl(address): a = address.replace(" ","+") url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + a + '&sensor=false' return url def queryGeocode(address): """ returns (latitude,longitude) """ f = urllib2.urlopen( makeGoogleUrl(address) ) x = f.read() j = json.loads(x) lat = j['results'][0]['geometry']['location']['lat'] lng = j['results'][0]['geometry']['location']['lng'] return (lat,lng) def fileToCSVList(filepath): """ filepath: csv file returns list of tuples (id,lat,lng) """ f = open(filepath) reader = csv.reader(f) reader.next() # drops title line result = [] for line in reader: addr = lineToAddress(line) id = line[0] try: (lat,lng) = queryGeocode(addr) print (id, lat, lng) result.append((id,lat,lng)) except: print "Google error with address: " + addr f.close() return result def lineToAddress(listLine): """ Grabs a line from a csv file in the format of 80268-escuelas-segun-la-dne.csv returns address """ address = listLine[6] city = listLine[9] if city == "CAPITAL": city = "CORDOBA CAPITAL" result = address + " , " + city + " , " + "CORDOBA, ARGENTINA" return result
330c622e6fa9587bcdf1a5afb3465c836548f63d
avastjohn/Exercise01
/numberguessing.py
750
3.953125
4
# greet player # get player name # choose random number between 1 and 100 # while True: # get guess # if guess is incorrect: # give hint # else: # congratulate player from random import randint print "Greetings earthling! What's your name?" name = raw_input() print "What a pleasure to meet you, %s ! I have a game for you." % name print "I'm thinking of a number between 1 and 100. Try to guess my number." guess = int(raw_input()) number = randint (1,101) while guess != number: if guess < number: print "Your number is too low, guess again." else: print "Your number is too high, guess again." guess = int(raw_input()) print "You win! Bravo!"
0ead23fbb45cdc7098a3be65b2b37ed1b6923b6e
alvina2912/CodePython
/datetime/datetimetest.py
161
3.515625
4
import datetime import time today = datetime.date.today() print 'Today :', today tomorrow= today+ datetime.timedelta(days=1) print "Tomorrow :", tomorrow
97a176970992e0a13afe55b9c8d031bea0300962
Marcus893/algos-collection
/array/EquiLeader.py
1,633
3.84375
4
A non-empty array A consisting of N integers is given. The leader of this array is the value that occurs in more than half of the elements of A. An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value. For example, given array A such that: A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 we can find two equi leaders: 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4. 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. The goal is to count the number of equi leaders. Write a function: def solution(A) that, given a non-empty array A consisting of N integers, returns the number of equi leaders. For example, given: A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 the function should return 2, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. from collections import Counter def solution(A): res = 0 leader, count = Counter(A).most_common(1)[0] left = [] right = A leftLeaders = 0 rightLeaders = right.count(leader) for i in range(len(A)): left.append(A[i]) del right[0] if A[i] == leader: leftLeaders += 1 rightLeaders -= 1 if (leftLeaders > (i+1)/2) and (rightLeaders > ((len(A) - i - 1)/2)): res += 1 return res
9a63bc8e6109ae259b9a785537efe235b581ddda
redteamcaliber/csaw_ctf_2014
/code/crypto200-stage2.py
1,225
3.5
4
#!/usr/bin/env python from math import floor from sys import argv, exit def decode(myStr): strLen = len(myStr) max = strLen / 2 if max < 3: max = 30 for key in range(2,max): rows = list() counter = 0 i = 0 last = 0 leftover = strLen % key #num of rows with one extra character minNum = int(floor(float(strLen) / float(key))) while i < strLen: #create rows if counter < leftover: i += minNum + 1 else: i += minNum if i > strLen: rows.append(myStr[last:]) else: rows.append(myStr[last:i]) last = i counter += 1 columns = list() i = 0 while i < len(rows): #create columns j = 0 for char in rows[i]: index = j % len(rows[i]) if index == len(columns): columns.append(char) else: columns[index] += char j += 1 i += 1 longStr = "".join(columns) if longStr[:10] == "I hope you": #check if it decrypted correctly break #find the key which is in between double quotes firstQuote = longStr.find('"') + 1 return longStr[firstQuote:longStr.find('"', firstQuote)] if len(argv) < 2: print "Usage: %s CIPH_TEXT_FILE" % argv[0] exit(-1) else: with open(argv[1], 'r') as myFile: ciph = myFile.read() print(decode(ciph))
6d059568493bb2fd3f59df930e2aafc78956d6a9
amandaserex/dimensionality_reduction
/main
2,765
3.546875
4
#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np #import scipy def read_data(path): """ Read the input file and store it in data_set. DO NOT CHANGE SIGNATURE OF THIS FUNCTION Args: path: path to the dataset Returns: data_set: n_samples x n_features A list of data points, each data point is itself a list of features. """ data_set = [] y = -1 with open(path, "r") as file: for line in file: y = y+1 data_set.append([]) currentline = line.split(",") for x in currentline: data_set[y].append(float(x.rstrip())) return data_set def pca(data_set, n_components): def first(item): return item[0] """ Perform principle component analysis and dimentinality reduction. DO NOT CHANGE SIGNATURE OF THIS FUNCTION Args: data_set: n_samples x n_features The dataset, as generated in read_data. n_components: int The number of components to keep. If n_components is None, all components should be kept. Returns: components: n_components x n_features Principal axes in feature space, representing the directions of maximum variance in the data. They should be sorted by the amount of variance explained by each of the components. """ covarience_matrix = np.cov(np.transpose(np.array(data_set))) w, v = np.linalg.eig(covarience_matrix) zipped_lists = zip(w, v) z = [x for _, x in sorted(zipped_lists, key = first, reverse = True)] z = np.array(z) if(n_components == None): return z z = z[:,range(n_components)] return z def dim_reduction(data_set, components): """ perform dimensionality reduction (change of basis) using the components provided. DO NOT CHANGE SIGNATURE OF THIS FUNCTION Args: data_set: n_samples x n_features The dataset, as generated in read_data. components: n_components x n_features Principal axes in feature space, representing the directions of maximum variance in the data. They should be sorted by the amount of variance explained by each of the components. Returns: transformed: n_samples x n_components Return the transformed values. """ transformed = [] index = -1 transformed = data_set @ components return transformed # You may put code here to test your program. They will not be run during grading. data_set = read_data("pizza.txt") components = pca(data_set,2) dim = dim_reduction(data_set, components) one=[] two=[] for x in dim: one.append(x[0]) two.append(x[1]) plt.scatter(one,two) plt.show()
f4a1015421794cf5dee9a9ad0243bdb4b74486f9
white3/Python-Exercise-Code
/test22.py
2,909
3.984375
4
# coding=utf-8 # 字符串组合问题 # 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符 # 例如: # 打印排列 permutation 情况: "abc" "acb" "bac" "bca" "cab" "cba" # 23.字符串全排列问题 def swap(arr, i, j): arr[i],arr[j]=arr[j],arr[i] def permutationStr(str): result = [] def permutationDao(chars, begin): if begin==len(chars):result.append(''.join(chars)) for i in xrange(begin, len(chars)): swap(chars ,i ,begin) permutationDao(chars, begin+1) swap(chars ,begin ,i) permutationDao([x for x in str], 0) result = map(lambda x: x,set(result)) return ' '.join(result),len(result) print permutationStr('alllll') print "----------------------------------------------------------------------------------------" # 打印组合 combination 情况: "a" "b" "c" "ab" "ac" "bc" "abc" # 24.字符串全组合问题 def combinationStr(str): result = [] temp = [] def combinationStrDao(ch, pos, num): if num==0:result.append(''.join(temp));return; if pos==len(ch):return temp.append(ch[pos]) combinationStrDao(ch, pos+1, num-1) temp.pop(len(temp)-1) combinationStrDao(ch, pos+1, num) strLen = [x for x in str] for i in xrange(1,len(strLen)+1): combinationStrDao(strLen, 0, i) return result print combinationStr('abc') print "----------------------------------------------------------------------------------------" # 原始字符串是"abc",打印得到下列所有排列组合情况 # "a" "b" "c" # "ab" "bc" "ca" "ba" "cb" "ac" # "abc" "acb" "bac" "bca" "cab" "cba" # 25.字符串全排列组合问题 # 思路分析: # 每行字符个数都是递增 ,下一行的字符是建立在上一行的基础上得到的 # 即在将第一行字符串长度限定为 1,第二行为 2...., # 在第一行数据基础上{a,b,c},创建第二行数据, # 遍历字符串中所字符,并与第一行数据组合。注意每行字符串长度限制 # 1、先将原始字符串转换成字符数组 ch # 2、将原始字符串每个字符添加到 Arraylist<String> list 集合中 # 3、遍历 list 集合用每个元素 str 去查找是否存在数组 ch 中的元素,如果 ch 中的字符 c 没有被 str 找到则用 str+c 作为新集合的值 # 返回; # 4、遍历新集合重复 3 步骤 def permComStr(str): strMap = {} def getDeriveList(List): result = [] for i in List: for j in str: if i.find(j)==-1:result.append(i+j); return result strList = [x for x in str] strMap[0] = strList for i in xrange(1,len(str)): strList = getDeriveList(strList) strMap[i] = strList return strMap print permComStr('abcd') print "----------------------------------------------------------------------------------------"
08f236bec5014f763c6b58d039a42921e054b27f
vicch/leetcode
/0100-0199/0128-longest-consecutive-sequence/0128-longest-consecutive-sequence-2.py
939
3.96875
4
""" The key is a performant way to check for a certain number's existence in the list, which can be achieved with hash map. By knowing if a number exists, we can try to extend the incrementing sequence from each number in the list: - If x exists, check if x + 1 exists. - Stop when the next value doesn't exist, then the local longest sequence is found. It can be optimized by ignoring x if x - 1 exists, because each number will be iterated once, so the starting number of each local sequence will be checked at some point, and no sequence will be missed. """ class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ nums = set(nums) l = 0 for n in nums: if n - 1 in nums: continue m = n + 1 while m in nums: m += 1 l = max(l, m - n) return l
083fe636adece4b26e72fc92d2d831a0522d388b
vavronet/python-for-beginners
/functions/examples/example_3.py
110
3.5
4
def volume_of_square_prism(s, h): volume = (s * s * h) / 3 print(volume) volume_of_square_prism(6, 3)
f1189b1234b1520aa7fa3f89e9b7575cd604c2c0
ohsean93/algo
/08월/08_30/4579.py
465
3.578125
4
import sys sys.stdin = open("input.txt", "r") T = int(input()) for test_case in range(T): str_origin = input() ans = 'Exist' if '*' in str_origin: str_list = str_origin.split('*') a, b = str_list[0], str_list[-1] n = min(len(a), len(b)) if a[:n] != b[::-1][:n]: ans = 'Not exist' else: if str_origin != str_origin[::-1]: ans = 'Not exist' print('#{} {}'.format(test_case+1, ans))
f4aea76e38c99e8e647d01c893bbb566170ad32c
dwardu89/learning-python-programming
/Sorting/Sorter.py
1,244
4.34375
4
__author__ = 'edwardvella' def bubble_sort(arr): """ Performs a bubble sort algorithm. :param arr: an unsorted array :return: a sorted array """ arr_len = len(arr) swaps = True while swaps: swaps = False for i in range(0, arr_len - 1): if arr[i] > arr[i + 1]: # swap the items temp = arr[i] arr[i] = arr[i + 1] arr[i + 1] = temp swaps = True return arr def heap_sort(arr): """ Performs a heap sort algorithm :param arr: an unsorted array :return: a sorted array """ from Sorting.HeapSorting import HeapSorting heap = HeapSorting(arr) for i in range(0, len(arr))[::-1]: heap.swap(0, i) heap.heap_size -= 1 heap.max_heapify(0) return heap.A def quick_sorting(arr): """ Performs a quick sort algorithm :param arr: an unsorted array :return: a sorted array """ from Sorting.QuickSorting import QuickSort quicksort = QuickSort(arr) quicksort.quick_sort(0, len(arr) - 1) return quicksort.A array = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] target_array = [1, 2, 3, 4, 7, 8, 9, 10, 14, 16] quick_sorting(array)
bbf253b5e70d1fd850be0a81871c96464d229d0c
jay3393/ShopAlert
/display.py
650
3.546875
4
''' Module to display information on console ''' class Display: def __init__(self): self.console_log = "" def generate_console_log(self, name, price, url, store): self.console_log += "==================================================\n" self.console_log += (f'Product >> {name}\n') self.console_log += (f'Store >> {store}\n') self.console_log += (f'Price >> {price}\n') self.console_log += (f'Link >> {url}\n') self.console_log += ('==================================================\n') def print_console_log(self): print(self.console_log) self.console_log = ""
4444f1a7d70a239aac7794c8bf26e547262d40c5
Jimmycheong/Simple-Calculator
/Backup/backup1.py
8,209
3.53125
4
from tkinter import * from tkinter import ttk class MyCalculator: def __init__(self, master): master.title("Jimmy's calculator") master.geometry('240x305+200+50') master.resizable(False, False) #WIDGET CREATION self.entry = Entry(master, width = 15, font = ('Arial', 24), justify = RIGHT) self.button_0 = Button(master, text = '0', width = 13, height = 3) self.button_1 = Button(master, text = '1',width = 5, height = 3) self.button_2 = Button(master, text = '2',width = 5, height = 3) self.button_3 = Button(master, text = '3', width = 5, height = 3) self.button_4 = Button(master, text = '4', width = 5, height = 3) self.button_5 = Button(master, text = '5', width = 5, height = 3) self.button_6 = Button(master, text = '6', width = 5, height = 3) self.button_7 = Button(master, text = '7', width = 5, height = 3) self.button_8 = Button(master, text = '8', width = 5, height = 3) self.button_9 = Button(master, text = '9', width = 5, height = 3) self.button_dot = Button(master, text = '.', width = 5, height = 3) self.button_plus = Button(master, text = '+', width = 5, height = 3) self.button_minus = Button(master, text = '-', width = 5, height = 3) self.button_multiply = Button(master, text = 'x', width = 5, height = 3) self.button_divide = Button(master, text = '/', width = 5, height = 3) self.button_equal = Button(master, text = '=', width = 5, height = 3) self.button_clear = Button(master, text = 'C', width = 5, height = 3) self.button_modulus = Button(master, text = '%', width = 5, height = 3) self.button_square = Button(master, text = '^', width = 5, height = 3) #GEOMETRY MANAGEMENT self.entry.grid(row=0, column = 0, columnspan=4) self.button_0.grid(row=5, column=0, columnspan=2) self.button_1.grid(row=4, column=0, ipadx=5) self.button_2.grid(row=4, column=1, ipadx=5) self.button_3.grid(row=4, column=2, ipadx=5) self.button_4.grid(row=3, column=0, ipadx=5) self.button_5.grid(row=3, column=1, ipadx=5) self.button_6.grid(row=3, column=2, ipadx=5) self.button_7.grid(row=2, column=0, ipadx=5) self.button_8.grid(row=2, column=1, ipadx=5) self.button_9.grid(row=2, column=2, ipadx=5) self.button_dot.grid(row=5, column=2, ipadx=5) self.button_plus.grid(row=1, column=3, ipadx=5) self.button_minus.grid(row=2, column=3, ipadx=5) self.button_multiply.grid(row=3, column=3, ipadx=5) self.button_divide.grid(row=4, column=3, ipadx=5) self.button_equal.grid(row=5, column=3, ipadx=5) self.button_square.grid(row=1, column=2, ipadx=5) self.button_modulus.grid(row=1, column=1, ipadx=5) self.button_clear.grid(row=1, column=0, ipadx=5) #BIND EVENTS self.math_express=' ' self.answered = False #Check to see if final answer self.enter = False self.lastb = False #Check to see if the last button was a non-number def insert_num(integer): if self.enter == True: self.entry.delete(0,END) self.enter = False check_answer() self.entry.insert(END, integer) self.lastb = False def check_answer(): if self.answered == True: self.entry.delete(0,END) self.answered = False def decimal(existing_string): if '.' not in existing_string: self.entry.insert(END,'.') def plus_event(): #CHECK IF THE LAST BUTTON WAS NOT A NUMBER if self.lastb == True: return if self.math_express[:-1] != '+': self.math_express += self.entry.get() self.math_express += '+' print(self.math_express) self.enter = True self.lastb = True def minus_event(): #CHECK IF THE LAST BUTTON WAS NOT A NUMBER if self.lastb == True: return print ('Printing', self.math_express[:-1]) if self.math_express[:-1] != '-': self.math_express += self.entry.get() self.math_express += '-' print(self.math_express) self.enter = True self.lastb = True def multiply_event(): #CHECK IF THE LAST BUTTON WAS NOT A NUMBER if self.lastb == True: return print ('Printing', self.math_express[:-1]) if self.math_express[:-1] != '-': self.math_express += self.entry.get() self.math_express += '*' print(self.math_express) self.enter = True self.lastb = True def divide_event(): #CHECK IF THE LAST BUTTON WAS NOT A NUMBER if self.lastb == True: return print ('Printing', self.math_express[:-1]) if self.math_express[:-1] != '-': self.math_express += self.entry.get() self.math_express += '.0/' print(self.math_express) self.enter = True self.lastb = True def square_event(): #CHECK IF THE LAST BUTTON WAS NOT A NUMBER if self.lastb == True: return print ('Printing', self.math_express[:-1]) if self.math_express[:-1] != '-': self.math_express += self.entry.get() self.math_express += '**' print(self.math_express) self.enter = True self.lastb = True def mod_event(): #CHECK IF THE LAST BUTTON WAS NOT A NUMBER if self.lastb == True: return if '%' not in self.math_express: self.math_express += self.entry.get() self.math_express += '%' print(self.math_express) self.enter = True self.lastb = True def evaluate(): self.math_express += self.entry.get() print ('Expression:', self.math_express) if self.math_express[-1] not in '+-': print ('Answer :',eval(self.math_express)) answer = eval(self.math_express)# self.entry.delete(0,END) if str(answer)[-2:] == '.0': answer = str(answer)[:-2] self.entry.insert(END,answer) self.math_express = " " self.answered = True #MOUSE event configuration self.button_0.config(command = lambda: insert_num(0)) self.button_1 .config(command = lambda: insert_num(1)) self.button_2 .config(command = lambda: insert_num(2)) self.button_3.config(command = lambda: insert_num(3)) self.button_4.config(command = lambda: insert_num(4)) self.button_5.config(command = lambda: insert_num(5)) self.button_6.config(command = lambda: insert_num(6)) self.button_7.config(command = lambda: insert_num(7)) self.button_8.config(command = lambda: insert_num(8)) self.button_9.config(command = lambda: insert_num(9)) self.button_dot.config(command = lambda: decimal(self.entry.get())) self.button_clear.config(command = lambda: self.entry.delete(0,END)) self.button_equal.config(command = lambda: evaluate()) self.button_plus.config(command = lambda: plus_event()) self.button_minus.config(command = lambda: minus_event()) self.button_multiply.config(command = lambda: multiply_event()) self.button_divide.config(command = lambda: divide_event()) self.button_modulus.config(command = lambda: mod_event()) self.button_square.config(command = lambda: square_event()) #Keyboard bind event configuration def keyeval(event): evaluate() def keyclear(event): self.entry.delete(0,END) def keydel(event): self.entry.delete(len(self.entry.get())-1,END) def keyplus(event): plus_event() def keyminus(event): minus_event() def keymultiply(event): multiply_event() def keydivide(event): divide_event() def keymod(event): mod_event() def keysquare(event): square_event() master.bind('<Return>', keyeval) master.bind('c', keyclear) master.bind('<BackSpace>', keydel) master.bind('+', keyplus) master.bind('-', keyminus) master.bind('*', keymultiply) master.bind('/', keydivide) master.bind('%', keymod) master.bind('^', keysquare) master.bind('1', lambda e: insert_num(1)) master.bind('2', lambda e: insert_num(2)) master.bind('3', lambda e: insert_num(3)) master.bind('4', lambda e: insert_num(4)) master.bind('5', lambda e: insert_num(5)) master.bind('6', lambda e: insert_num(6)) master.bind('7', lambda e: insert_num(7)) master.bind('8', lambda e: insert_num(8)) master.bind('9', lambda e: insert_num(9)) master.bind('0', lambda e: insert_num(0)) root = Tk() my_calculator = MyCalculator(root) root.mainloop()
7e12512fc0bd2d604c10bef61f67e6042b1ed405
guzelsafiullina/final
/angle.py
1,172
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: class angle: def __init__(self, degrees = 0, minutes = 0, direction = 'W'): self.degrees = degrees self.minutes = minutes self.direction = direction def __str__(self): return str(self.degrees) + u'\N{DEGREE SIGN}' + str(self.minutes) + "' " + self.direction def __repr__(self): return '0' + u'\N{DEGREE SIGN}' + '0.0' + "' " + 'W' def print_angle(self): print() degrees = int(input()) minutes = float(input()) direction = str(input()) if (direction == 'E') or (direction == 'W'): if (degrees>180) or (degrees<0): print("Incorrect input") else: self.__init__(degrees, minutes, direction) print(self) elif (direction == 'S') or (direction == 'N'): if (degrees>90) or (degrees<0): print("Incorrect input") else: self.__init__(degrees, minutes, direction) print(self) else: print("Incorrect direction")
fc880227af27e3bc85318559ddbd2cc7deaf13e4
fujunguo/learning_python
/The_last_week_in_Dec_2017/func_partial.py
555
3.953125
4
# 1.对数字字符串进行进制转换 import functools int2 = functools.partial(int, base=2) print(int2("1000000")) print(int2("1000000", base=10)) print(int2("1010101")) # 创建偏函数时,实际上可以接收函数对象、*args和**kw这3个参数,当传入: # int2 = functools.partial(int, base=2) # 实际上固定了int()函数的关键字参数base,也就是: # int2('10010') # 相当于: # kw = { 'base': 2 } # int('10010', **kw) print() # 2.求一组数字的最大值 max2 = functools.partial(max, 10) print(max2(5, 6, 7))
54bf2f7b240e5f0d1bc5910bf2c8658913bb9d18
Moziofmoon/algorithm-python
/Week_07/208-tire-tree.py
1,190
4.09375
4
# -*- coding: utf-8 -*- # @Time : 2020/6/1 9:54 # @Author : edgar # @FileName: 208-tire-tree.py class Trie: def __init__(self): """ Initialize your data structure here. """ self.dic = {} def insert(self, word: str) -> None: """ Inserts a word into the trie. """ a = self.dic for i in word: if not i in a: a[i] = {} a = a[i] a["end"] = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ a = self.dic for i in word: if not i in a: return False a = a[i] if "end" in a: return True else: return False def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ a = self.dic for i in prefix: if not i in a: return False a = a[i] return True if __name__ == '__main__': if 15 not in range(0,10): print(15) else: print(5)
31065a668e97d8d0dae7fe68d27bffbc7559814c
DanieleMagalhaes/Exercicios-Python
/Mundo3/Listas/listaComposta_Peso.py
950
3.515625
4
cadastro = [] dado = [] maior = menor = 0 print('='*60) while True: dado.append(str(input('Nome: '))) dado.append(int(input('Peso: '))) if len(cadastro) == 0: maior = menor = dado[1] else: if dado[1] > maior: maior = dado[1] if dado[1] < menor: menor = dado[1] cadastro.append(dado[:]) dado.clear() resp = str(input('Deseja continuar? [S/N]: ')).strip().upper()[0] while resp not in 'SN': resp = str(input('Opção inválida! Deseja continuar? [S/N]: ')).strip().upper()[0] print('-'*40) if resp in 'N': break print('='*60) print(f'Foram cadastradas {len(cadastro)} pessoas.') print(f'O mais leve tem {menor}kg. Peso de: ', end='') for c in cadastro: if c[1] == menor: print(f'[{c[0]}]', end=' ') print(f'\nO mais pesado tem {maior}kg. Peso de: ' , end='') for c in cadastro: if c[1] == maior: print(f'[{c[0]}]', end=' ')
ca02c7fd9e2bce5f22a9088b892ae2543f1ba999
LittleMinWu/MLprojects
/week4/funcfile.py
974
3.78125
4
import matplotlib.pyplot as plt import sympy as sp #plot the data from matplotlib.ticker import MultipleLocator """when y’s value equals 1 color is “red” ,else “green”, and set the x axis as ‘x_1’ , set the y axis as ‘x_2’ , because on the plot the x-axis is the value of parameter ‘x1 ’, the y-axis is the value of the second parameter ‘x1’ , and the parameter of ‘str’ is the title of the plot""" def scattersth(x1, x2, y, str): positivey_x1=[] positivey_x2 = [] negaivey_x1=[] negaivey_x2 = [] for i in range(len(x1)): if y[i] == 1: positivey_x1.append(x1[i]) positivey_x2.append(x2[i]) else: negaivey_x1.append(x1[i]) negaivey_x2.append(x2[i]) plt.scatter(positivey_x1,positivey_x2, label='y=1',color='red', s=5) plt.scatter(negaivey_x1, negaivey_x2, label='y=-1',color='green', s=5) plt.xlabel('x1') plt.ylabel('x2') plt.title(str)
aa8801a0f2c6b87b406fb4420feca4497a5717ae
svanan77/udacity-ud120-machine-learning
/ud120-projects/datasets_questions/explore_enron_data.py
2,434
3.578125
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ import pickle counter = 0 enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) for name in enron_data.keys(): if (enron_data[name]["poi"] == 1): #counter += 1 pass temp= enron_data[name]['salary'] try: val = int(temp) #counter +=1 except ValueError: pass if (enron_data[name]['email_address'] != 'NaN'): #counter += 1 pass if (enron_data[name]['total_payments'] == 'NaN'): #counter += 1 pass if ((enron_data[name]["poi"] == 1) and (enron_data[name]['total_payments'] == 'NaN')): counter += 1 pass tokens = name.split() if (len(tokens)==2): lname = tokens[0] fname = tokens[1] if (fname=='JAMES' and lname =='PRENTICE'): #print "James Prentice's total value of stock is $", enron_data[name]['total_stock_value'] pass if (fname=='WESLEY' and lname =='COLWELL'): #print "The number of Email messages from Wesley Colwell to persons of interest is", enron_data[name]['from_this_person_to_poi'] pass if (lname=='LAY' or lname=='SKILLING' or lname=='FASTOW'): #print name,enron_data[name]['total_payments'] pass if (len(tokens)==3): lname = tokens[0] fname = tokens[1] mname = tokens[2] if (fname=='JEFFREY' and mname== 'K' and lname =='SKILLING'): #print "Jeffrey K Skilling's total exercised stock options is $", enron_data[name]['exercised_stock_options'] pass if (lname=='LAY' or lname=='SKILLING' or lname=='FASTOW'): #print name,enron_data[name]['total_payments'] pass # print counter print len(enron_data) print float(counter+10)/float(len(enron_data)+10) #counter = 0 for line in file("../final_project/poi_names.txt"): tokens = line.split() if (len(tokens)>1): #counter += 1 dir_ = tokens[0] fname_ = tokens[2] lname_ = tokens[1] #print "dir_:",dir_, ",name_:",fname_,lname_[:-1] #print counter
3d8ac32b9c17cb98ae409adc8bb706357897ad83
AndrewDPena/Monopoly
/Deck.py
1,752
3.765625
4
import random import unittest class Deck(object): class Card(object): def __init__(self, name, value, effect): self.name = name self.value = value self.effect = effect def __str__(self): return str(self.name) def __init__(self, file=None): self.deck = [] self.discard = [] if file: my_file = open(file) for line in my_file: data = line.split(":") self.push(data[0], data[1], data[2]) my_file.close() self.shuffle() def __contains__(self, item): for card in self.deck: if card.name == item: return True return False def push(self, name, value, effect): self.deck.append(self.Card(name, value, effect)) def shuffle(self, pile=None): shuffled = [] if not pile: pile = self.deck while pile: shuffled.append(pile.pop(random.randint(0, len(pile)-1))) self.deck = shuffled def draw(self): drawn = self.deck.pop(0) self.discard.append(drawn) if not self.deck: self.shuffle(self.discard) self.discard.clear() return drawn class DeckTest(unittest.TestCase): def test_build(self): test_deck = Deck("test_deck.txt") self.assertTrue("card one" in test_deck) self.assertFalse("" in test_deck) def test_shuffle(self): test_deck = Deck("test_deck.txt") test_deck.shuffle() self.assertTrue("card three" in test_deck) def test_draw(self): test_deck = Deck("test_deck.txt") self.assertEqual(str(test_deck.draw()), "card one")
9f333128debc4cc7d52f17e9fb30946fdfa277be
waleOkare/PythonGames
/PY GAME - TICTAETOE.py
4,304
3.796875
4
from IPython.display import clear_output def display_board(board): clear_output() print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') test_board =[' '] * 10 display_board(test_board) def player_input(): marker = " " while marker != "X" and marker != "O": marker = str(input('Player 1:- Choose "X" or "O" ?')).upper() Player1 = marker Player2 = marker if Player1 == 'X': Player2 = 'O' elif Player1 == 'O': Player2 = 'X' return ('Player1 picks-> '+ Player1, Player2 + ' <- Player2') def place_marker(board, marker, postion): board[postion] = marker def win_check(board, mark): if mark == board[1] and mark == board[2] and mark == board[3]: return True elif mark == board[1] and mark ==board[5] and mark == board[9]: return True elif mark == board[1] and mark ==board[4] and mark== board[7]: return True elif mark == board[2] and mark== board[5] and mark == board[8]: return True elif mark == board[3]and mark == board[6] and mark == board[9]: return True elif mark == board[3]and mark == board[5] and mark== board[7]: return True elif mark == board[4] and mark== board[5] and mark == board[6]: return True elif mark == board[7]and mark == board[8] and mark == board[9]: return True return False import random def choose_first(): if random.randint(0, 1) == 0: return 'Player 2' else: return 'Player 1' choose_first() def space_check(board, position): if board[position] == ' ': return True else: return False # In[9]: def full_board_check(board): for i in range (1, 10): if space_check(board,i): return False return True def player_choice(board): x = 0 while x not in range(1,10): x = int(input('Choose your next position (1-9) ? ')) if space_check(board,x): return x return False def replay(): PlayAgain = str(input('Do you want to Play Again? "(y/n)" ')).lower().startwith('y') return PlayAgain == 'y' print('WELCOME TO A GAME OF TIC TAE TOE') while True: mainBoard = [' ']*10 Player1, Player2 = player_input() WhoseTurn = choose_first() print(WhoseTurn + ' will go first') play_game = input('Ready to play? y or n?') if play_game == 'y': game_on = True else: game_on = False while game_on: if WhoseTurn == 'Player 1': display_board(mainBoard) position = player_choice(mainBoard) place_marker(mainBoard,Player1, position) if win_check(mainBoard, Player1): display_board(mainBoard) print('PLAYER 1 WON!!!!') game_on = False else: if full_board_check(mainBoard): display_board(mainBoard) print('TIE GAME!') game_on = False else: WhoseTurn = 'Player 2' display_board(mainBoard) position = player_choice(mainBoard) place_marker(mainBoard,Player2, position) if win_check(mainBoard, Player2): display_board(mainBoard) print('PLAYER 2 WON!!!!') game_on = False else: if full_board_check(mainBoard): display_board(mainBoard) print('TIE GAME!') game_on = False else: WhoseTurn = 'Player 1' if not replay(): break # In[ ]:
b951115b13d536bda7871244df0ae79c07846cfc
Abdur15/100-Days-of-Code
/Day_003/Challenge 9 - BMI _2.0.py
1,432
4.8125
5
## BMI Calculator 2.0 # Instructions # Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height. # It should tell them the interpretation of their BMI based on the BMI value. # - Under 18.5 they are underweight #- Over 18.5 but below 25 they have a normal weight # - Over 25 but below 30 they are slightly overweight # - Over 30 but below 35 they are obese # - Above 35 they are clinically obese. # The BMI is calculated by dividing a person's weight (in kg) by the square of their height (in m): #Example Input #weight = 85 #height = 1.75 # Example Output #85 ÷ (1.75 x 1.75) = 27.755102040816325 #Your BMI is 28, you are slightly overweight. #"Your BMI is 18, you are underweight." #"Your BMI is 22, you have a normal weight." #"Your BMI is 28, you are slightly overweight." #"Your BMI is 33, you are obese." #"Your BMI is 40, you are clinically obese." weight = int(input("Enter your weight")) height = float(input("Enter your your height in m")) formula = weight/(height**2) bmi = round(formula) if(bmi<=18.5): print(f"Your BMI is {bmi}, you are underweight.") elif(bmi>18.5 and bmi<=25): print(f"Your BMI is {bmi}, you have a normal weight.") elif(bmi>25 and bmi<30): print(f"Your BMI is {bmi}, you are slightly overweight.") elif(bmi>30 and bmi<35): print(f"Your BMI is {bmi}, you are obese.") else: print(f"Your BMI is {bmi}, you are clinically obese")
0a823e363af62a6a44546cae00915645a7d1a9a8
vosergey/python3_btree_traversal
/LevelorderTraversal.py
1,028
3.828125
4
import collections # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def iterativelyLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] queue = collections.deque() queue.append(root) level = 0 result = [] while queue: result.append([node.val for node in queue]) queue_len = len(queue) i = 0 while i < queue_len: current = queue.popleft() if current.left: queue.append(current.left) if current.right: queue.append(current.right) i += 1 level += 1 return result
b33abc5f4ebc1fd874f624343beeb28b5e1fb3d4
leeo1116/PyCharm
/Algorithms/leetcode/051_N_queens.py
684
3.6875
4
__author__ = 'Liang Li' class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ queen_stack, solution = [[(0, i) for i in range(n)]], [] while queen_stack: board = queen_stack.pop() row = len(board) if row == n: solution.append([''.join('Q' if i == c else '.' for i in range(n)) for r, c in board]) for col in range(n): if all(col != c and abs(row-r) != abs(col-c) for r, c in board): queen_stack.append(board+[(row, col)]) return len(solution) s = Solution() print(s.solveNQueens(3))
a416f19e358afa1633dc643a2b4bacf27cb38fb7
jtlai0921/MP31909_Example
/MP31909_Example/範例/RPi/EX2_8.py
974
3.71875
4
# Homework 2-8 class property(): def __init__(self, name, value): self.__name = name self.__value = value def getName(self): return self.__name def getValue(self): return self.__value class house(property): def __init__(self, name, value, ownerName, address): super().__init__(name, value) self.ownerName = ownerName self.address = address class deposit(property): def __init__(self, name, value, account): super().__init__(name, value) self.account = account class stock(property): def __init__(self, name, amount, price): value = amount*price super().__init__(name, value) self.amount = amount tc = house('apartment', 5600000, 'tclin','taichung') money = deposit('money', 100000, 'taiwanBank') stock = stock('tpowerStock', 5, 20000) total = [tc, money, stock] for i in total: print("Property name:{0}, value:{1}".format(i.getName(), i.getValue()))
afe37cabf0d7d0de27d5fb12d106e32caa4d64e0
zanuarts/100DaysCodeChallenge
/Day003/Day003.py
178
3.78125
4
# We need a function that can transform a number into a string. # What ways of achieving this do you know? def number_to_string(num): return str(num) number_to_string(67)
81b6f7178074965575e96d8c9c0fe8469c21f8aa
eovallea3786/While
/menor_elemento.py
383
3.71875
4
def menor_elemento(vector): ''' Funcion que define cual es el mayor elemento del vector list of num -> num >>> menor_elemento([1,2,3]) 1 >>> menor_elemento([4,5,6]) 4 :param vector: Vector a calcular el mayor elemento :return: El elemento mayor del vector ''' menor = min(vector) for i in range(len(vector)): return menor
58be6f12fa5d8b522649b3b703455f356601b895
MJ-K-18/Python
/python 2일차 실습 답/training2_2.py
877
3.84375
4
''' training2_2.py Python 2일차 실습 #2 2. 10개의 정수를 입력받아 양수 개수, 음수 개수, 양수일 때 짝수 개수, 홀수 개수 출력 되는 프로그램 ''' positive = 0 negative = 0 even = 0 odd = 0 error = 0 for i in range( 1, 11, 1 ): number = int( input( '{0:3} 번째 정수 입력 : '.format( i ) ) ) if number != 0: if number > 0: positive += 1 remain = number % 2 if remain == 0: even += 1 else: odd += 1 else: negative += 1 else: error += 1 print( '\npositive count : {0:3}'.format( positive ) ) print( '\teven count : {0:3}\n\todd count : {1:3}'.format( even, odd ) ) print( 'negative count : {0:3}'.format( negative ) ) print( '\nerror count : {0:3}\n'.format( error ) )
c97327498686b4fc8025c73d5542e3ad8ae5ccb5
filipo18/-uwcisak-filip-unit3
/Inventoryproject/userpractise.py
587
3.71875
4
# Create bank info customer1 = {'FirstName': 'Filip', 'LastName': 'Keitaro', 'AccNumber': '00001', 'PinNumber': '1119', 'Balance': 5, 'Age': 18, 'Contact': 'filip@keitaro.jp'} def depoist(customerdict, amount): # This function deposits amount in the customer dict customerdict['Balance'] += amount print(f'New balance is {customerdict["Balance"]}') def checkbalance(customerdict): print(f'Balance is {customerdict["Balance"]}') def withdraw(customerdict, amount): customerdict['Balance'] -= amount print(f'New balance is {customerdict["Balance"]}')
b038d4390e7a90f23680ca6af745f7bd74dcd310
georgeteo/Coding_Interview_Practice
/chapter_4/4.4.py
1,178
4.1875
4
''' CCC 4.4: Design an algorithm that turns a binary tree into a linked list by level ''' from binary_tree import binary_tree def make_linked_list(bt): ''' BFS: Time Complexity: O(V + E) Space Complexity: O(V) traversal_queue is a queue represented by a list linked_lists is a list of linked lists represented by a list of lists ''' traversal_queue = [] linked_lists = [] linked_lists.append([bt.id]) traversal_queue.append((bt.left_child, True)) traversal_queue.append((bt.right_child, False)) for node in traversal_queue: if node[0] is None: continue if node[1] is True: traversal_queue.append((node[0].left_child, True)) linked_lists.append([node[0].id]) traversal_queue.append((node[0].right_child, False)) else: traversal_queue.append((node[0].left_child, False)) linked_lists[-1].append(node[0].id) traversal_queue.append((node[0].right_child, False)) return linked_lists if __name__ == "__main__": bt = binary_tree(0, 0, binary_tree(1,1), binary_tree(2,1)) ll = make_linked_list(bt) print ll
a9db289ca835732ebb735d15d2371a87009e948f
sansbacon/pangadfs
/pangadfs/misc.py
2,817
3.828125
4
# pangadfs/pangadfs/misc.py # -*- coding: utf-8 -*- # Copyright (C) 2020 Eric Truett # Licensed under the MIT License from typing import Dict, Iterable, Tuple import numpy as np def diversity(population: np.ndarray) -> np.ndarray: """Calculates diversity of lineups Args: population (np.ndarray): the population Returns: np.ndarray: is square, shape len(population) x len(population) """ uniques = np.unique(population) a = (population[..., None] == uniques).sum(1) return np.einsum('ij,kj->ik', a, a) def exposure(population: np.ndarray = None) -> Dict[int, int]: """Returns dict of index: count of individuals Args: population (np.ndarray): the population Returns: Dict[int, int]: key is index, value is count of lineup Examples: >>> fittest_population = population[np.where(fitness > np.percentile(fitness, 97))] >>> exposure = population_exposure(fittest_population) >>> top_exposure = np.argpartition(np.array(list(exposure.values())), -10)[-10:] >>> print([round(i, 3) for i in sorted(top_exposure / len(fittest_population), reverse=True)]) """ flat = population.flatten return dict(zip(flat, np.bincount(flat)[flat])) def multidimensional_shifting(elements: Iterable, num_samples: int, sample_size: int, probs: Iterable) -> np.ndarray: """Based on https://medium.com/ibm-watson/incredibly-fast-random-sampling-in-python-baf154bd836a Args: elements (iterable): iterable to sample from, typically a dataframe index num_samples (int): the number of rows (e.g. initial population size) sample_size (int): the number of columns (e.g. team size) probs (iterable): is same size as elements Returns: ndarray: of shape (num_samples, sample_size) """ replicated_probabilities = np.tile(probs, (num_samples, 1)) random_shifts = np.random.random(replicated_probabilities.shape) random_shifts /= random_shifts.sum(axis=1)[:, np.newaxis] shifted_probabilities = random_shifts - replicated_probabilities samples = np.argpartition(shifted_probabilities, sample_size, axis=1)[:, :sample_size] return elements.to_numpy()[samples] def parents(population: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Evenly splits population Args: population (np.ndarray): the population to crossover. Shape is n_individuals x n_chromosomes. Returns: Tuple[np.ndarray, np.ndarray]: population split into two equal-size arrays """ fathers, mothers = np.array_split(population, 2) size = min(len(fathers), len(mothers)) return fathers[:size], mothers[:size]
a52eb026b29d7e42d99d3303c65253230938eecd
ZhongruiNing/ProjectEuler
/Code of ProjectEuler/problem25.py
420
4.0625
4
def Fibonacci(num): if num == 1 or num == 2: return 1 else: Fibo.append(Fibo[-1] + Fibo[-2]) return Fibo[-1] def length(num): return len(str(num)) Fibo = [1, 1] i = 1 threshold = 1000 while True: if length(Fibonacci(i)) >= threshold: print(str(i) + " is the first term to contain " + str(threshold) + " digits") break else: i += 1
5093793c8b9b00b9aa73e2cf1857f3dd064d1c04
hanfang302/py-
/python基础/复习.py/列表乘方.py
185
4
4
#number = [] #for value in range(1,11): #num = value**2 #number.append(num) #print(number) number = [] for value in range(1,11): number.append(value**2) print(number)
f3592702be4876e54dc1604914ece01d38ac3854
easternpillar/AlgorithmTraining
/SW Expert Academy/D3/보충학습과 평균.py
402
3.828125
4
# Problem: # When you convert a score less than 40 to 40, print the average score. # My Solution: answer = [] for i in range(int(input())): score = list(map(int, input().split())) cnt = 0 for j in range(len(score)): if score[j] < 40: score[j] = 40 answer.append(sum(score) // len(score)) for i in range(len(answer)): print("#{} {}".format(i + 1, answer[i]))
4ecb65bfbce961768be17c44e73859d3329e4e4e
k-schmidt/Project_Euler
/Python/P016.py
345
3.921875
4
def compute_exponent_base_two(exp): return 2 ** exp def int_to_string(integer): return str(integer) def main(exp): exponent = compute_exponent_base_two(exp) string_int = int_to_string(exponent) result = 0 for i in string_int: result += int(i) return result if __name__ == "__main__": print(main(1000))
a1734b0cc09efac3275c594b3a04af1e4bd76619
micriver/leetcode-solutions
/1480-RunningSum.py
1,444
4.25
4
""" Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. at first index, add the lone index, at second index, add the last two indexs, at the third index, add the first 3 indexes Example 2: Input: nums = [1,1,1,1,1] Output: [1,2,3,4,5] Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. Example 3: Input: nums = [3,1,2,10,1] Output: [3,4,6,16,17] Constraints: length of the array will always be at least 1 but less than or equal to 1000 1 <= nums.length <= 1000 note: the numbers in the array will never be below the intmin or higher than intmax -10^6 <= nums[i] <= 10^6 PROTOTYPE: var runningSum = function(nums) { }; Questions to ask after looking at the example input: Can the array have negative numbers inside? """ nums = [3, 1, 2, 10, 1] # Output: [3, 4, 6, 16, 17] # https://docs.python.org/3/library/typing.html # https://medium.com/analytics-vidhya/type-annotations-in-python-3-8-3b401384403d from typing import List def runningSum( nums: List[int], ) -> List[int]: sum = 0 # number to add to new list lst = [] # empty list to return for i in range(len(nums)): sum += nums[i] lst.append(sum) return lst print(runningSum(nums))
ac50a7d9324ae10a1294e21492687f3e63493569
hhllbao93/Interactive-program-in-pyhon
/Guess the number.py
1,965
4.125
4
# input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math num_range = 100 n = 7 # helper function to start and restart the game def new_game(): global num_range, n, secret_number if num_range == 100: n = 7 elif num_range == 1000: n = 10 secret_number = random.randrange(0, num_range) if n > 0: print "New game. Range is from 0 to ", num_range print "Number of remaining guesses is ", n print " " # define event handlers for control panel def range100(): global secret_number, n, num_range n = 7 num_range = 100 secret_number = random.randrange(0, 100) new_game() def range1000(): global secret_number, n, num_range n = 10 num_range = 1000 secret_number = random.randrange(0, 1000) new_game() def get_input(inp): # main game logic goes here global guess,n guess = int(inp) n = n - 1 print "Your guess was", guess print "Number of remaining guesses is ", n if n > 0: if guess == secret_number: print "Correct!!" print " " new_game() elif guess < secret_number: print "Higher!!" print " " elif guess > secret_number: print "Lower!!" print " " else: print "Out of guesses! The number was ", secret_number print " " new_game() # create frame f = simplegui.create_frame("Guess number",300,300) # register event handlers for control elements and start frame f.add_button("Range is [0,100)", range100, 200) f.add_button("Range is [0,1000)", range1000, 200) f.add_input("Enter a guess", get_input, 100) new_game() f.start # always remember to check your completed program against the grading rubric
c20acc9dafa582630a32127a373af08a383a4512
CAgAG/Arithmetic_PY
/基本数学运算/实现异或.py
362
3.796875
4
def XOR(x, y): res = 0 i = 32 - 1 while i >= 0: # 获取当前bit值 b1 = (x & (1 << i)) > 0 b2 = (y & (1 << i)) > 0 if b1 == b2: xoredBit = 0 else: xoredBit = 1 res <<= 1 res |= xoredBit i -= 1 return res if __name__ == '__main__': print(XOR(3, 5))
a2b318691ae6db644a4f36fcc3e6652fe1734027
sankeerth/Practice
/leet_code/is_symmetric.py
2,322
3.671875
4
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): return 'TreeNode({})'.format(self.val) def deserialize(string): if string == '{}': return None nodes = [None if val == 'null' else TreeNode(int(val)) for val in string.strip('[]{}').split(',')] kids = nodes[::-1] root = kids.pop() for node in nodes: if node: if kids: node.left = kids.pop() if kids: node.right = kids.pop() return root class Solution(object): def isPalindrome(self, nodes, count): n = count - 1 for i in range(int(count / 2)): if nodes[i] != nodes[n - i]: return False return True def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root is None: return True if root.left is None and root.right is None: return True if root.left is None or root.right is None: return False queue = list() nodes = list() queue.append(root) queue.append(None) count = 0 while queue: current = queue.pop(0); if current is None: print(queue) print(count) if queue: queue.append(None) if count % 2 != 0: return False if not self.isPalindrome(nodes, count): return False del nodes[:] count = 0 else: if current.left is not None: queue.append(current.left) nodes.append(current.left.val) count += 1 else: nodes.append(None) if current.right is not None: queue.append(current.right) nodes.append(current.right.val) count += 1 else: nodes.append(None) return True tree = "[1,2,2,null,3,3]" tree = "[1,2,2,null,3,null,3]" r = deserialize('[1,2,2,null,3,null,3]') sol = Solution() print(sol.isSymmetric(r))
4bdb02fa6d55d67938158812efee89fa7c24c875
SeiteAlexMH/pyhton-stuff
/randomtree.py
823
4.1875
4
#randomtree.py #Alexandre Seite import turtle as t import random def drawTree(levels, len, angle,shrink): # draw the tree starting basic value then randomizes from them if levels > 0: if levels<=3: t.color(0,1,0) else: t.color("brown") shrink=random.uniform(0.7,0.9) angle=random.randint(10,20) t.forward(len) t.left(angle) drawTree(levels-1, shrink * len, angle, shrink) t.right(2 * angle) drawTree(levels-1, shrink * len, angle, shrink) t.pu() t.left(angle) t.backward(len) t.pd() # main program t.tracer(False) t.up() t.left(90) t.backward(250) t.down() drawTree(10, 60, 13,.09) t.update() t.exitonclick()
1db036fc5e416362efcbb9214d3a443540330bd4
CJRicciardi/cs-module-project-hash-tables
/applications/histo/trial.py
135
3.515625
4
# words = ['fuck', 'this', 'couch'] # for i in range(len(words)): # print(f"{words[i]:{10}}: #####") x = '#' y = '##' print(x+y)
da99769c39db7af9d98e5aa9368979c62373c45f
j-hmd/daily-python
/Object-Oriented-Python/magic_call.py
632
3.953125
4
# Calling an object as if it were a funciton class Book: def __init__(self, title, author, price): super().__init__() self.title = title self.author = author self.price = price def __str__(self): return f"{self.title} by {self.author}, costs {self.price}" def __call__(self, title, author, price): self.title = title self.author = author self.price = price b1 = Book("A mao e a luva", "Machado de Assis", 29.99) print(b1) # Here we can call the object, as if it were a funciton to modify its attributes b1("Dom Casmurro", "Machado de Assis", 25.50) print(b1)
346d119edb229681dd900bd8005df913ac4327ff
andprogrammer/crackingTheCodingInterview
/python/chapter3/4/solution.py
799
4.0625
4
class MyQueue(object): def __init__(self): self.stack = [] def push(self, elem): self.stack.append(elem) def pop(self): if self.is_empty(): raise Exception('Queue is empty') del self.stack[-1] def top(self): if self.is_empty(): raise Exception('Queue is empty') return self.stack[-1] def is_empty(self): return not self.stack def print_queue(self): for i in reversed(self.stack): print('[', i, ']') if __name__ == '__main__': queue = MyQueue() queue.push(5) queue.push(4) queue.push(36) queue.push(59) queue.push(7) queue.print_queue() print('top elem=', queue.top()) queue.pop() queue.pop() print('top elem=', queue.top())
f0b07dfa02cfd9b71bf3539dc89ea179bc559474
decimozack/coding_practices
/leetcode/python/regular_expression_match_recursion.py
1,171
4.09375
4
# https://leetcode.com/problems/regular-expression-matching/ class Solution: def isMatch(self, s: str, p: str) -> bool: # if pattern is empty but str is not, the str does not match the pattern if not p: return not s # first we check if str is empty. if it is empty and there is a pattern, # the char does not match char_match = bool(s) and p[0] in (s[0], '.') # we check if the next character is a * if it is, we will skip the curr char and the * char and see # if the following pattern matches the curr char. if they do, it is possible the (curr_char *) pattern will # have zero matches. Or if the next pattern does not match the curr char, we will see if the next char matches the # (curr_char *) if len(p) > 1 and p[1] == '*': return (self.isMatch(s, p[2:]) or (char_match and self.isMatch(s[1:], p))) else: # this is for normal scenario without *. # For the normal scenario we just compare pattern # and str char by char return char_match and self.isMatch(s[1:], p[1:])
779d7c501cb77ec677544e80cc5fb376313f6838
ThenuVijay/workout1-python
/neon.py
244
4
4
# neon number---->9^2=81-->8+1=9 num=int(input("Enter num: ")) sqr=num**2 total=0 #print(sqr) while sqr>0: total=total+sqr%10 sqr=sqr//10 #print(total) if num==total: print("Neon number") else: print("Non Neon Number")
185b57b73ef074c85d6bc1e51c3d56d9da50a17b
Srikumar-R/Sri
/55pl.py
84
3.703125
4
a,b=input().split() if a.lower()==b.lower(): print("yes") else: print("no")
6eb79b031b500f4f8b4e377b9df3448f400b91a9
romanpitak-classroom/all-possible-products-of-a-list-of-primes-lucyb1
/hw_1.py
684
3.984375
4
# 1st try: cycle inside a cycle ... inside definition of course my_input_numbers_1 = [2, 3, 5, 11] print my_input_numbers_1 def products(primes): my_output_1 = [] for i in range(len(primes)): x = primes[i] if x not in my_output_1: my_output_1.append(x) self_const = 1 else: self_const = 0 for j in range(len(my_output_1) - self_const): if not x*my_output_1[j] in my_output_1: my_output_1.append(x*my_output_1[j]) return sorted(my_output_1) print products(my_input_numbers_1) my_input_numbers_1 = [1, 2, 4, 8] print my_input_numbers_1 print products(my_input_numbers_1)
f634c644bedbe5d356fc3a23ed3a37ad05b5915e
maheshde791/python_samples
/pythonsamples/thread1.py
375
3.96875
4
#! usr/bin/python import time from threading import Thread def printer(): for num in range(3): print("hello",num) time.sleep(1) thread1 = Thread(target=printer) thread1.start() thread2 = Thread(target=printer) thread2.start() threads = [] threads.append(thread1) threads.append(thread2) for t in threads: t.join() #thread.join() print("goodbye\r\n")
513a493ed2bc3aacc39ee9065835c9b6a3aa83f2
yangjinke1118/createmath
/maths.py
5,362
3.578125
4
""" 本模块实现各种数学算术题型 1、竖式100以内加减法,进位、借位;逆向思维 2、横式100以内加减法,进位、借位,逆向思维 3、个位乘法,十位数除法。 """ from random import randint def get_ab_cd(ab_max, cd_max): ab = 0 cd = 0 # 获取符合要求的ab数值 if ab_max > 9 and ab_max <= 99: # 当ab最大值大于9 ab = randint(0, ab_max) while ab <= 9: ab = randint(0, ab_max) # 直到获取符合条件的ab数值,10-99 elif ab_max > 99 and ab_max <= 999: ab = randint(0, ab_max) while ab <= 99: ab = randint(0, ab_max) # 直到获取符合条件的ab数值,100-999 elif ab_max <= 9: ab = randint(0, ab_max) while ab > 9: ab = randint(0, ab_max) # 直到获取符合条件的ab数值,0-9 # 获取符合要求的cd数值 if cd_max > 9 and cd_max <= 99: # 当ab最大值大于9 cd = randint(0, cd_max) while cd <= 9: cd = randint(0, cd_max) # 直到获取符合条件的cd数值,10-99 elif cd_max > 99 and cd_max <= 999: cd = randint(0, cd_max) while cd <= 99: cd = randint(0, cd_max) # 直到获取符合条件的cd数值,100-999 elif cd_max <= 9: cd = randint(0, cd_max) while cd > 9: cd = randint(0, cd_max) # 直到获取符合条件的cd数值,0-9 return ab, cd def createMath_add(type, ab_max, cd_max): """ 100以内加法生成,返回加数,被加数,结果的十位、个位 数字 type = 0:普通生成方式 type = 1:特殊生成方式,个位必须有进位 ab_max表示被加数最大值上限,如果大于10,则ab不会小于10 cd_max表示加数最大值上限。 """ if ab_max >= 100 or cd_max >= 100: return -1 ab, cd = get_ab_cd(ab_max, cd_max) if type == 0: # 不进位 while int(str(ab)[-1]) + int(str(cd)[-1]) > 9: ab, cd = get_ab_cd(ab_max, cd_max) elif type == 1: # 进位 while int(str(ab)[-1]) + int(str(cd)[-1]) < 9: ab, cd = get_ab_cd(ab_max, cd_max) return ['+', a, b, c, d, e, f] def createMath_dec(type): """ 100以内减法生成,返回减数,被减数,结果的十位、个位 数字 type = 0:普通生成方式 type = 1:特殊生成方式,十位必须有退位 """ b = randint(0, 9) d = randint(0, 9) if type == 1: # 有退位 while b >= d: # b < d 才退出循环 b = randint(0, 9) d = randint(0, 9) if b >= d: a = randint(0, 9) c = randint(0, 9) while a < c: a = randint(0, 9) c = randint(0, 9) else: a = randint(0, 9) c = randint(0, 9) while a <= c: a = randint(0, 9) c = randint(0, 9) math_result = a * 10 + b - c * 10 - d e = math_result // 10 f = math_result % 10 return ['-', a, b, c, d, e, f] def createMath_Mul(): """ 生成十以内的乘法 :return: 以列表形式,返回乘数,被乘数,结果 十位,个位数 """ a = 0 b = randint(0, 9) c = 0 d = randint(0, 9) result = b * d e = result // 10 f = result % 10 return ['×', a, b, c, d, e, f] def createMath_div(): """ 生成被除数100以内,除数10以内的除法 :return: 以列表形式,返回除数,被数,结果 十位,个位数 """ c = 0 while True: a = randint(0, 9) b = randint(0, 9) d = randint(0, 9) if d == 0: continue if (a * 10 + b) % d == 0: break result = (a * 10 + b) / d e = result // 10 f = result % 10 return ['÷', a, b, c, d, e, f] def printMath_v(mathlist): if str(type(mathlist)) != "<class 'list'>": print('Error:Please Enter a list object!') return if len(mathlist) != 7: print('Error:The list has not 5 elements!') return op = mathlist[0] a = mathlist[1] b = mathlist[2] c = mathlist[3] d = mathlist[4] e = mathlist[5] f = mathlist[6] print(' ' + str(a) + ' ' + str(b)) print(op + ' ' + str(c) + ' ' + str(d)) print('----------') print(' ' + str(e) + ' ' + str(f)) print('') def printMath_h(mathlist): if str(type(mathlist)) != "<class 'list'>": print('Error:Please Enter a list object!') return if len(mathlist) != 7: print('Error:The list has not 5 elements!') return op = mathlist[0] a = mathlist[1] b = mathlist[2] c = mathlist[3] d = mathlist[4] e = mathlist[5] f = mathlist[6] print(' ' + str(a) + str(b) + ' ' + op + ' ' + str(c) + str(d) + ' = ' + str(e) + str(f)) print('') def runMath(mathlist): if str(type(mathlist)) != "<class 'list'>": print('Error:Please Enter a list object!') return if len(mathlist) != 7: print('Error:The list has not 5 elements!') return op = mathlist[0] a = mathlist[1] b = mathlist[2] c = mathlist[3] d = mathlist[4] firstNum = a*10 + b secondNum = c*10 + d if op == '+': print(str(firstNum + secondNum)) elif op == '-': print(str(firstNum - secondNum))
037fefbffd79817866209230c72ac28080e63724
Thibautguerin/EpitechMaths
/202unsold_2018/202unsold
4,004
3.609375
4
#!/usr/bin/python3 from __future__ import print_function from math import * import re import sys def marginal(): a = int(sys.argv[1]) b = int(sys.argv[2]) x = 10 y = 10 calcul = float(0) total = 0 tab = [] i = int(0) divisor = (5 * a - 150) * (5 * b - 150) x_total = [] print("------------------------------------------------------------") print(" X=10 X=20 X=30 X=40 X=50 Y law") while (y <= 50): while (x <= 50): tab.append(float(((a - x) * (b - y)) / divisor)) x = x + 10 total = tab[i] + tab[i + 1] + tab[i + 2] + tab[i + 3] + tab[i + 4] print("Y=",y," ",'{:.3f}'.format(tab[i])," ",'{:.3f}'.format(tab[i + 1])," ",'{:.3f}'.format(tab[i + 2]), " ",'{:.3f}'.format(tab[i + 3])," ",'{:.3f}'.format(tab[i + 4])," ",'{:.3f}'.format(total),sep="") x = 10 i = i + 5 y = y + 10 i = 0 while (i <= 4): x_total.append(float(tab[i] + tab[i + 5] + tab[i + 10] + tab[i + 15] + tab[i + 20])) i = i + 1 print("X law ",'{:.3f}'.format(x_total[0])," ",'{:.3f}'.format(x_total[1])," ",'{:.3f}'.format(x_total[2])," ",'{:.3f}'.format(x_total[3])," ",'{:.3f}'.format(x_total[4])," 1",sep="") print("------------------------------------------------------------") return (tab) def law_z(tab): p20 = tab[0] p30 = tab[5] + tab[1] p40 = tab[2] + tab[6] + tab[10] p50 = tab[3] + tab[7] + tab[11] + tab[15] p60 = tab[4] + tab[8] + tab[12] + tab[16] + tab[20] p70 = tab[9] + tab[13] + tab[17] + tab[21] p80 = tab[14] + tab[18] + tab[22] p90 = tab[19] + tab[23] p100 = tab[24] print("z 20 30 40 50 60 70 80 90 100 total") print("p(Z=z) ",'{:.3f}'.format(p20)," ",'{:.3f}'.format(p30)," ",'{:.3f}'.format(p40)," ",'{:.3f}'.format(p50)," ",'{:.3f}'.format(p60)," ",'{:.3f}'.format(p70)," ",'{:.3f}'.format(p80)," ",'{:.3f}'.format(p90)," ",'{:.3f}'.format(p100)," 1",sep="") print("------------------------------------------------------------") def esperance_x(tab): ex = float(0) i = 0 x = 10 y = 10 while (y <= 50): while (x <= 50): ex = ex + x * tab[i] x = x + 10 i = i + 1 x = 10 y = y + 10 return (ex) def esperance_y(tab): ey = float(0) i = 0 x = 10 y = 10 while (y <= 50): while (x <= 50): ey = ey + y * (tab[i]) i = i + 1 x = x + 10 x = 10 y = y + 10 return (ey) def variance_x(tab, ex): vx = float(0) i = 0 x = 10 while (x <= 50): vx = vx + (x - ex)**2 * (tab[i] + tab[i + 5] + tab[i + 10] + tab[i + 15] + tab[i + 20]) x = x + 10 i = i + 1 return (vx) def variance_y(tab, ey): vy = float(0) i = 0 y = 10 while (y <= 50): vy = vy + (y - ey)**2 * (tab[i] + tab[i + 1] + tab[i + 2] + tab[i + 3] + tab[i + 4]) y = y + 10 i = i + 5 return (vy) def variances(tab): ex = esperance_x(tab) ey = esperance_y(tab) ez = ex + ey vx = variance_x(tab, ex) vy = variance_y(tab, ey) vz = vx + vy print("expected value of X: ",'{:.1f}'.format(ex),sep="") print("variance of X: ",'{:.1f}'.format(vx),sep="") print("expected value of Y: ",'{:.1f}'.format(ey),sep="") print("variance of Y: ",'{:.1f}'.format(vy),sep="") print("expected value of Z: ",'{:.1f}'.format(ez),sep="") print("variance of Z: ",'{:.1f}'.format(vz),sep="") print("------------------------------------------------------------") def calcul(): tab = marginal() law_z(tab) variances(tab) def error_management(): string = (" ".join(sys.argv)) regexp = r"^((./202unsold [0-9]+ [0-9]+)|(./202unsold -h))$" if (re.match(regexp, string) is None): exit(84) if (sys.argv[1] == "-h"): print("USAGE") print(" ./202unsold a b\n") print("DESCRIPTION") print(" a constant computed from the past results") print(" b constant computed from the past results") exit(0) if (int(sys.argv[1]) >= 50 and int(sys.argv[2]) >= 50): calcul() else: exit(84) def main(): error_management() exit(0) main()
ff4d54cfd96fbcf0ab01cd7bd7d7961f3beec7cb
SozinM/PTests
/test_dict.py
862
3.734375
4
class FormattedDict(dict): def __str__(self): print self.items() string = '' for key, value in self.items(): tmpstr = '' if isinstance(value,dict): string += '%s:\n' % (tmpstr + key) while(isinstance(value,dict)):#thing to bypass recursion tmpstr += '\t' print value.items() key, value = value.items()[0]#cause it is a list of tuples string += '%s:\n' % (tmpstr+key) string += '\t%s\n' % (tmpstr+value) else: string += '%s:\n'% (key) string += '\t%s\n'%(value) return string def main(): print FormattedDict({ '1': { 'child': '1/child/value' }, '2': '2/value'}) if __name__ == '__main__': main()
1231b4dd5be7294016746cff95eaa9c1ed1d60e4
zainllw0w/skillbox
/lessons 20/HomeWork/task9.py
1,734
3.78125
4
def sort(data, time): tt = False ft = True st = False is_find = True winers_name = set() index = 0 while is_find: index += 1 for key, values in data.items(): if time[0 - index] == int(values[1]) and ft and values[0] not in winers_name: first_id = key ft = False st = True winers_name.add(values[0]) first_i = index elif time[0 -index] == int(values[1]) and st and values[0] not in winers_name: second_id = key st = False tt = True winers_name.add(values[0]) second_i = index elif time[0 -index] == int(values[1]) and tt and values[0] not in winers_name: three_id = key winers_name.add(values[0]) is_find = False three_i = index break return first_id, second_id, three_id, first_i, second_i, three_i n = int(input('Введите количество строк: ')) data = dict() time_list = list() for i in range(1, n+1): print(f'Введите {i} строку: ', end='') text = input().split() time = text[0] time_list.append(int(time)) name = text[1] obj = [name, time] data[i] = tuple(obj) f, s, t, fi, si, ti = sort(data, sorted(time_list)) time_list = sorted(time_list) print('1 место занимает: {0}, с очками {1}'.format(data[f][0], time_list[-fi])) print('2 место занимает: {0}, с очками {1}'.format(data[s][0], time_list[-si])) print('3 место занимает: {0}, с очками {1}'.format(data[t][0], time_list[-ti]))
92effa71c7d4c5c8b9c8ab392cbaa838780d1567
hamzaharoon1314/Python-Basics-Beginner
/Class #2/basics.py
280
3.625
4
# indentation if True: print 'hello' print 'HaMza' # commenting # single-line comment """ line 1 line 2 line 3 """ # variables name = 'engineer man' # multi-line num1 = 5; num2 = 8 # continuance long_name = \ "something" + \ "something else" # printing print 'hello world',
bc84b117291f514b88bd69bd7c83fe09bea4cf81
maurusian/sudoku
/draw.py
5,585
3.6875
4
import turtle import os from datetime import datetime #size of the square side SQUARE_SIDE = 75 DEF_WINDOW_SIZE_X = 1000 DEF_WINDOW_SIZE_Y = 800 #display coordinate corrections for numbers #these were obtained by trial and error on #multiple board sizes CORRX = 25 CORRY = 60 class Drawing(): """ Class that handles drawing a Sudoku board on canvas, and exporting it to postscript file. """ def __init__(self,values): """ Sets the values of the Sudoku cells. Sets different parameters of the canvas window, and the drawing. --Input: - values: list of lists containing """ self.grid = turtle.Turtle() #grid object self.values = values #list of lists, matrix self.board_size = len(self.values) #window size self.WINDOW_SIZE_X = DEF_WINDOW_SIZE_X*(self.board_size//10+1) self.WINDOW_SIZE_Y = DEF_WINDOW_SIZE_Y*(self.board_size//10+1) #font size for numbers self.font_size = max(25//(self.board_size//10+1),6) #Canvas and drawing properties turtle.setworldcoordinates(-1, -1, self.WINDOW_SIZE_X, self.WINDOW_SIZE_Y) self.grid.home() turtle.delay(0) self.grid.hideturtle() self.grid.ht() self.posx = (self.WINDOW_SIZE_X - SQUARE_SIDE*len(self.values)) // 2 self.posy = (self.WINDOW_SIZE_Y - SQUARE_SIDE*len(self.values)) // 2 def square(self,side): """ Draws square on the canvas. -- Input: - side: side of the square in canvas units. The unit is determined by the WINDOW_SIZE parameters. """ for i in range(4): self.grid.forward(side) self.grid.left(90) def row(self,n,side): """ Draws a raw of squares on the canvas. -- Input: - n: number of squares - side: side of each square in canvas units. The unit is determined by the WINDOW_SIZE parameters. """ for i in range(n): self.square(side) self.grid.forward(side) self.grid.penup() self.grid.left(180) self.grid.forward(n * side) self.grid.left(180) self.grid.pendown() def row_of_rows(self,n,side): """ Draws a row of rows on the canvas. -- Input: - n: number of rows and squares in each row. - side: side of each square in canvas units. The unit is determined by the WINDOW_SIZE parameters. """ self.grid.pendown() for i in range(n): self.row(n,side) self.grid.penup() self.grid.left(90) self.grid.forward(side) self.grid.right(90) self.grid.pendown() self.grid.penup() self.grid.right(90) self.grid.forward(n * side) self.grid.left(90) self.grid.pendown() def draw_sudoku(self,filename): """ Draws the grid on the canvas, and writes the numbers in their respective cells. The filename is returned so the file can be converted to another format. --Input: - filename: name of the Postscript file to be exported. --Output: - filename: the actual file name that was used. If no name was provided, a default name is built. """ side = SQUARE_SIDE self.grid.penup() self.grid.goto(self.posx,self.posy) self.row_of_rows(len(self.values),side) self.grid.penup() self.grid.goto(self.posx,self.posy) topx = (self.WINDOW_SIZE_X - SQUARE_SIDE*len(self.values)) // 2 + CORRX #correction on the X coordinates for number positions topy = (self.WINDOW_SIZE_Y + SQUARE_SIDE*(len(self.values))) // 2 - CORRY #correction on the Y coordinates for number positions for i in range(len(self.values)): posi = topy - i*75 for j in range(len(self.values[i])): posj = topx + j*75 self.grid.goto(posj,posi) if self.values[i][j] != 0: self.grid.write(str(self.values[i][j]),move=True,align="left", font=("Arial", self.font_size, "normal")) if filename is None or filename.split('.')[0].strip() == '': date = datetime.now() datestring = date.strftime('%y.%m.%d_%H.%M') filename = 'sudoku_'+datestring+'.ps' #default name cnv = turtle.getscreen().getcanvas().postscript(file=filename) return filename if __name__ == '__main__': """ Test implementation for Drawing class. """ import numpy as np lis = [[0,1,4,0,0,5,0,0,7], [0,3,0,0,2,0,8,0,0], [0,0,2,1,0,3,0,0,0], [0,0,0,0,4,0,0,1,0], [0,1,4,0,0,5,0,0,7], [0,3,0,0,2,0,8,0,0], [0,0,2,1,0,3,0,0,0], [0,0,0,0,4,0,0,1,0], [0,0,0,0,4,0,0,1,0]] lis2 = [[0,1,4,0,0,5,0,0], [0,3,0,0,2,0,8,0], [0,0,2,1,0,3,0,0], [0,0,0,0,4,0,0,1], [0,1,4,0,0,5,0,0], [0,3,0,0,2,0,8,0], [0,0,2,1,0,3,0,0], [0,0,0,0,4,0,0,1]] #testing correct display with different grid sizes size = 32 ones = list(np.ones([size, size], dtype = int)) drawing = Drawing(ones) print(drawing.values) filename = drawing.draw_sudoku('') print(filename)
2a726249bfa813c7f984cb9002e79b19eba0e272
nikola825/pp1_projekat
/block_ciphers/algorithms/aes256.py
581
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 13 20:29:47 2016 @author: bulse_eye """ import aes128 BLOCK_SIZE = 16 def generate_key(key): valid_key = '' for i in range(8): if len(key) < 4: key = key + ' ' * (4 - len(key)) valid_key += key[:4] key = key[4:] return valid_key def validate_key(key): if len(key) == 32: return True else: return False def encrypt_block(block, key): return aes128.encrypt_block(block, key) def decrypt_block(block, key): return aes128.decrypt_block(block, key)
26ed90b458ae9633c430eba0ccc09fcb8a3be511
vedant1551/111_VedantRajyaguru
/index.py
986
3.71875
4
import nltk # Python library for NLP from nltk.corpus import twitter_samples # sample Twitter dataset from NLTK import matplotlib.pyplot as plt # library for visualization import random # pseudo-random number generator #downloads sample twitter dataset. nltk.download('twitter_samples') # select the set of positive and negative tweets all_positive_tweets = twitter_samples.strings('positive_tweets.json') all_negative_tweets = twitter_samples.strings('negative_tweets.json') print('Number of positive tweets: ', len(all_positive_tweets)) print('Number of negative tweets: ', len(all_negative_tweets)) print('\nThe type of all_positive_tweets is: ', type(all_positive_tweets)) print('The type of a tweet entry is: ', type(all_negative_tweets[0])) fig = plt.figure(figsize=(5, 5)) labels = 'Positives', 'Negative' sizes = [len(all_positive_tweets), len(all_negative_tweets)] plt.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) plt.axis('equal') plt.show()
8b666724caa105b60f8e04a621a49f6269f94873
OmarCamaHuara/RecodePro2020
/Aulas/7_PYTHON/tuplas.py
406
3.71875
4
# Formato de declaracao de uma Tupla carros = ("KA", "HB20", "Kwid", "Onix", "UP", "Mobi") # EStrutura de tratamento de execao # (se o que esta dentro de Try trouxe algum erro e retornado o Exception) try: carros[0] = "Fiesta" except: print("Nao e possivel efectuar alteracoes em tuplas") # Imressao de Tuplas para verificar se houve alteracao for carro in carros: print(carro.capitalize())
268f348a920fa28b23b4e996ba5376c4d656e0da
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/5371.py
564
3.828125
4
def is_tidy(number): number = list(str(number)) for i in range(0, len(number)-1): if number[i] > number[i+1]: return False return True def solve(lnumber): temp_tidy = lnumber for number in range(1,lnumber+1): if is_tidy(number): temp_tidy = number return temp_tidy if __name__ == "__main__": t = int(input()) # read a line with a single integer for i in range(1, t + 1): last_number = input() answer = solve(int(last_number)) print("Case #{}: {}".format(i, answer)) # check out .format's specification for more formatting options
82d3e8b10d0dd2f32a003f16631e06960002f0eb
rgbbatista/python-iniciante-udemy
/python avançado função enumerate.py
401
4.21875
4
#Função enumerate '''navegar por uma lista e obter ao mesmo tempo que imprime nomes queira imprimir o índice de cada elementos normalmente usando a função renge e len ''' lista = ['abacate', 'bola', 'cachorro'] for i in range(len(lista)): print(i,lista[1]) print() '''Usando a função Enumerate''' print('Usando a função Enumerate') for i, nome in enumerate(lista): print(i,nome)
3457127afa1105c0ac0450730974d1732d0d04d7
JanNoszczyk/CountMeUp
/count_me_up.py
1,818
4.28125
4
import queue class CountMeUp: """ CountMeUp creates a FIFO queue to store all the votes. It also has methods to add new votes to the queue and to display the current vote statistics. CountMeUp will also track the total number of votes per candidate and the number of votes done per each user using hashmaps stored in runtime memory I do not have any experience in front-end or server-side developtment. Therefore, I have implemented my CountMeUp program as running locally with all the data stored locally. Alternatively, """ def __init__(self): self.maxsize = 10000000 self.Queue = queue.Queue(self.maxsize) self.candidate_votes = {1:0, 2:0, 3:0, 4:0, 5:0} self.users = {} def add_vote(self, user, candidate): """ The function will add the vote to the queue. Each vote is stored as a tuple in the queue as (user, candidate) :param user: The user who submitted the vote :param candidate: The candidate for whom the vote was submitted """ self.Queue.put((user, candidate)) def process_vote(self): """ The function will process a vote at the beginning of the queue. If the vote is valid (submitted by a user with at most 3 votes) it will be added to the candidate_votes dictionary which counts up the number of valid votes made per candidate. Otherwise, the vote will not be counted. The numbers of votes made per user are tracked in the dictionary users. """ user, candidate = self.Queue.get() if user in self.users: if self.users[user] < 3: # The vote will only be counted if its valid self.candidate_votes[candidate] += 1 self.users[user] += 1 else: # If the user is new, add him to the users dictionary self.users[user] = 1 self.candidate_votes[candidate] += 1
7b9e9ec8833d472e27407026003fc2323471dbbc
alcebytes/Phyton-Estudo
/04_estruturas_de_repeticao/01_laco_while.py
422
3.96875
4
senha = "54321" leitura = " " while (leitura != senha): leitura = input("Digite a senha: ") if leitura == senha: print('Acesso liberado') else: print('Senha incorreta. Tente novamente') contador = 0 somador = 0 while contador < 5: contador = contador + 1 valor = float(input('Digite o ' + str(contador) + '° valor: ')) somador = somador + valor print('Soma = ', somador)
b007eb134646483b0f18951ac8391fc6f2e01104
Jaires/advent
/day10.py
4,599
3.5625
4
#!/usr/bin/python # coding=utf8 from adventOfCode import AdventWithFile import re from abc import ABCMeta, abstractmethod class Robot: def __init__(self, microchip, botNumber): if not isinstance(microchip, list): microchip = [microchip] self.microchip = microchip or [] self.botNumber = botNumber def isAvailable(self): return len(self.microchip) == 2 def resetMicrochip(self): self.microchip = [] def setMicrochip(self, value): if not value: raise self.microchip.append(value) def getMicrochip(self): return self.microchip def getBotNumber(self): return self.botNumber def __str__(self): return "Robot(%s)" % str(self.microchip) class Command: __metaclass__ = ABCMeta def hasRequirements(self): return False @abstractmethod def apply(self, robots): pass @abstractmethod def getRelatedBots(self): pass class ValueCommand(Command): def __init__(self, value, botNumber): self.value = value self.botNumber = botNumber def __str__(self): return "ValueCommand(%s,%s)" % (self.value, self.botNumber) def apply(self, robots): if self.botNumber in robots: robots[self.botNumber].setMicrochip(self.value) else: robots[self.botNumber] = Robot([self.value], self.botNumber) return True def getRelatedBots(self): return [self.botNumber] class BotCommand(Command): def hasRequirements(self): return True def __init__(self, botNumber, lowBot, highBot, comparedMicrochips): self.botNumber = botNumber self.lowBot = lowBot self.highBot = highBot self.comparedMicrochips = comparedMicrochips def __str__(self): return "BotCommand(%s=>(%s,%s))" % (self.botNumber, self.lowBot, self.highBot) def apply(self, robots): if not self.botNumber in robots: return False microchips = robots[self.botNumber].getMicrochip() if len(microchips) < 2: return False robots[self.botNumber].resetMicrochip() if self.lowBot in robots: robots[self.lowBot].setMicrochip(min(microchips)) else: robots[self.lowBot] = Robot(min(microchips), self.lowBot) if self.highBot in robots: robots[self.highBot].setMicrochip(max(microchips)) else: robots[self.highBot] = Robot(max(microchips), self.highBot) if self.comparedMicrochips and not [ microchip for microchip in self.comparedMicrochips if microchip not in microchips]: print "Bot %s is comparing %s" % (self.botNumber, str(microchips)) return True def getRelatedBots(self): return [self.lowBot, self.highBot] class Day10(AdventWithFile): def __init__(self, comparedMicrochips=[], resultOutputs=[]): AdventWithFile.__init__(self) self.robots = {} self.commands = {} self.outputs = {} self.comparedMicrochips = comparedMicrochips self.resultOutputs = resultOutputs def parseLine(self, line): """ bot 37 gives low to bot 114 and high to bot 150 value 2 goes to bot 156 """ command = re.search( "(?P<botNumber>bot [0-9]+) gives low to (?P<lowBot>[a-z]+ [0-9]+) and high to (?P<highBot>[a-z]+ [0-9]+)", line) if command: return BotCommand((command.group("botNumber")), (command.group("lowBot")), (command.group("highBot")), self.comparedMicrochips) command = re.search("value (?P<value>[0-9]+) goes to (?P<botNumber>bot [0-9]+)", line) if command: return ValueCommand(int(command.group("value")), (command.group("botNumber"))) raise Exception("Invalid command") def doCommand(self, command): # do single command if command.apply(self.robots): # check each affected robot for robot in command.getRelatedBots(): if robot in self.robots and self.robots[robot].isAvailable() and robot in self.commands: if command.hasRequirements() and command.botNumber in self.commands: del self.commands[command.botNumber] self.doCommand(self.commands[robot]) return True return False def loadData(self): for line in self.sourceFile.readlines(): # parse command command = self.parseLine(line.strip()) # is value command if command.hasRequirements(): self.commands[command.botNumber] = command # do all commands available self.doCommand(command) def doPart1(self, ): self.loadData() def doPart2(self): self.loadData() result = 1 for robot in self.robots: if robot in self.resultOutputs: result *= self.robots[robot].microchip[0] print result Day10(comparedMicrochips=[61,17]).doPart1() Day10(resultOutputs=["output 0", "output 1", "output 2"]).doPart2()
d3a445f556bf826cd7f5f28691d8695be58d11c3
Bubliks/bmstu_Python
/sem_1/RK_3 - Matrix/First.py
1,515
3.6875
4
from math import * from random import * M = int(input("Длина Строки: ")) N = int(input("Длина Столбца: ")) X =[] B=[] G=[] mas=[] h=0;h1=N-1 for i in range(N): X.append([]) for j in range(M): X[i].append(float(input())) print("Исходная Матрица") for i in range(N): for j in range(M): print("{:5.3}".format(X[i][j]),end=" ") print() #for i in range(N): # B.append(X[i][i]) #print("Главная диагональ: ", B) #for i in range(N): # G.append(X[h1][h]) # h+=1 # h1-=1 #print("Побочная диагональ: ", G) #print("Рандомная матрица: ") #for i in range(N): # mas.append([]) # for j in range(N): # mas[i].append(randint(-10,10)) #for i in range(N): # for j in range(N): # print("{:5.3f}".format(mas[i][j]),end= " ") # print() #_-------------------поворот матрицы print("Поворот матрицы" ) X.reverse() st=N if N<M: st=M for i in range(M-N,M): X.append([]) for j in range(M): X[i].append("*") if M<N: st=N for i in range(N): X.append([]) for j in range(N-M,N): X[i].append("*") for i in range(st): for j in range(i,st): # print(i,j) X[i][j],X[j][i]=X[j][i],X[i][j] #for i in range(st): # for j in range(st): # if X[i][j]=="*": # X.pop(j) for i in range(st): for j in range(st): if X[i][j] != "*": print("{:4.3}".format(X[i][j]),end= " ") print()
17a626eccc9b85bd0c4b816b5501b286edc9569b
MilaShar/String-Operations
/UEFA Euro 1988 Final part 02.py
663
3.8125
4
#assignment 1 player = "Frank Rijkaard" #assignmnet 2 first_name = player[:5] print (first_name) #assignment 3 last_name = player [5:] #print (last_name) print (len(last_name)) #assignment 4 name_short = (first_name[0] + "." + "" + last_name) print (name_short) #assignment 5 chant = "Rijkaard!" lenght_first_name = (len(first_name)) #print (len(first_name)) print ((chant + " " ) * lenght_first_name) #assignment 6, I do not understand this assignment good_chant = "Go Rijkaard!" lenght_first_name = (len(first_name)) #print (len(first_name)) #print (good_chant.rstrip() * lenght_first_name) print ((good_chant + " ") * lenght_first_name)
685ed3e39f353be9b9d72d37a11187c8802e2dba
ltltlt/algorithms
/algorithms/eight-queen/iter.py
726
3.734375
4
''' > File Name: iter.py > Author: ty-l > Mail: liuty196888@gmail.com ''' import itertools NUM = 8 num = 0 not_print = True def print_board(arglist): global num num += 1 if not_print: return for pos in arglist: print('_ ' * pos + '@ ' + (NUM - pos -1) * '_ ') print() def check(arglist, i): for j in range(len(arglist)): if abs(arglist[j] - i) in (0, len(arglist) - j): return False return True def nqueens(): arglists = [[]] while arglists: arglist = arglists.pop() if len(arglist) == NUM: print_board(arglist) else: arglists.extend(arglist + [i] for i in range(NUM) if check(arglist, i)) nqueens() print(num)
914ac4741f44c2715dc12ccc354bf18a9a3a869a
MailsonFelipe/Brincando_Com_Python
/Quest08.py
328
4.03125
4
# Autor: Mailson Felipe # Data: 26/03/2021 def quantosNumeros(digito): qtd = 0 valor = 1 while valor <= digito: valor *= 10 qtd += 1 print("Quantidade de digitos: "+str(qtd)) def main(): digito = int(input("Digite um numero: ")) quantosNumeros(digito) if __name__ == "__main__": main()
a797f07c59e3e72c2c922e4da6679a9f461c94a4
Ismile-Hossain/Python_Codes
/27_Exercise01.py
688
4.25
4
""" Write a program with an infinite loop and a list of numbers. Each time through the loop the program should ask the user to guess a number (or type q to quit).If they type q, the program should end. Otherwise,it should tell them whether or not they successfully guessed a number in the list or not. """ numbers = [11, 32, 33, 15, 1] while True: answer = input("Guess a number or type q to quit.") if answer == 'q': break try: answer = int(answer) except ValueError: print("please type a number or q to quit.") if answer in numbers: print("You guessed correctly!") else: print("You guessed incorrectly")
3ad0a6b1d17649a37d8b309ae3ff6484787bef9e
estakaad/goodreads-stats
/stats.py
5,431
4
4
from datetime import datetime import sys import calendar # Returns the book that took the longest to read in the given year. It doesn't # necessarily mean that the user started reading the book the same year it # was finished. If the date of starting a book or finishing it unknown, # the book is skipped. def book_read_for_the_longest_in_given_year(books): book_read_for_the_longest = {} number_of_days = 0 if books: for key, value in books.items(): if (str(value['started_at']) != '-') and (str(value['read_at']) != '-'): date_started = datetime.strptime(str(value['started_at']), '%a %b %d %H:%M:%S %z %Y') date_finished = datetime.strptime(str(value['read_at']), '%a %b %d %H:%M:%S %z %Y') delta = (date_finished - date_started).days + 1 if delta > number_of_days: number_of_days = delta book_read_for_the_longest = {key: value, 'numberOfDaysRead': number_of_days} return book_read_for_the_longest # Returns number of pages read in the given year def total_pages_read_given_year(books): total_pages_per_year = 0 user_name = '' users_pages = [] for key, value in books.items(): if value['num_pages'] != '-': total_pages_per_year += int(value['num_pages']) else: total_pages_per_year += 0 user_name = value['username'] users_pages.append(total_pages_per_year) users_pages.append(user_name) return users_pages # Returns average number of pages read per day in the given year. def average_number_of_pages_read_in_day(books, year): total_pages = total_pages_read_given_year(books) user_name = '' for key, value in books.items(): user_name = value['username'] users_average_pages_per_day = [] if calendar.isleap(year): average_pages_per_day = total_pages[0] / 366 else: average_pages_per_day = total_pages[0] / 365 users_average_pages_per_day.append(average_pages_per_day) users_average_pages_per_day.append(user_name) return users_average_pages_per_day # Returns the book with the most ratings among the books read in given year. def book_with_most_ratings_in_given_year(books): book_with_most_ratings = {} number_of_ratings = 0 for key, value in books.items(): if int(value['ratings_count']) > number_of_ratings: number_of_ratings = int(value['ratings_count']) book_with_most_ratings = {key: value} return book_with_most_ratings # Returns the book with the least ratings among the books read in given year. def book_with_least_ratings_in_given_year(books): book_with_least_ratings = {} number_of_ratings = sys.maxsize for key, value in books.items(): if int(value['ratings_count']) <= number_of_ratings: number_of_ratings = int(value['ratings_count']) book_with_least_ratings = {key: value} return book_with_least_ratings # Returns the number of ratings a book read this year has on average. def average_number_of_ratings(books): sum_of_count_of_ratings = 0 number_of_ratings = 0 user_name = '' users_average_number_of_ratings = [] for key, value in books.items(): number_of_ratings+=1 sum_of_count_of_ratings += int(value['ratings_count']) user_name = value['username'] if number_of_ratings != 0: users_average_number_of_ratings.append(sum_of_count_of_ratings / number_of_ratings) else: users_average_number_of_ratings.append(0) users_average_number_of_ratings.append(user_name) return users_average_number_of_ratings # Returns the worst book read in the given year. The worst meaning having # the lowest average rating. Only takes into account books that have # at least 15 ratings. def worst_book_read(books): worst_book = {} worst_rating = 5.00 for key, value in books.items(): if int(value['ratings_count']) >= 15: if float(value['average_rating']) <= worst_rating: worst_rating = float(value['average_rating']) worst_book = {key: value} return worst_book # Returns the best book read in the given year. The best meaning having # the lowest average rating. Only takes into account books that have # at least 15 ratings. def best_book_read(books): best_book = {} best_rating = 0.00 for key, value in books.items(): if int(value['ratings_count']) >= 15: if float(value['average_rating']) > best_rating: best_rating = float(value['average_rating']) best_book = {key: value} return best_book # Returns an average rating of books read during the given year. Only takes # into account books that have at least 15 ratings. def average_rating_of_book(books): number_of_ratings = 0 sum_of_ratings = 0 user_name = '' users_average_rating = [] for key, value in books.items(): if int(value['ratings_count']) >= 15: sum_of_ratings+=float(value['average_rating']) number_of_ratings+=1 user_name = value['username'] if number_of_ratings != 0: users_average_rating.append(sum_of_ratings / number_of_ratings) else: users_average_rating.append(0) users_average_rating.append(user_name) return users_average_rating
8d28557fa8a5d40ea28d4c9b985db6723d0d9504
zhch-sun/leetcode_szc
/94.binary-tree-inorder-traversal.py
3,041
3.703125
4
# # @lc app=leetcode id=94 lang=python # # [94] Binary Tree Inorder Traversal # def listToTree(input): if not input: return None root = TreeNode(int(input[0])) nodeQueue = [root] # 最后这个包含所有node front = 0 # to index queue index = 1 # to index list while index < len(input): node = nodeQueue[front] front += 1 left_num = input[index] if left_num is not None: # 这意味着前面的None会使后面的位置直接跳过 node.left = TreeNode(left_num) nodeQueue.append(node.left) index += 1 if index >= len(input): break right_num = input[index] if right_num is not None: node.right = TreeNode(right_num) nodeQueue.append(node.right) index += 1 return root def treeToList(input): if not input: return None cur = input nodeQueue = [cur] res = [] front = 0 while True: val = cur.val if cur is not None else None res.append(val) if cur is not None: #及时该位置是空的,也要None? nodeQueue.append(cur.left) nodeQueue.append(cur.right) front += 1 if front < len(nodeQueue): cur = nodeQueue[front] else: break while res[-1] is None: # 符合定义? res.pop() return res # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): # def inorderTraversal(self, root): # """ # :type root: TreeNode # :rtype: List[int] # """ # def helper(root, ans): # if not root: # return # helper(root.left, ans) # ans.append(root.val) # helper(root.right, ans) # res = [] # helper(root, res) # return res def inorderTraversal(self, root): sta = [] ans = [] # 可能出现sta为空但是root不空的情况,比如root的左边都结束 while sta or root: # sta里是左边的, root代表右边的root while root: # 直到None的时候停下. sta.append(root) root = root.left cur = sta.pop() ans.append(cur.val) root = cur.right # 可能是None return ans if __name__ == '__main__': """ 解法1: 递归直接写掉. 解法2: 算法是对的, 没有证明? 没有完全理解. 先入栈所有左边的, 再逐个pop, 写值, 改root为right. root代表的是新一个可能有left的地方 解法3: TODO 大雪菜还有个通用递归转换方法 https://www.acwing.com/solution/LeetCode/content/176/ 解法4: Morris traversal: O(1)空间复杂度.. 很复杂. 不管 """ s = Solution() print(s.inorderTraversal(listToTree([1,None,2,3])))
e14a5adb055e33d7a0f0b131fe3897d200c2a489
ganhan999/ForLeetcode
/504、七进制数.py
435
3.65625
4
""" 给定一个整数,将其转化为7进制,并以字符串形式输出。 示例 1: 输入: 100 输出: "202" 示例 2: 输入: -7 输出: "-10" """ """ 递归 """ #大神做法1 class Solution: def convertToBase7(self, num: int) -> str: if num < 0: return "-" + self.convertToBase7(-num) if num < 7: return str(num) return self.convertToBase7(num // 7) + str(num % 7)
acfbf58bdae6ebf704861b94d485a502c1d0e94a
SercanSB/PYCHARM
/Listeye Eleman Ekleme Çıkarma Silme vs.py
300
3.671875
4
sesliHarfler=["a","e","ı","i"] print(sesliHarfler) sesliHarfler += ["ö","o"] print(sesliHarfler) sesliHarfler.append("U") print(sesliHarfler) sesliHarfler[1:3]=("Ü") print(sesliHarfler) sesliHarfler[:1]=("") print(sesliHarfler) sesliHarfler.clear() print(sesliHarfler)