blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0c9845d5f617319a905f3f1d30e6f9ef4b90135c
houhailun/leetcode
/Hot_100/leetcode104_二叉树的最大深度.py
1,341
3.6875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Time: 2020/1/14 14:03 # Author: Hou hailun # 深度:从根节点到叶子节点的最长路径上的节点数 # 二叉树的最大深度 = max(左子树的深度,右子树的深度) + 1 # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None clas...
21479279c68b0aba04211ffe703b6191067533b9
rajeshjaiswal878/Python-Packages
/re/regex_subn.py
2,050
4.46875
4
import re print(f'Usage Of re.subn method In Regex Example'.center(100)) in_p = "I went to him at 11 A.M. on 4th July 1886" # Using \d digit print('Result OF Sub Pat String [\d]:', re.subn('\d', 'N', in_p)) print('--' * 20) # Using \d+ for numeric values print('Result OF Sub Pat String [\d+]:', re.subn('\d+', 'NN'...
d25558a84237006214bd358e1b88d5d91e332d3d
liuyanhui/leetcode-py
/leetcode/reverse_words _in_a_string/reverse_words _in_a_string.py
735
3.9375
4
class Solution: def reverse_words(self, s): if not s.strip(): return "" print(s.strip()) ret = "" split_arr = s.strip().split() print(split_arr) split_arr.reverse() print(split_arr) for w in split_arr: ret += w + " " ret...
7eec1826cc9a9ed07e4a3b36cec0c3bcbfe2f441
jaredparmer/ThinkComplexity
/ch2.py
5,443
4.40625
4
""" in-text examples and exercises from ch 2 of Downey, Think Complexity. """ import networkx as nx import matplotlib.pyplot as plt # nx uses this to draw figures import numpy as np import random def all_pairs(nodes): """ generator function that yields all possible pairs from nodes """ for i, u in enumer...
bbaf785d7e82a1e06c75e5ad553e8ef6112f63c1
Neifn/ECourse
/python/longest.py
369
3.9375
4
#!/usr/bin/env python user_input = "lokori llo lard hardery labradorium" user_list = user_input.split() list_of_longs = [] for element in user_list: check_value = False for i in user_list: if len(element) >= len(i): check_value = True else: check_value = False if chec...
34e5721a9c7b707ac94a3e11d4e286ea6cffb2ce
Fayozxon/python-quests
/Birinchi qism/46.4-ifoda.py
214
3.578125
4
# a, b va c: a = int(input('a: ')) b = int(input('b: ')) c = int(input('c: ')) bool = a**2 - b**2 == c**2 # Tekshirish: if bool: print('Ko\'paytmasi: ', a*b*c) else: print('Yig\'idisi:', a+b+c)
7b6218f4ebc7735f56bdf76e5a447132b60bb7f0
klaethecoder/100Days
/Day2.py
1,530
4.21875
4
import math # Day 2 Project print("Welcome to the tip calculator") total_bill = float(input("What was the total bill?\t")) tip_percent = float(input("What percentage tip would you like to give 10, 12, or 15?\t"))/100 tip_amount = total_bill * tip_percent total_people = float(input("How many people to split the bill?\t...
f859c1bbb8bcfa967293a5a65a9eddbd2f6bd772
MuhammadEhtisham60/dev-code2
/task1.py
880
3.734375
4
""" def scnd_max(): list = [22,13,46,11,12,14,54] large=list[0] secondlargest=list[0] for x in range(1,len(list)): if list[x]>large: secondlargest=large large=list[x] elif list[x]>secondlargest: secondlargest=list[0] print(list) print(secondlargest) scnd_max() """ #prime numbber ...
2f2022cfd29ffa0d10be8fbccb58ca4edadf9475
MohamedAhmedShawky/Assignment
/MajorityElemnt.py
933
4.09375
4
import textwrap def majority(a): if len(a) == 0: return 0 if len(a) == 1: return a[0] half = len(a) // 2 left = majority(a[0:half]) right = majority(a[half:]) if left == right: return left if a.count(left) > half: r...
b21aa6541261bddfe217aa9aa516eceae7815111
olagjo/evolve
/evolve.py
8,248
4.125
4
''' Basic Evolutionary framework (primarily scaffolding) to be used for experimenting with simple problems and concepts ''' import random from typing import List, Optional, Tuple GENERATION_SIZE: int = 20 MUTATION_RATE: float = 0.07 class Genotype: """ Implements a basic genotype with a vector of genes as it...
881856cb53c4bca6a2d9c10671777c4ce055cbb5
holmesluck/dataM
/GroupClassify.py
602
3.734375
4
import pandas as pd data1 = pd.read_csv('./resource/test.csv') print(data1) # use groupby to combine multiple features in one new feature AMS = data1.groupby(['AreaID','Month','StoreID'],as_index=False) print("#######AMS########") print(AMS) print(data1) # combine AreaID and StoreID to AreaID and try to calculate t...
d5814639bd54ac7a47893d52c64754a762a92e09
harhoyz/Repo-Belajar-Class-2
/minggu4.py
4,238
3.765625
4
#=================== # CLASS (Object Oriented Proggraming / OOP) # Class = Cetakan # class hewan : # #class attribute : # spesies = 'kambing' # #instance attribute # def __init__(self, asal, bobot, usia) : # self.asal = asal # self.bobot = bobot # self.usia = usia # gaga = h...
f18b9bca3cefa6f9536c343ae126982c5ff3bd40
liliangely/programowanie-python-podstawy
/plikitekst.py
4,530
3.625
4
'''def wpisaniezawartosci(nazwapliku,tekst): pliktekstowy=open(nazwapliku, 'w') pliktekstowy.write(tekst) pliktekstowy.close() nazwapliku="test.txt" zawartosc='blah blah' wpisaniezawartosci(nazwapliku,zawartosc) def odczytzawartosci(nazwaplik): plik_tekstowy=open(nazwaplik,'r') print(...
d65b1b661bc7103fd09a1aa7398aafa68fb05edd
deepakyadav810/Leetcode-Solution
/1952_Three Divisors.py
409
3.515625
4
class Solution: def isThree(self, n: int) -> bool: count=0 i=1 while(i<=n): if(n%i==0) : count=count+1 i = i + 1 if(count==3): return True else: return False #uncomment to check with the testcases ...
6627f64de6d31a2f53adb570b181a6aae957f315
assuran54/UFABC-PI
/Caixa_Eletrônico.py
1,085
3.734375
4
#NÃO PRECISA DE IF saque = float(input()) #se valor for maior q C, dividir por C e pegar o inteiro em cédulas. Subtrair quantia e seguir os Cs, até zerar #deve ter jeitos mais eficientes, queria saber como #não precisa de int do saque//x while True: if(saque>=100): c100=saque//100 saque=saque-c100*10...
a1a8a9d637d1f434a427b09ca0642105d22e12c4
stak21/holbertonschool-higher_level_programming-1
/0x0A-python-inheritance/1-my_list.py
214
3.75
4
#!/usr/bin/python3 """This class inherits from list""" class MyList(list): """inherits list class Args: list: inheriting class list """ def print_sorted(self): print(sorted(self))
192e618779a21a0b91ad4b62a9e4fb2f77ce7282
ilkeryaman/learn_python
/introduction/ood/shape/Shape.py
1,390
3.953125
4
class Shape: char = "*" separator = "-" @staticmethod def draw_separator(): print(Shape.separator * 50) class Line: def __init__(self, length): self.length = length def draw(self): print(*self.length * "*") class Rectangle: def __init__...
e5fafbc0812bdc99947474d2dc079de9f7399b4d
NobuyukiInoue/LeetCode
/Problems/0700_0799/0735_Asteroid_Collision/Project_Python3/Asteroid_Collision.py
2,855
3.515625
4
# coding: utf-8 import collections import os import sys import time class Solution: # def asteroidCollision(self, asteroids: List[int]) -> List[int]: def asteroidCollision(self, asteroids): # 104ms stack = [] for asteroid in asteroids: if asteroid < 0: while a...
36e8c48cdeb112804d2ec02f1f58054ed4127c21
kabrick/jetbrains-hyperskill-coffee-machine
/app.py
3,314
4.15625
4
gl_money = 550 gl_water = 400 gl_milk = 540 gl_beans = 120 gl_disposable = 9 def how_many(): print() print("The coffee machine has:") print(gl_water, "of water") print(gl_milk, "of milk") print(gl_beans, "of coffee beans") print(gl_disposable, "of disposable cups") print("$" + str(gl_money...
e59b9351709c0fb683901babc094f70ee9f26adf
thaolinhnp/Python_Advanced
/Bai1_DEMO_OOP/vidu2.py
443
3.734375
4
class vector(): def __init__(self,a,b): self.__a = a self.b = b def __str__(self): return 'vector (%d,%d)' % (self.__a, self.b) def __add__(self,other): return vector(self.__a + other.__a,self.b + other.b) if __name__ == "__main__": vector1 = vector(1,3) print(vect...
25cca2a4d54819a2bbc93f3c6dda02b198f3504a
mukeshmuvva/M4DS
/M4DS_ANN.py
4,209
3.796875
4
#!/usr/bin/env python # coding: utf-8 # In[723]: import numpy as np import pandas as pd # In[733]: class Dense_Layer: #Layer initialization def __init__(self,inputsize,neurons): #Initilize weights and biases self.weights = 0.01 * np.random.randn(inputsize, neurons) self.biases = n...
9ce70e8d56c4f0da6ed60aaf29b3fc7151d67875
strengthen/LeetCode
/Python3/48.py
1,715
3.890625
4
__________________________________________________________________________________________________ sample 28 ms submission class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ l = len(matrix) for i ...
fb4b1a876d3430770d59e8ad6cf37cc7709ee7d7
lslaz1/gocodenow
/webserver-5-copy.py
3,341
3.65625
4
''' Phase Five: DB Support 1) Using "sqlite3 blog.db" - create a table called posts, which has an id, post_name, post_text - add a row to this table, with a post name and post text 2) add the line below - your file must be named blogmodel.py import blogmodel 3) Update blog.html template to have two te...
5ca726a81034ba4537b093a1e380f6c06951ce8c
VLinternship/jeu
/jeu.py
8,925
3.828125
4
import sys import random import salles def partie1(): premierchoix=(int(input ("choisis une porte 1 ou 2:"))) # Pas dedans if premierchoix not in [1,2]: print("Vous êtes tombés dans un trou, VOUS ETES MORT") sys.exit() if premierchoix == 1: print("Vous etes dans la salle des...
14f62cdf236c34cf417f510c2cd511199e0f3943
ilyabihun/homework
/8_operation.py
2,200
4.09375
4
def upper(): upper_line = input('Enter here: ') high_letter = "" for ch in upper_line: if 65 <= ord(ch) <= 90: x = ord(ch) - 32 y = chr(x) high_letter = high_letter + y return print(high_letter) def lower(): lower_line = input('Enter here: ') low_lette...
5f0e7daccefbb9a2bbd2c1a956881f6bc1c1a412
guilhermefsc/Curso-em-V-deo---Python
/Mundo 2/ex050 - soma dos pares.py
225
3.71875
4
soma = 0 cont = 0 for n in range(1,7): num = int(input('Digite o {} valor: '.format(n))) if num % 2 ==0: soma += num cont += 1 print('A soma dos {} números pares digitados é {}.'.format(cont,soma))
f7c11502980694aaf39a39a999dd0d8d294ec000
mertz1999/Pytorch-deep-learning-beginning
/02_Auto_grad.py
419
3.578125
4
import torch x = torch.randn(3, requires_grad=True) y = x+2 z = y.mean() z.backward() # --- dy/dx # --- Stop Grad 3 methods # x.requires_grad_(False) # y = x.detach() # with torch.no_grad(): # --- training weights = torch.randn(3, requires_grad=True) for epoch in range(3): model_output = ...
30e9d9520e492ecf469a29e0bf220e5bf0db1ff6
Prashant-mahajan/Python-Codes
/Hackerrank/Algorithms/serviceLane.py
455
3.5
4
# Problem: https://www.hackerrank.com/challenges/service-lane/problem #!/bin/python3 def serviceLane(cases, width): for i in range(len(cases)): a, b = cases[i][0], cases[i][1] select = width[a:b+1] print(min(select)) n, t = map(int, input().split()) width = list(map(int, input().rstrip()....
915613620e1d37e86806e74ebc180a78cbcb9366
dark4igi/atom-python-test
/coursera/Chapter_8.py
802
3.53125
4
##Lists x = ['123', ['1', 'dsa'], 123, True, 23.65] print (x) print (type(x)) print (len(x)) print(dir(x)) print () for y in x: print (y) print (type(y)) try: print (len(y)) except: print ('variable without len') print() # list mutable print () z = [1, 2, 3, 4, 5] print (z) z[2] = 9...
e584adb0af3505a7684b8340b36571ceee9ef343
Ajay2521/Python
/ADVANCE/Files/readline( ).py
435
4.34375
4
# In this lets see about "File Handling in python." # Reading from the file by readline( ) : # readline( ) = Used to read the file line by line. # Here is the program for "readline( )." # Opening file in read mode. FileObj = open( "File.txt" , "r" ) # Reading the data from the file by line by line us...
1641a2a0ac1351f783e23869675aac6eab75253c
parthnvaswani/Hacktoberfest-2020-FizzBuzz
/Python/fizzbuzz_dufftt.py
257
3.859375
4
# Trying FizzBuzz. # Author @dufftt def fizzBuzz(n): for number in range(n): if number % 3 == 0: print("FizzBuzz" if number % 5 == 0 else "Fizz") continue print("Buzz" if number % 5 == 0 else number) fizzBuzz(101)
2779cdb8814dc45593dd6bc09972c2a694ed0914
whison/PythonCode
/看漫画学Python/ch11/ch11_4.py
558
3.53125
4
# _*_ coding utf-8 _*_ """ @author: mohuisheng @software: PyCharm @file: ch11_4.py @time: 2021/1/30 11:50 @desc: """ import re p = r'\d+' text = "AB12CD34EF" repace_text = re.sub(p, ' ', text) # sub函数省略参数count时,表示不限制替换数量 print(repace_text) p = r'\d+' text = "AB12CD34EF" repace_text = re.sub(p, ' ', text, count=1) #...
65aa3f377a4b5b817b7445175f2e3ae9db89b037
Jimmycheong/Caeser_Keypair
/public_key.py
1,271
3.703125
4
import os def coder(): file_name = raw_input("Enter a file name : ") shifters = raw_input("Enter keyphrase : ") print shifters[-1:] shifter = ord(shifters[-1:]) file_content = open(file_name, 'r') file_content_list = file_content.readlines() new_list = [] for sentence in file_...
4cd46725de2c42952f0f201ed13d27a009c93ec9
tinaba96/coding
/acode/abc268/b/main.py
211
3.578125
4
S = str(input()) T = str(input()) #print(len(S)) if len(S) > len(T) or S[0] != T[0]: print('No') exit() for i in range(len(S)): if S[i] != T[i]: print('No') exit() print('Yes')
ad5af222f2e11023b9987afd1d73314134e5326f
EduardoRosero/python
/curso python/funciones2.py
1,525
4.0625
4
# def suma(numero_uno, numero_dos, numero_tres): return numero_uno+numero_dos+numero_tres resultado = suma(10,20,30) print(resultado) def division(numero_uno, numero_dos): return numero_dos/numero_uno resultado = division(10,20) print(resultado) #Asignar los valores deliberadamente resultado = div...
0017faa0546ee35f8c9b45167cc6cdfc48a0ab43
MichaelAntropov/python-masterclass
/ProgramFlow/options.py
384
4.03125
4
print("Please choose your option: ") options = ["Exit", "Learn Python", "Learn Java", "Go swimming", "Have dinner", "Go to bad"] chosen_option = None while chosen_option != 1: for i in range(len(options)): print("{0}. {1}".format(i + 1, options[i])) chosen_option = int(input()) if len(options) >...
eba3b6bf157056e46d4b43607375015874e893ec
OrHaker/ciphers-with-python
/ciphers.py
10,026
4.21875
4
import string import math import os.path import random # Practice python logic by writing ciphers EXCEPTION_MESSAGE = "An exception occurred " def brute_force_attack(string): """Enter string to use Brute-Force Attack """ try: for key in range(1, 26): string_to_return = "" for l i...
5a4d2b476b7a75aba614ab7412a48c3269ee84ce
aparnalikhitkar/Python
/simple_code/input.py
191
4
4
x = float(input ("Enter 1st number : ")) y = float(input("Enter 2nd number : ")) z = float(input("Enter 3rd nuber : ")) print("Max number is : " ,max(x,y,z)) input("press any key to exit ")
6a0c3f6cf24a120acb6c3faf98269ec958013005
EduardoSantos7/Algorithms4fun
/AlgoExpert/Smallest Difference/solution.py
595
3.875
4
def smallestDifference(arrayOne, arrayTwo): arrayOne.sort() arrayTwo.sort() p1 = 0 p2 = 0 smallest = float('inf') smallest_pair = [] while p1 < len(arrayOne) and p2 < len(arrayTwo): num1, num2 = arrayOne[p1], arrayTwo[p2] if num1 < num2: current = num2 - num1 ...
9654b2cafc1921f4adceb9d3f551de63fa47517a
Bernardo-MR/Mision_02
/ExtraGalletasBernardo.py
317
3.765625
4
# Autor: Bernardo Mondragon Ramirez, A01022325 # Descripcion: calcular cantidad de ingredientes # # Escribe tu programa después de esta línea g = int(input("Escribe cantidad de Galletas: ")) a = (g*1.5)/48 m = g/48 h = (g*2.75)/48 print ((a), "tazas de azucar") print ((m), "tazas de mantequilla") print ((h), "taza...
c845cd2ba5c4eca802e8a46830f49aaf89904851
zitkat/ukoly_py_zs2018
/03_cykly/roz_prv.py
373
3.765625
4
#!/usr/bin/env python """ Spočte rozklad na prvočísla """ c = int(input("Zadejte číslo> ")) print(c, '= ', end="") prvocislo = 2 while c > 1: if c % prvocislo == 0: print(prvocislo, end="") c = c / prvocislo if c != 1: print('*', end="") elif prvocislo == 2: prvocisl...
19669fa3f5182bcb05bc6dfaa74f26e6bc072231
DawnBee/01-Learning-Python-PY-Basics
/PY Practice problems/List Ends.py
636
4.34375
4
# LIST ENDS ''' Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. ''' a = [5, 10, 15, 20, 25] b = [12,34,53,73,85,2,44,7,3] def list_ends(giv_list): new_...
116a172a92b8b6602799accd14cf065ee79b8b59
cloew/Nytram
/src/python/nytram/input/input_code.py
975
3.640625
4
from .input_event import InputEvent class InputCode: """ Represents an InputCode """ def __init__(self, name, code): """ Initialize with the code """ self.name = name self.code = code def getEvent(self, pressed): """ Return the proper event """ ...
47b21bef98e99c48015ce9ec708d9a018f98b3b2
waspyfaeleith/shopping_basket_python
/basket_spec.py
1,124
3.546875
4
import unittest from basket import Basket from item import Item class TestBasket(unittest.TestCase): def setUp(self): self.basket = Basket() self.beans = Item("Beans", 0.22) self.milk = Item("Milk", 0.60) def test_basket_starts_empty(self): self.assertEqual(0, self.basket.numbe...
0b8d8994b82bcd33efa7ae89e426d1f7eb7ee36a
SioKCronin/sio_dojo
/statistics/poisson_distribution/poisson_distribution_two.py
294
3.59375
4
# Poisson Distribution import math x = 0.88 y = 1.55 A = 160 + 40 * (x + x**2) B = 128 + 40 * (y + y**2) print round(A, 3) print round(B, 3) ''' def poisson_distribution(l, k): return (l**k * 1/e**l) / math.factorial(k) result = poisson_distribution(l, k) print round(result, 3) '''
cb04fa67f81c5b66c8617ae64328c88458ed2032
RachelYang02/SD16FinalProject
/audio.py
1,207
3.515625
4
import alsaaudio import audioop import time import pygame class Audio(object): """Collects audio data and returns volume continuously""" def __init__(self,rate = 16000, periodSize = 160): # rate is the sample rate. default 16kHz. Period size. idk what that is... self.rate, self.periodSize = rate, periodSize ...
db6533da098c4aeb4db8697dec7c4be7aba48956
aclogreco/InventGamesWP
/ch04/guess.py
1,060
3.890625
4
# This is a guess the number game import random import math guessesTaken = 0 rangeHighValue = 100 rangeLowValue = 1 numGuesses = math.ceil(math.log((rangeHighValue + 1), 2)) print("Hello! What is you name?") userName = input() number = random.randint(rangeLowValue, rangeHighValue) print("Well, " + userName + ", I am...
df920b14058c7ec771fdb091b277261fc1829023
tennyp/tenovate
/import.py
338
3.890625
4
''' Here we are caclculatin mathematical and scientific values by importing math function ''' import math #importing math function print ("Sin value of 30 is: ",math.sin(30)) print ("power of 2 to 3 is:",math.pow(2,3)) #power of a,b is a raise to b print ("Square root of 16 is:",math.sqrt(16)) print ("cos of 30 i...
df0f9a9326d0d54afc7c3687842a5f3742d327d8
jo1jun/Machine-Learning-Python
/ex7/plotDataPoints.py
697
3.703125
4
import matplotlib.pyplot as plt def plotDataPoints(X, idx, K): #PLOTDATAPOINTS plots data points in X, coloring them so that those with the same #index assignments in idx have the same color # PLOTDATAPOINTS(X, idx, K) plots data points in X, coloring them so that those # with the same index assig...
b95facbba1d9662fc5477e2248a2f94e584375ad
joselmocabral/python-challenges
/Other Scripts/findOddNumber.py
277
3.671875
4
def iq_test(numbers): #Find the odd or even number different from the others numbersArray = [int(x) for x in numbers.split(" ")] filteredArray = [x%2 for x in numbersArray] return filteredArray.index(1)+1 if sum(filteredArray) == 1 else filteredArray.index(0)+1
9d5953ac6bc623a2dec03696fa44cafc10b6f13d
shotvibe/shotvibe-web
/photos_api/__init__.py
1,302
3.859375
4
import phonenumbers COUNTRY_CODE_IL = 972 def is_phone_number_mobile(number): """Returns True if given phone number is mobile""" country_checkers = { COUNTRY_CODE_IL: is_phone_number_mobile_IL } checker = country_checkers.get(number.country_code, None) if checker: ret...
4070c72b26dedb51c1fad53b22563fd95a9e86e4
derekdyer0309/interview_question_solutions
/Array Sequences/missing_element.py
1,178
4.1875
4
""" Problem Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. Here is an example input, the first array is shuffled and the number 5 is removed to co...
fca2882dfe4bd9612af2b415844c1eeab314b321
justin080837/0808
/1028.py
256
3.6875
4
''' def hello (): print('a') hello() ''' n='xS' if(type(n)==int): print('整數') elif(type(n)==float): print('浮點數') else: print('都不是') var=[1,2,3,4,5] print(var[1:-1:2]) #[起點,終點,跳步] a = '131545498' print(len(a))
0d58127b2504c4bee8d8ae50dad5c7f20969aeb9
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4161/codes/1675_1951.py
342
3.859375
4
x0 = float(input("x de p0: ")) y0 = float(input("y de p0: ")) x1 = float(input("x de p1: ")) y1 = float(input("y de p1: ")) x2 = float(input("x de p2: ")) y2 = float(input("y de p2: ")) c = (x1-x0)*(y2-y0) - (x2 - x0)*(y1 - y0) if (c<0): print("A direita da reta") elif (c>0): print("A esquerda da reta") elif c==0: p...
f4bc0e735662b9d431c244f0fdeede7d3a1b034b
alanc10n/snippets
/python/decorators.py
407
3.90625
4
""" A snippet to remind me how decorators work in python """ def instrument(f): """ This is the definition for the decorator """ def wrapper(): print "Before {}".format(f.__name__) f() print "After {}".format(f.__name__) return wrapper @instrument def some_func(): print "This...
550ab65542ff613eda9bcde8001ac21830511e24
isaac-rivas/Programa
/ejercici.py
228
4.03125
4
import math num = int(input('Digite un numero: ')) while num <0 : print ('Eroor -> deberia ser numero positivo') num = int(input('Digite un numero: ')) print (f'\nSu raiz cuadrada es: ({math.sqrt(num):.2f}')
841231354c97992f1d8fbbc862d6a59c1dc7e136
kitann/python_practice
/duplicate.py
506
3.8125
4
numbers = [3, 6, 2, 4, 3, 6, 8, 9] duplicate = None for i in range(len(numbers)): # n^2 operation for j in range(i+1, len(numbers)): if numbers[i] == numbers[j]: duplicate = numbers[i] break for i in range(len(numbers)): # n operation if numbers[i]...
4c734edc8443f54d2929cd0e740628704382fd2f
MidhunJithu/project
/wargamelogic.py
8,077
4.125
4
''' GAME OF WARS WITH CARD ''' # generating value for rank of cards #value = {'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9, 'ten':10, 'jack':11, 'queen':12, 'king':13 ,'ace':14} #suit = ['hearts','diamonds','clubs','spades'] from colorama import init init() from colorama i...
b93792c6021abdeaacf2ada110c4852a53228810
GowravTata/Basic-Python-Programming
/OOPS/inheritance_super_practice.py
5,823
4.1875
4
class Clothing: def __init__(self,name,cloth): self.name=name self.cloth=cloth print(self.cloth,self.name) # To print the values given class Men(Clothing): def __init__(self,cost,duration): self.cost=cost self.duration=duration def display(self): super().__in...
a7099cd6f80a1870dcb2ac01c949ff0cc5685e2d
aman1228/LeetCode
/Algorithms/count-number-of-homogenous-substrings.py
1,270
3.875
4
1759. Count Number of Homogenous Substrings https://leetcode.com/problems/count-number-of-homogenous-substrings/ Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A s...
3144a61529e3c923652c4a00bb6561f3db6e8c2e
milenmihaylov/SoftUni
/ProgrammingBasics/04.ForLoop/01.numbers_ending_in_7.py
323
3.890625
4
# something """ най-добрия вариант: for number in range(1001): if number % 10 == 7: print(number) """ """ for number in range(1001): text = str(number) if text[-1] == '7': # i = int(text) print(text) # print(i) """ for number in range(7, 1001, 10): print(number)
07ec2adfddfef69b785986edd41fc6818d4d8a95
beenzino/shingu
/0922_for.py
403
3.96875
4
for looper in [1,2,3,4,5]: print ("Hello") for looper in [1,2,3,4,5]: print (looper) for i in ["k","o","r","e","a"]: print(i) for i in ["ha","jae","ho"]: print(i) for i in [1,2,3,4,5,6,7,8,9,10]: i = int(i+1) print(i) for i in range(1,101): print(i) for i in "abcdefg": prin...
f5f9fc8cb32fd9c8257e45ccb8b092d06db72b71
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/sbysiz002/util.py
1,885
3.84375
4
height = 4 def create_grid(grid): """create a 4x4 grid""" for s in range(height): grid.append([0]*height) def print_grid(grid): """print out a 4x4 grid in 5-width columns within a box""" print('+--------------------+') for row in range(height): ...
0c634d08520e939d262c6dabd4b0874c099da95b
wahidul/210ct-cw
/week4q1.py
560
3.96875
4
def binarySearch(alist, lower,upper): if len(alist) == 0: return False else: midpoint = len(alist)//2 print(alist[midpoint]) if alist[midpoint]>lower and alist[midpoint]< upper: return True elif alist[midpoint] > upper: return binarySearch(alist[:midpoint...
ea41ee34cbff1cd724c9721eedbd2d736003d363
yunjin-cloud/2020-winter
/OOP_Variable/set&get.py
497
3.875
4
class C: #괄호 열고 (object) 해줄 수 O def __init__(self, v): self.value = v def show(self): print(self.value) def getValue(self): return self.value def setValue(self, v): self.value = v # c1 = C(10) # print(c1.value) # c1.value = 20 #instance value에 접근해서 쓰기 # pr...
9ea8218f6fb7ff7c832158d94de5afb29da74544
codingSIM/Python2FA
/auth.py
1,154
3.828125
4
import tools import sqlite3 import string saltChars = string.ascii_letters + string.digits codeGen = string.ascii_uppercase connObj = sqlite3.connect('login.db') c = connObj.cursor() # ------------CHECKING IF TABLE EXISTS / Creating table # get the count of tables with the name c.execute(''' SELECT count(name) FROM...
699ed78694f5ad3da4ab63135e65666b74bffb7e
MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo
/ExerciciosPython/Ex081_Extraindo_dados_de_uma_Lista.py
831
4.09375
4
""" Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e está ou não na lista. """ li...
31f22b215660d223f4a5123bc846bb6d673aaf6e
RomuloMileris/UCD_Professional_Certificate_in_Data_Analytics
/Week 8 - Introduction to Data Visualization with Seaborn/1-Making a scatter plot with lists.py
734
3.84375
4
# Import Matplotlib and Seaborn import matplotlib.pyplot as plt import seaborn as sns # Import Matplotlib and Seaborn import matplotlib.pyplot as plt import seaborn as sns # Create scatter plot with GDP on the x-axis and number of phones on the y-axis sns.scatterplot(x=gdp, y=phones) # Import Matplotlib and Seaborn...
7d27b7a52d5eb817cc001aff305ea2fbcbe8dfb2
razn308/Tkinter-Basic
/tkinter_labels_02.py
878
3.640625
4
import tkinter from tkinter import BOTH # Main Window root = tkinter.Tk() root.title("Window") # Adding icon root.iconbitmap("images\icon.ico") # Size of Window root.geometry("400x300") root.resizable(0,0) # Adding Background color Blue root.config(bg='blue') # Create widgets label1 = tkinter.Label(root, text='This ...
6a826e992f7816d85c0475096a4a6727d9647268
YumikoMiyauchi/PyQ
/bebinner/functioin/create_new_func/judge.py
238
4.3125
4
# 関数check_even_oddを定義します def check_even_odd(num): if num%2 == 0: print(num, 'is even number!') else: print(num, 'is odd number!') # 実行 check_even_odd(14) check_even_odd(25) check_even_odd(33)
a0614f591873bcdd2ca79f772842a513d4ea7f9b
LadyM2019/Python-Fundamentals-Softuni
/05. Dictionaries - Exercises/01. Key-Key Value-Value.py
631
3.90625
4
def Match(key,value,values): for val in values: if val.__contains__(value): dic[key].append(val) targetKey = input() targetValue = input() count = int(input()) dic = dict() for i in range(count): parts = input().split(" => ") key = parts[0] values = parts[1]...
f3bbb92d2f4c4837cd1cdae7d27443193713c793
KKosukeee/CodingQuestions
/LeetCode/55_jump_game.py
2,328
3.5625
4
""" Solution for 55. Jump Game https://leetcode.com/problems/jump-game/ """ class Solution: """ Runtime: 44 ms, faster than 91.67% of Python3 online submissions for Jump Game. Memory Usage: 14.5 MB, less than 5.28% of Python3 online submissions for Jump Game. """ # Time: O(n^2), Space: O(n) de...
9e5bdce76ba47ce6a8b456b3bf22857d3b4b5f61
mzzhmh/mathQ
/bk/mathQ.py
2,006
3.578125
4
import time from monster import * from player import * import re print("===========================================================") print("!!!!!!!!!!!!!!MATH CHANLLENGE for JAMES MIAO!!!!!!!!!!!!!!!") print("===========================================================") chs = 0 print("THERE ARE FOUR MONS...
971643b2eadae0602c175307cb585cbd57f3ce92
Botany-Downs-Secondary-College/todo_list-brianhuang77777777777777777777777777777
/todolist.py
791
4.0625
4
modes = ["Add a task", "View List", "Exit"] tasks = [] def mode_select(): print("\nChoose a mode by entering the number:") for i in range(3): print("%s : %s" % (i + 1, modes[i])) select = input("") if select == "1": add_tasks() elif select == "2": print("\nHere ...
17fd3c738b13b6e728837dfa470a88c25dd54863
HankerZheng/LeetCode-Problems
/python/264_Ugly_Number_II.py
1,311
3.875
4
# Write a program to find the n-th ugly number. # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 # ugly numbers. # Note that 1 is typically treated as an ugly number. # 1 2 3 4 5 # 6 # 8 9 10 12 15 # 16 18 20 24...
310e743bec51f078e640a469ea6bb3abc8ebfe90
AARON42695/sentiment_analysis_on_financial_news
/data_extraction/src/scrape_articles_bloomberg.py
5,906
3.625
4
""" # Code that is used to scrape articles from bnn bloomberg archive # This script will allow users to scrape 100 previous articles from the bnn bloomberg website for each searching query from the date when the code is executed """ import requests from bs4 import BeautifulSoup import os import json from datetime imp...
f25e0651130474b9c9214f97bb52c19127ec4159
Oowalkman23/Python-3.8
/Matplotlib_Pyramid.py
2,121
3.671875
4
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def getTop(top,sides,height,p1,delta_h): # Recursive process for defining height from outer layer to the core. if sides - p1 == 1: top[sides-1,p1] = height return top else: ...
1d7d2bff29351ec57c8e84bb95122602f8d5ca90
oldboy123/oldboy_practice
/day01/Login.py
2,150
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import getpass f = open('db', 'rU') users_info = f.read() temp_users_infos = users_info.split('\n') i = 0 users_info_list = [] while i < len(temp_users_infos): user_value = temp_users_infos[i] if len(temp_users_infos[i].strip()) > 0: users_info_list.appen...
27b8b69fc697feb5b795c39581bb3302f696a7d2
xavios/aoc2015
/01-1.py
733
3.78125
4
import os def santa(instr): level = 0 for step in instr: if step == "(": level = level + 1 elif step == ")": level = level - 1 return level assert santa("(())") == 0 assert santa("()()") == 0 assert santa("(((") == 3 assert santa(")())())") == -3 # second part ...
66b9adb2e1a5605687228044554a5463678d485d
mic0ud/Leetcode-py3
/src/448.find-all-numbers-disappeared-in-an-array.py
1,701
3.609375
4
# # @lc app=leetcode id=448 lang=python3 # # [448] Find All Numbers Disappeared in an Array # # https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/ # # algorithms # Easy (54.54%) # Likes: 2157 # Dislikes: 199 # Total Accepted: 201.8K # Total Submissions: 367.7K # Testcase Example: ...
4f140b2b724ce1cda779053bf26674b976c8fec8
nilkuzmenko/python-fancy-scripts
/word-weight.py
506
3.765625
4
#Вес слов. Тяжесть буквы растет с приближением к концу алфавита. ext = input("Введите свой русский текст: ").lower() abc = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" word = [] for i in text: if i not in """ '"[]\;.,!@#:$%^&*()_+-=1234567890""": word.append(abc.index(i) + 1) else: if word != []: ...
49b7ec76c85c3b1e85d26aa9991f397059f0b014
zxcas319/My_Allproject
/algorithm_level4_py/level4-1.py
1,096
3.515625
4
""" 최고의 집합 Level 4 자연수 N개로 이루어진 집합 중에, 각 원소의 합이 S가 되는 수의 집합은 여러 가지가 존재합니다. 최고의 집합은, 위의 조건을 만족하는 집합 중 각 원소의 곱이 최대가 되는 집합을 의미합니다. 집합 원소의 개수 n과 원소들의 합 s가 주어지면, 최고의 집합을 찾아 원소를 오름차순으로 반환해주는 bestSet 함수를 만들어 보세요. 만약 조건을 만족하는 집합이 없을 때는 배열 맨 앞에 –1을 담아 반환하면 됩니다. 예를 들어 n=3, s=13이면 [4,4,5]가 반환됩니다. (자바는 집합이 없는 경우 크기가 1인 배열에 -...
71efe7ed43809511b33303c40ef8f7bfb4e5fbc7
jordyngendron4/Integration-Project
/Main.py
6,183
3.8125
4
# Jordyn Gendron # Integration Project def calcBA(hits, num_at_bat): batting_avg = round(hits / num_at_bat, 3) return batting_avg def calcFP(chances, plays_made): field_per = round(plays_made / chances, 3) return field_per def calcOBP(h, bb, hbp, ab, sf): obp = (h + bb + hbp)/(ab + bb...
a92a4b135be8c2467c4fc3d10a622363a01cca5f
pelayo717/neurocomputacion
/practica3/Adapta_fichero_serie
2,820
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Generador de datos para entrenar el regresor de series temporales. # Neurocomputación - Practica 3 # Jorge Arellano y Pablo Marcos import argparse import numpy as np def preparar_datos(x, n, m): """Dada la serie temporal (x1, x2, x3, x4, ...) La prepara para s...
737d36c3884f553bffba7f24b3c516e3308a6157
adrixo/Codigos
/src/AlgebraLineal.py
9,954
3.6875
4
# -*- coding: utf-8 -*- #Biblioteca para el manejo de matrices import numpy as np import itertools import re # dadas unas ecuaciones parametricas podemos obtener los vectores de la matriz asociada sustituyendo las coordenadas con una base # input: parametricas (lista de listas): # la primera lista se corresp...
c9796b44069e33a27285c770c7e208ca7c7daeed
Dewald928/Alarm-System
/Test/States.py
2,488
3.640625
4
#!/usr/bin/env python from random import randint from time import clock ##=============================================== ## TRANSITIONS class Transition(object): """ Code executed when transitioning from one state to another """ def __init__(self, tostate): self.toState = tostate def Execute(...
429b251b7af3cedd276076e9e48bcac006d40533
AKlein920/python_toys
/eight_ball.py
665
3.5
4
import time import random responses = ['yes', 'no', 'maybe', 'definitely', 'absolutely'] in_progress_msg = 'Thinking...' timeout = 5 def activate_ball(): input('Ask a question: ') for second in range(0, timeout): print(in_progress_msg) time.sleep(1) if (second == timeout-1): ...
7d27317b9b3c64e3bf4592f98fa62874d8040903
AhhhHmmm/MITx-6.00.1x
/Week 3/Hangman/hangman.py
1,455
4.125
4
import string def playGame(): word = 'Xylophone' word = word.lower() skeleton = '_ '*len(word) playing = True usedLetters = [] remGuesses = 8 print('\n') print('*'*30) print('You have {} guesses to start.'.format(remGuesses)) print('The mystery word has {} letters.'.format(len(word))) print(skeleton) whi...
6e4bb3ebc6e34bf34a610ff3fa90399e5c4c8270
gopinathPersonal/python-exercises
/samplefun.py
379
3.65625
4
def add(a, b): return (a + b) def subt(a, b): return (a - b) def multi(a, b): return (a * b) def divs(a, b): return (a / b) def mod(a, b): return (a % b) print("Addition", add(5, 2)) print("Subtraction", subt(5, 2)) print("Mutliplication", multi(5, 2)) print("Division", divs(5, 2)) print("type of...
7b868e6a0d4636d3c34415c4cee5b826af1b67a1
mollyheller/Project1
/project1-206.py
5,535
3.6875
4
#Worked with Hannah Kriftcher and Sam Sherman to discuss ideas on how to attempt each function import csv import matplotlib.pyplot as plt import os import filecmp from dateutil.relativedelta import * from datetime import date def getData(file): data= open(file, 'r') list_of_dict= [] for line in data.readlines()[1:]...
c90092f6178f22d0fbd976f980deb56e7a17e741
alexandraback/datacollection
/solutions_5738606668808192_0/Python/pedrosorio/C.py
1,175
3.5625
4
def get_primes(n): is_prime = [True for i in range(n+1)] i = 2 while i * i <= n: for j in range(2*i, n+1, i): is_prime[j] = False i += 1 return [i for i in range(2, n+1) if is_prime[i]] BASES = range(2,11) MAX_PRIME = 100 # no need to identify all composite numbers PRIMES = get_primes(MAX_PRIME) def base(a...
74d8423a7dc2f731e452e3905b2415ca18fcbb97
xkuang/my_code_files
/python_code_plotting.py
2,408
4.03125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 25 14:42:38 2017 PLOTTING HELP From http://www.ast.uct.ac.za/~sarblyth/pythonGuide/PythonPlottingBeginnersGuide.pdf """ # Standard plotting packages import numpy as np import pylab as pl # more advanced plotting import matplotlib.pyplot as plt # Example data x = [...
76c5ba586fd72f4f878ebf02a58327dba9ff2b0e
lemonnader/LeetCode-Solution-Well-Formed
/binary-search/Python/0033-search-in-rotated-sorted-array(1、中间元素和左边界比较,选左中位数).py
1,208
3.796875
4
from typing import List class Solution: # 中间元素和左边界比较 def search(self, nums: List[int], target: int) -> int: size = len(nums) if size == 0: return -1 left = 0 right = size - 1 while left < right: mid = (left + right) >> 1 if nums[le...
36c73269a9b70cdac3c8d9e655301cf4dd661b96
XiaoFei-97/the-way-to-python
/python-progress/05-decoration-canshu.py
501
3.796875
4
#----------有参数装饰器------------ def w1(func): print("-----正在装饰-----") #如果a,b没有定义,那么会导致19行的调用失败 def inner(a,b): print("---正在验证权限---") if True: func(a,b) #如果没有把a,b当作实参进行传递,那么会导致调用15行的函数失败 else: print("没有权限") return inner @w1 #就等于已经把f1函数体指向了w1的闭包,等价于f1 = w1(f1) def f1(a,b): print("----f1-a=%d,b=%d"%(a,b)...
d9ca366a75b06bb5e380d337467eddea8a9c4d35
Talon1989/MIT-6.00.2x-python-data-science
/src/UNIT-1/lecture-3/Node.py
345
3.5
4
class Node: counter = 0 def __init__(self, name): assert isinstance(name, str) self.name = name Node.counter += 1 def getName(self): return self.name def setName(self, name): self.name = name def __str__(self): return self.name def count(self): ...
a4e3d53c7b35044e23334067ebcc6fd6c08ac22b
gschen/sctu-ds-2020
/1906101113-刘禹韬/day0407/text.py
3,479
3.921875
4
class Node(object): def __init__ (self.data): self data = data self.next = None class stack(object): def __ init__(self): self.node = Node(None) self.head = self.node self.size = 0 def is_ empty(self): return self.size == 0 def get_ size(self): re...
81d0a03e21d3fdd2f62d31f55b9fdc02b301d926
lienne/PythonLearning
/05_IfThenElse.py
935
4.28125
4
# Collect string / test length testinput = input("Please enter a test string: ") if len(testinput) < 6: print("Your string is too short.") print("Please enter a string with at least six characters.") # Prompt user to enter number / test if even or odd testinput2 = input("Please enter an integer: ") number =...
eb7ad22ea81c7294d8f68eea13777b11c02ace14
lilitom/Leetcode-problems
/Array/Leetcode_66_easy_数字加1.py
1,453
3.546875
4
''' Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. You may assume the integer do not contain any leading zero, except the number 0 itself. The digits are stored such that the most significant digit is at the head of the list. [1,9,9] 1Ϊ [2,0,0] ''' #South China Un...
b1b8f14112acdb688088e9a2e6b6fdda3523c87a
xchrislordx/pchqtcRetoS3
/reto9.py
334
4.03125
4
#Crea una lista con números e indica el numero con mayor valor y el que menor tenga bandera = True valor = [] while bandera == True: numero = int(input("Ingrese numero: ")) valor.append(numero) if numero == 0: bandera = False print("El valor maximo es el ",max(valor)) print("El valor minimo es el ...
3b2420fe71e7a95509d1508fac57e0d4d3c3982b
huerfanos/pitonbasic
/if toplama işlemi.py
289
3.65625
4
s1=int(input("toplamak istediğiniz 1.sayı")) s2=int(input("toplamak istediğiniz 2.sayı")) if s1 + s2 : print(s1+s2) if kullanmadan yapmak isterseniz s1=int(input("toplamak istediğiniz 1.sayı")) s2=int(input("toplamak istediğiniz 2.sayı")) z=s1+s2 print(z)