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
c9bfc8b6f6be09f9ff5c6a6d69457ccd2dc63c75
navya391/algorithms
/fibonacci_last_digit.py
176
3.65625
4
n = int(input("")) num = [0, 1] if n <= 0: print(n) else: for i in range(2, n+1): num3 = num[i-1] + num[i-2] num.append(num3) print((num[-1] % 10))
5c0d3533038e8cc6ef176f4d745ce61a03e0c4cc
vrushali-broad/py3DProjection
/matrices.py
3,909
4.25
4
""" this is a module to perform matrix operations currently it performs matrix multiplication, using matrices in the form of lists within lists, so that the indeces of the lists correspond to the rows and columns of a matrix for example: myMtx = [ [ a, b ], [ c, d ] ] to access a is mtMtx[0][0], as it corresponds t...
94c6d0c3e3b41e61e93a07bff3efb13f19864891
StefanFischer/Deep-Learning-Framework
/Exercise 3/src_to_implement/Layers/ReLU.py
1,211
4.5
4
""" @description The Rectified Linear Unit is the standard activation function in Deep Learning nowadays. It has revolutionized Neural Networks because it reduces the effect of the "vanishing gradient" problem. @version python 3 @author Stefan Fischer Sebastian Doerrich """ import numpy as np class ReLU: def __...
85b4ffb15b4e79b447a87ae09a28376c5cb76c02
disp1air/Lutc_M
/Chapter_19/Recursion_1.py
155
3.75
4
def recursionSum(L): print(L) if not L: return 0 else: return L[0] + recursionSum(L[1:]) print(recursionSum([1, 2, 3, 4, 5]))
8f0dfe688424216d52d3d637fa85a78d97ad3036
tidepool-org/data-analytics-tools
/metrics/metrics.py
7,582
4
4
import numpy as np from typing import Tuple import pandas as pd def get_cv_of_glucose(bg_values, round_val=2): """ Calculate the average within a set of glucose values Arguments: values -- numpy array contains a list of bg values. round_val -- the number of digits to round the res...
752c7107c06f7b3b2d5371cb96049215fbb66bf0
silicium14/TDD-Fraction
/tdd_fractions.py
1,786
3.5625
4
from typing import Union import math class Fraction(object): def __init__(self, numerator: int, denominator: int): if denominator == 0: raise DenominatorIsZero() numerator, denominator = self._move_sign_on_numerator(numerator, denominator) numerator, denominator = self._simpli...
9ebb158dca2a416d3bc3a48075f592e61e137508
Erdem-Karaman/BUS232-Spring-2021-Homeworks
/BUS 232 TEST2/BUS 232 Midterm.py
1,550
3.953125
4
total_shares = 0 all_shares = list() index = 0 def holdShares(): global total_shares,all_shares share = int(input("Please enter the number of shares: ")) all_shares.append(share) while(share != 0): total_shares += share share = int(input("Please enter the number of shares: "...
a226e6487f4ff2de4746712608e9ce5090b22473
devashisht12/python-works
/datetime.py
180
4.0625
4
import datetime a = "Hello" c= 'Friends' print(f"Hello Dev today, you look handsome {a} {c}") today = datetime.datetime.today() print(f"today's date is {today:%B %d, %Y}")
04875691af6f47f5550aaaa39e243199a40f7711
trev155/euler
/problem_solutions/problem_029.py
337
3.515625
4
""" Problem 29 - Distinct Powers https://projecteuler.net/problem=29 """ import math def distinct_powers(): s = set() for a in range(2, 101): for b in range (2, 101): n = int(math.pow(a, b)) s.add(n) return len(s) if __name__ == "__main__": answer = distinct_powers() ...
122ff2187c6fcbbcfd525a2307f26814bf374d6e
trev155/euler
/problem_solutions/problem_026.py
691
3.6875
4
""" Problem 26 - Reciprocal Cycles https://projecteuler.net/problem=26 """ def reciprocal_cycles(): best_denominator = -1 best_denominator_length = -1 for i in range(2, 1000): val = 1.0 / i cycle = longest_cycle(str(val)[2:]) if cycle > best_denominator_length: best_den...
08387bd0b8b67074540510d61202e813c0d00849
trev155/euler
/problem_solutions/problem_007.py
1,476
3.5625
4
""" Problem 7 - 10001st Prime https://projecteuler.net/problem=7 """ class MarkedNumber: def __init__(self, val): self.val = val self.visited = False def sieve(high=2000000): """ Implementation of the Sieve of Eratosthenes algorithm. This is similar to my implementation of Problem 1...
4376ed471f0405a43c431670d56543294d43236f
aditirai3/Python-Financial-Election-Data
/PyPoll/main.py
2,421
3.578125
4
import os import csv election_csv = os.path.join("Resources", "election_data.csv") #define variables and lists vote_count = 0 candidate_list = [] counter_khan = 0 counter_correy = 0 counter_li = 0 counter_tooley = 0 #Read the csv file with open(election_csv) as csvfile: csvreader = csv.reader(csvfile, delimiter ...
fa654305ec92af405f27f98e7dae3f16e3bc94aa
nicoletorres1/CS2302_Lab2A_bubblesort
/MergeSortMethod.py
1,562
4.03125
4
def mergeSort(self): # temp = self.head if temp is None or temp.next is None: return temp linkedlist1, linkedlist2, divdeLists(temp) linkedlist1 = solution3(linkedlist1) linkedlist2 = solution3(linkedlist2) temp = mergeLists(linkedlist1, linkedlist2) return temp def divideLists(sel...
9ec2441103f11f01955fa0d2e78d422f5a48d3a6
piyushsk90/machine-learning-repo
/Part 2 - Regression/Polynomial Regression/PolynomialRegression.py
2,455
3.5
4
# -*- coding: utf-8 -*- #data Preprocessing #libraries import import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the dataset data_set = pd.read_csv('Position_Salaries.csv') x = data_set.iloc[:,1:2].values y = data_set.iloc[:,2].values #taking care of missing data """f...
4460227115e90388f6b97735aff31ee75e45dc5b
marymarine/sem5
/hometask2/task2.py
824
4.1875
4
"""Task 2: The most popular word""" def get_list_of_words(): """return list of input words""" list_of_words = [] while True: new_string = input() if not new_string: break list_of_words.extend(new_string.split()) return(list_of_words) #transform text to list of words...
1f04071e1f3971e5dd5be37389eae1a8ffabd79c
jason-leeee/adventofcode2020
/Day2/solver.py
1,174
3.515625
4
import os import sys import math import itertools CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) def solution(lines): total_valid = 0 for line in lines: seps = line.split(" ") lens = seps[0].split("-") min_len = int(lens[0]) max_len = int(lens[1]) char = se...
1dfbd5ab4c545d227c62e3d425513f436d47e784
Diffblue-benchmarks/Lucafon-DesignPatterns
/lucafontanili.designpatterns.python/src/behavioral/strategy/Strategy.py
1,271
3.90625
4
''' Created on Nov 27, 2016 @author: Admin ''' from abc import abstractmethod payment_methods = {'paypal': 0, 'credit_card':1} class PaymentMethod: @staticmethod @abstractmethod def pay(payment_account, price): pass class PayPalPaymentMethod(PaymentMethod): @staticmethod de...
63a2d274a1ce06d4c5dc6976633e1f161036934d
Programacion-Algoritmos-18-2/trabajo-opcional-1er-bim-CarlosCastillo10
/pregunta3/prestamo/modelo.py
4,136
3.953125
4
""" @CarlosCastillo10 """ class Garante(object): # Constructor def __init__(self, n, c, s): self.agregar_nombre(n) self.agregar_ciudad(c) self.agregar_sueldo(s) # Metodos de agregar. def agregar_nombre(self, n): self.nombres = n.upper(); d...
3999394508f595c9b901801f43fe6a861fdc7299
tencypriya/python-programming
/beginner level/integer.py
91
3.921875
4
n=input(int("enter the no:")) sum=0 while(n>0): sum1=sum1+n n=n-1 print("the sum is,sum1")
8b5543e620a2cf71832d992baa61759080ad0f93
tencypriya/python-programming
/beginner level/ams.py
153
4.125
4
sum=0 temp=num while temp>0: digit=temp%10 sum=sum+digit*3 temp if num==sum: print(num,is an amstrong number) else: print(num,is not an amstrong number)
52b892e9892dd2efe14db148a78ccf51d655176e
LolaEnBeta/Checkout-Kata
/V3/test_checkout_v3.py
1,236
3.53125
4
import unittest from Cart import Cart class TestCheckout(unittest.TestCase): def test_list_items(self): cart = Cart() items = cart.list_items() self.assertEqual(items, []) def test_list_total_items(self): cart = Cart() cart.add("A") cart.list_total_items() ...
cf7c54a87a30ec11a5d1893e3ca53bb0a15ff9cb
dianekaplan/rosalind
/rosalind_mortal_rabbits_fibd.py
3,551
4.3125
4
# -*- coding: utf-8 -*- # Diane Kaplan # Rosalind Problem: fibd (mortal fibonacci rabbits) # http://rosalind.info/problems/fibd/ # (starts with the fib problem, plus rabbits die after a certain number of months) # Rules: # The population begins in the first month with a pair of newborn rabbits. # Rabbits reach reprod...
d38b6f8261f2631f0495bd84160bb6cf1c65400b
julElliot/python
/04.05.2020.py
517
4.125
4
# Программа высчитывает Индекс Массы Тела по введённым параметрам: вес и рост. print('Введите Ваш вес в килограммах: ') weight = int(input()) print('Введите Ваш рост в сантиметрах: ') hight = int(input()) bmi = weight/(hight/100)**2 print('Ваш индекс массы тела:', bmi) STEPS = 40 scale = '10' + "=" * (round(bmi) - ...
76b801ec0c0781e388cc832085878286abd9bdf9
plainspooky/giovannireisnunes
/mais-decoradores-em-python/module/decorators.py
1,950
3.609375
4
""" Decoradores usados como exemplo. """ from typing import Callable def marker(func_obj) -> Callable: """ (decorador) Realça uma _string_ usando outras cores. """ def decorator(*args: str, **kvargs: int) -> str: """ Adiciona os códigos VT-100 necessários para mudar a cor de uma ...
d6a1da53fbadfe25069fefee5f96a4b3dc103f43
plainspooky/giovannireisnunes
/excecoes-em-python-parte-3/minha_excecao.py
392
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class MinhaExcecaoError(Exception): pass try: erro = False # lista de comandos que mudarão o estado de 'erro' --> erro = True # <-- lista de comandos que mudarão o estado de 'erro' if erro: raise MinhaExcecaoError("Ocorreu um erro!") ...
cb73f37d0bd0e297795fe4f9a5569b9d4ca6d62a
plainspooky/giovannireisnunes
/decoradores-em-python/funcao_como_argumento.py
634
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Exemplo de função sendo passada como argumento. """ from __future__ import print_function def minha_funcao(i, j): """ Recebe dois valores em `i` e `j` e retorna a soma entre eles. """ return i + j def outra_funcao(func, *args, **kwargs): """ Executa ...
59bac5327e27ff33133ee21ca1f86edaba91e9db
plainspooky/giovannireisnunes
/criando-imagens-em-python/outro_teste_pillow.py
709
3.625
4
#!/usr/bin/env python3 """ Teste do Pillow. """ from PIL import Image FILENAME = ("outro_teste_pillow.png", "PNG") # carrega o arquivo do primeiro exemplo pillow_obj = Image.open("teste_pillow.png") pixel_set = pillow_obj.load() # recupera as dimensões da imagem width = pillow_obj.width height = pillow_obj.height #...
5bdc7ff8120eb079b0d8a425d0344c696c5cd447
tamu0021/Muscle
/venv/BigThree.py
755
3.578125
4
class BigThree: def __init__(self, weight, bench_press, squat, dead_lift): self.weight = weight self.bench_press = bench_press self.squat = squat self.dead_lift = dead_lift def output_big_three_weight_ratio(self): print(f'bench_press / weight = {self.bench_press / self.w...
ada2fab713a61884211b9f9ebf5fa68d37c8ade1
coopwilliams/Intro-Python-I
/src/is_prime.py
785
4.21875
4
def is_prime(n): """Returns True if number is prime.""" if n is not abs(int(n)): return False #test n a positive number. if n < 2: #0 and 1 are not primes return False if n == 2: #2 is the only...
9e765687e18faaba6ae19f7ce66180d795b66a0f
saify2j/NeuralNetworkSPL
/matrixTranspose.py
262
3.96875
4
def transpose(a): res=[] for i in range (len(a[0])): temp=[] for j in range(len(a)): x=a[j][i] temp.append(x) res.append(temp) return res print(transpose([[1,2], [3,4], [5,6]] ))
e7fb3cdf35a59e68eaccdd7d05a2341665f1a6bf
darshanjani/dj-practice
/python-practice/Lists.py
401
3.671875
4
__author__ = 'Darshan' from math import pi print([str(round(pi, i)) for i in range(1, 6)]) list = [1,2,3] list2 = [x for x in range(3,5)] list.extend(list2) list.insert(3,7) print(list) print(list.count(3)) list.remove(3) #This is not an index, but first element it finds print(list) list.reverse() pr...
71650dd0baf15364bb269818a143017264e47514
darshanjani/dj-practice
/python-practice/RangeFunc.py
313
3.984375
4
__author__ = 'Darshan' for i in range(5): print(i, end=",") print() for i in range(5, 10): print(i, end=",") print() for i in range(0, 12, 3): print(i, end=",") print() a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) print(list(range(5)))
7211e625877ab6e9c6ad7a5f2cf3ea1c401acfb9
U-Ar/PythonReversi
/reversi_gui.py
5,648
3.515625
4
import tkinter from board import * YOUR_COLORS = {"black":True, "white":False} top = tkinter.Tk() class GUIGameBoard(tkinter.Canvas): def __init__(self, master, your_color): self.grid_size = 50 en = self.grid_size * 9 z = self.grid_size * 0.36 self.master = master ...
91f21b18f0e47fdd79a75dc44a0e511bd07e4bc5
Khanguye/Election_Analysis
/Preliminary/NumberChain.py
201
3.828125
4
while True: num = int(input("How many numbers?")) for i in range(num): print(i) ans = input("Would you like continue? y (Countinue), n (Exit)") if (ans == "n"): break
523045fca287d87efa564b24f7bcf5bafaa9134f
Khanguye/Election_Analysis
/Preliminary/PrintFormat.py
827
4.03125
4
print("Arapahoe and Denver are not in the list of counties.") interest = 3000 print("Your interest for the year is $" + str(interest)) print("You","are","awesome") my_votes = 3000 total_votes = 5000 print(f"I received {my_votes / total_votes * 100}% of the total votes.") counties_dict = {"Arapahoe": 369237, "Denver...
1df3b7eddf31a94e58b225a2b83775cd5c0bae17
TangYunc/Python3Learn
/day03/objectInfo.py
1,307
3.921875
4
class Student: """docstring for Student""" # 限定此类创建的对象只能有name和age两个属性 __slots__ = ['name', 'age'] def __init__(self, n, a): super(Student, self).__init__() self.name = n self.age = a s1 = Student('肖打', 20) # s1.Age = 21 # print(s1.__dict__) # 类方法classmethod class A: """docstring for A""" v = 0 #类变量 ...
915cd033199bfe0a28a1602be374611ef3439778
TangYunc/Python3Learn
/day02/time.py
793
3.671875
4
import time # print(time.altZone) # def show_time(): # while True: # t = time.localtime() #绑定时间元组 # s = '\r %02d:%02d:%02d' % (t[3], t[4], t[5]) # # s = '\r %02d:%02d:%02d' % t[3:6] # print(s, end='') # time.sleep(1) # show_time() # # 输入生日。计算出生那天是周几。已经出生了多少天 y = int(input("输出年:")) m = int(input("输出月:...
36b62323bcec79e9690b95b77543581a22af6bd6
Oscar1305/Python
/Python/Calculadoras.py
478
4.125
4
""" Crea una calculadora que haga las siguientes operaciones con dos números: suma + resta - producto * división / módulo % """ #variables globales: Acceda a elas desde cualquier parte de mi programa num1 = 5 num2 = 6 num3 = 7 print ("suma:" + str(num1 + num2 + num3)) print ("suma:" + str(num2 + num1)) pr...
b77ece0e0a0e9dda4e8f92857b146cc79aa4eccf
Oscar1305/Python
/Python/Actividad 4.py
188
3.890625
4
""" 4. Escribir un algoritmo que lea un valor entero, lo doble, se multiplique por 25 y visualice el resultado-. """ num = int(input("Número: ")) num = (num *2) * 25 print(num)
7d5b202874f1e5a4de84ac189aaa64cabfdb93ec
deeplook/pyteen
/pyteen/snippets/algorithms/sieve_eratosthenes.py
717
4.0625
4
def sieve_of_eratosthenes(n): """Yield primes in [2..n] using the "Sieve of Eratosthenes". """ assert type(n) == int # Create a Boolean array "prime[0..n]" and initialize # all entries in it as true. A value in prime[i] will # finally be false if i is not a prime, else true. p, prime = 2, [T...
b91f5061c9d468ba5761d0568bab11eb128565cd
Rudecruels/RC-calculator
/calculator.py
13,494
3.75
4
from tkinter import * from tkinter import messagebox import math window=Tk() window.geometry('500x700') window.title("CALCULATOR") window.configure(bg='#a6a6a6') input=StringVar() operator='' #================================================functions============================================================== de...
6c9f686bdcd62561e4110c21357840e6717143f3
Heier2013/learn_python
/bmi.py
241
3.984375
4
height = 1.75 weight = 65 bmi = weight / (height * height) if bmi < 18.5: print( '过轻' ) elif bmi < 25: print( '正常' ) elif bmi < 28: print( '过重' ) elif bmi < 32: print( '肥胖' ) else: print( '严重肥胖' )
cc409606c6d6426cccce75c6c4bd4bc9ec9bc21a
hw5773/estimation
/draw_graph.py
1,821
3.90625
4
import matplotlib.pylab as plt import sys import numpy as np HOME_MENNO = 0 CAR_YESNO = 1 HOME_INCOME = 2 P_HOUSEHOLD = 3 P_MODEL = 4 P_ESTIMATION = 5 P_ANSWER = 6 A_HOUSEHOLD = 7 A_MODEL = 8 A_ESTIMATION = 9 A_ANSWER = 10 def usage(): print ("Draw graph") print ("python3 draw_graph.py <input file>") exit...
008ff4f140e55940b013bf2656be8cb4df2d5a80
elvish-visionary/mothership_decklists
/utils.py
295
3.6875
4
import pandas as pd def df_to_markdown(df): """ Converts dataframe to markdown format string """ s = "|{}|\n".format("|".join(df.columns)) s += "|{}|\n".format(":----".join(df.columns)) for idx, row in df.iterrows(): s += "|{}|\n".format("|".join(str(v) for v in row.values)) return s
7a079e6302ee497a6c0c83d2c08521ca39e2a623
34953126/pythonweb
/com/test/day4_迭代器_20190829.py
678
4.03125
4
import sys #引入sys模块 list=[1,2,3,4,5] it =iter(list) #创建迭代器对象 # print(next(it)) #输出跌代器的下一个元素 # print(next(it)) #全部输出 # while True: # try: # print(next(it)) # except StopIteration: # sys.exit() # -------------------------------------------------------------------------------------------------...
dd13b1252bacadd25d559c52e71d10de8b0ca101
34953126/pythonweb
/com/test/hello.py
325
3.953125
4
# 为什么使用Python # 自动化运维 # 数据分析师 # 游戏开发者 # 自动化测试 #变量与字符串 str="ybb" print(str) print(type(str)) #字符串相乘 words = 'word' * 3 print(words) #输入值 i = input("请输入值:") print(i) # 函数编程 def getNum(num ): return num print(getNum(9))
1d9af7e2d5228fe281458cf5f5452954cfcee2c1
JennyLynnFletcher/encryption_project
/machine_class.py
1,707
3.59375
4
import random import math def isPrime(n): return all(n % i for i in range(2,n)) def randprime(x,y): primes = [i for i in range(x,y) if isPrime(i) and i != 1] n = random.choice(primes) return n class Machine(): def __init__(self,name): self.name = name self.publi...
bc74eafcf75609798897275e90caad29202853af
zoelandia/dsp
/python/advanced_python_csv.py
215
3.5625
4
import csv faculty = csv.DictReader(open('faculty.csv'), delimiter=',') emails = list(line[' email'] for line in faculty) a = csv.writer(open('emails.csv', 'w')) for i in emails: print(i) a.writerow([i])
47c584f52893df25a884dc5deb53e33bb0421e02
morosanmihail/OCAPE
/DemoFiles/Basic/Prime/Prime_Sieve.py
390
3.703125
4
def prime(i, primes): for prime in primes: if not (i == prime or i % prime): return False primes.append(i) return i def find_primes(n): primes = list() i, p = 2, 0 while True: if prime(i, primes): p += 1 if i == n: return primes i += 1 f = open('input.txt', 'r') f2 = open('output.txt', 'w') n ...
2f009fe08b3eccc2e033f775bef556d6dcaf6902
Cetroipeo/Boureka
/AstarPlanner.py
1,729
3.9375
4
#!/usr/bin/env python # this file contains the planner for Dijsktra's algorithm, it is based on the general forward search algorithm #import packages and external files from DijkstraPlanner import * import math # self class implements the A* search algorithm class AStarPlanner(DijkstraPlanner): def __init__...
299d44332cd7d5248eebc7a5118e821d58550fd6
victoralex911/redes-telecom
/triangulacion.py
4,405
3.515625
4
import Tkinter, ImageTk, Image import numpy as np import math w, h = 800, 600 colors = ["red","green","blue"] iter = 0 # Clase Antena, proporciona las herramientas para pintar los puntos donde se localiza una antena. class Antena: # Se inicializa un objeto antena con su posición "x" y "y", el rango máximo d...
9da3f26a6cf08dd0d4ff9bed51803b357ef0b8b1
mahdibz97/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
259
3.859375
4
#!/usr/bin/python3 """Define class""" def number_of_lines(filename=""): """returns the number of lines of a text file""" with open(filename, mode='r', encoding='UTF8') as f: num = 0 for line in f: num += 1 return num
fd1f369f5d960a4655ec15673942ee956c4a99a0
taunoe/Test-pyhon-2
/pt1/1.4a.py
163
3.5625
4
ainepunktid = input("Sisestage ainepunktide arv:") nadalad = input("Sisestage nädalate arv:") ajakulu = (int(ainepunktid)*26)/int(nadalad) print(round(ajakulu))
d3d8b22baf8f04171e75715634cc30cfe5395333
sharky564/Codeforces
/CodeForces Problems 0001-0100/CodeForces Problem 0001B.py
1,072
3.578125
4
# Spreadsheets def alpha(n): result = '' dig = 1 while n > 27 ** (dig - 1) * 26: dig += 1 k = n while dig > 1: num = (k - 1) // (27 ** (dig - 2) * 26) char = chr(num + 64) result += char k -= num * 26 ** (dig - 1) dig -= 1 else: char = chr(...
3953da20dab7f7bccd39116513678a85cc559c02
sharky564/Codeforces
/CodeForces Problems 0101-0200/CodeForces Problem 0131A.py
380
3.640625
4
# cAPS lOCK a=input() b=list(a) if len(b)==1: if a==a.upper(): print(a.lower()) else: print(a.upper()) else: if a.lower()==a: print(a) elif a.upper()==a: print(a.lower()) else: if b[0].lower()==b[0]: c=a[1::] if c.upper()==c: print(b[0].upper()+c.lower()) else: ...
5723c79fb84dafaf5878125f68a17e296118a1e7
sharky564/Codeforces
/CodeForces Problems 1101-1200/CodeForces Problem 1154A.py
186
3.625
4
numbers = [int(i) for i in input().split()] big = max(numbers) output = [] for number in numbers: if number != big: output.append(str(big - number)) print(' '.join(output))
a617de77007ecf1e54fdad7742705a8fd3259b11
sharky564/Codeforces
/CodeForces Problems 1101-1200/CodeForces Problem 1145A.py
264
3.8125
4
def thanos_sort(array): n = len(array) if array == sorted(array): return n else: return max(thanos_sort(array[:n // 2]), thanos_sort(array[n // 2:])) n = int(input()) array = [int(i) for i in input().split()] print(thanos_sort(array))
fe690a2f1e7d30fe4b2f55a471e76a637b549957
sharky564/Codeforces
/CodeForces Problems 0401-0500/CodeForces Problem 0443A.py
145
3.65625
4
a=input() b=list(a) invalid=['{',',',' ','}'] valid=[] for i in b: if i not in invalid: valid.append(i) count=len(set(valid)) print(count)
574675363151477da8c7e59764d8e677cb201043
sharky564/Codeforces
/CodeForces Problems 1001-1100/CodeForces Problem 1013A.py
174
3.515625
4
# Piles With Stones n = int(input()) x = [int(i) for i in input().split()] y = [int(i) for i in input().split()] if sum(x) >= sum(y): print('Yes') else: print('No')
a2d2195a8b0e30afbc37896400e73dbf394e3df4
d1mk0u/codeacademy-python
/remove_duplicates.py
172
3.703125
4
def remove_duplicates(lst): new = [] for c in lst: if c not in new: new.append(c) return new print remove_duplicates([1, 1, 2, 3, 4, 4, 5])
03c9d189f18ef575ab7e62eace3be556cde55223
zingpython/kungFuShifu
/day_two/1b.py
1,166
4.09375
4
#Take user input word = input("Enter a sentence to be scrambled: ") shift = int( input("Enter how much to shift: ") ) #Create the empty string that will become our new message new_message = "" for letter in word: #If uppercase letter if ord(letter) >= 65 and ord(letter) <= 90: #Convert to number and shift shi...
2cd1ed48f5ae3a42ed397974fd56366d82cc733f
zingpython/kungFuShifu
/day_four/23.py
1,289
4.28125
4
#Convert an interger to a binary in the form of a string def intToBinary(number): #Create empty string to hold our new binary number binary_number = "" #While our number is greater than 0 Keep dividing by 2 and adding the remainder to binary_number while number > 0: #Divmod divindes the 1st number by the 2nd nu...
a37cee394a218707cb0ed3b273b2b37316d7aad1
zingpython/kungFuShifu
/day_four/7.py
1,651
4.28125
4
import math class SpaceShip: target = [] #2 values, X and then Y coordinate = [] #2 values X and then Y speed = float() name = "" def __init__(self, coordinate, target, speed, name): self.coordinate = coordinate self.target = target self.speed = speed self.name = name #To find the distence calculate t...
ff7553d909f1de5f201c5967b9b0a3a4ba62196f
annanymaus/babysteps
/fibrec.py
952
4.375
4
#!/usr/bin/env python3 #program to find the nth fibonacci number using recursion (and no for loops) import sys #function definition def fib(p): if (p == 0): return 0 elif (p == 1): return 1 else: #recursive equation c = fib(p-1) + fib(p-2) return c #take an input...
2930bb22509062c4785d646e2908693610b6be98
jian-xu/leetcode
/EASY/ImplementstrStr.py
392
3.640625
4
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if (needle == ""): return 0 needlelen = len(needle) for n in range(len(haystack) - needlelen + 1): if (haystack[n : (...
0a83a534febed208f8e7f3b543a6ae062ede58d2
jian-xu/leetcode
/MEIDUM/PalindromeNumber.py
947
3.6875
4
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False y = 0 tmp = x d = 1 while (x // 10 > 0): d += 1 x //= 10 x = tmp i = 0 while (i < d ...
18369d04e8c19d56be5f226271366e32ad6ee326
jian-xu/leetcode
/MEIDUM/LongestPalindromicSubstring.py
945
3.609375
4
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ #palindrome can be expanded from its center, and there are only 2n−1 such centers start = end = 0 for i in range(len(s)): len1 = self.extend_around_center(s, i, i) ...
b06c8138933df92a13388ac9e155defe7095cefc
jian-xu/leetcode
/EASY/ValidParentheses.py
1,222
3.8125
4
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if (s == '' or len(s) % 2 != 0 or s[0] == ')' or s[0] == ']' or s[0] == '}'): return False tmp = [] for i in range(len(s)): if (s[i] == '(' or s[i] == '[' or s[i] =...
6437c3cb1c8df22ab1c911f752ca91ed754c18ba
jian-xu/leetcode
/EASY/Pascal's_Triangle.py
586
3.53125
4
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] elif numRows == 1: return [[1]] elif numRows == 2: return [[1], [1, 1]] res = [[] for i in ra...
354d30e1c6baf40c9abafaea41382239d4369367
prabhatcodes/Python-Problems
/Leetcode/reverse-integer.py
825
3.9375
4
# https://leetcode.com/problems/reverse-integer/ # Given a 32-bit signed integer, reverse digits of an integer. # # Note: # Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function retur...
9d4ddaea82c5213d1825f5291299c09cc55505f2
prabhatcodes/Python-Problems
/Leetcode/3sum-closest.py
1,341
3.8125
4
# Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. # # # # Example 1: # # Input: nums = [-1,2,1,-4], target = 1 # Output: 2 # Explanation: The...
cbbd52a5f99ae5018930bbaa3adf865f6e54fefd
prabhatcodes/Python-Problems
/Placement-Tests/Interview-Prep-Astrea/DS.py
585
4.15625
4
# Linked List class Node: def __init__(self, data): self.data = data self.next = None # Null class LinkedList: def __init__(self): self.head = None if __name__=="__main__": llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) ...
2762945abefafb8b1bd35f556a8a313c174dad99
prabhatcodes/Python-Problems
/Data_Structures/Queues/ArrayQueue.py
1,182
4.125
4
class ArrayQueue: """FIFO queue implementation using a Python list as underlying storage""" DEFAULT_CAPACITY = 10 # moderate capacity for all new queues def __init__(self): """Create an empty queue""" self._data = [None]*ArrayQueue.DEFAULT_CAPACITY self._size = 0 self._...
1e8fd3f85fb00673da4c729bd1dd0f3b23af0a0f
prabhatcodes/Python-Problems
/Leetcode/Longest_Prefix.py
839
3.90625
4
# Write a function to find the longest common prefix string amongst an array of strings. # # If there is no common prefix, return an empty string "". # # # # Example 1: # # Input: strs = ["flower","flow","flight"] # Output: "fl" # Example 2: # # Input: strs = ["dog","racecar","car"] # Output: "" # Explanation: There is...
e728e09c628416d95415c14dcf537a649f94b501
prabhatcodes/Python-Problems
/Data_Structures/Stacks/reverse_file.py
514
3.984375
4
def reverse_file(filename): """Overwriting a given file line by line in reversed order""" S = ArrayStack() original = open(filename) for line in original: S.push(line.rsstrip('\n')) # we will re-insert newlines while writing original.close() # now we overwrite with contents in LI...
b27be7302ebf1d1a14cad3de72f9892536dacfa3
prabhatcodes/Python-Problems
/Leetcode/maximum-gap.py
871
4
4
# Given an unsorted array, find the maximum difference between the successive elements in its sorted form. # # Return 0 if the array contains less than 2 elements. # # Example 1: # # Input: [3,6,9,1] # Output: 3 # Explanation: The sorted form of the array is [1,3,6,9], either # (3,6) or (6,9) has the maxim...
6ff0fb35332210ab5918dedb40e781fc57ba3ed9
prabhatcodes/Python-Problems
/Leetcode/two-sum.py
1,154
3.65625
4
# Two Sum # Given an array of integers, return indices of two numbers # such that they add up to a specific target. # We can assume each input to have only one solution. # Initial Solution class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): f...
5b5f123eaa44558e5cbbd8a43643585cc750beb3
NatalyGes/SP
/3/L1.py
252
3.859375
4
print("Введите натуральное число N") N=int(input("N=")) b=0 a=[i for i in range(1,N+1) if 3*i>N] S=len(a) if S==0: print("Таких чисел нет") else: print("Min=",min(a)) K=3*min(a) print("3*min=",K)
dcc3c94b7cea0f9b45e18538b82cef46a8fc3e00
NatalyGes/SP
/3/L7.py
288
4.0625
4
import math y=0 for x in (1,3,0.2): y=y+(x**3+4*x**2+2) print("Сумма всех y на промежутке от 1 до 3 с шагом 0.2 =",y) def p1(): x = 1 while x <= 3: print (round(x,2), "\t", x**3+4*x**2+2) x += 0.2 print(" X Y ") p1()
dda5a62bbb8e59c5a4e40828ac385d1ec3ac7158
ExperienceNotes/Python_Leetcode
/Leet_Code/Move Zerose.py
117
3.65625
4
nums = [0,1,0,0,3,12,13] for i in nums: if i == 0: nums.remove(i) nums.append(i) print(nums)
052d51cd41e6cde1af453dbceeef6e834b2c227c
Coolman6564/python_learning
/renameDates.py
1,692
3.609375
4
#! python3 # renameDates.py - Rename file names with American MM-DD-YYY date format # to "European" DD-MM-YYY (where the hell is Europe??) import shutil import os import re # Create a regex that matches files with the American date format. datePattern = re.compile(r""" ^(.?) # All text befo...
34034ce290def466e6789a84ef0cbcaf0c78c335
gudnm/brainf_ck-interpreter
/execute2.py
1,310
3.578125
4
import sys class BF(object): def __init__(self, size=12): self.tape = [0]*size self.pointer = 0 def parse(self, code): stack = [[]] for command in code: if command == '[': stack.append([]) elif command == ']': loop = stack...
a526e1981666a8c01b2754a0c4f3677eae3f4220
tuheenahmmed/week04
/testing&debugging_exercise_7.py
365
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 25 07:39:10 2018 @author: tuheenahmmed """ def f(n): """ n: integer, n >= 0. """ if n == 0: return n else: return n * f(n-1) f(3) #solution def f(n): """ n: integer, n >= 0. """ if n == 0: return ...
d3499e31cd423b415ca0742f9adce1a2c868c6b0
vividyellow/oldboyeduPython14qi
/第14部分-复习/day148-基础回顾_01/代码/04 基础04.py
275
3.953125
4
""" list 列表[] 1. append() 追加 2. insert() 插入 3. extend() 迭代添加 4. list[index] = 数据 5. remove() 删除 6. pop() 删除 for循环 xx in list tuple 元组. 不可变的列表 """
8d69c11c70e5e73616fce9bdc60bb7bbb8ef5231
vividyellow/oldboyeduPython14qi
/第1部分-python基础(颜涛老师)/day01/code/four.py
232
3.875
4
''' a = 10 b = 3 print(a%b) # xxx是否可以被xxxx整除 num = input("请输入一个数:") num = int(num) if num % 3 == 0: print("是三的倍数") else: print("不是三的倍数") ''' a = 10 b = 3 print(a // b) # 取整
d5104cd4cf8a18046921791e7b6cb55e814ab455
vividyellow/oldboyeduPython14qi
/第1部分-python基础(颜涛老师)/day15/day15-code/07 二分法查找.py
1,214
3.65625
4
# lst = [11,22,33,44,55,66,77,88,99,123,234,345,456,567,678,789,1111] # n = 567 # left = 0 # right = len(lst) - 1 # count = 1 # while left <= right: # middle = (left + right) // 2 # if n > lst[middle]: # left = middle + 1 # elif n < lst[middle]: # right = middle - 1 # else: # pri...
81bb00706322a402d38d05d1504f72c6b7a812d8
vividyellow/oldboyeduPython14qi
/第1部分-python基础(颜涛老师)/day06/day06-code/03 is和==.py
1,609
3.625
4
# s = "alex 是 大 xx" # abc = id(s) # 得到内存地址 # print(abc) # lst = ["大阳哥", "佳琪哥", "小花生", "燃哥"] # print(id(lst)) # 就是一个内存地址. 毫无意义 # lst = ["周杰伦", "燃哥"] # lst1 = ["周杰伦", "燃哥"] # print(id(lst)) # print(id(lst1)) # s = "燃哥" # s1 = "燃哥" # # 小数据池. 会对字符串进行缓存, 为了节省内存 # print(id(s)) # print(id(s1)) # tu = ("燃哥", "周杰伦") # t...
05410bd1f18894f94886a7519b23d90bf05d564e
vividyellow/oldboyeduPython14qi
/第1部分-python基础(颜涛老师)/day13/day13-code/05 生成器表达式.py
337
3.5625
4
# g = (i for i in range(10)) # print(list(g)) # gen = ("麻花藤我第%s次爱你" % i for i in range(10)) # for i in gen: # print(i) # 生成器的惰性机制 # def func(): # print(111) # yield 222 # g = func() # g1 = (i for i in g) # g2 = (i for i in g1) # # print(list(g)) # print(list(g1)) # print(list(g2))
2eccef26bb0a8c0fc7a8b945c49f6f981fda07bf
vividyellow/oldboyeduPython14qi
/第1部分-python基础(颜涛老师)/day04/day04-code/02 作业讲解.py
2,936
3.765625
4
# 1.请输出 name 变量对应的值中 "e" 所在索引位置? name = "aleX leNb" # e1 = name.find("e", 0,5 ) # print(e1) # # e2 = name.find("e",5 ) # print(e2) # count = 0 # while count < len(name): # if name[count] == 'e': # print(count) # count = count +1 # s1 = name[:1] # s2 = name[1:] # print(s1.upper()+s2) # # name.replace...
f760e9ae20d5b5e85f85b4e0da9fd54db81a7982
JhonJhon31/Marvin
/fase04/ex04/abc.py
205
3.765625
4
def abc(letra): if letra[0:1] == "a" or letra[0:1] == "b" or letra[0:1] == "c" or letra[0:1] == "A" or letra[0:1] == "B" or letra[0:1] == "C": return "true" else: return "false"
551d8ca9c63d1d9ee7cd61b6c111432bbe7f1a71
sjaney/PDX-Code-Guild---Python-Fullstack-Solution
/python/lab7v1.py
1,033
4.09375
4
# Lab 7 Rock Paper Scissors import random print("Let's play rock paper scissor!") user = input('Choose one: rock, paper or scissors: ').lower() computer = ['rock', 'paper', 'scissors'] random_answer = random.choice(computer) if user == random_answer: message = f"Your {user} ties computer's {random_answer}" e...
b94e21fffffeede85942ca87aab41a1ce47a0dfc
sjaney/PDX-Code-Guild---Python-Fullstack-Solution
/python/lab9v2.py
409
4.125
4
# Lab 9v2 ROT Cipher import string print('Encrypt your word into a ROT Cipher.') user = input('Enter a word(s) you would like to encrypt: ') move = int(input('Enter an amount for rotation: ')) alphabet = string.ascii_lowercase encryption = '' for char in user: if char in alphabet: new_encrypt = alphab...
474094cf9b01bc4c4b41f3109c8a569e48a24d8b
sjaney/PDX-Code-Guild---Python-Fullstack-Solution
/python/lab19.py
1,442
3.8125
4
# Lab 19 Rain Data import requests import re import math # use requests to get a file response = requests.get('https://or.water.usgs.gov/non-usgs/bes/mt_tabor.rain') data = response.text total_rainfall = re.findall(r'\d{2}-\w{3}-\d{4}\s+\d+', data) # list of dictionaries rainfalls = [] for index in range(len(total_...
3713f4faae3efacfccbf3443a8c80081412ff456
aliasjohn/clusterization
/bstJkclaster.py
2,710
3.6875
4
# zero: binary search tree realisation for using like set class BST: def __init__(self): self.root = None self.cardinality = 0 self.nodes = [] def add(self, value): node = BSTnode() node.setData(value) if self.root == None: self.root = node else: ...
66eb8de2420ef4f2bced6c7260f453c3f18a68e4
lcsm29/edx-mit-6.00.1x
/ps2/problem_1.py
388
3.65625
4
balance = 42 # test 1, expected 31.38 (test 2, balance 484, expected 361.61) annualInterestRate = 0.2 monthlyPaymentRate = 0.04 for i in range(1, 13): unpaid = balance - balance * monthlyPaymentRate balance = unpaid + annualInterestRate / 12.0 * unpaid # print('Month {} Remaining balance: {:.2f}'.form...
5763159e3a22d1e3d72f09d33c50b2d75fcc009a
lcsm29/edx-mit-6.00.1x
/ps4/problem_6.py
1,691
3.5625
4
# Problem Set 4 - Problem 6 - Playing a Game # # Released 2021-06-30 14:00 UTC+00 # Started 2021-06-30 15:31 UTC+00 # Finished 2021-06-30 15:42 UTC+00 # https://github.com/lcsm29/edx-mit-6.00.1x # # oooo w r i t t e n b y .oooo. .ooooo. # `888 ...
4863b9dd729dffc2e1fc724ccce1d5dab8358b9f
Northwestern-CS348/assignment-3-part-2-uninformed-solvers-priyashah13
/student_code_uninformed_solvers.py
6,998
3.703125
4
from solver import * class SolverDFS(UninformedSolver): def __init__(self, gameMaster, victoryCondition): super().__init__(gameMaster, victoryCondition) def solveOneStep(self): """ Go to the next state that has not been explored. If a game state leads to more than one unexplo...
2fa7a57094eef0cc84b16d64901c603742ded47c
ShiZhan/newspapers
/utils/escaped-unicode-print.py
217
3.65625
4
#!/usr/bin/python import sys if len(sys.argv) < 2: print "where is input escaped-unicode file?" exit(1) with open(sys.argv[1]) as f: str = f.read().decode('unicode_escape') print str.encode('utf-8')
d9fb2c820e3a2838495c8f8f1eaa683b5dba1af2
lokal-profil/runeberg
/runeberg/article.py
3,725
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ A runeberg.org article is a chapter, article or poem. Per http://runeberg.org/admin/19990511.html#Indexing_Articles: 'Project Runeberg's text editions present each chapter of a novel as an HTML file of its own. Poetry book are made up of poems, while journals and dictionar...
6aca389fe173d2688abebe82ded8c87e6c9d753c
Mayankgupta688/working-with-python
/passingIntToFunction.py
474
3.8125
4
# Here we will look for the fact whether Int variables are passed by Reference or Values initialIntValue = 10 def change_user_data(inputParam): print(inputParam is initialIntValue) return inputParam outputData = change_user_data(initialIntValue) print(outputData is initialIntValue) # Here, it is verified t...