blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3601560b69f2cb4882716c971ef17302ff49d8f3
Margarita89/LeetCode
/0010_Regular_Expression_Matching.py
961
3.875
4
class Solution: def isMatch(self, s: str, p: str) -> bool: """ General idea: use recursion and check for 2 options with "*" - zero or non zero matches 1. Base case: pattern p is over -> check if s is also over 2. Boolean first_match True if is not yet empty and there is a match with ...
10f8f15d418108d231fbb5e612d8e8c89005b5fb
satchidananda-tripathy/PythonHacks
/8numpy.py
1,659
4.125
4
import numpy as np # This module helps us to creates super fast and memory efficients arrays #We can store data in 1d, 2d, 3d array etc. # As numpy has a datatype and it keeps less memory (because of contigous allocation) it needs less time to read data hence it is faster # x = [1,2] y=[3,4] here the list x*y will thr...
1a1b2853ac0a779ecaf4d71ca408b5f1e3664845
showintime/MachineLearningToolkit
/MachineLearningToolkitCore/Layer/Dense.py
1,709
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 30 00:16:56 2019 @author: ZWH """ import numpy as np from LayerBase import LayerBase ''' Dense layer is a trainable layer, which means that it has parameters to train. Attention to use this layer if you want to reuse this layer parameter. Attention : The Layer Dense i...
74def28e61dbaae2bbcc0fa68b106bde4cc361d6
tarun1792/DataStructure-Algorithem-Python
/DataStructures/python/LinkedList/MiddleOfLinkedList.py
375
3.546875
4
def findMid(head): # Code here # return the value stored in the middle node if head.next is None: return head.data ptr1 = head ptr2 = head while(ptr2.next is not None): ptr1 = ptr1.next if ptr2.next.next is not None: ptr2 = ptr2.next.next ...
1b9468e0977ab2d4fe2f8a8e1131668d2ba3320c
MahirI1009/CSE-216-HW4
/binarytree.py
1,466
4.25
4
class BinaryTree: # 5. constructor to initialize binary tree as an empty tree or with a single value def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # 6. add_leftchild and add_rightchild methods # 7. TypeError ...
5b0c8b4ed060dd178a12fe4be191b7ab4bc0f925
Growail/Python-codes
/29 7 14.py
456
3.53125
4
#29/7/14 def mcm(num1, num2, num3): cont=1 i=1 while i>num1 and i>num2 and i>num3 : if num1%i==0 and num2%i==0 and num3%i==0: num1=num1/i num2=num2/i num3=num3/i cont=cont*i i=i+1 else: i=i+1 return i ...
1df078e941c0e7a5645b873915e43aa843fb1927
Aasthaengg/IBMdataset
/Python_codes/p00005/s388716206.py
721
3.53125
4
while True: try: # a >=b a, b = sorted(map(int, input().strip("\n").split(" ")), reverse=True) d = a * b # calc. gcm by ユークリッド互除法 while True: c = a % b # print("{0} {1} {2}".format(a, b, c)) if c == 0: break els...
e343174888344e3aff75078ed2400f589675158e
rupeq/python-crypto
/elgamal.py
2,458
3.828125
4
from random import randint from math import gcd, sqrt def isPrime(x): if x == 1: return False if x <= 3: return True if x % 2 == 0 or x % 3 == 0: return False for i in range(5, x // 2 + 1): if x % i == 0: return False return True def findP...
22fa38c1630f576a204dc6891fcbe3ab051c4255
stys/y-test-ranknet
/lib/activation.py
1,222
3.921875
4
from abc import abstractmethod import math """ Activation functions """ class ActivationFunction(object): @abstractmethod def f(self, x): """ Activation function value at x """ pass @abstractmethod def df(self, f): """ Activation function der...
3e907178ff2568710426e8a2e23caa3cfb69de32
silvercobraa/competitive-programming
/1. Introduction/Ad Hoc Problems/Time, Harder/10070.py
580
3.890625
4
def is_leap(n): return n % 4 == 0 and (n % 100 != 0 or n % 400 == 0) first = True s = input() try: while s != '': n = int(s) if not first: print() else: first = False leap = is_leap(n) huluculu = n % 15 == 0 bulukulu = n % 55 == 0 and leap if not leap and not huluculu and not bulukulu: print...
0d5069b0a7b7869bcfc2a62d57f0e483ffabaecc
Windreelotion/store
/测试.py
2,680
3.671875
4
''' 京东的登陆、淘宝登陆、苏宁的登陆脚本 bilibili登陆脚本,搜索一个鬼畜视频并播放脚本写出来。 做知乎的官网,并登陆,和发表一篇文章。 企查查的官网登陆。 ''' from selenium import webdriver import time from selenium.webdriver.common.action_chains import ActionChains # 苏宁自动化登陆操作 driver = webdriver.Chrome() driver.get("https://www.suning.com") driver.maxi...
db152888584f85403424f21c0bb6ef79efb75caf
mihau1987/Python_basics
/Trello_Zadania/03_Instrukcje_Warunkowe/02_Zadania_dodatkowe/Zadanie_slodycze.py
1,215
4.15625
4
slodycze = ['paczek', 'drozdzowka', 'gniazdko', 'jagodzianka', 'szarlotka', 'muffin'] '''question = input("Czego sobie życzysz? ") if question in slodycze: print("Podany produkt jest dostepny") else: print("Niestety nie posiadamy artykulu na stanie") q1 = input("Podaj produkt no 1: ") q2 = input("Podaj prod...
f55046a4e13c90066c04f886536eb116ac967e18
narayansiddharth/Python
/AIMA/Assignment/NOV_17_18/AS-1-Binarization.py
1,559
4.25
4
# Write code in Python for Binarization without using any library from typing import List def Binarization(inputlist, symbol: object, threshold: object) -> object: finalList: object = [] for row in inputlist: innerList: object = [] for col in row: if symbol == '>': ...
090a87cb689d09561eaf01bfd5ca34e8b12f4f8b
roma-glushko/leetcode-solutions
/src/linked_list/merge_k_sorted_lists_test.py
1,106
3.5625
4
from typing import List from unittest import TestCase from .merge_k_sorted_lists import ListNode, MergeKSortedLists class MergeKSortedListsTest(TestCase): def get_values_from_list(self, list_head: ListNode) -> List: list_values = [] current_node = list_head while current_node: ...
ca08db7b319ed35439106b19f8870a3a7ed46ffc
JuanesFranco/Fundamentos-De-Programacion
/sesion-05/ejercicio 53.py
552
3.75
4
cantidad1=0 cantidad2=0 cantidad3=0 cantidad4=0 for f in range(10): valor=int(input("ingrese numero entero")) if valor>0: cantidad1=cantidad1+1 else: if valor<0: cantidad2=cantidad2+1 if valor%15==0: cantidad3=cantidad3+1 if valor%2==0: cantid...
428210cea039f846bffecd4ecfa0a04345dcb378
sumanthgunda/hacktoberfest2020
/guess_the_num.py
1,673
4.125
4
import random choice=random.choice(range(21)) def print_pause(msg_to_print): print(msg_to_print) time.sleep(2) def intro(choice): print("the computer choose a number within the range 20" ) intro(choice) def try1(): c1=input("i guess the number is ") if choice == c1: print("your gues...
d79b994433cd9ed5bfe33afb0e5e807cfe384803
garlicbread621/Garliczone
/Software.py
551
3.9375
4
price = 99 packages = int(input("Please enter amount of packages you wish to purchase: ")) sale=price*packages if packages < 10: discount=sale*0 elif 10 < packages and packages < 20: discount=sale*.10 elif 19 < packages and packages < 50: discount=sale*.20 elif 49 < packages and packages < 100: discount=sale*.3...
fe86ea6f3f4f43c3cf59d2b905709bbb37441c9b
olinkaz93/Algorithms
/loop.py
88
3.84375
4
list = [2, 3, 4] for i in range (len(list)): print("element", i, "value:", list[i])
a0f23cf0efb584317f4cc917008c577e18ca0cba
haoknowah/OldPythonAssignments
/Gaston_Noah_NKN328_Hwk13/015_the12DaysOfChristmas.py
2,381
4.03125
4
def the12DaysOfChristmas(): ''' the12DaysOfChristmas=asks for a number and determines the price from that many days of the 12 days of Christmas stored in Gifts.txt @param number=number of days specified @param infile=contains file Gifts.txt @param theDays=list holding the 12 days of Christmas from infile @param day...
a8bb024dcb06e69caf0ddf45926f76575aa4e701
hackrmann/learn_python
/printemoji.py
155
3.671875
4
n = input("Enter number of lines of emoji: ") n = int(n) for i in range(1,n+1): for j in range(1,i+1): print('\U0001f600',end="") print("")
7a0a88976ee867ee3be0c3844f9c2d14e80d4725
RAKS-Codes/simpyfy
/os_functions.py
1,047
3.96875
4
import os from pathlib import Path def make_directory_tree(pathname): """ Creats hierarchical paths """ path = Path(pathname) path.mkdir(parents = True, exist_ok = True) def get_directory_list(folderpath,sort = True,verbose = True): """ Returns a list of directories inside a directory """ directory_list =...
f5ef817df3207388907878ec524bf1d3453f4f77
SaiSujithReddy/CodePython
/BInarySearchTree_Practise_v4.py
1,589
4
4
class Node: def __init__(self,data): self.val = data self.leftChild = None self.rightChild = None def bst_insert(root,data): if root is None: root = Node(data) else: if root.val > data: if root.leftChild: bst_insert(root.leftChild,data) ...
ff0dba9e05c724ffa54eb4320ba908220b39c14f
py1-10-2017/ElvaC-p1-10-2017
/Strlists.py
447
3.796875
4
# words = "It's thanksgiving day. It's my birthday, too!" # print words.find('day') # print words.replace("day", "month") #min # x = [2,54,-2,7,12,98] # print min(x) #max # x = [2,54,-2,7,12,98] # print max(x) #First and Last # x = ["hello",2,54,-2,7,12,98,"world"] # print x[0], x[-1] #New List x2 = [19,2,54,-2,7,1...
889fa09f6c60e2131fb611a3e823bc3b7ec7170c
mwong33/leet-code-practice
/medium/remove_nth_node_from_end.py
925
3.890625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # O(n) time O(1) space def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: # Step One: Get the length of the Linked List ...
72de143aa2cef1c6d1691050d51d5119155fe3f6
mizrael63/learning
/lesson7/task3.py
2,151
3.921875
4
-#Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом. # Найти в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: # в одной находятся элементы, которые не меньше медианы, в другой – не больше ее. import random m = int(input("Введите натуральное число m: ")) ...
c32d2df0eec8084da4ba845f2bd260ad2ee082c5
Lmineor/Sword-to-Offer
/bin/insert_sort.py
210
3.59375
4
class Solution: def NumberOf1(self, n): # write code here count = 0 while n: count += 1 n = (n-1)&n return count s = Solution() print(s.NumberOf1(3))
6113c93ad961e231412930542739bf2d49ddc484
chogiseong/GovernmentExpenditureEducation
/Python/6.4.py
3,058
3.6875
4
''' a=[7,2,5,3,1] b=0 c=0 space = 0 for b in range(0, len(a)) : for c in range(0,len(a)) : if a[c] < a[c+1] : space = a[c] a[c] = a[c+1] a[c+1] = space c = c + 1 continue continue print(a) ''' #버블정렬 #1. 안바뀌면 정렬된 것 - 변수 #check #2. 앞과 뒤를 비교한...
f28610a2a9693e366d60456d90715c0b7177a4b7
zuxinlin/leetcode
/leetcode/217.ContainsDuplicate.py
603
3.828125
4
#! /usr/bin/env python # coding: utf-8 ''' 题目: 包含重复数字 https://leetcode-cn.com/problems/contains-duplicate/ 主题: array & hash table 解题思路: 1. 哈希表 ''' class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ hash_table = set() ...
c02e9be6b021014a946ba37266a72d2725ad410d
analuisadev/100-Days-Of-Code
/Day-25.py
1,200
3.765625
4
option = 'Yy' print ('\033[1;32m{:=^40}\033[m'.format(' ANNUAL STUDENT RESULT ')) while option == 'Yy': nome = str(input('\033[1mType your name: ')) n1 = float(input('\033[1;33m{}\033[m \033[1;32mType a first note:\033[m '.format(nome.lower().capitalize()))) n2 = float(input('\033[1;33m{}\033[m \033[1;32mE...
46637a1c9fcb73b17a1be05f43f68c81c024a362
lucasayres/python-tools
/tools/sha256_file.py
397
3.78125
4
# -*- coding: utf-8 -*- import hashlib def sha256_file(file): """Calculate SHA256 Hash of a file. Args: file (str): Input file. Retruns: str: Return the SHA256 Hash of a file. """ sha256 = hashlib.sha256() with open(file, 'rb') as f: for block in iter(lambda: f.read(...
3e45129b6878afe9be84075e0356c8d694172303
eltonrp/curso_python3_curso_em_video
/03_estruturas_compostas/ex082.py
718
3.8125
4
lista = [] pares = [] ímpares = [] while True: lista.append(int(input('Digite um número: '))) r = ' ' while r not in 'SN': r = str(input('Deseja continuar [S/N]: ').strip().upper()[0]) if r not in 'SN': print('Opção incorreta...') if r in 'N': break for pos, e in enum...
de9115b1ac802d914749ea0593a42b9128664cb5
anmolrajaroraa/core-python-april
/tic-tac-toe.py
2,310
4.03125
4
import random print("Tic Tac Toe".center(100)) userChoice = input("Which one do you want to use (X or O) : ") userChoice = "X" if userChoice == "X" or userChoice == "x" else "O" cpuChoice = "O" if userChoice == "X" else "X" gameProgress = [1, 2, 3, 4, 5, 6, 7, 8, 9] availablePositions = [1, 2, 3, 4, 5, 6, 7, 8, 9] wi...
a0efa53a3efb5ceab519f7814b6ff73a419a5357
fedegsancheza/POO
/Menu.py
819
3.859375
4
def opcion0(): print("Adiós") def opcion1(): print("Código de la opción 1") def opcion2(): print("Código de la opción 2") def opcion3(): print("Código de la opción 3") switcher = { 0: opcion0, 1: opcion1, 2: opcion2, 3: opcion3 } def switch(argument): func = switcher.get(argumen...
8d892b1efc16694a89666d6d429b6d1a98d0ecce
Rohit-83/pythonproblems
/prermnutationBacktrack.py
565
3.984375
4
#input = "ABC" #wap to print all permutation #output--> "ABC","BAC","CAB","ACB","BCA","CBA" string = "ABC" #we convert this into list bcz string object does not supporr changing and assignment output = list(string) n=len(string) l=0 r=n-1 def permutation(string,output,l,r): if l==r: print("".join(output),end = "...
02e8d20dddbfe8032b4ce26369424f33cd1b5525
imouiche/Python-Class-2016-by-Inoussa-Mouiche-
/Advance1.py
299
3.546875
4
def vowel(): vow = 'aeiouAEIOU' stence = raw_input(':') word = stence.split() d = 0 for w in word: W = [] d += 1 P = [] j = 0 for i in range(len(w)): if w[i] in vow: j +=1 P.append(i) W.append(w[i]) print '%d word:%s has %d vowels %s at position %s' %(d,w,j, W,P)
cb0189351a30a5a7129470815f64f6746e645430
SuyogRane/Air_flow
/plotgraphwrtanycity.py
389
3.609375
4
import pandas as pd import plotly.graph_objects as go df = pd.read_csv(r'new.csv') a=input("Enter the origin city") fig = go.Figure(go.Scatter(x = df['PASSENGERS_ON_WAY'], y = (df['AIRLINE_NAME']==a), name='Share Prices (in USD)')) fig.update_layout(title='airlines', plot_bgcolor=...
ccfc52a9aada76726447ab8d04c816d4cfe86d64
keshavkummari/python-nit-930pm
/DataTypes/String/str_center_ljust_rjust.py
776
4.25
4
#!/usr/bin/python str = "Python0007" print(len(str)) print (str.rjust(20, '*')) print (str.ljust(25, '#')) """ 29 rjust(width,[, fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns. """ #!/usr/bin/python """2. center() Method: Note: Returns centered in...
50521969ee7864b2d70c996c998bc189ecc0eeda
noufal85/make_a_developer
/algorithms/grokking_algorithms/divide_conquer.py
726
3.609375
4
""" the technique of D&C""" class DivideConquer: def __init__(self) -> None: pass def recursive_addition(self, array): if array == []: return 0 return array[0] + DivideConquer.recursive_addition(array) def recursive_length(self, array): if array == []: ...
7c6e695bf1f71f984896eda3dcb9d0e28efe60fb
troykiim/Python
/lpthw/ex02.py
347
3.84375
4
#This program is from lesson 2 in "Learn Python the Hard Way" # A comment, this is o you can read your program later. # Anything after the # is ignored by python. print("I could have like this.") # and the comment after is ignored # You can also use a comment to "disable" or coment out code: # print("This won't run"...
e26244d008ac702c12bbdb824f662d557b7a4e8f
amangautam727/rep_1
/test_list1.py
213
3.859375
4
test_list =[1,2,3,3,3,4,5,5,6,7,8,9] print ('before=:'+str(test_list)) t = [] for i in test_list: if i in t: i='n' t.append(i) else: t.append(i) print ('after=:'+str(t))
8d5dd02cb5094fb569c37522daea8b0b64d6f26c
ishandutta2007/ProjectEuler-2
/euler/algorithm/assignment.py
5,643
3.859375
4
from copy import deepcopy as __deepcopy def hungarian_algorithm(m): """Using the "Hungarian Algorithm" to solve the "Assignment Problem".""" def one(): nonlocal step, cost for r in range(L): min_r = min(cost[r]) cost[r] = [c - min_r for c in cost[r]] ...
d6a26db881fc0d188a46fe5c646136ffea53167a
StefanCondorache/Instructiunea_IF
/Problema_3_IF.py
544
3.671875
4
# Să se verifice dacă o literă introdusă este vocală sau consoană. # Exemplu : Date de intrare a Date de ieşire vocala. l=input("litera ") list1=["a","e","i","o","u","ă","î","â","A","E","I","O","U","Ă","Î","Â"] list2=['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','ș','t','ț','v','w','x','y','z','B','...
335e5dd25faa149115654b6f51943413e73ef814
AtheeshRathnaweera/Cryptography_with_python
/symmetric/streamCiphers/stream.py
718
3.765625
4
#Those algorithms work on a byte-by-byte basis. The block size is always one byte. #Two algorithms are supported by pycrypto: ARC4 and XOR. #Only one mode is available: ECB. (Electronic code book) from Crypto.Cipher import ARC4 def encryptionMethod(textToEncrypt): key = "myKeY" # can use any size of key obj...
09181b931083dc3f412ba0c95992cbc0638e3a2c
t4d-classes/advanced-python_04122021
/random_demos/gen_exp.py
262
4.15625
4
# fully enumerated when completed # double_nums = [x * 2 for x in range(10)] # list comprehension # enumerated as it is iterated over double_nums = (x * 2 for x in range(10)) # generator comprehension print(double_nums) for num in double_nums: print(num)
77a3f4cba65ef8330b85072e13fce70c23746f54
PlusWayne/Leetcode-solution
/504.base-7/base-7.py
383
3.625
4
class Solution: def convertToBase7(self, num): """ :type num: int :rtype: str """ res='' flag=0 if num==0: return '0' if num<0: num=-num flag=1 while num>0: remainder=num%7 res+=str(re...
e5ebc2159c5ce57efe17f18511cf08cc62105511
juanjoneri/Bazaar
/Interview/Practice/Dynamic-Programming/subset-sum-divisible.py
418
3.890625
4
""" Given a set of non-negative distinct integers, and a value m, determine if there is a subset of the given set with sum divisible by m. Input Constraints Input : arr[] = {3, 1, 7, 5}; m = 6; Output : YES Input : arr[] = {1, 6}; m = 5; Output : NO """ def subset_sum_divisible_by(numbers, divisor): ...
ae3e1d3fcf9ffc4caff47f46bbaac7b6d8176528
dsbrown1331/Python2
/Recursion/fibonacci.py
483
4.125
4
def fib(n): """recursive function that returns the nth Fibonacci number where fib(0) = 0, fib(1) = 1 and fib(n) = fib(n-1) + fib(n-2) """ print("calling fib({})".format(n)) #base cases if n == 0: print("returning 0") return 0 elif n == 1: print("returning 1") ...
1bfd02988e5f5ab4da9f83abc7b13b33517e408b
myohei/employee_mngr
/main.py
892
3.546875
4
# -*- coding: utf-8 -*- from EmployeeManager import EmployeeManager __author__ = 'yohei' def showMenu(): print(""" <MENU> ====================================== 1. 登録 2. 紹介 3. 削除 4. 更新(←時間なかったら実装しなくてもいい) ====================================== """) return True def main(): empMng = EmployeeManager() ...
983f46fc18435d014eb6759652b64c85f031c25c
Liverworks/Python_dz
/7.formatting_comprehensions/search.py
741
3.59375
4
l = [1,4,5,3,6,7,0,2] def lin_search(l, el): """ :param l: list :param el: element to find :return: index of element found """ for ind, i in enumerate(l): if i == el: return ind def bin_search(l, el, ind=0): """ :param l: sorted list :param el: element to find...
8d4f9d015481649d301b23863eafb87d87aeb911
benbendaisy/CommunicationCodes
/python_module/examples/1376_Time_Needed_to_Inform_All_Employees.py
1,976
3.84375
4
from collections import defaultdict from typing import List class Solution: """ A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct mana...
4332ed9e09378c6c3d3d40e87dec26ebf9ee9938
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/203/35027/submittedfiles/testes.py
112
3.640625
4
#coding: utf-8 n=int(input('digite n: ')) soma=0 for i in range (1,2*n,1): soma=soma+(1/2*i) print(soma)
bd74d9469abb2ab017e3b92cff988a85a833800a
Segura91Jonathan/conversor_de_moneda
/diccionarios.py
567
3.734375
4
def run(): mi_diccionario = { "key1" : 1, "key2" : 2, "key3" : 3, } # print(mi_diccionario) # print(mi_diccionario["key1"]) poblacion_paises = { "argeintina" : 45000000, "china" : 1000000000, "colombia" :50372424, } # print(poblacion_paise...
28377694dba67e97023c7f348380721b2c6400f0
oOoSanyokoOo/Course-Python-Programming-Basics
/Номер числа Фибоначчи.py
134
3.59375
4
n = int(input()) a = 0 b = 1 i = 0 while a < n: b, a = a + b, b i += 1 if a == n: print(i) else: print(-1)
d564ef3c7a178cc19f45f9ae545bb1b8f0466577
karakumm/puzzle
/puzzle.py
3,086
3.9375
4
''' Playing board for logic puzzle ''' def check_column(board: list, column: int) -> bool: ''' Checks if the column is valid. Returns True if yes, and False if not. >>> check_column([\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 2 ****"...
191e907bfb294cf8ee8612feee9fd3779efdf926
ViartX/PyProject
/lesson5_2.py
719
4.375
4
# 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, # выполнить подсчет количества строк, количества слов в каждой строке. # функция принимает строку и возвразает число слов в строке def get_words_number_in_string(str): str_list = str.split() return len(str_list) f_text = o...
87e23a56f8f847d0c10ce6ca3fc3e91a0f88920e
shreyansh-tyagi/leetcode-problem
/kth largest element in an array.py
510
3.96875
4
''' Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 Constr...
2568ec91318cdf17e0596778514afd508fc63f81
PaLaMuNDeR/algorithms
/Coding Interview Bootcamp/11_steps.py
2,054
4.25
4
import timeit """ Write a function that accepts a positive number N. The function should console log a step shape with N levels using the # character. Make sure the step has spaces on the right hand side. Examples: steps(2): '# ' '##' steps(3): '# ' '## ' '###' steps(4): '# ' '## ' '### ' '####...
01e30fe329eb82ef40a000faee97f9bab235e478
shadow-kr/My_python
/8_using_object_classe_make_player.py
1,528
3.78125
4
class gamer: #on cree le constructeur def __init__(self, name, hp,sp): #self est une base de données qui contient les elements contenus #self sert a affecter ces éléments name,hp... à la classe self.name = name self.hp = hp self.sp = sp self.weapon = None...
6b44f378ffc0e4cbb50255352b73cf766fbf76b6
ChandrakalaBara/PythonBasics
/basicAssignments/assignment14.py
475
4.25
4
# Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. # Suppose the following input is supplied to the program: # Hello world # Practice makes perfect # Then, the output should be: # HELLO WORLD # PRACTICE MAKES PERFECT inputLines = [] ...
81cb27ebaefd0262ee26455c113e1f8d593f83a8
RobertooMota/Curso_Python
/PythonMundo1/Exercicios/ex005 - sucessor e antecessor.py
136
4.15625
4
num = int(input('Digite um numero: ')) print('Numero digitado: {}, seu antecessor {}, seu sucessor {}.'.format(num, num - 1, num + 1))
c52301af398193471e0f0b235a01a1a2507a6204
alex4245/python_design_patterns
/creational/prototype.py
1,004
3.828125
4
from abc import ABC, abstractmethod from copy import copy, deepcopy class Prototype(ABC): def __init__(self, type, value): self._type = type self._value = value @abstractmethod def clone(self): ... def __str__(self): return f"Type: {self._type}, value: {id(self._value)...
4fc235960f4e8f99ecef246067175253bed36927
harishbharatham/Python_Programming_Skills
/Prob13_10.py
462
3.75
4
class Rational: def __init__(self, numerator = 0, denominator = 1): if denominator == 0: raise RuntimeError("Denominator cannot be zero") self.numerator = numerator self.denominator = denominator def main(): r1 = Rational() print("Default values:...
c9538e5d5f297447373c5840fca322d0d0a1b0cf
StevenDunn/CodeEval
/Pangrams/py2/pan.py
425
3.5625
4
# Pangrams solution in Python 2 for CodeEval.com by Steven A. Dunn import sys, string for line in open(sys.argv[1], 'r'): line = line.rstrip('\n').lower() alphabet = set(string.ascii_lowercase) missing_letters = alphabet - set(line) if len(missing_letters) == 0: print "NULL" else: missing_letters = li...
7d2ac4d5ce584e9ed818623704f814e91b2b276f
SamArtGS/Python-Intermedio
/Agenda.py
1,532
3.640625
4
import os personas = {} while True: print("----- AGENDA -----") print("1.Capturar datos del contacto") print("2. Ver datos") print("3. Ver todos los contactos") print("4. Eliminar contacto") print("5. Salir") opcion = int(input("\nElige una opción: ")) if opcion == 1: nombre = input("Escribe el nombre de ...
cd93953357e9662a46bec82f50578642b54da191
jschnab/data-structures-algos-python
/binary_trees/ast.py
1,246
4
4
class TimesNode: def __init__(self, left, right): self.left = left self.right = right def eval(self): return self.left.eval() * self.right.eval() def inorder(self): return "(" + self.left.inorder() + " * " + self.right.inorder() + ")" def postorder(self): retur...
5c74493806318799d18233995adcae879213b8b2
tsh/python-algorithms
/intervals/free_time.py
2,711
3.6875
4
from __future__ import print_function from heapq import * """ For ‘K’ employees, we are given a list of intervals representing the working hours of each employee. Our goal is to find out if there is a free interval that is common to all employees. You can assume that each list of employee working hours is sorted on th...
4ae9f4d6e36c323d7b77fe4f4b3a099d59919078
PiaNgg/t07_chunga.huatay
/iterar_rango_01.py
298
3.53125
4
#Contador del 0 al 20 import os for c in range(int(os.sys.argv[1])): #funcion iterar para poder indicar las repetiiones del valor segun el rango dado print(c) #se imprime el valor de la variable c entre el rango indicado #fin_iterar_rango print("fin del bucle")#se imprime fin del programa
1e5d6989eb5e4f1f8544ca49a666a35c00cf1dd4
sonushahuji4/Competitive-Programming
/Bit Manipulation/Sum_vs_XOR.py
172
3.5625
4
# Problem Statement Link : https://www.hackerrank.com/challenges/sum-vs-xor/problem n = int(input()) ans = 1 while n > 0: if n % 2 == 0: ans *= 2 n = n // 2 print(ans)
f858a27380c7aae9e94cf975404586efbb09f392
AdityaPrakash-26/450dsa
/Jayvardhan/linked-list-cycle/linked-list-cycle.py
447
3.640625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: slow_p = head fast_p = head while(slow_p and fast_p and fast_p.next): slow_p = slow_p...
d8a3b6f68a1baaf13380546fcb16a5c3e8ac29d9
GShyamala/GitRep_Selenium
/Py1/strings_concat.py
358
4.09375
4
name="johan" Age=123 print("Name is ",name,"Age is ",Age) print("Name is "+name+" Age is "+str(Age)) print("Name is {} and Age is {}".format(name,Age)) print("Name is {} and Age is {}".format(Age,name)) print("Name is %s and Age is %d" %(name,Age)) # print("Name is %d and Age is %s" %(name,Age)) ---- TypeError pri...
674a8ab1f9fecfcacb1765ab8e8a7f85f96cbc75
fp-computer-programming/cycle-3-labs-p22npiselli
/lab_3-1.py
322
3.96875
4
# Author: Nolan (AMDG) 9/29/2021 x = int(input("How many points did your team score? ")) if x >= 15: print("They won the gold") else: if x >= 12: print("They won a silver medal") else: if x < 9: print("No medal for you") else: print("They won the bronze"...
0ccd3b335c86e1e7a612b4841de3f263bbe6f30f
matheusmendes58/Python_fundamentos1
/dia mes ano.py
157
3.6875
4
dia = input (" dia ") mes = input (" mes ") ano = input (" ano ") print("o dia que voçê nasceu é",dia,"e o mês é",mes,"e o ano",ano,"correto?")
982cb9a456c3f5b914ef793b1fb55ea3353d659c
Hanlen520/-
/随机数字验证码/随机数字短信验证码.py
686
3.5625
4
import random verification_code = "".join(list(map(str, random.sample(range(0, 10), 6)))) # 将随机出来的内容通过map函数转换成字符串,再使用list方法将字符串转成列表 print("接收到的验证码为:" + verification_code) while True: code_str = input("请输入验证码:").strip() if not code_str.isdigit(): print("必须输入为数字,请重新输入!") elif len(code_str) != 6: ...
5c2c58bed2f1b98f88e82ec543cdf1f0c3eb1467
andreea-lucau/python-hello-world-package
/tests/greeting_test.py
1,008
3.609375
4
import unittest import hello.greeting class TestGreeting(unittest.TestCase): def test_get_greeting(self): expected_greeting = "Hello, Andreea!" greeting = hello.greeting.get_greeting("Andreea") self.assertEquals(greeting, expected_greeting) def test_get_greeting_name_not_valid(self):...
d8b64968678545adcf435b459aa930ec9a25e0b2
aravinve/PySpace
/utils.py
137
3.6875
4
def find_max(numbers): maximum = numbers[0] for n in numbers: if n > maximum: maximum = n return maximum
abda5fe2dbda6f1e5f9149f05fb480388523a6ab
GSchpektor/Python-Bootcamp
/week.4/day.1/xp.py
787
4.15625
4
# Exercise 1 # print("hello world\n" * 3) # Exercise 2 # print((99^3) * 8) # Exercise 4 # computer_brand = "mac" # print(f"I have a {computer_brand} computer") # Exercise 5 # name = "Guillaume" # age = 27 # shoe_size = 45 # info = f"My name is {name}, I am {age}, i have an average shoe size - {shoe_size}, but i'...
5c1264a8054112fc718f238a692776fd5bec55d0
pythonarcade/arcade
/arcade/examples/background_scrolling.py
3,448
3.6875
4
""" A scrolling Background. This program loads a texture from a file, and create a screen sized background. The background is constantly aligned to the screen, and the texture offset changed. This creates an illusion of moving. If Python and Arcade are installed, this example can be run from the command line with: py...
b98dc59f32b3633381855c7677e64b3e1c194f45
malmike/BucketListAPI
/tests/models/test_user.py
5,307
3.65625
4
""" Contains tests for the user model """ from unittest import TestCase from time import sleep from tests.base_case import BaseCase from myapp.models.user import User class UserTests(BaseCase, TestCase): """ Class contains tests for the user model """ def test_user_is_inserted_in_db(self)...
add8560a7cf81a8e057ba0de908fa8f0f76a2607
saji021198/player-set-1
/fact.py
80
3.65625
4
h=int(input()) fact=1 for i in range (1,h+1) : fact=fact*i print(fact)
d5c296062bb36c3063656eae5508d866a7947673
aliyarahman/code_that_only_does_one_thing
/v1-2018/read_a_csv/OurFirstCSVReader.py
898
4.09375
4
import csv #Python uses 'packages' to hold a set of tools you don't use all the #time. But you can import them when you need them. CSV is a package of tools for #working on CSVs. with open('the_file_name.csv', 'rb') as csvfile: event_file_reader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in event_f...
bf33ee135f6849481448cab4d99177c93bdd3ff7
luanrr98/Logica-Computacao-e-Algoritmos-Lista1
/Exercicio9.py
340
4.125
4
#Crie um algoritmo que calcule a área de um quadrado, sendo que o comprimento do lado é informado pelo usuário. #A área do quadrado é calculada elevando-se o lado ao quadrado. def area_quadrado(lado): area = lado**2 print(f"A Área do Quadrado é: {area}") lado = float(input("Digite o valor do lado: ")) area_q...
50f7d5611010a43965b0231838bd061ec67309d1
abhikrish06/PythonPractice
/DIC/Ch3/ch3_6.py
1,291
4.03125
4
import pandas as pd # Making data frame from a dictionary # that maps column names to their values df = pd.DataFrame({ "name": ["Bob", "Alex", "Janice"], "age": [60, 25, 33] }) # Reading a DataFrame from a file other_df = pd.read_csv("C:/Krishna/UB/Spring18/CSE 574 ML/proj1/slump_test_data.csv") # Making new c...
5cbb2241ff1d7cccda2b84f49670d87ce47a2970
Ajay-2007/Python-Codes
/hackerrank/Python/Introduction/python_if-else.py
395
4
4
# Problem Link # https://www.hackerrank.com/challenges/py-if-else #!/bin/python3 import math import os import random import re import sys def main(n): if n%2: print("Weird") elif 2 <= n <= 5: print("Not Weird") elif 6<= n <= 20: print("Weird") else : print("Not Weir...
6d29c28531f5603ff8757d946cbfd2af80b0b064
jmederosalvarado/daa-project
/icpc-finals/fibonacci-words/article/code.py
849
3.609375
4
# Nota: Este codigo solo cumple función ilustrativa # en el artículo, para ver una versión # completamente funcional, vea la carpeta solutions def kmp(text, pattern): pass def fibonacci_words(n, p): dp = [0]*(n+2) dp[0] = 1 if p == '0' else 0 dp[1] = 1 if p == '1' else 0 prefix, suffix = ['0',...
3dde3c6f74b194239bbde9667ecda89e13339450
hyperion-mk2/git
/Remove Duplicates from Sorted Array.py
489
3.765625
4
class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ deletenum = 0 index = 0 while index < len(nums) - 1: if(nums[index] == nums[index+1]): nums.pop(index) deletenum += 1 ...
df96413aa70595868b7097afa7d26da23fb78d29
Parzha/First_assignment
/ex3.py
1,953
4.28125
4
def BMI_calculator(W,H): H=H/100 return(W/pow(H,2)) def BMI_calculator_american(W,H): return((W/pow(H,2))*703) flag=1 while(flag==1): print("What measurment do you prefer => for kg/cm type 1 or for pounds/inches type 2 ") user_perference=int(input()) if user_perference==1:...
e92b91d5f7c47045a004078478b788235d3bd54a
95subodh/Leetcode
/069. Sqrt(x).py
182
3.703125
4
#Implement int sqrt(int x). # #Compute and return the square root of x. class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ return int(x**0.5)
c524d8fd919167cc6d1ccb28f301bb5da90744c5
saad181/CSPP1
/module 5/p4/square_root_newtonrapson.py
621
4
4
# Write a p_numthon program to find the square root of the given number '''writing newton rapson method to find square''' # using approximation method # testcase 1 # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991 def main(): '''using newton raphson method''' # epsilon...
86d627967d3becda11b8579fce200bc1aaa36f13
gburdge/python-exercises
/Project 5/Project 5.py
357
3.671875
4
from datetime import date with open("dates.txt") as f: lines = f.readlines() # f represents file with data lines = [int(l) for l in lines] t = date.today() # t represents today for l in lines: # l represents line d1 = date.fromtimestamp(l) td = d1-t # td represents today's date print "%s is ha...
4d62cba71ad14de4792ecdaa9ad0ffe56e796ef8
JLMunozOl/curso-python-1
/clases/clases.py
3,180
3.953125
4
#!/usr/bin/env python3 from math import pi class Foo(object): a = 1 b = "Soy Foo" class Gato(object): numero_de_patas = 0 color = "negro" cv = "" def __init__(self, nombre="Juan"): self.nombre = nombre def dormir(self): print("Yo el gato {} estoy durmiendo. Zzzz...".fo...
4a4c9a78851d100e6b08ce93a43aa1410c47ee8c
Jawaharbalan/python-programing
/oddeven.py
165
3.84375
4
import sys try: a=int(input("input:")) except ValueError: print ("Error..numbers only") sys.exit() if(a%2==0): print("even") else: print("odd")
ea36e998000a658daf09bb2d7c165be3f525baac
dogeplusplus/Python-Projects
/Data Science from Scratch/Histogram.py
793
3.734375
4
from matplotlib import pyplot as plt from collections import Counter grades = [83,95,91,87,70,0,85,82,100,67,73,77,0] decile = lambda grade : grade // 10 * 10 histogram = Counter(decile(grade) for grade in grades) plt.bar([x - 4 for x in histogram.keys()],histogram.values(),8) plt.axis([-5,105,0,5]) plt.xticks([10...
d3d0a62c5ec422a61807dba09fee5fb8414dfa37
vampypandya/LeetCode
/146. LRU Cache.py
1,479
3.546875
4
class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.drum = {} self.cap = capacity self.latest = [] def get(self, key): """ :type key: int :rtype: int """ # print key,self.drum if ...
ad53c130d412a4516d37140ce11350cb2f3e6b7a
Beasted1010/MachineLearning_Assignment
/hw3reg.py
1,106
3.546875
4
import pandas as pd from sklearn import linear_model from sklearn.metrics import mean_squared_error housing_data_set = pd.read_csv('boston_housing.txt', header=None) housing_data_set = housing_data_set.values #print(housing_data_set) shape_list = housing_data_set.reshape(housing_data_set.shape[0]) split_list = [val.sp...
d1e18fb781aeaba07da06e92206b178f04d5af60
erjan/coding_exercises
/network_delay_time.py
1,941
3.8125
4
''' You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We will send a signal from a given node...
eb8a5f62736252db16bcccccd378be78dc7e9268
vishantbhat/myfiles
/test-files.py
1,039
3.953125
4
""" my_input_file = open("hello.txt", "r") print ("Line 0 (first line):", my_input_file.readline()) my_input_file.seek(0) # jump back to beginning print("Line 0 again:", my_input_file.readline()) print("Line 1:", my_input_file.readline()) my_input_file.seek(8) # jump to character at index 8 print("Line 0 (starting at...
9834c629e5cf95ab25c168db1b36afbbb5ddc733
Sahil4UI/PythonJan3-4AfternoonRegular2021
/list exercise.py
1,596
4.03125
4
#store numbers from 1-10 in list '''x= [] for i in range(1,11): x.append(i) print(x) ''' #list comprehension ''' x = [i for i in range(1,11)] print(x) ''' # #find the largest element from the list ''' x = [-100,1,1000000,2,1000000,1000000,1000000,5,900,2000] largest = -9999999999 secondLargest = -888888888 for i ...
bc44d40fa8ca4f4de80c2e56a0d6c4d3a3ae7d5c
projeto-de-algoritmos/Grafos1_Labirintite
/main.py
2,250
3.515625
4
import random import pygame import queue from Constantes import size, cols, rows, width, GREY import Theme import maze_generator as mg from Cell import Cell, removeWalls, reload_colors from importlib import reload pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption("Maze Ge...
5c98f1d881b88a6dae99e17a5fc5d2682d8923e9
barrymun/euler
/30-39/38.py
942
3.828125
4
MAX_LEN = 9 DIGIT_CHECK = [str(i) for i in xrange(1, 10)] def derive_pandigital(n): """ """ r = "" x = 1 while len(r) < 9: r += str(n * x) x += 1 return r def has_pandigital_multiples(n): """ """ r = "" x = 1 while len(r) < 9: r += str(n * x) ...
5bc66a4c52a3bbb68b6bdad3115a77c4ab254e08
savlino/2019_epam_py_hw
/03-fp-decorator/hw2.py
471
3.96875
4
""" function is_armstrong allows to check if the given number is one of Armstrong(narcissistic) numbers """ import functools def is_armstrong(int_number): number = str(int_number) digits = [int(number[x]) for x in range(len(number))] dig_sum = functools.reduce(lambda x, y: x + y**len(number), digits) ...