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
1d7b4953f5108c63531de5d18af2722baaef0f21
hhummel/codewars-kata
/python/moving_zeros.py
366
3.703125
4
#Solution to "Moving Zeros to the End" 5 kyu #https://www.codewars.com/kata/52597aa56021e91c93000cb0 def move_zeros(array): #Have to be careful with False new_array = [element for element in array if element != 0 or element is False] zero_array = [element for element in array if element == 0 and element is...
7e17cc992441cecfff31476532ada3461462c275
hhummel/codewars-kata
/python/permutations.py
286
3.71875
4
#Solution for "Permutations" 4 kyu #https://www.codewars.com/kata/5254ca2719453dcc0b00027d def permutations(string): from itertools import permutations perm = permutations(list(string)) set_ = set([''.join(p) for p in perm]) list_ = list(set_) return sorted(list_)
fc9d7761b45597c8d3efb6fd81f76f0c96d547b7
Lenux56/FromZeroToHero
/text_vowelfound.py
519
4.4375
4
''' Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found. ''' import re def multi_re_find(): ''' search and count vowels ''' phrase = input('Please, enter a phrase to find vowels and count it: ') while not phrase: ...
21770c7ec274e6c661308deaf2695aafd308c7d5
Lenux56/FromZeroToHero
/gen_pi.py
1,456
4.03125
4
''' generation pi to nth digits ''' from decimal import Decimal, getcontext def gen_pi(n_digits): ''' The Chudnovsky algorithm is a fast method for calculating the digits of π, based on Ramanujan’s π formulae. https://en.wikipedia.org/wiki/Chudnovsky_algorithm ''' getcontext().prec = n_digits+2...
f5f5ab83b3d3936e28aa445b4d563e1ffe0ed600
TXZhe/Magic_Mirror
/server/dictionary.py
1,344
3.625
4
hair_clothes=[ "fluffy hairstyle", "flat hairstyle", "flat head of hair", "short hair", "oblique bangs", "neat bangs", "both sides of face have hair", "black hair", "make the chin prominence or contraction", "Chinese style", "slightly thic...
4ebe37c818382a42755c0d90736ac1591f920007
Hardonsky223/python-tasks
/task1/task1.py
269
3.5
4
from random import randint n=30 A = [randint(-100,100) for i in range(n)] print(A) b=max(A) print('max =',b) c=A.index(b) print('number =',c+1) A2 = [i for i in A if i % 2 == 1] if not A2: print("Немає чисел") else: A2.sort(reverse=True) print(A2)
3df580f456da3c166b9f2ee56068fba4e2df20c0
jacksky118/file_test
/files_demo.py
1,482
3.9375
4
import os # 获得单个文件的大小 files_dict = dict() def getFileSize(file): if os.path.exists(file): size = os.path.getsize(file) files_dict[file] = size # 列出目录下所有的文件和子目录的文件 def listFiles(path="."): # 传入路劲默认为当前目录 if not os.path.exists(path): print('path error') return None file = '...
95eca5a856196e82b5a99aafd13699860f7949ff
casvdrest/ci_practicum1
/backtrack.py
1,958
3.9375
4
# runs the backtrack search algorithm class Backtrack: from board import Board def __init__(self, board): self.board = board self.found = [] self.i = 0 def run(self): return self.backtrack([self.board]) def backtrack(self, stack): """ ...
aae05fadeecb1f4415b13733c996722ac59dd950
code-in-the-schools/IfElseStatements_AshliBullock
/main.py
199
3.90625
4
V = ("a", "e", "i", "o", "u") I = str(input("The word is...")) uI = I.lower() print(uI) for i in range(len(I)): if I[i] in V: print(I[i], ": Vowel") else: print(I[i], ": Consonant")
9a347e36dffbc7fb037654d29d1a1a95d99b8fc6
Gerald-Zhu/leetcode-test
/链表/2 两数相加.py
563
3.640625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: def dfs(l, r, i): if not l and not r and not i: return N...
68f9da2aada263278be6f95f3563952f8802cc46
Gerald-Zhu/leetcode-test
/二叉树/106 从中序与后序遍历序列构造二叉树.py
646
3.84375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def helper(iOrder, pOrder): if n...
9eef5d5e25b43a409fc6f440bc9e30e3d6bf9b19
zone31/Advent-of-Code-2020
/Days/1/Python/run.py
2,067
3.5625
4
#!/usr/bin/env python3 import os import sys #######################Helping functions########################### def data_parser(filepath): """Parse the data by splitting each line into a number.""" d = [int(line) for line in open(filepath)] return d #########################Main functions##############...
0b5697c62362cf257c5eb2de2fa0562605095924
barnesjake/python-stuff
/python_101/numbers.py
335
3.609375
4
### numbers 2 + 2 (50 - 5*6) / 4 17 / 3 # classic division returns a float 17 // 3 # floor division discards the fractional part 7 % 3 # the % operator returns the remainder of the division 5 * 3 + 2 # result * divisor + remainder 5 ** 2 # 5 squared 2 ** 7 # 2 to the power of 7 width = 20 height = 5 * 9 ...
7c66f35f4e7fe45ea3fa47241d86440f31576bb1
BensThoughts/learning-algorithms
/src/ch02/palindrome.py
326
3.890625
4
def main(): print(is_palindrome("A man, a plan, a canal. Panama!")) def is_palindrome(w): w = ''.join(e for e in w if e.isalnum()).lower() if len(w) % 2 == 0: middle = int(len(w)/2-1) return w[:middle:-1] == w[0:middle+1] else: middle = int(len(w)/2 - .5) return w[:middle:-1] == w[0:middle] ...
a4da9ec78ab9353c0c551081a46820466c612730
BensThoughts/learning-algorithms
/src/ch05/merge_sort.py
593
3.828125
4
def merge_sort(A): aux = [None] * len(A) def rsort(lo, hi): if hi <= lo: return mid = (lo+hi) // 2 rsort(lo, mid) rsort(mid+1, hi) merge(lo, mid, hi) def merge(lo, mid, hi): aux[lo:hi+1] = A[lo:hi+1] left = lo right = mid+1 for i in range(lo, hi+1): if left > mid: ...
49b7f797f935beada4afdd8a22a5ede684efbe9a
hadirana12345/sp19bscs-se-44
/GUI1.py
738
3.796875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #GUI Libararys #tkinter>buttons>show_text> import tkinter window = tkinter.Tk() window.title("GUI") label = tkinter.Label(window, text = "Hello World this is Abubakr\n" "Hello World this is Abubakr Hello World this is Abubakr\n" ...
9157be75b73ad948da9f975e94256331c6d9c913
TurtleThyme/HackerRank
/plusminus.py
331
3.640625
4
def plusMinus(arr): zeros = 0 abovezeros = 0 belowzeros = 0 for i in range(len(arr)): if arr[i] == 0: zeros += 1 elif arr[i] > 0: abovezeros += 1 else: belowzeros += 1 print(abovezeros/len(arr)) print(belowzeros/len(arr)) print(zero...
94af8e6b10222bb6fbe6fbe2021a94581eb5c50e
bleamer/ml
/ann/mlp.py
4,586
3.6875
4
import numpy as np from pprint import pprint from random import random class MLP: def __init__(self, num_inputs=3, hidden_layers=[3, 3], num_outputs=2): """Constructor for the MLP. Takes the number of inputs, a variable number of hidden layers, and number of outputs Args: ...
0810a64d3023990cd5e83e0eade953b38468b0dc
tamirMoshiashvili/DL_ex2
/part2/top_k.py
1,804
3.5625
4
from time import time import numpy as np import sys def read_vocab_file(filename): """ :param filename: name of vocabulary file. :return: list of strings, where each is a word. """ f = open(filename, 'r') lines = f.read().splitlines() f.close() return lines vocab = read_vocab_file('...
c2dcf4f3afd6e83c455a22cccd0b45b7b4c613aa
Jkt1412/basic-ml
/ml/neural_network.py
9,765
4.5
4
""" This class is an implementation of a neural network using the sigmoid activation function. """ import numpy as np import matplotlib.pyplot as plt class NeuralNetwork: def __init__(self, input_nodes, output_nodes, hidden_layers, nodes_per_hidden_layer): """ Create a NeuralNetwork with the giv...
e9b413b954831e1cefc621a5146eba6252cf0d7b
kojicovski/python
/exercises/ex023.py
823
3.625
4
num = input('Type a number from 0 to 9999: ') num1 = int(input('Type another number from 0 to 9999')) if len(num) == 4: print(f'Unit: {num[3]}') print(f'Ten: {num[2]}') print(f'Hundred: {num[1]}') print(f'Thousands: {num[0]}') elif len(num) == 3: print(f'Unit: {num[2]}') print(f'Ten: {num[1]}')...
c7cab12b1b588da0baf63529a9a081bf31d2109c
kojicovski/python
/exercises/ex074.py
442
3.53125
4
import random tup = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) ) bigger = 0 smaller = 255 for i in range(5): if tup[i] > bigger: bigger = tup[i] elif tup[i] < smaller and tup[i] != 0: ...
540e51caf1843a96771c1d6a145d51f637e340d5
kojicovski/python
/exercises/ex092.py
566
3.859375
4
import datetime people = {} x = datetime.datetime.now() x = int(x.strftime("%Y")) people["Name"]= str(input("Name: ")) age = int(input("Year of Birth: ")) age = x - age people["Age"] = age people["WorkCard"] = int(input("Work Card: ")) if people["WorkCard"] == 0: for v, k in people.items(): print(f"{v}:...
40d20f9b5d8ea8c1596712790168611a10f1df12
kojicovski/python
/exercises/ex059.py
1,318
3.90625
4
num1 = int(input('Type first number: ')) num2 = int(input('Type second number: ')) print('What u want to do?') menu = int(input('1 - To sum \n2 - To multiplication\n3 - Higher number\n4 - News numbers\n5 - Exit\n')) class Calc(): def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 ...
7ef180473ff74ca84b42b8298b2dae5e8e4d6a1c
kojicovski/python
/course/class07a.py
242
3.765625
4
n1 = int(input('Value one: ')) n2 = int(input('Value two: ')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print(f'The sum is {s}, multiplication is {s}, division is {d:.3f}, entire divison is {di}, potentiation is {e} ')
2cf324ff75aad67c528a30bc86c29cfa3bfb167f
kojicovski/python
/exercises/ex035.py
233
4.125
4
a = int(input('Value a: ')) b = int(input('Value b: ')) c = int(input('Value c: ')) if a > b-c and a < b+c and b > a-c and b < a+c and c > a-b and c < a+b: print('You can do a triangle') else: print('You cant do a triangle')
60a5185cf9387bf3deafbfc45e8ba4968bb6c11b
kojicovski/python
/exercises/ex87.py
536
3.984375
4
import random mat = [[], [], []] count_num_odd = 0 third_sum = 0 for i in range(0, 3): for j in range(0, 3): num = random.randint(1, 9) #num = int(input(f"Position {i},{j}: ")) mat[i].append(num) for i in range(0, 3): for j in range(0, 3): if mat[i][j] % 2 == 0: co...
5414a8dc9b86c44d1f7c1a8167c8c3bb1eb08b11
kojicovski/python
/exercises/ex068.py
630
3.90625
4
from random import randint num = int(input("Type a number: ")) choice = str(input('Choose even or odd: ')).strip() num_pc = randint(0,10) count = 0 while True: sum = num + num_pc print(f'Sum:{sum}') if sum % 2 == 0 and choice == 'E': print("Even, you're right") count += 1 elif choice ...
5a96aba3ee6cea6100da1ff75d615a15c4dd190a
kojicovski/python
/course/class09a.py
357
3.65625
4
frase = 'Curso em Vídeo Python, testando tratamento de strings' print(frase[::2]) print(len(frase)) print(frase.count('a')) print('Python' in frase) print(frase.find('testando')) lista = frase.split() print('Lista de frase : {}'.format(lista)) arquivo = open('python-test.txt', 'r') for list in arquivo: valor...
0b631638a7975adc8769aa25c67c69dcd1c193ee
hendricksonsarahl/voluntr
/helpers/datetime_helpers.py
3,420
3.921875
4
import datetime def readable_date(opp_date): ''' takes a single datetime input and returns a string to display along with opportunities ''' if opp_date == datetime.datetime(2100,1,1,23,30): opp_date = "Flexible schedule" else: opp_date = opp_date.strftime('%A, %B %d, %Y') return opp_dat...
7ca0fd778fdae125c7b34874ed3d98d334806668
Kohdz/Konek
/konek/search/utils.py
809
3.828125
4
import sqlite3 def search_database(database, query): connect = sqlite3.connect( '/home/joe/Projects/twitter-clone-v1/konek/twitterclone.db') cur = connect.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table'") for tablerow in cur.fetchall(): # finds all the tables in...
6fd37514ac6e3d8425ed3646191bfd539b2947b5
nurlan5t/python-homeworks
/hw15_queue в ООП варианте.py
551
4.21875
4
''' Написать queue в ООП варианте. В классе должно быть состояние хранящее со списком и метод pop()''' from collections import deque class My_list(): q = deque() q.append('a') q.append('b') q.append('c') print("Initial queue") print(q) print("\nElements dequeued ...
d1a78c4fdd0e77a279be858762ebfb256635d370
nurlan5t/python-homeworks
/homework5_cb2.py
1,117
3.5625
4
def make_bricks(small, big, goal): if (goal//5 <= big) and ((goal - 5*(goal//5))<= small): return True elif (goal//5 >= big) and ((goal - 5*(big)) <= small): return True return False def no_teen_sum(a, b, c): return fix_teen(a) + fix_teen(b) + fix_teen(c) def fix_teen(n): if 13 <= n and n <= 19 and...
50d4d4839430f1fb7808283132809b251fb58e8f
vikas-ukani/Hacktoberfest_2021
/python_pathvisualizer/bfs_visualizer.py
2,690
3.890625
4
from Spots import * import queue import timeit def bfs_compute(draw, grid, start, end): """ Computing the bfs """ visited = [] came_from = {} the_queue = queue.Queue() visited.append(start) the_queue.put(start) # algorithm: https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode ...
fa714b402a7fb0cc6faba0c19ebbff7598357764
vikas-ukani/Hacktoberfest_2021
/Python/Speed_typing_test.py
1,807
3.78125
4
from tkinter import * from timeit import default_timer as timer from PIL import ImageTk,Image import random window = Tk() #Dimensions for the gui window window.geometry("500x200") window.title('Speed typing test') window.configure(background="Sky blue") #here the path of the image should uploaded to set it in the wi...
32ba8668e053865b2355a2ab638cc8e1902eabf6
vikas-ukani/Hacktoberfest_2021
/Python/numberGuessingGame.py
807
3.90625
4
import random print("lets play a game") print("I have a secret number. Lets see if you can guess it.") print() Input = 0 def ask(): try: global Input Input = int(input("Guess a number >>> ")) except: ask() number_of_times = [] sec_number = random.randint(0,100) ask() won = False ...
20e59d6494ba4c87140ccf88af9e846164ce0596
vikas-ukani/Hacktoberfest_2021
/Rock_Paper_Scissors.py
1,368
4.28125
4
import random print("Welcome to rock paper scissors game .....") print("You have three chances greater the wins in individual game will increase your chance to win") print("Press 0-->paper , 1-->rock , 2-->scissors") comp = 0 player = 0 for i in range(3): player_choice = input("Your turn") comp_choice=random.r...
fedd83912946833ae81f59f608ea6eb75d87c27a
liunianzuoan/web_zuto
/0307_selenium_window/d4.py
810
3.65625
4
# 鼠标的一些悬浮操作 import time from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By drive = webdriver.Chrome() # 访问百度 #隐式等待 drive.im...
ea80c288484ab1694ff761e1b9c2807f43f92fbc
liunianzuoan/web_zuto
/0309_selenium_file/d3.py
976
3.671875
4
# python是不能浏览器的属性的 只能通过js去改变 所以需要发生js代码 import time from selenium import webdriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver =...
34b3982f50bd64b0c7439b5c87b69166ca6ec960
agrawal-prateek/codecata-hunter
/pro/pro11.py
178
3.65625
4
import math n = int(input()) while (n != 0): l = math.sqrt(n) if l == int(l): print(int(l)) break else: n = n - 1 if n == 0: print('no')
98d55e3653ea75a525863b3fb4b06448689f441e
KeleiAzz/Project-Euler
/10.Summation of primes.py
550
3.875
4
import math def is_prime(n): if n == 1: return False elif n < 4: return True elif n%2 == 0: return False elif n<9: return True elif n%3 == 0: return False else: r = math.floor(math.sqrt(n)) f = 5 while f <= r: if n % f =...
3f7c545c8765583c918074b6c73f4114522a1d2b
emmanuelnaveen/decision-science
/date_format.py
292
4.3125
4
from datetime import date # Read the current date current_date = date.today() # Print the formatted date print("Today is :%d-%d-%d" % (current_date.day,current_date.month,current_date.year)) # Set the custom date custom_date = date(2021, 05, 20) print("The date is:",custom_date)
74b70f4cb2525c9d77a65cbf7d127ff0c1c42e9b
dave-vazquez/Computer-Architecture
/ls8/cpu.py
7,201
3.515625
4
"""CPU functionality.""" import pprint import sys p_print = pprint.PrettyPrinter(width=30).pprint # RESERVED REGISTERS PC = 4 IM = 5 IS = 6 SP = 7 # RESERVED ADDRESSES STACK_START_ADDRESS = 0b11110011 # OPERATION CODES HLT = 0b00000001 LDI = 0b10000010 JMP = 0b01010100 PRN = 0b01000111 PUSH = 0b01000101 POP = 0b01000...
527db5b96ed4336b37ddb4db7c925059f49b44d0
kuspia/ML-Projects
/Data analysis_Linear_Logistic_Regression model/HR_Dataset_analysis.py
13,695
4.375
4
# Author: Kushagra Shukla # HR data analysis # Download HR.csv from https://www.kaggle.com/giripujar/hr-analytics # We will look into how linear regression in ML help in data analysis and step by step we will illustrate that #Description of coloumns is shown below: #Coloumn 1: satisfaction_level- It tells ...
87dec9f888e3b9fe35348ea22cf7f5eb0b706530
ivelinakaraivanova/SoftUniPythonOOP
/src/Attributes_and_Methods_Lab/hotel_04/project/hotel.py
1,303
3.546875
4
class Hotel: def __init__(self, name: str): self.name = name self.rooms = [] self.guests = 0 @classmethod def from_stars(cls, stars_count): name = f"{stars_count} stars Hotel" return cls(name) def add_room(self, room): self.rooms.append(room) def ta...
292615df980d1316a01ac399f76c53de78e538dd
ivelinakaraivanova/SoftUniPythonOOP
/src/Testing_Lab/test_worker_01/tests/worker_test.py
1,413
3.59375
4
from test_worker_01.project.worker import Worker import unittest class WorkerTests(unittest.TestCase): def setUp(self): self.worker = Worker('Ivan', 1000, 50) def test_worker_is_initialized_correctly(self): self.assertEqual(self.worker.name, 'Ivan') self.assertEqual(self.worker.salary...
f771dd049ecdda1d25c14147dd1aa72d1a18b8d0
danaimone/Blind_75
/Graphs/graph-valid-tree/graph-valid-tree.py
551
3.59375
4
from collections import defaultdict class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: if len(edges) != n - 1: return False adj_list = defaultdict(list) for A, B in edges: adj_list[A].append(B) adj_list[B].append(A) visited ...
0027859482850700783c96d17653f21680912714
MenMor/Ejercicios01
/BaseDecimal.py
731
3.828125
4
# Conversión de un entero con cualquier base a decimal numero = int(input("Ingrese valor a convertir: ")) base = int(input("Ingrese base del valor: ")) num_output = numero # Ingresar valores en lista de forma invertida lista_numeros = [] bucle = 4 while bucle == 4: invertir = numero % 10 lista_numeros.append(...
d774ae73375bfe70d49bffd1195bffdb9923df1d
MenMor/Ejercicios01
/maximo_comun_divisor_E.py
1,269
3.953125
4
# Encontrar máximo común divisor (mcd), entre dos números num_uno = int(input("Ingrese valor: ")) num_dos = int(input("Ingrese segundo valor: ")) list_1 = [] list_2 = [] list_3 = [] # Llevara valores que al ser comparados de listas anteriores sean iguales # Guardo en una lista los valores primos de cada número: cont...
40142f4b931afed05041f62eac978f96029c25e2
RockmanJim/python-study
/sumt.py
187
3.796875
4
def sumtri(d, e, f): return d + e + f a = int(input("please input a:")) b = int(input("please input b:")) c = int(input("please input c:")) print("the answer is %d"%(sumtri(a, b, c)))
f3f9e9a7c404012f9ad2fbaf35550159cc6daf2d
RockmanJim/python-study
/python基础/python语法基础/面向对象-2/11-多继承注意点.py
427
3.515625
4
class Base(object): def test(self): print("Base") class A(Base): def test(self): print("A test1") class B(Base): def test(self): print("B test2") class C(A, B): #def test(self): # print("C test3") pass c = C() #看看到底运行了哪个test方法? c.test() print(C.__mro__) #C.__mro__决定了调用方法时的搜索类的顺序,如果某个类中找到了方法,就停住 顺序...
aab5f99f6a042ae5ec3f605854981294256e0eb0
RockmanJim/python-study
/python基础/python语法基础/模块/03-all的作用.py
213
3.546875
4
# 这里赋值之后,就能限定该模块被import时,会被引入的内容了 #__all__ = ["test1", "Test"] def test1(): print("test1") def test2(): print("test2") num = 10 class Test(object): pass
9393bec72a3913bd324c8f45192f3fc8080efd16
DuwanVargasSalas96/Baloto
/main.py
1,125
3.703125
4
# -*- coding: UTF-8 -*- #Import import os from random import randint as rnd #Crear balotas def playBaloto(): #Declarar baloto = [] balota = 0 #Primeras balotas while len(baloto) < 5: #Asignar balota = rnd(1, 43) #Busqueda duplicados if balota not in baloto: baloto.append(balota) #Ultima balota bal...
096576a602348941ee886a60df67d3f6b6381c03
eveem/tcg_dojo
/player.py
1,668
3.515625
4
from random import choice class Player: def __init__(self, pid=0): self.pid = pid self.deck = {0: 2, 1: 2, 2: 3, 3: 4, 4: 3, 5: 2, 6: 2, 7: 1, 8: 1} self.hand = [] self.health = 30 self.mana = 0 def draw(self): if not self.is_deck_empty(): card_cost...
8b108d47cdbe9bf0b2139d6948a865da86fb6c19
Aronorn02/origin
/mímir/assignment3/4.py
152
3.875
4
n = int(input("Input an int: ")) # Do not change this line # Fill in the missing code below summa = 0 for i in str(n): summa += int(i) print(summa)
271ba28797549c455cd3e8f884c66e46854b6e87
Aronorn02/origin
/mímir/assignment4/3+.py
866
3.8125
4
# Read exactly four lines of input line1 = input() line2 = input() line3 = input() line4 = input() # Define variables for the range of numbers within which we have 'printable' characters. # As we shift the input characters, we must ensure that they stay within this range. LOW = ord(" ") # 32 HIGH = ord("~") # 126 ...
0f80fef83c9fe2dbdf7e09f44312c4d4ea65ef55
antoalv19/AOC_2019
/venv/DAY_2.py
511
3.546875
4
import pandas as pd import math df = pd.read_csv(r"C:\Users\antonio.alvino\Desktop\AOC_1.csv", header= None) df["tot"] = df[0].apply(lambda x: math.floor(x/3) - 2) ############################## DAY 2 ############################################# def fuel_req(mass): return mass // 3 - 2 def fuel_req_recursive(ma...
7e6a062fa97ff5267a87d2b06fd0ebaa34cc748b
16-Sheikh-2002/wa_dicetask2
/task2.py
8,268
3.890625
4
#Note1: Finish Output file rule in flowgorithm - not possible from random import randint import time saveFile = open('F:\Documents\exampleFile.txt','w') saveFile.write("(Round, Player, Total of Dice):\n") pass1 = "Sheikh" pass2 = "Sheikh2" player1 = input("Player 1, enter your name (Case sensitive): ") player2 = input(...
49c046a92870d3f128849c8ad0452ca7c71c75f1
SruthiM-10/5th-grade
/Programs/reverseName.py
275
4.21875
4
s=input("What is your first name?") f=input("What is your middle name if you have one? If you don't have a middle name, just type no") r=input("What is your last name?") if f=="no": print("Your name in reverse is",r,s) else: print("Your name in reverse is",r,f,s,)
4b89290f41afd34cfa9ea7918e195fc4b89970c1
Tonny-Git/Python-Minesweeper
/sqlite.py
2,921
3.53125
4
import sqlite3 as sql import os class Database: def __init__(self): pass # super(Database, self).__init__() # self.conn = self.connect_to_db() # self.c = self.conn.cursor() # self.insert_into_db() def connect_to_db(self): if os.path.isfile("example.db"): ...
3a4f82432e55554720f6a4b58ad1d9ecd7ea1c05
lambernabe/iecep-python-exer
/factorial.py
118
3.984375
4
import sys fact = 1 x = input("Factorial of: ") for x in range (x,1,-1): fact = x*fact print ("is", fact)
3ebd89ac13b5973fe8f4666bfdd89d6a19feaf7d
KWMalik/organization
/teaching/jordan/assignments/a2/a2.py
878
3.90625
4
# Takes 2 values and returns True if only one parameter is true. def but_not_both (x,y): if x and not y >=10: return True else: return False but_not_both(10,9) #Defines a Class that will initialize fields x,y,and z. class points: def _init_(self,x,y,z): self.x = x ...
caf7c92c4f4d7c77e870567774562c3044f6e890
ragarunov/workingwithfiles
/app.py
1,238
3.59375
4
addMore = 0 while addMore == 0: file = open("datafile.txt", "a") exists = False name = contact = '' while name == '': name = input("Username: ") while contact == '': contact = input("Contact: ") name = name.upper() contact = contact.upper() with open("datafile.txt", "r"...
6e05395d83a68a888ed6bd5ca243457408e292ff
akenz1901/SequelQueries
/MysqlPython/connect_insert.py
1,636
3.640625
4
import mysql.connector from mysql.connector import Error def connect_insert(): '''function to connect and insert a row in a database''' #create a connection variable conn = None try: conn = mysql.connector.connect(host = 'localhost', database = 'demo', user = 'root', password = 'olashile1') ...
c6508a82a3ab1e12ec6bf4cb5e5567eaae73e207
modengdai/learning_notes
/7.py
1,470
3.578125
4
#7段数码管 import turtle as t import time def kong(): t.penup() t.fd(5) def drawline(draw): kong() t.pendown() if draw else t.penup() t.fd(40) kong() t.right(90) def drawdigit(digit): drawline(True) if digit in [2,3,4,5,6,8,9] else drawline(False) drawline(True) if digit in [1,3,4,5...
2289f6497ff5a146c0bbe3c64020bd3fff405e24
katerinaiptv/India-Cotton.-DataKind-UK
/run_pca.py
1,001
3.921875
4
import numpy as np import pandas as pd from sklearn.decomposition import PCA import matplotlib.pyplot as plt def run_pca(data, column_set, n_pca=None): """Fit a PCA model on data for the columns in column_set.""" cols=column_set.intersection(set(data.columns)) if not n_pca: n_pca...
fda9dba39d434a718989223fe24192b732cc32ab
PoopLord1/centipede
/models/reddit_post.py
1,246
3.609375
4
""" reddit_post.py - defines a class that holds information relevant to a post on reddit """ class RedditPost(object): def __init__(self, input_dict): self.post_id = "" self.points = "" self.post_author = "" self.post_datetime = "" # TODO - this should be a datetime object, not a ...
881059eea0a645d94cb96d0af6b571cf202de893
PoopLord1/centipede
/limbs/abstract/Limb.py
1,459
3.5
4
""" An abstract class that defines the requirements for any "limb," or individual scraping module. """ from abc import ABC import re class Limb(ABC): # Associates a compiled regex object to a scraping method. _COMPILED_RE_TYPE = type(re.compile("")) def __init__(self, config_dict): self.regex_to...
69067116ec461ecbaf76d2e37a53fbbcb4c7920c
ffrankies/reddit_seer
/post_getter.py
6,647
3.828125
4
"""Retrieves text posts from reddit using the reddit API, and saves them in a csv format. Authors: Frank Wanye, Kellin McAvoy, Andrew Prins, Troy Madsen """ import datetime import argparse import requests import pathlib import csv TODAY = datetime.datetime.utcnow() ONE_MONTH_DELTA = datetime.timedelta(days=30) MINU...
11777fafc7e2a13943997a58a107bf1c02eb7fb3
RuturajKotwal/Python-College-Assignments
/Cows_Bulls.py
758
3.515625
4
import random number = random.randint(1000,9999) number_list = [int(x) for x in str(number)] print("A 4-digit number has been generated. Let's play Cows & Bulls. "+str(number)) cnt = 0 guess = None while(guess != number) : cows = 0 bulls = 0 guess = int(input("Your guess : ")) guess_list = [int(x) for...
ddbb2f5ff48ad1a43a47521862bc7194b9e132d9
mkyu0917/pystudy
/format_ex.py
970
3.75
4
#format_ex.py #문자열 서식 #서식 문자 ''' %s : 문자열 %d : 정수 %f : 부동소수 %% : %ㄹl터럴 ''' format = "I have %d apples" print(format % 10) print("Interest Rate is %.2f%%" %1.24) # %x.yf 정수자리 x까지출력, y소수점자리 # 두 개 이상의 값을 넣고 싶을때 format = "total: %d개, get: %d개" print(format % (10,3)) #format과 값의 형식이 일치하지 않으면 TypeError 발생 format_str ...
413da539690b2008f3ccab545d2c61818043ca84
mkyu0917/pystudy
/quiz/tquiz01_3.py
408
3.75
4
students = [ { "name": "Kim", "kor": 80, "eng": 90, "math": 80 }, { "name": "Lee", "kor": 90, "eng": 85, "math": 85 } ] for student in students: total = student.get("kor")+student.get("eng")+student.get("math") avarage = tota...
12f421efec5a93b8dd0184671317fe0247349ed4
Muhinyuzi/data_science
/Intro_Data_Science/Week3/DateFunctionality.py
6,819
4.21875
4
# Let's bring in pandas and numpy as usual import pandas as pd import numpy as np #Timestamp # Pandas has four main time related classes. Timestamp, DatetimeIndex, Period, and PeriodIndex. First, let's # look at Timestamp. It represents a single timestamp and associates values with points in time. # For example, let's ...
d7b62c682e47801a56d553e49c4a3306bf6a3924
Muhinyuzi/data_science
/Intro_Data_Science/Week1/functions.py
8,986
4.53125
5
# -*- coding: utf-8 -*- #`add_numbers` is a function that takes two numbers and adds them together. def add_numbers(x, y): return x + y print(add_numbers(1, 2)) #'add_numbers' updated to take an optional 3rd parameter. Using `print` allows printing of multiple expressions within a single cell. def add_numbers(x,y...
6b951c1451d56de924a7e73ffe5a7aafb6151f6d
kaist-plrg/jstar
/tests/compile/basic/recent/Number::remainder.spec
761
3.609375
4
1. If _n_ is *NaN* or _d_ is *NaN*, return *NaN*. 1. If _n_ is *+∞*<sub>𝔽</sub> or _n_ is *-∞*<sub>𝔽</sub>, return *NaN*. 1. If _d_ is *+∞*<sub>𝔽</sub> or _d_ is *-∞*<sub>𝔽</sub>, return _n_. 1. If _d_ is *+0*<sub>𝔽</sub> or _d_ is *-0*<sub>𝔽</sub>, return *NaN*. ...
ee6472e2d0af2753a92c00c56c4ad7fa9db1a569
DrakeSeifert/Software-Engineering-I
/assignment1/testkwic3.py
293
3.546875
4
import kwic3 #This test makes sure the last value in the inner list is an int. This int is the line number of its corresponding string. mystr = "ZHello world,\nthis is a test!\napples and oranges\nbears are scary" assert isinstance(kwic3.kwic(mystr)[0][(len(kwic3.kwic(mystr)[0]) - 1)], int)
d3a823ac0a321f1cbb0523d29e1b9c76f496cadc
VDK45/Full_stack
/Lesson_2/Lesson 1 Task 3.py
1,711
4.03125
4
""" Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict. """ m2 = int(input('(list) месяц: ')) months2 = ['январ - Зима', 'февраль - Зима', 'март - весна', 'апрель - весна', ...
c6caed913eb05565cc82095df24b159c098f4a4b
VDK45/Full_stack
/Lesson_3/lesson3Task5.py
1,358
3.828125
4
""" 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вм...
8d138c56ac0215a1ea4dabd2ccf7d575b09c6d9c
VDK45/Full_stack
/Lesson_1/Lesson 1 Task 5.py
1,288
4.28125
4
""" 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность в...
e0c98e27237e12afd4485ef4c188a6fb0bf22479
VDK45/Full_stack
/Lesson_4/lesson4Task7.py
1,115
4.21875
4
""" 7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: for el in fact(n). Функция отвечает за получение факториала числа, а в цикле необходимо выводить т...
9ef6b9ce2784401805ce4e94dc43c00ea8333082
VDK45/Full_stack
/Lesson_2/Lesson 1 Task 4.py
719
3.96875
4
""" Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ l = input('Hi: ').split() for d, i in enumerate(l, 1): if len(i) > 5: print(d, i[:...
38a21afac272a67acd50b6ed0d161e26f79aaaf0
kilikkuo/py3_101
/listcomprehension.py
359
3.5
4
square_items = [] for num in range(10): square_items.append(num**2) print(square_items) square_items_lc = [num**2 for num in range(10)] print(square_items_lc) combs = [] for x in [1,2,3]: for y in [3,2,1]: if x != y: combs.append((x, y)) print(combs) combs_lc = [(x,y) for x in [1,2,3] for ...
025a31bbfa6288b803bd51a20986263a8ed59bfb
kilikkuo/py3_101
/multithread/multithread_1_workers.py
404
3.640625
4
# 匯入 threading module import threading # 宣告一個函數給執行緒來執行 def worker(): print('I\'m working') # 宣告一個 list 來存放產生出來的執行緒 threads = [] # 建立三個執行緒, 並且都指定 worker 作為他們的執行函數, # 建立完後並啟動這些執行緒 for i in range(3): t = threading.Thread(target=worker) threads.append(t) t.start()
415c7b325cab0ffe12f3194f2f4fb3002af1a210
kilikkuo/py3_101
/multithread/multithread_6_lock.py
1,704
3.796875
4
import time import random import threading # 一個計數器物件 class Counter(object): def __init__(self, start=0): self.lock = threading.Lock() # 給定一個起始值, 在物件生成時預設數值為 0 self.value = start def increment(self, actor): print('[{}] Waiting for lock'.format(actor)) self.lock.acquire() ...
8a0b57a42fbde1650c92e32e7a0633b6cd3f8925
stevet284/useful_scripts
/python/Old_scripts/print_line_no_ex.py
387
3.8125
4
#!/usr/bin/env python3 while True: fil = input("filename? ") try: with open(fil, 'r') as f: x = f.read() except: print("ERROR opening file:", fil) continue break while True: lineno = int(input("line number? ")) - 1 filelist = x.split('\n') if lineno > len(filelist): print("Error, file has only" , l...
5c7a097d68db2b63c8c9ddbb7ee5081b2d493b1f
smith458/CSCI23000
/StopWatch.py
2,409
3.96875
4
from tkinter import * from tkinter import ttk import time #Container class for the object that is passed through the program class container(object): def __init__(self): self.start_time = 0 self.task = "" self.current_time = "" self.second_count = "" #These are th...
513a9d0167adda155e9f267aab31db2b75f4e441
dulalsaurab/Graph-algorithm
/plot.py
418
4.1875
4
''' This file will plot 2-d and 3-d points''' import numpy as np import matplotlib.pyplot as plt # drawing lines between given points iteratively def draw_line(array): data = array # array should be of format [(),(),(),()] # 2D ploting using matplotlib def plot_2D(array, size): # array should be of format...
c46a4563778ab1696dcafd0d67026e05a1829909
rubchume/MediumScraper
/tests/test_article.py
701
3.671875
4
import unittest from src.article import Article class ArticleTests(unittest.TestCase): def test_get_number_of_words(self): # Given article = Article( id="id", url="url", title="title", author="someone", paragraphs=["Hello I am your frien...
688ca944e9ea99f8c1f5b5ec84693c29edd0eb9b
asheeshdwivedi/tutorials
/python-tutorials/Basic/Format.py
893
4.03125
4
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 n = 11 f = 1.23456 s = "Asheesh is Grate !!!!!!!!!" print("My number is {:d}".format(n)) # {:d}print n in decimal print("My number is {:b}".format(n)) # {:b} print n in binary print("My number is {:f}".format(f)) # {:f} print f in floting point print...
6d7528a546b535f5034b7561d5a83a89c74e4948
filibtester/pde
/pde.py
25,135
3.796875
4
# coding: utf-8 # # Programming Project # In this programming project, I will use Python to code a solver for a first-order linear PDE: # $$ # \frac{\partial u}{\partial t} + v \frac{\partial u}{\partial x} = 0 \quad \mbox{ on }(x,t) \in[0,L]\times[0,T] # $$ # # for a scalar and positive $v\in\mathbb R$ with initi...
71a8f0e84f95434fe705631ffefef566a99e03ec
nico-bart/project-euler-python
/problem006.py
727
3.828125
4
# The sum of the squares of the first ten natural numbers is, # 12 + 22 + ... + 102 = 385 # # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)2 = 552 = 3025 # # Hence the difference between the sum of the squares of the first ten natural # numbers and the square of the sum is 3025 − 385 =...
c5455d98be6ddba41ed0f7a54f29886383a0e334
nico-bart/project-euler-python
/problem005.py
846
3.671875
4
# 2520 is the smallest number that can be divided by each of the numbers from # 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the # numbers from 1 to 20? # # Finde das kleinste gemeinsame Vielfache der Zahlen 1 bis 20 # # One has to find all the prime factors o...
29eea067bff4fe63ec889a501e9cfcc6e82b9d33
acloserview/corpus-latinum
/latin_tag.py
3,399
3.78125
4
from os import system #Needed to run bash commands. from subprocess import check_output #Needed to run bash commands. from sys import argv #Needed for command-line arguments. # This file is organized with the more important functions # first for ease of comprehension. # DEPENDENCIES: # - bash # - Whitacker's Words (a...
87f7d6a1956c3eb443a898455bfd999080f5b1b6
SakiFu/leetcode
/python/plus_one.py
324
3.5
4
"""Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. """ class Solution(object): def plusOne(self, digits): temp = str(int(''.join(map(str, digits))) + 1) return map(int, list(te...
9370640d5999e11c1d73dcc0dea7ce92fc642350
SakiFu/leetcode
/python/symmetric_tree.py
632
4.0625
4
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following is not: 1 / \ 2 2 \ \ 3 3 class Solution(object): def help(self, el, r): if el ==...
c9a43a28eb7256b68d298d4d3cdeab27f2828d04
SakiFu/leetcode
/python/integer_to_roman.py
574
3.796875
4
"""Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. """ class Solution(object): def intToRoman(self, num): roman_dict = {1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL", 50: "L", 90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM", 1000: "M"} ...
568347592edcc31f9f8ea7cd84bda9f00b96285e
sdoger/py1
/func1.py
5,663
3.546875
4
def pi(n): #π=4*(1-1/3+1/5-1/7+1/9……) 求PI s=0 for i in range(n): if i%2==1: s=s-1.0/(1+2*i) else: s=s+1.0/(1+2*i) return s*4 def datetime(): import time d1=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) return d1 def ss(s1,s2,s3=0,h=0): ##圆面积 ...
caba6f422fd09649f36de86466586c2a94ae2302
aditya-786/coding-submissions
/codeforces/1450/A.py
283
3.5
4
for i in range(int(input())): n = int(input()) st = input() count = 0 for j in st: if j!='t': print(j,end="") else: count+=1 for j in range(count): print("t",end="") print()
a43e32db754770abdfc32d1ebbe6fd35776b567f
shuryak/ege-inf
/multi-pass-and-brute-force/3.py
638
3.625
4
# a = [] # n = 30 # for i in range(0, n): # a.append(int(input())) # Проще можно записать так: # n = 30 # a = [int(input()) for i in range(0, n)] # Чтобы вручную не вводить числа, для тестирования алгоритма, можно записать: from random import randint n = 30 a = [randint(0, 100) for i in range(0, n)] # - - - - - ...
13140b47604e441464b27eabb175424d47838b62
nostartama/Exploratory-Data-Analysis
/code/cleaning.py
4,221
3.984375
4
#import module import pandas as pd import numpy as np ##################################################################### ### DROP MULTYPLE COLUMNS ### ##################################################################### def drop_multiple_col(df, columns_list): ''' ...