blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
df544cbe90c24f0757315c4c371dadd83a9e0254
tobinSen/python01
/python01/while.py
1,339
3.71875
4
# 矩形 i = 0 while i < 5: j = 0 while j < 5: print('*', end='') j += 1 print() i += 1 # 三角形 i = 0 while i < 5: j = 0 while j <= i: print('*', end='') j += 1 print() i += 1 # 99乘法表 i = 1 while i < 10: j = 1 while j <= i: print(f'{i} * {j} = {i...
318126d1369d5ba33515b7b40f5b64664a4d8490
bwconrad/backpropagation
/backpropagation.py
6,464
3.640625
4
import random import math import time import copy def logistic(x): return 1.0 / (1.0 + math.exp(-x)) def logistic_derivative(x): return logistic(x) * (1-logistic(x)) class Neuron: def __init__(self, attribute_weights, neuron_weights, bias_weight): # neuron.attribute_weights[i] = We...
c3f68a5073dc000379a32dcd29a0b0959e8bd98f
TheEvolvingFrontier/TheEvolvingFrontier
/examples/FacilitySense/comments.py
3,269
3.5625
4
#comments.py - contains the code that runs the comments system. import os class comment(): username = "" commentText = "" time = "" building = "" floor = "" location = "" isGood = "Neutral" def addComment(username,commentText,time,building,floor,location,isGood): newComment = comment(...
8b6e4666bf75fc6b7023e8c93717384f56183890
hayuzi/py-first
/base/dealwithexp.py
2,766
4.25
4
# 异常处理 # 语法错误是错误 # 异常是 语法正确,但是执行时候出现错误。 # 异常处理使用 try except 格式 # 与其他一些语言一样,责任链的模式,如果不做 except获取,会反馈到上一层. while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("that was no valid number, try again ") # 一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组,例如 # ...
22e465e1b91d8e4f27021f9196d9dec8467efd9e
gbertao/MC102-20182s
/01/lab01.py
1,253
3.828125
4
total = int(input()) nota = 100 x = 0 x = total//(nota*100) total = total % (nota*100) print(str(x)+" nota(s) de R$ "+str(nota)+",00.") nota = 50 x = 0 x = total//(nota*100) total = total % (nota*100) print(str(x)+" nota(s) de R$ "+str(nota)+",00.") nota = 20 x = 0 x = total//(nota*100) total = total % (nota*100) pr...
0d006bd23c4057533b661d0f30fa7c6b0be6d14e
gbertao/MC102-20182s
/07/lab07.py
1,689
3.71875
4
def tupla_float_int(x) : x = x[1:-1] # remove parênteses x = x.split(",") # separa em duas strings f = float(x[0]) # converte primeiro elemento para float i = int(x[1]) # converte segundo elemento para int return (f,i) # retorna tupla notas_c = input().split() notas_lab = [tupla_f...
9c76faed8f4d76c6a777c72f97a3e9c66e88ada7
kotpilun/Stepic_course
/file_01.py
2,658
3.640625
4
# Напишите программу, которая считывает из файла строку, соответствующую тексту, сжатому с помощью кодирования # повторов, и производит обратную операцию, получая исходный текст. # # Запишите полученный текст в файл и прикрепите его, как ответ на это задание. # # В исходном тексте не встречаются цифры, так что код одно...
0d2977285a7edaf5bb6e66687243a07374aa92b4
uname10000/itea
/lesson2/task_3.py
1,875
3.859375
4
class Point: def __init__(self, x, y, z): self._x = x self._y = y self._z = z def get_x(self): return self._x def get_y(self): return self._y def get_z(self): return self._z def set_x(self, value): self._x = value def set_y(self, value...
9aa8ff6d36620be534adaad17e6e38e2bd0425b9
uname10000/itea
/lesson1/task_1.py
194
4
4
numbers = int(input('Enter numbers: ')) list_of_numbers = list(range(0, numbers + 1)) # print(list_of_numbers) for number in list_of_numbers: if number % 2 == 0: print(str(number))
641033faf8ace40c26ec5871265cf4635f175610
PangHua/nonlinearIB
/code/fig2.py
2,648
3.859375
4
# Example that demonstrates how to generate a figure similar to Fig.2 in Artemy Kolchinsky, Brendan D. Tracey, David H. Wolpert, "Nonlinear Information Bottleneck", https://arxiv.org/abs/1705.02436 # Minimal example of how to create a model with nonlinearIB layers import numpy as np from keras.models import Model fro...
1ad55373b6130a4616cc87373db5414c3ba5fe11
ezhang0520/python-challenge
/PyPoll/main.py
1,239
3.65625
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 7 19:47:45 2020 @author: elliezhang """ import pandas as pd election = pd.read_csv('election_data.csv') # compute total number of votes n = len(election) # get a list of candidates can_ls = list(set(election['Candidate'].values)) # compute percentag...
b54971562aae2b3aa91486f533a178213cca3ee2
ayakutko/HW_1_6
/tasks 7_10.py
972
3.734375
4
#7 date_us = "05.17.2016" def date_eu(date_us): day = date_us[3:6] month = date_us[:3] year = date_us[6:10] return day + month + year print(date_eu(date_us)) #8 string1 = "love" string2 = "python" def task8(s1, s2): half_length1 = int(len(s1)/2) half_length2 = int(len(s2)/2) first_result = s...
b6eb799e6fcd17923db62551f3ea765c3d533058
singlrplayer/denis
/cool.py
213
3.71875
4
"""sergeiev denis 5-A claas""" rectangle={"a":123,"d":321,"e":446,"c":543} l=rectangle["e"]+rectangle["a"]+rectangle["d"]+rectangle["c"] print(l) g=0#перыметр for key in rectangle: g=g+rectangle[key] print(g)
72368e88f7aa41b777597a4383eca690927bf953
laskalav/Python
/Python_lesson1/python1_4.py
208
3.53125
4
incoming = abs(int(input("Введите число: "))) result = 0 while incoming: remains = incoming % 10 incoming = incoming // 10 if remains > result: result = remains print(result)
d5c5711fe3b3c26741105d622eef3cbf67bcc551
laskalav/Python
/Python_lesson4/Python4_5.py
173
3.65625
4
from functools import reduce def multiply(prev_el, el): return prev_el * el num_list = [n for n in range(100, 1001) if n % 2 == 0] print(reduce(multiply, num_list))
b88292337b2615c6634698baeec4774f7a920ec7
laskalav/Python
/Python_lesson3/Python3_3.py
143
3.5
4
def my_func(*args): args_list = list(args) args_list.sort() return args_list[-1] + args_list[-2] print(my_func(250, 1, 250, 3))
531bdd84d14f6365e1e2b3d5d7b2b3e07946c87d
YuZhanHuang/design-pattern
/observer/waterheater.py
1,416
3.875
4
import time from abc import abstractmethod class WaterHeater: """ 熱水器,冬天的英雄 """ def __init__(self): self._observer = [] self.temperature: int = 25 def set_temperature(self, temperature: int): self.temperature = temperature self.notifies() def get_temperature(...
6908e812674438b45fa67c0da9dac4b83e3e1f98
lierscn789/learning-programming
/二级/真题/2018年9月第二套/PY103.py
395
3.8125
4
n = eval(input("请输入数量:")) ... print ("总额为:",cost) ######################答案############################# n = eval(input("请输入数量:")) if n >= 10 : cost = n * 160 * 0.7 elif 5 <= n <= 9 : cost = n * 160 * 0.8 elif 2 <= n <= 4 : cost = n * 160 * 0.9 else: cost = n * 160 cost = int(cost) #...
551f8f3545537217ff3b086f187b324d4964b240
lierscn789/learning-programming
/二级/真题/2018年9月第三套/PY201.py
413
3.859375
4
# 以下代码为提示框架 # 请在...处使用一行或多行代码替换 # 请在______处使用一行代码替换 import turtle for i in range(4): turtle.fd(100) _________(-100) _________((i+1)*90) ######################答案##################################### ##import turtle ##for i in range(4): ## turtle.fd(100) ## turtle.fd(-100) ## tur...
590a4e964144110b77cb8a1b1563b72a59858f4e
42force/100days42
/lesson2texts.py
313
3.625
4
message = "Hello" greeting = 'Duchess' name = greeting + ', ' + message # formatting words the best way to concatenate.. newtests = f'{greeting}, {message},I miss you!' newmessage = message.replace('love', 'miss') #dir shows you attributes on what to do print(dir(newtests)) #print(help(str.lower))
6031116408f17d25a1dd43b5abddc66a0b945232
shakil12-coder/python-college-codes-
/6.py
178
3.859375
4
a=input("Enter 1st variable : ") b=input("Enter 2nd Variable : ") print("Before swapping a :", a, "and b :",b) temp=a; a=b; b=temp; print("After swapping a: ",a, "and b :",b);
dfc21a67ba47086661ab15bb54f8c1bdc5e1efb9
pebenini/PhytonBasicoCurso
/HT2.py
566
4.09375
4
#Ejercicio 1 Contrasena = input("Ingrese su contraseña: ") Validacion = input("Ingrese nuevamente su contraseña:") if Contrasena == Validacion: print("Su contraseña es correcta") else: print("*****La contraseña ingresada es incorrecta****") # Ejercicio 2 name = input("¿Como te llamas?: ") gender = input(...
9f215dc7b92a78dc7d27e7a800adedcb5408169e
Osman808/lab-6
/ind_1.py
870
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys # Ввести список А из 10 элементов, найти произведение положительных # элементов кратных 3, их количество и вывести результаты на экран. if __name__ == '__main__': # Ввести список одной строкой. a = list(map(int, input().split())) # Проверить количе...
b5f1871d75286600ca61d58ffd7d408703cfa9f2
Alexandre-Lara/information-organization-and-recovery
/projects/hashtable/main.py
6,271
4.09375
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ ===== Trabalho 1 de ORI ===== Arquivo: main.py Descrição: script que roda a aplicação e faz interface com o usuário Autores: Raul Vieira Cioldin Alexandre Rocha """ import sys from classes import Dicionario, Tesauro class Aplicacao: def __...
0bbbb09f374e70162f41c23c329924fa59f72ca2
loading99pct/computationalphysics_N2013301020062
/Chap_2.1/nest.py
1,934
3.6875
4
''' nest a function nest(function, initialValue, times) nestList(function, initialValue, times) nestListIter(function, initialValue, times) nestUntil(f, x, stopQ, maxStep = 100000) nestUntilList(f, x, stopQ, maxStep = 100000) ''' def nest(f,x0,n): "return f(f(...f(x)))" i = 0 while i < n:...
837f6e6d2610fb529e3ab6470bc39f9bcb90796f
abhishekshanbhag/Design-By-Software-HW-Files
/Week_4/w4_polynomial.py
5,371
3.765625
4
# AUTHOR Abhishek Shanbhag anshan@bu.edu # AUTHOR Ziteng Xu zxu83@bu.edu class Polynomial(): def __init__(self, sequence = []): self.sequence = dict({}) for i in range(len(sequence)): if(sequence[i] != 0): self.sequence.update({len(sequence) - 1 - i:sequence[i]}) #self.max = len(sequence) - 1 #self.min ...
8a36a3991de68ef7a49650a7c403c8f5f936de0b
NizarAlsaeed/data-structures-and-algorithms
/python/code_challenges/array_binary_search/array_binary_search.py
1,007
3.921875
4
import math def BinarySearch(input_list:list, search_key)->int: """ return the index of the array’s element that is equal to the search key, or return -1 if the element does not exist. """ input_list = sort_list(input_list) first_index = 0 last_index = len(input_list)-1 while first...
3996f11b48fe15d6d9b86a8e774b8f409068137c
NizarAlsaeed/data-structures-and-algorithms
/python/code_challenges/fifo_animal_shelter/fifo_animal_shelter.py
1,713
4.03125
4
class Animal: def __init__(self,name,age): self.name = name self.age = age class Dog(Animal): def __init__(self, name, age): super().__init__(name, age) class Cat(Animal): def __init__(self, name, age): super().__init__(name, age) class AnimalShelter: """holds only do...
9d848849b6d688b2872bd9923a86319e3ad73807
Anchals24/InterviewBit-Practice
/Topic - String/Longest Common Prefix.py
1,216
4.25
4
#Longest Common Prefix. #Arr = ["aa" , "aab" , "aabvde"] """ Problem Description >> Given the array of strings A, you need to find the longest string S which is the prefix of ALL the strings in the array. Longest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1...
30ba1cf672c11b233f3842e6463817b4314ca096
ccosteliu/CursuriGrupa5
/Calculator.py
932
3.875
4
def get_input() -> (float,float,str): a=float(input("a >> ")) operatie=input("operatie >> ") b = float(input("b >> ")) return a, operatie, b def suma(a: float, b: float) -> float: return a+b def subt(a: float, b: float) -> float: return a-b def mult(a: float, b: float) -> float: return...
d688b94951b51d6b86d1d926375fc90084b6d772
mit-acl/gym-collision-avoidance
/gym_collision_avoidance/envs/vec_env.py
6,772
3.609375
4
from abc import ABC, abstractmethod from collections import OrderedDict import numpy as np from gym import spaces class VecEnv(ABC): """ An abstract asynchronous, vectorized environment. :param num_envs: (int) the number of environments :param observation_space: (Gym Space) the observation space :p...
cf9b4718f045de78735f19a4c3d43f9caa6c4eb7
cd-chicago-june-cohort/python-fundamentals-john
/names.py
1,201
3.5
4
# Part I students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def print_names(lst): for obj in lst: print obj["first_name"] + "...
ac5c63c61695257d4af49c09a886a1ad0e037a23
jamsidedown/euler_py
/problems/0XX/03X/030/solution.py
373
3.9375
4
def run() -> int: total = 0 i = 10 powers = {str(x): x**5 for x in range(10)} while i < 1_000_000: value = sum(powers[d] for d in str(i)) if value == i: total += value i += 1 return total if __name__ == '__main__': print(f'Sum of numbers that can be written ...
b51c2177c5e5e0f9a71ec560576b7e775866faf0
jamsidedown/euler_py
/problems/0XX/00X/007/solution.py
297
3.984375
4
def run() -> int: primes = [2] current = 3 while len(primes) < 10_001: if all(current % p > 0 for p in primes if p * p <= current): primes.append(current) current += 2 return primes[-1] if __name__ == '__main__': print(f'10_001st prime: {run()}')
37d4a6a67b28f15b3c969faa13323dd87b2c10e4
jamsidedown/euler_py
/problems/0XX/04X/041/solution.py
696
4.09375
4
from itertools import permutations from math import sqrt ENDS = [1, 3, 7, 9] def run() -> int: largest_prime = 0 for n in range(3, 10): digits = ''.join(map(str, range(1, n + 1))) for end in [i for i in ENDS if i <= n]: for xs in map(''.join, permutations(digits.replace(str(end),...
8a04606cbf6f658f55c4b51a9dfbff3dd4fc9022
jamsidedown/euler_py
/problems/0XX/03X/031/solution.py
584
3.828125
4
from functools import lru_cache from typing import List COINS = [200, 100, 50, 20, 10, 5, 2, 1] def run() -> int: return len(combinations(200)) @lru_cache(maxsize=512) def combinations(value: int, last: int = 200) -> List[str]: combs = [] for coin in [c for c in COINS if c <= value and c <= last]: ...
4e8a56547ef768afa3882d872138130a015f7bee
jamsidedown/euler_py
/problems/0XX/00X/008/solution.py
385
3.875
4
from math import prod def run() -> int: number = parse() return max(prod(int(digit) for digit in number[start:start + 13]) for start in range(len(number) - 13)) def parse() -> str: with open('problems/0XX/00X/008/input.txt', 'r') as f: return f.read().replace('\n', '') if __name__ == '__main__...
b0da08a6ebb828ad7f981f2463bd435910f4f9f0
jamsidedown/euler_py
/problems/0XX/03X/034/solution.py
431
4.0625
4
from math import factorial DIGITS = {str(x): factorial(x) for x in range(10)} def run() -> int: # 9! * 7 = 2540160 # 9! * 8 = 2903040 # max 7 digits before a number cannot equal the sum of its digits' factorials return sum(n for n in range(10, factorial(9) * 7) if n == sum(DIGITS[d] for d in str(n))...
e6039f97c07ee400cf94053265938587cece0008
fernandofalla/Tarea1LFP
/Tarea1/NestedLists.py
1,332
3.8125
4
def nested_lists(n): lista = [] valores = [] maximo = 0 minimo = 0 nombres = [] valores_menores = [] contador_notas = 0 for _ in range(n): lista_extra = [] name = input() score = float(input()) lista_extra.append(name) lista_extra.appe...
f6678f222a745950f1a9b4f98e7c40b999f4932b
fernandofalla/Tarea1LFP
/Tarea1/ColletionsName.py
343
3.875
4
from collections import namedtuple n = int(input()) campos = input().split() total_marks = 0 for _ in range(n): estudiantes = namedtuple('estudiante', campos) MARKS, CLASS, NAME, ID = input().split() estudiante = estudiantes(MARKS, CLASS, NAME, ID) total_marks += int(estudiante.MARKS) print('{:.2f}'.f...
223e4d6cfc61a45e03dd12260711a84c31b2bad9
pWhitS/Password-Cracking
/sha256_wordlist.py
1,414
3.703125
4
''' This program opens the dump of Formspring hashed passwords and a selected wordlist file. The password hashes are loaded into a hash table and the wordlist is loaded into an array. The array is then looped through with all possible salts of 00-99 prepended and hashed with sha256. We then look in the hash table for ...
fdbf6d1f2beec9ec3d377096c32ba5d72fceb65e
mohammadasim/python-oop
/oop/multiple_inheritance.py
518
4.03125
4
class ClassA: def hi(self): print('Hello!') class ClassB: def hi(self): print('Hallo!') def another(self): print('We are in classB') class ClassC(ClassA, ClassB): """ In Python when we inherit from multiple classes when a method is invoked it will go and first check ...
b8b1b3d9f012fb10c9792e47617f49dcabcb3fcc
A5he1ter/code
/python/pythonlearn/example3.py
187
3.8125
4
number = input() value = input() count = int(number) + int(value) print(count) number = input() value = input() count = float(number) + float(value) print('sum={0}' .format(count))
9300988d45998347cf9a5a919860f96be6f9b955
rishavb123/DeepQLearningLibrary
/environments/flappy_bird/util.py
393
3.625
4
def clamp(val, minimum, maximum): return val if minimum < val < maximum else minimum if val <= minimum else maximum def collide(rect, circle): closest_x = clamp(circle[0], rect[0], rect[0] + rect[2]) closest_y = clamp(circle[1], rect[1], rect[1] + rect[3]) dist_x = circle[0] - closest_x dist_y = ci...
5bb5333e3b1adace89613fb7d6fb2bae0398aa9e
Lam-Git/Simple-Turtle
/spiral_inside_out.py
396
3.640625
4
import turtle # Inside_Out wn = turtle.Screen() wn.bgcolor("light blue") wn.title("Inside Out") turtle = turtle.Turtle() turtle.color("blue") turtle.shape("turtle") def sqrfunc(size): for i in range(4): turtle.fd(size) turtle.left(90) size = size + 5 sqrfunc(6) sqrfunc(26) sqrfunc(46) ...
46361fc91f0120f58b852ee8776250caebe26a53
larajorge11/python-davor-training
/collections/tuples_ex_02.py
140
3.8125
4
tupla = (13, 1, 8, 3, 2, 5, 8) tupla_lista = [] for i in tupla: if i >= 5: continue tupla_lista.append(i) print(tupla_lista)
bd51b7d753bb5fdb02d11e027a39a52e53196161
larajorge11/python-davor-training
/functions/greet.py
162
3.515625
4
def greet(name, age=0): print(f"Hello {name} how are you?") if not age <= 0: print(f"I know your age: {age}") greet("Davor", 31) greet("Test")
1d30dbc85098e86c7591f4a20d3bbcc4dc8110fa
larajorge11/python-davor-training
/datastructures/listsdemo.py
725
4.03125
4
cars = ['mazda', 'renault', 'kia', 'chevrolet'] print(len(cars)) print(cars[0]) print(cars[1]) print(cars[2]) # var = cars[4] # IndexError: list index out of range print('inside a for loop') for car in cars: if car == 'mazda': print('Great car: ' + car.capitalize()) else: print('Normal car: '...
4a75090075d23c53a62e7834a4e1ba607cc5433d
larajorge11/python-davor-training
/numbersdemo.py
173
3.765625
4
addition = 10 + 5 subtract = 5 - 10 multiplication = 5 * 10 division = 5 / 10 mod = 10 % 5 print(addition) print(subtract) print(multiplication) print(division) print(mod)
a42e7a23a4ec81f18a986144b5db3b15abaf1077
larajorge11/python-davor-training
/datastructures/setsdemo.py
379
3.59375
4
numbersList = [0, 1, 2, 5, 7, -43, 56, 100, 0] numbersSet = {0, 1, 2, 5, 7, -43, 56, 0, 100} # Duplicates are not allowed, not guaranteed the order print(numbersList) print(numbersSet) petsSet = {"bianca", "davor", "danger", "lu", "davor"} print(petsSet) def factorial(num): if num == 1: return 1 el...
404e52fcaed2a30b01a979025d6dea73376c57ab
larajorge11/python-davor-training
/datastructures/setunion.py
310
3.90625
4
pets = {"davor", "bianca", "lu", "luna", "max", "lupe", "jorge"} owners = {"daniel", "zulay", "stefani", "Nanes", "jorge"} union = pets | owners intersection = pets & owners difference = pets - owners print(f"union: {union}") # union print(f"intersection: {intersection}") print(f"difference: {difference}")
ccc34b2118d7e3da33f6d4f0a99700ebc57c9974
larajorge11/python-davor-training
/loops/exercise1.py
89
3.671875
4
numbers = [1, 3, 5, 6, 7, 9] acc = 0 for num in numbers: acc = num + acc print(acc)
dfde71d6425386babc3a58f113da171173d9822f
larajorge11/python-davor-training
/closures/Closures.py
459
3.71875
4
# Local functions # Enclosing namespace # Returning local functions def sort_by_last_letter(strings): def last_letter(s): return s[-1] print(last_letter) return sorted(strings, key=last_letter) my_string = ["hello", "from", "a", "local", "function"] print(sort_by_last_letter(my_string)) def en...
212c2d74f9a7a09455dad0dbae65525c3b1972c7
larajorge11/python-davor-training
/function_decorator/03-decorators.py
319
3.5625
4
import time def measuretime(func): def wrapper(): starttime = time.perf_counter() func() endtime = time.perf_counter() print(f"Time needed: {endtime - starttime} seconds") return wrapper @measuretime def wastetime(): sum([i ** 2 for i in range(10000000)]) wastetime()
a65416b30a0d021f2289b7d253024e3f982a8cdb
JoanneHsu227/driving
/driving.py
609
3.984375
4
country = input('請問您是哪國人:') age = input('請問您幾歲:') if country == "台灣" or country == "韓國" or country == "新加坡": if int(age) >= 18: print('您可以開車') else: print('你不能開車') elif country == "美國" or country == "加拿大" or country == "日本" or country == "英國": if int(age) >= 16: print('您可以開車') else: print('您不能開車') elif c...
d6442d7b239788f9d19dcf802c1c049a6b973258
AtlasR2D2/typing_speed_test_v2
/typer.py
1,381
3.78125
4
from turtle import Turtle import time FONT = ("Courier", 24, "normal") FONT_PROMPT = ("Courier", 14, "normal") ALIGNMENT = "Center" class Typewriter(Turtle): def __init__(self): super().__init__() self.penup() self.hideturtle() self.color("black") self.goto(x=0, y=0) ...
2259c7308691cc71d1af7635b1f0495bc84244eb
emlemmon/emlemmon.github.io
/python/Week1/myAssign01.py
839
4.09375
4
import random from random import randint print("Welcome to the number guessing game!") seed_value = input("Enter random seed: ") random.seed(seed_value) print() def guessing_game(): num = randint(1,100) count = 1 user_guess = -1 while user_guess != num: user_guess = int(input("Please enter a gu...
fa169c751e1bf58b66da7c38ab1a9da8293e364a
emlemmon/emlemmon.github.io
/python/Week3/check03a.py
690
4.0625
4
class Student: """student class for creating new students ids""" def __init__(self): self.firstName = "" self.lastName = "" self.idNum = 0 def prompt_student(): student1 = Student() student1.firstName = input("Please enter your first name: ") student1.lastName = input("Pleas...
ac81f1e984700b6b3993e1b60e29812dc82e69c4
emlemmon/emlemmon.github.io
/python/Week6/check06b.py
1,121
4.4375
4
class Phone: """Parent class that has 3 member variables and 2 methods""" def __init__(self): self.area_code = 0 self.prefix = 0 self.suffix = 0 def prompt_number(self): self.area_code = input("Area Code: ") self.prefix = input("Prefix: ") self.suffix = inpu...
ecdc5d0a46281d943a7f7e7ce6e43bd2e8084d4f
emlemmon/emlemmon.github.io
/python/Week9/check09b.py
860
3.921875
4
class NegativeNumberError(Exception): def __init__(self, message): super().__init__(message) def get_inverse(n): try: n = int(n) if n == 0: raise ZeroDivisionError("Error: Cannot divide by zero") elif n < 0: raise NegativeNumberError("Error: The value ca...
959638e2342fb5f6f2fe4b7513bcf0b383c4d56c
gugawag/so-exemplo-alunos-threads
/threads.py
622
3.53125
4
import threading class Usuario: def __init__(self, idade): self.idade = idade u = Usuario(20) def calculo_estatistico(num_thread, usuario): usuario.idade += 1 print('thread', num_thread, 'idade:', usuario.idade) def salva_dados(num_thread, usuario): usuario.idade += 2 print('thread',...
0fcc04cc9efd8728787545e2bdfe97bf64aa4d03
GarnetLithos/picturelogic_solve_part_logic
/picturelogic_solve_part_logic.py
800
3.515625
4
# -*- coding: utf-8 -*- import json def picturelogic_solve(): file = open('data.json', 'r') data = json.load(file) check = logic_data_valid_check(data) print(check) def logic_data_valid_check(data): row_len = len(data['cols']) col_len = len(data['rows']) rows_check = len_check(data['row...
ab25741b402ab60346bbf982f5625717b5cbc9e2
Jrufino/ListaRepeticaoPython
/ex27.py
670
3.984375
4
'''Faça um programa que calcule o número médio de alunos por turma. Para isto, peça a quantidade de turmas e a quantidade de alunos para cada turma. As turmas não podem ter mais de 40 alunos.''' qtdTurmas=int(input('Digite a quantidade de turmas disponiveis: ')) somaAlunos=0 turmas=[] i=0 for i in range (0, qtdTur...
659c33f1b6b66c0ed2afcbc644072329b545d626
Jrufino/ListaRepeticaoPython
/ex9.py
123
3.90625
4
iteracao=0 while iteracao<51: if iteracao%2 != 0: print('{} '.format(iteracao),end="") iteracao=iteracao+1
0e821086fd74aebd7e245509f1507fc3ac6ccec2
Jrufino/ListaRepeticaoPython
/ex22.py
638
4.21875
4
sair='N' divisivel=[] while sair !='S': num=int(input('Digite um numero inteiro: ')) if num==2 or num==3 or num==5 or num==7: print('Primo') else: if num%2==0 or num%3==0 or num%5==0 or num%7==0: if num%2==0: divisivel.append(2) if num%3==0: ...
58ff88c3d9e577655eb0bc20fd587cc403a09f13
Jrufino/ListaRepeticaoPython
/ex12.py
234
3.984375
4
num=int(input('Digite um numero entre 1 e 10: ')) multiplicador=1 print('Tabuada de {}'.format(num)) while multiplicador<11: print('{} X {} = {}'.format(num,multiplicador,num*multiplicador)) multiplicador=multiplicador+1
31cbea228dee3603cf1f8e8eb53dc63af1331ea6
Jrufino/ListaRepeticaoPython
/ex13.py
379
4.0625
4
base=int(input('Digite a base:')) expoente=int(input('Digite o expoente:')) resultado=base iteracao=1 if base==0: resultado=0 elif base==1: resultado=1 elif expoente==0: resultado=1 elif expoente==1: resultado=base else: while iteracao < expoente: resultado= resultado*base iteracao=...
41f61ba806ae6942a62b114ae624ab00ce0d6b7d
kobecow/algo
/NoAdjacentRepeatingCharacters/problem.py
543
4.15625
4
""" Given a string, rearrange the string so that no character next to each other are the same. If no such arrangement is possible, then return None. Example: Input: abbccc Output: cbcbca """ def rearrangeString(s: str) -> str or None: pass print(rearrangeString("gahoeaddddggrea")) # no order required # ahg...
bb83b46ccd9d9cfd80b471e785e2fa0ce10ca771
maurusian/aliquot
/aliquot.py
9,101
3.625
4
from math import sqrt from igraph import * def getDivisors(n): #print('...Getting divisors for '+str(n),end='') divisors = [] for i in range(1,int(sqrt(n))+1): if n%i == 0: divisors.append(i) divisors.append(n//i) divisors = sorted(list(set(divisors))) #print('....do...
ac476f74a87d5a618736c4231be9b48366735639
rob-roeburn/advent-of-code
/solutions/day6/day6_puzzle1.py
686
3.6875
4
#!/usr/bin/env python # coding: utf-8 def countAnswers(__values): batchComplete = False answerCount = 0 answerDict = {} for answers in __values: for answer in answers: answerDict[answer] = 1 if answers == '': batchComplete = True if batchComplete: ...
bcc4410c0cf3e0fba859b17813accee8a9171879
lonelyCoder-jrbing/pythonDemo
/algorithm/Demo04.py
2,162
3.90625
4
# # 利用子字符串寻找在大的字符串中子字符串第一次匹配的位置 # # 定义一个窗口的长度 字串的长度 # import math # # bigStr = "ilovechinaiwanttobesuperman" # littleStr = 'want' # newStr = bigStr.replace(littleStr, "") # print(newStr) # # for i in range(0, len(bigStr) - 1): # # print(bigStr[i:i + len(littleStr)]) # if bigStr[i:i + len(littleStr)] == littleSt...
dd8d249901ca8e6951812f4214ce1f98763470b1
csubram/boston-marathon-scrape
/filter.py
1,310
3.703125
4
from constants import CSV_COLUMNS from abc import ABCMeta, abstractmethod from typing import List class Filter: __metaclass__ = ABCMeta @abstractmethod def __init__(self, bucket): self.filter_category = None self.filter_bucket = bucket def filter(self, row) -> bool: match = ro...
42c245aac555a9a5d33b937903de1c75219c6a4b
cybort/APRG18
/assignments/assignment3/assignment.3.py
4,483
3.984375
4
class Node: def __init__(self, data, parent=None): ''' nodeType indicates if it is a 2 node, a 3 node, or a 4 node d1, d2, d3 are the data from left to right c1, c2, c3, c4 are the children, from left to right ''' # make sure that if c2 is None, so is c3 and c4. And i...
363260d40230fed4bc9d449b8ee0a32e6f729a54
MWWST/pythonFundamentals
/selectionSort.py
1,407
3.609375
4
## linear iteration find the minimum ## swap minimum with previous minimum value ## start from the next value, find the minimum ## swap with the previous import datetime from random import randint timer_start = datetime.datetime.now() sortMeArray = [] for i in range(0,100): sortMeArray.append(randint(0,1000)) # pri...
cf0ec113a258e5a220190b029d56b70f63d924dc
MWWST/pythonFundamentals
/scoreAndGrades.py
426
3.828125
4
myList = [] for x in range(0,10): print "What is your score?" thisEntry = input() myList.insert(x,thisEntry) for x in range(len(myList)): if myList[x] <59: grade = "F" elif myList[x] >=60 and myList[x] <=69: grade = "D" elif myList[x] >=70 and myList[x] <=79: grade = "C" elif myList [x] >=80 and myList[x...
9754e370efefe99d8b1e5b7a28cc2b38cb042198
margosi4/PycharmTutorial
/helloworld.py
200
3.65625
4
import pandas as pd import numpy as np print('hello world!') dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD')) print(df.head())
b6a1309a07f6203b3d183552e30e4e05c5582713
Kishy-nivas/ds-in-python
/linked list.py
522
4.15625
4
# linked list implementation class Node(object): def__init__(self,value,pointer=None) self.value =value self.next =None class LinkedList(object): def __init__(self): self.head =None self.tail =None def add(self,value ): if self.head==None: self.head =self.tail = Node(value ) self.head.next =se...
bc23f0d411f66220ffa29207bc63a4bc96c50b4c
rucpata/udemy-python-zaawansowany
/Udemy-kurs-zaawansowany/sekcja_5/5.73_cache_LAB.py
359
3.5625
4
import time import functools @functools.lru_cache(maxsize=100) def fib(n): if n <= 2: result = n else: result = fib(n - 1) + fib(n - 2) return result start = time.time() for i in range(50): result = fib(i) print('{} {}'.format(i, result)) stop = time.time() print('Execution time'...
79c0ffd1421e00a29672031d87e7b7499b9b0c0b
rucpata/udemy-python-zaawansowany
/Udemy-kurs-zaawansowany/sekcja_2/2.6_Typy_zmienne(mutlabe)_i_niezmienne_(immutable).py
819
4.09375
4
number = 10 print('Variable number:', number, id(number)) number += 2 print('Variable number:', number, id(number)) text = 'Africa' print('Variable text:', text, id(text)) text +=' is hot' print('Variable text:', text, id(text)) list = [1, 2, 3] print('Variable list:', list, id(list)) list.append(4) print('Variable l...
1921359b15528a67ce6dbaaeeae4b2bb8f23ff3d
jaspreet7037/python-in-vs-code
/even_number.py
121
3.84375
4
''' for i in range(2,102,2): if i%2==0: print(i) using if condition ''' i=2 while i<102: print(i) i=i+2
62e49cfa47fcb27e3c6b6f17b8583b0a51311b7b
jaspreet7037/python-in-vs-code
/numloops_projects.py
164
3.875
4
''' # 1 i=10 while i>0: print(i, end=" ") i=i-1 # 2 print(" ") i=242 while i>0: print(i) i=i-2 ''' # 3 i=101 while i>0: print(i) i=i-2
7e340a7dcc0ca595c5a031023e615bc9d8d00424
jaspreet7037/python-in-vs-code
/filehandling7.py
375
3.59375
4
""" In this Python program the content in the file will get stored in another file in reverse order . """ file = open("C:\\Users\\jaspr\\OneDrive\\Desktop\\python in vs code\\abc.txt",'a') with open("C:\\Users\\jaspr\\OneDrive\\Desktop\\python in vs code\\abc.txt",'r') as myfile: data = myfile.read() ...
cd951780fb979e27efc532c7f03b279bc163c736
jaspreet7037/python-in-vs-code
/program.py
170
4
4
print('hello world🚀') num1 = int(input("Enter the number")) print(num1) n=1 for a in range (5) : print(n) n = n*10+1 a= int(input('enter the number')) print(a)
d0bb0f1edaecf5b3773eadbc4e45a446ba8efbd3
allisnone/letusgo
/EMS/agent/firstTimeConfiguration.py
1,586
3.640625
4
# -*- coding:utf-8 -*- ''' Note: Run it for the first time configuration. Function: Initialize timestamp.txt: write a recent date time (the current local time minus 5min) to the file. Addition: timestamp.txt: It helps to query the emsdb_latest_time of local site quickly later. It is under ...
7c057d9a2e709b5a269950a0357be4faafbd6385
j0mueller/python_practice
/loops.py
3,136
4.09375
4
################ WHILE LOOPS ################## # 1: validate input choice = raw_input('Enjoying the course? (y/n)') while choice != 'y' and choice != 'n': choice = raw_input("Sorry, I didn't catch that. Enter again: ") # 2: While loop set to 'True' - guaranteed to run at least once. Uses 'if -- break' to exit lo...
8e1ade83d20e90bf67eeae24a581945ec5eaadca
j0mueller/python_practice
/xy_02_variables_and_collections.py
8,896
4.40625
4
# Source: https://learnxinyminutes.com/docs/python/ for python v2.7 with insertions for v3.x #################################################### # 2. Variables and Collections #################################################### ############## V 2.7 ############### => Print doesn't use parentheses # Python has a p...
0ca3cc1ecb2ea7996b3cf7b9df2b88201e0f084d
MelonFaceDOOM/cannabis_scraping
/cleaning/clean_weight_price.py
3,680
3.609375
4
import re def clean_weight(text): """Clean weight string through six steps. Steps: 1. Remove parentheses 2. Remove hyphens 3. Replace variant string components with standardized ones 4. Standardize weight unit values 5. Fix odd numerical values (i.e. 3-5 used instead of 3.5) ...
785729bff53baa507d966dd119c4b82a00c107eb
marianog1000/Curso-de-Phyton
/pop del remove.py
173
3.671875
4
n = [1, 3, 5] # Remove the first item in the list here n.pop(0) # elimina y devuelve index n.remove(1) # elimina el nro. 1 del(n[1]) # elimina pero no devuelve print n
eb7f918ae67489ad11221130868bcf04103a97f5
jayanthns/hackerrank_problems
/max_sum_sub_array.py
655
3.828125
4
def max_sub_array_sum(a, size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 # Do not compare for all elements. Compare only # when max_ending_here > 0 el...
a14c7e9204ff48a1794f00669a7fdaf06544714d
entombed/pythonOpenedu
/w1-l3.py
789
4
4
""" Считать единой строкой без пробелов набор целых чисел (28745623873465386), удалить все дубликаты, вывести отдельными операторами вывода в порядке возрастания и в порядке убывания в виде кортежей целых чисел (2, 3, 4, 5, 6, 7, 8) и (8, 7, 6, 5, 4, 3, 2). Пример входных данных: 28745623873465386 Пример выходных дан...
b0a19656aefadd84e27ca37a1682469028c802fe
brandonjyan/AlgorithmicToolbox
/week5_dynamic_programming1/1_money_change_again/change_dp.py
678
3.5625
4
# python3 import math def change_naive(money): min_coins = float("inf") for num1 in range(money + 1): for num3 in range(money // 3 + 1): for num4 in range(money // 4 + 1): if 1 * num1 + 3 * num3 + 4 * num4 == money: min_coins = min(min_coins, num1 + num...
c47370697303df60b4e50e91092a5564b047a718
stephenforsythe/crypt
/shift.py
1,172
4.125
4
""" This is essentially a substitution cypher designed to avoid fequency analysis. The idea is to shift the char to the right by an increasing number, until n = 25, at which time the loop will start again. Spaces are treated as a character at the end of the alphabet. """ import string FULL_ALPHABET = string.lowercas...
c0ca428731c8355d0715d142c9b808d854a2cc28
parmarmanojkumar/MITx_Python
/6001x/Quiz/quiz_problem_7.py
792
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 13 07:18:35 2016 @author: VirKrupa """ listA = [1, 2, 3] listB = [4, 5, 6] def f(a,b): return (a > b) d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} def dict_interdiff(d1, d2): ''' d1, d2: dicts whose keys and values are integers R...
5887faf237a4105ef920a9a84fb6b72e4541a039
parmarmanojkumar/MITx_Python
/6002x/week2/L4P5/histogramfun.py
1,125
3.5
4
import pylab import re # You may have to change this path WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of uppercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loa...
04f5b8a4e2505eb5b2ad7c06b7721f3650d420fb
laurineaujeau/Python1
/exercice2.py
402
3.578125
4
tab=4*[0] index=0 while index<4: val=input('Entrez un entier >') if val.isalpha() : print('Entier incorrect') else: tab[index]=int(val) index=index+1 max=tab[0] min=tab[0] index=0 for i in tab: if max<tab[index]: max=tab[index] if min>tab[index]: min=tab[inde...
f3762c7152ce94cc58010153598331bb9c93621a
Marrior-dot/Atividades_de_Sistemas
/bin_to_dec.py
606
3.921875
4
from math import pow def binonot(varyable): o = "01" for char in varyable: if char not in o: return False else: return True def counter(variable): start = 0 while start <= len(variable)-1: yield start; start = start + 1; r = input("Entre com um número binário: ") wh...
00d6b6adf0effb4ed6a0a00e854c84ae0f086306
glaude/n_body_simulation
/Particle3D.py
4,049
4.125
4
""" Describes a 3D particle, methods to update particle position, velocity, and calculation of energy values. """ import numpy as np class Particle3D(object): def __init__(self, label, x_pos, y_pos, z_pos, vel_x, vel_y, vel_z, mass): """ Initialises a 3D particle instance. :param label: pa...
e4b73c1e38e5139119e97616bc9db85cca719946
MCLACS/Python-Public
/Module1/1C-TaxAndTip.py
325
4.03125
4
TAX_RATE = 0.05 TIP_RATE = 0.20 # Ask user to enter cost cost = float(input("Enter cost of meal:")) # Calc tax and tip tax = cost * TAX_RATE tip = cost * TIP_RATE # Calc total cost total = cost + tax + tip # Print the result print("The tip is $%.2f\nThe tax is $%.2f\n\nThe total is $%.2f" % \ (tip, tax, total...
d1424e285bd883efbdcb31142c62efa279769de5
MCLACS/Python-Public
/Module2/2C-ValidANumber.py
685
4.0625
4
anum = str.upper(input("Enter your A Number: ")) valid = True if len(anum) != 9: valid = False elif anum[0] != 'A': valid = False elif anum[1].isdigit() == False: valid = False elif anum[2].isdigit() == False: valid = False elif anum[3].isdigit() == False: valid = False elif anum[4].isdigit() == Fa...
94d820e75fa563ef0eb23973f1db1f6ccfd613af
MCLACS/Python-Public
/Module1/1F-UnitsOfTime.py
400
4.09375
4
# Magic numbers HR_DAY = 24 MIN_HR = 60 SEC_MIN = 60 days = int(input("Enter days:")) hours = int(input("Enter hours:")) mins = int(input("Enter minutes:")) seconds = int(input("Enter seconds:")) interval1 = days * HR_DAY * MIN_HR * SEC_MIN interval2 = hours * MIN_HR * SEC_MIN interval3 = mins * SEC_MIN total = inte...