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
09aeafc69b0d30dcbb773a6bc91cbb29840d8e1c
minthf/codewars
/responsible_drinking.py
174
3.9375
4
def hydrate(drink_string): water = sum([int(x) for x in drink_string.split() if x.isdigit()]) return '1 glass of water' if water == 1 else f"{water} glasses of water"
fddef7c03cb660307163856d591186a056d49a20
minthf/codewars
/sum_of_numbers_from_0_to_n.py
196
3.640625
4
def show_sequence(n): if n == 0: return '0=0' if n < 0: return f"{n}<0" arr = [str(x) for x in range(n+1)] return '+'.join(arr) + f" = {sum([int(x) for x in arr])}"
b1a2982f9a82b2da82bf0e5735d8d75cdfae1acb
curiosubermensch/python-autodidacta
/pythonPildorasInformaticas/continuePassElse.py
880
3.78125
4
def continua(): for i in "hola a todos": if i=="o": continue #tu continua que este caso no importa, ignoralo print(i, end=" ") #h l a a t d s def continua2(): c=0 f="hola mundo" for i in f: if i==" ": continue #tu sigue e ignora este caracter c+=1 print("tu frase tiene ",c,"...
9c52f450362698d376cba79886778948e3f5f67e
curiosubermensch/python-autodidacta
/python training/if_anidados_promedios.py
572
4.03125
4
""" Confeccionar un programa que pida por teclado tres notas de un alumno, calcule el promedio e imprima alguno de estos mensajes: Si el promedio es >=7 mostrar "Promocionado". Si el promedio es >=4 y <7 mostrar "Regular". Si el promedio es <4 mostrar "Reprobado".""" n1=int(input("ingrese nota 1: ")) n2=int(input("i...
5b1dd5c8f0a6a6e9c1dd6861bc9649899d3a25e1
curiosubermensch/python-autodidacta
/pythonPildorasInformaticas/POO/poo1.py
863
3.75
4
class Coche(): #atributos de la clase coche largoChasis=250 #cm anchoChasis=120 ruedas=4 enMarcha=False #metodos de la clase coche, son funciones propias de ésta clase #funcion seteadora del atributo enMarcha: def arrancar(self): #self equivale al this, indica objeto perteneciente a la clase sel...
98b9056312ec3fca6d8e0c6ba99ceb97988df33d
curiosubermensch/python-autodidacta
/python training/area_cuadrado.py
354
3.59375
4
# Hallar la superficie de un cuadrado conociendo el valor de un lado. x = int(input("ingrese el lado: ")) area=x*x print("el area es: ") print(area) # ctrl+alt + b ejecuto de inmediato """ { "keys": ["ctrl+alt+b"], "command": "run_existing_window_command", "args": { "id": "repl_python_run", "file": "config/...
7271cc5e8c22c1d971428f37a2cac1801a19e878
curiosubermensch/python-autodidacta
/python training/funciones.py
242
3.609375
4
def gato(nombre): print("tu gato se llama "+nombre) nombre='juan' print(nombre[0]) #se imprime una j if nombre[0]=="j": #verificamos si el primer caracter del string es una j print(nombre) print("comienza con la letra j")
f36a625ec88dd2c343a5cd267ae9519a1adac53c
curiosubermensch/python-autodidacta
/python training/cantinfleoCuma.py
1,710
4.03125
4
#Solicitar la carga del nombre de una persona en minúsculas. # Mostrar un mensaje si comienza con vocal dicho nombre. def vocal(): n=input("ingresa tu nombre: ") if n[0]=="a" or n[0]=="e" or n[0]=="i" or n[0]=="o" or n[0]=="u": print("tu nombre comienza por una vocal") def dos(): a="zapatos" ...
c366118597ba334a7ae6a168e8ae50958f8f112d
curiosubermensch/python-autodidacta
/Juegos/pong.py
3,431
3.59375
4
import turtle wn=turtle.Screen() #obj ventana wn.title("Pong 2019") wn.bgcolor("black") wn.setup(width=800, height=600) #ancho de la ventana wn.tracer(0) #jugador 1 (paleta 1): jugador1=turtle.Turtle() jugador1.speed(0) #que se vea de inmediato el jugador jugador1.shape("square") #forma de la pelota ju...
da0158c1a20f3cf8a521b342fd4315bb5672100d
curiosubermensch/python-autodidacta
/wily.py
290
4.125
4
#while es un ciclo indefinido def whily(): n=int(input("ing numero positivo:")) while n<0: print("error de ingreso") n=int(input("ing numero positivo:")) print("el numero positivo ing es: ",n) def whilyBreak(): n=int(input("ing numero positivo:")) if n<0: break print()
f7802f949050798b8b5ba4ef63f4102d85073a99
plojhi/Python_Credit_Calculator
/Credit_Calculator.py
1,881
3.765625
4
import math def count_of_months(): print("Enter credit principal:") P = int(input("> ")) print("Enter monthly payment:") A = float(input("> ")) print("Enter credit interest:") i = (float(input("> ")) / 12) / 100 n = math.log((A / (A - i * P)), (1 + i)) if n // 12 == 1 ...
9f9eb1523bd235c271fd15e9aa6cf50975f6fcf0
HBharathi/Python-Programming
/Inheritance.py
334
3.890625
4
class Animal: #Parent Class def walk(self): print("walk") class Dog(Animal): #child1 class def bark(self): print("bark!!!!!!!!!!!") class Cat(Animal): #child2 class def meow(self): print("meow meow!!") c1 = Cat() #objects created for child1 class c1.walk() c1.meow() d1 = Do...
d673103b6d9361916427652b337b9fbbf1fe7eae
cnkarz/Other
/Investing/Python/dateCreator.py
1,743
4.21875
4
# -*- coding: utf-8 -*- """ This script writes an array of dates of weekdays as YYYYMMDD in a csv file. It starts with user's input, which must be a monday in the same format Created on Wed Jan 25 07:36:22 2017 @author: cenka """ import csv def displayDate(year, month, day): date = "%d%02d%02d" % (year, month, da...
534294c181657a51037f6cd13fd4d6efb4f4b6f4
Choapinus/SistemasInteligentesUNAB
/Tarea 5/sergio/Tarea 3/TSP-GA/costMatrix.py
1,123
3.578125
4
import math class CostMatrix: def __init__(self, townList): self.townDict = dict() self.townList = townList self.tmpTownList = townList def createCostMatrix(self): count = 1 while (count <= len(self.townList)): #Crea un diccionario con cada numero de la ciudad self.townDict[count] = dict() count ...
1ed53d9feed04c6c487bdaf53413bf2a04be2b52
keelanfh/2020-advent-of-code
/6/start.py
329
3.53125
4
from functools import reduce with open("6/input.txt") as f: data = f.read() groups = data.split("\n\n") # Part 1 print(sum(len({x for x in g if x != "\n"}) for g in groups)) # Part 2 total = 0 for group in groups: x = reduce(set.intersection, (set(x) for x in group.split())) total += len(x) prin...
4e24af0ca0feaca8a035352ba99b2ac6c0dd6972
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Recursion/nthFibonacciNumber.py
597
4.09375
4
def fibonacciIterative(index): if index == 0: return 0 if index == 1: return 1 prevValue = 0 valueBeforePrevValue = 1 while index >= 1: answer = prevValue + valueBeforePrevValue valueBeforePrevValue = prevValue prevValue = answer index -= 1 retur...
244b6c9d829b45dd9fef7dea00f8eadd569ba0cd
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Examples/Arrays/negativePositiveSort.py
384
3.71875
4
def sortNegativePositive(arrayInput): i = 0 j = len(arrayInput) - 1 while i <=j: while arrayInput[i] < 0: i += 1 while arrayInput[j] >= 0: j -= 1 if i < j: arrayInput[j], arrayInput[i] = arrayInput[i], arrayInput[j] inputArr = [2,-3,4,-5,6,-7,8...
ead2b35de9f951e512e45b525e16617129142127
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Sorting/selectionSort.py
1,025
3.9375
4
def selectionSort(arrayInput): # Smarter implementation for i in range(len(arrayInput)): smallest = arrayInput[i] for j in range(i + 1, len(arrayInput)): if arrayInput[j] <= smallest: smallest = arrayInput[j] arrayInput[j], arrayInput[i] = arrayInput[i], ...
644386467df73009395ef1267fcc3fb99878d018
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Hashmaps.py
2,070
3.859375
4
#Hash maps and Hashing functions Initial_capacity = 50 #an arbritrary value. Can be changed to any value class node: def __init__(self, key, value): self.key = key self.value = value self.next = None class HashTable: def __init__(self): self.capacity = Initial_capacity ...
01cbec33157876e2e43ece1e93a2ac29f463fdac
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Sorting/mergeSort.py
910
3.84375
4
def mergeSort(arrayInput): if len(arrayInput) == 1: return arrayInput #SPLIT ARRAY middle = len(arrayInput)/2 leftArray = arrayInput[:middle] rightArray = arrayInput[middle:] return merge(mergeSort(leftArray), mergeSort(rightArray)) def merge(leftArray, rightArray): result = ...
d7a0c5ae5e0ebc9d4a374d8e99ed87f02978a5de
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Examples/Arrays/multipleMissingElement.py
1,125
3.609375
4
def multipleMissingElement(arrayInput): missingElements = [] for index in range(len(arrayInput) - 1): if arrayInput[index + 1] - arrayInput[index] > 1: numOfMissingElements = arrayInput[index + 1] - arrayInput[index] - 1 if numOfMissingElements == 1: missingEleme...
05015d1f5a53dfe17ab49bc1356d171de76ebce5
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Examples/Arrays/reverseArray.py
304
3.921875
4
def reverseArray(arrayInput): i = 0 j = len(arrayInput) - 1 while i <= j: arrayInput[i], arrayInput[j] = arrayInput[j], arrayInput[i] i += 1 j -= 1 inputArr = [2,3,4,5,6,7, 8] print(inputArr) reverseArray(inputArr) print(inputArr)
68e42633e8b461cc9627b95e5c67053bdc2cea45
MichaelOgunsanmi/Algorithms-and-Data-Structures
/Sorting/radixSort.py
1,194
3.765625
4
import math def getDigit(number, placeValue): return math.floor(abs(number) / pow(10, placeValue)) % 10 def digitCount(number): if number == 0: return 1 return math.floor(math.log10(abs(number))) + 1 def mostDigits(arrayInput): maxDigits = 0 for number in arrayInput: maxDigits = max(ma...
6e65f61a447b7040cc30a495f02e994df9fbfe6f
alexpon92/ntlg_test
/Python/hw1/base_tasks.py
2,378
3.875
4
import math """ 1. Даны 2 строки long_phrase и short_phrase. Напишите код, который проверяет действительно ли длинная фраза long_phrase длиннее короткой short_phrase. И выводит True или False в зависимости от результата сравнения. """ long_phrase = 'Насколько проще было бы писать программы, если бы не заказчики' short...
b3ee3c37efe6d97d32869f14d6e5bba5e9e8fc91
bglogowski/IntroPython2016a
/students/Boundb3/Session05/cigar_party.py
594
4.125
4
#!/usr/bin/env python """ When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values ...
c81670473d618bdb663d88d94f54980e3f0b563c
rohitgupta29/Python_projects
/Data_Structures/4.Hexadecimal_output.py
337
4.1875
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 10 16:46:47 2020 @author: infom """ def hex_output(): decnum = 0 hexnum = input('Enter a hex number to convert: ') for power, digit in enumerate (reversed(hexnum)): decnum += int(digit,16) * (16 ** power) print(decnum) ...
0189a94302c455cce3b9c51d6dfd79822a358fcf
rohitgupta29/Python_projects
/Data_Structures/15.Rainfall.py
504
4.03125
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 11 11:20:09 2020 @author: infom """ def get_rainfall(): rainfall = {} while True: city_name = input('Enter city name: ') if not city_name: break mm_rain = input('Enter mm rain: ') rainfal...
87b73b0e6c80f4a30283748fbfbd4e70900a7795
marinabar/cs50
/pset6/cash.py
403
4.03125
4
while True: try: change = float(input("Change owed: ")) if change >= 0 and change <= 100: break except ValueError: print("No.. the input string is not a number. It's a string") coins = 0 argent = int(round(change * 100)) coins += argent // 25 argent %= 25 coins += argent /...
3d92ea03d3fa09cc1e43a00dbe9fa558a047f3ab
pizzapanther/python-flex-02
/exercise1.py
167
3.875
4
raw_input = input('age? ') age = int(raw_input) if age >= 21: print('You get beer') elif age < 18 or age > 10: print('get lost') else: print('Sorry')
0dd49c87ec154f01500d74af321043dcc1c2e3cd
Kwask/project-euler
/0005/lcm.py
595
3.890625
4
min_multiple = 2 # We start at 2 instead of 1, everything is divisble by 1 max_multiple = 20 def multiplyRange(min, max): product = 1 for i in range(min, max): product *= i return product max_lcm = multiplyRange(min_multiple, max_multiple) multiples = max_multiple-min_multiple for i in xran...
ce982264c776db4f075d1cc053d4a4c99536ef03
sillsdev/WorldPad
/Test/TestSql/unittestasserts.py
1,378
3.5
4
""" unitassert Description: An IronPython script using unittest doesn't crashes on asserts. (22 March 2007.) Even if the bug is fixed, these asserts are helpful for counting up pass/failure. """ class UnitAssert: """Replacement for asserts in IronPython and unittest""" def __init__(self): self.passed = ...
73a241b1ba5d6337a93fe53fdfdb85815953d13e
AaryaVora/Python-Level-1-2
/hw3.py
266
4.125
4
fnum = int(input("Please enter a number: ")) snum = int(input("Please enter a number: ")) if fnum == snum : print("Both numbers are equal") elif fnum < snum: print("Second number is greater") else: print("First number is greater than the second number")
fd96154dda20cb2c0f72f1ca5fa070f101ff4d1b
VikParuchuri/percept
/percept/utils/input.py
532
3.5625
4
def import_from_string(import_string): """ Import a class from a string import_string - string path to module to import using dot notation (foo.bar) """ import_split = import_string.split(".") import_class = import_split[-1] module_path = ".".join(import_split[:-1]) mod = __import__(modu...
6b66eb0f995952c2ffeb387ebf8b3b98e35b02e8
eeason11/SCRAPERS
/dartmouth_scraper.py
861
3.546875
4
import pandas as pd import lxml.html as lh from selenium import webdriver driver = webdriver.Chrome('C:/Users/ethan/local/bin/chromedriver_win32/chromedriver.exe') url = 'http://oracle-www.dartmouth.edu/dart/groucho/timetable.main' driver.get(url) SA_button = driver.find_element_by_xpath('//input[@value="Subj...
87e41c345643da7e1be01ef5ddc397e6397f027b
Widizzi/NeuralNetwork
/src/library/net/components/Neuron.py
735
3.828125
4
import src.library.net.components.Activation as Activation import math import numpy as np class Neuron: ''' A single Neuron ''' def __init__(self, activationFunction=Activation.Activation.ReLu): ''' Initializes the Neuron with a given activation function ''' self.acti...
5bd7ea5e023aced759ba1fd7c0248fec63d0155a
Widizzi/NeuralNetwork
/src/library/net/components/Activation.py
1,588
3.84375
4
import numpy as np from enum import Enum class Activation(Enum): ReLu = 1 Sigmoid = 2 Gaussian = 3 def switch(function, input): ActivationFunctions = { Activation.ReLu: relu(input), Activation.Sigmoid: sigmoid(input), Activation.Gaussian: gaussian(input) } return Activa...
ad3466cf8daae3a88105274b5463a1ea2103d348
ychenz/Algorithm-practice
/trees.py
1,667
3.671875
4
class TreeNode: def __init__(self,key,val): self.key = key self.val = val self.balance_factor = 0 self.parent = None self.left = None self.right = None class Tree: def print(self): pass pass class AVLTree(Tree): root = None def __init_...
e61e0925cb261ff53f4a3ce9cf90314a3d9c4ed9
Harrison-Z1000/IntroProgramming-Labs
/labs/lab_03/pi.py
1,077
4.34375
4
# Introduction to Programming # Author: Harrison Zheng # Date: 09/25/19 # This program approximates the value of pi based on user input. import math def main(): print("This program approximates the value of pi.") n = int(input("Enter the number of terms to be summed: ")) piApproximation = approximate(n)...
1005945c31f8e533bba9d23a7c2bb6a00671ec56
Harrison-Z1000/IntroProgramming-Labs
/labs/lab_08/product.py
711
3.78125
4
class Product: def __init__(self, name, price, quantity): # Includes all info about a single product self.name = name self.price = price self.quantity = quantity def inStock(self, count): # Takes an integer count and determines whether that many of the product are in sto...
6080fd157cd568d355f023c6318748c072fea2af
mdomanski-usgs/scoupy
/scoupy/water.py
4,531
3.71875
4
"""This module contains the WaterProperties class definition. WaterProperties contains methods for calculating properties of water for acoustic processing. """ import numpy as np class WaterProperties: """Calculates properties of water WaterProperties contains methods for calculating properties of water. ...
ec6875d9db62bd691ce71bb9180eee5aaae3eedd
myalenti/UniBlog
/UniBlog/count.py
500
3.796875
4
fruit = ['apple','orange','grape','kiwi','orange','apple'] #defining the list def analyze_count(l): try: counts = {} for i in l: print ('Fount item' + ' ' + i) #if i in counts: counts[i] = counts[i] + 1 #else: # counts...
1fee6c8d64592de3973dc2c28faff7faf0c4a854
alinaMKR/Python-Practice-
/ForestDrawing/utilities.py
6,827
4.1875
4
import turtle #import turtle to implement graphics import math #to find height of triangle import random #to generate random size of trees #set window size and color w_width = 800 w_height = 800 bg_color = 'aliceblue' #background color simulating sky turtle.setup(w_width, w_height) turtle.bgcolor(bg_color) turtle.sp...
c859465d1cc7916a78d3ebdec8785d72b43b071f
Sagarnaikg/Cryptography
/Cryptography/decrypto.py
732
3.984375
4
def decrpto(result,key): end_string = "" #second layer encryption for letter in result: l=ord(letter)+key l=chr(l) end_string=end_string+l display(end_string) def display(message): reverseMessage = "" #firstlayer encryption ...
20393f66baf0fd03f72e53d1a8d771c1a130ee99
chinmayabhatb/Linear-Regression-Model-for-temperature
/temp_using_sklearn.py
1,227
3.625
4
# Linear Regression Model for temperature from sklearn import model_selection from sklearn import linear_model import sklearn import matplotlib.pyplot as plt import numpy as np import random # y=mx+c this linear equation # F= 1.8*C+32 this is real time data calculation # creating data from random values x...
da6e91c0e917d6f926fda977d95aef067b9febd1
amir-jafari/Data-Visualization
/Streamlit/basic_code/01-title.py
744
3.5
4
import streamlit as st # %%-------------------------------------------------------------------------------------------------------------------- st.title("Streamlit App") st.markdown("""___""") st.header("Header 1") st.subheader("header2") st.divider() # %%----------------------------------------------------------------...
ca283eee1d0e089e4c54bea002ece146dc90e445
ErikaMariana/URIJUEZ
/Areadelcirculo.py
93
3.578125
4
# -*- coding: utf-8 -*- radio= float(input()) A= 3.14159*radio*radio print("A="+"%.4f" % A)
a29e23c8dd15be1d4975b952aee27df6b8e57ffe
OluJS/Small-tasks
/guessingGame/guessingGame.py
332
4.03125
4
import random secretNumber = random.randint(1, 5) guessCounter = 0 guessLimit = 3 while guessCounter < 3: userGuess = int(input("Guess the number: ")) guessCounter += 1 if userGuess == secretNumber: print("You won!") break else: print(f"You had 3 guesses and failed. The number was {sec...
a672c2826c3b9de125469ed2079772c8f350af62
SAMPROO/textadventure-game
/textadventure-python/eat.py
2,033
3.53125
4
def eat(conn, location_id, item): if item == None: print("What do you want to eat?") item = input("--> ") eat(conn, location_id, item) cur = conn.cursor() #CHECK IF IN INVENTORY OR IN A LOCATION check_loc_inv = "SELECT name, item_location_id, item_character_id, addhp FROM i...
13389cb1e7ef919bbba3f3528c736c6c545944c2
daniametller/hackerrank
/algorithms/maximumIndexProduct/maximumIndexProductNoOptim.py
1,726
3.703125
4
# https://www.hackerrank.com/challenges/find-maximum-index-product # You are given a list of N numbers a1,a2,…,an. For each i (1≤i≤N), define LEFT(i) to be the nearest index j before i such that aj>ai. # Note that if j does not exist, we should consider LEFT(i) to be 0. Similarly, define RIGHT(i) to be the nearest ind...
3a1c519a5268637faf52f3ae14675dea8ba57cb9
fredipucv/Sistemas-Embebidos
/ejercicio 3guia 2.py
98
3.59375
4
inicio=1; while inicio<16: if inicio%2==0: print(inicio) inicio+=1; print('Adios!')
080415b8ac913be7b991041c34fa3f52bf992297
wraikes/pythonds
/ch_1/ex_2.py
950
3.75
4
def gcd(m, n): while m%n != 0: oldm = m oldn = n m = oldn n = oldm%oldn return n class Fraction: def __init__(self,top,bottom): self.common = gcd(top, bottom) self.num = top // self.common self.den = bottom // self.common def __str__(self)...
4db441093baa7f64e6b6b09f96f20b095d0feb21
Alan-Murphy91/daily_py
/#4 first_missing_positive.py
454
4.09375
4
''' Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. ''' def first_missing_positive(arr): if not arr: retur...
1b2dea794f55fab9398ec2fcbf258df7007f0f90
yash95shah/Leetcode
/swapnotemp.py
284
4.28125
4
''' know swapping works on python without actually using temps ''' def swap(x, y): x = x ^ y y = x ^ y x = x ^ y return (x, y) x = int(input("Enter the value of x: ")) y = int(input("Enter the value of y: ")) print("New value of x and y: " + str(swap(x, y)))
dad632f550031cd5c565f380fb4592be652e9826
yash95shah/Leetcode
/Problem #1.py
1,501
3.96875
4
###Problem 1 - Day 1 - 06/10/2019 ''' Problem 1: Maximum Binary Tree Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum numb...
ca312b4e02650221b6bb5f34871ef12f45ad98d9
yash95shah/Leetcode
/sumwithoutarith.py
411
4.3125
4
''' Sum of two integers without actually using the arithmetic operators ''' def sum_without_arith(num1, num2): temp_sum = num1 ^ num2 and_sum = num1 & num2 << 1 if and_sum: temp_sum = sum_without_arith(temp_sum, and_sum) return temp_sum n1 = int(input("Enter your 1st number: ")) n2 = int(i...
c21e49399999040ab638c4e5394a8e11d0d4e273
yash95shah/Leetcode
/priorityqueue.py
767
3.96875
4
''' array = [ 0 0 0 0 0 ] After implementing push(5) array = [ 5 0 0 0 0 ] push(4) -> array = [ 5 4 0 0 0 ] iniitially push it to the closest available position. run a while loop to actually check where exactly the push needs to happen ''' class PriorityQueue: def __init__(self, maxsize): self).maxsize...
40e5099f346fec0d73edcb526e52fef510f77845
yash95shah/Leetcode
/wordexists.py
756
3.859375
4
def exist( matrix , word): for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == word[0]: answer = w_s(word,i,j,matrix) if answer == True: return answer return False def w_s(word, i,j,matrix): if i<0 or j<0 ...
367b41b94b48f05edecb8d7bc84faf8e6a805f70
yash95shah/Leetcode
/removeDups.py
1,131
3.859375
4
class Node: def __init__(self, val): self.val = val self.next =None class LinkedList: def __init__(self, head): self.head = Node(head) #self.next = None self.buffer = [self.head.val] self.allDone = False def append(self, data): if not self.head: ...
3962ed28f3ccc7d4689d73f5839bc6d016e43736
Juhkim90/Multiplication-Game-v.1
/main.py
980
4.15625
4
# To Run this program, # Press Command + Enter import random import time print ("Welcome to the Multiplication Game") print ("Two Numbers are randomly picked between 0 and 12") print ("Try to Answer ASAP. If you do not answer in 3 seconds, You FAIL!") score = 0 ready = input("\n...
55175cdc5f08c7f52efe4905e4efbd9037972064
ewartj/cs50_2020
/week6/readability.py
979
4
4
import re from cs50 import get_string def main(): text = get_string("Please input text:\n") readability(text) def readability(text): letter_count = 0.0 word_count = 1.0 sentence_count = 0.0 for i in text: # next line from https://www.tutorialgateway.org/python-program-to-check-charact...
442554266ce87af7740511669163b8c575a96950
OliviaParamour/AdventofCode2020
/day2.py
1,553
4.25
4
import re def load_file(file_name: str) -> list: """Loads and parses the input for use in the challenge.""" input = [] with open(file_name) as file: for line in file: parts = re.match(r"^(\d+)-(\d+) ([a-z]): (\w+)$", line) input.append((int(parts.group(1)), int(parts.group(...
0bf914d29316a47ff4e0adba67ea7f3ab45f9261
OliviaParamour/AdventofCode2020
/template.py
642
4.03125
4
import re import functools import itertools import operator def load(file_name: str) -> list: """Loads and parses the input for use in the challenge.""" input = [] with open(file_name) as file: for line in file: input.append(line.strip()) return input def myfunc(input: list) -> int...
d46b74f11b567206a6ec1eb8a854c4acea09dd54
christopherc1331/CodeChallenges
/10-10-20/MatrixAddiction.py
164
3.703125
4
def matrix_addition(a, b): # your code here for x in range(len(a)): for y in range(len(a)): a[x][y] += b[x][y] return a
402063b7d2631a19821b374a51fed16a08ef9288
Echo002/Python
/CodeAccu/03 comprehensions.py
1,464
3.78125
4
#!/usr/bin/env python #!-*-coding:utf-8 -*- #!@Author:xugao # ┌─┐ ┌─┐ # ┌──┘ ┴───────┘ ┴──┐ # │ │ # │ │ # │ >   < │ # │ │ # │ .... ⌒ .... │ # │ │ # └───┐ ┌───┘ # │ │ # ...
99c525f409e04319b9012cbf1773657c69aff72a
XxidroxX/BioInfo-Labs
/Lab1/es1.py
1,604
3.84375
4
""" ### Assignment 1 ### Write a python program that generates both fasta and fastq files containing reads with the following characteristics: - Read id contains a progressive number starting from 0. - Sequences have length 50 bp - Bases are randomly generated using a A,T,C,G alphabet, but probability of each base for ...
90fdea9c360ba4f108a7db0cec9c607d48e87356
ssmitar/NetworkAutomation
/ip_file_validity.py
832
4.09375
4
import os.path import sys #Checking IP address file and its content validity def ip_file_validity(): #Prompting user for input ipaddr_file = input("\n# Enter IP file path and name (e.g. D:\MyApps\myfile.txt): ") #Checking if file exist if os.path.isfile(ipaddr_file) == True: pr...
58869d2c0c09732e06f8e5c3f4486c08ae40b3c7
ojongchul/studyPython
/list.py
651
3.75
4
a = [1,2,3,4,5] print (a[0:2]) print (a[1:2]) b = '12345' print (b[0:2]) print (b[1:2]) c = [2,3,4,5,6] d = a+c f = [1,2,3,4,5,2,3,4,5,6] print (a+c) print (d) d.sort() print (d.sort()) f.sort() print (f) f.reverse() print(f) del a[2] print (a) a.append(3) print (a) e = [1,4,3,2] e.sort() print (e) print(a.index(...
56b9d449d5a8b4435192e8a7a09986bbdde61429
devplayer0/cs3012
/lca/dag.py
8,757
4.03125
4
class DAG: ''' Class representing a Directed Acyclic Graph. Note: it is up to the user to ensure the graph contains no cycles ''' def __init__(self): self.__vertices = {} def add_vertex(self, v): ''' Add a new vertex to the graph. Does nothing if the vertex is ...
71582b94b8df822e0ae2865fdd2d97c65d15361f
DarshAsawa/ML-and-Computer-vision-using-Python
/Python_Basics/mysql_python.py
1,219
3.53125
4
import mysql.connector import time myDB= mysql.connector.connect( host="localhost", user="root", passwd="123456", database="Python" ) print(myDB) #displaying tables in the database.. myCursor=myDB.cursor() print("Tables present in Python Database :") myCursor.execute("Show tables") results = myCu...
1b120b65333495c5bd98f63e0e016942b419a708
DarshAsawa/ML-and-Computer-vision-using-Python
/Python_Basics/Roll_Dice.py
413
4.28125
4
import random no_of_dices=int(input("how many dice you want :")) end_count=no_of_dices*6 print("Since you are rolling %d dice or dices, you will get numbers between 1 and %d" % (no_of_dices,end_count)) count=1 while count==1 : user_inp=input("Do you want to roll a dice : ") if user_inp=="yes" or user_inp=="y" or use...
85d937170e10c76eb0a5aba3f74918a2dc63267d
angelali4096/hri
/HRI/node.py
644
3.59375
4
# Graph-Node Implemenation # 16-467: Human-Robot Interaction class Node: def __init__(self, nid, pq_id, in_pq, g, x, y, mode): self.id = nid # The node ID self.pq_id = pq_id # The nodes index/priority in the priority queue self.in_pq = in_pq # Whether or not the node is in the priority queue s...
e3cbb90f3b3bd7d041dfc03402d5ee0578b1acb1
souravbadami/hackerrank
/itertools-product.py
239
3.765625
4
#!usr/bin/env python from __future__ import print_function from itertools import product a=map(int,raw_input().split()) b=map(int,raw_input().split()) _list=list(product(a,b)) for i in xrange(len(_list)): print(_list[i],sep="",end=" ")
790eaffede6339adc3f06928ceb6924f09354b35
souravbadami/hackerrank
/itertools-permutations.py
312
3.53125
4
#!/usr/bin/env python from __future__ import print_function from itertools import permutations #import os _str,pl=map(str,raw_input().split()) _str2=list(permutations(_str,int(pl))) _str2.sort() for i in xrange(len(_str2)): for j in xrange(len(_str2[i])): print(_str2[i][j],sep="",end="") print()
9a180dd54258c5a1e05200fb84857bc9b4e93b9b
TaihuLight/renew-skyline-path-query
/skyline_path/generator/trajectory_generator.py
1,508
3.5625
4
import random class TrajectoryGenerator: """ Generating Trajectory by random. Include Graph. """ def __init__(self, graph): super().__init__() self.graph = graph self.trajectory = [] def generator(self, prefer='value', stop_prob=1, sizes=10000): self.stop_prob ...
5fcc740fcaddbf9492020d820e54e37fa340ccad
Terrence1005/Finite-State-Machine
/regexp-py/reference/NFAtoDFA.py
3,234
3.65625
4
# NFAtoDFA.py : # This is Python code for representing finite automata, DFAs and NFAs, # and for converting from an NFA into a DFA. # # Ben Reichardt, 1/17/2011 # class DFA: """Class that encapsulates a DFA.""" def __init__(self, transitionFunction, initialState, finalStates): self.delta = transitionFunction ...
bf3c89ec1cb815ea258ddae693d7cf804692044d
mpp100579/test_case
/mpp/FUNC.py
7,568
4
4
# -*- coding:utf-8 -*- import time import string import os import random def func1(x,y): return x+y func2=lambda x,y:x+y#lambda函数用于运算简单的 print func2(4,8) def test(func1,a,b): print func1(a,b) test(func1,5,7) test(func2,6,9) func1(7,0) func=lambda x,y:x+y print func(4,6) re=map(func,[1,5,6,7],[4,6,7,0])#map函数将...
f989c34281c23fff2c4ac38344a56b3633268deb
mpp100579/test_case
/pytest_file/test_shili01.py
587
3.640625
4
# -*- coding:utf-8 -*- class Person: def __init__(self,age,sex): self.age=age self.sex=sex def set_age(self): self.age+=2 return age def set_sex(self): if self.sex=='famle': return '女' else: return '男' mpp1=Person(20,'famle') print (...
e292f359a1590e9f67e530deb99bbaf41506d9fb
ZainabMehdee/Augmented-Assignment-Operators
/main.py
549
3.640625
4
# Classes: Custom Data Types # Specialized Data Types # Modules that can be used from libraries.(Extensions, packages etc. # None = Nothing, 0 print(type(2+4)) num_iq = 14 print(bin(num_iq)) print(int("0b1110", 2)) # What is an expression? # It's a piece of code that produces a value. user_height = 156 user_age = ...
9ca7ae4bd64db696fd7da6da8e7d9b6bfbf4159e
99lalo/Python-Loops-n-Arrays-Practice
/exercises/12.4-Map_list_of_objects/app.py
713
4.09375
4
import datetime people = [ { "name": 'Joe', "birthDate": datetime.datetime(1989,10,24) }, { "name": 'Bob', "birthDate": datetime.datetime(1976,5,24) }, { "name": 'Erika', "birthDate": datetime.datetime(1990,6,12) }, { "name": 'Dylan', "birthDate": datetime.datetime(2002,12,14) }, { "name": 'Steve', "birthDate": ...
694a11e1cea8ba3513feed462d3819cb633e1663
99lalo/Python-Loops-n-Arrays-Practice
/exercises/12.1-more_mapping/app.py
172
3.609375
4
myNumbers = [23,234,345,4356234,243,43,56,2] #Your code go here: def increment_by_one(n): return n * 3 new_list = list(map(increment_by_one,myNumbers)) print(new_list)
f1d228b0afac00ffc567698775fc594b8e2b1069
nischalshk/pythonProject2
/3.py
385
4.3125
4
""" 3. Write code that will print out the anagrams (words that use the same letters) from a paragraph of text.""" print("Question 3") string1 = input("Enter First String: ") string2 = input("Enter Second String: ") sort_string1 = sorted(string1.lower()) sort_string2 = sorted(string2.lower()) if sort_string1 == so...
c69f1e5d6e6a9b6fe97aa0117a6f2e6c0952262d
jkfer/LeetCode
/Check_array_formation_through_concat.py
458
3.59375
4
# https://leetcode.com/problems/check-array-formation-through-concatenation/ class Solution: def canFormArray(self, arr, pieces): D = dict() for x in pieces: D[x[0]] = x # print(D) ans = [] for a in arr: if a in D: ans += D[a...
12656fa0f3fc97cbc002bb4759de82b2640f56bd
jkfer/LeetCode
/Reverse_words_in_string.py
582
3.90625
4
# https://leetcode.com/problems/reverse-words-in-a-string/ class Solution: def reverseWords(self, s): ANS = "" i = 0 while i < len(s): if s[i] != " ": word = "" while i < len(s) and s[i] != " ": word += s[i] ...
e838332cbe89a89c11746c421c6b284c0c05af94
jkfer/LeetCode
/Find_Largest_Value_in_Each_Tree_Row.py
1,117
4.15625
4
""" You need to find the largest value in each row of a binary tree. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(1) root.left = TreeNode(3) root.right = TreeNode(2) root.left.left = TreeNode...
78ebc29eae3cc985d1ee8fcc949d64a8677f2ae6
jkfer/LeetCode
/dp-fib_sequence.py
1,094
4.09375
4
""" Using Dynamic Programming for generating the output if the nth fibonacci The idea here is that when we have """ #recursive approach not good for larger numbers- ex: 1000 def fib(n, memo): # if there is a result in memo[n], return that if memo[n] is not None: return memo[n] # else y...
b23f22b50c37501e270555162eefee0d31166455
jkfer/LeetCode
/Ugly_Number_II.py
1,732
3.546875
4
# https://leetcode.com/problems/ugly-number-ii/ import math import collections class Solution: def is_prime(self, n): j = (n // 2) + 1 for k in range(2, j + 1): if n % k == 0: return False return True def good_divisors(self, n, primes): if self.is_...
11d528f8a27cdc573033da72358365d87c1b1863
jkfer/LeetCode
/Count_good_nodes_in_binary_tree.py
1,073
3.671875
4
# https://leetcode.com/problems/count-good-nodes-in-binary-tree/ # MEDIUM # 1448 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def goodNodes(s...
f1ba7c1de923d6921d0820a2c4f7946a4ebd52b6
jkfer/LeetCode
/increasing_triplet_subseq.py
473
3.609375
4
# https://leetcode.com/problems/increasing-triplet-subsequence/ # referred solution: class Solution: def increasingTriplet(self, nums: List[int]) -> bool: smallest = second_smallest = float('inf') for num in nums: if num < smallest: smallest = num if smalles...
2882d90e57c7ed6f3929cf08d465cbbd7938e112
jkfer/LeetCode
/Remove_Nth_Node_From_End_of_List.py
1,398
3.84375
4
# 19 """ Idea: provided node is N find the nth node from the start of N. Say this is X from there: = traverse N and X simultaneously until X.next is none. = now you have reached the node where the next node will be the nth from the last. from here its simply removing the next node of N task """ # ...
663256a9b04516df7abd17422ebaaaeaa9a074cc
jkfer/LeetCode
/All_elements_in_two_binary_search.py
1,699
3.640625
4
# https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ # 1305 # Medium import collections # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def getAllElements(self, root1, root...
61bb9daa92156671204a4b5169f4cf1a66464564
jkfer/LeetCode
/Split_a_String_in_Balanced_Strings.py
521
3.75
4
# 1221 # check for count of R and L to be equal in the intersection points class Solution: def check(self, s): return s.count("R") == s.count("L") def balancedStringSplit(self, s): ans = 0 i = 0 x = 2 while i + x <= len(s): S = s[:x] if self.che...
0d67208efcea56fc1d659658ecd26ef88cf16caf
jkfer/LeetCode
/Valid_Plaindrome_II.py
1,059
3.6875
4
# 680 """ Tough. Idea: compare charachters in both ends (first and last). If they are equal to each other remove both. and repeat. If they are not equal to each other: - include the first if the string[:-1] is a plaindrome - include the last if the string[1:] is a plaindrome """ class Solution...
13f220818fabf45f05a0f1253282748b3d219ec0
jkfer/LeetCode
/Multiply_Strings.py
2,204
3.546875
4
# 43 # 43. Multiply Strings num1 = "45696" num2 = "1235" class Solution: def multiply(self, num1, num2): if num1 == "0" or num2 == "0": return 0 ANS = [] for n in num2[::-1]: small_ans = [] carry = 0 for k in num1[::-1]:...
2af929754e2561b2afb516aba71908239ac82d8e
jkfer/LeetCode
/Add_Strings.py
369
3.921875
4
# 415 from math import pow def multip(num1, num2): n1 = n2 = 0 for i, num in enumerate(num1): n1 += (ord(num) - 48) * int(pow(10, len(num1) - 1 - i)) for i, num in enumerate(num2): n2 += (ord(num) - 48) * int(pow(10, len(num2) - 1 - i)) return str(n1+n2) num1...
3fe2e967f5e35bb73702eeb7a237e49597b0264e
jkfer/LeetCode
/Plaindrome_number.py
389
3.78125
4
# https://leetcode.com/problems/palindrome-number/ # 9 class Solution: def isPalindrome(self, x): # if x is negative or ends with a 0: if x < 0 or (x % 10 == 0 and x != 0): return False n = x x_rev = 0 while x > 0: lnum = x % 10 x = x /...
3d3bd2d281d4ebc021b404d0d11c12e5cb356292
jkfer/LeetCode
/Invert_Binary_Tree.py
1,348
3.9375
4
# 226 # This should be easy just do the BFS with root, right and left order, # instead of the traditional root, left and right # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(4) ro...
1f7512a66ddf2114a1cc99781a923a836f2d8d6b
jkfer/LeetCode
/Subtree_of_a_tree.py
1,120
3.71875
4
""" 572: Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. Idea: convert the input TreeNode ...
182ecf53e6d1816accb7ff97a0f3f4d61b56c8e8
jkfer/LeetCode
/Max_depth_of_N_array_tree.py
591
3.75
4
# https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ # 559 # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: def maxDepth(self, root): if not root: return 0 if not roo...
e093c6704e5b4c7a707280078a5bc80e221c21d9
jd1123/ProjectEuler
/Problem5.py
646
3.703125
4
import sys def main(): smallest = 1 factors = [] for i in range(1,21): if smallest % i == 0: factors.append(1) else: m = i divides = False for j in factors: if (m % j == 0): divides = True ...
985f41009485743756b33db227c514854f5cf3ed
kino002/base_tec
/Multi_tasking/threading_test.py
501
3.6875
4
# スレッド(threading)でマルチタスクプログラムを動かす import threading from time import sleep def test1(): while True: print("test1") sleep(1) def test2(): while True: print("test2") sleep(1) if __name__ == "__main__": thread_1 = threading.Thread(target=test1) # targetに関数を()無しで渡す threa...