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
71ac0d787089fc1b308bee28a0ff3a168091a366
xandhiller/learningPython
/listToString.py
917
3.90625
4
def stringList(list1): leng = len(list1) # Get the length of list. for i in range(leng-1): print(str(list1[i]), end=' ', sep=', ') print("and " + str(list1[leng-1]), end='.\n') # alex = ['alpha', 'bravo', 'charlie', 'delta'] # stringList(alex) statement = [] # Essentially initialised the list. ...
c03921277796d919912f2d247fbd7ff8c6c786c4
eli173/escher_project
/hyp.py
3,199
3.796875
4
""" The most important function in this file is the get_cylinder function You should probably not directly use any of the other functions here. The goal of this file is to take an image of a Poincare disc and put it on the cylinder Important note: the functions here consider the input image to be a square image, wh...
eb9e459b6d701f3ebe1c0ca3cbd519a4abc2f60c
coelhudo/interview_street
/Kingdom_Connectivity/kingdom.py
2,439
3.5625
4
import sys def get_number_of_paths_between(city_source, city_destiny): class InfinitePathsException: pass #city_destiny will always be the max identifier, no need to strongly identify cicles max_connections = 1 for i in range(1, city_destiny.get_identifier()+1): max_connections = i * m...
e0857debf62e82a0580551136b7f6a4a7dc08c80
chon26909/python-oop
/basic.py
2,200
4
4
class Employee: company_name = "HiChon Company" minSalary = 10000 maxSalary = 50000 def __init__(self,name,salary,department): #private self.__name = name self.__salary = salary self.__department = department #protect def _showData(self): print("ชื...
8eb516e1b1c901b404932ad26026b194cd591058
aileentran/advent2020
/day6/day6.py
1,730
3.625
4
""" Day 6: Custom Customs input: list of list of letters; each list = 1 group. each item = answers a-z output: sum of count thoughts: turn each group into set of answers. count length of sets and sum them """ def open_file(file_name): file = open(file_name, 'r') groups = [] group = [] for line in fil...
2f7083dd95d99d65a751d744acd73b6569b7270f
sharland/python_scripts
/programs-tobesorted/functions_global.py
1,603
4.21875
4
#!f: #filename: functions.py def addition(): # x = int(input('enter x :')) # y = int(input('enter y :')) a = x + y print ('x + y = ', a) print() return def subtraction(): # x = int(input('enter x :')) # y = int(input('enter y :')) b = x - y print ...
d12fabed3df9345f4b4589833aa768c41c8684b4
ahady01/Python-Challenge
/PyBank/main.py
2,867
4.09375
4
# Import the os module and module for reading CSV files import os import csv # Path for the csv file budget_Data = os.path.join('Resources','budget_data.csv') # Lists to store Data Months = [] Profit_Losses = [] #Total_Change = [] # Variable initialisation Total_Months = 0 Total_Revenue = 0 Average_Change = 0 # ...
0bca5cb3987de4eecbad7cdc71f657ac87b06521
karinasamohvalova/OneMonth_python
/input.py
500
3.890625
4
# name = input("What is your name?") # age = int(input("How old are you?")) # #print(name) # #print(name, age) # age_in_dog_years = age * 7 # #print(f"{name} you are {age} years old") # print (f"{name} you are {age_in_dog_years} in dog years. Wow") import requests answer = input("Please enter what you want: "...
9c4f4e377ce5a87057ecf8e4324a2fc141a527c0
AlanSean/leetcode-record
/链表/138. 复制带随机指针的链表/index.py
2,090
3.578125
4
""" # Definition for a Node. """ class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random class Solution: def copyRandomList(self, head: 'Node') -> 'Node': lista,newHead = head,Node(-1) ...
2c32059171276d62abf3b7b9d71f60788659d328
AlekseyAbakumov/PythonLearn
/Scripts/Python_HSE/WEEK2/homework/solution13.py
384
4
4
a, b, c = (int(input()) for _ in range(3)) hyp = max(a, b, c) side1 = min(a, b, c) side2 = a + b + c - hyp - side1 condition = a < b + c and b < a + c and c < a + b if hyp ** 2 == side1 ** 2 + side2 ** 2 and condition: print("rectangular") elif hyp ** 2 < side1 ** 2 + side2 ** 2 and condition: print("acute") el...
e60648410297105da8958f065163fbb8a417159b
woozoo73/tf-study
/tensorflow.org/mnist.py
1,383
3.5
4
from tensorflow.examples.tutorials.mnist import input_data print("-------- one_hot=True ---------") mnist = input_data.read_data_sets("MNIST_data", one_hot=True) batch = mnist.train.next_batch(2) print(batch) batch = mnist.train.next_batch(2) print(batch) batch = mnist.train.next_batch(2) print(batch) print(batch...
775c1bae0abecd09a9ab8af0ce2565686111c6ec
allyhandro/FreshAnimatedTomatoes
/media.py
625
3.578125
4
# author: Ally Han # Class Movie implements a Movie object and holds the movie title, storyline, # poster image, and a link to the trailer import webbrowser class Movie(): # initialization / constructor def __init__ (self, movie_title, movie_storyline, poster_image, trailer_youtube): self.title = ...
ae019098295ca596bdc5d6ac3ccc5eeb2ee5a1ca
tbonino/pythonassignments
/EvenOdd Module.py
471
4.25
4
#Write your function here def EvenOdd (integer): remainder = int() remainder = integer % 2 if remainder > 0: return 'ODD' else: return 'EVEN' #Declare the variables you will need in order to call your function and print out the correct value. #Variables result = str() integer = int() #Get the input fr...
eeaafdb8bf029cf02ebf84d3d2a6bb07ea4d4b78
miumiu0917/AOJ
/ALDS1_7_D/main.py
504
3.515625
4
def reconstruction(l, r, pre, _in, result): if l >= r: return c = pre[0] del pre[0] m = _in.index(c) reconstruction(l, m, pre, _in, result) reconstruction(m+1, r, pre, _in, result) result.append(str(c)) def main(): n = int(input()) pre_order = list(map(int, input().split(' ...
f9ea0f341d9237a7902ea1350fc62182c5574867
mishimingyue/hou
/algorithm/数据结构入门/课程三:数据结构.py
952
3.765625
4
# name,age,hometown # 用一个数据来表示一个班级所有学生的信息 # 以数组or字典去存储,不同存储时,时间复杂度如何 # 数据结构是一种封装后的一种高级数据结构,封装了基本数据类型:int,string,float # a = [ ("zhangsan", 24, "beijing"), ("zhangsan", 24, "beijing"), ("zhangsan", 24, "beijing") ] # for i in a: # if a[0][0]=="zhangsan": # pass # O(n) # b = [ { "name...
a67de2b178206cf9ca42136fc59bb430765e1e76
optionalg/crack-the-coding-interview
/list-of-depths.py
4,206
4.3125
4
############################################################################### # List of Depths # # # # Given a binary tree, design an algorithm which creates a linked list of # ...
18ed63f90a5c09852f18f47faaa34f909512ffb9
marcobelo/tic_tac_toe_python
/code/coord.py
567
3.703125
4
from code.exceptions import InvalidCoord class Coord: def __init__(self, column: int, row: int): self.column = column self.row = row self._validate() def _validate(self): invalid_coords = [] if self.column not in [0, 1, 2]: invalid_coords.append("column") ...
fd6f909b7872ae2cf5c102735b70da07ddfcf40c
melpomenex/exercism-python-solutions
/python/hamming/hamming.py
227
3.953125
4
def distance(x, y): """Counts the differences in two sequences of DNA""" if len(x) != len(y): raise ValueError("The two strings are not of equal length.") return sum(1 for a,b in zip(x, y) if a != b)
bea348592d12fc098d8f3e3046790f756ac39a2b
Mukantwarivirginie/NewsHighlight
/app/models/article.py
386
3.640625
4
class Article: ''' article class to define article Objects ''' def __init__(self, author, title, description, url, urlToImage, publishedAt, content): self.author =author self.title = title self.description= description self.url =url self.urlToImage =urlToImage ...
ffca30751e90fe046815c71899f3ecdadb513c81
stacygo/2021-01_UCD-SCinDAE-EXS
/11_Unsupervised-Learning-in-Python/11_ex_3-06.py
719
3.734375
4
# Exercise 3-06: The first principal component import pandas as pd import matplotlib.pyplot as plt from sklearn.decomposition import PCA grains = pd.read_csv('input/seeds-width-vs-length.csv', header=None).values # Make a scatter plot of the untransformed points plt.scatter(grains[:, 0], grains[:, 1]) # Create a PC...
d769e9f3c70bc376ee8a43a3d7739d1e96001921
notthumann/nguyentrangan-fundametals-c4e22
/session2/homework/se4c.py
148
3.75
4
stars = ("*") for _ in range (int(9/2)): print ("x",end="") print (" ",end="") print (stars,end="") print (" ",end="") print ("x")
c110217e43be5d732e5b6c330b06275eee820942
george-mammen/IEEE-Bootcamp.py-Hackerrank
/Addition & Subtraction.py
167
4
4
""" Qs: Read two numbers and print their sum and difference. Sample Input 0 3 2 Sample Output 0 5 1 """ Code : a=int(input()) b=int(input()) print(a+b) print(a-b)
d61b18065ecace8b074f6f8d7f712a996688cf44
eflipe/python-exercises
/apunte-teorico/16 - Pilas y colas/ej_colas.py
322
3.75
4
class Cola: def __init__(self): self.items = [] def encolar(self, x): self.items.append(x) def desencolar(self): if self.esta_vacia(): raise ValueError("La cola está vacía") return self.items.pop(0) def esta_vacia(self): return len(self.items) == 0
9ab498d108722f9bf38a681794295b8bc3436a4d
Fraleym7700/cti110
/P2HW2-Turtle Graphic.py
1,070
4.4375
4
# Create an shape using python # 08/28/2019 # CTI-110 P2HW2 - Turtle Graphic # Michael Fraley #Pseudocode #import turtle #Create a circle #make turtle go up #make turtle write north #make turtle go south #Make turtle write south #bring tutrle to center #Make turtle go east #make turtle write...
ee876f3bd70cfd053d24817d7231299bf48d2730
kesaroid/Gradient-Descent-algorithm
/gradient.py
1,937
3.921875
4
# Kesar TN import pandas as pd import numpy as np import matplotlib.pyplot as plt # Function to read input def get_data(input): # Read the data.txt file using pandas data = pd.read_fwf(input) data.columns = ["non", "X1", "X2", "X3", "X4", "X5"] # Only create separate numpy arrays for X and ...
c8800ae815e0ebe08eb5cf71093d4083f65df315
gitHalowin/IBI1_2019-20
/Practical 8/RC.py
501
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 1 08:59:07 2020 @author: halowin """ import re seq='ATGCGACTACGATCGAGGGCCAT' #make original T 'disappear' result = re.sub(r'T',' ',seq) #replace A with T result = re.sub(r'A','T',result) #replace the space(original T) with A result = re.sub(r' ',...
eaf98107590f4d391482ddbbf32fa06a0bbac0ac
Social777/Exercicios
/Exercicio_48.py
273
3.75
4
# Leia um valor em segundos e imprima-o em horas, minutos e segundos. segundo = int(input('\nDigite a quantidade de segundos: ')) hora = segundo / 3600 minuto = segundo / 60 print(f'\nAgora são {hora.__int__()} horas, {minuto.__int__()} minutos e {segundo} segundos')
46e5c37b6d13357053082ee389775c3041063b47
boini-ramesh408/week1_fellowship_peograms
/utility/pythonUtil.py
10,947
4.3125
4
#########################Basic core programs########################### # string template program import time def string_template(username): text = "hii <<userName>> ,how are you" # hii ramesh how are you result = re.sub("<<userName>>", username, text) # replace fuction has two a...
3ff562dacfcf904a768b817bdfb6096406fc9f10
ajpiter/PythonProTips
/DataCleaning/DataCleaning.py
338
3.5625
4
#Load Data import pandas as pd df = pd.read_csv('doc_name.csv') #Load Header df.head() #Load Tail (footer) df.tail() #Load Column Names. Column names are attributes so there are no parathesis needed. df.columns #Load shape, which is represented by (rows, columns) df.shape #Load info. Good for locating missing...
858bb2bf96cf2d41c80d451e04609d18f66eecc0
miltonleal/MAC0110_Introduction_Computer_Science_IME_USP
/Ex. do Paca/Aula 5/P_5.15.py
563
4.1875
4
''' Dada uma sequência de números inteiros (positivos e/ou negativos) terminada por zero, calcular a média dos positivos e a média dos negativos. ''' # inicia x com um valor diferente de zero x = 1 # inicia o contador e a soma contador = 0 soma = 0 # lê o próximo elemento e soma while x != 0: x = int(input("Digi...
de5a6d8c5303d0e764d064b5fdfc216e7048b302
DGMichael/sqlite_databases
/database.py
3,557
3.515625
4
#database.py import sqlite3 as lite import pandas as pd import sys import pdb #INPUT DATA: cities_tuple = (('New York City', 'NY'), ('Boston', 'MA'), ('Chicago', 'IL'), ('Miami', 'FL'), ('Dallas', 'TX'), ('Seattle', 'WA'), ('Portland', 'OR'), ('San Francisco', 'CA'), ('Los Angeles', 'C...
9cd8c68d885ee820dcaa888d65755a3cce4ec173
UsaMasa/Programming_Competition
/ProblemC/ABC148C.py
310
3.640625
4
#from fractions import gcd #A,B = map(int, input().split()) #print(A*B//gcd(A,B)) def gcd(a,b): if(a<b): b,a=a,b if(b==0): return a r = a%b if(r!=0) : a,b,r=b,r,b%r return gcd(b,r) else: return b A,B = map(int, input().split()) print(A*B//gcd(A,B))
a20546fe9b8ae20d6500419eb5336dd250d517df
agkozik/CleanPython
/data_structure/dictionaries/dictionary.py
390
3.8125
4
phonebook = { 'bob': 123, 'elise': 456, 'jon': 789, } print(phonebook) print(phonebook['jon']) phonebook['bill'] = 987 print(phonebook) phonebook['jon'] = 987 print(phonebook) phonebook[''] = 987 print(phonebook) print(phonebook.keys()) print(phonebook.values()) print(phonebook.items()) squares = {i: i * i ...
bc41a29b27e2d3ddf7c5dcfc244febdfcfb2683d
itactuk/ITT521
/clase2_scripting/calcula.py
193
3.625
4
#!/usr/bin/python import sys if len(sys.argv) < 3: print("Error. Syntaxis: calcula.py <n1> <n2>") else: a = int(sys.argv[1]) b = int(sys.argv[2]) print("El resultado es:" + str(a + b))
d8ca907cb03dad0653f6fe1994cf19b1c18b5d97
BhargaviNadendla/Python_DeepLearning
/Source/Lab1/6.py
625
4.375
4
""" Using NumPy create random vector of size 15 having only Integers in the range 0-20. Write a program to find the most frequent item/value in the vector list. Sample input:[1,2,16,14,6,5,9,9,20,19,18] Sample output:Most frequent item in the list is 9 """ import numpy as np print(np.arange(9).reshape(3,3)) array = np....
8f4de86ab22960d6b65645d7baa4a73a5501a67d
huchaoyang1991/py27_class
/py27_07day/02for循环的应用场景.py
1,044
3.5
4
""" ============================ Author:柠檬班-木森 Time:2020/2/18 20:41 E-mail:3247119728@qq.com Company:湖南零檬信息技术有限公司 ============================ """ """ - 遍历字符串 - 遍历列表 - 遍历字典 -遍历所有的键 - 遍历所有的值 - 遍历所有的键值对 """ # 遍历字符串 # s = "fghjklfvghjfghjasdf" # for i in s: # print(i) dic = {"a": 11, "b": 22, "...
8a9846184579deccef7a9e73680dc2a6482450b2
JesterRexx-ux/2-min-codes
/Grocery.py
1,409
3.890625
4
"""Grocery calculator """ class grocery: def __init__(self,dict,li): self.dict=dict self.li=li def print_men(self): self.tota=0 print('Here is your list you choose to buy-->>') for i in self.li: if i in self.dict: self.tota=self.dict[i]*...
4d3123ceb9d84291217f792d9f82cee3f43b0482
MateuszPajor/StartLearningPython
/Types.py
751
4.0625
4
import os # Dictonaries # ------------- # Dictonary method 'get' pairs = {1: 'apple', "orange": [2, 3, 4], True: False, None: "True", } print (pairs.get("orange")) print (pairs.get(7)) print (pairs.get(12345, "not in dictionary")) os.system('cls') # Tuples - krotki - it is immutable (ca...
a381df22e5c4aa54e14336297eb307ee5b0f2f60
q2806060/python-note
/day06/day06/exercise/max_min_avg.py
397
4.125
4
# 练习: # 1. 输入三个数存于列表中,打印出这三个数的最大值,最小值 # 和平均值. n1 = int(input("请输入第1个数: ")) n2 = int(input("请输入第2个数: ")) n3 = int(input("请输入第3个数: ")) L = [n1, n2, n3] zd = max(L) # 求最大值 zx = min(L) avg = sum(L)/len(L) print("最大值是:", zd) print("最小值是:", zx) print("平均值是:", avg)
31a12f6d7a4b75d416e29416f28eaf53aacd9228
Sanyarozetka/Python_lessons
/hometask/hometask_03/Greatest_whole_degree_of_two.py
1,101
3.8125
4
""" По данному натуральному числу N найдите наибольшую целую степень двойки, не превосходящую N. Выведите показатель степени и саму степень. Операцией возведения в степень пользоваться нельзя! 50 5 32 2 ** 5 = 32 10 3 8 2 ** 3 = 8 8 3 8 2 ** 3 = 8 7 ...
784aff82fcc405daff4dd655448b39dbbb6c96ac
JudyHsiao/codejam
/uva/612.py
835
3.640625
4
import io import sys import collections # Simulate the redirect stdin. if len(sys.argv) > 1: filename = sys.argv[1] inp = ''.join(open(filename, "r").readlines()) sys.stdin = io.StringIO(inp) def count_inversion(A): swap = 0 for i in range(len(A)): for j in range(i, len(A)): i...
e609419ab57459c5735e235a7f44ce9c82addb17
Miguelmargar/ucd_programming1
/practical 17/p17p3.py
496
3.84375
4
# ask user for input # set dog and cat counters #loop through user input string = input("Please enter a word: ") #set up counter for cat and dog dog = 0 cat = 0 #loop through string to check for words needed for i in range(len(string)-2): if string[i:i+3] == "dog": dog += 1 if string[i:i+3] == "cat":...
0b2349302253e75662a1834246d44367ab7f3005
TJBrunson/War
/main.py
1,584
3.859375
4
import sys from game import Game # Function to ask user for number of players def get_num_of_players(): counter = 0 while counter < 3: text = input() try: string_int = int(text) if(string_int < 5 and string_int > 1): return string_int else: ...
92dd2059c4f397727b03000a79babd63261e45ad
elemosjr/trab2_estr_dados
/main1.py
4,181
3.703125
4
#!/bin/python import random NUM_ELEMENTS = 1000 class Node: def __init__(self, value): self.value = value self.prev = None self.next = None class Stack: def __init__(self): self.first_node = None def __len__(self): i = 0 node = self.first_node while...
f7363e9c5589badcadbed3532dade9fff34b7607
TMAC135/Pracrice
/find_missing_number.py
841
3.75
4
#Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array. #Given N = 3 and the array [0, 1, 3], return 2. class Solution: # @param nums: a list of integers # @return: an integer def findMissing(self, nums): # write your code here if not nums: retur...
14094332c62fd6f36737116417c5fabba820b760
Royely08/Chatbot_project1
/Project 1 - Chatbot.py
1,538
4.1875
4
name = ('what is your name?') #Chatbot Information print('hello. I am Royely 01. I am a chatbot') print('I like animals and I love to talk about food') print ('Hi', name, 'nice to meet you') #get year information year = input('I am not very good at dates. What is the year?: ') print('Yes,I think that is co...
5bd549bb12e61ce7a7ad3aa39c21194f3e4aeca2
hudsonmalaquias/estudo
/new 1.py
7,243
4.1875
4
#criação de uma classe ''' class carro: nome = "" tipo = "" cor = "" valor = "" #criação de uma função para captar os campos da classe def descricao(self): desc_str = "%s é um tipo de %s, de cor %s e custa $%.2f dólares." % (self.nome, self.tipo, self.cor, self.valor) ...
cb42099ec4b2f7caa8e05762c329e15d1efb3cb2
stak21/holbertonschool-higher_level_programming-1
/0x01-python-if_else_loops_functions/1-last_digit.py
424
3.96875
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) if number < 0: l_num = number % -10 else: l_num = number % 10 if l_num > 5: print("Last digit of {} is {} and is greater than 5".format(number, l_num)) elif l_num == 0: print("Last digit of {} is {} and is 0".format(number, l_num)) ...
ee066004fd981ec40daf50d617e3de755106849f
yeemey/scriptingProjects
/python/mortgage.py
1,668
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 26 15:51:17 2018 functions for mortgage-related calculations @author: ymseah """ def pmi_rate(monthly_pmi, initial_loan_amt): pmi_rate = (monthly_pmi * 12)/initial_loan_amt return pmi_rate def monthly_pmi(pmi_rate, initial_loan_amt): ...
a1b2a02f0c4ad0fd2563b0476fd29cc008b0e4c5
Jung-Woo-sik/mailprograming_problem
/autocomplete_programmers.py
601
3.75
4
def make_trie(words): dic = {} for word in words: current_dict = dic for letter in word: current_dict.setdefault(letter, [0, {}]) current_dict[letter][0] +=1 current_dict = current_dict[letter][1] return dic def solution(words): answer ...
dff9efe8ad9cce2c46b7f463bb9248d3246b51e0
vokeven/CourseraPythonHSE
/Week5/Вывести в обратном порядке.py
307
4.03125
4
# Выведите элементы данного списка в обратном порядке, # не изменяя сам список. def reverseList(xList): for i in range(len(xList) - 1, -1, -1): print(xList[i], end=' ') mList = list(map(int, input().split())) reverseList(mList)
616f448f4640e5c4e1d5689a10ac891df501d56c
woshitc8535/wenxuanLiu
/Teamproject/user0108.py
4,697
3.59375
4
from datetime import datetime import os from datetime import timedelta from sprint01_yuzhen import Homework04_Zhonghua_Bao as hz def userStory01(result): """implement user story 01, dates (birth, marriage, divorce, death) should not be after the current date, verify the date checked validity, return none if...
3a5269c15a13734032a07d39ec322a9d62beb103
alexyinxuanyu/Leetcode
/ATC.py
913
3.5
4
""" chokudai redcoder """ import sys from collections import Counter one=list(input()) print(one) two=list(input()) if len(one)!=len(two): print("No") sys.exit() three=Counter(one) print(one) four=Counter(two) print(two) if len(three)!=len(four): print("No") sys.exit() print("Yes") L1=len(one) list2=lis...
c48e84b86b79995c95f04321328d1f3dd210c59b
dkippes/Python-Practicas
/Introduccion a Python/funciones-utiles.py
413
4.28125
4
#funcion print print("El numero es:", 5) print(1,2,3,4,5, sep =', ') print(1,2,3,4,5, sep ='-') print(1,2,3,4,5, sep ='-', end='') print([1,2,3,4,5]) #funcion range print("***************") for x in range(10): print(x) print("***************") for x in range(1,10,2): print(x) print("***************") for x i...
420c7e024664640de4f7a69cbb3a32a85c986cbf
JohnPaulGamo/Sample
/sample_Gamo.py
637
4.0625
4
# Declaring and initializing variables in Python #Strings Red = "Apple" Yellow = "Mango" Violet = "Grapes" Green = "Dalandan" #Numerical Values bilang_ng_prutas = 10 bilangNgPrutas = 30 kabusugan = 30 print(Red) print(Yellow) print(Violet) print(Green) print(bilang_ng_prutas) print(bilangNgPrutas) print(kabusugan)...
c5b2e4136667592fa8c5eeebc5945777dbee81c8
zzy1120716/my-nine-chapter
/ch08/optional/0129-rehashing.py
3,681
4.125
4
""" 129. 重哈希 哈希表容量的大小在一开始是不确定的。如果哈希表存储的元素太多(如超过容量的十分之一), 我们应该将哈希表容量扩大一倍,并将所有的哈希值重新安排。假设你有如下一哈希表: size=3, capacity=4 [null, 21, 14, null] ↓ ↓ 9 null ↓ null 哈希函数为: int hashcode(int key, int capacity) { return key % capacity; } 这里有三个数字9,14,21,其中21和9共享同一个位置因为它们有相同的哈希值 1(21 % 4 = 9 % 4...
ee00cfc763224a9879cbceef1b6cf7991e6a3603
bohnacker/data-manipulation
/csv-manipulation/csv-delete-columns.py
2,347
3.546875
4
from __future__ import print_function # A script to help you with manipulating CSV-files. This is especially necessary when dealing with # CSVs that have more than 65536 lines because those can not (yet) be opened in Excel or Numbers. # This script works with the example wintergames_winners.csv, which is an excerpt f...
07f0dd366b1d62f836595c12ff337ea82f7a12eb
AugustoQueiroz/ODE-Solver
/main.py
478
3.5625
4
import sys from ode_solver import ODE_Solver # Get the input file if len(sys.argv) >= 2: input_file_name = sys.argv[1] verbose = False output_file_name = None if len(sys.argv) >= 3 and (sys.argv[2].strip("\n") == "-v" or sys.argv[2].strip("\n") == "-p"): verbose = "-v" in sys.argv should_plot = "-p" in sys.ar...
215135e3cea3b51795d5931bf4a2f0f55013376f
nekaz111/djikstras-traversal
/dijkstras_test.py
7,142
4.21875
4
#Jeremiah Hsieh ICSI 502 Dijkstra's implementation #class implementation useses binary heap and adjacency list for dijkstras #current implementation uses adjacency list so probably not as efficient as it could be #also currently does not store actual shortest path data, just distance data import random import math imp...
44d4db51e288dd5b87f2a6c346eaa9c6fa12214a
CatarinaBrendel/Lernen
/curso_em_video/Module 3/exer082.py
652
4.03125
4
mylist = [] even = [] odd = [] while True: mylist.append(int(input('Give me a Number: '))) option = str(input('Do you want to add more [Y/N]? ')).strip().upper()[0] if option == 'N': break elif option != 'YN': print('You have entered an invalid input.') option = str(input('Do yo...
09b61d843f04b54d7b4053e102625f61eb2c530b
antoniobarbozaneto/Tecnicas-Avancadas-em-Python
/02_varargs_tarefa.py
422
3.953125
4
# Uso de argumentos variáveis # TODO: Defina uma função que recebe argumentos variáveis def adicao(*args): return sum(args) def main(): # TODO: Passe argumentos diferentes para o método adicao() print(adicao(5, 10, 20, 30)) print(adicao(1, 2, 3)) # TODO: Passe uma lista para o método adicao() ...
dc780ff87864daa03a01e816f6bef270f2f0aeb9
diegomscoelho/ProjectEuler
/ProjectEuler - 010.py
864
3.84375
4
#Summation of primes - Problem 10 ''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. ''' def primesome(n): from math import sqrt prime=[] num=2 while n>num: #Enquanto o tamanho da lista no atingir o n, ela no para. Comea em 2 (num)....
ddc548aef8b8b9583de80a785b1593028c70ca20
pulupigor/Python_course
/lesson_8/3.py
244
3.5
4
import random fun_list=[len,min,max,abs,round,input,open,print] calculate='' while(calculate != 'stop' and fun_list): rnd_item=random.choice(fun_list) print(rnd_item,rnd_item.__doc__) fun_list.remove(rnd_item) calculate=input()
38f6c769ffddc81da26476a2f44b6a2e626edd70
jramaswami/Advent-Of-Code-2015
/puzzle18/python/test_puzzle18.py
5,802
3.53125
4
"""Tests for puzzle 18""" import unittest import puzzle18 as p18 class TestPuzzle18(unittest.TestCase): """Tests for puzzle 18""" def test_from_string(self): """Tests for Grid.from_string()""" grid = p18.Grid(0, 0) grid_string = "...\n###\n..." expected = [[0, 0, 0], [1, 1, 1]...
c871a565d662f2ac5c349db86c27041c0294cb73
Zioq/Python_Programming_MasterClass
/chapter_2/variable.py
674
4.09375
4
#Rules for vaiable names #Python vaiable names must begin with a letter or an underscore _ character name = "Robert" age = 30 #TypeError: cannot concatenate 'str' and 'int' objects #print(name + ' is ' + age + ' years old') # Python Data Types """ numeric iterator sequence mapping file class exception """ # 3 Numer...
dfd42e97bc9291ef8dc640833d1a449e67f333e5
ChengHan111/Traditional_ML_Algorithms
/seperate of for_ and back_/back_relu.py
1,479
3.609375
4
import numpy as np def back_relu(x,y,dzdy): # define back_relu function, which is the backward propagation of relu layer # dzdx = dzdy * dydx # dydx = 1 if x>0 # dydx = 0 if x<0 x = np.array(x, dtype=float) y = np.array(y, dtype=float) dzdy = np.array(dzdy) l = np.maximum(x, 0) ...
4724380d3f3ba11dafabc454243c8db66d4ca4ed
cesarfois/Estudo_Livro_python
/#Livro_Introd-Prog-Python/cap-6/Listagem 6.48 - Verificação de uma existência numa chave.py
590
3.84375
4
print('=' * 72) print('{:=^72}'.format(' Listagem 6.48 ')) print('{:=^72}'.format(' By César J. Fois ')) print('=' * 72) print('{0:=^72}'.format(' LListagem 6.48 - Verificação de uma existência numa chave ')) print('=' * 72) print('') tabela = {"Alface": 0.45, "Batata": 1.20, "Tomate": 2....
22fe7b7ffcf9a054e75003c0f444e8a054518962
hercwey/PythonBestStudySamples
/samples/basic/list2.py
477
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: 1.0 @author: Hercwey @license: Apache Licence @contact: 29053631@qq.com @site: @software: PyCharm @file: list2.py @time: 2017/2/6 23:31 """ def extend_list(val, list=[]): list.append(val) return list list1 = extend_list(10) print(list1) # list1...
dc149c8721bdfab679db2f80b65dfba9aece93e4
ebrahimsalehi1/frontend_projects
/Python/HundredsAreTired.py
394
3.8125
4
a = str(input('')) b = str(input('')) # if a==b: # print("{} = {}".format(a,b)) # else: # print("{} {} {}".format(max(a,b),'<',min(a,b))) a1=list(a) a1.reverse() b1=list(b) b1.reverse() a2=int(''.join(a1)) b2=int(''.join(b1)) # print(a2,b2) if a2<b2: print("{} < {}".format(a,b)) if b2<a2: pr...
2aa15d3cabe823952c2e43d07ed4e6dff7b103dc
sheauyu/sapy
/src/exercise_solutions/S5_exp_avg.py
1,181
3.5625
4
""" Solution Ex. 'Exponential Averaging Filter', Chapter 'Data Filtering' """ # author: Thomas Haslwanter # date: April-2021 # Import the required packages import numpy as np import matplotlib.pyplot as plt from scipy import signal def applyLeakyIntegrator(alpha:float, x:np.ndarray) -> np.ndarray: """ ...
df1287eb463cf2777696352817a8ab4ec9bcf1c8
andreti03/S-J
/Calendario/Entregas/Primera_Entrega.py
2,124
3.984375
4
import tkinter as tk import datetime import calendar #VALORES DE LAS VARIABLES PRINCIPALES year = datetime.date.today().year month = datetime.date.today().month """ Esta funcion ubica un texto en la interfaz grafica """ def crear_calendario(): str1 = calendar.month(year,month) label1.configure(text=str1) #FUNCIO...
b7f5273bf43c7654e61cadbac6add1b6a8c4c414
yifanliu98/assignments
/CMPT 383/Julia/binary_search.py
1,130
3.75
4
import numpy as np import timeit # def binary_search (arr, begin, end, target): # if begin <= end: # mid = int(begin + (end - begin) / 2) # if arr[mid] == target: # return mid # elif arr[mid] > target: # return binary_search(arr, begin, mid-1, target) # else:...
c8aa0cee355b5bb7802c41c246a6bcfb061e4707
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/284/69619/submittedfiles/testes.py
76
3.734375
4
a=float(input('digite a: ')) b=float(input('digite b: ')) c=(a+b)/2 print(c)
df64f70619c65f7bb568f2aae377281e2b24c473
Yossarian0916/AlogrithmsSpecialization
/median_maintenance.py
1,248
3.765625
4
"""using my own implementation of priority queue""" from BinaryHeap import MaxHeap, MinHeap def median_in_time(item, heap_low, heap_high): """ find the median in a dynamic way, read the elements one by one, and then return the median of the current subarray """ if len(heap_low) == 0: heap_...
ea3bae7ff12ce9fec5d71dc73207a4c5dff6cbf3
Genius98/HackerrankContestProblem
/List Manipulation 1.py
369
4.3125
4
# Write a Python program to move all zero digits to end of a given list of numbers. def test(lst): result = sorted(lst, key=lambda x: not x) return result numbers = [3,4,0,0,0,6,2,0,6,7,6,0,0,0,9,10,7,4,4,5,3,0,0,2,9,7,1] print("\nOriginal list:") print(numbers) print("\nMove all zero digits to end of th...
d821cb27343bd57e0a240d29b337477dfbb6321a
CodyBuilder-dev/Algorithm-Coding-Test
/problems/programmers/lv1/pgs-12918-re.py
264
3.578125
4
""" 제목 : 문자열 다루기 기본 """ import re def solution(s): if len(s) != 4 and len(s) != 6 : return False if re.findall('[A-z]',s) : return False else : return True s = "123645" #print(re.findall('[a-zA-Z]',s)) print(solution(s))
7458ca6ad798497e351edcf6980299ad896420b8
hsuyuming/python_basic_recap
/class_init.py
2,786
4
4
# 類中包含了數據(屬性)以及行為(方法),但是每一個類的屬性可能都有不同的value,所以我們基本上不會在class中定義屬性 class Person: def say_hello(self): print("Hello~~~{}".format(self.name)) #如果不在類中定義屬性的話,直覺的想法可能是創建後給予屬性 p1 = Person() p1.name = "Abe" p1.say_hello() p2 = Person() p2.name = 'John' p2.say_hello() #p3 = Person() #p3.say_hello() #Traceback (...
3a42ead5a05e6b6d3e24257573ea6ebcff7de5a9
JamesMcDougallJr/CodingChallenges
/Python/BST/testbst.py
695
3.546875
4
import bst import random, time def testRandomInsert(): root = bst.Node(random.randint(0,1000)) start = time.time() for i in range(100000): bst.insert(root, random.randint(0,1000), 0) end = time.time() print('Time Elapsed: {0}\tAverage Time per insert: {1}'.format(end-start, (end-start)/100000)) def testI...
5c8a9ff85b67c92748e09f543d040a2b56885a96
matxa/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
723
3.71875
4
#!/usr/bin/python3 def text_indentation(text): if type(text) != str: raise TypeError("text must be a string") list(text) text_cpy = [] new_cpy = [] where_to_add_new_line = ['.', '?', ':'] for char in range(len(text)): if text[char] in where_to_add_new_line: text_cp...
8af74493404a431c4d915ebf55423c9517e8f9a8
AaronDonaldson74/Python-Notes
/conditionals.py
234
4
4
age = 50 if age < 25: print(f"I'm sorry, you need to be at least 25 years old.") elif age > 100: print(f"I'm sorry, {age} is too old to rent a car.") else: print(f"You're good to go, {age} fits in the range to rent a car.")
1098367c5dbff5ba817b17936470c28ce250c95c
jkicmal/tsp-genetic-algorithm
/src/fitness/fitnessCalculator.py
517
3.546875
4
def getPopulationFitness(distances, population): populationFitness = [] for specimen in population: fitness = getSpecimenFitness(distances, specimen) populationFitness.append(fitness) return populationFitness def getSpecimenFitness(distances, specimen): fitness = 0 specimenSize ...
2a7c62ff3f0597dbb8e43d7af10d9cc4f7d4b335
bhusalashish/DSA-1
/Data/Binary Search/Peak Element/Peak Element.py
1,564
3.78125
4
''' #### Name: Peak Element Link: [youtube](https://www.youtube.com/watch?v=OINnBJTRrMU&list=PL_z_8CaSLPWeYfhtuKHj-9MpYb6XQJ_f2&index=17) Link: [leetcode](https://leetcode.com/problems/find-peak-element/) **Brute Force**: Linear O(n) with keeping track of prev element and comparing; return when criteria match ...
a6cbfa9a159f99f2ac7d771d01f491c1b3d5686e
shenxiaoxu/leetcode
/questions/42. Trapping Rain Water/trapping.py
667
3.65625
4
''' Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. ''' class Solution: def trap(self, height: List[int]) -> int: stack, res = [], 0 for i in range(len(height)): while stack and height[i] >= h...
1c6624d4260ff755b2629ebd9fae182389461af1
Skyime/Scripting-Challenges
/digital number reader.py
1,159
3.921875
4
# conversion list numbers = [ ' _ | ||_|', ' | |', ' _ _||_ ', ' _ _| _|', ' |_| |', ' _ |_ _|', ' _ |_ |_|', ' _ | |', ' _ |_||_|', ' _ |_| _|' ] # read challenge text file, add each line into a list with no \n, then close the file chall_text ...
f5307984b7cdf602cc68e0fd808c44c37b5e7c93
ChuhanXu/LeetCode
/Amazon OA2/spiralMatrix.py
830
4.09375
4
# Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. # # Example: # # Input: 3 # Output: # [ # [ 1, 2, 3 ], # [ 8, 9, 4 ], # [ 7, 6, 5 ] # ] def generateMatrix(n): mat = [[None for _ in range(n)] for _ in range(n)] h1, h2 = 0, n-1 v1, v...
78c9c441667103169fa9a422da0832098e403597
montesinopaula/recuperatorioGit2
/programa.py
2,180
4.25
4
""" #Calcula el mayor entre dos números. #lee dos números numero1 = int (input("Ingresa el primer número: ")) numero2 = int (input("Ingresa el segundo número: ")) #Determina el número más grande if numero1> numero2: maximo = numero1 else: maximo = numero2 #Imprimir el resultado print("El máximo es: ", maximo)...
94b9491ffb71641acdc2a88bbc0abf879de5ad52
Shivang1983/Application-Oriented-Programming-Using-Python
/Addition.py
172
4.125
4
#addition of two number by taking value from user x = input("Type a number: ") y = input("Type another number: ") sum = int(x) + int(y) print("The sum is: ", sum)
08170a1019cae9e1fff41e2db462e3a3531f1e42
anyatran/school
/CG/SciPy/button_interaction_1.py
3,093
3.890625
4
""" Program name: button_interaction_1.py Objective: Using buttons to control other buttions including the button that itself was pushed. Keywords: canvas, button, validation, geometry, modify button properties ============================================================================79 Explanation: The s...
5e2a1c4df22db8c0608eefbebed858e6891fc95b
tweissm35/Engineering_4_Notebook
/Python/quadSolver.py
728
3.875
4
def quadSolve(a,b,c):#function called quadSolve that takes three inputs import math disc=b**2-4*a*c#gets the discriminant if disc < 0:#if negative print("No real roots") return ["No real roots"] elif disc == 0:#if zero return [-b/(2*a)]#r...
9a859efd9dd42f3cc6bdb54044210f10f6fb6f56
VilmaLago/Alien_Invasion
/alien/ship.py
1,936
3.703125
4
import pygame from pygame.sprite import Sprite class Ship(Sprite): '''Inicializar configurações da nave.''' def __init__(self, ai_settings, screen): '''Inicialize a nave e configure sua localização.''' super(Ship, self).__init__() self.screen = screen self.ai_settings = ai_set...
a71ac7e15a9c137aa8972a302bf4ba7456e9bb92
TokyGhoul/Coursera
/Week1/HW17.py
843
4.3125
4
''' Электронные часы показывают время в формате h:mm:ss, то есть сначала записывается количество часов (число от 0 до , потом обязательно двузначное количество минут, затем обязательно двузначное количество секунд. Количество минут и секунд при необходимости дополняются до двузначного числа нулями. С начала суток прош...
d1c1a6d00b772fa4f3f81f7bcb352c23a22945c8
green-fox/cypher-soft
/cesar_cypher.py
3,378
3.703125
4
""" part cipherdecryption """ #!/usr/bin/env python2.6 __author__ = ["Alexis Schreiber"] __credits__ = ["Alexis Schreiber"] __license__ = "GPL" __version__ = "1.0" __maintainer__ = ["Alexis Schreiber"] __status__ = "Prodcution" import string from argparse import ArgumentParser import sys TAB_ASCII = list(string.asc...
8afe2050cb699f01fc3d4ee909936bba3f19f152
nralex/Python
/2-EstruturaDeDecisao/exercício18.py
1,225
3.625
4
# Faça um Programa que peça uma data no formato dd/mm/aaaa e determine se a mesma é uma data válida. data_completa = str(input('Informe uma data: [dd/mm/aaaa] ')) valida = True dma = data_completa.split('/') # converte data_completa em uma lista data = [] for c in dma: # Conversão das strings de dma em inteiro data...
b63b8fd6829f96ecf66ea822bc92219d01b12a05
saibi/python
/tutorial/dic.py
214
3.84375
4
#!/usr/bin/env python3 tel = {'jack': 4098, 'sape':4139} tel['quido'] = 4127 print(tel) sorted(tel.keys()) a = { x: x**2 for x in (2, 4, 6) } print(a) b = dict(sape=4139, guido=4127, jack=4098) print(b)
930e148ae19dc344d62ff84c37137d587db65a2c
MrunalKotkar/PPL_Assignment
/assignment4/ppl_ass4.py
4,865
4.28125
4
#Inheritance is a mechanism that allows us to create a new class – known as child class – #that is based upon an existing class – the parent class, by adding new attributes and methods #on top of the existing class. When you do so, the child class inherits the attributes and methods of the parent class. import math ...
364cc340ed90dac0c8913f51fbf2ee039eb03169
speed676/algoritmia_2018-2019
/Israel/Entregable2/Entregable2.py
3,357
3.71875
4
from typing import * from sys import argv Folleto = Tuple[int, int, int] PosicionFolleto = Tuple[int,int,int,int] def lee_fichero_imprenta(nombreFichero: str) -> Tuple[int, List[Folleto]]: folletos = [] with open(nombreFichero) as fichero: m = int(fichero.readline()) for folleto in fichero: ...
8caa46997e1a0df8b870a465b41ca181bf44ec2b
thanmaireddy1997/Machine-Learning
/classification/test.py
309
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 25 11:27:35 2019 @author: thanmaireddy """ test = 'chandini' n = 3 if len(test) % n != 0: print("invalid") part = len(test)/3 k = 0 for i in test: if k % part == 0: pass #print ('\n') print (i) k += 1
0f085ad65d51eeee1d4a89e6d896243a00436ac1
KevinLAnthony/learn_python_the_hard_way
/ex40/ex40.2.py
620
3.640625
4
class Smashing_Pumpkins(object): def __init__(self, lyrics): self.lyrics = lyrics def play_a_song(self): for statement in self.lyrics: print(statement) today_lyrics = ["Today is the greatest", "day I've ever known", "Can't live for tomorrow", "Tomorrow's much too long"] bullet_with_butte...
eab247a90fe9c49aa973c7f1bbdfe24fbbb25dbe
Lucas-Severo/python-exercicios
/mundo01/ex011.py
565
4.0625
4
''' Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados. 1L TINTA -> 2M² ''' largura = float(input('Largura da parede: ')) altura = float(input('Altura da pared...
998fd3b9b9486101b0405fe8ed65da6727b91729
alexnaiman/Fundamentals-Of-Programming---Lab-assignments
/Laborator3-4/Laborator3-4/Model.py
331
3.703125
4
def expenseToString(expense): ''' Converts a list of form (day, sum, category) to a formated string in: expense - list of form (day, sum, category) out: string ''' return "Day: " + str(expense[0]) + " Sum: " + str(expense[1]) + " Category: " + str(expe...