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
77522ef68ac2f08a2a7fdd0ad68fa213960b3ba3
ValeriaK17/test
/счетчик, 4,1 .py
488
3.828125
4
# Глава 4. Задание 1 nachalo = int (input ("Введите число, которое является началом отсчета ")) konec = int (input ("Введите число, которое является концом счета ")) interval = int( input ("Введите число, равное значению интервала ")) for i in range (nachalo, konec, interval): print (i, end = " ") input ("\nНажмите Enter, чтобы выйти")
e916366362fc2e1dbfcc16ce3cd71f9e6a0e1903
PangXing/leetcode
/bytedance/DP/SellStock3.py
2,012
3.796875
4
# coding:utf-8 ''' 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入: [3,3,5,0,0,3,1,4] 输出: 6 解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。   随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。 示例 2: 输入: [1,2,3,4,5] 输出: 4 解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。 示例 3: 输入: [7,6,4,3,1] 输出: 0 解释: 在这个情况下, 没有交易完成, 所以最大利润为 0。 ''' class Solution(object): def maxProfit(self, prices): dp = dict() dp[-1] = {0: {0: 0, 1: -float('inf')}, 1: {0: 0, 1: -float('inf')}, 2: {0: 0, 1: -float('inf')}} for i in range(len(prices)): for k in range(1, 3): dp.setdefault(i, {0:{0: dp[i-1][2][0], 1: dp[i-1][2][1]}}) dp[i].setdefault(k, {}) dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k-1][1] + prices[i], dp[i][k-1][0]) dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i]) return dp[len(prices)-1][2][0] if __name__ == '__main__': solution = Solution() print solution.maxProfit([3,3,5,0,0,3,1,4]) print solution.maxProfit([1,2,3,4,5]) print solution.maxProfit([2,1,2,0,1])
7cabafb165a7a92d735b7e95d02a6d3eb44f143d
nearll/a-of-code-2020
/2/first_solution.py
574
3.703125
4
valid_count = 0 inputs = [] with open('input.txt', 'r') as input: for pw in input: inputs.append(pw.rsplit()) for value in inputs: first_location = int(value[0].split('-')[0]) - 1 second_location = int(value[0].split('-')[1]) - 1 pw_char = value[1].split(':')[0] pw = value[2] if ((pw[first_location] == pw_char and pw[second_location] != pw_char) or (pw[first_location] != pw_char and pw[second_location] == pw_char)): valid_count += 1 print('You found ' + str(valid_count) + ' valid passwords.')
b195c6629da0e43dcdb5df0f4d2e2e63c3f4e1f4
amdadul3036/Python-Data-Structure
/number_of_same_length_character.py
509
3.53125
4
# number_of_same_length_character.py names = ['Dhrubo' , 'Dhruboish' ,'Amdadul' , 'Poribrritto' , 'Dhrubo' , 'Shakib' , 'Arpa Roy' , 'Roy' , 'Arun' , 'Amdadul' , 'Oaliullah' , 'Shakib' , 'Jockey' , 'PK'] count = dict() for name in names: if name not in count: count[name] = 1 else: count[name] = count[name] + 1 print(count) # OUTPUT # {'Dhrubo': 2, 'Dhruboish': 1, 'Amdadul': 2, 'Poribrritto': 1, 'Shakib': 2, 'Arpa Roy': 1, 'Roy': 1, 'Arun': 1, 'Oaliullah': 1, 'Jockey': 1, 'PK': 1}
6e34e714a294fb8bc72e1f217cf73a3843ec0216
p-stets/python6
/python/lesson2/practice/1.number_is_even.py
216
4.03125
4
number = int(input("Input nr: ")) ''' Проверить, является ли введеное число четным ''' if (number % 2) == 0: print("Number is even") else: print("Number is not even")
7fdc4cb5a9a9bb015955babd631abe0c9dcd5c46
razz0n/Exploratory-Data-Analysis-of-Iris-Dataset
/iris.py
5,990
4.03125
4
# -*- coding: utf-8 -*- """ Created on Tue May 18 13:56:01 2021 @author: RaZz oN """ import numpy as np import pandas as pd import matplotlib.pyplot as plt # We load the iris dataset from the sklearn.datasets package from sklearn.datasets import load_iris # importing dataset to a variable iris = load_iris() # Type of iris which is utils.Bunch object type(iris) # Converting the iris dataset to dataframe with columns present # in feature_names dataset = pd.DataFrame(iris.data, columns= iris.feature_names) print(dataset) #Adding the target column in the dataset dataset['target'] = iris.target print(iris.target_names) # Now we use scatter function to visualize the dataset # Here, iloc in used to select the 3rd column and 4th column plt.scatter(dataset.iloc[:,2],dataset.iloc[:,3], c = iris.target) # Now, we put labels in the plt graph as plt.xlabel("Petal Lenght (in cm)") plt.ylabel(" Petal width (in cm)") plt.legend() plt.show() # Now, we separate the dataset into two parts i.e 4 columns # and a single target column x = dataset.iloc[:,0:4] y = dataset.iloc[:,4] """ k-NN Nearest Neighbors """ from sklearn.neighbors import KNeighborsClassifier # if p = 1 - manhattan if p = 2 - euclidean # Set the model kNN = KNeighborsClassifier(n_neighbors = 6, metric='minkowski', p=1) # fiT the model kNN.fit(x,y) # Create a new sample x_New = np.array([[5.2,3.4,1.3,0.1]]) # Predict the sample with the model kNN.predict(x_New) # Output is array[0] which means 0 from target i.e # setosa flower """ Using train_test_split """ from sklearn.model_selection import train_test_split # Splitting the data into 20% test set and random_state provides exact same # data for each iterative with shuffle true and stratified X_train, X_test, y_train, y_test = train_test_split(x,y, train_size=0.8, test_size=0.2, random_state = 40, shuffle= True, stratify = y) from sklearn.neighbors import KNeighborsClassifier #Using Manhattan distance kNN = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p=1) #Fitting the trained data kNN.fit(X_train, y_train) #Predicting the trained set predicted_y = kNN.predict(X_test) # Now, we need to verify the predicted data with the test data from sklearn.metrics import accuracy_score accuracy_score(y_test, predicted_y) """ Decision Tree """ from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score # Creating the model dT = DecisionTreeClassifier() # Fitting the model dT.fit(X_train,y_train) # Predicting the outcome of the model y_predict = dT.predict(X_test) # Calculating the accuracy of the model accuracy_score(y_test, y_predict) """ Cross Validation """ from sklearn.model_selection import cross_val_score # dT is the model used( here decision tree) , x = featurecolumns , y = target # cv = cross validation - no. of sections the test will be made (k - fold) score_dT = cross_val_score(dT, x , y, cv = 10) """ Naive Bayes """ from sklearn.naive_bayes import GaussianNB nB = GaussianNB() nB.fit(X_train,y_train) y_pred_nB = nB.predict(X_test) from sklearn.metrics import accuracy_score accuracy_score(y_test, y_pred_nB) from sklearn.model_selection import cross_val_score score_nB = cross_val_score(nB,x,y, cv =10) ''' Clustering Using K-Mean ''' # Importing the Kmean function from sklearn.cluster import KMeans # Creating a model for applying K-Mean Clustering KMNS = KMeans(n_clusters=3) # Fitting the dataset into the model KMNS.fit(iris_data) # Predicting the values but this time we create a label variable to store the # labels of the n_clusters Label = KMNS.predict(iris_data) # Finding the centroid value of the clusters cent = KMNS.cluster_centers_ # ============================================================================= # Plotting the datasets using scatter function # ============================================================================= # We can only plot 2D array so we take petal values only plt.scatter(iris_data[:,2], iris_data[:,3], c=Label, s=80) # We plot the centroid value of each clusters plt.scatter(cent[:,2], cent[:,3], marker='o', color='r') # Show the plot plt.xlabel('Petal Length(cm') plt.ylabel('Petal width(cm') plt.title("Data Visualization for K-Mean Clustering") plt.show() # ============================================================================= # Model Evaluation # ============================================================================= # To evaluate the K-Mean Cluster, we calculate the Inertia. KMNS.inertia_ # However, only one cluster value can't be enough to evaluate the entire # dataset so we evaluate the dataset with k in range 0-10 for better # results. # To store the inertia result for each iteration, we create an empty list. K_inertia = [] # Applying for loop with k in range(0,10) for i in range(1,10): KMNS = KMeans(n_clusters=i,random_state=30) KMNS.fit(iris_data) K_inertia.append(KMNS.inertia_) # Plotting the result with each value of k plt.plot(range(1,10),K_inertia,c='green',marker='o') plt.xlabel('No.of cluster(k)') plt.ylabel('Inertia') plt.title('Model Evaluation for K-Mean CLustering') plt.show() ''' DBSCAN ( Density Based Spatial Clustering od Application with Noises) ''' #Importing the DBSCAN function from sklearn.cluster import DBSCAN # Creating the model dB = DBSCAN(eps = 0.6, min_samples=4) # Fitting the model dB.fit(iris_data) # Labels for the data Label = dB.labels_ # Plotting the results plt.scatter(iris_data[:,2],iris_data[:,3],c = Label) # Show the result plt.show() ''' Herirachical Clustering ''' # Importing linkage, dendogram and fcluster from scipy.cluster.hierarchy import dendrogram, linkage, fcluster # Linkage to create model. Method can be single, complete or average hR = linkage(iris_data, method='complete') # Dendogram to plot the graph dNd = dendrogram(hR) # fcluster to find the labels Label = fcluster(hR,4, criterion='distance')
5fb865e79fe67c1071deb71c7f479c0750fc7fec
tylerashoff/mapping
/mapping.py
7,712
3.53125
4
import numpy as np class window(): # Dealing with the viewing window defined by user # Dependencies: numpy # METHODS: ## pane: finds the corners of a window around a point ## box_corner: finds the corner of a box for a point ## square_corner: finds the corner of the square " ## square_number: finds the square number " ## in_square_coords: finds the northing and easting wihtin a square ## spanner: finds the corners for all squares in the pane ## filename: finds the file in which a point resides ## pane_files: gets filenames for all squares in the pane def __init__(self, point, side_len=500): # INPUT: ## point (easting, northing) both in feet ## side length of window (optional), default: 500 self.point = point # define the desired side length self.side_len = side_len # basis defined for finding box and square corners # necessary in case plots are not defined from true 0 self.easting_basis = 2000000 self.northing_basis = 640000 pass def pane(self): # find the viewing window pane defined by user # INPUT: ## self.point (easting, northing) ### easting of center self.point (feet) ### northing of center self.point (feet) ## side length of the window (feet) # OUTPUT: ## numpy array (4x2) ## 4 coordinates of the corners of the pane ## (easting, northing) x4 left to right top to bottom easting, northing = self.point # split coords of self.point # each corner is 1/2 a side length in the easting # and 1/2 a side lenth in the northing from eachother north_west = [easting - self.side_len / 2, northing + self.side_len / 2] north_east = [easting + self.side_len / 2, northing + self.side_len / 2] south_west = [easting - self.side_len / 2, northing - self.side_len / 2] south_east = [easting + self.side_len / 2, northing - self.side_len / 2] return np.array([north_west, north_east, south_west, south_east]).astype('int') def box_corner(self): # find the south-west corner of the box # in which the self.point resides # INPUT: ## self.point (easting, northing) both in feet # OUTPUT: ## numpy array (2x1) ## box corner coordinates (easting, northing) in feet easting, northing = self.point # split coords out of self.point # round down to the nearest 10,000 feet # from basis of 2,000,000 down_to = 10000 corner_easting = np.floor((easting - self.easting_basis) / down_to) * down_to + self.easting_basis # round down to the nearest 1,000 feet # from basis of 66,000 down_to = 10000 corner_northing = np.floor((northing - self.northing_basis) / down_to) * down_to + self.northing_basis return np.array([corner_easting, corner_northing]).astype('int') def square_corner(self): # find the south-west corner of the square in the box # in which the self.point resides # INPUT: ## self.point (easting, northing) both in feet # OUTPUT: ## numpy array (2x1) ## square corner coordinates (easting, northing) in feet easting, northing = self.point # split coords of self.point # round down to the nearest 2,500 feet down_to = 2500 corner_easting = np.floor((easting - self.easting_basis) / down_to) * down_to + self.easting_basis corner_northing = np.floor((northing - self.northing_basis) / down_to) * down_to + self.northing_basis return np.array([corner_easting, corner_northing]).astype('int') def square_number(self): # find the square number in which the self.point resides # INPUT: ## self.point (easting, northing) # OUTPUT: ## square number based on weird convention corner_square = self.square_corner() # find corner of the square corner_box = self.box_corner() # find corner of the box # set up array for weird naming convention num_conv = np.array([['17', '18', '19', '20'], ['13', '14', '15', '16'], ['09', '10', '11', '12'], ['05', '06', '07', '08']]) # find how many squares over the square corner is from box corner squares_loc = (corner_square - corner_box) / 2500 easting_squares, northing_squares = squares_loc.astype('int') # backwards because indexes rows then cols square_number = num_conv[northing_squares, easting_squares] return square_number def in_square_coords(self): # finds the easting and northing from the square corner # INPUT: ## self.point (easting, norhting) # OUTPUT: ## (easting, norhting) from square corner corner_square = self.square_corner() # get square corner return np.array([self.point - corner_square]).astype('int') def spanner(self): # finds all squares in the pane # INPUT: ## pane() # OUTPUT: ## numpy array of all square/box corners in the window corners = self.pane() # find the corners of the pane # find square corners for pane corner points pane_square_corns = np.array( [window(corner).square_corner() for corner in corners]) # finding the bounds of the pane nw_northing = pane_square_corns[0][1] sw_northing = pane_square_corns[2][1] sw_easting = pane_square_corns[2][0] se_easting = pane_square_corns[3][0] # find the range of square corners (+1 so its inclusive) step = 2500 easting_square_range = np.arange(sw_easting, se_easting + 1, step) northing_square_range = np.arange(sw_northing, nw_northing + 1, step) # create coordinates from the ranges of square corners mesh = np.meshgrid(easting_square_range, northing_square_range) coords = np.array([mesh[0], mesh[1]]) coord_len = coords.shape[1] * coords.shape[2] square_coords = coords.reshape(2, coord_len).T return square_coords def filename(self): # INPUT: ## self.point (easting, norhting) # OUTPUT: ## string filename where the point resides box_easting, box_northing = self.box_corner() # find corner of the box w, y = str(box_easting)[1:3] x, z = str(box_northing)[0:2] #string together name file = 'c2005_' + w + x + y + z + '_0' + self.square_number() + '.png' #return tuple #file = (box_easting, box_northing, self.square_number()) return file def pane_files(self): # find file names for points identified in pane() # INPUT: ## spanner() # OUTPUT: ## numpy array of file names of all the squares in the pane square_coords = self.spanner() # find all square corners in pane # find all file names for squares in pane files = np.array( [[window(coord).filename() for coord in square_coords]]).T return files pass # testing easting = 2050000 + 2500 # easting coordinate (feet) northing = 670000 + 7500 # northing coordinate (feet) side_len = 1000 # side length of pane (feet) point = np.array([easting, northing]) wind = window(point, side_len) files = wind.pane_files() files
ed7a9b95a047c0ad20f4fa27a32fa77c057fcbf4
kevinsantana/exercicios
/w3resource/Python Challenges (Part -1)/ex004.py
235
4.125
4
''' 4. Write a Python program to check if a number is a perfect square. Input : 9 Output : True ''' from math import sqrt numero = 256 print(True) if int(int(sqrt(numero)) * int(sqrt(numero))) == numero else print(False)
2b43d6da0e567c53c65f22fa925f96186059fd06
tcandzq/LeetCode
/BitManipulation/CountingBits.py
1,221
3.5
4
""" 题号 338 比特位计数 给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。 示例 1: 输入: 2 输出: [0,1,1] 示例 2: 输入: 5 输出: [0,1,1,2,1,2] 进阶: 给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗? 要求算法的空间复杂度为O(n)。 你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。 """ from typing import List class Solution: # 暴力解法 def countBits(self, num: int) -> List[int]: res = [] for i in range(num+1): count = 0 while i: i &= (i - 1) count += 1 res.append(count) return res # 优化后的代码 def countBits2(self, num: int) -> List[int]: res = [0] * (num + 1) for i in range(1,num+1): res[i] = res[i & (i - 1)] + 1 return res if __name__ == '__main__': num = 5 solution = Solution() print(solution.countBits2(num))
d49a728e8a0e66b155461c1e71bb02ee5c45d028
AlexRogalskiy/Duino
/getting-started-code-101/raspberrypi/led_hello/led_hello.py
711
3.625
4
# led_hello.py - blink external LED to test GPIO pins # (c) BotBook.com - Karvinen, Karvinen, Valtokari "led_hello.py - light a LED using Raspberry Pi GPIO" # Copyright 2013 http://Botbook.com */ import time # <1> import os # <2> def writeFile(filename, contents): # <3> with open(filename, 'w') as f: # <4> f.write(contents) # <5> # main print "Blinking LED on GPIO 27 once..." # <6> if not os.path.isfile("/sys/class/gpio/gpio27/direction"): # <7> writeFile("/sys/class/gpio/export", "27") # <8> writeFile("/sys/class/gpio/gpio27/direction", "out") # <9> writeFile("/sys/class/gpio/gpio27/value", "1") # <10> time.sleep(2) # seconds # <11> writeFile("/sys/class/gpio/gpio27/value", "0") # <12>
64aa0de7eff11a8e76e2d7e3d17da721ba8f060d
jatekalkotok/catdogdogcat
/animal.py
4,596
3.625
4
import pygame from os import path class Animal: """Never in my life did I think I would really make an animal class.""" def __init__(self, screen): self.cat = Head(self, screen, "cat") self.dog = Head(self, screen, "dog") self.body = Body(screen, self.cat.image.get_size()[0] + self.dog.image.get_size()[0]) self.update_body() def update_body(self): self.body.calculate_body(self.dog.rect.center, self.cat.rect.center) class Body: """ Body between the heads """ sides = ((0, 0), (0, 0)) color = (255, 238, 170) thickness_multiplier = 10 @property def thickness(self): distance = abs(self.sides[0][0] - self.sides[1][0]) if distance <= self.heads_size / 2: distance = self.heads_size / 2 return int(self.screen.get_size()[0] / distance * self.thickness_multiplier) def __init__(self, screen, heads_size): self.screen = screen self.heads_size = heads_size def calculate_body(self, start, end): self.sides = (start, end) class Head(pygame.sprite.Sprite): """One head of the animal.""" MOVE_TICK_TIME = 1 FREEZE_TICK_TIME = 20 EAT_TICK_TIME = 10 def __init__(self, animal, screen, animal_type): pygame.sprite.Sprite.__init__(self) self.animal = animal if animal_type not in ["dog", "cat"]: raise ValueError("Animal Head must be one of 'dog' or 'cat'") self.screen = screen self.animal_type = animal_type self._images = { 'alive': pygame.image.load(path.join("assets", animal_type + ".png")), 'dead': pygame.image.load(path.join("assets", animal_type + "-dead.png")), 'eat': pygame.image.load(path.join("assets", animal_type + "-eat.png")), } self.image = self._images['alive'] self.rect = self.image.get_rect() self._start_pos() self.move_ticker = 0 self._step = screen.get_size()[0] / self.image.get_size()[0] / 2 self._frozen = False self._eating = False self._freeze_ticker = 0 self._eat_ticker = 0 def _start_pos(self): """Calculate starting position for animal head""" # shortcuts [[s_w, s_h], [i_w, i_h]] = [ self.screen.get_size(), self.image.get_size() ] # what name do you give a multiplier for positioning based on what side # of the screen a thing is on? side_multiplier = 1 if self.animal_type is "cat" else 3 self.rect.x = s_w / 4 * side_multiplier - i_w / 2 self.rect.y = s_h - i_h def _other(self): if self.animal_type == "cat": return self.animal.dog if self.animal_type == "dog": return self.animal.cat return None def update(self): """Game state logic for every tick""" # TODO: call other common logic here # tick down freeze until you can move again if self._frozen: if self._freeze_ticker > 0: self._freeze_ticker -= 1 else: self._frozen = False self.image = self._images['alive'] # tick down eating face until not eating if self._eating: if self._eat_ticker > 0: self._eat_ticker -= 1 else: self._eating = False self.image = self._images['alive'] def left(self): """Step left but not into negative""" if self.move_ticker > 0: return if self._frozen: return if self.rect.move(-self._step, 0).colliderect(self._other().rect): return if self.rect.x <= 0: return self.rect.move_ip(-self._step, 0) self.move_ticker = self.MOVE_TICK_TIME def right(self): """Step right but not off the screen""" if self.move_ticker > 0: return if self._frozen: return if self.rect.move(self._step, 0).colliderect(self._other().rect): return if self.rect.x >= self.screen.get_rect().width - self.rect.width: return self.rect.move_ip(self._step, 0) self.move_ticker = self.MOVE_TICK_TIME def freeze(self): """Stop the head from moving for a while""" self._frozen = True self.image = self._images['dead'] self._freeze_ticker = self.FREEZE_TICK_TIME def eat(self): """Eat a piece of good food""" self._eating = True self.image = self._images['eat'] self._eat_ticker = self.EAT_TICK_TIME
34e6111c07f44766cd89d058eeb1cacace654ff0
ElHa07/Python
/Curso Python/Aula01/Exercicios/Exercicios01.py
205
4
4
# Exercício Python #001 - Somando dois números n1 = int(input('Digite um numero: ')) n2 = int(input('Digite outro valor: ')) s = n1 + n2 print('A soma ente {} e {} é igual a {}!' .format(n1, n2, s))
56ca97e25ff4a95fb1463e4f01b93296d7a51a04
vinsmokemau/PythonRandomExercices
/04 Comparar Numeros/comparar_numeros.py
163
3.578125
4
numero_magico = 12345679 numero_usuario = int(input('Ingresa un numero entero del 1-9')) numero_usuario *= 9 numero_magico *= numero_usuario print(numero_magico)
8514bb604dccfaf674f81c5832530efe7307393e
thibaultcallens/Informatica5
/Toets/Irrationale fuctie.py
298
3.828125
4
from math import sqrt x = (input('geef x ∈ R: ')) fx = sqrt(int(x) - 2) if int(x) == 2: print('{:.2f}'.format(int(x)) + ' is nulpunt van f') elif int(x) > 2: print(f('{:.2f}'.format(int(x)) + '=' + ' {:.f2}'.format(fx))) else: print('{:.2f}'.format(int(x)) + ' ∉ dom(f)')
261f43532082d4b35793d9b5e045e6ca041c31f7
Manuel-00/edd_1310_2021
/Tarea #9/cola_no_acotada.py
710
3.71875
4
class PriorityQueue: def __init__(self): self.__data = list() def is_empty(self): return len(self.__data) == 0 def length(self): return len(self.__data) def enqueue(self, valor : str, priorida: int) -> None: self.__data.append((valor, priorida)) self.__data = self.order(self.__data) def dequeue(self): if not is_empty(): return self.__data.pop(0) else: return None def order (self, cola): return sorted(cola, key=lambda v: v[1]) def to_string(self): cl = "" for elem in self.__data: cl = cl + "| " + str(elem) cl = cl + "| " return cl
20787d420126c64906285810ddea417202e4ae56
tektite00/cs50
/pset6/sentimental/cash/cash.py
1,008
4
4
""" cash.py is python program that calculates the minimum number of coins required to give a user change, contrast it with cash.c implementation. USAGE: ``` $ python cash.py Change owed: 0.41 4 $ python cash.py Change owed: -0.41 Change owed: -0.41 Change owed: foo Change owed: 0.41 4 ``` """ from cs50 import get_float def main(): # Prompt user for change while True: change = get_float("Change owed: ") change = int(round(change * 100)) # Check input is valid, break out if it is if change > 0: break print("Change is: ", change) # Currency dictionary where values are in pennies currency = { "quarter": 25, "dime": 10, "nickle": 5, "penny": 1 } # No. of coins coins = 0 # Loop greedily beginning for key in currency: coins += change // currency[key] change %= currency[key] # Print no. of coins print(f"{coins}") if __name__ == "__main__": main()
e4c337569c72af35e4b455ca233f1a21f3a92984
olohard/Pong-game
/enemy.py
654
3.5
4
import pygame class Enemy(object): def __init__(self, screen): self.screen = screen self.enemyX = 1180 self.enemyY = 310 self.enemyWidth = 10 self.enemyHeight = 150 # Drawing the opponent def drawEnemy(self): pygame.draw.rect(self.screen, (255,255,255), pygame.Rect(self.enemyX, self.enemyY, self.enemyWidth, self.enemyHeight)) # Moving the opponent def moveEnemy(self): key = pygame.key.get_pressed() if key[pygame.K_UP] and self.enemyY > 100: self.enemyY -= 10 elif key[pygame.K_DOWN] and self.enemyY < 580: self.enemyY +=10
9f9f98dc820bbf75b3b005460f40984812533217
VincentLeal/PythonESGI
/venv/DeuxiemeBreakPoint.py
844
3.953125
4
#Question 6 temp = str(input("Saisir une chaine de caractères")) boolA = False boolB = False for i in range(len(temp)): if temp[i] == "@": boolA = True if boolA and temp.endswith(".com"): print("Email valide") else: print("Email invalide") #Question 7 for i in range(10): print("Message") #Question 8 for l in "String": print(l) #Question 9 a = 0 b = 10 for i in range(b - 1): a = a+1 print("a = " + str(a)) #Question 10 for i in range(10): print(b-i) #Question 11 temp = int(-1) print(temp) while temp > 10 or temp < 0: temp = int(input("Saisir un chiffre")) #Question 12 for c in "bonjour" : print(c) for item in ["ok", "nok", "rip"]: print(item) #Question 13 for i in range(14): if i != 0 and i % 3 == 0: print(i) #Question 14 temp = int(input("Saisir un chiffre"))
4e78e11951560ac56d27554ef25531c3626c0a42
YisongShen1995/machine-learning-algorithm
/utils.py
5,733
3.578125
4
from typing import List import numpy as np def mean_squared_error(y_true: List[float], y_pred: List[float]) -> float: assert len(y_true) == len(y_pred) y_true,y_pred=np.array(y_true),np.array(y_pred) return np.mean((y_true-y_pred)**2) raise NotImplementedError def f1_score(real_labels: List[int], predicted_labels: List[int]) -> float: """ f1 score: https://en.wikipedia.org/wiki/F1_score """ assert len(real_labels) == len(predicted_labels) #print(len(real_labels)) tp=0.0 fp=0.0 fn=0.0 tn=0.0 for i in range (0,len(real_labels)): if real_labels[i]==predicted_labels[i]: if predicted_labels[i]>0: tp=tp+1.0 #print(tp) else: tn=tn+1.0 #print(tn) else: if predicted_labels[i]>0: fp=fp+1.0 #print(fp) else: fn=fn+1.0 #print(fn) #print(i) #print(tp) #print(fp) F1=2*tp/(2*tp+fn+fp) return F1 raise NotImplementedError def polynomial_features( features: List[List[float]], k: int ) -> List[List[float]]: A=np.array(features) #print(A) #print(k) for i in range (1,k+1): #print(i) if i==1: X=A else: X = np.c_[X,A**i] #print(X) return X.astype(float).tolist() raise NotImplementedError def euclidean_distance(point1: List[float], point2: List[float]) -> float: point1=np.array(point1) point2=np.array(point2) dis=np.sqrt(np.sum((point1-point2)**2)) #print(dis) return dis.astype(float).tolist() raise NotImplementedError def inner_product_distance(point1: List[float], point2: List[float]) -> float: point1=np.array(point1) point2=np.array(point2) dis=np.dot(point1.T,point2) return dis.astype(float).tolist() raise NotImplementedError def gaussian_kernel_distance( point1: List[float], point2: List[float] ) -> float: point1=np.array(point1) point2=np.array(point2) dis=-np.exp(-np.sum((point1-point2)**2)/2.0) return dis.astype(float).tolist() raise NotImplementedError class NormalizationScaler: def __init__(self): pass def __call__(self, features: List[List[float]]) -> List[List[float]]: """ normalize the feature vector for each sample . For example, if the input features = [[3, 4], [1, -1], [0, 0]], the output should be [[0.6, 0.8], [0.707107, -0.707107], [0, 0]] """ for i in range (0,len(features)): temp=np.array(features[i]) num=np.sqrt(np.sum(temp**2)) for j in range (0,len(features[i])): if num!=0: features[i][j]=features[i][j]/num return features raise NotImplementedError class MinMaxScaler: """ You should keep some states inside the object. You can assume that the parameter of the first __call__ must be the training set. Note: 1. you may assume the parameters are valid when __call__ is being called the first time (you can find min and max). Example: train_features = [[0, 10], [2, 0]] test_features = [[20, 1]] scaler = MinMaxScale() train_features_scaled = scaler(train_features) # now train_features_scaled should be [[0, 1], [1, 0]] test_features_sacled = scaler(test_features) # now test_features_scaled should be [[10, 0.1]] new_scaler = MinMaxScale() # creating a new scaler _ = new_scaler([[1, 1], [0, 0]]) # new trainfeatures test_features_scaled = new_scaler(test_features) # now test_features_scaled should be [[20, 1]] """ def __init__(self): self.w = 0 self.diff = [] self.mini = [] pass def __call__(self, features: List[List[float]]) -> List[List[float]]: """ normalize the feature vector for each sample . For example, if the input features = [[2, -1], [-1, 5], [0, 0]], the output should be [[1, 0], [0, 1], [0.333333, 0.16667]] """ if self.w == 0: self.w = 1 temp=np.array(features) maxi=temp.max(axis=0) self.mini=temp.min(axis=0) self.diff=maxi-self.mini temp=temp-self.mini temp=np.true_divide(temp,self.diff) #print(temp) elif self.w==1: temp=np.array(features) temp=np.true_divide(temp-self.mini,self.diff) return temp.astype(float).tolist() raise NotImplementedError """def normalize(features: List[List[float]]) -> List[List[float]]: normalize the feature vector for each sample . For example, if the input features = [[3, 4], [1, -1], [0, 0]], the output should be [[0.6, 0.8], [0.707107, -0.707107], [0, 0]] for i in range (0,len(features)): temp=np.array(features[i]) num=np.sqrt(np.sum(temp**2)) for j in range (0,len(features[i])): if num!=0: features[i][j]=features[i][j]/num return features raise NotImplementedError def min_max_scale(features: List[List[float]]) -> List[List[float]]: normalize the feature vector for each sample . For example, if the input features = [[2, -1], [-1, 5], [0, 0]], the output should be [[1, 0], [0, 1], [0.333333, 0.16667]] temp=np.array(features) maxi=temp.max(axis=0) mini=temp.min(axis=0) diff=maxi-mini temp=temp-mini temp=np.true_divide(temp,diff) print(temp) return temp.tolist() raise NotImplementedError """
0b5a68c0a5554c5af0d076022627a4e6cb93086a
pavel-malin/data_generation
/cubes_numbers.py
365
3.84375
4
import matplotlib.pyplot as plt x_values = list(range(1, 6)) y_valuse = [x**3 for x in x_values] plt.scatter(x_values, y_valuse, s=40) # Assigning a chart title and axis labels. plt.title("Square Numbers", fontsize=14) plt.xlabel("Value", fontsize=14) plt.ylabel("Square Numbers", fontsize=14) # Assign range for each axis. plt.axis([0, 50, 0, 150]) plt.show()
d74730b184b073d7d95d86cc0a972df6104caa3f
unkleted/Practice-Problems
/amicable_numbers.py
909
3.796875
4
# Problem 21 # # Let d(n) be defined as the sum of proper divisors of n (numbers less than n # which divide evenly into n). If d(a) = b and d(b) = a, where a!=b, then a and # b are an amicable pair and each of a and b are called amicable numbers. # # For example, the proper divisors of 220 are 1,2,4,5,10,11,20,22,44,55, and # 110 ; therefore d(220) = 284. The proper divisors of 284 are 1,2,4,71, and # 142; so d(284)=220. # # Evaluate the sum of all the amicable numbers under 10_000. from math_stuff import all_divisors def proper_divisors_sum(number): """Returns the sum of proper divisors.""" proper = sum(all_divisors(number)[:-1]) return proper ammicable = [] for a in range(1,10_000): if a in ammicable: continue b = proper_divisors_sum(a) if a == proper_divisors_sum(b) and a != b: ammicable.append(a) ammicable.append(b) print(sum(ammicable))
da6b06b149fbff310ccf4e9a9497efdddf0c9e59
dueytree/LeetCode
/Group_Anagrams.py
1,079
3.5
4
# Group Anagrams # https://leetcode.com/problems/group-anagrams/ # 애너그램은 문자열을 재배열해서 다른 뜻을 가진 단어로 바꾸는 것을 말한다. # 애너그램을 판별하는 방법은 정렬하여 비교하는 것이 가장 간단해 보인다. 정렬하는 방법은 sorted 함수를 사용해 준다. # 정렬되어 나온 값은 리스트 형태이기 때문에 join 으로 합쳐서 이 값을 키로 딕셔너리를 만들어 준다. # 만약 없는 키를 넣어줄 경우 keyerror가 생겨 에러가 나지 않도록 defaultdict()으로 정리하고, # 매번 키 여부를 확인하지 않고 간단하게 해결한다. import collections def groupAnagrams(strs): anagrams = collections.defaultdict(list) for word in strs: anagrams[''.join(sorted(word))].append(word) return anagrams.values() def test_solution(): assert groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) != [["bat"], ["nat","tan"], ["ate", "eat", "tea"]] assert groupAnagrams([""]) != [[""]] assert groupAnagrams(["a"]) != [["a"]]
f3b23337affb6353a9c7778e37c7557eec17d5a3
clhchtcjj/Algorithm
/offer/offer 33 后序遍历二叉树.py
1,024
3.875
4
# -*- coding:utf-8 -*- __author__ = 'CLH' class Solution: def VerifySquenceOfBST(self, sequence): # write code here if len(sequence) == 0: return False else: return self.isVerifySquenceOfBST(sequence) def isVerifySquenceOfBST(self,sequence): if len(sequence) == 1: return True elif len(sequence) == 0: return True else: root = sequence[-1] left = [] right = [] for i in range(len(sequence)-2,-1,-1): if sequence[i] > root and len(left) == 0: right.append(sequence[i]) elif sequence[i] < root: left.append(sequence[i]) else: return False left.reverse() right.reverse() return self.isVerifySquenceOfBST(left) and self.isVerifySquenceOfBST(right) if __name__ == "__main__": S = Solution() print(S.VerifySquenceOfBST([]))
1b78fc866f869b9c3a8f2a19e7a66dc039f5731f
Nancy214/Python_clg
/Assignment 2/A2_Q2.py
248
4.1875
4
#Fibonacci series using recursion def fibo(n): if n <= 1: return n else: return fibo(n-1)+fibo(n-2) terms = int(input('Enter no. of terms: ')) print('Fibonacci Series:') for i in range(terms): print(fibo(i))
14eeca8ec0c50b4ceeac2229b78e9adff61342e1
rgabeflores/Data-Structures-and-Algorithms
/python/search/linear_search.py
345
3.546875
4
import random as r def linearSearch(mArray, key): for _ in mArray: if _ == key: return True return False def main(): a = [] for i in range(100): a.append(r.randint(-100,100)) a.sort() n = int(input("Enter a number: ")) print(linearSearch(a,n)) if __name__ == "__main__": main()
a7268b657ccdc5e3efbb5677ab2bbf9f998e3a1d
sumanthbodapatruni/Date_time
/inheritance_super().py
3,368
4.5
4
''' 28/4/2021 B Sumanth create two classes of birds and animals with their features read the input from user check which category it belongs display the name of category and its feature ''' query=input('Enter animal or bird name') # user input-animal name or bird name class Birds: # created a class for birds def Bird(self,query): # defining a function for birds category Bird_dict={'Crow':'Black', # dictionsry of birds with their colour 'Parrot':'Green', 'Pigeon':'White', 'Sparrow':'Brown', 'Chick':'Yellow' } for k in Bird_dict: # for loop to go through all elements of dictionary if k==query: # checking the given input is in the dictionary or not print(query +' belongs to Bird category' ) # if in the dict,,prints that it belongs to this bird category print() print(query) print(query+' colour is '+Bird_dict[query]) # printing the available bird's colour class Animals: # creating a class for animals def Domestic_Animals(self,query): # defining a function for domestic animals Domest_dict={'Dog':'Brown', # dictionary of domestic animals with their colour 'Cat':'Black', 'Sheep':'White', 'Goat':'Brown', 'Horse':'Black', } for i in Domest_dict: # for loop to go through all elements of dictionary if i==query: # checking the given input is in the dictionary or not print(query+' belongs to Domestic_Animal category') # if in the dict,,prints that it belongs to this domestic animal category print(query+ ' belongs to animal category') print() print(query) print(query+' colour is '+Domest_dict[query]) def Wild_Animals(self,query): # defining a function for wild animals Wild_dict={'Lion':'Brown', # dictionary of domestic animals with their colour 'Tiger':'Yellow', 'Bear':'Black', 'Cheetah':'Black', 'Kangaroo':'Brown'} for j in Wild_dict: # for loop to go through all elements of dictionary if j==query: # checking the given input is in the dictionary or not print(query+' belongs to Wild_Animal category') # if in the dict,,prints that it belongs to this wild animal category print() print(query) print(query+' colour is '+Wild_dict[query]) class Creatures(Animals,Birds): # create class for inherting above classes def __init__(self,query): super().Bird(query) # calling bird function from birds class super().Domestic_Animals(query) # calling Domestic animals function from animals class super().Wild_Animals(query) # calling wild animals function from animals class A=Creatures(query) # calling the creatures class
f660f1fce05aa0296976423617532102194902e7
hitu404/DataCampPython
/Importing Data in Python -Part 1/Importing data from other file types/ImportingSheets.py
602
3.875
4
Load the sheet '2004' into the DataFrame df1 using its name as a string. Print the head of df1 to the shell. Load the sheet 2002 into the DataFrame df2 using its index (0). Print the head of df2 to the shell. # Import pandas import pandas as pd # Assign spreadsheet filename: file file = '../yourFile.xlsx' # Load spreadsheet: xl xl = pd.ExcelFile(file) # Load a sheet into a DataFrame by name: df1 df1 = xl.parse('2004') # Print the head of the DataFrame df1 print(df1.head()) # Load a sheet into a DataFrame by index: df2 df2=xl.parse(0) # Print the head of the DataFrame df2 print(df2.head())
0f50acc6f6474c50fe17a245e30cb2b3b1abc45b
PauloVilarinho/algoritmos
/ListasFabio/Lista1/fabio01_q12.py
343
3.796875
4
""" Questão: Lista 1 12 Descrição: lê o salario de um trabalhador e devolve o salario com um aumento de 25% """ def main(): #entrada salario = float(input("Insira o seu salario: ")) #processamento novo_salario = salario*(1.25) #saida print("O seu novo salario é igual a %.2f" %(novo_salario)) if __name__ == '__main__': main()
22f5f42f2c1bbd7394fb8dc2d5ae63b865765de4
mehdi-ahmed/python-introduction
/loops.py
431
4
4
# While i = 0 while i <= 5: print('*' * i) i = i + 1 print('Done!') # For for item in 'Python': print(item) for item in ['Mosh', 'Mehdi', 'John']: print(item) for item in range(10): print(item) for item in range(99, 199): print(item) # step = 2 for item in range(99, 199, 2): print(item) # Nested loops - generate coordinates for x in range(4): for y in range(3): print(f'({x},{y})')
8bf9c99963ec1baac655ee9689c7ae0bb2f4f7f2
bferriman/python-learning
/examples/strings2.py
949
4.09375
4
rand_string = " this is an important string " # remove white space on left rand_string = rand_string.lstrip() # remove white space on the right rand_string = rand_string.rstrip() # remove white space from left and right rand_string = rand_string.strip() print(rand_string) # capitalize first character print(rand_string.capitalize()) # capitalize all characters print(rand_string.upper()) # make all characters lower case print(rand_string.lower()) a_list = ["Bunch", "of", "random", "words"] # concatenate list items into a string with a " " separator / delimiter print(" ".join(a_list)) # create a list from words in a string and print a_list_2 = rand_string.split() for i in a_list_2: print(i) # find num of occurances of a substring in a string print(rand_string.count("is")) # find index of a substring in a string print(rand_string.find("string")) # replace a substring print(rand_string.replace(" an ", " a marginally "))
1cc981d8552e67e17f180efbd576d9aec60a5785
IrinaStavitskaya/PyHomeWork
/lesson_1_3.py
127
3.609375
4
n = int(input('Введите число от 0 до 9')) nn = str(n) + str(n) nnn = nn + str(n) print(n + int(nn) + int(nnn))
9bc2541ed782f1a134581ca1e9d2c6885d416796
avni510/data_structures_and_algo
/src/trees/search_algorithms.py
1,208
3.671875
4
## Depth First Search ## Runtime: O(N) # traverses left -> parent -> right def inorder(tree, values = None): if values is None: values = [] if tree: inorder(tree.get_left_child(), values) values.append(tree.get_root_value()) inorder(tree.get_right_child(), values) return values # traverses parent -> left -> right def preorder(tree, values): if tree: values.append(tree.get_root_value()) preorder(tree.get_left_child(), values) preorder(tree.get_right_child(), values) return values # traverses left -> right -> parent def postorder(tree, values): if tree: postorder(tree.get_left_child(), values) postorder(tree.get_right_child(), values) values.append(tree.get_root_value()) return values ## Breadth First Search ## Runtime: O(N) def bfs(tree): current_level = [tree] values = [] while current_level: next_level = [] for subtree in current_level: values.append(subtree.data) if subtree.left: next_level.append(subtree.left) if subtree.right: next_level.append(subtree.right) current_level = next_level return values
45c719ab955e77b820f5bdf37fc96219f6a3929d
packse/Timesheet
/src/employee.py
1,002
3.9375
4
# Employee class primarily for validating entered text input data for saving class Employee: def __init__(self, name, classification): self.name = name self.classification = classification @property def name(self): return self._name @property def classification(self): return self._classification # Checks if the name doesn't contain any digits and has a length larger than 0 @name.setter def name(self, new_name): if len(new_name) > 0 and not any(i.isdigit() for i in new_name): self._name = new_name else: self._name = "" # Checks if the classification doesn't contain any digits and has a length larger than 0 @classification.setter def classification(self, new_classification): if len(new_classification) > 0 and not any(i.isdigit() for i in new_classification): self._classification = new_classification else: self._classification = ""
e3e221ab611879c9f8ae631280a6a421afff4357
a8ksh4/junk
/Python/python_class/labs/containers/dict-1.py
505
4.21875
4
""" Dicts are used to store key/value pairs. Write a function that prints out the number of occurrences of a word in a sentence. >>> num_words("The little brown fox ran fast") brown 1 fast 1 fox 1 little 1 ran 1 the 1 >>> num_words("Red sky at night, sailors delight, red sky at morning, sailor take warning") at 2 delight 1 morning 1 night 1 red 2 sailor 1 sailors 1 sky 2 take 1 warning 1 Hint: you'll want to use a dict! Double Hint: what order do you get when you loop through a dictionary? """
d31438c0d741351cc01cf956f207f86ab4d4de4a
09foxtrot/graph
/BFS_Disconected Graph.py
854
3.625
4
from collections import deque # creating a graph and then implementing BFS traversal V = int(input("enter the no. of nodes")) E = int(input("enter the no. of edges")) table={} print("enter the vertices.") for i in range(V): table[int(input())]=set() for i in range(E): s,d,w=map(int,input().split()) table[s].add(tuple((d,w))) table[d].add(tuple((s,-1*w))) # Display graph for i in table: print(i," -> ",table[i]) # BFS TRAVERSAL IMPLEMENTATION FROM HERE sn=int(input("enter the node taken as source node ")) visited={} for i in table: visited[i]=0 q=deque([]) bfs=[] visited[sn]=1 q.append(sn) while(len(q)!=0): a=q.popleft() for i in table[a]: b=i[0] if visited[b]!=1: visited[b]=1 q.append(b) bfs.append(a) print(bfs)
efb74d0db86d18808dc091b83910fa796a3309ea
rafaelperazzo/programacao-web
/moodledata/vpl_data/10/usersdata/87/21704/submittedfiles/testes.py
239
3.625
4
# -*- coding: utf-8 -*- from __future__ import division def x(julie): if julie<0: julie=valenada return julie a=input('digitevalor de julie:') if x(a): print('julie num vale um real') else: print('julie é minha')
6d94a0212cbffcad7d881cb23eb747c9e4b9ff61
vivek-mishr/Python
/subarray3.py
377
3.515625
4
class Solution: def maxSubArray(self, A): max_ending_here = max_so_far = A[0] for number in A[1:]: max_ending_here = max(max_ending_here + number, number) max_so_far = max(max_ending_here, max_so_far) return max_so_far sol=Solution() a = [-2, -3, 4, -1, -2, 1, 5, -3] print("Maximum contiguous sum is", sol.maxSubArray(a))
2b9cd56f001a3227f1f48578da316cc52a6ff23e
SelvorWhim/competitive
/LeetCode/ContainsDuplicate.py
742
3.578125
4
# NOTE: the first solution is slower on given test cases, despite stopping immediately on finding a duplicate while the second solution goes over entire list ''' class OldSolution: # O(n) solution using Python set def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ seen = set() for i in nums: if i in seen: # amortized O(1) containment check return True seen.add(i) # amortized O(1) return False ''' class Solution: # O(n) solution using Python set def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ return len(nums) > len(set(nums))
5f3bffd9896cdcb08af7df941ad855ea80522e87
Shimada666/LeetCode
/python/020有效的括号.py
416
3.734375
4
def abc(): s='([])' if len(s) % 2 == 1:#这一步真的机智,我只会想到输入一个的状况。。。 return False d = {'{': '}', '[': ']', '(': ')'} stack = [] for i in s: # in stack if i in d: print(i) stack.append(i) else: if stack==[] or d[stack.pop()] != i: return False return stack == [] abc()
719075911d099a2dcf9676d5b51974bdaffc0b31
gPongdee/vsaProject
/proj02/proj02_01.py
654
4.25
4
# Name: # Date: # proj01: A Simple Program # This program asks the user for his/her name and age. # Then, it prints a sentence that says when the user will turn 100. # If you complete extensions, describe your extensions here! name = raw_input("Enter your name: ") age = int(raw_input("Enter your age: ")) birthday = raw_input("Has your birthday happened this year? Enter Y or N: ") if birthday == "Y": # Calculates the year that the user will be 100 year_100 = str((100 - age) + 2017) else: # Calculates the year that the user will be 100 year_100 = str((100 - age) + 2016) print name, " will turn 100 in the year ", year_100, "."
da20d51e51299e528f599e586ca6e403cbf92ea0
CarlosRodrigo/project-euler
/euler10.py
345
3.546875
4
## Project Euler - 10 ## https://projecteuler.net/problem=10 ## Summation of primes import math def is_prime(n): for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def sum_of_primes(n): sum = 2 for i in range(3, n, 2): if is_prime(i): sum += i return sum print sum_of_primes(2000000)
ff63390e7b04cb4a3b1c953970d5071004446694
raeyoungii/baekjoon
/이런저런/자료구조/11653_1.py
492
3.515625
4
import sys def prime_list(n): sieve = [True] * n m = int(n ** 0.5) for i in range(2, m + 1): if sieve[i] is True: for j in range(i + i, n, i): sieve[j] = False return [i for i in range(2, n) if sieve[i] is True] + [n] N = int(sys.stdin.readline()) PL = prime_list(N) arr = [] while N != 1: for p in PL: if N % p == 0: arr.append(p) N //= p for p in sorted(arr): print(p) # TODO: 시간복잡도
808806154096169c00347a63e277e7996e158afe
CodeInDna/Algo_with_Python
/02_Medium/11_Lavanshtein_Distance/Lavanshtein_Distance.py
1,162
3.859375
4
# ---------------------------------- PROBLEM 11 (MEDIUM) --------------------------------------# # Levenshtein Distance # Write a function that takes in two strings and returns the minimum number of edit operations that # need to be performed on the first string to obtain the second string. There are three edit operations: # insertion of a character, deletion of a character, and substitution of a character for another. # Sample input: "abc", "yabd" # Sample output: 2 (insert "y"; substitute "c" for "d") # ----------------METHOD 01---------------------# # COMPLEXITY = TIME: O(nm), SPACE: O(nm), n:num_of_rows, m:num_of_cols def levenshteinDistance(str1, str2): # edits = [[x for x in range(len(str2)+1)] for y in range(len(str1) + 1)] # for i in range(len(str1)+1): # edits[i][0] = i edits = [[x for x in range(y, len(str2)+y+1)] for y in range(len(str1) + 1)] for i in range(1, len(str1)+1): for j in range(1, len(str2)+1): if str1[i-1] == str2[j-1]: edits[i][j] = edits[i-1][j-1] else: edits[i][j] = 1 + min(edits[i-1][j-1], edits[i][j-1], edits[i-1][j]) return edits[-1][-1] # ----------------METHOD 01---------------------#
0b8a5ab4f5cc051cfc2a3b6cee233363dd74b826
dixitomkar1809/Coding-Python
/LeetCode/twoSumLessThanK.py
591
3.53125
4
# Author: Omkar Dixit # Email: omedxt@gmail.com # Link: https://leetcode.com/problems/two-sum-less-than-k/ # Time Complexity: O(n) import collections import heapq class Solution(object): def twoSumLessThanK(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort() i = 0 j = len(nums) - 1 ans = -1 while i < j: summ = nums[i] + nums[j] if summ < k: ans = max(ans, summ) i += 1 else: j -= 1 return ans
6f26461116965f7d63649aa23a384985cdc2ed57
monkeybuzinis/Python
/10.miscellaneous topic/9.py
164
4
4
""" Write a program to determine how many of the numbers between 1 and 10000 contain the digit 3 """ for i in range (1,1001): if "3" in str(i): print(i)
cc7e21dbda58b8b5b2ccd31de7af9e81ea668f38
cecilmalone/lista_de_exercicios_pybr
/2_estrutura_de_decisao/02_positivo_negativo.py
202
4.09375
4
""" 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. """ n = int(input("Informe um número: ")) if n >= 0: print('Positivo') else: print('Negativo')
eedb729463dfd06d50422221fc778400baedfd9e
JavierCuesta12/Algoritmia
/PruebasCodigo/CRA.py
340
3.65625
4
a="wall1([" for i in range(5): a=a+"'_'," a=a+"])." print(a) a="wall2([" for i in range(5): a=a+"'_'," a=a+"])." print(a) a="wall3([" for i in range(5): a=a+"'_'," a=a+"])." print(a) a="wall4([" for i in range(5): a=a+"'_'," a=a+"])." print(a) a="wall5([" for i in range(5): a=a+"'_'," a=a+"])." print(a)
66de48095015df1923a17c5750270ef82a925507
zhaocong222/python-learn
/yield.py
255
4.0625
4
#把函数当成生成器用 def fib(n): a,b,s = 0,1,0 while s < n: a,b = b,a+b s = s + 1 yield b ''' a = fib(5) print(next(a)) print(next(a)) print(next(a)) print(next(a)) print(next(a)) ''' for v in fib(5): print(v)
9d3fc624b7caf43b3d86f8bdd663462156ea40fd
ThanhNguyenThe/IE221
/main.py
3,334
3.625
4
import pygame from game.game import * from data.top3 import * pygame.init() pygame.display.set_caption('Mario 1.0') screen = pygame.display.set_mode((800,448)) click = False def main_menu(): while True: screen.fill((0, 0, 0)) message_to_screen('Main menu', white, screen, (325, 20)) mx, my = pygame.mouse.get_pos() #định vị con chuột btn1 = pygame.Rect(300, 150, 200, 30) #các hitbox ô chữ nhật để bấm vào btn2 = pygame.Rect(300, 250, 200, 30) btn3 = pygame.Rect(300, 350, 200, 30) if btn1.collidepoint(mx,my): if click: start_game(screen) if btn2.collidepoint(mx, my): if click: hall_of_fame() if btn3.collidepoint(mx, my): if click: pygame.quit() sys.exit() pygame.draw.rect(screen, (255, 0, 0), btn1) #vẽ hcn pygame.draw.rect(screen, (255, 0, 0), btn2) pygame.draw.rect(screen, (255, 0, 0), btn3) message_to_screen('Play', white, screen, (370, 150)) #set up tên lựa chọn cho các hcn message_to_screen('Ranked', white, screen, (350, 250)) message_to_screen('Quit', white, screen, (370, 350)) click = False for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: if event.button == 1: #click chuột trái click = True pygame.display.update() def hall_of_fame(): #xuất top 3 trong file data.txt """Màn hình Hall of Fame.""" running = True while running: screen.fill((0, 0, 0)) message_to_screen('Ranked', white, screen, (350, 20)) top_player = top3() if (len(top_player) == 0): message_to_screen('Nobody has been here!', white, screen, (260, 150)) elif (len(top_player) == 1): message_to_screen('Name: ' + top_player[0][0] + ' ' + 'Time: ' + str(top_player[0][1]) + 's', white, screen, (280, 150)) elif (len(top_player) == 2): message_to_screen('Name: ' + top_player[0][0] + ' ' + 'Time: ' + str(top_player[0][1]) + 's', white, screen, (280, 150)) message_to_screen('Name: ' + top_player[1][0] + ' ' + 'Time: ' + str(top_player[1][1]) + 's', white, screen, (280, 250)) else: message_to_screen('Name: ' + top_player[0][0] + ' ' + 'Time: ' + str(top_player[0][1]) + 's', white, screen, (280, 150)) message_to_screen('Name: ' + top_player[1][0] + ' ' + 'Time: ' + str(top_player[1][1]) + 's', white, screen, (280, 250)) message_to_screen('Name: ' + top_player[2][0] + ' ' + 'Time: ' + str(top_player[2][1]) + 's', white, screen, (280, 350)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False pygame.display.update() main_menu()
27d81097f77f7c3e3b392a759275386c9aba5503
arsho/Hackerrank_Python_Domain_Solutions
/BasicDataTypes/Lists.py
912
3.78125
4
""" Title : Lists Subdomain : Data Types Domain : Python Author : Ahmedur Rahman Shovon Created : 06 July 2020 Updated : 06 February 2023 Problem : https://www.hackerrank.com/challenges/python-lists/problem """ if __name__ == "__main__": N = int(input()) ar = [] for _ in range(N): command_args = input().strip().split(" ") cmd = command_args[0] if cmd == "print": print(ar) elif cmd == "sort": ar.sort() elif cmd == "reverse": ar.reverse() elif cmd == "pop": ar.pop() elif cmd == "remove": val = int(command_args[1]) ar.remove(val) elif cmd == "append": val = int(command_args[1]) ar.append(val) elif cmd == "insert": pos = int(command_args[1]) val = int(command_args[2]) ar.insert(pos, val)
aef0080a55c37d200e7514bc8200d6eb8f55dca6
Incredibleea/python-brighton
/Lecture_3/3_4.py
265
3.84375
4
def is_number(s): try: float(s) return True except ValueError: print 'Bad value' return False while True: x = raw_input("Podaj liczbe: ") if is_number(x): print x, pow(x,3) elif x == "stop": break
146e19eac26a6a8a28e4f90c3671abb4320a9602
Brevetecno/Tempo-Atual-em-Python
/tempo_atual.py
2,423
3.71875
4
from datetime import datetime from time import sleep class StartTime(): def __init__(self): # Pega tempo atual: data, ano, mês, dia, horas, minutos, segundos class DateTimeNow(): def year_now(self): # Retornar o ano atual self.dt = datetime.now() self.year = self.dt.year return self.year def month_now(self): # Retorna o mês atual self.dt = datetime.now() self.month = self.dt.month return self.month def day_now(self): # Retorna o dia atual self.dt = datetime.now() self.day = self.dt.day return self.day def hour_now(self): # Retorna a hora atual self.dt = datetime.now() self.hour = self.dt.hour return self.hour def minute_now(self): # Retorna o minuto atual self.dt = datetime.now() self.minute = self.dt.minute return self.minute def second_now(self): # Retorna os segundos atuais self.dt = datetime.now() self.second = self.dt.second return self.second def date_now(self): # Retorna a data atual self_d = self.day_now() # Pega dia atual self_m = self.month_now() # Pega mês atual self_y = self.year_now() # Pega ano atual self.date = ('{}/{}/{}'.format(self_d, self_m, self_y)) # xx/yy/zz return self.date def time_now(self): # Retorna a hora atual self.h = self.hour_now() self.m = self.minute_now() self.s = self.second_now() if self.h < 10: self.h = '0' + str(self.h) if self.m < 10: self.m = '0' + str(self.m) if self.s < 10: self.s = '0' + str(self.s) self.time = ('{}:{}:{}'.format(self.h, self.m, self.s)) return self.time while True: # Atualiza a hora no console print('-'*50) print('Horário: ', DateTimeNow().time_now()) print('Data', DateTimeNow().date_now()) sleep(1) #Iniciar StartTime()
feb8cde0b559fb949ffabcc0ca4069638c2ae606
RidvanDayanc/python-exercises
/program-3.py
162
4.09375
4
length_of_fibonacci = int(input("length of fibonacci:")) n1 = 0 n2 = 1 for x in range(length_of_fibonacci): print(n1,end=",") tt = n1 + n2 n1 = n2 n2 = tt
37191593caafe74791ae291413f3e64df276f793
huangchao20/python_test
/python_test/CreatUser.py
1,807
3.609375
4
userlist = [ ["huangdabao", "cs123456" ], ["litiedan","123"], ["zhaotieniu", "123789" ] ] state_dict = { "username":None, "login": False } def Createuser(): t = [] username = input( "用户名:" ) passwd = input( "密码:" ) t.append( username ) t.append( passwd ) print( t ) for l in userlist: if t in userlist or t[0] == l[0]: print( userlist ) print( "您注册的用户【%s】已经注册!" %t[0] ) return None else: userlist.append( t ) print( userlist ) print( "恭喜您【%s】,您已注册成功!" %t[0] ) return userlist def checkuser( func ): def checker( *args, **kwargs ): s = [] if state_dict["username"] and state_dict[ "login" ]: res = func( *args, **kwargs ) return res username = input( "XX用户名XX:" ) passwd = input( "密码:" ) s.append( username ) s.append( passwd ) for t in userlist: if s == t: res = func( *args, **kwargs ) state_dict["username"] = username state_dict["login"] = True return res elif username in t: print( "您输入的密码有误,请确认!!" ) return None elif username not in t: answer = input( "是否注册Yy:" ) if answer == "Y" or answer == "y": ret = Createuser() print("*" * 130 ) print( ret ) state_dict["username"] = username state_dict["login"] = True return ret return checker @checkuser def home( name ): print("%s,欢迎来到恶魔的世界!!" %name ) @checkuser def role( occupation ): #角色 print("亲爱的[%s]勇士,今天撸了吗?" %occupation ) @checkuser def likes( list ): #收藏 for i in list: print( "收藏有【%s】" %( i ) ) if __name__ == "__main__": home( "litiedan" ) role( "法师" ) likelist = ["篮球", "足球", "小姐姐", "娃娃" ] likes( likelist )
94860038523d7e506eade97148024d69f942b4ae
Filipe-V/python-fil
/w24a2.py
1,298
3.890625
4
#------------------------------------------------------------------------------------------ # week 2, assignment 2: count organizations using file mbox.txt as input #------------------------------------------------------------------------------------------ import sqlite3 import urllib conn = sqlite3.connect('bd1.sqlite') cur = conn.cursor() cur.execute(''' DROP TABLE IF EXISTS Counts''') cur.execute(''' CREATE TABLE Counts (org TEXT, count INTEGER)''') fname = raw_input('Enter file name: ') #if ( len(fname) < 1 ) : fname = 'mbox-short.txt' fh = open (fname) for line in fh: # print "loop for", line.strip() if not line.startswith('From: ') : continue pieces = line.split() atpos = pieces [1].find ('@') org = pieces[1] [atpos+1:] cur.execute('SELECT count FROM Counts WHERE org = ? ', (org, )) row = cur.fetchone() if row is None: cur.execute('''INSERT INTO Counts (org, count) VALUES ( ?, 1 )''', ( org, ) ) else : cur.execute('UPDATE Counts SET count=count+1 WHERE org = ?', (org, )) # https://www.sqlite.org/lang_select.html conn.commit () sqlstr = 'SELECT org, count FROM Counts ORDER BY count desc limit 10' print "Counts:" for row in cur.execute(sqlstr) : print str(row[0]), row[1] cur.close()
81d5e91a7328b93b90860ef6620e43418a785ffd
findingxvlasova/aliens
/bullet.py
786
3.59375
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self, aiSettings, screen, ship): super().__init__() self.screen = screen # Создание пули в позиции (0,0) и назначение правильной позиции. self.rect = pygame.Rect(0,0, aiSettings.bulletWidth, aiSettings.bulletHeight) self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top self.y = float(self.rect.y) self.color = aiSettings.bulletColor self.speedFactor = aiSettings.bulletSpeedFactor def update(self): self.y -= self.speedFactor self.rect.y = self.y def drawBullet(self): pygame.draw.rect(self.screen, self.color, self.rect)
f85ce5f7a119498bccafdd8df26fcf0665badfce
petermatyi/coursera
/assignment8.1.py
244
3.703125
4
fh = open('romeo.txt') lst = list() for line in fh: newWords = line.split() if not lst: lst = newWords else: for word in newWords: if word not in lst: lst.append(word) lst.sort() print lst
68d4be7a87bcd9174dae9ce1d8519a129517cbe8
jisr0703/learn-algorithm-by-writing
/Stack/4_3_valid_parentheses/valid_parentheses_bf.py
1,121
3.71875
4
from typing import List tests = { 1: "()", 2: "()[]{}", 3: "(]", 4: "([)]", 5: "{[]}", 6: "(", 7: "]", 8: "((){})" } res = { 1: True, 2: True, 3: False, 4: False, 5: True, 6: False, 7: False, 8: True } def check_result(index: int, output: int): if index > len(tests): raise RuntimeError(f'Failed to get {index}th case') return res.get(index, False) == output def isValid(s: str) -> bool: stack = [] paren_map = { ')': '(', '}': '{', ']': '[' } for ch in s: if ch not in paren_map.keys(): stack.append(ch) else: pair = stack.pop() if stack else '' if paren_map[ch] != pair: return False return len(stack) == 0 def main(): for index, input_string in tests.items(): res = isValid(input_string) if check_result(index, res): print(f'Test case {index} is correct: value {res}') else: print(f'Test case {index} is failed: value {res}') if __name__ == '__main__': main()
491e77abbafa3bc6143f19b339e36f33537b47ea
xyloguy/open-kattis
/solved/conundrum/py_conundrum.py
235
3.65625
4
count = 0 string = raw_input().upper() for i in range(len(string)): if i%3 == 0 and string[i] != 'P': count += 1 if i%3 == 1 and string[i] != 'E': count += 1 if i%3 == 2 and string[i] != 'R': count += 1 print count
f29820f664fa0c968fbfc6e6334b1bb8427b6641
Sowayi/primeNumbergen
/primeNumbers.py
839
3.671875
4
#n = raw_input ("enter the upper limit") import time def primeNumbers (n): list_Primes=[] if not isinstance(n, int): raise TypeError elif n==0: return [] elif n<0: return {"Type Error":"No primes for negatives"} elif n==1: return [1] elif n==2: return [1,2] else: list_Primes.append(1) list_Primes.append(2) for m in range (0,n+1): s = m - 1 for counter in range (2,m): r = m%counter if (r == 0): break; elif (r != 0 and counter != s): continue elif (counter == s and r > 0): list_Primes.append(m) return list_Primes startTime=time.time() print(primeNumbers (1000)) print(time.time()-startTime)
453c9442391e1af3560ece54af33825665b9477b
sripoonkodi/GUVI
/codekata/armstrong.py
110
3.53125
4
n=int(input()) r=0 t=n while(t>0): d=t%10 r+=d**3 t//=10 if n==r: print("yes") else: print("no")
413e818cbf81de1ac8a333a046ea135d8e0b8197
dinaeliza/Flask_Python_Exercise
/Python_Exercise1/common/geo_xml_parser.py
969
3.703125
4
import xml.etree.ElementTree as ET def get_element_list(xml_file): '''Get the list of devices from the xml file. ''' tree = ET.parse(xml_file) return tree.findall('devices/device') #print 'Number of elements : ', len(get_element_list('mini-schema.xml')) def list_element_names(xml_file): '''List name of all devices in the device list''' element_list = get_element_list(xml_file) for item in element_list: print(item.find('name').text) def get_element_note(xml_file, element_name): '''Get the notes for a particular device given its name from the xml file. ''' element_list = get_element_list(xml_file) for item in element_list: if item.find('name').text == element_name: return (True, item.find('notes').text) else: return (False, 'ERROR') #list_element_names('mini-schema.xml') #print get_element_note('mini-schema.xml', 'ctdina') #print get_element_note('mini-schema.xml', 'ct')
7ae55a59837b8fa075ccf7e39dd45023254bd3c7
sornaami/luminarproject
/Flow Controls/decisionmakingstmts/vote.py
157
3.875
4
#pgm to check eligiblity for vote age=int(input("enter your age")) if(age>18): print("you can vote") else: print("you are not eligible to vote")
3e434d1e8087b8e76b2666a29d08f2bfe1de45b2
iTerner/Search-Algorithms
/algorithms/ids.py
887
3.75
4
from node import Node """ The funtion runs the Depth First Search algorithm on a given problem """ def DFS_L(problem): x, y = problem.get_start() grid = problem.get_grid() limit = problem.get_limit() frontier = [Node(x, y, grid[x][y], 0, Node(x, y, 0, 0, None, ""), "")] while frontier: node = frontier.pop() if problem.is_goal(node): return node.solution() if node.get_depth() < limit: neighbors = node.update_neighbors(problem) for n in neighbors: frontier.append(n) return None """ The Iterative Depth Search algorithm """ def IDS(problem): for limit in range(2, 20): # set the new limit for the problem problem.set_limit(limit) # check if we find a solution res = DFS_L(problem) if res: return res return "no path"
e9cba63a9255df8002a1c9e77c9e6051f7959d56
anumala2/cs3b
/CS3B/aadithyaAnumalaLab6.py
1,932
4.15625
4
############################################### # CS 21B Intermediate Python Programming Lab #6 # Topics: gui # Description: This program creates a simple app # that allows the user to convert # kilometers to miles - the output # of which will show up as an analog # message. # Input: kilometers # Output: miles # Version: 3.7.0 # Development Environment: IDLE # Developer: Aadithya Anumala # Student ID: 20365071 # Date: 05/28/19 ############################################### from tkinter import * from tkinter import messagebox KILO_TO_MILE = 0.621371192 class App(Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.entrythingy = Entry() # here is the application variable self.contents = StringVar() # set it to some value self.contents.set("Enter number of kilometers") # tell the entry widget to watch this variable self.entrythingy["textvariable"] = self.contents self.hi_there = Button(self) self.hi_there["text"] = "Calculate to miles" self.hi_there["command"] = self.compute self.hi_there.pack(side = "bottom") self.quit = Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") self.entrythingy.pack() def compute(self): kilo = self.contents.get() fail = False try: kilo = float(kilo) mile = kilo*KILO_TO_MILE except: fail = True messagebox.showinfo("Answering your request", "improper input - please enter a float") if not fail: messagebox.showinfo("Answering your request", '%.2f'%(mile) + str(" miles")) root = Tk() app = App(master=root) app.mainloop()
319d6026a8a53d7a60b3cf6361e904ec03fb4224
wzce/77GRadar
/util/batch_rename.py
861
3.796875
4
# coding:utf8 import os def rename(path): i = 0 file_list = os.listdir(path) # 该文件夹下所有的文件(包括文件夹) for file_name in file_list: # 遍历所有文件 print('file: ', file_name) old_file = os.path.join(path,file_name) new_file = os.path.join(path,'2019_03_24_'+file_name) # i = i + 1 # Olddir = os.path.join(path, files); # 原来的文件路径 # if os.path.isdir(Olddir): # 如果是文件夹则跳过 # continue; # filename = os.path.splitext(files)[0]; # 文件名 # filetype = os.path.splitext(files)[1]; # 文件扩展名 # Newdir = os.path.join(path, str(i) + filetype); # 新的文件路径 os.rename(old_file, new_file) # 重命名 if __name__ == '__main__': path = 'D:\home\\20190324' rename(path)
defdba248e35c432ee3e25cf2aa5d79c83a27335
piupom/Python
/helloworld.py
1,049
4
4
print('Hello') print(" 'Hello, World!' \" \nja uudelleen") print('-------------------') print('muuttjien käsittelystä') x=4 x='neljä' print(' ',x) print('-------------------') print('laskutoimitukset') x=4 y=5 z=x*y print(z) print('-------------------') print('viittauksista') print(' ',id(x),id(y)) print('-------------------') print('printtauksista') print(' ',y,id(y), sep='') print('-------------------') print('loopeista') if 5 > 2: print("Five is greater than two!") for x in range(1,10,2): print("x:",x) # for i in range(0,10,1): # j=0 # while(j<10): # print('i ja j', str(i) , str(j)) # j += 1 print('-------------------') print('listoista') t10=[0]*10 t10=[0,1,2,3,4,5,6,7,8,9] print(t10, type(t10)) del t10[len(t10)-1] print(t10) t10.append([1,2,3]) print(t10) print(t10[9][1]) print('-------------------') print('inputtii') rivi=input('anna rivi ') print (rivi) #talletetaan komennot taulukkoon while True: rivi=input('anna komento: \n (Lopeta=l)\n') if rivi ='l' break taulu.append(rivi) print(taulu)
20c5ac1208b58fa95a9e56c21e65492108423171
Devanshi1803/Socket-Programming
/client.py
1,978
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 24 16:18:18 2021 @author: devanshi """ """ 1. Write a Java program such that: i) The client program fetches user’s choice for adding two numbers, or calculating factorial of a number , or finding binary of a decimal input. As per choice user input is also fetched. ii) Client sends the input to the server. iii) Server calculates and returns the necessary value as per user’s choice (e.g., if user had requested for adding two numbers server will calculate sum and return it to the client) """ import socket HEADER = 99 DISCONNECT_MSG = "disconnect" FORMAT = 'utf-8' PORT = 5356 SERVER = socket.gethostbyname(socket.gethostname()) ADDR = (SERVER,PORT) #create socket socket_created = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect to server socket_created.connect(ADDR) def sendmsg(msg): message = msg.encode(FORMAT) msg_len = len(message) send_len = str(msg_len).encode(FORMAT) send_len += b' '*(HEADER-len(send_len)) socket_created.send(send_len) socket_created.send(message) print("1) Add two numbers\n2) Factorial of number\n3) Binary of decimal\n") while(1): choice = int(input("Enter your choice: ")) if choice==1: n1=int(input("Enter num1: ")) n2=int(input("Enter num2: ")) msg = ",".join([str(choice),str(n1),str(n2)]) break elif choice==2: while(1): n1=int(input("Enter number: ")) if n1>=0: break else: print("Please Enter positive number") msg = ",".join([str(choice),str(n1)]) break elif choice==3: n1=int(input("Enter number: ")) msg = ",".join([str(choice),str(n1)]) break else: print("Invalid choice") sendmsg(msg) ans = socket_created.recv(HEADER).decode(FORMAT) print("\nAnswer : "+ans) sendmsg(DISCONNECT_MSG)
03fde9b267b7227a9c9f06bf16b224be7c4cbdcd
ag-python/pyzzle
/pyzzle/text.py
2,822
3.78125
4
"""Presents text to the user""" import os import media import pyzzle from pygame.rect import * from pygame.sprite import * class Text(Sprite): """Presents text to the user""" fontFileDefault='freesansbold.ttf' fontSizeDefault=32 colorDefault=(0,0,0) def __init__(self, text, fontFile=None, fontSize=None, color=None, slide=None, rectRel=None, onClick=None, cursor=None): """Creates new Text""" if not fontFile: fontFile=Text.fontFileDefault if not fontSize: fontSize=Text.fontSizeDefault if not color: color=Text.colorDefault Sprite.__init__(self) self.slide= slide if self.slide: slide.add(self) self.text = text self.fontFile = fontFile self.fontSize = fontSize self.image= None self.rectRel = rectRel self.rect=None self.color = color self.onClick=onClick self.cursor=cursor def _getRect(self): """The coordinates of the movie. rect coordinates are determined by rectRel. If a coordinate in rectRel is None, the coordinate is determined by the slide's image size. """ if self.rectRel: slideRect=self.slide.image.get_rect() left, top, width, height=self.rectRel self.rect=Rect(left *slideRect.width +self.slide.rect.left, top *slideRect.height +self.slide.rect.top, width *slideRect.width, height *slideRect.height) if self.image: imagerect=self.image.get_rect() if not self.rect: self.rect=imagerect else: self.rect.width=imagerect.width self.rect.height=imagerect.height return self.rect def setText(self, text): self.text=text if self.image: self._loadImage() def _loadImage(self): """The image of text as presented to the user""" font=media.fonts.load(self.fontFile) self.image=font.render(self.text, False, self.color) self._getRect() def _getImage(self): self._loadImage() return self.image def draw(self, screen): """Writes the text to the screen""" text=self._getImage() textrect=self._getRect() screen.blit(text, textrect) def highlight(self): """Called when text is highlighted by the user.""" if self.cursor: pyzzle.cursor.image=media.cursors.load(self.cursor) def click(self,*param): """Called when user clicks on the text. Runs onClick() function""" if self.onClick: self.onClick()
11e9ae9955d080d3dfd3dd6b2c6d604e9863d0c9
mizsrb/cc-clique-proof
/clique-proof/clique-proof.py
1,248
3.625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # ULL - Complejidad Computacional 2018/2019 # # Main file with transformation from 3-SAT to CLIQUE import matplotlib.pyplot as plt import networkx as nx from clique import * from three_sat import ThreeSat def transform3SAT2CLIQUE(sat): G = nx.Graph() k = len(sat.clauses) for clause in range(len(sat.clauses)): for literal in sat.clauses[clause].literals: node = "C" + str(clause + 1) + "-" + literal.name if literal.value == False: node = "~" + node G.add_node(node, clause=clause, name=literal.name, value=literal.value) for i in G.nodes(data=True): for j in G.nodes(data=True): if i[1]["clause"] != j[1]["clause"]: if i[1]["name"] != j[1]["name"] or i[1]["value"] == j[1]["value"]: G.add_edge(i[0], j[0]) nx.draw(G, with_labels=True, width=2, edge_color="grey", node_color='skyblue', node_size=1500, pos=nx.circular_layout(G)) plt.show() clique = Clique(G, k) return clique ##################################################### print("Proof that CLIQUE is NP-complete") sat = ThreeSat("data/ejemplo.txt") clique = transform3SAT2CLIQUE(sat)
c15d7c9d9b4f20ca9dd896f1a1277a4be3247a7a
jcraggs/Python-Coding-Challenges
/cs50_pset2_caesar.py
3,567
4.40625
4
"""A program which ciphers a user input message by shifting unicode characters""" def main(): """Main program""" clear_text, int_scrambler, password_input = user_inputs() rev_cipher_msg = cipher_message(clear_text, int_scrambler) password_test(password_input) decipher_message(rev_cipher_msg, int_scrambler) def user_inputs():#FIRST STAGE: Getting user inputs """This function gets the user inputs""" clear_text = input("> Enter the message you want encrypted: ") password_input = input("> Enter a password (case sensitive) for your message: ") #used to set scramble amount for the message and catch any user errors while True: scrambler = input("> Enter a number between 1 and 26 to scramble your message: ") try: if 1 <= int(scrambler) <= 26: break else: print("Error_1: Number must be between 1 and 26 \n") except ValueError: print("Error_2: Input must be a number between 1 and 26 \n") # used to convert the user input from postive to negative intergers int_scrambler = int(scrambler)*-1 return clear_text, int_scrambler, password_input def cipher_message(clear_text, int_scrambler): """This function ciphers the users message""" clear_text_list = list(str(clear_text)) #converts clear_text message to a list ord_input = [] for item in clear_text_list: ord_input.append(ord(item)) #Applying the scrambler variable to the unicode numbers to cipher the data cipher_data = [] for item in ord_input: cipher_data.append(item + int_scrambler) #Printing the scrambled message cipher_msg = [] for item in cipher_data: cipher_msg.append(chr(item)) #this reverses the cipher message to add an extra level of scrambling rev_cipher_msg = cipher_msg[::-1] print("\nYour ciphered message is displayed below: \n") for item in rev_cipher_msg: print(item, end="") print() print("\n-------------------------------------------------------") return rev_cipher_msg def password_test(password_input): """This function asks the user for a password to unlock the message""" attempts = 3 #allows a max of 3 failed attempts while True: password_check = input("\n> Enter the password (case sensitive) to access this message: ") if password_input != password_check and attempts >= 0: print("Password is incorrect: " + str(attempts) + " more retry(s) left \n") attempts -= 1 if password_input == password_check: break if attempts == 0: print("\nERROR: Too many password attempts made, exiting program.") exit() def decipher_message(rev_cipher_msg, int_scrambler): """This function diciphers and then displays the user message""" print("\nYour deciphered message is displayed below: \n") decipher_data = [] for item in rev_cipher_msg: decipher_data.append(ord(item) - int_scrambler) #re-aligns to original unicode rerev_decipher_data = decipher_data[::-1]#re-reverses the message back to orignal #converts re-reversed deciphered data from unicode to ascii characters chr_decipher = [] for item in rerev_decipher_data: chr_decipher.append(chr(item)) #prints the deciphered message for item in chr_decipher: print(item, end="") if __name__ == "__main__": main()
cd9ad9f0aef617a21fe6a6fe71989e6295f89989
senthilkumaar/testcodes
/dict/dictprocess.py
682
3.59375
4
# d = {'a': {'b': {'c': {'d': {'e': 'f'},'n':'d g f'}, 'k': 'g'}}} d = {'a': {'b': {'c': {'d': {'e': 'f'}}, 'fj': {'z': 'x y q'}}}, 'k': 'g'} # d={'a':{'b':{'c':{'d':{'e':'f'}}}},'k':'g'} # d={'a': {1: {1: 2, 3: 4}, 2: {5: 6}}} def recursive(d): for key, value in d.items(): print(key) if type(value)== dict: recursive(value) else: continue # print(value) recursive(d) # dict process # # if hash(1)==hash(1.0002): # print (True) # else: # print(False) # print(hash(1),hash(1.0002)) # def argts(a,**kwargs): # print(a) # for item in kwargs: # print('args', item) # # # argts(5,c= 3)
cf6336752d4e03302247d90e0e4580d194a1c6b0
Chalmiller/competitive_programming
/python/algorithms/trees/binary_tree_cousins.py
822
3.734375
4
# 993: Cousins in Binary Tree from typing import * # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isCousins(self, root: TreeNode, x: int, y: int) -> bool: current = [root] while current: temp = [] m = {} for node in current: for child in [node.left, node.right]: if child: temp.append(child) m[child.val] = node if x not in m and y not in m: current = temp else: return not( (x not in m) or (y not in m) or (m[x] == m[y])) obj = Solution() num = obj.isCousins([1,2,3,4], 4, 3) print(num)
038249b84c19dfd191dd4589dbfd420fc8af434e
Taoge123/OptimizedLeetcode
/LeetcodeNew/python/LC_308.py
2,608
3.921875
4
""" Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Range Sum Query 2D The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. Example: Given matrix = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5] ] sumRegion(2, 1, 4, 3) -> 8 update(3, 2, 2) sumRegion(2, 1, 4, 3) -> 10 Note: The matrix is only modifiable by the update function. You may assume the number of calls to update and sumRegion function is distributed evenly. You may assume that row1 ≤ row2 and col1 ≤ col2. """ class NumMatrix: def __init__(self, matrix): m = len(matrix) if m == 0: return n = len(matrix[0]) if n == 0: return self.nums = [[0 for j in range(n)] for i in range(m)] self.BIT = [[0 for j in range(n + 1)] for i in range(m + 1)] for i in range(m): for j in range(n): self.update(i, j, matrix[i][j]) def _lowbit(self, a): return a & -a def update(self, row, col, val): m, n = len(self.nums), len(self.nums[0]) diff = val - self.nums[row][col] self.nums[row][col] = val i = row + 1 while i <= m: j = col + 1 while j <= n: self.BIT[i][j] += diff j += (self._lowbit(j)) i += (self._lowbit(i)) def getSum(self, row, col): res = 0 i = row + 1 while i > 0: j = col + 1 while j > 0: res += self.BIT[i][j] j -= (self._lowbit(j)) i -= (self._lowbit(i)) return res def sumRegion(self, row1, col1, row2, col2): return self.getSum(row2, col2) - self.getSum(row2, col1 - 1) \ - self.getSum(row1 - 1, col2) + self.getSum(row1 - 1, col1 - 1) class NumMatrix2: def __init__(self, matrix): self.tree = matrix for row in matrix: for i in range(1, len(row)): row[i] += row[i - 1] def update(self, row, col, val): row = self.tree[row] orig = row[col] - (row[col - 1] if col else 0) for i in range(col, len(row)): row[i] += val - orig def sumRegion(self, row1, col1, row2, col2): res = 0 for i in range(row1, row2 + 1): res += self.tree[i][col2] - (self.tree[i][col1 - 1] if col1 else 0) return res
28b60832e71b8779d9d4ed213c5206e139b8c175
manika1511/interview_prep
/array_and_strings/rotate_array.py
616
4.09375
4
#reverse array def reverse_array(arr, start, end): if len(arr) == 0: return None while start < end: temp = arr[start] arr[start] = arr[end] arr[end] = temp start = start + 1 end = end - 1 return arr #rotate array def rotate_array(arr, n): if n > len(arr): return arr l = len(arr) rev_arr = reverse_array(arr, 0, l-1) first = reverse_array(rev_arr, 0, l-n-1) final = reverse_array(first, l-n, l-1) return final def main(): arr = [1,2,3,4,5] print (rotate_array(arr, 5)) if __name__ == "__main__": main()
cdddff35357c320cfa6ab332d26336fa708549d1
eboladev/Study
/ProgrammingLanguage/Python/HelloWorld/Fac.py
210
3.53125
4
#! /usr/bin/env python def fac(n) : sum = 1 while n : sum *= n n -= 1 return sum def main() : for i in xrange(10) : print i, fac(i) if __name__ == "__main__" : main()
dfea25a90b98ede2b88275229ba4db0f9d3249aa
mjkloeckner/py-repo
/functions.py
244
3.703125
4
def myFuntion(): # Statements return def sayHi(name): print("Hello " + name + "!") def echoAge(age): print("You're " + age + " years old.") name = input("What's your name?: ") age = input("How old are you?: ") sayHi(name) echoAge(age)
6300d4642f4e21c73bcadec29520a9018b882b67
AaronBecker/project-euler
/euler060.py
1,416
3.828125
4
from euler_util import sieve, is_prime def concat_prime(p1, p2): if not is_prime(int(str(p1)+str(p2))): return False if not is_prime(int(str(p2)+str(p1))): return False return True def concat_primes(n, primes): for p in primes: if not concat_prime(n, p): return False return True def euler60(): """http://projecteuler.net/problem=60 The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. """ primes = sieve(10000) # turns out 10k is enough for a set of 5. for p1 in primes: for p2 in primes: if p2 <= p1 or not concat_prime(p1, p2): continue for p3 in primes: if p3 <= p2 or not concat_primes(p3, [p1, p2]): continue for p4 in primes: if p4 <= p3 or not concat_primes(p4, [p1, p2, p3]): continue for p5 in primes: if p5 <= p4 or not concat_primes(p5, [p1, p2, p3, p4]): continue return sum([p1, p2, p3, p4, p5])
4e5e01735f46e99b0d9776eb8f9473719bfe3717
Lohomi/Competitive-Programming
/31-May.py
796
3.734375
4
#Q-1 https://www.interviewbit.com/problems/fizzbuzz/ class Solution: # @param A : integer # @return a list of strings def fizzBuzz(self, A): Arr = list() Arr.append(0) for i in range(1,A+1): if(i%3==0 and i%15!=0): Arr.append('Fizz') elif(i%5==0 and i%15!=0): Arr.append('Buzz') elif(i%15==0): Arr.append('FizzBuzz') else: Arr.append(i) Arr.remove(0) return Arr #Q-2 https://www.interviewbit.com/problems/trailing-zeros-in-factorial/ class Solution: # @param A : integer # @return an integer def trailingZeroes(self, A): sum = 0 while(A!=0): sum+=A//5 A = A//5 return sum
29aa92a05a102bba0753f4b8cbba664e7b3804a0
rameshparajuli-github/python-programming
/Advance python/06_file1.py
89
3.59375
4
def greet(name): print(f"Good Morning! {name}") n=input("Enter Your Name: ") greet(n)
c5c34556a5743fc6c4bb7ffb3c4f3842ef8f606f
lizetheP/PensamientoC
/programas/LabLiz/8_strings/rapidoStrings.py
762
3.640625
4
def reemplaza_caracter(cadena, letra1, letra2): cadena2 = "" for i in range(len(cadena)): if cadena[i].lower() == letra1.lower(): cadena2 = cadena2 + letra2 else: cadena2 = cadena2 + cadena[i] return cadena2 def reemplaza_caracter2(cadena, letra1, letra2): cadena2 = "" for i in range(len(cadena)): if cadena[i] == letra1: cadena2 = cadena2 + letra2 else: cadena2 = cadena2 + cadena[i] return cadena2 def main(): cadena = str(input("Introduce una cadena: ")) letra1 = str(input("Introduce la letra 1: ")) letra2 = str(input("Introduce la letra 2: ")) cadenaf = reemplaza_caracter2(cadena, letra1, letra2) print(cadenaf) main()
3d3554fb48115e00527a0ebd20aefc83ad11edde
KanitthaKointa/CED59-5902041620016
/assignment3/practise.py
283
3.609375
4
my_list = [25,25,50] print("My List : ",my_list) print("Sum List :",sum(my_list)) my_tuple = (32,57,41,18,73,94) print("\nMy Tuple :",my_tuple) set1 = {2,1,14,5,65,78,34,55,77,9,90,91,11,12} set2 = {5,41,23,85,77,9,3,28,45,16,12} print("\nIntersection : ",set1.intersection(set2))
fb47f52f97be3f5f23c9f26d21cc699c2a246c61
duanbibo/cookbook
/cookbook/C4_iterAndGener/p04_diedaiqiepian.py
913
3.515625
4
from itertools import islice from itertools import count from operator import itemgetter ''' 对迭代对象做切片操作: islice 由于生成器和迭代器产生的数据是产生就释放的,普通的方式是不可能捕获到的, ''' def Count(n): while n>0: yield n n-=1 n=Count(20) print(n) # for i in n: # print(i,end='..') lice=islice(n,0,10) #捕获到迭代进行的第5次到第10次之间的数据,第 print(list(lice)) ''' 使用itemgeter 结合 sorted,对可迭代对象进行排序''' ''' 使用 count试下:无限生成器,生成出来的对象必须通过for循环遍历。''' c=count(5,7) for i in c: if i<100: print(i) #内部实现结果 def count1(start=0, step=1): # count(10) --> 10 11 12 13 14 ... # count(2.5, 0.5) -> 2.5 3.0 3.5 ... n = start while True: yield n n += step
3ff8d37404a0b352377bdae74c79bbee7bb77495
tawseefpatel/ECOR1051
/python/assignments/Lab 11/Lab11ex1.py
549
3.796875
4
#Step 1 point1 = [1.0,2.0] print (point1) #Step2 point1.append(3.0) print (point1) point1.pop(0) print(point1) point1.pop() print(point1) #Step3 point1 = (1.0, 2.0) print(type(point1)) print (point1) point1 = 1.0, 2.0 print(point1) #Step4 x = point1[0] y = point1[1] print (x,y) point2 = (4.0, 6.0) x,y = point2 print(x,y) #Step 5 point2[0] = 2.0 point2.appened(4.0) point2.pop(0) #Step 6 points = [(1.0,5,0), (2.0,8,0), (3.5,12,5)] point1, point2, point3 = points print (point1, point2, point3)
788b527e970cb26992cbce7504c3ce5c878263d5
YukiFujisawa/shikoku-ai-study
/hello2.py
758
4.40625
4
# num = 0 # range(stop) for num in range(5): print("hello world" + str(num)) print("# 5〜10") # range(start, stop) for num in range(5, 10): print("hello world" + str(num)) print("# 2ステップ") # range(start, stop, step) for num in range(5, 10 , 2): print("hello world" + str(num)) print("# 逆順") # range(start, stop, -step) for num in range(10, 0 , -1): print("hello world" + str(num)) # range(start, stop, -step) print("--range(start, stop, -step)") strings = "hello world" for num in range(len(strings)-1, 0 , -1): print(strings[num]) print("# list") # list(start, stop, -step) print(type(range(5))) print(type(list(range(5)))) print(list(range(5))) list1 = list(range(5)) for item in list1: print("hello world" + str(item))
e9603b80d37d43f0d183bfa12619d342452e479c
Deepkumarbhakat/Python-Repo
/Write a Python program that prints all the numbers from 0 to 6 except 3 and 6..py
171
4.25
4
#Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. for i in range (0,7): if i == 3 or i ==6: continue else: print(i)
d9ccc1c3c4ce6c773e590fba5824fe5f5d073929
karar-vir/python
/read_with_indexing.py
263
3.796875
4
#open file with indexing f=open('text.txt','r') call=f.read() #we can also use the 'readlines()' funtion for lines in call: # print(call,end='') #it will print the file of no. of lines print(lines,end='') #it will print the no of lines f.close()
17d2ea81d61115a016776aec34fbab3106fbf122
DanielRosasT/PythonForMgrs
/SecondWeekCode/FizzBuzz.py
363
3.796875
4
# FizzBuzz Challenge # by Daniel Rosas T for counter in range (1,101): if counter % 3 == 0 and counter % 5 != 0: print ("Fizz") elif counter % 5 == 0 and counter % 3 != 0: print ("Buzz") elif counter % 3 == 0 and counter % 5 == 0: print ("FizzBuzz") # elif counter % 3 != 0 and counter % 5 != 0: else: print(counter)
c4894fd8c77d9ece06584a1c32300b0384fd4378
MomomeYeah/DailyProgrammer
/hex_to_bitmap_manipulate.py
2,080
3.5625
4
# http://www.reddit.com/r/dailyprogrammer/comments/2ao99p/7142014_challenge_171_easy_hex_to_8x8_bitmap/ #FF 81 BD A5 A5 BD 81 FF #AA 55 AA 55 AA 55 AA 55 #3E 7F FC F8 F8 FC 7F 3E #93 93 93 F3 F3 93 93 93 from string import maketrans def hex_to_bitmap(hex_string): output = "" for i in hex_string.split(" "): for bit in range(8): output += "x" if (int(i, 16) << bit) & (1 << 7) else " " output += "\n" return output[:-1] def zoomIn(image, factor): output = "" for row in image.split('\n'): line = ''.join([char*factor for char in row]) output += (line+'\n')*factor return output[:-1] # [::2] - return all elements stride 2, so every other element def zoomOut(image, factor): return '\n'.join(row[::factor] for row in image.split('\n')[::factor]) def zoom(image, direction, factor): if direction == 'IN': return zoomIn(image, factor) elif direction == 'OUT': return zoomOut(image, factor) def rotate(image, direction): output = "" rows = [row for row in image.split('\n')] rowLen = len(rows) for i in range(rowLen): line = "" if direction == 'CW': for row in reversed(rows): line += row[i] if direction == 'CCW': for row in rows: line += row[rowLen-i-1] output += line+'\n' return output[:-1] def invert(image): return image.translate(maketrans('x ', ' x')) def input_and_call(image): command = raw_input("Enter command (x to quit): ") commands = command.split(' ') if commands[0] == 'x': return False elif commands[0] == 'zoom': return zoom(image, commands[1], int(commands[2])) elif commands[0] == 'invert': return invert(image) elif commands[0] == 'rotate': return rotate(image, commands[1]) else: return image def main(): hex_input = raw_input("Enter Hex Numbers: ") image = hex_to_bitmap(hex_input) while(image): print image image = input_and_call(image) main()
e08337de2a39f3d4b5379fc7d477c56d08ba859c
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4190/codes/1679_1872.py
429
3.984375
4
# Ao testar sua solução, não se limite ao caso de exemplo. x = float(input('Digite um numero para x: ')) y = float(input('digite um numero para y: ')) if (x>0 and y>0): print('Q1') elif (x<0 and y<0): print('Q3') elif (x>0 and y<0): print('Q4') elif (x<0 and y>0): print('Q2') elif ((x==0) and (y>0) or(x==0) and (y<0)): print('Eixo Y') elif ((x>0) and (y==0) or(x<0) and (y==0)): print('Eixo X') else: print('Origem')
458a64027cdc30b21ce596022bcb920caa3390cf
jerrycychen/leetcode
/204.count_primes/main.py
1,222
4.0625
4
class Solution: def countPrimes(self, n: 'int') -> 'int': # if n is less than 3 meaning there are at most 0 and 1 under consideration which are all non primes, then we return 0 immediately if n < 3: return 0 # create a Sieve of Eratosthenes table(using a list of 1's here) to record the primes and non primes primes = [True] * n # mark slots with index 0 and 1 as false cause they are not primes primes[0] = primes[1] = False # iterate through the list using index from 2 to square root of n(**0.5) because we only need to consider factors up to sqrt(n) for i in range(2, int(n ** 0.5) + 1): # start iterating from i=2, and if primes[i] = True(all entries in the list were all initialized as True), then we mark the multiples of primes[i] as non primes in the list(marking them as False) if primes[i]: primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) # and eventually the leftover True entries in the table are all prime numbers, so we sum them up and return it return sum(primes) if __name__ == '__main__': prime_count = Solution() print(prime_count.countPrimes(10))
2da176fd3639c0c32e7e9937172915de839ba4af
upasanatyagi/udacity
/photos/organize_photos.py
950
3.625
4
#!/usr/bin/env python3 # os.listdir # os.mkdir # os.rename to move files import os # os.chdir("photos") # originals = os.listdir(".") def extract_place(filename): # first = filename.find("_") # partial = filename[first+1:] # second = partial.find("_") # place = partial[:second] # return place print(filename) return filename.split("_")[1] def make_place_dictionaries(places): for place in places: os.mkdir(place) # create_directory("originals") def organise_photots(directory): places = [] os.chdir(directory) originals = os.listdir() for filename in originals: place = extract_place(filename) if place not in places: places.append(place) make_place_dictionaries(places) for filename in originals: place = extract_place(filename) os.rename(filename, os.path.join(place, filename)) directory = "photos" organise_photots(directory)
931184ae4b1d540fecb045398dfda9dd93b7d51e
AngelOfTheNight246/Curso-em-V-deo-Python
/Mundo 1/Exercícios/ex029.py
322
3.84375
4
velocidade = float(input('Qual a velocidade atual do carro ? ')) multa = float(7.00) if velocidade <= 80: print('Seu carro não está excendendo o excesso de velocidado, parabéns!') else: print('Você está acima da velocidade permitida!, Você receberá uma multa de R${:.2f}'.format((velocidade - 80) * 7))
8336630abd2c82522bdde2210cb7be8224a5ac79
marcus-aurelianus/leetcode-solutions
/questions/dot-product-of-two-sparse-vectors/Solution.py
1,828
4.125
4
''' Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. Follow up: What if only one of the vectors is sparse? Example 1: Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] Output: 8 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8 Example 2: Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2] Output: 0 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 Example 3: Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4] Output: 6 Constraints: n == nums1.length == nums2.length 1 <= n <= 10^5 0 <= nums1[i], nums2[i] <= 100 ''' ## Straight forward, use dictionary to save space by ignoring 0 value class SparseVector: def __init__(self, nums: List[int]): self.nums = {i: n for i, n in enumerate(nums) if n} # Return the dotProduct of two sparse vectors def dotProduct(self, vec: 'SparseVector') -> int: result = 0 if len(self.nums) < len(vec.nums): for key in self.nums.keys(): if key in vec.nums: result += self.nums[key] * vec.nums[key] else: for key in vec.nums.keys(): if key in self.nums: result += self.nums[key] * vec.nums[key] return result # Your SparseVector object will be instantiated and called as such: # v1 = SparseVector(nums1) # v2 = SparseVector(nums2) # ans = v1.dotProduct(v2)
79e20b0b940b8f002b93a95d18d8305bdc29049c
ashishkrb7/Type-ahead
/src/utils.py
497
3.5625
4
""" This file contains all the functions used in the model """ import re def norm_rsplit(text, n): """ Function to make the text to lower case and split it""" return text.lower().rsplit(" ", n)[-n:] def re_split(text): """ Function to find the list of words """ return re.findall("[a-z]+", text.lower()) def chunks(l, n): """ Function to make a chunk of words from the long string """ for i in range(0, len(l) - n + 1): yield l[i : i + n]
bcec5f7722034c0d2f9207470a70912e35cba4d5
suprviserpy632157/zdy
/ZDY/Jan_all/pythonbase/January0104/text0104/chenlian.py
319
3.8125
4
print('''Tom's per is a cat.\ The cat's name is "Tiechui" ''') q = int(input('number(0or1or2):')) if q == 0: print("stone") elif q == 1: print("shear") elif q == 2: print("cloth") else: pass a = 'Py' b = 'thon' c = '3' print(a+b+" "*2+c) print(a+b,c) s = input("请输入字符串:") print(len(s))
06c9e075c2114605538329ea836299d081687330
outbrain/valid_model
/valid_model/validators.py
1,321
4.0625
4
""" Basic validators which can compose other validators Any function which returns a boolean can be used as a validator. All of the defined functions other than truthy and falsey take a parameter to define a validator function. # x is not None not_identity(None) # x >= 100 or x < 20 any_of(gte(100), lt(20)) # isinstance(x, dict) and (not x or x in ['a', 'b', 'c']) all_of(is_instance(dict), any_of(falsey, is_in(['a', 'b', 'c']))) """ def truthy(value): return bool(value) def falsey(value): return not bool(value) def identity(value): return lambda x: x is value def not_identity(value): return lambda x: x is not value def is_instance(value): return lambda x: isinstance(x, value) def equals(value): return lambda x: x == value def not_equals(value): return lambda x: x != value def gt(value): return lambda x: x > value def gte(value): return lambda x: x >= value def lt(value): return lambda x: x < value def lte(value): return lambda x: x <= value def contains(value): return lambda x: value in x def not_contains(value): return lambda x: value not in x def is_in(value): return lambda x: x in value def is_not_in(value): return lambda x: x not in value def any_of(value): return lambda x: any(v(x) for v in value) def all_of(value): return lambda x: all(v(x) for v in value)
98786f2060e0fcc6e17358187b14a866b87340fd
sumioo/coding
/sort/select_sort.py
497
3.625
4
#coding:utf-8 def select_sort(L): #选择排序--选择当前值为最小值,比较当前值与剩余 n=len(L) #序列,当发现比当前值小的,把此索引值赋给min for i in range(0,n-1): #进行比较的最小值改变 min=i for j in range(i+1,n): if L[min]>L[j]: min=j if min!=i: L[i],L[min]=L[min],L[i] L=[1,9,9,1,2,3,5,4,8] select_sort(L) print L
70eb1b0fabe4a262e5f76bd07da232d6dea0a88b
HNO22/Python
/Homework5_2.py
764
4.28125
4
from random import randrange print("\n\n__________Integer Divisions__________") #The game about learning 'Integer Divisions' for kids try: play = "yes" while (play == "yes"): a = randrange(5) x = randrange(5) if (x != 0): answer = a // x print (" Integer Divisions of "+ str(a)+"/" + str(x)) guess = input (" ") if answer == int(guess): print (" CORRECT !") else: print(" INCORRECT, try again") play = input(" Do you want to play more? ") else: print(" Thanks for playing\n") except ValueError: print(" ERROR: Please enter Integers Only!\n") pass except ZeroDivisionError: print(" ERROR: progaram error, please try again\n") pass except Exception as h: print(" ERROR: Unexpected error\n") pass
91399dcecca660b5b3a0c941871016f05be9ebc0
satrini/python-study
/exercises/exercise-35.py
319
4.0625
4
# Calc from datetime import date birth = int(input("Year of birth:")) year = date.today().year years_old = year - birth if years_old <= 12: print("Mirin!") elif years_old > 12 and years_old <= 18: print("Junior!") elif years_old > 18 and years_old <= 22: print("Senior!") elif years_old > 22: print("Master!")