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
874feedf3c02f9179d2b42544121d3108e91e094
Vivenkko/Python
/Ejercicios/parking/parking.py
1,299
3.640625
4
# -*- coding: utf-8 -*- from vehiculo import vehiculo as v class parking(object): def __init__(self, numPlazas, plazasOcupadas, listaVehiculos, caja): self.__numPlazas = numPlazas self.__plazasOcupadas = plazasOcupadas self.__listaVehiculos = listaVehiculos self.__caja = caja d...
8ed26c5d7b798fab11eed8035ce90d2445d2da38
purpleladydragons/Dissociated-Press
/dissociatedpress.py
7,315
3.6875
4
# -*- coding: utf-8 -*- import random def dissociate(originale,new,chunks,chunksize): if len(new.split()) >= chunks * chunksize: return new original = originale.replace(".","").replace(",","").split() occurs = [] if new != "": occurs = teststring(new.split()[len(new.split())-chunksiz...
76f1d5c87447499615345d91b9ff60a2aaa50f40
zeroKang/day0402
/game2.py
457
3.5625
4
from random import randrange result_list = [] for x in range(10): user_num = int(input("가위 0, 바위 1, 보 2 \n")) com_num = randrange(0, 3) if com_num < user_num: com_num += 3 gap = com_num - user_num result = '' if gap == 2: result = 'U' elif gap == 1: result = 'C...
260c295ddf6fdac06144fb9532fcdba68e888c71
suresh4040/mytestgit
/python_programs/with_open.py
158
3.65625
4
with open("t.txt") as f: a = f.read(3) print(a) # here no need to close file as with will handle it f = open("t.txt") s = f.read() print(s) f.close()
5ee56a53a05d98d445cd1262c2402f3ad511c580
suresh4040/mytestgit
/python_programs/decorators.py
292
3.953125
4
# modifies function's functionality # def fun(fun1): # fun1() # fun1("yyyy") # fun(print) def ff(fun2): def fun3(): print("Hi") fun2() print("bye") return fun3 def dec1(): print("hhhh") ss = ff(dec1) ss() #lets use ff as decorator now @ff def dec2(): print("gg") dec2()
a211e65dd12c8d57586a4608c497c89cee169f96
suresh4040/mytestgit
/python_programs/opps.py
465
3.640625
4
# class method alternative constructor class college(): x = 10 def __init__(self,aname,aage): self.name = aname self.age = aage def meth1(): pass #define a class method @classmethod def cmeth(cls,val): # param = val.split("-") # cls.x = val # return cls(param[0],param[1]) return cls(*val.split("-...
be49b952ddc4587aa511a5a3599d66f245918d77
suresh4040/mytestgit
/python_programs/__name__main/a.py
365
3.78125
4
def func1(): return "f1" def func2(): return "f2" if __name__ == '__main__': s = func1() print(s) t = func2() print(t) # Above main function will only execute when we call a.py , if we call b.py and we already import a function # func1 # in b.py ,, then only func1 will execute as we used main in a.py , e...
6d241df269f6053c52aecafa660dc447657e78b2
CXK55/google-translate-game
/main.py
5,925
3.5
4
#!/usr/bin/python3 import argparse import os import sys import datetime import languages import voice_synth from pathlib import Path from shutil import rmtree from googletrans import Translator def parse_arguments(): parser = argparse.ArgumentParser(description="""Google Translate game. The point is to transla...
445b40df5e55fc817c7d736fb106232407a79449
PSaraswat10074/scatterpyllar
/scatterpyllar/filters/utils.py
4,571
3.578125
4
"""Implements some generally useful utilities""" import numpy as np from scipy import ndimage import numbers def pad(images, before=0, after=None): """Pads an ndarray Parameters ---------- before : list or array or int indicates how much to pad in front by for each axis after : lis...
d2ad965d61e66afb9cc38eb8cc10bf9d29a1f2ff
Dantide/Project-Euler
/Python/questions1-50.py
7,246
3.671875
4
from common import * #Problem Solving Area #print (timeit.repeat("for x in range(100): factor(x)", "from __main__ import factor", number=1000)) #print (timeit.repeat("for x in range(100): factor2(x)", "from __main__ import factor2", number=1000)) print ("running") #problem 1 SOLVED def problem1(): "Find the sum of...
463476b38b1738dde0d13c6159f9e89607795282
clairebroderick/TrainingLog
/SelectTeam.py
1,208
3.90625
4
#Import Swim, Cycle and Run Lists def SelectTeam(): import pickle #Import run results list file = open("SwimResults.txt", "rb") RunResults = pickle.load(file) file.close() #Calculate the averages and append to a list names = [] averages = [] for i in RunResults: ...
8c6c20e057321be57317c2ac68ce21f09e405a62
Qvita/python255
/programa6.py
114
3.6875
4
var_edad = int(input("ingrese edad")) if(var_edad >= 18): print("Mayor de edad") else: print("Menor de Edad")
6e4feb7a22f3fbc9eac06c2196bd6319cc98cc6b
chyjuls/CS1301xIII---Data-Structures
/SumList.py
274
3.9375
4
def sum_lists(listint): result = 0 for s in listint: value = 0 for item in s: value+=item result+=value return result list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(sum_lists(list_of_lists))
657c276a39eb453e2315e6cfe57febd281fd6fcc
chyjuls/CS1301xIII---Data-Structures
/InputType.py
354
3.84375
4
def input_type(s): if s == "True": return "boolean" elif s == "False": return "boolean" elif s == "": return "string" elif s.isdigit(): return "integer" else: return "float" print(input_type("")) print(input_type("False")) print(input_type("7.43...
bd98dd70d188e1d0365c7b77f70d9755c2046558
chyjuls/CS1301xIII---Data-Structures
/NumCharge.py
346
3.75
4
def num_changer(s): even = "" odd = "" for l in s[1:9:2]: even+=l for l in s[0:9:2]: odd+=l even = int(even) odd = int(odd) result = even+odd return result string_int = "123456" result = num_changer(string_int) print(string_int...
12283c386a427c21b916e455f3dfeb2deee9ad50
chyjuls/CS1301xIII---Data-Structures
/AngryFileFinder.py
369
3.6875
4
def angry_file_finder(filename): yn = False files = open(filename,"r") readfiles = files.readlines() for item in readfiles: #could >for item in files if "!" in item: yn = True else: return False return yn files.close() #print: True print(a...
d6e2ca4189a53fb20b97efa6739686c5b4b3153b
chyjuls/CS1301xIII---Data-Structures
/RightTriangle.py
505
3.546875
4
import math def solve_right_triangle(opposite,adjacent,use_degrees=False): result0 = (opposite**2) + (adjacent**2) result01 = math.sqrt(result0) hs = opposite / adjacent atan = math.atan(hs) if use_degrees: sss = math.degrees(atan) return result01,sss else: r...
3a37f85cecbb24f7b19e6a69c813ddc3b26e9212
chyjuls/CS1301xIII---Data-Structures
/AttendanceCheck.py
389
3.78125
4
def attendance_check(roster,present): result = [] for s in roster: if s not in present: result.append(s) result.sort() return result #['Ferguson', 'Winston'] test_roster = ['Jessica', 'Nick', 'Winston', 'Schmidt', 'Cece', 'Ferguson'] test_present = ['Nick', 'Cece', 'Sch...
414ed6c3e3ed036ff2598f51db29cac7cf073428
gebn/wood
/wood/util.py
1,528
3.671875
4
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Optional, TypeVar, Iterable import itertools import more_itertools A = TypeVar('A') B = TypeVar('B') def zip_dict(a: Dict[str, A], b: Dict[str, B]) \ -> Dict[str, Tuple[Optional[A], Optional[B]]]: """ Combine the values within two dictionaries ...
12c6e6c24069a35a7a3adf603b939cb0e27dcec1
judy1116/pythonDemo
/Included/use_collections.py
4,140
4.71875
5
#collections是Python内建的一个集合模块,提供了许多有用的集合类。 #######namedtuple####### #我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: #p = (1, 2) #但是,看到(1, 2),很难看出这个tuple是用来表示一个坐标的。 #定义一个class又小题大做了,这时,namedtuple就派上了用场: from collections import namedtuple Point=namedtuple('Point',['x','y']) p=Point(1,2) print(p.x) print(p.y) #namedtuple是...
d1fcd63229bb89f8cc5aaa45580404f7110f6335
judy1116/pythonDemo
/Included/use_htmlparser.py
2,592
3.765625
4
#如果我们要编写一个搜索引擎,第一步是用爬虫把目标网站的页面抓下来,第二步就是解析该HTML页面,看看里面的内容到底是新闻、图片还是视频。 #假设第一步已经完成了,第二步应该如何解析HTML呢? #HTML本质上是XML的子集,但是HTML的语法没有XML那么严格,所以不能用标准的DOM或SAX来解析HTML。 #好在Python提供了HTMLParser来非常方便地解析HTML,只需简单几行代码: from html.parser import HTMLParser from html.entities import name2codepoint class MyHTMLParser(HTMLParser): ...
6a69333f97b90987e027759c9e5cfd5229343526
judy1116/pythonDemo
/IO/use_json.py
3,286
3.890625
4
#如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。 #如何把Python对象变成一个JSON: import json d=dict(name='Bob',age=20,score=88) json_str=json.dumps(d) print(json_str) #dumps()方法返回一个str,内容就是标准的JSON。类似的,dump()方法可以直接把JSON写入一个fi...
0396aa2b1d5ef1e5ee8b546c705b7567a5818a5d
judy1116/pythonDemo
/FuncCode/returnFunc.py
2,466
3.8125
4
def calc_sum(*args): ax=0 for n in args: ax=ax+n return ax #但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数: def lazy_sum(*args): def sum(): ax=0 for n in args: ax=ax+n return ax return sum #当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数: f=lazy_s...
6f116aea385cd48f1081f76df2f993677343cedd
judy1116/pythonDemo
/Included/use_hashlib.py
3,189
3.5
4
#Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。 #什么是摘要算法呢?摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。 #举个例子,你写了一篇文章,内容是一个字符串'how to use python hashlib - by Michael',并附上这篇文章的摘要是'2d73d4f15c0db7f5ecb321b6a65e5d6d'。如果有人篡改了你的文章,并发表为'how to use python hashlib - by Bob',你可以一下子指出Bob篡改了你的文章,因为根据'how to use python has...
ed233aaf25be50af09dbdab1a274b9cff35a02b9
judy1116/pythonDemo
/AsyncIO/async_hello.py
1,742
3.546875
4
#asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。 #asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。 #用asyncio实现Hello world代码如下: #import asyncio #@asyncio.coroutine #def hello(): # print("Hello world!") # # 异步调用asyncio.sleep(1): # r=yield from asyncio.sleep(1) # pri...
dc6af3be13be922128409b78b11cec0001d236ae
judy1116/pythonDemo
/Tester/err_raise.py
2,257
4.15625
4
#因为错误是class,捕获一个错误就是捕获到该class的一个实例。因此,错误并不是凭空产生的,而是有意创建并抛出的。Python的内置函数会抛出很多类型的错误,我们自己编写的函数也可以抛出错误。 #如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例: # err_raise.py class FooError(ValueError): pass def foo(s): n = int(s) if n==0: raise FooError('invalid value: %s' % s) retu...
0359b15055f14630eac6508c0864216f3ad89225
judy1116/pythonDemo
/OOPAdvance/create_class_on_the_fly.py
2,151
4.375
4
#type() #动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。 #比方说我们要定义一个Hello的class,就写一个hello.py模块: class Hello(object): def hello(self,name='world'): print('Hello,%s.'%name) #当Python解释器载入hello模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个Hello的class对象,测试如下: #from hello import Hello h=Hello() print(h.hello()) print(t...
a2d0a206f388c10fa50dfc51041efd4fd85bc34b
judy1116/pythonDemo
/FuncCode/doSorted.py
886
4.375
4
#Python内置的sorted()函数就可以对list进行排序: print(sorted([36,5,-12,9,-21])) #sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序: print(sorted([36,5,-12,9,-21],key=abs)) print(sorted(['bob', 'about', 'Zoo', 'Credit'])) #我们给sorted传入key函数,即可实现忽略大小写的排序: print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower)) #要进行反向...
27e4ef0d8bb177a902727eabc24249c933fbb6e2
AO-AO/pyexercise
/ex8.py
653
4.4375
4
""" Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed. For example: anti_vowel("Hey You!") should return "Hy Y!". """ def anti_vowel(text): result = "" lenth = len(text) for i in xrange(0, lenth): if i == 0: r...
c0c029f57716b36ce683cb588bc35b018b7c2e56
mkarimawan/mk-hello-world
/rand_win.py
175
4.09375
4
import random num = random.randint(1,10) guess = int(input("Guess a number between 1 and 10:")) while guess!=num: guess = int(input('Guess again:')) print("You Win")
624e6d1c13f5feb448d3fa635ee38b66fe656a54
BillyHoyle15/Iris-Data-Set-KNN
/k-nearest-neighbours-byHand.py
5,736
3.875
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 23 12:56:47 2020 @author: Suat """ from collections import Counter import requests from typing import Dict,TypeVar, Tuple, NamedTuple, List import csv from collections import defaultdict import random import math #1 Creating a Vector Vector = List[floa...
ef086f2cbdedca7cd54c1a1e07e1636b5d8726c1
EthelEz/LearningHTML
/Learning_python/lists.py
774
3.78125
4
# list my_list = ['strangethings', 1, 5, 5, True, 'abcdf', [1, 2, 3, 'hi']] # list_extend = ['d','s','l'] # my_list.extend(list_extend) # print(my_list) # # print(len(my_list)) # # print(my_list[0:4]) # # print(my_list[0::5]) print(my_list[6][3]) # List are totally immutable, meaning you can add sth to the List pos...
81a0c0bb3fdd40a50e01c20d6f92161983633c0a
ColinBurch/class-work
/Data/8.6.py
292
3.9375
4
mlist = [] while True: test = input("Enter a number: ") if test == "done" : break try: num = float(test) except: print("Invalid input") continue x = mlist.append(num) print(mlist) print("Maximum:", max(mlist)) print("Minimum:", min(mlist))
0e903fd0b25494c990e70d8ac8437b52b9ec2b2e
H0bbitBaron/SeaLions_2_lopuhin
/Code/average_submissions.py
460
3.5
4
#!/usr/bin/env python3 import argparse import pandas as pd def main(): parser = argparse.ArgumentParser() parser.add_argument('inputs', nargs='+') parser.add_argument('output') args = parser.parse_args() inputs = [pd.read_csv(fname, index_col=0) for fname in args.inputs] output = sum(df / len...
3d705a2a9c2a61d893691a9a531e40e1a3ff8aac
NicoFHNS/Travelling-Sallesman-Problem--Graphic-Theory
/Travelling-Sallesman-Problem/NextNeighboor.py
1,789
3.53125
4
import sys def nearestNeighbor(matrix, source): # escolhe um vértice arbitrário como vértice atual verticeAtual = source # descobre a aresta de menor peso que seja conectada ao vértice atual e a um vértice não visitado V distanciaProximo = sys.maxsize proximoVertice = 0 verticeVisit...
63f26a31699118381a0fb5add1945285391e3efa
Sikae/MIT6002x
/lecture_04_problem_03.py
591
3.953125
4
''' Created on Mar 17, 2015 @author: nanci ''' def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ n = len(L) mean = 0 summ = 0 if n == 0: return float('NaN') else: fo...
6dad0e0b1ac99cd489e20a297b8b9929a6d8b77e
Trollernator/Lesson
/app.py
929
4.25
4
#variable #data types int, float, str #input(), print(), type() # len() shows the lenght of str # upper() makes the letters BIG # lower() makes the letters smol # capitalize() captitalize the first letter # replace() replace certain letters # FirstName="Tom" # print(FirstName.find("enter search")) # a=58 # b=108 # if ...
df6dc1e87f1a2861224107bbba1c901a0b89e094
rajeshvermadav/XI_2020
/character_demo.py
376
4.3125
4
#program to display indivual character name = input("Enter any name") print("Lenght of the string is :", len(name)) print("Location or memmory address of the Character :",len(name)-1) print("Character is :", name[len(name)-6]) print("Substring is :",name[1]) print("Substring is :",name[-1]) print("Substring ...
c95d113b4a432c952b188a1542ba9719f44b3dc8
rajeshvermadav/XI_2020
/controlstatements/loop_for.py
106
3.59375
4
# For loop a=0 s=0 for a in range(1,11): s += a print(a) print("Sum of Series %s " %s)
9f31d5cf063ae55d50193cd9c8c43d84e69501b9
rajeshvermadav/XI_2020
/sampleif_else.py
266
4.09375
4
# Sample program if-else conditional statement price = float(input("Enter a price")) qty = float(input("Enter Quantity")) amt = price*qty if amt>1000: disc = amt*0.10 print("Discount", disc) else: disc= amt * 0.05 print("Discount", disc)
407163916887e91d39c5c0f3bfa465a767f37433
rajeshvermadav/XI_2020
/logicaloper_demo.py
149
4.28125
4
#Demonstration of logical operator x = 2 y = 3 print("X and Y is :-", x and y) print("X or Y is :-", x or y) print(" not x is :-", not x)
d355a51296d2bb643bb9d3354b6cd6e6688b6d68
rajeshvermadav/XI_2020
/mathlib_demo.py
164
3.984375
4
#Demo math module import math a = float(input("Enter any Number:-")) print("Square Root of a number:",math.sqrt(a)) print("integers is", math.ceil(a))
f9f878b732c90b1f9848a939d4810eae5f1030bd
rajeshvermadav/XI_2020
/DIct/contactdict.py
271
3.515625
4
dict = {'Pranav':8544704526,'Pranjal':7018778837,'Raman':9287529827,'devansh':82788838909, 'Rashi':7650011336,'Monaal':9816626090, 'Ansh':6239113947, 'Sanehil':7807693372, 'Ridhi':8219227595} l = list(dict) for i in dict: print(i, ":", dict[i])
01b8d492db475863eda099b6540c08ec8caf6169
rajeshvermadav/XI_2020
/swap_demo.py
236
4
4
#Input two numbers and swap them a = int(input("Enter First Number:-")) b = int(input("Enter Second Number:-")) print("Orignal numbers are :",a,b) a, b = b, a print("Swapped numbers:-", a, b)
841d3b45c6dd57d8fccbfcc984c26677fe96107e
rajeshvermadav/XI_2020
/relationoper_demo.py
414
4.1875
4
#Relational Operator Demo Program a = int(input("Enter First Number:-")) b = int(input("Enter Second Number:-")) print("A>B is :", a>b) #Greater than print("A<B is :", a<b) #Less than print("A===B is :", a==b) #Equal to print("A!=B is :", a!=b) #Not equal to print("A>=B is ...
bfa1a6fa17cbb9cbc0e8028f4454b3bb482dcbd2
rajeshvermadav/XI_2020
/error1.py
173
3.75
4
#num_1 = 546 #num_2 = '786' #print (num_1 + num_2) x = 10 def func(num): x = 5 for i in num: x*=i return(x) print(func((-2, -1, 1, 2, 3)))
4849a377f3eb05b5e074e959b1aaf16793754daf
rajeshvermadav/XI_2020
/sample3no_if.py
498
4.15625
4
#Program to input three numbers calculate sum of numbers and non duplicate numbers s1 = s2 = 0 a = int(input("Enter first number: ")) b = int(input("Enter Second number: ")) c = int(input("Enter Third number: ")) s1 = a + b + c if a != b and a != c: s2= s2 + a print(a) if b!= a and b != c: s2 = s2 ...
cdc710c7c64c2029fa2b53f210689162fcaf1931
acs/python-red
/leetcode/two-sum/two-sum.py
746
4.15625
4
from typing import List, Tuple def twoSum(nums, target): twoSumTargetTuples = [] for (i, number) in enumerate(nums): for otherNumber in nums[i+1:]: print(number, otherNumber) # Move this logic to a function if (number + otherNumber) == target: if [nu...
7f8b3ceeff28f59b0b186d3b3dbd8a7bafd24fdc
Environmental-Informatics/building-more-complex-programs-with-python-roccabye
/Program_7.1.py
2,669
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 28 09:55:50 2020 Lab Assignment02 ThinkPython 2e, Chapter 7: Exercise 7.1 This program finds the Square Root of a number by using the famous newton's Method approach and using the function from 'math' library. And compares the absolute values estimat...
bfdc1c6f53a6f5bd20e961768c3ad0ad19998a88
VishnuArukat/pythoncodepool
/python-algo/MazeProblem.py
1,664
3.90625
4
class Mazeproblem: def __init__(self , mazeTable): self.mazeTable = mazeTable self.mazeSize = len(mazeTable) self.solutionTable = [[0]*self.mazeSize for i in xrange(self.mazeSize)] def solveMaze(self): if not self.solve(0,0): print "no feasile solution has found" else: self.showResu...
f978d756c3c9145673ac18546b4a088a1bf434b5
RedOneLima/Appointment-Scheduler
/TCP_Client_OSScheduler.py
3,100
3.515625
4
import socket #setting up socket information HOST, PORT = "localhost", 4445 data = '' #Create socket where SOCK_STREAM indicates a TCP connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((HOST, PORT)) except socket.error: print socket.error else: #Take in PPI print 'He...
c727db2cfb9ddf83566b4b028f3e96f02fe03c51
lluxury/pcc_exercise
/05/age.py
297
4.09375
4
age = 68 if age < 2: print("he is a baby") elif age >=2 and age <4: print("he walk") elif age >=4 and age <13: print("he is a children") elif age >=13 and age <20: print("he is a teen-ageer") elif age >=20 and age <65: print("he is a human") else: print("he is older")
f5e05cde5ad827f29bb779c6a572903589fed88c
lluxury/pcc_exercise
/06/friend2.py
426
3.96875
4
friend = {'first_name': 'li', 'last_name': 'cl','age': '28', 'city':'sh'} friend2 = {'first_name': 'li2', 'last_name': 'cl2','age': '28', 'city':'sh'} friend3 = {'first_name': 'li3', 'last_name': 'cl3','age': '28', 'city':'sh'} friend_all = [friend,friend2,friend3] # print(friend['first_name']) # print(friend['last_na...
d04ad65740ce3c2b1b5d60a128b97b9f00fc6a59
lluxury/pcc_exercise
/07/pizza_ingredents.py
220
3.953125
4
prompt = "\nWhat kind of ingredients do you want " prompt += "\nEnter 'quit' to end of program." messeage = "" while messeage !='quit': messeage = input(prompt) print("We will add "+ messeage + " with you pizza")
0e441dfc71ea697abd409c6985bbac2ac55d5b3d
lluxury/pcc_exercise
/09/Restaurant.py
2,058
3.84375
4
class Restaurant(): """固定的值在函数入口的参数里没有""" def __init__(self, restaurant_name, cuisine_type): #super(Restaurant, self).__init__() self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_user(self): '''描述''' p...
b90629782f0675be59007ff080970ebdce00ad83
mavis0/LeetCode
/Binary Tree Zigzag Level Order Traversal.py
710
3.71875
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 zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root...
72b2d5bc89f043db6d38bba671f512cbd15c4f44
mavis0/LeetCode
/Unique Binary Search Trees II.py
813
3.8125
4
from binary_tree import TreeNode class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ def dfs(l): if not l: return [] if len(l) == 1: return [TreeNode(l[0])] res = list() for i in l: ...
af6810bf97af2a356cc49fa29714030000ab1719
mavis0/LeetCode
/Binary Tree Paths.py
736
3.9375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from binary_tree import Tree class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: Li...
46ebac48b5a470e893f873082c7977e11a463e34
mavis0/LeetCode
/Palindrome Linked List.py
1,246
3.78125
4
class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ def reverse(h): first, second = None, h while second: tmp = second.next second.next = first first, second = ...
84f361ade8c97b861f0330fad2630271f27f29ae
mavis0/LeetCode
/Sort Colors.py
635
3.65625
4
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums: return nums l, r, mid = 0, len(nums) - 1, 0 while mid <= r: if nums[mid] == 0: ...
049782b6fcbcf0a53e0c4fef6f2dffaf80c645f2
mavis0/LeetCode
/Permutations.py
500
3.53125
4
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans = list() if len(nums) == 1 or len(nums) == 0: return [nums] else: for i in self.permute(nums[:-1]): for j in rang...
2612849dafc12af4212a5de015e82f01a2107f57
Mask-of-the-Fractal-Abyss/Mail-Matcher
/emailtest.py
1,888
3.578125
4
from users import * import datetime ##send("kebabbles", 'Jake') introEmail = """ Hello, %s! You've been matched with %s from %s! Say hi at: %s They are interested in: %s Here is their introduction: %s """ applicationEmail = """ So far I plan to match everyone with one other person automatically, exactly once a wee...
9655142b6fb6c6428666d899f345c376a61deeb1
crazy1235/PythonPracticeProject
/day9/__init__.py
3,311
3.84375
4
# -*- coding: utf-8 -*- import math # 高阶函数 print '------------- 高阶函数 ----------------' # 能接受函数做参数的函数叫做高阶函数 def add(x, y, f): return f(x) + f(y) print add(1, -3, abs) print add(25, 9, math.sqrt) # math.sqrt() 的结果是浮点数 # map()函数 print '------------- map()函数 ----------------' def sqrtList(x): return x * ...
ff4e545ef4de457d99f879146de806112f7e9572
crazy1235/PythonPracticeProject
/day6/__init__.py
1,417
3.984375
4
# -*- coding: utf-8 -*- # 切片-slice print '------------- 切片 ----------------' L = ['Adam', 'Lisa', 'Bart', 'Paul'] print L r = [] for i in range(3): r.append(L[i]) print r print '----- Python提供了切片(Slice)操作符 ----' print 'L[a:b]表示取出从索引a到索引b的元素,但是不包括索引b' print L[0:3] print L[0:5] print 'L[:]实际上表示赋值出来一个新的list' prin...
625bb153accfda34c902d72660a5417cc542dc45
Nortsev/WhoIs_Blogger_task
/Task_1/create_data_base.py
2,557
3.78125
4
import sqlite3 import json # Указание файла базы данных database_file = "database.db" # Определенние скрипта создания таблиц в базе данных sql_create = """ CREATE TABLE IF NOT EXISTS Users( userId INTEGER PRIMARY KEY, age INTEGER NOT NULL ); CREATE TABL...
88590a9117a88959a4bee64971c12fec92dac564
Roby5791/Image-processing-tool-in-python
/Part 1/tests/scale_Fichiers_image.py
4,942
3.703125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 16:18:10 2021 @author: boris """ #Visualisation: on importe matplotlib import matplotlib.pyplot as plt import matplotlib.image as mpimg import argparse import os import sys parser = argparse.ArgumentParser() parser.add_argument("imageName", help=...
9628b723ac7573a5f04a7e89c1bd5b2900efa73a
suryavipin42/PythonProjects
/FlowControl/Looping/NumPattern.py
202
3.796875
4
l=int(input("limit")) for i in range(0,l): for j in range(1,i+2): print(j, end="\t") print() for i in range(3,0,-1): for j in range(1, i + 1): print(j, end="\t") print()
a75b412b1e543fc4441f7a73b49c5b3e9666bd39
suryavipin42/PythonProjects
/Function/MathsOperations.py
190
3.625
4
def add(num1,num2): return(num1+num2) def subtract(num1,num2): return(num1-num2) def multilply(num1,num2): return(num1*num2) def division(num1,num2): return(num1/num2)
188991a1e9774e63fc9f47d094ec5af1d1c383ca
suryavipin42/PythonProjects
/FlowControl/Looping/Reverse.py
150
4.03125
4
num=int(input("enter the num")) reverse=0 reminder=0 while(num>0): reminder= num%10 reverse=reverse*10+reminder num=num//10 print(reverse)
92f175de71deb8b462bd48ab8f8b7ddcf975fbb8
Ilissi/project_sheet_bot
/utils/date_pattern.py
904
3.53125
4
from datetime import datetime def check_date(line): try: two_date_str = line.split('/') one_date = two_date_str[0].split('-') second_date = two_date_str[1].split('-') one_datetime = datetime(int(one_date[2]), int(one_date[1]), int(one_date[0])) second_datetime = datetime(in...
89c9c32c1a40c5a826266d6378b30659a3d2c579
mato07/Vaja8-domaca_naloga
/pretvornik_enot.py
1,203
3.6875
4
# -*- coding: utf-8 -*- #Pretvornik iz kilometrov v milje in obratno print "Pozdravljen, sem pretvornik razdalje iz kilometrov v milje in nazaj." pretvornik = 1.6 while True: razdalja = float(raw_input("Vnesi razdaljo, ki jo želiš pretvoriti: ")) pogoj = int(raw_input("Za pretvorbo iz km v milje vnesi 0, za ...
59ef933c2c1bde0c3c78e560d439885b555c114f
skiry/Advent-of-Code
/AoC20/Day05/part2.py
495
3.546875
4
def main(): maxSeat = 0 seats = set() while True: try: line = input() f, b = 0, 127 for s in line[:7]: if s == 'F': b = (f + b) // 2 else: f = (f + b) // 2 + 1 l, r = 0, 7 for s in line[7:]: if s == 'R': l = (l + r) // 2 + 1 else: r = (l + r) // 2 maxSeat = max...
e57f84186c3130728985c85c7c67c4c54efb1646
skiry/Advent-of-Code
/AoC19/Day03/part1.py
1,136
3.84375
4
import heapq first_wire = input().split(',') second_wire = input().split(',') def find_closest_point(first_wire, second_wire): visited = {} row, column = 0, 0 for action in first_wire: move = action[0] times = int(action[1:]) while times: if move == 'D': ...
f1f80869b3845e44d0fd8a97400dff98c2422f63
motoyasu-saburi/python-sand
/list.py
1,300
3.84375
4
seq = [0, 1, 2, 3, 5] print(seq[:]) a = ["a", "b", "c"] b = [1, 2, 3, 4] c = [a, b] print(c) """ # Multiple Comment List Method .append(x) .extend(iterable) .insert(index, x) .remove(index) .pop([index]) # remove and return target(index). .clear() .index(x[, start[, end]]) # リスト中で x と等しい値を持つ最初...
bb81b13754d9549122d7816c8d5f0fb026f28a8a
yalilu/GitHubApi567
/homework04.py
615
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 19 10:10:37 2019 @author: luyali """ import requests import json '''response_list=[]''' repo_dict={} url = 'https://api.github.com/users/yalilu/repos' r=requests.get(url) print(r.status_code) print("The user has "+str(len(r.json())) + " repos, na...
1d21943dace332bd3f0e6a601808cdbb9bf9fe72
Gchesta/assignment_day_2
/fizz_buzz.py
341
4.1875
4
def fizz_buzz(entry): if entry % 3 == 0 and entry % 5 == 0: #tests for numbers that are divisible by both three and five return "FizzBuzz" elif entry % 3 == 0: #tests for numbers that are divisible by three return "Fizz" elif entry % 5 == 0: #tests for numbers that are divisible by five return "Buzz" e...
d6aa20a31894a3f6e94e0d964de05c0e2c232f50
RuthieRNewman/hash-practice
/hash_practice/exercises.py
2,735
4.125
4
#This is a solution that I worked out with a study group hosted by a TA and Al. It was working #until I made some changes and now I cant seem to figure out what I did or how it was #really working in the first place. I will continue to work on it but I didnt feel it was worthy #turning in fully. def anagram_he...
80eda122c5cd045a6b367fa270134bd2bcdd6e76
omerfarballi/Python-Dersleri
/32.while.py
282
3.71875
4
# liste = [0,1,2,3,4,5,6] #0-1000'e kadar liste istersem # x =0 # number = [] # while x < 1000: # # print(x) # number.append(x) # x = x + 1 # print(number) # name = ''#false # while not name.strip(): # name = input("İsminizi Giriniz : ") # print("Merhaba",name)
37520272676eb137a4052d12515e798c5c3ea47e
omerfarballi/Python-Dersleri
/38.loops-demo-2.py
519
4.03125
4
""" Girilen bir sayının asal saı olup olmadığını kontrol ediniz. *** Asal sayılar sadece kendilerine ve 1'e bölünebilen sayılardır.*** 3 asaldır. 1 sayısı asal değildir. """ number = int(input("Sayi : ")) asalmi = True if number == 1: asalmi = False for i in range(2,number): ...
13d1492b000fc3d3e6ea31c3cd0182b3d8edf9d0
omerfarballi/Python-Dersleri
/27.if-elif-else.py
491
3.953125
4
# number1 = int(input("Birinci sayıyı giriniz : ")) # number2 = int(input("İkinci sayıyı giriniz : ")) # if (number1>number2): # print("number1 number2 dan büyüktür.") # elif (number2 == number1): # print("İki sayı birbirine eşittir.") # else: # print("number1 number2 dan küçüktür.") number = int(i...
ae554658c85861388c84519646c248ce41bb25f4
omerfarballi/Python-Dersleri
/35.for-while-methods.py
365
4
4
# range() # number = [] # for x in range(0,10,2): # number.append(x) # print(number) # print(list(range(0,10000,2))) #enumerate # index = 0 name = 'Ömer' for index,letter in enumerate(name) : print(index,' ',letter) # index += 1 #zip liste1 = [0,1,2,3,4,5,6] liste2 = ['a','b','c','d','e','...
8551e2b1b35760a94d48e9c6ab1d169af08124bb
kod3r/bacon
/bacon.py
2,261
3.8125
4
import cPickle import bacon_functions if __name__ == "__main__": # Loading the pickled data structure of actors to movies print 'Loading the pickled data structure of actors to movies ...' with open('actors_to_movies') as pickled_actors_to_movies: actors_to_movies = cPickle.load(pickled_...
b883c7713564e607c2330d9d4865d5775344862d
mauerflitza/Datalogger
/Webpage/cgi-bin/cgi_skelett.py
1,271
3.578125
4
#!/usr/bin/python3 import cgi # NEW def main(): # NEW except for the call to processInput form = cgi.FieldStorage() # standard cgi script lines to here! # use format of next two lines with YOUR names and default data numStr1 = form.getfirst("x", "0") # get the form value associated with form ...
ad9625615c7da54b04acf367158240bbdb395cdc
whirlyNerd/py
/function_param.py
228
4.09375
4
def print_max(a,b): if a > b: print a, 'is maximum' elif a == b: print a, 'is equal to', b else: print b, 'is maximum' # directly pass values print_max(3,4) x = 5 y = 7 # pass variables as arguments print_max(x,y)
7872cfafa24f7618be0b7c82bce5cd58d5a63689
whirlyNerd/py
/turtleSquare.py
248
3.5625
4
from swampy.TurtleWorld import * world = TurtleWorld() t = Turtle() length = int(raw_input('Enter the side length for the square:')) def square(t): print t for i in range(4): fd(t,length) lt(t) square(t) wait_for_user()
61046218e69419313128dffb777ed1e9e6af4102
sppghost/leetcode_python
/second.py
1,208
3.765625
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 maxLevelSum(self, root: TreeNode) -> int: max_level_sum = root.val max_level = 1 curr_le...
a07b1b727d557133e80c05df7d7ab83c8b7bcc15
sppghost/leetcode_python
/third.py
1,622
4.0625
4
class TrieNode: def __init__(self, ch: str): self.ch = ch self.nxt = {} self.is_end = False class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode('#') def addWord(self, word: str) -> None: ...
58dc60e1c98e13ca9e734597241818986edb1a03
b-ark/lesson_14
/Task3.py
1,625
3.765625
4
# Write a decorator `arg_rules` that validates arguments passed to the function. # # A decorator should take 3 arguments: # max_length: 15 # type_: str # contains: [] - list of symbols that an argument should contain # # If some of the rules' checks returns False, the function should return False and print the reason i...
e4245eb564efea657c95875a60b037e53cce5f17
angminsheng/python-learn
/type-hinting.py
130
3.5625
4
from typing import List def list_avg(sequence: List) -> float: return sum(sequence) / len(sequence) print(list_avg((1,2,4,5)))
3fe252eb942a4a4f93e6a14250260a59d5468232
angminsheng/python-learn
/string-template.py
399
3.9375
4
x = 15 price = 9.99 result = price * x # two ways of creating dynamic String template name = "Bob" greeting = f"Hello,{name}" name = "John" longer_phrase = "Hello {} and {}" greet = longer_phrase.format("rolf", "sally") # user input size_input = input("How long is your ruler (m)?") size_m = float(size_input) size_cm...
f43686010662ea48a1eb685b277f3b991b2d9092
angminsheng/python-learn
/data-type.py
983
4.15625
4
user_age = int(input("What is your age?")) user_age_month = user_age * 12 print(f"you are {user_age}years old or {user_age_month} months old.") l = ["bob", "john", "sally"] t = ("bob", "john", "sally") h = {"bob", "john", "sally"} l.append("rosie") h.add("molly") friends = {"bob", "ken" , "simon"} other_friends = {...
faee95b97c801ae6f22112f7cf3a83926ddbedb4
Yash-07C/Python-Codes
/Item Stock/code/itemstock.py
576
3.8125
4
item_number=[101,102,103,104] item_name=['Milk','Cheese','Ghee','Bread'] item_price=[42,50,500,40] item_stock=[10,20,15,16] itemnum=int(input()) item_quantity=int(input()) try: index=item_number.index(itemnum) except ValueError: print("Invalid input") exit() if item_quantity<=item_stock[index]: ...
c10889d1d20c9c4c4eaf392493a9b794a7efe055
zarcaxm/Number-of-days-we-lived
/Number of days we lived.py
230
3.84375
4
__author__ = 'zarcaxm' import datetime userinfo=input("When did u born?(dd/mm/yyyy)") #convert userinfo bday = datetime.datetime.strptime(userinfo,"%d/%m/%Y").date() today = datetime.date.today() days = today - bday print(days)
887bda0aae2e0b3bdbebc95c498889e49d49a616
Songbz1999/pythonForFinance
/lesson2/Numpy exercises.py
1,743
3.890625
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 12 19:45:31 2018 @author: Thinkpad """ ''' Numpy exercises: 1. Create a null vector of size 10 but the fifth value which is 1 2. Create a vector with values ranging from 10 to 49 3. Reverse a vector (first element becomes last) 4. Create a 3x3 matrix with values ranging...
040b975f732219e548b55157d75995004ad65396
espdev/scikit-curve
/skcurve/curves.py
4,316
3.765625
4
# -*- coding: utf-8 -*- """ The module provides parametric equations for well-known curves """ import numpy as np from scipy.special import fresnel from skcurve import Curve def arc(t_start: float = 0.0, t_stop: float = np.pi * 2, p_count: int = 49, r: float = 1.0, c: float = 0.0) ...
f6d376b2abb51d2d64d60b8d0351aea80ccbe80b
espdev/scikit-curve
/skcurve/_numeric.py
3,284
3.640625
4
# -*- coding: utf-8 -*- """ The module provides numeric routines """ import typing as ty import numpy as np F_EPS = np.finfo(np.float64).eps def isequal(obj1: np.ndarray, obj2: np.ndarray, **kwargs) -> np.ndarray: """Returns a boolean array where two arrays are element-wise equal Notes ----- int...
b8ae50cdb4f72a2c4f7ef6900ac45c0d0766eaa6
lsst-camera-dh/EO-utilities
/python/lsst/eo_utils/base/stat_utils.py
5,329
3.71875
4
"""Functions to help with statistics and fitting""" import numpy as np import scipy.optimize from scipy.special import erf SQRT2 = np.sqrt(2) def gauss_intergral(xval, norm, x_0, sigmax): """Integrate Gaussian centered at (x0) with width sigmax Parameters ---------- xval : `array` The bin ...
cf7dd961149974adef27aa66e63c95a085ca6783
alex9609/Analisis-Numerico-Copy-
/Numéro de Condición.py
994
3.53125
4
# Librería numpy import numpy as np from time import* print('NUMÉRO DE CONDICIÓN',end="\n\n") print("Este algoritmo te permite hallar el numero de condición de una matriz ya sea por su norma infinita o por su norma 1") # Coloca la matriz A: A = np.array([[1,1,1,1], [8,4,2,1], [3,2,1,0], [12,2,...
dbf59f857655bb4da6089567e3adb962a8074a13
markomav/Wave-1
/Time1.py
645
4.0625
4
days = int(input('days: ')) hours = int(input('hours: ')) minutes = int(input('minutes: ')) seconds = int(input('seconds: ')) nice = True if hours > 24: print('There are only 24 hours in a day!') if nice == True: nice = False if minutes > 60: print('There are only 60 minutes in an hour!') if nic...
0e698a4cb26fcc42af0edeeef90f5506343e86c9
shood2/ImageFilters
/testPillow.py
5,373
3.5
4
from PIL import Image, ImageDraw, ImageFont ################################ ###### Image Loading ########### ################################ #takes a filename #returns an image type def load_img(filename): img = Image.open(filename) return img #takes an image type #displays image def show_img(im): im.show() ...