blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
16ef7625d209909e66693475626eda6fd76c6e64
adwardlee/leetcode_solutions
/hash&heap/0129_lint_Rehashing.py
2,680
4.34375
4
''' Description The size of the hash table is not determinate at the very beginning. If the total size of keys is too large (e.g. size = capacity 10), we should double the size of the hash table and rehash every keys. Say you have a hash table looks like below size=3, capacity=4 [null, 21, 14, null] ↓ ↓ ...
7f5958f2814e5ae68902a21db0fc09902a4c821e
juansalvatore/algoritmos-1
/prueba_parcial/ultimo_parcial/1.py
499
4.03125
4
# 2) Escribir una funcion recursiva que reciba una lista y un parametro n, y devuelva otra # lista con los elementos de la lista replicados esa cantidad n de veces. # Por ejemplo, replicar ([1, 3, 3, 7], 2) debe devolver ([1, 1, 3, 3, 3, 3, 7, 7]) . def replicar(lista, n): nueva_lista = [] if len(lista) == 0:...
2b190e5d8945b779f243094e3a11a05354bd8f82
NagahShinawy/100-days-of-code
/day_1/varaibles.py
352
3.515625
4
from constant import DIE_DICE, UNDER_AGE from die_dice import Number number = Number(2) # number = Number("4") # is_valid = number.is_valid() num = number.to_int() num_as_literal = DIE_DICE[num] print(num, num_as_literal) print(number.is_odd()) print(number.is_even()) if num < UNDER_AGE: print("Age is under ag...
917bc6041b15f93e55dab419d5a074fe71adeca2
jashidsany/Learning-Python
/Codecademy Lesson 6 Strings/LA6.10_Strings_And_Conditionals_2.py
1,196
4.5625
5
# We can iterate through a string using in # The syntax for in is: letter in word # Here, letter in word is a boolean expression that is True if the string letter is in the string word. Here are some examples: print("e" in "blueberry") # => True print("a" in "blueberry") # => False # In fact, this method is ...
cb9867ceb042e3d4069edfa99a8ca04d4f1ec1e6
poojithayadavalli/codekata
/longest consecutive sub sequence.py
748
3.546875
4
def findLongestConseqSubseq(arr, n): x={} s=set(x) ans=0 # Hash all the array elements for ele in arr: s.add(ele) # check each possible sequence from the start # then update optimal length for i in range(n): # if current element is the starting ...
27c27346a4e5e2f6adfc8b77a2d65b0b851f56ec
CTEC-121-Spring-2020/mod-5-programming-assignment-Brandon-Clark189
/Prob-3/Prob-3.py
1,262
4.125
4
# Module 4 # Programming Assignment 5 # Prob-3.py # Brandon Norton # Input: Square feet of wall space, cost of gallons of paint # process: calculate estimate of hours and cost of job # Output: Prints estimate of hours, and cost of job # function definition from math import * # main function definition def ...
8d3b0e82a785305f90e1bc09fd0bdfc027f336f0
kah3f/python_example_solutions
/filestats.py
1,682
3.5625
4
import string class Wordstats: def __init__(self,filename): try: fin=open(filename,'r') except IOError: print "Unable to open file %s"%filename return None ignore=['the', 'of', 'and', 'to', 'a', 'in', 'be','been', 'it', 'by', 'if', 'that', 'or', 'for', 'which', 'this',...
a5e6c14e03fc9acef8372d8eb30cf608f1e9fcf5
petervdonovan/ArticlesProc
/ArticlesProc/StatsAndVisualization/Difference.py
4,499
3.90625
4
from StatsAndVisualization.visualizationUtils import zScoreToRGB import math from scipy import stats class Difference(object): """Class representation a difference between samples, described in terms of what it signifies about a difference between populations.""" def __init__(self, testStatistic, sign...
d6c1ddd88886c4d13754ba3e32223daca7648c89
mitarai1kyoshi/Python_learning
/ch01-02.py
322
3.921875
4
#变量 数据类型 name = 'Hello Python ' #//f: ,cd pwork ,python 1.py print(name.upper())#不改变name值 print(name.lower()) name_modified=name.rstrip()#去除末尾多余的空白,也可以用lstrip,strip去除开头和两端的空白 age=18 message="happy "+str(age)+"th birthday" #int to string print(message)
421c091f433be6f8f601b82e8ec6e229a64e309d
kh4r00n/SoulCodeLP
/sclp040.py
275
3.953125
4
#7) Faça um programa que leia 5 idades e mostre na tela a média das idades lidas. cont = 1 soma = 0 while cont <= 5: idade = int(input('informe a sua idade: ')) soma += idade cont += 1 media = soma / 5 print(f'A média das idades é igual a: {media}')
47855cdc6308905b15202548fe1fd5eb6beb1424
aichiko0225/Python_review
/review/review.py
7,694
4.0625
4
from collections import Iterable, Iterator import os # 高等特性 # 1. 切片 L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] L1 = L[0:3] print(L1) # 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环: r = [] n = 3 for i in range(n): r.append(L[i]) print(r) # L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。 # 如果第一个索引是0,还可以省略: L[:3] ...
9037371df54a238a0115ce69f7dd8ec65d13f07f
bonnieyan/Python
/gemstone.py
683
3.53125
4
# 复杂度是较高 def numJewelsInStones(J, S): J_length = len(J) S_length = len(S) if J_length > 50 or S_length > 50: print("字符长度超长") count = 0 for s in S: if s in J: count = count + 1 return count print(numJewelsInStones("ba", "aAAbbbb")) # 复杂度O(n) def numJewelsInStones(J...
bd5583489e640b4dbe0b19cfd65b64551b35e750
thenickforero/holbertonschool-machine_learning
/math/0x02-calculus/9-sum_total.py
479
4.09375
4
#!/usr/bin/env python3 """Module to calculate sums of i*i. """ def summation_i_squared(n): """Compute the summation of i squared (i²) by using the Faulhaber's formula. Arguments: n (int): the index or the limit of the summation. Returns: int: the summattion if the limit is valid, else...
e3739e2426ed3c909e713d3b796d9a4803016b34
ShayanRiyaz/Data-Visualization-basics
/2_CSV-File-Format/sitka_highs.py
1,114
3.640625
4
import csv import matplotlib.pyplot as plt from datetime import datetime filename = 'data/sitka_weather_2018_simple.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) # Get dates, high and low temperatures from this file. dates, highs,lows = [], [], [] ...
580c9c5fa9b21d3285c2dad01f55fc9aff5cde07
Abhay-official/Summer-Training
/Day08/Day8J.py
1,580
3.75
4
x=set('A Python Tutorial') print(x) print(type(x)) x=set(['Perl','Python','Java']) print(x) cities=set(('Paris','Lyon','London','Berlin','Paris','Birmingham')) print(cities) #cities=set(('Python','Perl'),('Paris','Berlin','London')) print(cities) cities=set(['Frankfurt','Basel','Freiburg']) print(cities) cities.add('St...
61d145c1068e99ea1efab8fc835b0216616ab33b
Android-Ale/PracticePython
/mundo3/INPUTNATUPLAVENDOPOSIÇÃO.py
509
4.09375
4
a = (int(input('Digite um número: ')), int(input('Digite outro número:')), int(input('DIgite mais um número: ')), int(input('Digite o último número: '))) print(f'Você digitou os valores {a}') print(f'O valor 9 apareceu {a.count(9)} vezes.') if 3 in a: print(f'O valor 3 aparece na posição {a.index(3)+...
7aa098ea67aa494cb4e4dfaa32b26edc84697683
bidgars/python
/lambda.py
680
3.59375
4
# lambda arguments : expression add10 = lambda x: x + 10 print(add10(1)) mult = lambda x, y: x * y print(mult(2, 7)) points = [(1, 2), (15, 1), (5, -1), (10, 4)] print(points) print(sorted(points)) points_sorted = sorted(points, key=lambda x: x[1]) print(points_sorted) points_sorted = sorted(points, key=lambda x: x...
7ed5f7e1c22f59a946078ae7d3db7ab8def02f51
professorbossini/20212_fatec_ipi_pbd_regressao_linear_simples
/regressao_linear_simples.py
1,362
3.703125
4
import numpy import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression dataset = pd.read_csv ('dados_regressao_linear_simples.csv') x = dataset.iloc[:, :-1].values # print (x) y = dataset.iloc[:, -1].values # print (y) x...
79b8eaf4ac73a82430affc499b60adc5c7710e1d
divercraig/AdventOfCode2018
/day1/puzzle1.py
669
3.765625
4
current_frequency = 0 frequency_history = {0} found_reoccurance = False while not found_reoccurance: for line in open('input.txt'): change = int(line) new_frequency = current_frequency + change print("Current Frequency is {}, change of {}, resulting frequency is {}" .format(cu...
e23c5d0da91649c8f70970fa1a9a4b5e41462ecd
slutske22/Practice_files
/python_for_js_devs/try-except.py
165
3.5
4
# %% my_dict = { "title": "Python is charming" } print(my_dict["title"]) try: print(my_dict["author"]) except KeyError: print("Anonymous Author") # %%
73862a2dd84deb27a2ddfa2b726139c208feb05c
Tim-Barton/BudgetTracker
/src/ui/cli.py
1,237
3.921875
4
def PrintCurrentCategories(categoryList): i = 1 for category in categoryList: print("{}\t{}".format(i, category)) i = i+1 def PromptForNewCategory(categoryManager): categories = categoryManager.getCategoryNames() print("Your currently configured Categories are:") PrintCurrentCateg...
745200fcaa22ab6771a20ace4343c80d8f1f2735
mhall12/SOLSTISE_Simulation
/massreader.py
7,199
3.796875
4
import re import numpy as np def readmass(reac): #reac = input("Enter a reaction of the form d(17F,p): ") # reac = 'd(28Si,p)' # firstpos grabs the position of the ( so we can get the target firstpos = reac.find('(') # target mass and symbol grabbed here target = reac[:firstpos] # splitt...
b1146a46ee78d6e521f28457012acc8c89633c4a
japnitahuja/FirstHackathonChatBot
/chatbot_respond.py
4,761
3.5625
4
import nltk, string, random #initialise user_respond="What a party pooper! There wasn't much at the party." #noise reduction/expression removal like "lah" and punctuation removal def preprocessing(input_text): def _remove_noise(input_text): lst_stop_words=open("stop_words_and_singlish.txt", "r") ...
22dd2b9e9e8df7f55ff3d0a907ecf4d37803018d
iap015/introprogramacion
/clases/imccondicionales.py
910
3.84375
4
#-----constantes-----# PREGUNTA_PESO = "cuanto pesas? : " PREGUNTA_ESTATURA = "cuanto mides en metros? : " MENSAJE_BIENVENIDA = "hola, como estas? vamos a calcular tu imc" MENSAJE_DESPEDIDA = "tu imc es ..." MENSAJE_BAJO_PESO = "estas muy delgado" MENSAJE_PESO_ADECUADO = "estas en forma" MENSAJE_SOBRE_PESO = "ten cuida...
cda4cce604475d291ab2898b7087ed50a3af4d1f
smtamh/oop_python_ex
/student_result/2019/01_number_baseball/baseball [2-5 김A].py
3,773
3.703125
4
# 숫자야구 import random def make_num(): answer = [] num = list(range(10)) # 0~9의 숫자를 리스트로 만든다 random.shuffle(num) # 리스트를 랜덤으로 섞는다 for i in range(3): answer.append(num[i]) # answer 이라는 리스트에 랜덤으로 섞은 0~9를 세개만 넣는다. return answer # 만든 answer 리스트를 리턴 def scanf(): print("입력해봐 : ", end='')...
b90889eb5de099bb1411e6a4bc6c76b9d699b92e
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/nvnjam003/boxes.py
641
4
4
def print_square(): for x in range (0, 5): if (x == 0 or x == 4): print (5*"*") else: print ("*" + 3*" " + "*") def print_rectangle(width, height): for x in range(0, height): if (x == 0 or x == (height-1)): print (width*"*") ...
a5e68b71d66be36bbdd6e829c1b3f5b5451da76e
MrHamdulay/csc3-capstone
/examples/data/Assignment_1/plsnor001/question3.py
847
3.796875
4
def intake(): first_name=input('Enter first name: \n') last_name=input('Enter last name: \n') money=eval(input('Enter sum of money in USD: \n')) country=input('Enter country name: \n') k=0.3*money def output(): print("\nDearest {0}\nIt is with a heavy heart that I inform you of th...
542fce2c695b7656cfa173bd9ba011bf6a57146e
zxbange/OldBoy
/class9/生产者消费者模型.py
603
3.546875
4
import threading,time import queue q = queue.Queue(maxsize=10) def Producer(name): count = 1 while True: q.put("骨头%s" % count) print("生产了骨头%s\n" % count) count += 1 time.sleep(1) def Consumer(name): while True: # while q.qsize() > 0: print("[%s] 取到 [%s], 并且吃了它...
1cd4dcc06656eb21bfb550411732aa5710d3cd61
flypigfish/test
/Test/hello.py
1,768
3.65625
4
def matrix_multi(): a_row=2 a_col=3 b_row=3 b_col=4 a=[[1 for row in range(a_col)] for rows in range(a_row)] b=[[2 for row in range(b_col)] for rows in range(b_row)] a[0][0]=0 b[0][1]=1 for i in range(a_row): for j in range(a_col): ...
a2e61e668a4e487a13480eda6c8f914e2f539a1e
markwatkinson/project-euler
/9.py
503
3.796875
4
""" 1) a < b < c 2) a*a + b*b = c*c 3) a + b + c = 1000 find a*b*c """ """ 2 => sqrt(a*a + b*b) = c sub into 3) a + b + sqrt(a*a + b*b) = 1000 now we have only two unknowns """ import math a, b = None, None for b in range(1000, 0 ,-1): brk = False for a in range(b-1, 0, -1): if a + b + math.sqrt(a*a ...
aa670dcef38164ef87d888a531cf196d1746f14d
roni-kemp/python_programming_curricula
/CS1/0350_list_projects/magic_8_ball_answer.py
455
3.828125
4
import random #http://www.pythonforbeginners.com/code-snippets-source-code/magic-8-ball-written-in-python/ options = ["It is certain","Outlook good","You may rely on it","Ask again later","Concentrate and ask again","Reply hazy, try again","My reply is no","My sources say no"] question = True while question: que...
0c8e476246f473c463914242b1960e8d5679b2ba
Vatican-Cameos/Algorithms
/Min Cost Climbing Stairs.py
739
3.6875
4
# On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). # Once you pay the cost, you can either climb one or two steps. # You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, # or the step with index 1. class Solution: ...
225f6b81a6cc1e701452a9584808037a88530fb5
emilydlu/exercism-python
/hamming/hamming.py
140
3.5625
4
def distance(a, b): if len(a)!= len(b): return counter = 0 for i in range(len(a)): if a[i]!= b[i]: counter+=1 return counter
3b12ec57154e8f766b4d2fe790a3ef9e959e01c0
wilbertgeng/LintCode_exercise
/DFS/10.py
1,359
3.96875
4
"""10. String Permutation II""" class Solution: """ @param str: A string @return: all permutations """ def stringPermutation2(self, str): # write your code here if not str: return [""] res = [] str = list(str) str.sort() self.dfs(str, [], ...
9e45b98de15fcd26affba22a2c22e5946737a6d9
jorge-alvarado-revata/code_educa
/python/week8/r_ejem04.py
158
3.625
4
# inverso de una cadena def inverso(s): if s == '': return '' else: return inverso(s[1:]) + s[0] print(inverso('hola como estas'))
3f6cfb6d2b15a69ce0c80440093376b2e6e2b3d0
yeduxiling/pythonmaster
/absex84.py
224
3.828125
4
n = int(input('请输入一个数:')) def is_positive(n): if n > 0: return True else: return False if is_positive(n): print(f"{n}是个正数") else: print(f"{n}不是正数")
93909bccd922814dfe22c9e6758a7aadb8085f80
phamvantai/bai6
/t6.2.py
273
3.578125
4
class Hinhchunhat(object): def __init__(self, a): self.canh = a def __init__(self,b): self.canh = b ################################## def area(self): return.self.canh*a*b aHinhchunhat = Hinhchunhat(2) print(aHinhchunhat.area())
cd9482433dcab725c4935eb457b87fab0fc9a2c2
justagist/tf_playground
/autoencoder_mnist.py
9,516
3.578125
4
''' # autoencoder class to learn and predict mnist images: Reduces 28x28 image to a 2D value and learns to predict the class from it. @author: JustaGist @package: tf_playground ''' import sys import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import matpl...
421051e22264c10822544e58835b1c8349f71a7f
KATO-Hiro/AtCoder
/Others/paken/pakencamp-2018-day3/a.py
216
3.546875
4
# -*- coding: utf-8 -*- def main(): y, m, d = map(int, input().split()) if m == 12 and d == 25: print(y - 2018) else: print('NOT CHRISTMAS DAY') if __name__ == '__main__': main()
97a472785b7024fb576dfd8cb00e637d2e8b2b73
domantasjurkus/python
/euler/16_euler.py
102
3.6875
4
num = 2**1000 sum = 0 num = str(num) for char in num: sum += int(char) print "Final sum:", sum
7a93dcb7fb2be4fc2f16cbe196583b8a55a96978
larlyssa/uoft_csc108H
/tic-tac-toe/tictactoe_functions.py
2,848
4.34375
4
import math EMPTY = '-' def is_between(value, min_value, max_value): """ (number, number, number) -> bool Precondition: min_value <= max_value Return True if and only if value is between min_value and max_value, or equal to one or both of them. >>> is_between(1.0, 0.0, 2) True >>> is_be...
33a26f0aaca6c8f32e2e6657c9c1f11a048a77c2
sandip-gavade/python_practice
/conditional.py
487
4.03125
4
n = int(input("please input a number ")); if n<=100 and n>=1: print("you have entered -",n," this is between 1 and 100"); if n<=50 and n>=1: print("you have entered -", n, " this is between 1 and 50"); if n<=25 and n>=1: print("you have entered -", n, " this is between 1 and 25"); el...
f7924e7a60a844350e865c72e6aee17501e75374
p4panash/Algorithms-and-Programming
/Lab3/ReadFile.py
1,341
4.4375
4
def ReadFromFile(currentArray, fileName): """ Function used in order to change the current list with a list from a file Input: currentArray - an array of integers representing the current array Output: an array with elements from file """ array = [] try: file = open(fileName, "r") ...
b6d81ca1976b446d4ce385728828c80663db53f5
eidleweise/ToolsForWishblendRPG
/PhonePad.py
2,238
3.9375
4
# Import the groupby function from itertools, # this takes any sequence and returns an array of groups by some key from itertools import groupby # Use a dictionary as a lookup table dailpad = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', ...
1d9b59a4604be6a8ccb5b4d95cdf79b051ced971
DhanashreeRevagade/Clustering-Air-Objects_Challengers-of-the-Unknown
/calculate_angle_of_elevation.py
1,854
3.53125
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd import math v = 700 g=9.8 def get_data(path): dataframe = pd.read_csv(path,usecols=['Longitude', 'Latitude','Altitude (m masl GPS)'],nrows=10) return dataframe def check_std(df): ''' df: Dataframe Object We will keep eit...
d9b3edf3dc3ce5a69530e326144e025750ca3606
jgrynczewski/zdpytpol16_design_patterns
/oop/duck_typing.py
581
4.03125
4
# If it looks like a duck, swims like a duck and quacks like a duck, then it probably is a duck. import abc class SwimDuckAnimal(abc.ABC): @abc.abstractmethod def swim_quack(self): pass class Duck(SwimDuckAnimal): def swim_quack(self): print("Jestem kaczką") class Dog(SwimDuckAnimal): ...
0feccb7a6f09a960a364ea46cd7929b18fe57258
richardvecsey/python-basics
/060-break_continue.py
655
4.25
4
""" How to speed up for cycle with break and continue ------------------------------------------------- continue: Jump to the next iteration, the remain part of the actual iteration won't be executed break: Jump out from the for loop, the remain part of the whole for cycle won't be ...
a09f428f0e0e1f79b64dd02f841da9656e335ea5
abbasjam/abbas_repo
/python/func.py
131
3.984375
4
x={'Name':"Abbas",'RN':"1188",'Age':"39",'Mark1':"90",'Mark2':"95"} x["Mark3"]="67" x.pop("Name") y=x.copy() print(y) print(x)
b573017ca336216332be4612d48206ba1eaa6b8c
SyureNyanko/asymmetric_tsp
/asymmetric_tsp/core.py
1,957
3.765625
4
# -*- coding: utf-8 -*- import math import time import sys class Timeout(object): def __init__(self, limittime, starttime): self.starttime = starttime self.limittime = limittime def get_timeout(self, time): timeout = (time - self.starttime> self.limittime) return timeout def testlength(v1, v2): '''Measur...
08e6a33334f8e0ff8e896dece715c5dbd7d90b5c
zohaibafridi/Scripts_of_Data_Exploration_and_Analysis_Book
/Volume_II/3-Pandas/Code_Scripts/3.12-Aggregation.py
2,342
3.609375
4
#!/usr/bin/env python # coding: utf-8 # ### Applying Aggregations on DataFrame # # In[1]: import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print (df) r = df.rolling(window=3,min_periods=1) print (...
6315dd6a066de16269a84b22bc03cad2acaf1e88
moongchi98/MLP
/백준/MAR-APR/12904_A와B.py
331
3.59375
4
S = input() T = input() while len(S) != len(T): if T[-1] == 'A': T = T[:-1] else: T = T[:-1] T = T[::-1] if len(S) > len(T): result = 0 break elif len(S) == len(T) and S != T: result = 0 break elif S == T: result = 1 break prin...
39f22c6409e76b010a99d74a79f3e968ddb87fa8
afieqhamieza/DataStructures
/python/split_string.py
1,069
4.0625
4
# Given a string s with length n, how many ways can you split it into two substrings s_1 and s_2 # such that the number of unique characters in s_1 and s_2 are the same? # Parameter # s: A string with length n. # Result # The number of ways you can split it into two substrings that satisfy the condition. import co...
37a554bc933736bc95077e7050facefd4d5771e4
EDU-FRANCK-JUBIN/exercices-sur-python-Nummytincan
/Ex5.py
341
3.78125
4
def minMaxMoy(list): min = list[0] max = list[0] moy = list[0] for i in range(1, len(list)-1): moy += list[i] if list[i] > max: max = list[i] if list[i] < min: min = list[i] moy /= len(list) tuple = [min, max, moy] print(tuple) minMaxMoy([10,...
23321c2af3efa78ef1cc16eb827ca63f3e638a14
I3lacx/Pythonbot
/Blacx/simpleNN_TensorFlow.py
1,645
3.65625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 10 batch_size = 100 #so many into one iteration #sets the shape so nothing goes wrong x = tf.placeholder(...
43a3796979abae7ff9e192020e50d4d75fc10ab5
GeertenRijsdijk/Theorie
/code/algorithms/random.py
1,084
3.765625
4
''' random.py Authors: - Wisse Bemelman - Michael de Jong - Geerten Rijsdijk This file implements the random algorithm which places houses randomly onto the grid. Parameters: - grid: the grid object Returns: - None ''' import numpy as np from copy import copy def random(grid): # Randomly place houses ...
ffc1b07d67ac33e435dba906f1dea37bc304e508
RandyHodges/Self-Study
/Python/Functions/funPractice.py
964
4.21875
4
# ======================= Play around with Python a bit ============================ # # Create a new Python file in this folder called funcpractice.py. # Inside it, create a function called 'addthree', that takes as input three parameters - num1, num2, num3. # Then, write logic to create a new variable, y, that ...
ad7e40b80285c42ffa069c5e04c70809ef7ead46
Illugi317/forritun
/mimir/12/4.py
1,200
4.375
4
''' Write a program that accepts a list of integers, int_list, as an argument and a single integer, check_int, and then prints 'True' if two consecutive values of check_int are found in the int_list. The program prints out an error message saying 'Error: enter only integers.' if the list is found to contain any non-...
8c0fe33540e47ca20c0da16af61ef9e44f7de0d7
dorisli777/SSP2017-CUB
/orbitdet.py
12,217
3.828125
4
# This function gives the six orbital elements of an asteroid given a data file containing RA and DEC. # Last modified August 2017 at the Summer Science Program in Boulder, CO from math import * #magnitude function def mag(x): y = 0 for i in x: y = y + i**2 return sqrt(y) #dot product function ...
ecf06c6339c380da9b64e2ef5e8a83f6568d60d8
oktavianidewi/interactivepython
/ss_bubblesort.py
551
3.796875
4
def diyBubbleSort(alist): for iterasiEksternal in reversed(range(len(alist))): print iterasiEksternal for nilaiInternal in range(iterasiEksternal): if alist[nilaiInternal] > alist[nilaiInternal+1]: temp = alist[nilaiInternal] alist[nilaiInternal] = alist[n...
118a576d61e57beb2a8dcda493f41811995da387
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/mtsmol017/question4.py
384
3.765625
4
b=eval(input("Enter the starting point N:\n")) c=eval(input("Enter the ending point M:\n")) result=[] for i in range(b,c): if str(i)==(str(i))[-1::-1]: factors=0 for m in range(2,10): if i%m==0: factors+=1 if factors<1: result.append(i) prin...
c96ca87da9d987a46c17b78e5c9d9398202a9f78
xliang01/AlgoExpertChallenges
/Easy/closestValueBST.py
1,687
3.65625
4
import sys class BST: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): if value < self.value: if self.left is None: self.left = BST(value) else: self.left.insert(val...
b19a08c6773244feead303fd3c29b01933c6f535
SimonJang/advent-of-code-2019
/day2.py
2,480
3.640625
4
def execute_operation(operation: int, a: int, b: int) -> int: if operation is 1: return a + b if operation is 2: return a * b if operation is 99: return None print(f"Exception operation: {operation}") raise Exception def day1(): with open('./data/day2.txt') as file: ...
796d371d812915500f17495888310d6839e93754
OrangeHoodie240/SB_Captstone_One
/utility.py
1,392
3.65625
4
import datetime as dt import random import math weekdays = {'monday': 1, 'tuesday': 2, 'wednesday': 3, 'thursday': 4, 'friday': 5, 'saturday': 6, 'sunday': 7} def find_closest_workout(workout): weekday = dt.datetime.today().weekday() + 1 closest = 8 closest_day = None for day in workout.days: ...
fe3a4562a519cc6186805177db345b4a71b660cf
anttilip/telepybot
/telepybot/modules/weather.py
9,604
3.59375
4
"""*Returns weather forecast for a location.* This module can search weather reports using Wunderground API. Weather reports consist of a current weather in observation location, a 3 day weather forecast and distance from observation location to the requested location. Module also features an interactive mode where us...
36f1dad1209bb1f575fca85d536011663f473a33
ChWeiking/PythonTutorial
/Python基础/day11(继承、多态、类属性、类方法、静态方法)/demo/03_类属性/02_类属性.py
1,079
4.1875
4
''' 类属性: 1、定义在类内部,方法外部的属性就是类属性 2、在类的外部,通过类对象.属性就是类属性 类属性是属于类对象的,还属于所有实例对象 ''' class Dog: name = '子庆' color = '黑色' num=123456 def run(self): print('run...') ''' d1 = Dog() d1.name = '旺财' print(d1.name) print(dir(Dog)) print(Dog.name) Dog.sex = '雄' print(Dog.sex) print(dir(Dog)) print(d1.sex) ''' ...
e527a551b17d706c206afc1285fe6c319aabbeda
NagaTaku/atcoder_abc_edition
/ABC066/b.py
197
3.546875
4
s = input() s_len = len(s) for i in range(1, int(s_len/2)+1): s = s[:-2] half = int(len(s)/2) s_mae = s[:half] s_ato = s[half:] if s_mae == s_ato: break print(len(s))
694bd775680ac62ddca32c15bad3e73072495a65
moecherry99/GraphTheory
/shunting.py
674
3.5625
4
# Alex Cherry - G00347106 # Shunting Yard Algorithm def shunting(infix): specials = {'*': 50, '.': 40, '|': 30} pofix = "" stack1 = "" for c in infix: if c == '(': stack1 = stack1 + c elif c == ')': while stack1[-1] != '(': pofix, stack1 = pofix + stack1[-1], stack1[:-1] st...
52a63b37fe7c1beb20b5f9566a824ca10620db03
saicharantejaDoddi/COMP_6411_GuessGame
/game.py
4,567
4.03125
4
class Game: """ The Game object provides the scheme to store the individual game. Parameters: ---------- No parameters are passed. Attributes: ---------- GameNo(int):The is where we store current game number. Word(str):The is where we store curren...
628aa689b89323a24ad7f84ca67ab28fa9e63ba9
AkeBoss-tech/chessEngine
/Screen.py
14,461
3.625
4
import pygame, random, math, time, os def drawRectangle(screen, color, x, y, width=100, height=100): pygame.draw.rect(screen, color, (x, y, width, height)) def drawHollowCircle(screen, color, radius, center_x, center_y): iterations = 100 for i in range(iterations): ang = i * 3.14159 * 2 / ...
b87a64d959d5e5fbeaa9147d3da41ea2661d0f8b
luckkyzhou/leetcode
/33_1.py
201
3.671875
4
# -*- coding: utf-8 -*- from typing import List class Solution: def search(self, nums: List[int], target: int) -> int: if target in nums: return nums.index(target) else: return -1
f6cb8139c7bc123a63ac0e65647d61e32849e5cb
Abi3498/guvi
/lar.py
174
3.53125
4
a=10 b=20 c=30 if(a>b) and (a>c): great=a elif(b>a) and (b>c): great=b else: great=c print ("The greatest number is",great)
a5ffaefa1f958326daca4dd3f1a7bdc778f2b59a
jnnersli/BlackJack
/BlackJack/BlackjackModel/Player.py
1,416
3.890625
4
from Card import * #One of the blackjack players class Player: def __init__(self): self.__hand = [] self.__gameState = "playing" #Keeps players from playing out of turn def hand(self): return self.__hand.copy() def gameState(self): return self...
014cad9a68bf6b18ab7d860dff49d1e1393137eb
anildhaker/DailyCodingChallenge
/GfG/Mathematical Problems/primeFactors.py
401
4.25
4
# for 12 -- print 2,2,3 import math def primeFactors(n): while n % 2 == 0 and n > 0: print(2) n = n // 2 # n becomes odd after above step. for i in range(3, int(math.sqrt(n) + 1), 2): while n % i == 0: print(i) n = n // i # until this stage all the composite numbers ha...
48886bdd03163e7f7e3142e02978934540562151
dylean/python-learn
/python从入门到实践/case8.py
685
3.875
4
from collections import OrderedDict from random import randint favorite_languages = OrderedDict() favorite_languages['jen'] = 'python' favorite_languages['sarah'] = 'c' favorite_languages['edward'] = 'ruby' favorite_languages['phil'] = 'python' for name, language in favorite_languages.items(): print name.title()...
554b2c63229378225f93730462222cd3180be8d4
vaibhavranjith/Heraizen_Training
/Assignment1/Q48.py
166
3.796875
4
n=int(input("Enter the number:\n")) print("Output") i=3 temp=n while i>=0: print(f"{n//(10**i)}*{10**i}={(n//(10**i))*10**i} ") n=temp%(10**i) i-=1
854b71145d6221a3367b9dcccdfef02b9a8b651d
ezhang-dev/competitive-programming
/DMOJ/Uncategorized/Jason's Theorem.py
313
3.53125
4
def modexp ( g, u, p ): """computes s = (g ^ u) mod p args are base, exponent, modulus (see Bruce Schneier's book, _Applied Cryptography_ p. 244)""" s = 1 while u != 0: if u & 1: s = (s * g)%p u >>= 1 g = (g * g)%p; return s q=10**9+7 print((pow(2,int(input())+3,q)-5)...
4fe87a1611da3eacdce1ed77161a21395129d7b9
beOk91/baekjoon2
/baekjoon10707.py
215
3.59375
4
x=int(input()) y_price=int(input()) y_limit=int(input()) y_price2=int(input()) joi_water_ant=int(input()) print(min(x*joi_water_ant,y_price if y_limit>=joi_water_ant else y_price+ (joi_water_ant-y_limit)*y_price2))
99bd7e715f504ce64452c252ac93a026f426554d
gotdang/edabit-exercises
/python/factorial_iterative.py
414
4.375
4
""" Return the Factorial Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers. Examples: factorial(3) ➞ 6 factorial(5) ➞ 120 factorial(13) ➞ 6227020800 Notes: Assume all inputs are greater than or equal to 0. """ def facto...
18259f93ca893f050a1ce6ca853f2c1e456a503e
aleko-/substitution-cipher-decoder
/decoder.py
5,860
3.671875
4
import re import random import json import sys import time if len(sys.argv) < 2: print "Add the name of the encrypted file and try again" sys.exit() elif len(sys.argv) > 2: print "Too many arguments used. Try again." sys.exit() # Read in and preprocess text of the encrypted file # Store original_decod...
b66ae60a46340a685d0c9e9204f7282c9d02ecc2
Madhuchigri/Python_work_New
/OOPs_notes_Programs/Polymorphism1.py
887
4.03125
4
# Overriding and Super() Method class Employee: def setnumberofworkinghours(self): self.numberofworkinghours = 40 def display_number_working_hours(self): print("Number of working hours for an employee:", self.numberofworkinghours) class Trainee(Employee): def setnumberofwo...
a0e220589d9e1535653a925f5117bdfaed2ccab2
alimoreno/TIC-2-BACH
/PYTHON/parimpareador.py
348
4.03125
4
def parimpareador(): x=input("Dime un numero ") y=input("Dime otro numero ") if(x%2>0 and y%2>0): print "Los dos numeros son impares" if((x%2==0 and y%2>0) or (x%2>0 and y%2==0)): print "Un numero es par y el otro impar" if(x%2==0 and y%2==0): print "Los dos numeros s...
dcf9564c7dc03e120309ad0b60548804af2c6d30
mucheniski/python-for-data-science
/module2/QuesitionsReview.py
108
3.734375
4
A=('a','b','c') print(A[0]) Dict={"A":1,"B":"2","C":[3,3,3],"D":(4,4,4),'E':5,'F':6} print(Dict["D"])
01a24ae55c6319c043829e890631432e04c0acec
edumaximo2007/Mundo1
/Desafio23.py
840
4.0625
4
print('-=-'*10) print('''\033[7m DESAFIO 23 \033[m''') print('-=-'*10) print('') print('''\033[1mFaça um programa que leia um número de 0 a 9999 e mostre na tela cada um digitos separados. EX: Digite um número: 1834 Unidade: 4 Dezena: 3 Centena: 8 Milhar: 1\033[m''') print('') p1 = str(inp...
1173b05664e2ea8cf6382f8dc3a61e8e224d63cf
liamphmurphy/2020_hackathon
/src/beers.py
1,509
4.03125
4
class Beers: all_beers = { # values are as follows: drink name, attributes, acceptable locations, cost to make, purchase price "Fresh Squeeze": ("Fruity", "Hoppy", ["Ashland", "Portland"], 2.50, 4.00), "Kombucha": ("Non-Alcoholic", "Flavorful", ["Ashland", "Portland"], 3.00, 4.25), "...
f942789a43fbc4158b3260f70ea9e82271fbe870
carlox7/Intro-to-computer-science-with-python
/lecture4.py
606
3.84375
4
##def withinEpsilon(x, y, epsilon): ## return abs(x - y) <= epsilon ## ##print(withinEpsilon(2,3,1)) ##val = withinEpsilon(2,3,0.5) ##print(val) ## ##def f(x): ## x = x + 1 ## print('x', x) ## return x ##x = 3 ##z = f(x) ##print('z = ', z) ##print('x = ', x) ## ##def f1(x): ## def g(): ## x = 'abc...
d735fa704efc96cb8e00fdd1b984f76d5410c134
rishabhsharma015/python_programs
/alphabeticalorderstr.py
132
4.03125
4
n=input("Enter the String: ") k=list(n) k.sort(reverse=False) s=''.join(map(str,k)) print("String characters in sorted order: ",s)
3b55d3ba70c7145c34f54050baa1b6767e1fbf1b
clovery410/mycode
/leetcode/242valid_anagram.py
502
3.578125
4
class Solution(object): def isAnagram(self, s, t): char_list = [0 for x in xrange(26)] for item in s: char_list[ord(item) - ord('a')] += 1 for item in t: char_list[ord(item) - ord('a')] -= 1 is_anagram = True for i in xrange(26): if char_li...
40845e61d51b2ca3b31540a7c2b10a2fe1827894
cyrilvincent/math
/demo_tuple.py
259
3.765625
4
from typing import List, Tuple, Iterable def my_function(param: float) -> Tuple[int, str]: return 1, "toto" def sum(l: List[float]): res = 0 for x in l: res += x return res x, y = my_function(3.14) print(x, y) print(sum([1,2,3]))
b863c57cc46fcb0220334be7400e3295f39c6380
SourTofu/Python-learning
/week1/边长为N的正方形.py
98
3.828125
4
while True: number = int(input('>>>')) for i in range(number): print(number*"*\t")
5206f684b1bfdbe1fcbb18994df1eedf6057bcb7
LarmIg/Algoritmos-Python
/Capitulo 3/Exercicio O.py
514
4
4
# Elaborar um programa que leia quatro valores numéricos inteiros (variáveis A, B, C e D). Ao final o programa deve apresentar o resultado do produto (variável P) do primeiro com o terceiro valor, e o resultado da soma (variável S) do segundo com o quarto valor. A = int(input('Informe o valor de A:')) B = int(input(...
35625d25a698a3a9bbc4cbfb78f51d51bd6acdf7
andrewwebukha/pythonbasic
/string_operations.py
879
4.375
4
#concatenation using a plus operator, using .format first_name = "Andrew" last_name = "Webukha" #full_name ="{} {}".format(first_name,last_name) #print(full_name) print("The tallest person in the family of {} is named after {}".format(last_name,first_name)) #full_name= first_name+" "+last_name #print(full_name) name= ...
1ad3a2ea0c11fa8f921430fd4896349f94e5d580
xc1111/untitled2
/hk_homework1_10/demo1.py
1,000
4
4
# 定义猫类 class Cat: # 构造函数初始化:初始化同时设置初始值姓名和颜色 def __init__(self,name,color): # 形参姓名保存为属性 self.name=name # 形参颜色保存为属性 self.color=color # 定义捕捉方法 def catch(self): # 打印 print(f"抓到老鼠了") # 定义str方法:当输出对象时可不输出地址而是自定义的内容 def __str__(self): # return "我的名字叫 %s 颜...
29cd9dda629eadf5ee65fc94105cb8867b3bb11c
KamarajuKusumanchi/rutils
/python3/get_urls.py
986
3.625
4
#! /usr/bin/env python3 # Script to get urls in a url. import argparse import requests from bs4 import BeautifulSoup import re def create_parser(): parser = argparse.ArgumentParser( description='Get urls in a url' ) parser.add_argument( '-v', '--verbose', action='store_true', def...
efc3e0f87062b466b6cfa04b841a001f74e25717
hardhary/PythonByExample
/Challenge_058.py
644
4.25
4
#058 Make a maths quiz that asks five questions by randomly generating two whole numbers to make #the question (e.g. [num1] + [num2]). Ask the user to enter the answer. If they get it right add #a point to their score. At the end of the quiz, tell them how many they got correct out of five. import random def maths(): ...
9a1d4f2fead15f720ea4f0cacc551926cc8b2dde
CamilliCerutti/Python-exercicios
/Curso em Video/ex082.PY
704
4.0625
4
# DIVIDINDO VALORS EM VARIAS LISTAS # Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas. valores = list() impar = list()...
2f7baa0cdeb7a324dd5b1f076315ef4bc34b680b
Aasthaengg/IBMdataset
/Python_codes/p03547/s006743911.py
98
3.734375
4
s = list(input()) if s[0] == s[2]: print("=") elif s[0] < s[2]: print("<") else: print(">")
30336b1bffa8a40ba70efeff58ffee90e7d339be
sagarnikam123/learnNPractice
/hackerEarth/practice/dataStructures/arrays/1D/fredoAndLargeNumbers.py
3,134
3.578125
4
# Fredo and Large Numbers ####################################################################################################################### # # Fredo is pretty good at dealing large numbers. So, once his friend Zeus gave him an array of N numbers, # followed by Q queries which he has to answer. In each query...
045482fcfb5e250049bf7facce519a2cbb6dc0a9
shreya3079/guess-the-number
/guess the number.py
913
3.984375
4
import random process = True no = random.randint(0, 100) chance = 0 print("Enter a number between 0 to 100\n") print("You have only 5 chances to guess the number\n") while process: choice = input("Guess the number:") if int(choice) == no: print("Yeah!!! You guessed the number!!!") ...
03792ec4b03098ca2248e50df1f90d3ba50dd4cb
rhanugr/webautomationusingpyhton
/pythonProject/APITesting/Basics/Basictest.py
163
4.125
4
# TYPE CASTING # Converting Integer to String and String to Integer age = input("Enter your Age : -") age = int(age)+5 print("Age of the Man is :- " + str(age))
f3bcddb0e40ce21e84362daef59a33309384a230
brandon-rowe/Python
/Py Programs/MyPy/Beginner/Worms/exploitFile.py
585
3.640625
4
def main(): inp = input("Please enter your file name with extension. ") read(inp) def read(inp): myFile = open(inp,'r') data = myFile.read() words = data.split(" ") print() print(data) print(words) i = 1 while i > 0: i += 1 m = 1 fname = "Kronus" ...