blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b4800f2f5d2b2eb8d7f0dadf4e362408ecdfbe29 | NavneetKourSidhu/Python | /guess_number/main.py | 430 | 4.03125 | 4 | import random
def guess(x):
random_num = random.randint(1,x)
guess = 0
while guess !=random_num:
guess = int(input(f'guess a number between 1 and {x}:'))
if guess < random_num:
print("Too low number,give another try")
elif guess > random_num:
print("Too high ... |
e425eccbf37bfd569546dff962085b56353a398d | feddieminas/boggle | /boggle.py | 3,987 | 3.65625 | 4 | #import os
from string import ascii_uppercase
from random import choice
#SCRIPT_PATH = os.path.join(os.getcwd(), os.path.dirname(__file__))
def make_grid(width,height):
"""
Creates a grid that will hold all of the tiles for a boggle game
"""
return {(row,col): choice(ascii_uppercase)
for row ... |
fd5cd40618135face23338958486bc2d3dce36eb | arun-karthikeyan/Python-Development | /Python Basics/Decision Making and Loops/decision_and_loops.py | 1,570 | 4.40625 | 4 | #!/usr/bin/env python
#a = 10, b = 12, c = 13 #Not possible in python
a, b, c = 10, 12, 13
#Finding the minimum of 3 numbers using if
if ((a<b) and (a<c)):
print a, ' is the smallest'
elif b<c:
print b, ' is the smallest'
else:
print c, ' is the smallest'
#using for loop to print star pattern
for i i... |
ad97cd930308e43a520d62bf7c3e47585bc023a5 | Bernardo-MG/dice-notation-python | /tests/parser/dice/test_dice_parser_dice.py | 2,233 | 3.984375 | 4 | # -*- coding: utf-8 -*-
import sys
import unittest
from dice_notation.parser import DiceParser
"""
Dice parser tests for expressions only containing dice.
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
class TestSimpleDice(unittest.TestCase):
"""
Tests that simple dice expressions can be... |
a06707a355e7e0c3faad49f7d4871daa2cf2bd76 | green-fox-academy/TemExile | /week-03/day-2/Fibonacci.py | 289 | 4 | 4 | def fibonacci(num):
if num <= 2 and num > 0:
return [x for x in range(num)]
elif num <= 0:
return f'Please enter a valid index'
else:
start = [0,1]
for i in range(2,num+1):
start.insert(i, start[i-2]+start[i-1])
return start
|
673cba1538c1010653a2b0418049c46417a2e6a1 | riley-martine/calc | /iroc.py | 237 | 3.6875 | 4 | from aroc import aroc
from math import sqrt
def f(x):
return x**x
def iroc(f, x):
return aroc(f, x, x+0.00000001)
if __name__ == '__main__':
while True:
x = float(input("x: "))
print("IROC: ", iroc(f, x))
|
3f430ccbe90b850b6803a43290a1321de21360a0 | neerajp99/intro_to_cs_CS-101 | /cs1101/Neeraj_Pandey_cs1101_practice4/q6.py | 727 | 4.21875 | 4 | """
Write a program that accepts integers until the user enters 1, and display the average of all the numbers.
Also note that 1 should not be included as an element while calculating the average.
"""
def calculate_average(value: int, average: int, count: int) -> int:
average = ((average * (count - 1)) + va... |
99979d12e7faae24d269900ddd86246f1005f1fc | barthinator/Practice | /Interview/LeftRotation.py | 97 | 3.75 | 4 | arr = [1,2,3,4,5]
r = 1
for i in range(0, r):
arr.append(arr[0])
arr.pop(0)
print(arr)
|
807e4e6dddd7a8d66a8613bb0e3f8394346d7050 | hiramcastillo36/Cursos-Platzi | /Programacion Dinamica/Fibonacci.py | 427 | 3.796875 | 4 | def fib(n):
if n==0 or n==1:
return 1
return fib(n-1) + fib(n-2)
def fib_dina(n, mem= {}):
if n==0 or n==1:
return 1
try:
return mem[n]
except KeyError:
resultado = fib_dina(n-1) + fib_dina(n-2)
mem[n]= resultado
return resultado
if __... |
cfcbf4853780cfa3ede7e00a4a6a45de1f60a497 | estheuxe/test | /inner/functions.py | 659 | 3.984375 | 4 | x=50
def func():
''' Тут рассматриваются локальные, глобальные и нелокальные переменные '''
global x
print('x is', x)
x,y=2,7
print('x > ', x)
print('\ty > ', y)
def func_inner():
nonlocal y
y = 5
def func_innner():
nonlocal y
y = 3
func_innner()
func_inner()
print('local y > ', y)
def me... |
2d6024cc7d0e9926f78ae1c5e5efd800c3887484 | RayMPerry/kitchen-sink | /python/get-unique.py | 338 | 3.609375 | 4 | def getUnique(collection):
uniqueNumbers = []
for index, item in enumerate(collection):
if collection.index(item) != index:
if item in uniqueNumbers:
uniqueNumbers.remove(item)
else:
uniqueNumbers.append(item)
return uniqueNumbers
print(getUnique([0, ... |
6dd66665e410d5b24334d924091788bba1d2991d | Shashi-Raju-Gowda/PythonProject | /main.py | 4,339 | 3.921875 | 4 | class bookmymovie:
def menu(self):
ans = True
while ans:
self.choice = int(input("\n1. Show the seats\n2. Buy a ticket\n3. Statistics\n4. Show booked ticket user info\n0. Exit\n"))
if self.choice == 1:
self.show_seats()
elif self.choice == 2:
... |
07e1e933fd76257b451dd16c93debe21e7d8f414 | KIRANROUTH/Python-Basic-Programming | /23_Decorator/Episode37_Decorators.py | 7,839 | 4.21875 | 4 | def outer_function():
message='hi'
def inner_function():
print(message)
return inner_function()
outer_function()
print()
def outer_function():
message='hi'
def inner_function():
print(message)
return inner_function#Note that it doesnt have brackets which is stored in my_fun
#variable just below
#Ready to b... |
ffb4f8ef863d57f395c32ad5406fbc6c3a186b51 | ikenley/pySwissPairer | /api/SwissPairingsTest.py | 3,515 | 3.6875 | 4 | import random
from typing import List
from api.algorithm.Tournament import Tournament
from api.algorithm.Player import Player
from api.algorithm.Round import Round
from api.algorithm.Pairing import Pairing
class SwissPairingsTest:
def randomlyAssignWinners(pairings: List[Pairing]) -> None:
"""This simula... |
14f49d671b7f047fa4fa367900bec0d903ed5073 | atg-abhijay/LeetCode_problems | /number_of_islands_200.py | 2,627 | 3.84375 | 4 | """
URL of problem:
https://leetcode.com/problems/number-of-islands/
"""
from typing import List
class GridPiece(object):
def __init__(self, is_land, row, column):
self.is_land = is_land
self.row = row
self.column = column
self.island_number = 0
class Solution(object):
def n... |
9db7e853d7e1b772af08ce1dbd55298a69652cc6 | nss-day-cohort-18/bag-o-loot | /p.py | 813 | 3.890625 | 4 | class Employee():
def __init__(self, first_name, last_name):
self.name = "{} {}".format(first_name, last_name)
class FullTime():
"""Describes full-time employees"""
def __init__(self):
self.hours_per_week = 40
class PartTime():
"""Describes part-time employees"""
def __init__(self):
self.hou... |
90f73c8136e6ac25e34a5e15e3b618a2e62ebecf | jingong171/jingong-homework | /樊宇宸/2017310401第四次作业金工17-1樊宇宸/2017310401第四次作业樊宇宸/ice_cream_stand.py | 699 | 3.640625 | 4 | from restaurant import Restaurant
#从restaurant.py中导入Rsetaurant类
class IceCreamStand(Restaurant):
"""创建冰淇淋站类,并继承饭店类"""
def __init__(self,restaurant_name,cuisine_type,flavors):
"""创建冰淇淋站类的init方法"""
super().__init__(restaurant_name,cuisine_type)
#初始化父类属性
self.flavors=flavors
... |
55880d35098a8580f89f09ed056dbf6ff21dece0 | thebravoman/software_engineering_2013 | /class34/Emil_Dudev_2.py | 463 | 3.953125 | 4 | #!/usr/bin/python
def encrypt(keys, number):
return number**keys[1] % keys[0]
def decrypt(keys, number):
return number**keys[2] % keys[0]
if __name__ == '__main__':
n = int(input("Enter N: "))
t = 'a'
while t != 'E' and t != 'D':
t = raw_input("Enter Encrypt/Decrypt: ")
i = int(input("Enter key: "))
num ... |
0fe07b39da0e41e4602e324a4d535e468707f30d | massg/Hackerrank_Python | /NestedLists.py | 466 | 3.609375 | 4 | #Nested Lists
# Link : hackerrank.com/challenges/nested-list/problem
if __name__ == '__main__':
arr=[]
m = []
p=0
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([])
m.append([])
arr[p] = [name,score]
m[p] = score
p+... |
316f1b7f2d1424d0eaca4306192f9861b02354ee | skhlivnenko/Python | /Yarmak_course/L04X2_HT_calc_TBD.py | 540 | 4.21875 | 4 | #write a calculator with console input, that works with +,-,*,/
expression = raw_input("Input expression")
#check input: print "{}".format(expression)
operators = ["+","-","*","/"]
#parse first number until meet operator
i=0
element1 = ""
for i in range(0,len(expression)):
for v in range(0, len(operators)):
... |
b948d25e85ae4975bba0f685aa54aad0dbe7a5c4 | willyowi/codewars | /5kyu/human_readable_time.py | 943 | 4.125 | 4 | """ Write a function, which takes a non-negative integer (seconds) as input and
returns the time in a human-readable format (HH:MM:SS)
HH = hours, padded to 2 digits, range: 00 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (... |
c2f001267cd53b0b0e7c96fdbfab742a6407d4b1 | withoutCoffee/Estudos_Lavid_Python | /python_tutorials/sorting_lists_tuples_objects/employee.py | 1,008 | 3.625 | 4 |
from operator import attrgetter
class Employee():
def __init__(self, name, age ,salary):
self.name = name
self.age = age
self.salary = salary
def __repr__(self):
"""[A função __repr__ retorna uma representação do objeto,
ela deve retornar uma string, caso contr... |
52a7735567af25b84cb1540a0830b3471c2ab419 | fp-computer-programming/cycle-5-labs-p22anishiyama | /lab4_1.py | 295 | 3.65625 | 4 | # Author: ATN 10/26/21
str1 = "Fairfield "
str2 = "Prep"
str3 = str1 + str2
print(str3)
dashes = "-"
print(dashes * 20)
story = "I\'m loving this short story I\'m reading, \"The Fall of the House of\
Usher\""
print(story)
print(len(story))
apple = "apple"
letter = apple[3]
print(letter)
|
7acdabd3fb554b155efac82d51537e9fb92e503b | hadrizia/coding | /code/cracking-the-coding-interview/cap_4_tree_and_graphs.py/4.1.route_between_nodes.py | 1,124 | 3.578125 | 4 | from code.data_structures.graph.graph import Graph
from code.data_structures.graph.node import Node
from code.data_structures.queue.queue import Queue
def generate_graph(dict):
g = Graph()
for k in dict:
for v in dict[k]:
g.create_edge(k, v)
return g
def search_path(graph, s, d):
if s == d:
retu... |
54de3b33b2997bb73602c50c5021938e81b7759d | spunos/project_euler | /problem14.py | 1,020 | 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 finishing... |
8341aefe560662ba56d2bb9da43da3a98d76c2c7 | Sindhujavarun/Training | /Python/apidictionary.py | 518 | 3.765625 | 4 | # show the meaning and play the audio of pronunciation of a given word.
import requests
import subprocess
word = input("Enter a word to get the meaning and pronunciation: ")
url = "https://api.dictionaryapi.dev/api/v2/entries/en/" + word
response = requests.get(url).json()
audio = 'vlc -I null --play-and-exit h... |
59aa37afca5cb0ea5a7df82f4d7fba7034e1f900 | robin9804/RoadToDeepLearningKing | /Jinu/week2/problem195.py | 181 | 3.859375 | 4 |
x_range = list(range(0,10))
y_range = list(range(0,10))
for x in x_range:
for y in y_range:
if (3 * x + 2 * y == 10):
print(x,y) |
0032a8b90368096ebddb51afaa4504022ce09fde | zack-murray/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 881 | 3.890625 | 4 | def intersection(arrays):
# Prep hash table
hash_table = {}
# Loop through arrays
for array in arrays:
# Loop through each item in the array
for i in array:
# Check if each item is in the hash table
if i in hash_table:
# If it is, increment its val... |
2d5756aa9ac65ffb8245ae5cc9deb0540b498bcf | seanbritt4/COSC490-DecisionFactory | /test.py | 752 | 3.890625 | 4 | from Stack import *
s = SuperStack()
print 'WASD for directions. Q to quit'
key = ''
while key != 'q':
key = raw_input()
key= key.lower()
if key == 'q':
pass
elif key == 'w':
s.superPush('up')
elif key == 'a':
s.superPush('left')
elif key == 's':
s.superPush('down')
elif key == 'd':
s.superPush('rig... |
19f1a1d59bc2d5e22cae9405bf41ecd9012b3be5 | kelpasa/Code_Wars_Python | /5 кю/Not very secure.py | 566 | 4.09375 | 4 | '''
In this example you have to validate if a user input string is alphanumeric. The given string is not nil/null/NULL/None, so you don't have to check that.
The string has the following conditions to be alphanumeric:
At least one character ("" is not valid)
Allowed characters are uppercase / lowercase latin letters ... |
dbf188f4befdee4ac5bdbaac92b34d70327d48da | Ivo142/RTR105 | /sin_caur_summu_versija 5.py | 520 | 3.65625 | 4 | # -*- coding: utf -8 -*-
from math import sin
x =float(input("Lietotāj, lūdzu ievadi argumentu (x): "))
y = sin(x)
print ("sin(%.2f) = %.2f"%(x,y))
k = 0
a = (-1)**0*x**1/(1)
S = a
print ("a0 = %6.2f S0 = %6.2f"%(a,S))
k = k +1
a = a * (-1)*x*x/((2*k)*(2*k + 1))
S= S + a
print ("a%d = %6.2f S%d = %6.2f"%(k,a,k,S))
... |
8f28ba00a774ac5f59632cde8d2087c4c6b226fb | venkatbalaji87/guvi | /loop/sumOfDigits.py | 172 | 3.5625 | 4 | inputNumber=int(input())
sumNumber=0
while(inputNumber>0):
digits=inputNumber%10
sumNumber=sumNumber+digits
inputNumber=inputNumber//10
print(sumNumber)
|
6b7211216b9c3eaf933a9bbda139d9007c87dbb9 | Arthur236/shopping-list-app | /tests/test_shopping_list_items.py | 3,518 | 3.703125 | 4 | """
Class fot shopping list items test cases
"""
import unittest
from app.shopping_list_items import ListItems
class TestCasesItems(unittest.TestCase):
"""
Test cases for shopping list items
"""
def setUp(self):
"""
Setting up dataset
"""
self.list_data = ListItems()
... |
b77ec661cec4f7b340c2ea3a345a0145848c2669 | Fover21/notebook | /Python笔记/Wzy05/python面向对象之魔法方法:双下方法:内置方法.py | 4,398 | 3.78125 | 4 | 1.__new__ and __init__
这两个方法都是在实例化的时候执行,__new__ 在 __init__ 之前执行,并且
如果实例化的时候封装属性,__new__也是必须要传的,而且__new__必须有返回
值,而且这个返回值就是对象的内存空间而且会传给__init__的self参数,而且
封装的属性也会传给__init__.
class A:
def __new__(cls, *args, **kwargs):
print('我执行了')
return super().__new__(cls)
def __init__(self, name):
se... |
1a04441ff49ea0b45774b1bbb2725b7e41896aa0 | yapdianhao/Kattis-Solutions | /rollcall.py | 588 | 3.609375 | 4 | import sys
def main():
lastName = dict()
names = []
for line in sys.stdin:
names.append(line)
line = line[:-1]
line = line.split(" ")
if line[0] not in lastName:
lastName[line[0]] = False
else:
lastName[line[0]] = True
names.sort(key = lam... |
caea0fc68b4812cac92e815d9f8539bbe40cb69d | quwip10/ClassOct14 | /alex_exercises/guess.py | 680 | 4.03125 | 4 | #!/usr/bin/env
user_num = -1
min_val = 0
max_val = 1000
guess = -2
while not min_val <= user_num <= max_val:
user_num = int(input("Enter a number between {} and {}: ".format(min_val, max_val)))
guess = (min_val + max_val) // 2
while guess != user_num:
print("My guess is {}".format(guess))
low_high = in... |
8bc1a0cf50e584cd2f83c01de07ca05b0d7c4901 | qmnguyenw/python_py4e | /geeksforgeeks/python/basic/18_10.py | 3,647 | 4.21875 | 4 | Python | Pandas Series.str.len()
Python is a great language for doing data analysis, primarily because of the
fantastic ecosystem of data-centric Python packages. **_Pandas_** is one of
those packages and makes importing and analyzing data much easier.
Pandas **str.len() **method is used to determine length... |
5d3d3ad34ffece9219c27c5ab9d0ffaca4337684 | kmustyxl/DSA_final_fighting | /NowCoder/Queue/利用固定数组实现一个队列.py | 1,322 | 4.3125 | 4 | '''
需要引入三个变量 start(队列返回的指针)
end(队列插入数值的指针)
size(当前队列规模)tips:引入size可以有效地将start与end进行解耦,使得
start与end分别和size有关系,而它两者本身不产生关系,
便于理解逻辑与写代码。
'''
class Queue:
def __init__(self,Queue_size):
self.start = 0
... |
fd66479cf5a77af6332f58c4501959613e9b370e | pawelpel/open-kattis | /PhoneList.py | 789 | 4.03125 | 4 |
def read_input():
return raw_input() # raw_input (Python 2), input (Python 3)
class PhoneTree(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
def check_phones():
answer = True
phones_tree = PhoneTree()
def add_phone(phone):
d = pho... |
115fa484392f10c80e3341653c1e8bd7a6bec0f7 | pattarabh/CP3-Pattara-Bhesyanavin | /Lecture73_Pattara_B.py | 530 | 3.75 | 4 | systemMenu ={'ปลาทอด':450,'เนื้ออบ':150,'ไก่ย่าง':150,'ส้มตำ':55}
menuList =[]
Total = 0
def showbill():
print("-My Food-")
for food in range(len(menuList)):
print(menuList[food][0],menuList[food][1]," THB")
while True:
menuName= input("Please Enter menu")
if(menuName.lower() =="exit"):
... |
02244758497e275ece109918033c2b8f3237ebb2 | fernandocostar/competitive-programming | /uri/2502.py | 484 | 3.671875 | 4 | def solve(t, to, fr):
text = t
new = ""
frlower = "".join([x.lower() for x in fr])
tolower = "".join([x.lower() for x in to])
frupper = "".join([x.upper() for x in fr])
toupper = "".join([x.upper() for x in to])
for each in text:
if each in frlower
return text
while(True):
try:
a, b = map(int, input(... |
78d1b0d77293b4362bb5d1b8bac2e686f0872852 | jinshengwang92/Leetcode_train | /symmetricTree.py | 1,288 | 3.75 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
#-*-coding:utf-8-*-
# this is test of leetcode solutions
'''
这个题是判断一棵树是不是对称树。我们可以根据上一个题来解决这个问题
有代码可知,我们首先把这个树分成左右两颗子树,然后遍历这两颗子树,
比较时不再是左边和左边的比,因为对称,所以比较左子树的左节点和右子树
的右节点以及左子树的右节点和右子树的左节点是否相等即可。
'''
class Solution:
# @param root, a tree node
# @retu... |
847b429520bdadae5a19998a7f3338b2b89e9059 | NeoLinkin/py | /sort.py | 267 | 3.625 | 4 | #!/usr/bin/env python
def by_name(t):
return t[0]
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
L2=sorted(L,key=by_name)
print "by_name: ",L2
def by_score(t):
return t[1]
L2 = sorted(L,key=by_score,reverse=True)
print "by_score: ",L2
|
24be8c969b4eb8175148ee7bc0afbf888527af1d | cyrinerh/Hackathon-python | /exercice10.py | 181 | 3.75 | 4 | def overlapping (list1,list2):
for i in range(len(list1)):
for j in range(len(list2)):
if list1[i] == list2[j]:
return True
return False
|
3234ddb92ae62bb112d17a63c9d2d50d3b1f75f1 | angelahe/NLPPython | /S02_text_files.py | 1,830 | 4.1875 | 4 | from datetime import datetime
# print functions
# prints my name is Jose (string variable)
person = "Jose"
print(f"my name is {person}")
# prints my number is 123 (element in a list)
d = {'a':123, 'b':456}
print(f"my number is {d['a']}")
# prints my number is 0 (element in an array)
mylist = [0, 1, 2]
print(f"my ... |
8f0be708b3245806e692d1e5837d56f6bf7d7b77 | bradleyjay/scikit-learn | /2-supervised-learning/shrinkage.py | 760 | 3.609375 | 4 | import numpy as np
from sklearn import datasets
from sklearn import linear_model
X = np.c_[ .5, 1].T
y = [.5, 1]
test = np.c_[ 0, 2].T
regr = linear_model.LinearRegression()
import matplotlib.pyplot as plt
plt.figure()
np.random.seed(0)
for _ in range(6):
this_X = .1 * np.random.normal(size=(2, 1)) + X
r... |
6b5fd310af10a22d5c32c0d7f95b556b90cc5a6f | evanqianyue/Python | /day11/对象的初始状态(构造函数).py | 850 | 4.03125 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@ Author :Evan
@ Date :2018/10/31 12:44
@ Version : 1.0
@ Description:
@ Modified By:
"""
"""
__init__()
# 如果不显示的写出构造函数,默认会自动添加一个空的构造函数
"""
class Person(object):
def __init__(self, name, age, height, weight):
# 定义属性
self.name... |
b9d2283f21d89c0ef108254cd7afbd60245226cd | pumpkincouture/4-hour-recipe | /tests/price_calculator_test.py | 1,319 | 3.671875 | 4 | from price_calculator import PriceCalculator
import unittest
class PriceCalculatorTestCase(unittest.TestCase):
def setUp(self):
self.calculator = PriceCalculator()
def test_total_price_of_ingredient(self):
quantity = 2
price = 2.10
total = 4.20
total_price = self.calc... |
4e8f49275a3de88de3105b8f457faea2dfb41319 | stanrex-stack/algorithms_and_solutions | /algorithms_solution_3.py | 4,756 | 4.4375 | 4 | # Write a Python function, which will count how many times a character (substring) is included in a string. DON’T USE METHOD COUNT
string = input('Input a string ')
char = input('What charachter are you looking for ? ')
def count_string_char(str1, char1):
char2 = char1.lower()
str2 = str1.lower()
counter... |
84b0ab713b6e8c637dafa30b2ee986f028ec0642 | smiroshnikov/ebaPo4tu | /playground/linux_academy/standardLibClasswork.py | 328 | 3.71875 | 4 | from time import localtime, strftime, mktime
start_time = localtime()
print(f"Timer started at {strftime('%X', start_time)}")
input("Press ENTER key to stop timer ")
stop_time = localtime()
diff = mktime(stop_time) - mktime(start_time)
print(f"Timer stopper at {strftime('%X', stop_time)}")
print(f"Total time {diff} se... |
f66863a758b997ec658d4abd2fd9551b6727e76b | lokendra1704/LeetCode | /438_FindAllAnagramsInAString.py | 709 | 3.6875 | 4 | #438
#Find All Anagrams in a String
#Speed: 89.41%
class Solution:
def findAnagrams(self, s, p):
n = len(s)
m = len(p)
if n<m:
#print('False')
return []
d = [0]*26
d1 = [0]*26
result = []
for i in range(m):
d[ord(s[i])-ord('... |
5ca38e1bde6b89a6351aeb6d9e5319fe3d39ce99 | automationhacks/python-ds-algorithms | /algorithmic_analysis/4_map_implementation.py | 3,086 | 3.9375 | 4 | """ Map interface implementation using hash table"""
class HashTable(object):
"""
Hash table class implementation
"""
def __init__(self):
# no of items in hash table
self.size = 11
# slots will hold key item
self.slots = [None] * self.size
# corresponding positi... |
80e219b42284bf50b3d3ce4a13e2a6dfe994afcb | devinsuy/LeetCode-Solutions | /171_Sheet_Column_Num.py | 1,075 | 3.6875 | 4 | class Solution:
letter_values = {"A" : 1} # Cache values
A_ASCII = ord("A")
def get_value(self, letter):
if letter in letter_values:
return letter_values[letter]
else: # Calculate value and cache it for later use
dist_from_a = ord(letter) - A_ASCII
num... |
c6e39f3a1b360226527833f76741042b9a2964e2 | nzsnapshot/MyTimeLine | /1-2 Months/tutorial/Files/catsanddogsread.py | 391 | 3.828125 | 4 | def read_files(filename):
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry we could not find the file: {filename}\n")
else:
lists = contents.split()
for list in lists:
print(list)
filename ... |
51f990ac70324e25272cd320d9dd37b608847866 | cgnik/euler | /src/py/problem34.py | 1,457 | 3.59375 | 4 | # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
#
# Find the sum of all numbers which are equal to the sum of the factorial of their digits.
#
# Note: As 1! = 1 and 2! = 2 are not sums they are not included.
# https://projecteuler.net/problem=34
from math import factorial
from time import process_time... |
db9042b4de7e208ded176e1e5038155560268dfb | qiBerry/Sunmobile | /Client/main.py | 1,852 | 3.5625 | 4 | from tkinter import *
root = Tk()
def stopFunc():
print("Stop")
exec(open('stop.py').read())
def forwardFunc():
print("forward")
exec(open('forward.py').read()) #write any file with .py extension.This method is similar to rightclick and open
def leftFunc():
print("left")
exec(open('l... |
afa0360e453f35761957e6d71778874b86371e98 | Fe1c/cs362hw4 | /name.py | 143 | 3.578125 | 4 | def name(first_name, last_name):
full_name = first_name + " " + last_name
print("Your full name is", full_name)
return full_name |
23893330489190471e256c755d408b42d4ba1b97 | Pohjois-Tapiolan-lukio/sensehat-materials | /iot-sensor/iot_sensor.py | 1,947 | 3.578125 | 4 | from sense_hat import SenseHat
from time import sleep
from random import randrange
from time import time
import requests
sense = SenseHat()
# The URL of the database server (github.com/pohjois-tapiolan-lukio/iot-server)
iot_server_url = "http://iot.olarinlukio.fi:5000"
# The name of the db this script will create and... |
78a58ff09756d1200b027e9e63cfab83a6026e09 | hammad-rauf/block-chain | /Block-chain/string.py | 548 | 4.125 | 4 | import copy
# this function split and convert into numerics
def split(string):
word=""
word2=""
flag=False
for i in string:
if i==" ":
flag=True
elif flag==False:
word+=i
else:
word2+=i
return word,float(word2)
#removing... |
7deaa94e959bcb2f7e3ecca3d5f3dc04f4ce244f | MrMyastan/Advent-of-Code-2020 | /4/4-2/passport_verifier.py | 829 | 3.546875 | 4 | from typing import List
from field_validators import *
with open("input.txt") as f:
batch = f.read()
required = {"byr": byr, "iyr": iyr, "eyr": eyr, "hgt": hgt, "hcl": hcl, "ecl": ecl, "pid": pid}
batch = batch.split("\n\n")
def flatten_pass(passport: str) -> List[str]:
fields = []
for line in passport.... |
318afc79e9cc1c8ace0fc6141662709b7857b448 | teslamyesla/leetcode | /python/0322-coin-change.py | 867 | 3.625 | 4 | """
Time complexity : O(S∗n), where S is amount, n is number of coins. On each step the algorithm finds the next F(i) in n iterations, therefore in total the iterations are S∗n.
Space complexity : O(S). We use extra space for the dp table.
Note:
1. initialize dp with float('inf') instead of zeros, due to min problem
... |
d88c969d399bc0e1cdc0e2ba925a22f14e840fe8 | priyankchheda/algorithms | /dynamic_connectivity/quick_find.py | 1,841 | 3.96875 | 4 | """ Quick Find is a Eager Approach.
*Limitations:*
- Union is too expensive (N array accesses)
- Trees are flat, but too expensive to keep them flat
"""
class QuickFind:
""" elem1 and elem2 are connected iff they have the same id """
def __init__(self, n):
""" Initializing list of size n where valu... |
be76d3e61d0790f76bdc113d9f366320ae1e7c8e | rob-by-w/Invent-with-Python | /Chapter_71_SoundMimic/SoundMimic.py | 1,136 | 3.640625 | 4 | import os
import random
import playsound
import time
print('Sound Mimic')
print("""Try to memorize a pattern of A S D F letters (each with its own sound)
as it gets longer and longer.""")
input('Press Enter to begin...')
soundPattern = ''
while True:
os.system('cls' if os.name == 'nt' else 'clear')
soundPatt... |
9a4bdfadd4b2e25cbf304a373d5c804804f2c204 | ZhouningMan/LeetCodePython | /system_design_ladder/FriendshipService.py | 1,542 | 3.609375 | 4 | class FriendshipService:
def __init__(self):
self.user_followings = {}
self.user_followers = {}
"""
@param: user_id: An integer
@return: all followers and sort by user_id
"""
def getFollowers(self, user_id):
return sorted(self.user_followers.get(user_id, set()))
"... |
c40650c3a5ebbfc924549423e64086083786c782 | Markpajr/Automate-the-Boring-Stuff | /Udemy Notes/CharacterCount Practice.py | 412 | 3.78125 | 4 | import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message.upper():
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
pprint.pprint(count) # Print using pretty print modules pprint funtion to get a n... |
6a16fb30f6e9274544f0eee89197cc78c4fd1421 | Pablo5653/python-challenge. | /PyPoll.py | 567 | 3.5 | 4 | import csv
with open('Resources_election.csv', newline = '') as f:
csvreader = csv.reader(f, delimiter=',')
reader = csv.reader(f)
next(reader)
conta= 0
for row in csvreader:
conta += 1
print(f"Total Votes: {conta}")
with open('Resources_election.csv', new... |
b4e2b7f142b36057a58ab40e070ba10a027e1af5 | ashwin21rao/Sudoku-Solver | /solver.py | 1,127 | 3.59375 | 4 | import numpy as np
def solve(array, i, j):
if j > 8:
j = 0
i += 1
if i > 8:
return True
if array[i, j] != 0:
return solve(array, i, j + 1)
for value in range(1, 10):
if validCell(array, i, j, value):
array[i, j] = value
if solve(array, i... |
44ddca347cda7d83f921b1bcb321235d893d72b2 | jfarizano/LCC | /1_año/ProgII/Python/p1/ej3.py | 263 | 3.828125 | 4 | def mayores(n, m, termino = 1):
if termino*2 <= m:
mayores(n, m, termino+1)
elif termino*2 <(n*2)+m:
print(termino*2)
mayores(n, m, termino+1)
else:
print(termino*2)
mayores(6, 6)
|
769bdbb708b2cb57b494b493e4d2f8eb6731bdbc | karthiikselvam/yoci | /Graphs/precedence-table.py | 693 | 3.921875 | 4 | def dfs_tree(graph, start=0):
"""DFS, build DFS tree in unweighted graph
:param graph: directed graph in listlist or listdict format
:param int start: source vertex
:returns: precedence table
:complexity: `O(|V|+|E|)`
"""
to_visit = [start]
prec = [None] * len(graph)
... |
a1e333ddbd1456822ee2801a5ab5bdf6bbce23cc | felipefiali/studying-in-python | /algorithms/find_position_of_max_element.py | 685 | 4.09375 | 4 | """
Given an array of integers, return the position of the maximum element.
If the maximum element occurs multiple times, use a random number generator
to choose one of the positions uniformly at random
"""
from random import randrange
def find_position_of_max_element(integers):
max_index = None
max_so_far... |
d032c6f41d00dda98ca2db8e9541b20e444f77cb | BriefyHQ/briefy.common | /src/briefy/common/utils/phone.py | 352 | 3.765625 | 4 | """Module to deal with Phone numbers validation."""
import phonenumbers
def validate_phone(value: str) -> bool:
"""Validate a phone number."""
try:
number = phonenumbers.parse(value)
except phonenumbers.NumberParseException:
status = False
else:
status = phonenumbers.is_valid_n... |
5ac1ef9d3d82d6addf2b24ed3f6d4ffd12a5ef8c | k018c1072/Paiza_Python | /Pyramid.py | 71 | 3.5 | 4 | N = int(input())
p = 0
for i in range(1, N + 1):
p += i
print(p)
|
0600779361f1f46e0b108140c7ebf213cb5b33ac | AndriiBoikiv/lab03repos | /Lab_03_4.py | 623 | 4.15625 | 4 | # Lab_03_4.py
# Бойків Андрій
# Лабораторна робота № 3.4
# Розгалуження, задане плоскою фігурою.
# Варіант 2
x = int(input("Enter value of x: ")) # Вхідний аргумент
y = int(input("Enter value of y: ")) # Вхідний параметр
R = int(input("Enter value of R: ")) # Вхідний параметр
# Розгалуження в повній формі:
if (x <= ... |
1e441ceb6a5a814d6e3983054150b0ef5a12d08c | thanakorn487/CP3-Thanakorn-Chaiwong | /assigments/Exercise5_2_Thanakorn_Ch.py | 115 | 3.984375 | 4 | s = float(input("Distance (km) : "))
t = float(input("Time (hours) : "))
v = s / t
print("Velocity is : ",v,"km/h") |
ddf9ab52f61875538d1fcc377ea136bccd002a58 | josiahckim/HW4 | /person.py | 1,570 | 3.828125 | 4 | class Person:
active_user = 0;
def __init__(self, name, age, eid):
self.name = name
self.age = age
self.eid = eid
self.debt = 0
self.account_list = []
'''def deposit(self, account, amount):
if(hasAccount(account)):
Account.deposit(amount)
else:
print("You do not have access to this account")
... |
c6f3aae0b9edc18a62420e5834cbb7a20905c312 | BrantLauro/python-course | /module02/classes/class14b.py | 239 | 4.09375 | 4 | n = 1
impair = odd = 0
while n != 0:
n = int(input('Type a number: '))
if n != 0:
if n % 2 == 0:
impair += 1
else:
odd += 1
print(f'You typed {impair} impair numbers and {odd} odd numbers')
|
dae5887b855f7a863a823827ddfcc24f9080cb47 | ISP19/uml | /HotelManagement/hotel.py | 1,425 | 3.75 | 4 | """This code shows hotel management"""
class Customer:
"""This class collect information on the customers"""
def __init__(self, booking_id: str, name: str, billing: float):
self.booking_id = booking_id
self.name = name
self.billing = billing
def request_room_service(self):
"... |
ae97e19e4a35f2c6bad891143e75ad4a1fb3df00 | JaneJianLee/Array-1 | /solution2.py | 1,461 | 3.65625 | 4 | # // Time Complexity : o(n)
# // Space Complexity :o(1)
# // Did this code successfully run on Leetcode : yes
# // Any problem you faced while coding this : so many cases to consider gave me a headache..
#
#
# // Your code here along with comments explaining your approach
class Solution:
def findDiagonalOrder(self,... |
1244c0af27be1fdbf90e7b6cc5e50cc3acd58f06 | beebel/HackBulgaria | /Programming0/week1/1-IO-Simple-Problems/solutions/names.py | 195 | 4.15625 | 4 | string = input("First name? ")
firstName = string
var = input("Second name? ")
secondName = var
var = input("Third name? ")
thirdName = var
print(firstName + " " + secondName + " " + thirdName)
|
5933112e38847f4eff0c6433093e91d16cff3921 | OksKV/python | /Lesson3/Task3.py | 381 | 4.3125 | 4 | # Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(num1, num2, num3):
my_list = [num1, num2, num3]
my_list.sort(reverse=True)
return my_list[0] + my_list[1]
print(my_func(1, 5, 4)) |
bcb2c441301dc14fd6a11854e54e15fae189fc23 | bikee6315/Facial_LandMark_Detection | /facial.py | 3,549 | 3.625 | 4 | '''
Detecting facial landmarks is a two step process:
Step 1: Localize the face in the image.
Step 2: Detect the key facial structures on the face ROI(Region of Image).
The facial landmark detector included in the dlib library is an implementation of the One Millisecond
Face Alignment with an Ensemble of Regression T... |
53d904bb65c1e70d1a024055928e58188b72dba1 | snoppy14/pft-fkj | /projects/homework/ifelse.py | 155 | 3.671875 | 4 | a =input()
b =input()
с =input()
if a>b :
print (c)
elif a<b :
print ('грустный текст')
else:
print ('веселый текст') |
3f64bed0bc77f15de807b3694b294240e6b3a93b | bmcclannahan/sort-testing | /sorts.py | 611 | 3.90625 | 4 |
def is_sorted(arr):
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
return False
return True
def swap(a, b, arr):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def insertion_sort(start, end, arr):
for i in range(start, end):
curr = i
while curr >= 1 and arr... |
d68b88ded625fa99dd275d34ab7da474ab607e71 | divyanshupandey/DS_Algo | /AVL_Tress.py | 2,584 | 3.6875 | 4 |
class Node:
def __init__(self,data=None,left=None,right=None,height=1):
self.data = data
self.left = left
self.right = right
self.height = 1
class AVL_Tree():
def __init__(self,root=None):
self.root = root
def insert(self,root,key):
if not root:
... |
f1a463b49cd8253afd6ef3174d2a04e5e0df8123 | chandansau/Algorithm | /algo/missing_number_finding.py | 484 | 4.0625 | 4 | # How do you find the missing number in a given integer array of 1 to 100
def missing_number(nu):
if nu in (_ for _ in range(101)):
print(nu, "present in b/w 1 to 100")
nu = int(input("Enter any number"))
missing_number(nu)
# ----------------2nd process ----------------------
def missing_number(nu):
... |
bb9a2712397e6673423bce0036c4055b5da09a3a | YatchiYa/python_tps | /rendu_tp02/main2.py | 3,081 | 4.15625 | 4 |
# --------------------------------------------------------------------------
# 5. Structures de données
# ---------------------------------------------------------------------------
from collections import deque
from math import pi
print ("5. Structures de données")
fruits = ['orange', ... |
5909e31b76bb2395cb4f1a0a826047b7783776ce | annmag/Student-manager | /nested_functions.py | 682 | 4.125 | 4 | # Nested functions and closures
# Used when you want to delegate a certain task that is only going to be used in one function
# You simply declare a nested (or inner) function in an outer function
# Closure - nested functions does have access to the variables defined in the outer function
def get_students():
... |
b7f4de25316c502690e8bc55c407e45005664063 | futureistaken/School_projects | /Python/PycharmProjects/Learning process/If_Statments.py | 405 | 4.09375 | 4 | is_male = True
is_Girl = False
is_tall = True
if(is_male or is_tall) and is_Girl:
print("Your dick is short")
elif is_male and is_Girl == False:
print("Your are a fucking transgender")
else:
print("pussy")
def max_num(num1,num2,num3):
if num1 >=num2 and num1>=num3:
return num1
elif num2 >=n... |
cd2ee8b63cde2545b7848e58b320c06fea840776 | TomekPk/Python-Crash-Course | /Chapter 7/7.10.Dream Vacation/dream_vacation.py | 757 | 4.28125 | 4 | '''
7-10. Dream Vacation: Write a program that polls users about their dream
vacation. Write a prompt similar to If you could visit one place in the world,
where would you go? Include a block of code that prints the results of the poll.
'''
question = "If you could visit one place in the world, where would you go?"
qu... |
849789fdedb912df8d2c2ff8f5dcd71709801704 | royrowe/python | /restaurant.py | 689 | 3.5 | 4 | #!/usr/bin/env python
'''
@File :p_9.1_restaurant.py
@Copyright :luoming
@Date :
@Desc :
'''
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
'''打印酒... |
90c05eeb223c0b64365c6c3edec8f7bbb44953c4 | Gomesx/Aprendizado---Python | /Ex-05(Sucessor e Antecessor).py | 166 | 3.890625 | 4 | n1 = int(input('Digite um número: '))
ant = n1 - 1
suc = n1 + 1
print('O Sucessor de {} = {}'.format(n1,suc))
print('O Antecessor de {} = {}'.format(n1,ant))
|
5e35fd873bddcc910382ee9a9294c779f0056150 | dhruv-karan/Algo-cast | /prac/trees.py | 1,446 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 12:06:28 2019
@author: dhruv
"""
class Node:
def __init__(self,key):
self.key = key
self.left = None
self.right = None
def search(node,key):
if node is None or node.key == key:
return node
elif key<node.key:... |
bf5b4901ea8ea2d3874abfb9a170c9fdf2324b25 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/2571.py | 933 | 3.625 | 4 | #!/usr/bin/env python
import sys
# Initalizing file and number of cases
f = open(sys.argv[1], 'r')
num_cases = int(f.readline())
# For each case, make guess, mistake, or cheat!
for x in range(1, num_cases+1):
# Initial row placement
row_init = int(f.readline())
pos_init = []
for y in range(0, 4):
... |
9cf2bbcb1507f605ab88ccd0c5b424b8fea5a9b0 | Nidhiks2000/eyrc-mooc | /Week_5/Assignment_1/ex1.py | 338 | 3.78125 | 4 | import argparse
import argparse
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument("num", type=int, help="input the number")
parser.add_argument("--verbosity", action="store_true",
help="readable")
args = parser.parse_args()
if args.verbosity:
print("The square is: ", args.num**2)
else:
p... |
020ddbb5a24fdda6fc1ce0ba88f3b49ec84f337d | sharmaji27/Problem-Solving | /7. Square_Submatrix.py | 881 | 3.53125 | 4 | # Given a 2D array of 1s and 0s, find the largest square subarray of all 1s.
a = [[1,1,1,0],
[1,1,1,1],
[1,1,0,1]]
rows = len(a)
cols = len(a[0])
m= 0
flag = 0
dp_matrix = [[0 for _ in range (cols)] for k in range (rows)]
for i in range(rows):
for j in range(cols):
# checking if 1 ex... |
97c8581e95a3e04c488ed7cedf1e75b668438683 | robbertbloem/robbertbloem.github.io | /python/041_text_positioning.py | 724 | 3.546875 | 4 | """
TEXT POSITION
The text can be positioned relative to the data or relative to the axes
coordinates. In the latter case you'll need to transform the coordinates.
Note: When using Python 3.3 on a Mac, Matplotlib will truncate strings (like
labels and titles).
"""
import matplotlib
import matplotlib.pyplot as pl... |
c3b53085187e09113d3e644df405cffd3df78741 | UNH-LunaCats-Robotics/LunacatsRaspberryPi | /2018-2019/lidarCode/ObstacleManager.py | 1,753 | 3.6875 | 4 | import LinkedList.py
class ObstacleManager(object):
def __init__(self):
self.obstacleList = LinkedList(None, None, None)
self.count = 0
def insertObstacle(obs, alist):
if alist.obstacle.y > obs.y:
if alist.next == None:
alist.next = LinkedList(ob... |
5b1e3947ca57aba29dd5354b47c085d86d887a99 | arnabs542/interview-notes | /notes/algo-ds-practice/problems/graph/mother_vertex.py | 1,522 | 3.765625 | 4 | '''
What is a Mother Vertex?
A mother vertex in a graph G = (V,E) is a vertex v such that all other vertices in G can be reached by a path from v.
How to find mother vertex?
Case 1:- Undirected Connected Graph : In this case, all the vertices are mother vertices as we can reach to all the other nodes in the graph... |
b4d60a2b9e663445a74ddb1230364796f1a87dea | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4443/codes/1594_820.py | 470 | 3.5 | 4 | # Instituto de Computacao - UFAM
# Lab 01 - Ex 10
# 28 / 03 / 2019
valor = int(input("Qual o valor do saque? "))
# Quantidade de notas de R$ 50
n50 = valor // 50
# Valor restante a ser sacado com notas menores que R$ 50
resto1 = valor % 50
# Quantidade de notas de R$ 10
n10 = resto1 // 10
# Valor restante a ser sa... |
d2f85e1b24b6421c50f45f27722b24081034f164 | VivekKumarSingh07/Stocks-Predictor | /Util/DataExtractionUtil.py | 1,755 | 3.53125 | 4 | """Utility to extract meaningful data from various files"""
import re
from Util.DownloadUtil import download_companies_in_market_indices
import csv
import requests
from bs4 import BeautifulSoup
# Extracts the company list which from market index
def extract_companies_from_indices(market_index):
download_companies... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.