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
ca085503f1201b2efe4c6ddd0340650a052d0886
filaone/codewars
/python_skills/027_beginning_patterns.py
685
3.703125
4
#!/usr/bin/python #-*- coding: utf-8 -*- import re string_1 = """helloo hello helloooo world world worlds world""" pattern_1 = re.compile(r'\Ahello+') pattern_2 = re.compile('^hello+') pattern_3 = re.compile(r'hello') pattern_4 = re.compile(r'hello$') pattern_5 = re.compile(r'hello\Z') print pattern_1.findall(s...
97852be09b3fc36ea72a874757b1867db5aa5ef1
filaone/codewars
/python_skills/024_repeat_string.py
139
3.703125
4
#!/usr/bin/python #-*- coding: utf-8 -*- s = "hello world" print s[:6]*2 print 2*s print ' '.join((s[:]) * 2) print ' '.join([s[:]] * 2)
c83519e4a005ea48662883818eb4de74e0f26411
miko13/implement-hashmap
/hashmap/hash_map_tests.py
2,695
3.546875
4
import unittest from hash_map import MyHashMap class MyHashMapTests(unittest.TestCase): def setUp(self): self.hashmap = MyHashMap(5) def tearDown(self): self.hashmap = None def initialize_hashmap(self): empty_hashmap = MyHashMap(10) self.assertEqual(empty_hashmap, 10) ...
109fdc8a373f6c021e45af029d0d39b4e970c60e
vaynexie/Leetcode-Algorithm
/125. Valid Palindrome_e.py
721
3.546875
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ final=False s_low=s.lower() result='' for i in range(len(s_low)): if not s_low[i] in string.punctuation + ' ': result += s_low[i] ...
2a2c049faf91510a747b8aba3a32a223ab08ac3b
vhjmlw/Learn-Python
/day14/Iterable-Iterator.py
443
3.796875
4
# -*- coding:utf-8 -*- "Iterable和Iterator的区别" __author__ = '建磊' from collections import Iterable,Iterator print(isinstance('123',Iterable)) print(isinstance([1,2,3],Iterable)) print(isinstance((1,2,3),Iterable)) print(isinstance({'name':'jianlei'},Iterable)) print(isinstance({1,2,3},Iterable)) print(isinstance...
e21b27885f9ea89f9e355a73df51c3bae259a48f
vhjmlw/Learn-Python
/day18/死锁.py
822
3.640625
4
# -*- coding:utf-8 -*- '死锁' __author__ = '建磊' from threading import Thread from threading import Lock import time def main(): def fn1(): if lock1.acquire(): print('fn1中的lock1上锁成功') time.sleep(1) if lock2.acquire(): print('fn1中的lock2上锁成功') ...
a15564743dba3692d6853dfccfe66097ec41f664
vhjmlw/Learn-Python
/day18/死锁2.py
1,032
3.734375
4
# -*- coding:utf-8 -*- '死锁' __author__ = '建磊' import time from threading import Thread from threading import Lock def main(): class Task1(Thread): def run(self): while True: if lock1.acquire(): print('task1') time.sleep(1) ...
151f08bd1757498c9191520233c2faf62249573f
vhjmlw/Learn-Python
/day14/裴波那切数列3.py
249
3.71875
4
# -*- coding:utf-8 -*- '使用生成器实现裴波那切数列' __author__ = '建磊' def fib(n): m = 0 a,b = 0,1 while m < n: yield b a,b = b,a+b m += 1 generator = fib(10) for x in generator: print(x)
104a17a86916765a129e61f0305d843ac3c55636
vhjmlw/Learn-Python
/day18/生产者消费者模式.py
1,318
3.875
4
# -*- coding:utf-8 -*- '生产者消费者模式' __author__ = '建磊' from threading import Thread from threading import Lock import time from queue import Queue que = Queue() def main(): class Producer(Thread): def run(self): global que while True: if que.qsize() < 1000: ...
26b3a546f7b920277e7ab29a7c2aa6fe08721a95
vhjmlw/Learn-Python
/day17/Queue进程间通讯Process.py
717
3.5625
4
# -*- coding:utf-8 -*- "使用Queue实现进程间通讯Process创建子进程" __author__ = '建磊' from multiprocessing import Process,Queue def read(queue): for x in ['a','b','c','d']: queue.put(x) def write(queue): # for x in range(queue.qsize()): #为啥queue.qsize()报错??? # tmp = queue.get() # print(tmp) whi...
8ede491c23cd40707bd0c8589b066a2d136f4418
MaiShantanuHu/Coursera-Python-3-Programming
/Python Classes and Inheritance/Week One/Week One.py
1,031
3.828125
4
#Q-1. class Bike: def __init__(self, color, price): self.color = color self.price = price testOne = Bike("blue", 89.99) testTwo = Bike("purple", 25.0) #Q-2. class AppleBasket: def __init__(self, apple_color, apple_quantity): self.apple_color = apple_colo...
19387fd2d7095b98e0492d1e93bd8f98001d8cf1
MaiShantanuHu/Coursera-Python-3-Programming
/Python-Basics/Week-2/Lists and Strings.py
1,622
4.21875
4
'''Q-1: What will the output be for the following code?''' let = "z" let_two = "p" c = let_two + let m = c*5 print(m) #Answer: # pzpzpzpzpz '''Q-2: Write a program that extracts the last three items in the list sports and assigns it to the variable last. Make sure to write your code so that it work...
ab9ab35575b2ef50642cac645b614737872b09c8
ksoftlabs/labsheets1001
/Tutorial 2/Tutorial 2 Activity 9.py
102
3.9375
4
C=float(input("Enter the temperature in Celsius :")) F=(C*9/5)+32 print(C,"Celsius =",F,"Fahrenheit")
a401d2cc87b01db05bb3fa50ef3680f7d2766a10
ksoftlabs/labsheets1001
/Sorting/Selection Sort/Selection Sort.py
373
4
4
list=[33,2,15,89,489,46486,21,25,24] print("The unsorted list is as follows",list) for i in range(8,0,-1): maxIndex=0 for location in range(1,i+1): if list[location]>list[maxIndex]: maxIndex = location #swapping temp = list[i] list[i] = list[maxIndex] list[maxIndex] = temp prin...
88aa8d4f5e4c0db6bc03e01b37b1b81e5419b3fa
dtulett15/5_digit_seperator
/3digit_seperator.py
300
4.28125
4
#seperate three digits in a three digit number entered by user #get number from user num = int(input('Enter a 3 digit number: ')) #set hundreds digit num1 = num // 100 #set tens digit num2 = num % 100 // 10 #set ones digit num3 = num % 10 #seperate digits print(num1, ' ', num2, ' ', num3)
f0bc7e511fdc5b7c2f131cf6b0a13fd547572b83
tl-mark/sorted
/sort.py
6,601
3.90625
4
#不稳定排序:(希尔,选择,堆,快速)排序 #冒泡排序 稳定 时间复杂度:平均n平方,最坏n平方,最好n def bottlSorted(a): n = len(a)#列表长度 for i in range(n-1): for j in range(i+1,n): if a[i] > a[j]: a[i],a[j] = a[j],a[i] # while 1: # state = 0 # 假设本次循环没有改变 # for i in range(len(a) - 1): # ...
9c2987a4dc6565034ae0ee703a4af1175d409d22
shahzeb-jadoon/Euclids-Algorithm
/greatest_common_divisor.py
691
4.375
4
def greatest_common_divisor(larger_num, smaller_num): """This function uses Euclid's algorithm to calculate the Greatest Common Divisor of two non-negative integers pre: larger_num & smaller_num are both non-negative integers, and larger_num > smaller_num post: returns the greatest com...
873a3801db68683d1551df016016074821335284
Meghna-U/posList.py
/posList.py
215
4.125
4
list=[] s=int(input("Enter number of elements in list:")) print("Enter elements of list:") for x in range(0,s): element=int(input()) list.append(element) for a in list: if a>0: print(a)
485799f9a8d7d5e54f2648c0780228cbf6e13e9b
panmak93/Anagram-Parts
/AnagramParts.py
721
3.828125
4
""" Name: Cheuk Pan, Mak Compsci 220 Assignment 2 """ import sys class Assignment2: def anagram(words): list_dict = dict() for word in words: word1 = "".join(sorted(word)) if word1 not in list_dict: list_dict[word1] = [word] else: list_dict[word1] += [word] output_list = list() for key in lis...
b088d63f6224b4081924db231b5f058b78498171
aastha2008/C1-Turtle
/main.py
1,993
4.59375
5
''' 03/22/2021 Introduction to Turtle # 1. Import turtle library import turtle # 2. Create a pen/turtle variable=turtle.Turtle() # 3. Create a paper/screen variable2 = turtle.Screen() # 4. Movements a. Move forward variable1.forward(DISTANCE) variable1.fd(DISTANCE) b. Move backward variable1.ba...
8b2619927e93fa3b97f834361e5885942606d389
hermann225-zrouama/leetcode_problem
/construction_tree_with_inorder_and_postorder.py
1,269
3.796875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ Ce problème peut être facilement résolu en utilisant une méthode récursive. Étant donné les listes inorder et postorder de l'arbre, ie inorder[1..n]et postorder[1..n], postorder[n]devrait être la vale...
878e331711e7c6111a6d6dc647e0954d948a016e
lars-petter-hauge/aoc
/2019/python/day1/day1.py
582
3.609375
4
import math def parse_input(fname): with open(fname) as f: data = f.readlines() data = [int(d) for d in data] return data def calc_fuel_amount(mass): return math.floor((mass / 3)) - 2 def calc_fuel_amount_recursive(mass): if mass <= 5: return 0 fuel_req = math.floor((mass ...
50402d641ec17fbf690d9d0dc2a58ed7f9826673
lars-petter-hauge/aoc
/2022/python/day8/day8.py
5,262
3.6875
4
TEST_INPUT = """30373 25512 65332 33549 35390""" import itertools import math from collections.abc import Iterable from functools import singledispatch flatten = itertools.chain.from_iterable def load_input(fname): with open(fname) as fh: return [l.strip() for l in fh.readlines()] def rotate_grid(grid...
6201d749aa88c59fd8b541d453977c95bf2a1ed6
william-richard/BowdoinMath252
/elliptic_curve_factoring.py
3,026
3.953125
4
from fractions import gcd def extEuclideanAlg(a, b) : """Computes a solution to a x + b y = gcd(a,b), as well as gcd(a,b) """ if b == 0 : return 1,0,a else : x, y, gcd = extEuclideanAlg(b, a % b) return y, x - y * (a // b),gcd def modInvEuclid(a,m) : """Computes the modular multiplicative...
733b857255afa8a745fbfc259462f95cec72eef0
william-richard/BowdoinMath252
/unnamed_primality.py
2,207
3.78125
4
import sys import math import trial_division from pow_mod import modOfPower def test(n, print_info): #set up a dictonary to store the prime factors and their exponent #the key is the factor, the values are the exponents factorization = {} temp = n-1 #factor temp until it is prime f = trial_div...
042a04f2407fbefbbc93cf9480c4eea98a0592a9
Chittesh/PythonFunctionalProgramming
/datetime.py
702
3.578125
4
from Lib import datetime x = datetime.datetime.now() print(x) #Year -moth - day - Time #2020-08-04 15:36:06.407618 print(x.hour) #15 print(x.day) #4 print(x.minute) #38 print(x.year) #2020 print(x.month) #8 some_day =datetime.datetime(2019, 12, 31) # ad...
0636688abc7b54d799f258b81e361d826fb53426
bishalsainju/Rapid-Problem
/atcoder/abc147/A-BlackJack.py
123
3.515625
4
num = input().split() sum = int(num[0]) + int(num[1]) + int(num[2]) if sum >= 22: print("bust") else: print("win")
fa1447abee7cb8ceb24b550ca1c6f3f399fc9c70
mjhbest/Verifiable_Random_Function
/src/Elliptic_Arithmetic.py
1,736
3.6875
4
class Point(): b = 7 def __init__(self, x=None, y=None): self.x = x self.y = y if x is None: self.x = BASEx self.y = BASEy def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg...
065477ec5029fd2e6ddd3cbe4b722ee2dabd6c73
shikhaghosh/python-assigenment1
/assignment1/question5.py
113
3.9375
4
num1=input('enter first number:') num2=input('enter second number:') sum=int(num1)+int(num2) print("sum=",sum)
7e97f790d96abf42d0220cb1fe537834a50d0796
shikhaghosh/python-assigenment1
/assignment2/question10.py
284
4.15625
4
print("enter the length of three side of the triangle:") a,b,c=int(input()),int(input()),int(input()) if a==b and a==b and a==c: print("triangle is equilateral") elif a==b or b==c or a==c: printf("triangle is a isoscale") else: printf("triangle is a scalene")
cdb623345efcc3ff2dee89c085a81c88abc12b35
shikhaghosh/python-assigenment1
/assignment1/question2.py
139
3.875
4
print("enter the marks") num1=int(input()) num2=int(input()) sum=num1+num2 aggregate=sum/2 print("aggregate mark =") print(aggregate)
e22b05a76b97dc275f3092a23404a3b7263f0f24
shikhaghosh/python-assigenment1
/assignment2/question7.py
268
4.21875
4
print("enter three numbers:") a1,a2,a3=int(input()),int(input()),int(input()) if(a1<a2<a3 or a3<a2<a1): print(a2,"is the second smallest") elif(a2<a3<a1 or a1<a3<a2): print(a3,"is the second smallest") else: print(a1,"is the second smallest")
41a8c94cde1e86577b044a9d7408a1f0bb80e4f9
biguelito/CompanhiaAerea
/exemplos.py
2,965
3.640625
4
from mysqlcontroller import MysqlController if __name__ == "__main__": mysql = MysqlController('SUA SENHA AQUI') # EXEMPLOS DE SELECT================================================================== # print('\nselect *') # r = mysql.select("RESERVA_ASSENTO") # for i in r: # print(i) ...
a2cf6d9ae405d04224e0d963b5308fa8799a80c5
pythonvietnam/pbc032015
/DinhManhHung/doanso.py
299
3.546875
4
import sys import math print 'day la chuong trinh giup doan binh phuong cua 1 so' so = input('nhap so can doan binh phuong ',) bp = input('ban doan binh phuong cua so vua nhap la bao nhieu ',) so = so * so if bp == so: print 'ban da doan dung' elif bp < so: print 'qua thap' else: print 'qua cao'
21160d3d020237d40dddb9e73dc36c553f1b1612
pythonvietnam/pbc032015
/NguyenCongDuc/7.1-TinhLuong.py
890
3.6875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # PCB032015 # Chuong trinh tinh luong # ducnc92@hotmail.com hello = '''\nChuong trinh tinh luong! Moi ban lua chon chuc nang: \t1. Tinh luong \t2. Thoat''' def tinhluong(a, c, e, f , b = 400, d = 1.5): return (a * b) + (c * d) - e - f while True: print hel...
f398c6e74fb847c9fe79deb547b345bb799c2230
pythonvietnam/pbc032015
/NguyenCongDuc/2.2-calculator-fibonacci.py
1,566
3.796875
4
#!/usr/bin/python # Chuong trinh tinh toan nhan / chia / cong / tru hai so print "Chuong trinh tinh toan cong tru nhan chia 2 so tu nhien hoac viet day so Fibonacci!" print "Nhap vao phep toan (cong / tru / nhan / chia / fibo), an 'q' de thoat!" pheptoan = raw_input("Nhap phep toan: ") try: a = int(raw_input(" >...
0e409e1fef22e3cf4dd542598019d11a3bba88bf
bakhmurov/yandex-auditorii
/yandex-auditorii.py
1,069
3.515625
4
import csv import re def is_not_blank(s): return bool(s and s.strip()) def csv_writer(data, file): with open(file, "w", newline='') as csv_file: fieldnames = ['external_id', 'phone', 'email'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter=',') writer.writeheader()...
95b9f9c97f42d68d4adea377faf54f3bb2eb1aed
aditinair21/python
/list.py
161
3.9375
4
x="" mylist=[] while x != "quit": x= input("Enter a name: ") if x!="quit": mylist.append(x) str(mylist) print("The names you entered are" + str(mylist))
041e8e1d8a9c6f4b2dca2d89564939ad745ae34b
aditinair21/python
/counting_down.py
62
4.0625
4
x=int(input("Enter a number: ")) while x>0: print(x) x=x+1
7e50a30580779d9d8f75650f20b78d65fa37f281
idsglee/register
/list.py
133
3.6875
4
fruit = ['apple','banana', 'watermelon'] print(fruit) print(fruit[0]) fruit.append('orange') print(fruit) del fruit[1] print(fruit)
8474ca1ac34ee8a2ac85603b605202dd2626771b
ltimsit/python_AI
/day01/ex00/book.py
1,277
3.875
4
from datetime import date from recipe import recipe class book: def __init__(self, name): self.name = name self.creation_date = date.today().strftime("%d/%m/%Y %H:%M:%S") self.last_update = self.creation_date self.recipe_list = {'starter': {}, 'lunch': {}, 'desert': ...
4118233cfccb390d9c40613b793a28dcaf8cd061
ltimsit/python_AI
/day02/ex03/csvreader.py
2,318
3.609375
4
class CsvReader(): def __init__(self, file_name, sep=',', header=False, skip_top=0, skip_bottom=0): if type(file_name) == str: self.file_name = file_name self.sep = sep self.header=header self.skip_top = skip_top self.skip_bottom = skip_bottom self.data ...
2eac1e3675d466a9da49fa656897f082ae7b4751
homo-sapiens94/Bites_of_py
/208/combos.py
244
3.625
4
def find_number_pairs(numbers, N=10): final_list =[] for index in range(len(numbers)): if round(N-numbers[index],2) in numbers[index+1:]: final_list.append((numbers[index],round(N-numbers[index],2))) return final_list
54f093ca5420582045703e96e4117428fcb90b2c
homo-sapiens94/Bites_of_py
/180/names.py
598
3.6875
4
from collections import defaultdict # fake data from https://www.mockaroo.com data = """last_name,first_name,country_code Watsham,Husain,ID Harrold,Alphonso,BR Apdell,Margo,CN Tomblings,Deerdre,RU Wasielewski,Sula,ID Jeffry,Rudolph,TD Brenston,Luke,SE Parrett,Ines,CN Braunle,Kermit,PL Halbard,Davie,CN""" def group_n...
9fc088c82ccbf0ac1fae2dbcf8157161af8fc354
luvjoey1996/url_match_trie_tree
/TrieRgxTree.py
3,533
3.609375
4
import re import string from typing import Dict alphabet = '{}{}{}{}'.format(string.digits, string.ascii_letters, '/', '-') char_map = list(-1 for _ in range(128)) def initial_char_map(): global char_map for idx in range(len(alphabet)): char_map[ord(alphabet[idx])] = idx class TrieRgxNode: de...
f29a15bcad1b9816602013863724edebc027d6d2
neospeed83/Personal_Codes
/Linearsearch.py
347
3.84375
4
A = [3, 4, 9, 5, 8] v = int(input("Enter the number to be searched\n")) flag = False for i in range(0, len(A)): if A[i] == v: print("your number is at index \"" + str(i) + "\" in list A.") flag = True break elif i == len(A): flag = False if not flag: print("Entered number ...
714d82cea0fd762ef0f30303d4c5d5882f1b3893
loye168/algorithm_hw
/week8.py
438
3.71875
4
# -*- coding: utf-8 -*- # 191. 位1的个数 class Solution: def hammingWeight(self, n: int) -> int: return bin(n).count('1') # 231. 2 的幂 class Solution: def isPowerOfTwo(self, n: int) -> bool: return n == n & (-n) if n else False #190. 颠倒二进制位 class Solution: def reverseBits(self, n...
10faaa66b86dadb51c03a5463ec17fe1040ce5a6
eileen-kuehn/assess
/assess/decorators/anomalydecorator.py
6,020
3.515625
4
from assess.decorators.decorator import Decorator class AnomalyDecorator(Decorator): """ The anomaly detector works based on each event for given prototypes and ensembles. For each event it is determined if it is handled as an anomaly or not. If it might be an anomaly, True is appended, False otherwis...
02c30b33e981382de654865dac5f7eaeab2bf587
IbroCalculus/Python-Codes-Snippets-for-Reference
/Modules.py
602
3.546875
4
#A module is a file containing python code. It may contain functions, classes etc #It is used with modular programming, which is used to separate a program into parts. #Create and import your own custom module #i.e Modules2 #On this machine, it always shows the red for custom module import, don't know why, but still...
143f78b793a0772073bcc3239ce361d2735339d4
IbroCalculus/Python-Codes-Snippets-for-Reference
/Set.py
1,592
4.21875
4
#Does not allow duplicate, and unordered, but mutable. #It is faster than a list #Python supports the standard mathematical set operations of # intersection, union, set difference, and symmetric difference. #DECLARING EMPTY SET x= set() #NOTE: x = {} is not an empty set, rather an empty dictionary s ...
09648775855fe711469dedbe02d1e108da3d3c32
IbroCalculus/Python-Codes-Snippets-for-Reference
/Text_To_Speech.py
2,615
3.65625
4
import pyttsx3 import time #Works offline #1. Basic Usage def basicUsage(): msg1 = "Good day ibrahim, Press Enter to proceed with the launch sequence?" print(msg1) pyttsx3.speak(msg1) input() pyttsx3.speak("Ready to launch in...") for i in range(10, 0, -1): print(i) pyttsx3....
b27175e1a40f491c0ef12308615e1fc946b694e6
IbroCalculus/Python-Codes-Snippets-for-Reference
/Regex2.py
902
4.4375
4
import re #REGULAR EXPRESSIONS QUICK GUIDE ''' ^ - Matches the beginning of a line $ - Matches the end of a line . - Matches any character \s - Matches whitespace \S - Matches any non-whitespace character * - Repeats a character zero or more times *? - Repeats a character zero or more times (non-greedy) + ...
8db9c94452475725c2945ea26c1ea197ed9f61db
IbroCalculus/Python-Codes-Snippets-for-Reference
/Classes.py
1,020
3.96875
4
#CHECK: OOP for more ie Class and Instance variables, Inheritance etc, though many repetitions import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) rate = engine.getProperty('rate') print(rate) engine.setProperty('rate', 190) #Classes - is a bluepri...
99ed42ee52f79007c04845a9d119f761b73af15c
IbroCalculus/Python-Codes-Snippets-for-Reference
/CSV.py
796
3.96875
4
import csv #CSV -> Comma separated Values #What separated the values is called a delimeter #READING FROM A CSV FILE with open('csvTestFile.csv', 'r') as csvFileObj: #csvReader = csv.reader(csvFileObj, delimiter=",") #Returns value in list format csvReader = csv.DictReader(csvFileObj, delimiter=",") ...
3872b6f6c501e87bf87ef48c7da6165f40d02877
IbroCalculus/Python-Codes-Snippets-for-Reference
/Secrets Module.py
767
3.875
4
import secrets #It's also used for random number generations, but more secure, the others are: random and numpy(Numpy2) #It only has 3 functions #Used for i.e: Passwords, security tokens, account authentication #DISADVANTAGE: It takes more time to generate the algorithms for i in range(3): a = secrets.randbelow(1...
43c3fddb4167b616b765b692e7c4a02d36f2e32f
IbroCalculus/Python-Codes-Snippets-for-Reference
/Dictionary.py
1,766
4.3125
4
#CREATE A DICTIONARY: 2 METHODS cars = {"Benz": 2, "Corola": 1} cars2 = dict(fname="Ibrahim", mname="Musa", sname="Suleiman") print(f'The number of Benz cars are: {cars["Benz"]}') print(f'You are welcome Mr {cars2["fname"]} {cars2["mname"]} {cars2["sname"]}') #Copy a dictionary cars2 = dict(fname="Ibrahim",...
a44a3f5d42df0d350c5219b742d5900e11ae930c
KanagatS/PP2
/FINAL/b.py
175
3.609375
4
import sys s = input() a = sys.stdin.read().split() res = set() for i in range(len(a)): if sorted(s) != sorted(a[i]): res.add(a[i]) print(*sorted(list(res)))
d7b5a6c9018d1bb114af0494c15849922f270887
EvelinaZakharchenko/CourseraPython
/threeDigitsNumber.py
136
3.703125
4
N = int(input()) firstDigit = (N // 10) // 10 secondDigit = (N // 10) % 10 thirdDigit = N % 10 print(firstDigit+secondDigit+thirdDigit)
896305e01c3d81c7c262615a6e692ce26ec015f2
cller/Simple-Calculator
/tests/calculate_test.py
1,141
3.71875
4
from calculate import calculate def test_basic_operators(): assert calculate('5+5') == 10 assert calculate('5*5') == 25 assert calculate('10/2') == 5 assert calculate('10-4') == 6 assert calculate('10%4') == 2 assert calculate('6/3') == 2 assert calculate('5-10') == -5 assert calcula...
1f7f8ee6ed425bc86dba4a171d6c5da109035b5a
santospat-ti/Python_ExListas
/ex10.py
318
4.125
4
"""Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos elementos do vetor.""" num = [] soma = 0 for n in range(10): num.append(int(input('Digite um número: '))) soma += (num[len(num) - 1] ** 2) print('A soma dos quadrados do vetor são', soma)
d13a82fd3c12c780d64089c05e1e3387c3d5ab39
santospat-ti/Python_ExListas
/ex07.py
826
4.21875
4
"""Faça um Programa que leia duas listas com 10 elementos cada. Gere uma terceira lista de 20 elementos, cujos valores deverão ser compostos pelos elementos intercalados das duas outras listas.""" lista_um = [] lista_dois = [] lista_tres = [] lista_inter = [] for n in range(10): print('Lista um') lis...
376c6bad299e91cdc0f8970a727ea8c3fd3923d2
Y-Suzaki/python-advanced-sample
/advanced/sample_metaclass.py
903
4.03125
4
from abc import abstractmethod from abc import ABCMeta class Human: @abstractmethod def shut(self): pass class Employee(Human): def __init__(self): print('init:{}'.format(self.__class__)) # @abstractmethodを付与しただけでは、特にエラーになってくれない # classオブジェクト作成時に、metaclassの機能を動かす必要がある prin...
fd9adb7ebb5603760577526aa16ab7d83555be5d
ParulProgrammingHub/assignment-1-mistryvatsal
/Program8.py
241
4.15625
4
# WPP TO TAKE INPUT BASE AND HEIGHT OF THE TRIANGLE AND PRINT THE AREA OF THE TRIANGLE base = int(input('ENTER THE BASE OF THE TRIANGLE :')) height = int(input('ENTER THE HEIGHT OF THE TRIANGLE :')) print('AREA IS : ', 0.5 * height * base)
dba5c4d58950ac408580a1a256c8dcbc44e01d65
ParulProgrammingHub/assignment-1-mistryvatsal
/Program6.py
178
4.25
4
# WPP TO TAKE INPUT TWO NUMBERS X AS BASE AND Y AS POWER AND PRINT X^Y x = int(input('ENTER THE VALUE OF X : ')) y = int(input('ENTER THE VALUE OF Y : ')) print('x^y : ', x**y)
c11cb358856c1f79cf22c0f37bdaf0efe063ca38
lyz21/untitled
/test1.py
2,881
3.78125
4
print("字符串测试-----------------------------------") str = "123" # "" 和 '' 效果一样 str2 = "abc" var1 = ",.?" print(str) # 输出字符串 print(str2) # 输出字符串 print(var1) # 输出字符串 print(str[0:-1]) # 输出第一个到 倒数第二个 print(str[-1]) # 输出倒数第一个 print(str * 2) # 输出字符串两次 print(str + 'hello') # 连接字符串 print("输出测试----------------------------...
ea468a5c22435ae92ac6dae3a17d684c9324eecc
horenbergerb/GaussianIntegers
/gaussianprimes.py
5,361
3.5
4
import sympy as sp import numpy as np import matplotlib.pyplot as plt ########### # CLASSES # ########### class GaussInt(): def __init__(self, a, b): '''GaussInt(a,b) => a+bi''' if not (isinstance(a, int) and isinstance(b, int)): raise Exception("GaussInt must be given two integers") ...
c26f6b50cf1d5469dbd3cc97838e12ec9893e8ba
johnlev/coderdojo-curriculum
/Week2/activity.py
633
4.34375
4
# We are going to be making a guessing game, where the user guesses your favorite number # Here we define a variable guess which holds the user's response to the question # The input function asks the user the question and gives back the string the user types in. # The int(...) syntax converts the string into an i...
ee32a93f36838992df8e88109640d5d6296d5f34
johnlev/coderdojo-curriculum
/Week6/Paddle.py
1,571
3.6875
4
""" Week 6 - Paddle Class --------- AUTHOR: Edward Camp """ from cs1lib import * class Paddle: def __init__(self, x, y, width, height, r, g, b, paddleName, game): self.game = game self.x = x self.y = y self.width = width self.height = height self.r ...
bc2e5dc779dcd9b3ae5ed34f242c5f9b8f21225a
ytmimi/Intro-To-Python
/Week1/practice_exercises.py
6,749
4.3125
4
#!/usr/bin/env python # coding: utf-8 # **1) What command do you use to run a cell in a Jupyter Notebook?** # write your answer in this cell # **2) What command do you use to create a new cell above the current cell** # write your answer in this cell # **3) How do you create comments in Python?** # write your ans...
f83050b30754d73714f4382103ec3499635b7eb2
GiantPanda0090/Cisco_Toolbox
/regex/remove_dup_words.py
695
4.46875
4
################################################### # Duplicate words # The students will have to find the duplicate words in the given text, # and return the string without duplicates. # ################################################### import re def demo(): print(remove_duplicates("the bus bus will never be...
4170b73799bb15fde00a7725878a36921655b643
candytale55/Python_3_Function_Arguments_Examples
/recrod_library/script.py
540
3.84375
4
from record_library import place_record, rotate_record, drop_needle def play_record(album): place_record(album) rotate_record(album) drop_needle(album) next_album = "Blondie / Parallel Lines" play_record(next_album) # A parameter is a variable in the definition of a function. # An argument is the value bein...
c05eaf06de6beda55e6a6fbf5180f7705c67fe32
abhishekparakh/Matasano-Challenges
/P6.py
3,276
3.703125
4
#Breaking repeating-key XOR import base64 import math from bitstring import BitArray import bitarray #returns the hamming weight of the XOR of two strings #this is called the hamming distance between the strings #also called the edit distance def hammingDistance(str1, str2): #input must be bytes countHammingDis...
7b23940e3907b14467adeec77e52d3713ae5ad87
jtylerroth/euler-python-solutions
/1-100/14.py
1,219
4.125
4
# The following iterative sequence is defined for the set of positive integers: # # n → n/2 (n is even) # n → 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and fin...
f8ba737f5a10bd6f8d3bdc7edb17545ed95c78fb
Monamounika/Python
/Functions/Var_len_arg.py
734
4.3125
4
''' The variable length argv is an argv that can accept any no.of values. The variable length argv is written with * before variable in fn definition. ''' def totalcost(x,*y): sum=0 for i in y: sum+=i print(x+sum) #print(sum) totalcost(100,200) totalcost(122,576,8) totalcost(67) def to...
5e42fa0472ae2ba9dc58fa1840d7ee3b28b218a4
Monamounika/Python
/Extension.py
198
4.03125
4
file = input("please enter the files name :") #print("file extension is :",file.split('.')) s=file.split('.') print("file extension is : ",repr(s[1])) print("file extension is : ",repr(s[-1]))
0b9f1c0d0462d5875468966792b4180a9c5d8ef5
Monamounika/Python
/Function_Demo.py
184
3.78125
4
#def is the create to create fn in python def mul(a,b): #Defining a fn. print("Multiplication is :",(a*b)) #Calling a fn. mul(5,2) def define(): print("Hello!Monu") define()
a69223b5c66d309747e66c588aa50a98d78f6db6
scxbx/AutoSummary
/StringTest.py
84
3.515625
4
str1 = 'a' str2 = 'b' str3 = 'c' longStr = str1 + ' ' + str2 + str3 print(longStr)
c886c017641fbb1fecc15c02e6bf263a2d06d438
lissepark/pyth_practice
/part3.py
15,189
3.765625
4
'''2.3 Напишіть два скрипта представлених вище. Подивіться, як вони працюють. У другу програму додайте ще одну властивість і один метод, що дозволяє її міняти. Створіть третій об'єкт і змініть всі його властивості. Напишіть програму в стилі ООП, що задовольняє наступним умовам: в програмі повинні бути два класи і два о...
89ff7af2b7c547532200554e7919da842acf8065
luthfieku/Mechine-Learning-Penentuan-Harga-Rumah-di-King-Caunty
/Source_code.py
3,133
3.609375
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split df = pd.read_csv('kc_house_data.csv', usecols=['bedrooms', 'bathrooms', 'sqft_living', 'grade', 'price', 'yr_built']) #Mel...
3fc1b2bcf42ff8717cbc0311a5cf4c8606a8959a
qdyxmas/Study-Lesson
/parChecker.py
735
3.796875
4
#coding=utf8 class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() s = Stack() # def check(cc): left = {"(":")","[":"]","{":"}"} for ...
d0001e57590fa7bc91e62309a5f7c3b68249fcdb
cmmccre1/Chris-s-Dumba-Project
/Chris's Dumbass Project.py
4,157
3.6875
4
import random class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] ...
414f005f66e727d618600c828bf9d36aa4520a73
GQI7FS6/Cognitive-Learning-Theory-Project
/pebl_custom/shared_utils.py
1,134
4.03125
4
"""Miscellaneous utility functions.""" def as_list(c): """Ensures that the result is a list. If input is a list/tuple/set, return it. If it's None, return empty list. Else, return a list with input as the only element. """ if isinstance(c, (list,tuple,set)): return c elif c ...
4bb83220c02b4bec063fe8d4aedf1cf2d45ac369
fsaraos27/Codigos_Varios
/RecorrerLaRegla.py
223
3.875
4
# numero par o impar recorriendo la regla numero = int(input("ingrese un numero:\n")) while numero > 0: if numero % 2 == 0: print("es par") else: print("Es impar") numero = numero + 1 print(numero)
7c54831f8c3e6f351e963513424ee7cc89c52ee6
fsaraos27/Codigos_Varios
/Multiplicar.py
413
4.15625
4
print("") print("Multiplica ") print("") print("Ingresa un numero a multiplicar ") num1 = int(input()) print("Ingresaste el numero", num1) print("") print("Ingresa el segundo numero a multiplicar ") num2 = int(input()) print("Ingresaste ", num2) print("Presiona enter para multiplicar ") enter = input() print("La multip...
9c742fc9262213a5173d4efc9db80487ba138b2c
learning-Kong/python-concurrent
/线程/python-互斥锁.py
1,027
3.859375
4
# -*- coding:utf-8 -*- # author: "XiangLei Kong" # from threading import Thread # import threading # import time # # n = 100 # # def task(): # global n # temp = n # time.sleep(0.01) # n = temp-1 # print(n) # # if __name__ == "__main__": # t_1 = [] # for i in range(100): # t = Threa...
7fed37ed94f63ec6fda9779193df3ac616e5add5
drspiegel/IPPM
/Mont/Fact/ex1/ex1.py
1,866
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import numtheory import primesieve def doit (fact): for p in fact.keys(): if (p != 2 and fact[p] > 1): return False return True def _expr (a, b): if b > 1: return "({0}**{1})".format(a, b) else: return str(a...
493169e481e22bb6058f16672087e4410df1c346
ssulav/interview-questions
/leetcode/4_median-of-two-sorted-arrays.py
1,237
3.921875
4
""" https://leetcode.com/problems/median-of-two-sorted-arrays Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged arra...
c1c653276ef8c61b6a18f24ed3825249d93f777c
PritKalariya/Python-practice-problems-and-exercises
/The Basics - Loops/Loop over dict and format.py
235
3.796875
4
# Write a code to print the following output # John Smith: +37682929928 # Marry Simpsons: +423998200919 phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"} for key, values in phone_numbers.items(): print(f"{key}: {values}")
345d2673e844c49c3b4a7d22a0aa8db557ca1ec0
PritKalariya/Python-practice-problems-and-exercises
/The Basics - Loops/Loop over colors.py
142
3.734375
4
# Loop over the color items and print out the item in every loop colors = [11, 34, 98, 43, 45, 54, 54] for color in colors: print(color)
1cb828d44fd12fed572b85676f8a37e2fcb96393
PritKalariya/Python-practice-problems-and-exercises
/The Basics - Loops/Loop over int and big colors.py
257
4
4
# Loop over the colors items and print out the item in every loop only if the item is an integer and it is greater than 50. colors = [11, 34.1, 98.2, 43, 45.1, 54, 54] for color in colors: if isinstance(color, int) and color > 50: print(color)
000ee4d6282ef33e598d6f7077a2c0fc01d9dd94
PritKalariya/Python-practice-problems-and-exercises
/The Basics - Processing User Input/String formatting.py
175
3.609375
4
# Implement a function that gets a person's name as parameter and greets the person with 'Hi Person'. def greeting(name): return (f"hii {name}") print(greeting('Prit'))
598e3b10d1b6d1b1de0c65de797a0727d22e5500
PritKalariya/Python-practice-problems-and-exercises
/The Basics - Functions and Conditionals/lengther.py
153
3.734375
4
# Write a lengther function so that it return the number of items of every input lst. def lengther(lst): return len(lst) print(lengther([1, 2, 3]))
f49b8f163b6732bb6cbdd098c8af74d911f10c45
anti-Alz/leetcode-python
/004. Median of Two Sorted Arrays.py
1,316
3.953125
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). """ class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List...
18b5818c00b1490984d7a635afce8b108cedf014
anti-Alz/leetcode-python
/128. LongestConsecutiveSequence.py
1,244
4.09375
4
""" Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. """ class Solu...
cf00f6f26490154a3f996d05ca8384751f7420a1
kevsiraki/FlappyBird
/gamedir/main/Last Score.py
188
3.546875
4
Score = input("Enter your score") with open("c:\\users\\kevsi\\Desktop\\gamedir\\main\\Last_Score.txt", "w") as text_file: print("Last Score: {}".format(Score), file=text_file)
5a78bbb54f861e073b89ca0639d0c87e60ed5092
LeonardRodri/python_test
/list_comprerist/list.py
192
3.703125
4
# [expressão for intem in list if conficional] dobros = [i * 2 for i in range(1, 10)] print((dobros)) # Versao normal dobros = [] for i in range(10): dobros.append(i * 2) print(dobros)
a4c919d6a1fd770c1f3ed5650498860e5796a941
LeonardRodri/python_test
/funcao/unpacking.py
350
3.890625
4
def soma2(a, b): return a + b def soma3(a, b, c): return a + b + c def soma_n(*numeros): print(type(numeros)) soma = 0 for n in numeros: soma += n return soma if __name__ == '__main__': print(soma2(5, 3)) print(soma3(5, 3, 1)) print(soma_n(1, 3, 4, 5, 10)) nums = (1 ,3...
072e62f317e5ffb450b36adfa99f80eb19794ef0
jmarrieta98/Entorno-de-Desarrollo
/Documentación/Supercalculadora/expr_aritmetica.py
1,237
4.0625
4
class ExprAritmetica: """la clase ExprAritmetica aquella donde se realiza los operadores que van a intervenir en factores numericos """ def __es_numero__(self, cadena): """Se evalua si es cadena o numero el valor introducido y lo trasnforma a valor numerico, si es necesario ...
d33a69c3b0309b8b36e375555f9037a43d64404d
jmarrieta98/Entorno-de-Desarrollo
/Dojos/Dojo 3 Game of life Python/matriz.py
1,740
3.578125
4
from numpy import * matriz = array([ [0,0,0,0,0], [0,0,1,0,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0] ]) coordenadas={ "x" : [], "y" : [] } area_mapa = len(matriz)-1 def GameOfLife(numero): """Funcion que Recibe un numero y modifica la matriz cada turno Arguments: numero int...
23b08ce476c289af0f0dff069b9b46efff47d6b7
biguelito/RBTree
/arvoreRB.py
9,387
3.765625
4
class Node: def __init__(self, data, color=None): self.data = data self.right = None self.left = None self.father = None self.color = color def __str__(self): return str(self.data) class Binarytree: def __init__(self): self.root = None def inor...