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
2b06a6603f3b196b0ddff69cf7f21d10c357642b
nacler-83/problem-solving
/Task1.py
1,032
3.984375
4
import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 1: How many different telephone numbers are there in the records? Print a message: "There are <count> different telephone num...
e486049e3ee77222325cf474606cb0886ac13e35
Ryoichi-Ueno/Self_Taught
/challenge13_1.py
1,409
4.125
4
class Shape: def __init__(self): self.my_name = 'I am shape!' def what_am_i(self): print(self.my_name) class Rectangle(Shape): def __init__(self, base, height): super().__init__() self.base = base self.height = height def calculate_perimeter(self): ...
0093bd5b9d8312844956f4e6ef5967f2ce989a94
Mohamed209/Python_OOP_tutorial
/LogicGate.py
2,536
3.609375
4
class LogicGate: # super class Logic Gate def __init__(self,label):# init function to set label and output self.label=label self.output=None # function to check if input is valid boolean value '''ef check_valid_input(self): assert int(input()) is bool, "0 and 1 are only valid inputs"...
25a93f5855eddc25b9d48de5c200d91a5632279f
RahulBhoir/Hospital-Welfare-System
/HWS/Pharmacy.py
1,570
3.9375
4
class Pharmacy: def __init__(self): print("ONLINE STORE") def search_product(self): self.product = input("Product name:") def check_product(self): try: # opening file to read data file = open("product.txt", "r") #read lines from file ...
b62e8bacd1c65b84f96320247928e4a326d20690
RoxyFarhad/AI
/HW4/robot/Qlearner.py
3,185
4
4
""" COMS W4701 Artificial Intelligence - Programming Homework 4 A Q-learning agent for a stochastic task environment @author: YOUR NAME AND UNI """ import random import math import sys class Qlearner(object): def __init__(self, states, valid_actions, parameters): self.alpha = parameters["alpha"] ...
8d778ad37d5ce6d42153438e1479ce47240669d6
vsrivathsan/hackerrank
/algorithms/implementation/05_sherlock_and_squares.py
600
3.875
4
""" https://www.hackerrank.com/challenges/sherlock-and-squares """ def calc_prfct_sqrs(a, b): sqrt_of_a = float(a**(0.5)) sqrt_of_b = int(b**(0.5)) if sqrt_of_a.is_integer(): num_of_pft_sqrs = sqrt_of_b - int(sqrt_of_a) + 1 else: num_of_pft_sqrs = sqrt_of_b - int(sqrt_of_a) return ...
976fa93cd8982af52a2204e4b30c601da6b438d8
marcoAureliosm/Listas-de-atividades-03-de-python
/questão15.py
921
3.984375
4
custo=float(input("DIGITE O CUSTO DO PRODUTO")) origen=int(input("DIGITE O CODIGO DE ORIGEM DO PRODUTO")) if origen==1: origen="Sul" print("VALOR DO PRODUTO:{} E SUA ORIGEM: {}".format(custo,origen)) elif origen==2: origen = "Norte" print("VALOR DO PRODUTO:{} E SUA ORIGEM: {}".format(custo, orige...
07b22ce216b957939ec1a1a6cf1f9db10d9bf123
marcoAureliosm/Listas-de-atividades-03-de-python
/questão21.py
1,173
4
4
dia=int(input("DIGITE O DIA")) mes=int(input("DIGITE O MES")) ano=int(input("DIGITE O ANO")) if (mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12): if (dia <= 31): print("DATA VALIDA") print("{}/{}/{}".format(dia,mes,ano)) else: print('DATA INVAL...
825ec59416f55fc878d80510b12175a248fbbf6d
marcoAureliosm/Listas-de-atividades-03-de-python
/questão11.py
249
3.625
4
turno=str(input("DIGITE O TURNO Q VC ESTUDA [M]-MATUTINO [V]-VESPENTINO [N]-NOTURNO")) if turno=="M": print=("BOM DIA!") elif turno=="V": print("BOA TARDE!") elif turno=="N": print("BOA NOITE") else: print("VALOR INVALIDO")
1ebb6664ede2264965deccebcca43d8450437cd8
marcoAureliosm/Listas-de-atividades-03-de-python
/questão29.py
225
3.625
4
n1=float(input("DIGITE 1ª VALOR")) n2=float(input("DIGITE O 2ª VALOR")) operacao=(int(input("[1] ADIÇÃO [2]SUBTRAÇÃO [3]MULTIPLICAÇÃO[4]DIVISÃO")) if operacao == 1: soma=n1+n2 if soma == round(soma):
01de71c1a741307a225cbc86326389539f2676c7
ChenMalobani/semiparametric
/utils/geometry.py
8,807
3.59375
4
""" Miscellaneous geometric functions that have been helpful from time to time. """ from typing import Tuple from typing import Union import numpy as np import scipy import torch def geodesic_distance(R1: np.ndarray, R2: np.ndarray ) -> float: """ Return the geodes...
9a91ca291b8e753ff518b807620893ef3805c2c3
Adit-jain/Face_Recognition
/Face Recognition/generate.py
2,736
3.828125
4
# this file is used to detect face # and then store the data of the face import cv2 import numpy as np import npwriter name = input("Enter your name: ") # this is used to access the web-cam # in order to capture frames cap = cv2.VideoCapture(0) classifier = cv2.CascadeClassifier("haarcascade_front...
88fac355c143aa070be1200ddc361c46fdccaa99
anillava1999/Innomatics-Intership-Task
/Task6/Task2.py
247
4.0625
4
# Shape and Reshape in Python - Hacker Rank Solution # Python 3 import numpy # Shape and Reshape in Python - Hacker Rank Solution START print(numpy.array(input().split(), int).reshape(3, 3)) # Shape and Reshape in Python - Hacker Rank Solution END
824fc85f915cf07dc85fe9fec82afd7b54cef06d
anillava1999/Innomatics-Intership-Task
/Task5/Task13.py
808
4.09375
4
# Detect HTML Tags, Attributes and Attribute Values in Python - Hacker Rank Solution # Python 3 # Enter your code here. Read input from STDIN. Print output to STDOUT # Detect HTML Tags, Attributes and Attribute Values in Python - Hacker Rank Solution START from html.parser import HTMLParser class MyHTMLParser(HTMLPars...
715b81a4acaa63e0a6461b7bf921ca42559a526e
anillava1999/Innomatics-Intership-Task
/Task5/Task5.py
490
3.75
4
# Re.start() & Re.end() in Python - Hacker Rank Solution # Python 3 # Enter your code here. Read input from STDIN. Print output to STDOUT # Re.start() & Re.end() in Python - Hacker Rank Solution START import re S, k = input(), input() matches = re.finditer(r'(?=(' + k + '))', S) anymatch = False for match in matches:...
5353caf553cebfc696a268a856e45fad42c806f6
anillava1999/Innomatics-Intership-Task
/Task5/Task2.py
269
3.65625
4
# Re.split() in python - hacker rank solution # Python 3 # Re.split() in python - hacker rank solution START regex_pattern = r"[.,]+" # Do not delete 'r'. # Re.split() in python - hacker rank solution END import re print("\n".join(re.split(regex_pattern, input())))
d86b80e7d3283ff2ee1b062e14539dbb87e34206
anillava1999/Innomatics-Intership-Task
/Task 2/Task3.py
1,778
4.40625
4
''' Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line. Example ...
7e7e9e0826a574042da29d27515bdb87b7a8e2bf
nimoes/beer-api
/beer/beerapp/openbrewery.py
2,195
3.53125
4
import requests import json # example response from the server about a brewery # { # id: 299, # name: "Almanac Beer Company", # brewery_type: "micro", # street: "651B W Tower Ave", # city: "Alameda", # state: "California", # postal_code: "94501-5047", # country: "United States", # ...
a7407a3d89062ed216bbe8a27a82c23fe8a7d799
aditya710/Python-Practice
/DataStructures.py
4,130
4.28125
4
# -------------------------------------------------------------------- # List # This is my shopping list shoplist = ['apple', 'mango', 'carrot', 'banana'] print('I have', len(shoplist), 'items to purchase.') print('These items are:', end=' ') for item in shoplist: print(item, end=' , ') print('\nI also have to...
8799dbc6843370fc93741151b3bd1d82b782d445
banditypte/leet-code
/add-two-numbers.py
2,538
3.828125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = None tail = N...
3664b39e29387cb4c7beb0413249014d34b132bc
Arsalan-Habib/computer-graphics-assignments
/mercedez-logo/main.py
1,719
4.21875
4
import turtle # initializing the screen window. canvas = turtle.Screen() canvas.bgcolor('light grey') canvas.title('Mercedez logo') # initializing the Turtle object drawer = turtle.Turtle() drawer.shape('turtle') drawer.speed(3) # Calculating the radius of the circumscribing circle of the triangle. # The formula is:...
3049cbdee50883eb5cc95f2106550b400692eb31
Andressa-Anthero7/Exercicios-Python
/Desafio-95.py
1,559
3.703125
4
gols_marcados = list() time = list() jogador = dict() tot_gols = 0 opcao = 0 resp = '' while True: jogador['nome'] = str(input('Nome do jogador: ')).upper() partidas = int(input('Quantas partidas {} jogou?: '.format(jogador['nome']))) for c in range(0, partidas): gols_marcados.append(int(i...
aed05163c935f98c9eedbf8b23f7eff45f36c28a
Styfjion/-offer
/exam_record/xc_1.py
940
3.703125
4
class ListNode: def __init__(self,x): self.val = x self.next = None class Solution: def isLoop(self,pHead): pFast = pHead pSlow = pHead while pFast and pFast.next: pFast = pFast.next.next pSlow = pSlow.next if pFast == pSlo...
2118c7f11ed2d85c967c54197abd8499f7d6da64
since2016/studypython
/CollectionOverview/chapter1/defalutditc_test.py
406
3.53125
4
from collections import defaultdict user_dict = {} default_dict = defaultdict(int) users = ['a', 'b', 'c', 'a', 'b'] for user in users: # 1. # if user not in user_dict: # user_dict[user] = 0 # else: # user_dict[user] += 1 # # # 2. # user_dict.setdefault(user, 0) # 3. defa...
3123bbe4a09fc4a2b6a561183481d9448f819ea4
since2016/studypython
/CollectionOverview/chapter1/tuple_test.py
442
3.984375
4
# 不可变, iterable name_tuple = ('bobby1', 12,32) name_tuple = ('bohhd', 32,54343, 'beigjin') #拆包 name , age, value ,*other= name_tuple print(name, age, value, other) # 不可变不绝对 name_tuple = ('nae', [239, 10323]) name_tuple[1].append(432) print(name_tuple) # immutable的重要性 ,性能优化, 线程安全, 可以作为dict的key, 拆包特效// # 如果拿 c语言类比, ...
96c4b332eae1f6ba5e2097287d6d6d4baf5b7db8
jhy979/all-solved-club
/members/U02BQ6G1SQJ/programmers/problem/튜플.py
565
3.515625
4
import re; import collections; def solution(s : str) -> list: (answer, resultCounter) = ([], collections.Counter()); tupleList = list(filter(lambda k : k not in ["", ","], sorted(re.split("{|}", s), key = lambda k : len(k)))); # print(tupleList); for curTuple in tupleList: tupleCounte...
5f74addf506090cd84224f630873286f4298482c
EliGolan69/WorldOfGames
/Game.py
902
3.5
4
from abc import ABC, abstractmethod from Common import common from random import * class game(ABC, common): def __init__(self, override_menu): self.difficulty = 1 self.override_menu = override_menu @abstractmethod def play(self, difficulty): pass @abstractmethod def get_menu(self)...
49fb9f94501503eedfd7f5913efb3c8ffe656e68
Saij84/AutomatetheBoringStuff_Course
/src/scripts/12_guessNumber.py
968
4.3125
4
import random #toDo ''' -ask players name -player need to guess a random number between 1 - 20 -player only have 6 guesses -player need to be able to input a number -check need to be performed to ensure number us between 1 - 20 -check that player is imputing int -after input give player hint -"Your guess i...
9c521d4fbafb0876e5e1e0d42719ddcf537a158b
ChristopherLBruce/WordRPG
/WordRPG/engine/story/main.py
4,392
3.578125
4
import textwrap # TODO: Are there only 2 genders? PRONOUNS = [ 'HE_SHE', 'HIM_HER', 'HIS_HER', 'HIS_HERS', 'HIMSELF_HERSELF', ] def get_pronoun(pronoun, gender='MALE', sep='_'): """ Gets the correct gender pronoun Arguments: pronoun {str} -- HE_SHE pronoun that needs to be ...
9a7696252ce795e5cb3bdadb645db086af5b44bf
ChristopherLBruce/WordRPG
/WordRPG/systems/inventory/inventory.py
1,352
3.65625
4
class Inventory(): def __init__(self, items=[], limit=10): self.inventory = items self.limit = limit # Add item to inventory if space is available # Return true if add was successful def add(self, item): """[summary] Arguments: item {[type]} -- [d...
a316a0f00dc0e1a94a79abb2b472b01caa016402
ChristopherLBruce/WordRPG
/WordRPG/engine/gui/font.py
1,261
3.6875
4
""" Module used for formatting text with colorama escape characters Notes: Fore/Back: 'BLACK', 'BLUE', 'CYAN', 'GREEN', 'LIGHTBLACK_EX', 'LIGHTBLUE_EX', 'LIGHTCYAN_EX', 'LIGHTGREEN_EX', 'LIGHTMAGENTA_EX', 'LIGHTRED_EX', 'LIGHTWHITE_EX', 'LIGHTYELLOW_EX', 'MAGENTA', 'RED'...
138466d2c0d7e59c2dba822cec86270a0432fd97
ckoppula199/Detecting-Parkinsons-Disease-with-XGBoost
/XGBoost_Parkinsons.py
2,954
3.796875
4
""" This is a program to train a classifier using the XGBoost ML algorithm to detect the presence of parkinsons in individuals """ import numpy as np import pandas as pd from xgboost import XGBClassifier import os, sys from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split ...
4e9cba484f82f06ae41d41de2120b7491d1f9a26
Orcuslc/CS-Courses
/Berkeley CS61A/hw08/hw08.py
6,496
3.734375
4
import time def timeit(func): """Returns the time required to execute FUNC() in seconds.""" t0 = time.perf_counter() func() return time.perf_counter() - t0 def missing_val(lst0, lst1): """Assuming that lst0 contains all the values in lst1, but lst1 is missing one value in lst0, return the miss...
794e12d0c4ac2d7d119a218178f08ccb04c9c5d9
bentley-historical-library/baroque
/baroque/report_generation.py
1,491
3.53125
4
import csv import os from datetime import datetime def generate_reports(baroqueproject): data = [] # Print out the number of errors and warnings for each validation. for validation, errors in baroqueproject.errors.items(): num_requirements = len([error for error in errors if error["error_type"] =...
72a405cd9c9624b1e4c75d1975a1975406393424
pratamov/pe
/19.py
929
3.953125
4
from datetime import datetime year1, month1, date1 = 1900, 1, 1 year2, month2, date2 = 2000, 12, 31 day_of_week = 0 sundays = 0 while (year1*1000 + month1*100 + date1) < (year2*1000 + month2*100 + date2): if month1 in [1,3,5,7,8,10,12] and date1 > 30: date1 = 1 if month1 == 12: month1 ...
98fc3abad80619f793a07c88b5bbfb35b589a29a
pratamov/pe
/9.py
184
3.5
4
def find(): for a in range(1, 1000): for b in range(1, (1000 - a)): c = 1000 - a - b if a*a + b*b == c*c: return a*b*c print(find())
99a37940bc50e3d912b1a1818c2d87b7037940d4
geisonfgf/code-challenges
/challenges/poisonous_plants/poisonous_plants.py
2,137
3.96875
4
""" Problem Statement There are N plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each plant. Print the number...
1fe95611e986a78376936a49e4b0d9dc5762c80a
geisonfgf/code-challenges
/challenges/components_in_a_graph/components_in_a_graph.py
2,280
3.84375
4
""" Problem Statement There are 2N values to represent nodes in a graph. They are divided into two sets G and B. Each set has exactly N values. Set G is represent by {G1,G2,...,GN}. G can take any value between 1 to N(inclusive). Set B is represented by {B1,B2,⋯,BN}. B can take any value between N+1 to 2N(inclusive). ...
d28b91aa36ee49eb6666a655e1ef9fb6239b1413
geisonfgf/code-challenges
/challenges/find_odd_ocurrence.py
701
4.28125
4
""" Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Input = [1, 2, 3, 2, 3, 1, 3] Expected result = 3 """ def find_odd_ocurrence(arr): result = 0 for i in xrange(len(arr)): ...
5094922c58d92b776ce244bb3dc25e3e49dbe0e1
geisonfgf/code-challenges
/challenges/minimal_number_of_coins_problem.py
1,043
3.90625
4
""" Minimal number of coins problem """ def possibilities(value, coins_available, coins_used): if sum(coins_used) == value: yield coins_used elif sum(coins_used) > value: pass elif coins_available == []: pass else: for c in possibilities(value, coins_available[:], coins_...
1e4946a59bb520ff0f409292eded2ccc0990bdbc
geisonfgf/code-challenges
/interviews-code/codility_interviews/binary_period.py
2,241
3.703125
4
""" Consider a non-empty string S = S[0]S[1]...S[Q-1]] consisting of Q characters. The period of this string is the smallest positive integer P such that: - P <= Q / 2 and - S[K] = S[K+P] for every K, where O <= K < Q - P. For example, 8 is the period of "codilitycodilityco' and 7 is the period of "abracadabracadabra...
7eb356997cc0862b77e09a80699b1681f0b51952
geisonfgf/code-challenges
/challenges/evaluate_reverse_polish_notation.py
560
4.21875
4
""" ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 """ def evaluate(expression): stack = [] while expression: val = expression.pop(0) if (str(val) == "+" or str(val) == "*" or str(val) == "-" or str(val) == "/"): x, ...
ce893c32d50cca474b8e87ba220d54101bbfd35b
geisonfgf/code-challenges
/challenges/array_max_difference.py
190
3.5625
4
def max_diff(arr): return max(arr) - min(arr) if __name__ == '__main__': arr = [1, 2, 6, 80, 100] print "Expected result:", 99 print "Maximum difference is:", max_diff(arr)
d4cb904739f83f855023959face62bad9bbe0869
bochap-udacity/dsand-p1
/finding_files/problem_2.py
3,455
3.921875
4
from os import listdir from os.path import isfile, isdir, exists, realpath, relpath, dirname, join from collections import deque BASE_DIR = dirname(realpath(__file__)) def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories...
624b7fc8c9d350cc712b464475e44e7230149474
thecodebloodedguy/my-basic-python
/Number Guess.py
1,006
3.9375
4
import random jackpot=random.randint(0,51) score= 100 gameend=True print("Here are rules:\n1.Guess the number chosen between 1 and 50\n2.If Your difference is less than or equal to 20, little is used\n3.Otherwise too is used\n\nHAVE FUN\n") guess=int(input("Give your guess:")) while score>0: if gue...
424505ff633e4ffd22ea0aefff1bca233a0b1951
Vikaskumar75/flames
/flames.py
2,231
4
4
first = input("enter the first name -->") second = input("enter the second name -->") # changing all the characters to lower case first = first.lower() second = second.lower() # relacing spaces with no spaces first = first.replace(" ","") second = second.replace(" ","") # readi...
16e850839ea5a01d7acd60a3455ee2772ddcad6c
bijitchakraborty12/MyProjects01
/20180701/normalFunctions.py
298
3.6875
4
def oddeven(myList): mapping=[] for elem in myList: if elem%2==0: mapping.append('e') else: mapping.append('o') return mapping print('I am inside prod code') print(__name__) if __name__ == '__main__': m=oddeven([1,2,3,4]) print(m)
05af2b01610ba4b9937da270ad74d599d50bcb60
bijitchakraborty12/MyProjects01
/20180728/CSV_03.py
260
3.890625
4
# this is how we write to a file import csv filename='University_Records.csv' with open(filename,'r')as fn: csvReader=csv.DictReader(fn) for row in csvReader: print(row['Name'] + ' ' + row['Branch'] + ' ' + row['Year'] + ' ' + row['CGPA'])
ccdd3a6e0723dabd6f807ae65711ca45c05f2a03
jolynutella/Zookeeper
/Problems/Sum/main.py
125
3.578125
4
# put your python code here var1 = int(input()) var2 = int(input()) var3 = int(input()) sum1 = var1 + var2 + var3 print(sum1)
37242f79099fc772b99c81681ac5223fe6d0fd2f
aptxj/Codewars
/4kyu_The_Observed_PIN.py
3,065
4.0625
4
''' Alright, detective, one of our colleagues successfully observed our target person, Robby the robber. We followed him to a secret warehouse, where we assume to find all the stolen stuff. The door to this warehouse is secured by an electronic combination lock. Unfortunately our spy isn't sure about the PIN he saw, wh...
7dc60f540e75eb66383cc993ec9553fcd5d3a421
aptxj/Codewars
/6kyu_Tortoise_racing.py
1,784
3.828125
4
''' Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A and furthermore has not finished her cabbage. When she starts, at last, she can see that A has a 70 feet lead but B speed is 850 feet per hour. How long will it take B to catch A? ...
1a24e8635c2c5f46d0fdd32a8fda0e0343e88429
FlowerofAhab/PythonExec
/conversorMetrospraMM.py
160
3.6875
4
Metros = int(input('digite o valor: ')) N1 = 1000 resultado_final = (Metros*N1) print (str(Metros) + f' metros em milimetros é igual a {resultado_final}')
fcec51105c9c4ba62da33ff205db067dbeb05217
ricklupton/floweaver
/floweaver/utils.py
160
3.578125
4
import itertools def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
e454d89cc660460b6f915b1d8dc59ff86f6a8661
gabidinica/PEP20G06
/modul2/homework2.py
621
4
4
"""Homework 2 - needs to be presented before exam day""" # 1) Prove "and" operation takes precedence over "or" operation by setting # parentheses in (False or False and True or True) print((True and True) or (False and False)) # 2) Get from input two different times in the format hh:mm:ss and print # the difference...
d2f4ffda7aba1abba922f32b5159e6c5da0e46d4
gabidinica/PEP20G06
/modul5/modul5_2.py
1,331
4.0625
4
my_list = [1, 2, 3] my_list_iter = my_list.__iter__() print(my_list_iter) print(next(my_list_iter)) print(next(my_list_iter)) # print(len(my_list_iter)) # generator obiect pe care se call-uie metode de tip next def my_generator(): # construieste un obiect de tipul generator for i in range(3): print(...
1758af802adc1bf5dbf6b10bf4c04fd19d48e975
mk9300241/HDA
/even.py
209
4.34375
4
#Write a Python program to find whether a given number (accept from the user) is even or odd num = int(input("Enter a number:")) if (num%2==0): print(num," is even"); else: print(num," is odd");
5d9adbe2a7041bb3ced833b0596c2754a6f30517
nunomota/spatial-inequality
/spatial_inequality/core/greedy_algorithm.py
23,911
3.5625
4
""" Greedy implementation of our school redistricting algorithm (i.e., `Greedy Partitioning`). """ import os import logging import numpy as np from time import time from datetime import datetime, timedelta from auxiliary.functions import * from optimization.early_stopper import EarlyStopper from optimization.entity_...
5364d7f1f6b17c4852030b7b005fb1e02192843e
fabiommendes/uritool
/src/uritool/grader.py
11,083
3.796875
4
import os from decimal import Decimal, InvalidOperation from datetime import datetime import pandas as pd # Names __all__ = ['Grade', 'Grader'] class CancelOperation(Exception): """Cancel the current operation and go back to a nice starting point.""" class FinishGrading(Exception): """Finish the grading jo...
8712ae37e691e8e0c135a5d10601beac865591c3
tussharbhatt/all_projects
/PycharmProjects/MyOwnStuff/data_Structure_progs/remove_common.py
293
4.125
4
def main(): items=[] for i in range(5): items.append(input("enter values ")) dict={} for item in items: #print(item) if item not in dict: dict['key']=item #for keys in dict.items(): print(dict['key']) main()
9979472aca0ae85cffffb3ddbee68ecb7a3d4b01
tussharbhatt/all_projects
/PycharmProjects/pyStart/syntax_test.py
405
4.21875
4
import datetime #date1=datetime.datetime.now() #print(now) #print(now._day) #date=datetime.datetime(date1._year,date1._month,date1._day) '''def print_date(now1): date1=now1 date2=datetime.date(,now1.month,now1.day) print(date2) ''' now=datetime.date.today() #print_date(now) year=int(input(...
99f13c768a4cd7c565201b4df544e20b5556f2b5
dgjung0220/deepLearing_tensorflow
/DL_Source/Day_03_04_sigmoid.py
605
3.546875
4
# Day_03_04_sigmoid.py import math import matplotlib.pyplot as plt def show_sigmoid(): def sigmoid(z): return 1 / (1 + math.e ** -z) print(math.e) print(sigmoid(-10)) print(sigmoid(-1)) print(sigmoid(0)) print(sigmoid(1)) print(sigmoid(10)) for i in range(-10, 10): ...
8bd4e4cdb8f32f99c9c0683aa454a4719f0ece73
quinn3111993/nguyenphuongquynh-lab-c4e21
/lab3/calc.py
610
4.25
4
# x = int(input("x = ")) # op = input("Operation(+, -, *, /): ") # y = int(input("y = ")) # if op == '+': # z = x + y # print(x, '+', y, '=', z) # elif op == '-': # z = x - y # print(x, '-', y, '=', z) # elif op == '*': # z = x * y # print(x, '*', y, '=', z) # elif op == '/': # z = x / y # ...
dcce7ec0c560f57f7abf4932a004b1ccb639cc79
bulam/ZIP-scraper
/ZIP_demographics_scraping.py
1,891
3.71875
4
#! python3 # A python script that scrapes ZIP code demographics attributes from a website built on javascript, using the selenium module and writes the scraped results into # an Excel spreadsheet. Because the script is written to be used with the Firefox browser, # it is necessary to have Firefox installed to run ...
a7c988d19ea91b310062886b09a179ec274eb59e
tianbaozhu/LeetCode
/551. Student Attendance Record I.py
524
3.734375
4
class Solution(object): def checkRecord(self, s): """ :type s: str :rtype: bool """ # time complexity O(n) # space complexity O(1) count_a = 0 count_l = 0 for ch in s: if ch == "A": count_a += 1 count...
9b0fc2e2322e6d0b7378ecd249b467fae0b66a53
tianbaozhu/LeetCode
/540. Single Element in a Sorted Array.py
1,174
3.625
4
class Solution(object): # def singleNonDuplicate(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # # time complexity O(n) # # space complexity O(1) # n = 0 # for num in nums: # n = n ^ num # return n def singleNo...
2ac186efc6e3e4a28bf36c5588291421e114a3c7
tianbaozhu/LeetCode
/23. Merge k Sorted Lists.py
719
3.8125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ heap = [] dummy = ...
a4fc946b7420898e070030782edecefb520b1555
pmorrell/Utilities
/splitter/splitter.py
1,802
3.953125
4
#/usr/bin/env python # 12 August 2014, St. Louis, MO # Peter L. Morrell - my first piece of Python code # This script is intended to split a file into smaller pieces # so that it can be uploaded to S3 (Amazon) storage. # Sending the files to a specified S3 repository would be a nice addition. # The UNIX split command ...
28ca3b3521994cdb317d3f8baadc779fc61804f7
sylvainsalame/Udemy-MayaPython
/Scripts/UI/ReusableUI_HOWTO.py
5,163
3.78125
4
from maya import cmds import tweener from gearCreator import gears2 as gear # We put a lot of work into making our window for the tweener. # But what if we want to make another window? Do we have to write everything again? # Fortunately Python classes support inheritance # Just like your inherit your good looks from...
c48436971967d5e457bff1192129d193d986dc31
AC-DC-glitch/Cool-Python-Projects
/Guess_The_Number.py
813
4.09375
4
import random guess_num = random.randint(1, 100) user_guess = int(input("Try to guess the number! It lies between 1 and 100. You have 5 guesses, use them carefully!:")) guess_count = 0 while user_guess != guess_num and guess_count < 4: if user_guess < guess_num: print("The number you are looki...
b545339131d03e32f90fe553a767ba66caaaacfd
GINK03/project-euler-solvers
/65/euler.py
431
3.53125
4
import sys,itertools,math def euler_generator(): n = 1 while True: yield 1 yield 1 yield 2*n n += 1 t = [2, 3] def calcFomula(n, e): # t = e*t-1 + t-2 t.append(e*t[-1] + t[-2]) return t[-1] # main for i, e in enumerate(euler_generator()): i += 1 if i > 2:...
b68d4117b48495e6ffedad9e21d0398e72a799a2
GINK03/project-euler-solvers
/69/euler_bruteforce.py
841
3.5
4
import math, sys, os, itertools,fractions sys.path.append('../pythonlib') import basic pTable = set(basic.primeTable(1000000)) def countPrime(n): if n in pTable: return n-1 i = 2 t = 1 #while i*i <= n: while i <= n: #print n, i, fractions.gcd(n,i) if fractions.gcd(n,i) ...
628e6392054e5256324f4de38c0c913721de6280
GINK03/project-euler-solvers
/91/euler.py
601
3.75
4
import math, os, sys, itertools def is_right_triangle(P, Q): if P[1] == 0 and Q[0] == 0: return True elif P[0] * (Q[0] - P[0]) == P[1] * (P[1] - Q[1]): return True elif Q[0] * (P[0] - Q[0]) == Q[1] * (Q[1] - P[1]): return True return False def is_right_lower(P, Q): return ...
70ca9640d5d0c6d601869c2dac9402b5220c5a1b
crsroy/calculator-practice
/test/operation.py
1,557
3.765625
4
import re def str_proc(text): text = text.replace(' ', '') if re.search('[^\d]', text[0]): text = '0' + text # 匹配非数字非四则运算符号or有连续重复运算符 if re.search('[^\d\+\-\*/.]', text) or '' in re.split('[\+\-\*/]', text): return None return text def operation(text): if not text: re...
3c16a7d51658806c1233e14640f6ce6d3cabda12
voksmart/python
/QuickBytes/StringOperations.py
1,601
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 11 13:35:40 2019 @author: Mohit """ # String Assignment str1 = "Hello" str2 = "John" # Checking String Length print("Length of String is :",len(str1)) # String Concatenation (join) print(str1 + " "+str2) # String Formatting # inserting name of guest a...
d433d5b3701d97562e5af0eafecc57527fe618ed
vapat/homework-09
/unitconverter.py
487
3.96875
4
print("hallo! hier kannst du kilometer in meilen umrechnen.") km = int(input("gib bitte die km zahl ein: ")) print(km * 0.621371, "meilen") print("möchtest du noch etwas umrechnen? Ja / Nein") antwort = input(" ") while antwort != "Nein": km = int(input("gib bitte die km zahl ein: ")) print(km * 0.621371, "...
3fb229c64db00cbcbe78640274be75203fccfcb1
mady1258/Bioinformatics_Stronghold
/solutions/sseq.py
1,171
3.515625
4
import sys from rosalind_utility import parse_fasta def subseq_indices(string, query): ''' Locate Subsequence :param string: main string :param query: query string :return: indices of symbols of query as a subsequence in string ''' positions = [0 for _ in query] i = 0 j = 0 while i ...
bed469e6536fe5765bd7ec7b6700160126d43640
mady1258/Bioinformatics_Stronghold
/solutions/root.py
503
3.71875
4
import sys from cunr import count_unrooted_binary_trees def count_rooted_binary_trees(n): return count_unrooted_binary_trees(n) * (2 * n - 3) % 10 ** 6 if __name__ == "__main__": ''' Let B(n) represent the total number of distinct rooted binary trees on n labeled taxa. Given: A positive integer n (n...
7879c56ef4fc2f8f8afe29902de0e97d53ca1765
mady1258/Bioinformatics_Stronghold
/solutions/conv.py
1,018
3.640625
4
import sys def Minkowski_difference(set1, set2): diff_multiset = [] for s1 in set1: for s2 in set2: diff_multiset.append(round(s1 - s2, 5)) multiplicities = {} for item in diff_multiset: multiplicities[item] = diff_multiset.count(item) max_val = -1 for item, count...
a5d0e8d0c3c0daa2675bc3d1876d69fd930e28ea
mady1258/Bioinformatics_Stronghold
/solutions/lia.py
1,537
3.84375
4
import sys from operator import mul from math import factorial as fact from functools import reduce def choose(n, x): ''' Returns the integer value for n choose x. ''' if x in (0, n): return 1 if x > n / 2: return reduce(mul, range(x + 1, n + 1)) / fact(n - x) else: retu...
aac0c96ee892889b6ce2d4bd09b32d3d8f6e801e
ErosMLima/python-server-connection
/exercicios-aula-8-math-module.py
148
4.15625
4
from math import sqrt,floor num = int(input('Digite um número: ')) raiz = sqrt(num) print('A raiz de {} é iqual a {}'.format(num, floor(raiz)))
c5e7b72cabf084c40320d31eb089b93451d7072d
ErosMLima/python-server-connection
/average.py
217
4.375
4
num = int(input("how many numbers ?")) total_sum = 0 for n in range (num): numbers = float(input("Enter any number")) total_sum += numbers avg = total_sum / num print('The Average number is?'. avg)
f39bfb655a256744ebf8601366e34860bd472d8e
ErosMLima/python-server-connection
/ex010.py
374
3.984375
4
#Exercicio 10 crie um programa que leia quanto dinheiro uma pessoa tem na #carteira e mostre quantos dólares ela pode comprar. carteira = float(input('O valor em carteira: ')) dolar = 1 reais = 3.27 wallet = carteira * (reais * dolar) print("O valor de ${} dólares vale ${} totalizando um montante de ${} dólares...
c29fb5d2a57fc7b76fb1a7253daef780658a496a
meduardacn/Redes
/T1/eightb6t.py
2,533
3.59375
4
class EightB6T(): def table(): f = open("eightb6t.txt", "r") text = f.read() text = text.split("\n") table = dict() for elem in text: value = elem.split(" ") table[value[0]] = value[1] return(table) def invertedTable(): f = open("e...
c1c0f2fb59c845cd567f966224d831cbb1333375
HTR-United/htr-united.github.io
/assets/vanilla-i18n/compile.py
1,657
3.578125
4
import csv import json from typing import List, Dict, Union Output: Dict[str, Dict[str, Union[Dict, str]]] = {} def decomment(csvfile): # https://stackoverflow.com/a/50592259 for row in csvfile: raw = row.split('#')[0].strip() if raw: yield raw def augment_dict(keys: List[str], dictionary: Di...
eedc7dd3a9c03bb370f10e2d21b6a8a90ad0bd11
caneryalcin/Python-Projects
/ExchangeRate-USD--Python/exchangeRate.py
737
3.53125
4
import requests import json import smtplib import time def exchange_rate(): url = "https://api.exchangeratesapi.io/latest" r = requests.get(url) data = r.json() #convert the value to json return data['rates']['USD'] def send_email(): import smtplib # SMTP is required to connect to the mail serve...
0824911b8912ad5fbd469897317c596e35453d6a
AnujPatel21/DataStructure
/Binary_Tree.py
3,525
4.0625
4
from Queue import * class Node: def __init__(self,data): self.left = None self.right = None self.data = data def insert(self,data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) el...
3a926ac51f31f52184607c8e4b27c99b4cbb9fb8
AnujPatel21/DataStructure
/Merge_Sort.py
863
4.25
4
def merge_sort(unsorted_list): if len(unsorted_list) <= 1: return unsorted_list middle = len(unsorted_list) // 2 left_half = unsorted_list[:middle] right_half = unsorted_list[middle:] left_half = merge_sort(left_half) right_half = merge_sort(right_half) return list(merge(left_half,...
0fd5305783d8180e0610bfabf8bb2374aacf966a
AnujPatel21/DataStructure
/average.py
169
3.921875
4
list1 = [] n = int(input("Enter size of list : ")) for i in range(0,n): elem = int(input("Enter numbers : ")) list1.append(elem) avg = sum(list1) // n print avg
ccb6ddde2f71062b478185a1c012b677f6c50ed7
AnujPatel21/DataStructure
/LinkedList1.py
1,797
3.71875
4
class node: def __init__(self, data): self.data = data self.nextval = None class Linklist: def __init__(self): self.headval = None def printlist(self): printval = self.headval while printval is not None: print(printval.data) printval = printv...
4c8e5589c0dc95d1b924fad04e18bbaa3d0a5318
Annamalai1995/websitecreated
/callingfunc2.py
365
3.5625
4
def prompt(qual,ref): if qual == 'ug' and ref == 'HR':print("you are in uk team") elif qual == 'diploma' and ref == 'TestLead':print("Test Associate") elif qual == 'diploma' and ref == 'TestLead':print("Test Associate") else:print("you are hired") prompt('engg','Project Manager') prompt('ug','...
7778f0419861f1e279b5da70251a0a781f635462
VadimZakablutski/funktsionid
/funktsionid.py
1,002
3.890625
4
from module import * while True: print("Funktsioonid".center(50,"+")) v=input("arithmetic- A, \nis_year_leap- B, \nsquare- C, \nseason- D, \nbank- E") if v.upper()=="A": a=float(input("Arv 1: ")) b=float(input("Arv 2: ")) c=input("Tehe: ") result=arithmetic(a,b,c) pri...
9fe71cad659e416a3c9349114ceebacae3895b15
12agnes/Exercism
/pangram/pangram.py
317
4.125
4
def is_pangram(sentence): small = set() # iterate over characters inside sentence for character in sentence: # if character found inside the set try: if character.isalpha(): small.add(character.lower()) except: raise Exception("the sentence is not qualified to be pangram") return len(small) == 26
4ea96dfd07c7443af5840084fb1eb8e5123c9176
naveenkamalpv/computer-graphics-openGL
/programs/Bresenham_circle.py
1,501
3.953125
4
#Bresenham's circle drawing python opengl program from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import sys def init(): glClearColor(0.0,1.0,1.0,0.0) glColor3f(1.0,0.0,0.0) glPointSize(2.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0,640.0,0.0,480.0) def readinput_c...
91b05fb8a27914684d4aa68bfc64b5b7ab38165b
edwardcodes/Udemy-100DaysOfPython
/Day-18/different-shapes.py
416
3.953125
4
from turtle import Turtle, Screen import random t = Turtle() colours = ["orange red", "dark violet", "peru", "lime green", "cyan", "deep pink", "indian red"] def draw_shape(sides): angle = 360/sides for _ in range(sides): t.fd(100) t.right(angle) for shape_sides in range(3, 11):...
c5a777c88c3e6352b2890e7cc21d5df29976e7e7
edwardcodes/Udemy-100DaysOfPython
/Self Mini Projects/turtle-throw/who_throw_better.py
1,371
4.3125
4
# import the necessary libraries from turtle import Turtle, Screen import random # Create custom screen screen = Screen() screen.setup(width=600, height=500) guess = screen.textinput(title="Who will throw better", prompt="Guess which turtle will throw longer distance?") colors = ["red", "orang...
643150c21df243cd2780e3dd6c260fe883628fae
edwardcodes/Udemy-100DaysOfPython
/Day-17/quiz_brain.py
1,150
3.765625
4
class QuizBrain: def __init__(self, q_list): self.question_number = 0 self.question_list = q_list self.score = 0 def still_has_questions(self): """returns True if questions are still to answer, False if there are no questions left""" return self.question_number ...
a1b55422e2b6894d140dd58033843110d1374fc1
Nateque123/python
/python_tutorials/chapter3/for_loops.py
226
4.09375
4
# Sample of For loops # for i in range(1,11): # print(f"Hello world: {i}") # Sum of numbers num = int(input("Enter number: ")) total = 0 for i in range(1,num+1): total += i print(f"Your answer : {total}")
a0b048b1662eb9c262fc453d8775a50af187a9cc
rveneracion/gpioled
/rgbled.py
868
3.53125
4
import RPi.GPIO as GPIO import time pinmap = { 'r':16 ,'g':20 ,'b':21 } pinlist = [16,20,21] GPIO.setmode(GPIO.BCM) def initpins(): for pin in pinlist: GPIO.setup(pin, GPIO.OUT) def pinOn(pin): GPIO.output(pin, GPIO.HIGH) def pinOff(pin): GPIO.output(pin, GPIO.LOW) def onoff(pi...
8680ed0c79f30dead7add45ccba90fa253374d76
Nam1130Tx/Python
/Python Assignments/abstraction.py
597
4.28125
4
#Python: 3.9.0 #Author: Nicholas Mireles #Assignment: Abstraction Assignment from abc import ABC, abstractmethod class Shapes(ABC): def sides(self): print('How many sides does a ') @abstractmethod def num(self): pass class Triangle(Shapes): def num(self): ...
0e21ece8f07b4abc07641459cc09d68cc31f351c
Nam1130Tx/Python
/Python Assignments/PY_Class_Assignment.py
1,304
4.125
4
# Python: 3.8.5 # Name: Nicholas Mireles # Assignment: Class Assignment class instrument(): def __init__(self, name, section, band): self.name = name self.section = section self.band = band class strings( instrument ): def __init__(self, name, section...