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
6168e7579f4d014b666e617f5ff9869cea0d68b4
mayanksh/practicePython
/largestarray.py
521
4.34375
4
#def largest(array, n): # max = array[0] #initialize array # for i in range (1, n): # if array[i] > max: # max = array[i] # return max #array = [1,2,3,4,5] #n = len(array) #answer = largest(array, n) #print("largest element is: " , answer) arr=int(input('Enter the element of an array:')...
5c74a32a547368cca984ade073c5c6a710c6c412
mayanksh/practicePython
/arithmetic_operations.py
281
3.625
4
import cmath if __name__ == '__main__': n = int(input("")) if 1 <= n <= 20: for i in range(0,n): print (i*i) #for 123....n #if __name__ == '__main__': # n = int(input('')) # if 1 <= n <= 150: # print(*range(1, n + 1), sep ="")
829b18b496627c90cd9a5e9e454fc214e701f2e3
Jaum97/python-practice
/range.py
177
3.953125
4
for i in range(5): print(i) >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Mary 1 had 2 a 3 little 4 lamb
8a35cb375225120b05c1a6ba0896b0e01d6bd9df
dkkc/Python
/Data types/exercises.py
943
3.953125
4
defDictionary = {} while (True): menu = print("Menu\n\r1 - dodaj do słownika\n2 - szukaj w słowniku\n3 - usuń ze słownika\n4 - zakończ program") choise = input('Co chcesz zrobić? ') if (choise == "1"): key = input("Podaj klucz ") descr = input("Podaj definicję ") defDictionary[key]...
f6b8d77095c5ce7ec4b26096eaca52cf7e2c4b1b
dkkc/Python
/TransformData/wyrazeniaGenerujace.py
274
3.609375
4
import sys evenNumbers = [number for number in range(4400) if(number % 2 == 0)] evenNumberGenerator = (number for number in range(440) if(number % 2 == 0)) print(sys.getsizeof(evenNumbers)) print(sys.getsizeof(evenNumberGenerator)) print('suma', sum(evenNumberGenerator))
73f512739d1c7f8df48b4366b7fc571474d38fad
tarantot/homework-for-Feb-6
/homework-for-Feb-6-2.py
1,459
3.921875
4
a = int(input('Please enter a HUGE number: ')) z = a/60 y = a%60 x = a/3600 w = a%3600 v = a/86400 u = a%86400 t = w/60 s = w%60 r = u/3600 print((str(int(v))) + ' : '+ (str(int(r))) + ' : ' + str(int(t)) + ' : ' + str(int(s))) #if a <= 59: # print(str(int(a)) + ' seconds') #elif a == 60: # print(str(int(z)) +...
6bc76baaf14c6605e16add5f1fd994459f739f5b
gup-abhi/comp_image
/compressor.py
333
3.53125
4
# import PIL module import PIL # importing image from PIL module from PIL import Image # opening image from the current working directory img = Image.open("margot.jpg") # resizing the image to specific dimensions img = img.resize((500, 500), PIL.Image.ANTIALIAS) # saving the resize image to the directory img.save("m...
b39b3982038af0946a25ed27c3350d6bb4b37c56
saamrth/PythonBible
/palindrome.py
175
4.1875
4
string = input("enter the string:") a=string[0::] b=string[::-1] if a==b: print("The string is a palindrome") else: print ("The string is not a palindrome")
a3fafad3eb76b42c7a6a8a10d9047bc001b8517a
saamrth/PythonBible
/slicer.py
216
3.703125
4
x=input("enter the email address: ").strip() user =x[:x.index("@")] domain =x[x.index("@")+1:] message=" Your username is {} and the domain name is {} " output=message.format(user,domain) print(output)
35f02361cf7b9a11d2b8d2c19df36a86435f7f63
ljdutton2/steganography
/steganography.py
2,800
3.515625
4
from PIL import Image,ImageDraw, ImageChops def decode_image(path_to_png): # Open the image using PIL: encoded_image = Image.open(path_to_png) # Separate the red channel from the rest of the image: red_channel = encoded_image.split()[0] # Create a new PIL image with the same size as the enc...
4349b1660dd368b7acaddb178cb6809e775ef7c2
TijmenK/AoC2020
/day11.py
2,462
3.59375
4
seatGrid = [[3 if char == '.' else 0 for char in line.rstrip()] for line in open("day11_input.txt")] h = len(seatGrid) w= len(seatGrid[0]) def printGrid(array): for row in array: print(row) def checkAdjacent(row, chair): if seatGrid[row][chair] == 3: return 3 adjacentArray = [...
2d0e0d3a7e994d9023663510d8a582fc6e145ae9
TijmenK/AoC2020
/day09.py
1,065
3.59375
4
q = [int(line.rstrip()) for line in open("day9_input.txt")] preambleSize = 25 def findNumber(preAmble, q): for idx, value in enumerate(q[preAmble:]): searchDict = {el:1 for el in q[idx:idx+preAmble]} found = False for key in searchDict: if value - key in searchDict: ...
e66225de1e823da2f1e77d17bf16874ae2e667f9
ginking/pymol-1
/lib/random_walk.py
149
3.6875
4
import numpy as np def random_walk(N): x = np.random.randn(N+1,3).astype('f').cumsum(axis=0) x -= x.mean(axis=0) return 5 * x / x.std()
970d5bee4acfe240e4891e348336df5486d9b6a5
gabrslen/estudos
/EntrevistaEmprego/DataModule.py
769
4.25
4
class Entrevista(): nome = "" ano_informado = 0 idade = 0 def pergunta_nome(self): self.nome = input("Nome do candidato: ") print("O nome é '" + self.nome + "'") return self.nome def pergunta_idade(self, ano_atual=2021): self.ano_informado = int(input("Ano de nasci...
581a3923b88ec06627b37db60b2d4f0cbad9fb04
nevzorovsergey/py_lesson1
/task_5.py
571
3.859375
4
# 5. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят и сколько между ними находится букв. c1 = input('Введите первую букву ') c2 = input('Введите вторую букву ') f = ord('a') - 1 ch1 = ord(c1[0]) ch2 = ord(c2[0]) n1 = ch1 - f n2 = ch2 - f r = n2 - n1 print('Номер первой буквы ', n1) prin...
6e9665705ed698ab8907f764d7e08dc828298b3a
ofeliiaB/blackJackPython
/Black_JACK_TASK_2_Ofeliia_Bagratian.py
8,767
4.0625
4
##importing random to shuffle the cards import random ##initializing constant values ##creating list, these cards list does not consider 4 suits, in further programming this point will be considered CARDS = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King') ##Black jack values of each card ...
a96e247634b1adb9575eeba3dcaf9148fc9f71b7
gracielle-ch/atividades
/ativ3.py
296
3.859375
4
dia = int(input('digite com o dia: ')) horas = int(input('digite com as horas: ')) minutos = int(input('digite os minutos: ')) segundos = int(input('digite os segundos: ')) ###teste segundosF= (dia*24*60*60) + (horas*60*60) + (minutos*60) + segundos print ('Numero em segundos é ', segundosF)
d1f23a655d413d7426cd20b1ebd483b5db7713b6
gracielle-ch/atividades
/ativ2.py
103
3.546875
4
valor = int(input('entre com o numero: ')) valorC= valor*1000 print ('Numero em milimetros é', valorC)
da79b2841e74227a8ac511dea7afdbb340db4677
apktool/LearnPython
/1.15.05.py
591
3.65625
4
# 字典|创建字典 ''' 键-值 ''' # 不使用字典来实现字典的功能 brand=['LiNing','Nike','Adidas'] slogan=['Anything is possible','Just do it','Impossible is nothing'] print('LiNing\'s slogan is \"',slogan[brand.index('LiNing')],'\"') # 创建字典|使用{} dict1={'LiNing':'Anything is possible','Nike':'Just do it','Adidas':'Impossible is nothing'} prin...
4d074670c51a575a66b25d6bd667b5d51d0551c9
apktool/LearnPython
/1.17.09.py
524
3.984375
4
# 类|绑定 class C: def x(self): print('x-man') c=C() c.x() c.y=1 print(c.y) ##################### class CC: def setXY(self,x,y): self.x=x self.y=y def printXY(self): print(self.x, self.y) dd=CC() print(dd.__dict__) print(CC.__dict__) ''' 类的属性和方法同名的时候,会导致类的属性会覆盖方法从而导致调用出错 实例化 ''' ''' 类定义 C ...
4bbbacc98c88261ddba0ed4fa59ff83b78b41c64
apktool/LearnPython
/1.20.01.py
347
3.984375
4
# setup.py文件install之个人猜想 # 主要采用的是继承机制 class A(object): def __init__(self): self.run() def run(self): print('I am A, I am running') def walk(self): print('I am A, I am walking') class B(A): def run(self): print('I am B, I am running') self.walk() b=B()
d663b392d048396983b8e8ed825b1cd8c7ae013b
apktool/LearnPython
/1.12.01.py
587
4.28125
4
#--coding:utf-8--- #元组 tuple1=(1,2,3,4,5,6,7,8) print(tuple1) tuple2=(1) print(tuple2) tuple3=(1,) print(tuple3) tuple4=1 print(tuple4) tuple5=1, print(tuple5) ''' 应该注意tuple2和tuple3的区别:tuple2创建的是一个整数,tuple3创建的是一个元祖 tuple4创建的是一个整数,tuple5创建的是一个元组 ''' a=8*(8) print(a) a=8*(8,) print(a) ''' 第一次打印出的a是64 第二次打印出的a是(...
cee22da55a9751aa53af329a281a7cdbd593d4bd
apktool/LearnPython
/1.13.02.py
558
3.640625
4
#--coding:utf-8-- # 函数|不带参函数,带参函数 def MyFirstFunction(): print("hello world") MyFirstFunction() def MyScondFunction(name): '这里是函数文档,应该不会显示在屏幕上' # 这里name只是一个形式,表示占据一个参数位置 print('传递进来的'+name+'叫做实参,因为Ta是具体的参数值') # 打印函数文档 print(MyScondFunction.__doc__) MyScondFunction('aron') def sum(num1, num2): result=num1+n...
28d8ba7e127b48366431f488fb049b02837bba58
apktool/LearnPython
/3.15.01.py
1,301
3.953125
4
# 命名空间和作用域 def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlo...
4a967e2285d09f08261e92df7f719abb0e7d4cf4
apktool/LearnPython
/3.14.03.py
1,635
4.15625
4
# 命名空间的生命周期 x=1 def fun1(): x=x+1 fun1() def fun2(): y=123 del y print(y) fun2() ''' UnboundLocalError: local variable 'x' referenced before assignment UnboundLocalError: local variable 'y' referenced before assignment ''' ''' 不同的命名空间在不同的时刻创建,有不同的生存期。 1、内置命名空间在 Python 解释器启动时创建,会一直保留,不被删除。 2、模块的全局命名空...
259b527686a4c01f74a04c7f9e450441db5959b6
apktool/LearnPython
/1.18.03.py
660
4.09375
4
# 魔法方法|算数运算|__add__,__sub__,__rand__,__sub__ class New_int(int): def __add__(self,other): #return int(self)+int(other) return int.__sub__(self,other) def __sub__(self,other): #return int(self)-int(other) return int.__add__(self,other) a=New_int(3) b=New_int(5) print(a+b) print(a-b) ''' self可以认为是类的实例化绑定的一...
949439071ea87181644bbcaa1abbf4ab33272e8d
apktool/LearnPython
/1.15.03.py
273
4.0625
4
# 函数|递归(factorial,Fibonacci) # 求解factorial def MyFunction(n): if n==1: return 1 return n*MyFunction(n-1) temp=MyFunction(5) print(temp) # 求解Fibonacci sequence def Feber(x): if x==1 or x==2: return 1 return Feber(x-1)+Feber(x-2) print(Feber(20))
52e55f15a55e877ba0f818041ca4853eabf715f5
SergeyTishchenko/trainings
/6.py
198
3.75
4
def add_numbers_to_zero_sum(array): element = sum(array) array.append((0 - element)) return array if __name__ == '__main__': print add_numbers_to_zero_sum([9, -9, 8, 1])
fb40b16370e06588e3e970767cb9a396ba9bc90b
Erik1987/PythonPandas
/checkAccountsByDateSummer.py
1,340
3.59375
4
#import necessary modules import pandas as pd import csv import re from pandas import DataFrame def main(): # Collecting data from .csv df1 = pd.read_csv("./2019/Member last activited2019.csv", sep=";", dtype={"Account Number": str}, encoding='ISO-8859-1', engine = 'python') accountnum = df1["Ac...
159b1959b0a5abc2247fc3151bb3b936ce5be372
Faerbit/evol-racer
/population.py
5,533
3.828125
4
# Based on code from http://lethain.com/genetic-algorithms-cool-name-damn-simple/ from random import randint, random from operator import add from functools import reduce from math import sin, cos, pi, sqrt from track import Track, Vector from map import Point from operator import itemgetter class Population(): "...
f2609519dd0c04dc76fe53e347aa46ba13ca1b3e
Rugdumph/Star-Wars-Saga-Edition
/mechanics.py
478
3.65625
4
import random def roll(sides): return random.randint(1, sides) def abilitiesRoll(): abilityScores = list() for i in range(0,6): # roll Abilities abilityRoll = list() for x in range(4): abilityRoll.append(roll(6)) # get the sum of the highest three rolls abilityRoll.sort() abil...
e728a778c290bae31210faad229bb64cbc0329eb
samkrimmel/unit1
/warmup1.py
225
3.9375
4
#Sam Krimmel #1/19/18 #warmup1.py - asks the user for base and height and prints the area b = float(input('Base of the triangle: ')) h = float(input('Height of the trianlge: ')) print('The area of the triangle is: ',(0.5*b*h))
c3cdf2eb7bb97ef859d8e6f99a2af11d9cf3e291
samkrimmel/unit1
/shouter.py
131
3.578125
4
#Sam Krimmel #1/17/18 #shouter.py - Repeats user input in all upper case letters little = input('Enter text: ') print(little.upper())
4f5fd9a5d9c9834a44c740078c419d9efe444efb
knsaitejas/python_oop
/math.py
802
3.828125
4
class MD(object): def __init__(self): self.rsum = 0 def add(self,*num): self.rsum+=sum(num) return self def subtract(self,*num): self.rsum-=sum(num) return self def display(self): print self.rsum return self md = MD() print md.add(5,[5,5]).display() # class MD(object): # def __init__(self): # se...
617e98aa40ff5d01a7c2e83228c011705de0b928
timlindenasell/unbeatable-tictactoe
/game_ai.py
2,347
4.3125
4
import numpy as np def minimax(board, player, check_win, **kwargs): """ Minimax algorithm to get the optimal Tic-Tac-Toe move on any board setup. This recursive function uses the minimax algorithm to look over each possible move and minimize the possible loss for a worst case scenario. For a deeper under...
ccf433106f1225e7c3008955d11aa4fcdf17d676
mcdkakao/hw
/day9_hw.py
1,008
3.59375
4
import turtle as t t.shape("arrow") # 화살표 모양으로 설정 t.bgcolor("black") # 배경을 검으색으로 설정 t.speed(0) # 그리기 속도 최고로 설정 for x in range(450): # for 반복 블록 450번 반복 설정 if x%4 == 0: # 450/4를 계산해 남은 나머지가 0이면 빨강색으로 설정 t.color("red") ...
5859fdd2879af68a6801b1634969a6a2e1552f44
milenazilena/Analysing_clustertool_swarm
/unittests/test_sum.py
1,547
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest from fractions import Fraction from my_sum import sum class TestSum(unittest.TestCase): def test_list_int(self): data = [1, 2, 3] result = sum(data) self.assertEqual(result, 6) def test_tuple_int(self): data = (1...
6dd8fac12d8cc916c094faac29ed8866ac055c6a
dadafros/Harvard-CS50-Course
/pset7/houses/roster.py
510
3.703125
4
from cs50 import SQL from sys import argv if len(argv) != 2: print("Usage: python roster.py housename") exit() db = SQL("sqlite:///students.db") result = db.execute("SELECT first, middle, last, birth from students WHERE house = ? ORDER BY last, first", argv[1]) for row in result: if row.get("middle") == ...
e32292d7d4338fdd3e5fa63a8ff118bb1258b92e
AgbaD/collpy
/collpy/base.py
318
3.609375
4
#!/usr/bin/python # Author: @BlankGodd_ __version__ = '0.0.3' def space(n): return " " * n def dot(n): return "." * n def square(n): return '▢' * n def circle(n): return '◯' * n def third(x): return True if x % 3 == 0 else False class IterError(Exception): pass
e53fe9c8d57008083fa85904cab7b855e6350932
kajleshraddha/python
/new_way
197
3.71875
4
def fav(n): l=[0,1] if n<=1: return n else: for i in range(2,n+1): l.append(l[i-2]+l[i-1]) return l[-1] print(fav(int(input())))
7a7a758a9f6e92b188bb91c5eefd9a19b7e7a20d
KhoobBabe/next-prime-number
/next prime number.py
850
3.828125
4
def next_prime(n): def is_prime(n): for j in range(2, n): if (n%j) == 0: pass else: pass for j in range(n+1, n+150): if j > 1: for i in range(2, j): if (j%i) == 0: break ...
64711e6faa4e99de81a27bf1d2f870c5fa1782c1
jade-min/Algorithm
/SWEA/D3/4406.모음이 보이지 않는 사람.py
328
3.59375
4
import sys sys.stdin = open("4406.모음이 보이지 않는 사람_input.txt") T = int(input()) for tc in range(1, T+1): string = list(input()) vowels = ['a', 'e', 'i', 'o', 'u'] result = "" for char in string: if char not in vowels: result += char print("#{} {}".format(tc, result))
95e6c557de1247abcf1351050ea1d9b4ba6e071a
jbarber69/CS-homework
/Binary trees.py
3,560
3.515625
4
__author__ = 'barberj' values = [90, 6, 70, 23, 1, 11, 420] array = [] for i in range(0, len(values)): array.append([values[i], "", ""]) for i in range(1, len(values)): pointer = 0 #location = 0 ##while loop while pointer != "": #while array[i-1][1] == "" and array[i-1][2] ==...
6afd274f94c14358a75ca62b691fd92a13569557
kavinda-ravishan/Machine_Learning_A_Z_Codes_and_Datasets
/Part 2 - Regression/Section 4 - Simple Linear Regression/app.py
1,748
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 20 19:18:09 2021 @author: kavinda """ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values # Spli...
53d70416719ca5ed67d78732378862dfc45b4f77
aidanwalk/ASTR260_HW09
/AidanWalk_HW09_1.py
4,050
3.5
4
#Aidan Walk #Astr 260-001 #HW09 Problem 1 #31 March 2021, 17:00 import numpy as np import matplotlib.pyplot as plt def analytic_solution(t, K=None, P0=None, r=None): """K = maximum carrying capacity of ecosystem P0 = initial population at time t=0 r = population growth rate t = time """ n...
c44b5ad1a629933067fc5c313b080a43a74bc4cd
PawanMathur/007-get-prime-numbers
/prime_numbers.py
788
3.78125
4
import math def get_prime_numbers (n): if n <= 1: print "Give a number greater than one" return [] else: primes = [] nums = range (2,n+1) bigdivisor = math.sqrt(n) while nums: prime = nums[0] if prime > math.sqrt: primes.ext...
21fdc051abec3c908b1118a8517a3a97d75d360e
mandy-jr/something-python
/sorting/bubble_sort.py
266
4.0625
4
a=[] n= int(input("enter size of array: ")) for i in range(0, n): x=int(input()) a.append(x) print(a) def bubble_sort(a): for i in range(n): for j in range(0, n-i-1): if(a[j]>a[j+1]): temp= a[j] a[j]= a[j+1] a[j+1]= temp bubble_sort(a) print(a)
1a70b44ce3823a29d5d2bff1004ca1fa35b44a58
linkghm/PythonSQL
/Create&Connect.py
3,367
3.65625
4
# -*- coding: utf-8 -*- # @Time : 2019/6/7 0:37 # @Author : GUO Huimin # @Email : guohuimin2619@foxmail.com # @FileName: Create&Connect.py # Python MySQL Tutorials from https://pynative.com/python-mysql-tutorial/ import mysql.connector from mysql.connector import Error from mysql.connector import errorcode # 1...
a67007c94d1f71f3157db593264d14b3919eaa50
AnkitGupta860/Pythoncodes
/Linkedlist.py
669
3.78125
4
class node: def __init__(self,value): self.info = value self.link = None class Singlelinkedlist: def __init__(self): self.start = None def display_list(self): if self.start is None: print("List is empty") return else: print("List i...
af14268d01cc722b8c5a622d7cb6874860fd8fb6
tanya9779/lab24
/4_vigenere.py
5,716
3.640625
4
# -*- coding: utf-8 -*- class Vigenere: alphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" def __init__(self, keyword): # словарь для нахождения номера буквы в алфавите self.alphaindex = {self.alphabet[index]: index for index in range(len(self.alphabet))} # вместо символов список номеров ...
7e5ec591e6ab0af46d7d6179c015feb6f5973f71
gwwatkin/lattice-surgery-compiler
/utils.py
1,166
3.953125
4
from fractions import Fraction import math def decompose_pi_fraction(f:Fraction): """ Break a fraction that has a power of two as denominator into a sequence of fractions that add up to it, all of which have 1 for numerator. Adjusts the fraction to be in the (2,0] range """ # Check that f's denominator...
89565fd3c4523e86f8fd18c42bc55df35640f1ae
BabaSeigo/config
/python_memo.py
596
3.65625
4
# 再帰でyield使うパターン def recur_test(): def recur(array,residual,index): if index==len(array)-1: array[index]=residual yield array return for i in xrange(0,residual+1): temp_array=[x for x in array] temp_array[index]=i for j in rec...
4972288d150f2829cb44744839e19aed6cd9e8cf
guilhermebr/hackercups
/facebook_hackercup/2013/qualify/balancedSmileys.py
2,405
3.578125
4
# Balanced Smileys for Facebook Hackercup # fb.com/gbrezende # Guilherme Rezende <guilhermebr@gmail.com> def rule1(word): """ rule: If an empty string """ if word == '': return True return False def rule2(word): """ rule: One or more of the following characters: 'a' to 'z', ' ' (a ...
79d284ea9bbdec58dd6c4d5befca9d971bc4ee14
ANh0r/LeetCode-Daily
/8.9 goodPair.py
914
3.578125
4
# 复杂度 O(N) from collections import Counter from typing import List class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: print([v * (v - 1) // 2 for v in Counter(nums).values()]) return sum(v * (v - 1) // 2 for v in Counter(nums).values()) '''# 复杂度 O(N^2) class Solution: def n...
e59d0fd5123f22d769089181168ece378cafdc2c
ANh0r/LeetCode-Daily
/7.31 verticalTraversal.py
597
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: stack, d = [(root, 0, 0)], defaultdi...
232c4d15cdcb985f470c407e06026a4f14371b4a
ANh0r/LeetCode-Daily
/7.28 distanceK.py
1,584
3.515625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: stack = deque() def bt(node): sta...
136aa8c4711a1b447683e8f0740652a68da3629e
ANh0r/LeetCode-Daily
/9.9 combineTarget.py
2,168
3.578125
4
""" 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。  示例 1: 输入:candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ] 示例 2: 输入:candidates = [2,3,5], target = 8, 所求解集为: [   [2,2,2,2],   [2,3,3],   [3,5] ] """ from ...
e32e9dc509a039a343dd6c265aff186f0790325a
ANh0r/LeetCode-Daily
/8.30 FindUnsortSubarray.py
2,005
3.921875
4
"""给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。 你找到的子数组应是最短的,请输出它的长度。 示例 1: 输入: [2, 6, 4, 8, 10, 9, 15] 输出: 5 解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。 """ from typing import List """思路: 第一次简历: 从前向后遍历,保存到当前位置为止的最大值,若下个数大于等于max_num,则更新max_num。否则,更新需要排序数组的右界right。 初始化right=0,max_num=nums[0] 遍历数组,遍历区间...
32deb3fb6884891ddc1bd76f65a4d0d855a1b6e2
ANh0r/LeetCode-Daily
/9.25 buildTree.py
2,161
3.578125
4
class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: # 实际上inorder 和 postorder一定是同时为空的,因此你无论判断哪个都行 if not inorder: return None root = TreeNode(postorder[-1]) i = inorder.index(root.val) root.left = self.buildTree(inorder[:i], p...
e4e974a7188fb8c9cdd0918548e7e4c7dd88d628
ANh0r/LeetCode-Daily
/10.31 O1insert Hard.py
2,180
3.65625
4
class RandomizedCollection: def __init__(self): self.vals=[] self.index={} def insert(self, val: int) -> bool: self.vals.append(val) if val in self.index: self.index[val].add(len(self.vals)-1) return False else: self.index[val] = {len(...
ad4e19e7df1666d10c1368a961b6cc8811d69c24
ANh0r/LeetCode-Daily
/9.30 insertBST.py
1,806
4
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return TreeN...
9324c8155e2e7d3f938dec554486d1b004201906
ANh0r/LeetCode-Daily
/9.8 deleteNode.py
1,148
4.09375
4
"""请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点。传入函数的唯一参数为 要被删除的节点 。 示例 1: 输入:head = [4,5,1,9], node = 5 输出:[4,1,9] 解释:给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9. 示例 2: 输入:head = [4,5,1,9], node = 1 输出:[4,5,9] 解释:给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9. """ class Solution: def deleteNode(self, node): "...
ccbae0d9762ecface6e8bd7384fce5a1de38621a
ANh0r/LeetCode-Daily
/7.31 bin2int.py
741
3.796875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode(object): def __init__(self, x): self.val = x self.next = None # class Solution: # def getDecimalValue(self, head: ListNode) -> int: # a...
9dbcae71d716119b0f737b1d2eda75550e544925
ANh0r/LeetCode-Daily
/11.14 RelativeSortArray.py
744
3.59375
4
from typing import List class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: def mycmp(x: int) -> (int, int): return (0, rank[x]) if x in rank else (1, x) rank = {x: i for i, x in enumerate(arr2)} arr1.sort(key=mycmp) return arr1 ...
cdca6293bf1f8b8810893fbbac547b64343d4a8d
stanleyuan/nicetomeetyou
/crawler/scraper.py
1,719
3.671875
4
""" This modules contains the class for get response from website""" import requests class Scraper: "For get response from the target website" def __init__(self, url="www.google.com"): self.url = url self.request_headers = None self.response = None self.text = None sel...
3112544de2df15edf8e14ca7dd2722188ff4f057
mcoutolive/python_exercicios
/Fatorial.py
136
4.15625
4
num = int(input("Digite um número: ")) fatorial = 1 for i in range(1,num): fatorial = fatorial*(i+1) print(num,'! = ',fatorial)
20f9f70c1e80c555b654addbac4e5fecc3cf12da
mcoutolive/python_exercicios
/Exercício_04.py
404
3.75
4
vetor = [] vetor_inv = [] numero_par = 0 contador = 0 '''Inserindo 10 números pares''' while (contador < 10): numero_par = int(input("Insira um numero par: ")) if (numero_par%2==0): vetor.append(numero_par) contador += 1 else: pass print(vetor) '''Mostrando o vetor inver...
000e9c86745e99ee6dc55c6567851d905137396c
mcoutolive/python_exercicios
/Exercício_06.py
554
3.953125
4
vetor = [] contador_negativos = 0 soma_positivos = 0 contador_zeros = 0 for i in range(10): numero = float(input("Insira um numero: ")) vetor.append(numero) if (numero<0): contador_negativos+=1 elif (numero>0): soma_positivos = soma_positivos + numero else: contad...
80a9934c2c2fe00ec70b217ee0e8dbb87fbfe02f
weslleyantonio/Python
/URI/1007/1007.py
171
3.515625
4
def main(): A = input() B = input() C = input() D = input() dif = int(A)* int(B) - int(C) * int(D) print("DIFERENCA = {}".format(str(dif))) main()
6e8d5f691bb8b51d35d4b74c18454e2c48e16c7a
ChristianR21/CS-490-Deep-Learning
/Lab 1 Q6-2.py
1,550
3.96875
4
#Chrisitan Rodas #490-0003 #Question 6 #First import libraries needed to parse a webpage and extract specific data from it #Then get the URL using requests and parse it using BS4 #Next, find the where the data is on the webpage and extract that #So in this case, #Then iterate through the table, extracting the co...
deaf2714db6d048f867acab5315618364d49bd05
2008haas/ml
/series_GS.py
760
3.671875
4
def train(X, y, W, B, alpha, max_iters): ''' Performs GD on all training examples, X: Training data set, y: Labels for training data, W: Weights vector, B: Bias variable, alpha: The learning rate, max_iters: Maximum GD iterations. ''' dW = 0 # Weights gradient accumulator dB = 0 # Bias gradient accumulator ...
4ccce1bf53212599c051774c0c80b1d0279c6ff9
alexmuller/advent-of-code-2020
/day-02/part-2.py
851
3.828125
4
#!/usr/bin/env python def password_is_valid(first_index, second_index, required_character, password): results = [] for index in [first_index, second_index]: results.append(password[index-1] == required_character) if results == [True, False] or results == [False, True]: return True els...
5b438286bed1480182db1692ddbd310da007173b
borzfele/2048wMark
/2048.py
1,010
3.9375
4
''' - Feldarabolás: Main / mozgatás & reset / highscore / kirajzolás / menü - Bugfix: Ha változás történik a mátrixban csak akkor adhat hozzá új értéket - globális változók csökkentése - High score fileba / Dedicated to Mark - ha marad időnk: HP game (időre high score) - docstrings ''' #################################...
c4db98f614f03b516ad5a6a59d57c766c96c1eab
AmandeepSaxena/DataStructures-Algorithm-CodingMaster
/twonumbersum_s2.py
244
3.546875
4
def twonumberSum(array, targetSum): nums = {} for num in array: potentialMatch = targetSum - num if potentialMatch in nums: return [potentialMatch, num] else: nums[num]= True return []
10477ece5af7078c5493c7c640bbc06e81636af6
flysaint/Autumn_battle
/Code/my_leetcode/problems/hard_02_add-two-numbers.py
2,789
3.984375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 22 09:00:02 2020 @author: fly_s hard_02_add-two-numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linke...
b7097b87e7b2b1fdf4ef7cbc4ccaa68d406aeb6f
Betwulf/PythonNeural
/customnn.py
1,023
3.65625
4
import numpy as np def sigmoid(x): return 1/(1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1 - x) input_data = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) train = np.array([[0], [1], ...
931f20674552191574fd48a0b29c5168a65117a0
sealockej15/starter-games
/water_balloon.py
4,658
4.4375
4
""" LESSON: 3.4 - Program Structure EXERCISE: Water Balloon Drop """ #### ---- SETUP ---- #### # --- Libraries & window --- # # Import random library import random # Import PYGAME import pygame # INITialize pygame pygame.init() # Open a WINDOW of size [800, 600] and assign to window w=pygame.di...
b13782742052671680b58822ff8d588df0636d31
murodjonjuraev/week6
/files_and_exeptionds.py
310
3.53125
4
file_name = 'data/inputData.txt' with open('data/inputData.txt') as input_data: contents = input_data.read() print(contents) print(contents) print("Reading a inputData.txt file completed") # writing to the file with open(file_name, 'a') as file_object: file_object.write("I love programing.\n")
11655d993d1db846284a1807f0382c0e8c07e08e
Charisa/PSA1
/naloge/2016/dn1/matrix/SaraKorat/slowmatrix.py
1,472
3.65625
4
# -*- coding: utf-8 -*- #from ..matrix import AbstractMatrix from matrix import AbstractMatrix class SlowMatrix(AbstractMatrix): """ Matrika z naivnim množenjem. """ def multiply(self, left, right): """ V trenutno matriko zapiše produkt podanih matrik. Množenje izvede z izraču...
609c2396fa376981fed4a37a6d5607284c218121
wesaputra/labpy03
/program 1.py
404
3.578125
4
print ( 'Total Keuntungan Selama 8 Bulan Berjalannya Usaha' ) #Modal Awal n=100000000 print ("Awal Modal : ", n ) #presentase Keuntungan A=0*n B=0*n C=0.01*n D=0.01*n E=0.05*n F=0.05*n G=0.05*n H=0.03*n y=[A,B,C,D,E,F,G,H] for i in range (len(y)): print (" Keuntungan Bulan ke ",i+1 , "-> ", y...
3c40dd6026f8d50ca95babf44c99c962a581c8df
ZuckermanLab/phat
/phat/metrics.py
595
3.640625
4
"""Distance functions on path space.""" from scipy.spatial.distance import directed_hausdorff def symmetric_difference_cardinality(s, q): """Return the cardinality of the symmetric difference of two sets. Parameters ---------- s : iterable Elements of the first set. Values must be hashable. ...
6e283e8b0575d93f86375ddf5b9b73af8285b640
kazimsadiq/githubtest
/class_test.py
573
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 6 19:05:47 2020 @author: fali """ class Person: def __init__(self, name, age): self.name = name self.age = age def printname(self): print(self.name, self.age) p1 = Person("John", 36) print(p1.name) print(p1.age) #p1.prin...
dab8136fbc0ce07a24989cf716545499829066c0
kbgro/breakout-game
/breakout/breakout.py
3,512
3.671875
4
import tkinter as tk from .ball import Ball from .brick import Brick from .paddle import Paddle class GameFrame(tk.Frame): """ Game Canvas Frame """ def __init__(self, master): super().__init__(master) self.lives = 3 self.width = 610 self.height = 400 self.c...
0ca9bf8608ed24b554d6874e4c4e538e2be56685
patel-jinesh/CSFundamentals
/Data Structures/queue.py
1,185
3.796875
4
from linkedlist import * class LinkedListQueue: def __init__(self): self.first = None self.last = None self.size == 0 def enqueue(self, value): if self.first == None: self.first = LinkedListNode(value, None) self.last = self.first else: ...
9cfec6d6d3f8b8fc0f3fe796da73ee8ffd7be2ad
dnyanadap/Python
/Motif_match.py
960
3.984375
4
import math, string, re return_value = "" """ ---------------------------------------------------------------------------------------------------- == FUNCTION 4 == Write a function called MotifMatch, that takes a sequence as an argument. The function returns the string "Match" or "Not Match" depending on whet...
da9dd4efe94ceb8fd6ac6a90c1b09ae06d6ad7b9
liuzhennn/Ryu_SDN_Controller
/ryu/app/experiments/PureSDNPkt/predict.py
2,638
3.5
4
# -*- coding: utf-8 -*- def double_exponential_smoothing(series, alpha, beta): """ series - dataset with timeseries alpha - float [0.0, 1.0], smoothing parameter for level beta - float [0.0, 1.0], smoothing parameter for trend """ # first value is same as series result = [serie...
2952665f276d14a9abd2c74d709a5b5c68cd6644
liuzhennn/Ryu_SDN_Controller
/ryu/app/Test/testNetworkX.py
660
3.578125
4
import networkx as nx import random as rand import matplotlib.pyplot as plt def test(): G=nx.Graph() G.add_edge(1,2,weight=3) G.add_edge(2,3,weight=8) G.add_edge(1,4,weight=4) G.add_edge(1,5,weight=1) G.add_edge(2,5,weight=5) G.add_edge(5, 2, weight=5) G.add_edge(4,5,weight=9) G.add...
759176d9b1450e3af5039e3a94c02250b430c368
edderick/euler
/problem17.py
2,101
3.53125
4
## There are more pythonic ways to do it, but this works.. def to_letters(n): s = str(n) if len(s) == 4: return "onethousand" elif len(s) == 3: if n % 100 == 0: return to_letters(int(s[0])) + "hundred" return to_letters(int(s[0])) + "hundredand" + to_letters(int(s[1]+s...
020dc69e0824f562baf94e1452e49107828ab54c
edderick/euler
/problem12.py
588
3.5
4
import math top = 20 # Generate some primes l = [True for i in range(0, top)] l[0] = False l[1] = False end = int(math.sqrt(top)) for i in range(2, end + 1): if l[i]: for j in range(2, int(top / i) + 1): if j * i >= top: continue l[j * i] = False primes = [i for ...
ecc2c1be03cff9abbd275dfe9c0f49d1b98b9991
tkaderr/python_fundamentals
/stars.py
539
3.671875
4
#Part 1 def stars(arr): stars_str= "" letter_str="" temp_str="" for i in range (0,len(arr)): if type(arr[i])==str: letter_str=letter_str+arr[i] for y in range(0,len(letter_str)): temp_str=temp_str+letter_str[0] print temp_str te...
d3adf4ee74b13a4faf30a93fe504e0bf3f8ee565
tkaderr/python_fundamentals
/coin_flip.py
637
4
4
import random def coin_flip(num): heads_counter=0 tails_counter=0 for i in range (1,num+1): randnum=random.randint(0,1) if randnum==0: tails_counter=tails_counter+1 print "Attempt #{}: Throwing a coin...Its tails...Got{} heads so far and {} tails so far".format(num,h...
257cbb668ab219722724269b42fd1d0065a12973
tkaderr/python_fundamentals
/average_list.py
137
3.640625
4
def average_list(arr): sum_list=arr[0] for i in range(1,len(arr)): sum_list=sum_list+arr[i] return sum_list/len(arr)
7279b1211ed1c194169ed06a067ec0c6d157ad3f
tkaderr/python_fundamentals
/car.py
629
3.859375
4
class car(object): def __init__(self, price, speed, fuel, mileage): self.price=price self.speed=speed self.fuel=fuel self.mileage=mileage if self.price>10000: self.tax=0.15 else: self.tax=0.12 self.display_all() def display_all(sel...
852725042a4b88ae949fd12b7d84c97ad706d886
nareshmuthyala/Assignment_2.3
/Assignment_2.3.py
68
4.25
4
word = input("Enter the word") print("Reverse word is :"+word[::-1])
46017dfcebae1c03671abfdf63cb70c309bdd5a8
PavanKulkarni/python-code-samples
/code/medium/permutation.py
419
3.609375
4
def perm(word): print '1: %s' % word if not word: return [word] else: temp = [] for k in range(len(word)): part = word[:k] + word[k+1:] print '2: %s' % part for m in perm(part): print '3: %s and %s' % (word[k:k+1], m) ...
503a39a40158f61bca17b729e028e4a1855813df
PavanKulkarni/python-code-samples
/code/easy/postfix_evaluation.py
1,539
3.5625
4
from library.stack import Stack from optparse import OptionParser def evaluate_postfix(expression): s = Stack() operand_list = ['+', '-', '*' , '/'] for item in expression: if item.lower().isdigit(): # Item is operand, hence push in stack s.push(item) elif item in o...
c3bcfa93c68948c1ca6ca441eb2a6fd967712471
PavanKulkarni/python-code-samples
/code/easy/3sum.py
751
3.515625
4
import random def three_sum(a, target): a.sort() n = len(a) res = set() if n < 3: return [] for i in range(n-2): # If duplicate items not allowed , if allowed then remove (a[i] != a[i-1]) check if a == 0 or a[i] != a[i-1]: j = i + 1 k = n -1 ...
e24e5bbc51423fd9a7af7ad60ba51c1ef9d21159
PavanKulkarni/python-code-samples
/code/medium/hamming.py
392
3.75
4
def hammingdistance( a, b , bits = 32): a_int = 0 for i in a: a_int = a_int + ord(i) b_int = 0 for i in b: b_int = b_int*10 + ord(i) def _hamdist(x, bits): if bits: return (x & 1) + _hamdist(x >> 1, bits-1) return x & 1 return _hamdist( a_int ^ b...
9e8b973065392a76bb52e04fedb63123345d0a2b
PavanKulkarni/python-code-samples
/code/easy/hash.py
265
3.71875
4
class C(object): def __hash__(self): return 42 class D(C): def __eq__(self, other): return hash(self) == hash(other) if __name__ =='__main__': c, d = C(), C() x = {c: 'c', d: 'd'} print x p, q = D(), D() y = {p:'p', q:'q'} print y
89b88ec75394ac8960bee8c65dc457c82648a1aa
icefoxen/lang
/python/practice/phone.py
805
3.71875
4
# translates strings to phone-number sequences, eg 1-800-GET-CASH # Simon Heath # 16/07/2002 from string import upper, joinfields # a module 'constant' dictionary keypad = { 'abc':2, 'def':3, 'ghi':4, 'jkl':5, 'mno':6, 'prs':7, 'tuv':8, 'wxy':9 } # a derived module constant dictionary letmap = {} fo...