blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fe525faad8235cb419f509c20b18103499eabdba
iamkissg/leetcode
/leetcode/101.symmetric_tree.py
2,295
4.03125
4
from queue import deque # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # Time Limit Exceeded # def isSymmetric(self, root: TreeNode) -> bool: # from queue import Queue # ...
f686e8eeda9488b3c98a7db06903e8fe734a8a78
basic1aw/Excercise_for_Algorithm
/Easy_Medium/try_finally.py
412
3.890625
4
def test(): try: a = 3 return a except: pass finally: a += 3 return a # 1. 当try代码块中有return语句时,先执行return语句再执行finally代码块 # 2. 当finally中也有return语句,且return的是同一个变量,那么只会返回 # try中的变量对应的值,finally中对变量进行修改后也不会影响返回的值
a24fc2b98c5650ae145eb76b99a75f394d0b3d20
Wei-Mao/Assignments-for-Algorithmic-Toolbox
/Dynamic Programming/Edit Distance/edit_distance.py
678
3.578125
4
# python3 def edit_distance(first_string, second_string): m, n = len(first_string), len(second_string) D = [[0 for _ in range(n+1)] for _ in range(m+1)] for j in range(n+1): D[0][j] = j + 1 for i in range(m+1): D[i][0] = i + 1 for i in range(1, m+1): for j in range(1, n+1)...
d721070a49e68361c5e41b083e44c87c554c9058
BowenLiu92/CodeWars
/Find the next perfect square.py
129
3.546875
4
def find_next_square(sq): sq_rt = float(sq**0.5) if sq_rt.is_integer(): return (sq_rt + 1)**2 return -1
84594b899582ac270fbabe72c0c885adfc9bd370
yuchenzheng/week-3-assignment
/creat by my own.py
1,443
4.15625
4
import random def main(): lenth = get_lenth() compare(lenth) # get the lenth of word from user and a random number def get_lenth(): lenth_1 = random.randint(2, 8) lenth_2 = int(input('choose a lenth of word.(2-8)')) # set these two number as a tuple to return lenth = (lenth_1, lenth_2) r...
d4ce6f2832aaa7230eceeaa90150a33c763e955d
hotheat/LeetCode
/104. Maximum Depth of Binary Tree/104.py
662
3.671875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def maxDepth(self, root: 'TreeNode') -> 'int': if root is not None: level = 1 ...
f8fcbf04869d6f0a607ac67a06d8bac674927505
zhu2qian1/Python_public
/AOJ/ALDS1/2/d.py
1,099
4.09375
4
src = r"https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/2/ALDS1_2_D" # ---- solution ---- def insertionsort(a, g, c) -> int: """ a ::= an array of the sorting target g ::= a distance for distanced insertion sort c ::= a variable for cnt returns c """ cnt, n = c, len(a) for i ...
b852f69f8914f4c5a7993e959194d7feee5ad1c3
wasshoy/cpaw-ctf
/level1/q6.py
385
4.1875
4
def encrypt(s): if not type(s) is str: print('Please give me string!') return alphabets = tuple(chr(ord('a') + i) for i in range(26)) + tuple(chr(ord('A') + i) for i in range(26)) return ''.join([chr(ord(c) - 3) if c in alphabets else c for c in s]) if __name__ == '__main__': res = ...
e50c369b505c61b1f02cac86122ce18a4a439c2e
AnnaCilona/PythonExercises
/EjHoja1/5.py
634
4.09375
4
'''Ejercicio 5. Escriba un programa que pregunte la edad al usuario, la fecha actual, y en qué día y mes es su cumpleaños, y en base a esa información calcule su año de nacimiento.''' edad=int(input("Cuántos años tienes?")) diaHoy=int(input("Qué día es hoy?")) mesHoy=int(input("En qué mes estamos? (En número)"))...
771583d7e66957c8c3dbcb8c094c0ea1c4a2aff1
gilberto-009199/MyPython
/algoritimos/uri/Extemant basic/main.py
94
3.53125
4
# -*- coding: utf-8 -*- val0 = int(input()); val1 = int(input()); print("X =",val0 + val1);
6fe76eff4f9b3a0532fa2ce15c7cb2165cf2d5a5
Ebrahiem-Gamal-Mohamed/Python_Labs
/Assignments/lab1/calcArea.py
912
3.984375
4
#Write a function that calculate the area of these shapes: #triangle = (0.5 * base * height), rectangle = (width * height), Circle= (PI * radius ^ 2) def calcArea(shapeName,dim1=0,dim2=0): if shapeName == "t": return (0.5 * dim1 * dim2) elif shapeName == "r": return (dim1 * dim2) elif shape...
bc229fbfd200609dae0c0737eb1a084d70524628
zerghua/leetcode-python
/N1399_CountLargestGroup.py
1,140
4
4
# # Create by Hua on 4/6/22. # """ You are given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size. Example 1: Input: n = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according sum of its digits o...
cb8d3274e1ffa09834596623eea22cefd3fa4e03
Michal-lis/python_playground
/Algorithms_and_data_structures/insertion_sort.py
385
3.5625
4
a = [4, 6, 7, 3, 2,52,34,123,22,0] def insertion_sort(l): for idx, elementi in enumerate(l): temp = elementi for jdx, elementj in enumerate(l): if jdx == idx: break elif elementj > temp: l[jdx] = temp l[idx] = elementj ...
7a6f7082d74a74f295edc79ca522c953f463fd4f
opickers90/Python2-1
/Breakloop.py
103
3.96875
4
i = 0 while 1==1: print("in the loop") i += 1 if i>=10: print("Break") break print("Finished")
f8bf672ddceb477766bc2a6b221cefd098669c0f
ltang93/python
/python快速上手练习/8.9.2.py
972
3.71875
4
''' The ADJECTIVE panda walked to the NOUN and then VERB.A nearby NOUN was unaffected by these events. ''' import re def MadLibs(newList): txt=open('D://1.txt','r') text = txt.read() adjectivere=re.compile(r'ADJECTIVE') text=adjectivere.sub(newList[0],text) nounre = re.compile(r'NOUN') text=noun...
4d08f6a7d8486840885a5a54841e91d7c1d4f5eb
simtb/coding-puzzles
/leetcode-may-challenge/single_element_sorted_array.py
857
4.03125
4
""" You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. """" from typing import List class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: sin...
8e9085756a26e9b74de6040f31d080e5c2bb3d50
NizanHulq/Kuliah-Python
/UTS/suit.py
404
3.71875
4
blangkon = input() semar = input() if blangkon == semar: print('Seri') elif blangkon == '[]' : if semar == '()': print('Blangkon') else: print('Semar') elif blangkon == '()' : if semar == '8<': print('Blangkon') else: print('Semar') elif blangkon == '8<' : if...
ddb29b2cc3258bb5c4039bc37408a32ad975e926
FFFutureflo/CodingChallenges
/codeforces/800/ILoveUsername.py
1,241
3.78125
4
""" https://codeforces.com/problemset/problem/155/A """ def function(): n = int(input()) points = list(map(int, input().split())) counter = 0 for i in range(1, n): subcounter_highest = 0 subcounter_lowest = 0 for a in range(0, i): if points[i] > points[a]: ...
03e1a28bf28cac794c7feb395b6de13fdb563575
ranabanik/DebugTorch
/Codes/BabyNetwork/ConvNetStepbyStepUtils.py
601
4.0625
4
import numpy as np def zero_pad(X, pad): """ Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, as illustrated in Figure 1. Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images pad -- integer, amount...
bff8345439b68b039fc0d141ffc2c1418d3418e7
uneves/exercicios-cursoemvideo-python-01
/exerciciios/ex016.py
466
4.125
4
#import math from math import trunc num = float(input('Escreva um número real com 3 ou mais casas decimais')) print('O número real {} equivale ao numero inteiro {:.0f}'.format(num, trunc(num))) # ou truncando na formatacao do campo num = float(input('digite um valor')) print('A porcao inteira de {} é {:.0f}'.format(num...
7903013ecf186e776d006f7306a2cf04d67c7db4
zhuyurain888/python_test
/home_work/day_01/list_null.py
821
3.703125
4
'''义一个空列表,用于保存5个学生信息,一个学生信息包括三个属性:id、姓名、年龄 提示:列表元素是字典、向列表中添加数据用append()''' lst=[] lst.append("{'id': 1, 'name': '小明', 'age': 18, 'python_s': 78}") lst.append("{'id': 2, 'name': '小花', 'age': 19, 'python_s': 88}") lst.append("{'id': 2, 'name': '小聪', 'age': 20, 'python_s': 98}") print(lst) str1=input("请输入一个字符") '''1. ...
d960555bdf1c39544242952228ace3115b65dcd6
abhisjai/python-snippets
/MIT 6.00.1X/Excercises/Final/ps4.py
1,000
4.21875
4
def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ # Your code here # Create a dictionary of all integers in list L list_dict = {} for i in L: ...
7866ee064c4344ca52193295b3f2bee8a3be0aa5
littlecodemaster/python_practice
/tax3.py
1,540
3.796875
4
#cutoff_list = [0, 0, 0, 0, 0, 0] #print(cutoff_list[0]) def calc_income(income, tax_list,income_list): cutoff_list=[0]*len(income_list) cutoff_list[0]=tax_list[0]*income_list[0] for i in range (1,len(income_list)): cutoff_list[i]=cutoff_list[i-1]+(income_list[i]-income_list[i-1])*tax_list[i] ...
cfb77b737396b0a4f63cd145ef49fd76f160d580
SpenceGuo/my_leetcode
/problem_algorithms/python3/59.py
952
3.78125
4
from typing import List import numpy as np class Solution: def generateMatrix(self, n: int) -> List[List[int]]: result = np.zeros((n, n), dtype=int) target = n * n left, right, top, bottom = 0, n-1, 0, n-1 index = 1 while index<=target: for i in range(left, righ...
e2d88898dbc112c5108c98ea37437de18702d8e7
EmmanuelSR10/Curso-Python
/Funciones/Ejercicio_5.py
1,021
4.21875
4
""" Realiza una función llamada recortar(numero, minimo, maximo) que reciba tres parámetros. El primero es el número a recortar, el segundo es el límite inferior y el tercero el límite superior. La función tendrá que cumplir lo siguiente: Devolver el límite inferior si el número es menor que éste Devolver el límite s...
5bcbfa7ed41fcc8c7d48a46ec68eb15f88368dc5
zzj0311/interesting-algorithoms
/sol3/sol3.py
10,933
3.53125
4
class Hero: def __init__(self, HP = 0, AP = 0, BUFF = 0, pos_x = 0, pos_y = 0):#pos_x 为行数,pos_y 为列数(just a reminder self.HP = HP self.AP = AP self.BUFF = BUFF self.pos_x = pos_x self.pos_y = pos_y class Monster: def __init__(self, HP = 0, AP = 0, hasBuff = False, pos_x =...
1d402b9f06ddece2544dfe2e14bf2c1cd6d1cf73
samuelveigarangel/CursoemVideo
/ex10_conversorMoeda.py
138
3.828125
4
n = float(input('Digite o numero de reais a serem convertidos :')) print(f'Quantidade de reais: {n}. Quantidade em dolares: {n/5.34:.3f}')
fe57dfb893d09ed141e251663bc8651d0b8fff6c
laeberkaes/ctf_scripts
/Python3/hex2ascii.py
173
3.796875
4
def hexdecoder(hex): return ''.join(chr(int(hex[i*2:i*2+2], 16)) for i in range(len(hex)//2)) if __name__ == '__main__': n = input("hex:") print(hexdecoder(n))
faa1aa23372fba59a70def3515c53e8a3050cedc
robinsonium/python
/oop/car.py
2,009
4.25
4
import unittest class Car: def __init__(self, make, model, year): """ initialize attributes to make a car""" self.make = make self.model = model self.year = year self.odomoter_reading = 0 def get_descriptive_name(self): """ return a nicely formatted long nam...
ca926026e709385444f0d575288e81a61fd5afdb
31337root/Python_crash_course
/Exercises/Chapter8/10.User_profile.py
409
3.734375
4
def build_profile(first, last, **user_info): """Build a dictionary containing everything we know about a user.""" profile = {} profile["first_name"] = first profile["last_name"] = last for key, value in user_info.items(): profile[key] = value return profile print(build_profile("Omar", "...
d260afa923db638e0874ac6982c4be5af88c5f17
nozokada/cracking-the-coding-interview
/chapter_1/exercise_1_3.py
428
3.65625
4
def are_permutations_each_other(str_1: str, str_2: str): if len(str_1) != len(str_2): return False counter = {} for char in str_1: if char in counter: counter[char] += 1 else: counter[char] = 1 for char in str_2: if char not in counter or counter...
f5b61e9688d1a60ef20c63e5d6076ce9050fe522
JacobHayes/Pythagorean-Theorem
/Pythagorean Theorem.py
1,984
4.375
4
# Jacob Robert Hayes # Pythagorean Theorem # C^2 = B^2 + A^2 import math print "This program if for calculating the Pythagorean Theorem." print "If the program crashes, an invalid answer was entered, please restart." Solve_For = raw_input("\nWhich variable are you solving for; A, B, or C? ") while not Solv...
a3405ecd732ba3e0afe8f06ec3bf16055ae69aad
gabriellaec/desoft-analise-exercicios
/backup/user_139/ch45_2020_06_22_14_17_06_049757.py
152
3.953125
4
lista = [] n = int(input('Número inteiro: ')) while n > 0: lista.append(n) n = int(input('Número inteiro: ')) lista = lista[::-1] print(lista)
6c15ca1c416a6049f6743e53bd625e73809daa71
joshua2579/inf1340_2014_asst1
/exercise1.py
2,891
4.5
4
#!/usr/bin/env python3 """ Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion This module contains one function grade_to_gpa. It can be passed a parameter that is an integer (0-100) or a letter grade (A+, A, A-, B+, B, B-, or FZ). All other inputs will result in an error. Example: $ python ex...
8d8096213829158ad4f0bddf02ceb18009ca28f7
CadeSummers/Cryptocurrency_Analysis
/coin_db_creation.py
510
3.9375
4
import sqlite3 #creation / connect of the database in current directory coin_db = sqlite3.connect('cryptocurrencies.db') #creation of a cursor instance c = coin_db.cursor() #execution of SQL creating new table coins c.execute("""CREATE TABLE coins ( name TEXT, symbol TEXT, rank INTEGER, ...
223eccba5e0d5c152cb22b3e8cd3b37c09f70be7
meera-ramesh19/sololearn-python
/howtouselist.py
605
4.21875
4
list_1=[] list_2=list() print("list_1:{}".format(list_1)) print("list_2:{}".format(list_2)) if list_1==list_2: print("lists are equal") else: print("lists are not equal") even=[2,4,6,8] another_even=even print(another_even is even) another_even.sort(reverse=True) print(even) another_even=list(even) print(...
93ddb35ab330f007c27a6528acff48f9238e943c
mhichen/Patterns
/Sliding_Window/smallest_subarray_given_sum.py
1,307
3.984375
4
#!/usr/bin/python3 import math # Given array of positive numbers and a positive number S # find the *length* of the smallest contiguous subarray whose # sum is greater than or equal to S # Return 0 if no such subarray exists def smallest_subarray_with_given_sum(arr, S): _sum = 0 min_length = math.inf wsta...
61163fa5fdb514928ac849b6868eee2643925803
collins-emasi/simple_login
/login.py
1,181
3.859375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 16 09:09:40 2019 @author: pythonister """ class User(object): def __init__(self, username, password): """Assumes username and password are strings""" self.username = username self.password = password def getName(self, password): ...
0bb4a4b2046539bc803d62b80abbe322539135ef
BlaisMathieu/302separation
/302separation.py
5,136
3.5625
4
#!/usr/bin/env python3 import sys from math import * list = [] all = [] y = 0 class people: def __init__(self, name): self.name = name self.friends = [] self.visited = False def addFriend(self, friend): self.friends.append(friend) def getFriends(self): ...
d63ca90657ca717df9f64bfad0d881a63d2bad25
WarrenU/Python-Practice-Problems
/8-Two-Nums-LL-LC.py
1,189
3.859375
4
# You are given two non-empty linked lists # representing two non-negative integers. # The digits are stored in reverse order # and each of their nodes contain a single digit. # Add the two numbers and return it as a linked list. # You may assume the two numbers do not contain # any leading zero, except the numb...
d7e6a3f5daacf065d94505134eb4d071d1ed7676
edjrbashian/bigdata
/sdo_event_video.py
1,536
3.515625
4
from datetime import date, timedelta import urllib2 import ctypes from HTMLParser import HTMLParser import webbrowser import urllib #this script will aim to download all SDO instrument videos ending with .mp4 #print yesterdays date yesterday = date.today() - timedelta(1) yesterday_date = yesterday.strftime('%Y/%m/%d/...
aff24a831b1dcca4bc60254bf8fe136f6676c70d
Stevemz09/Hello-World
/whileloops.py
771
4
4
''' 1) Swap two variables ''' #a=5 #b=10 #print('a=',a,'b=',b) # Create a temporary variable temp #temp=a # Save the value of a in the temp variable #a=b # a is getting the value in b #b=temp #print('The new variables a =',a,'b=',b) # write all integers between 1 and 9 using a while loop #x=1 #...
a7562ff17d8f178f143e7beeb32da9910f644562
PrajwalHR/MasteringPython
/farm.py
1,280
3.84375
4
print("Welcome to South Indias Farmers help line center ") print() print("_"*45) a=input("Enter your name:") print("_"*45) b=a.upper() print() print("Welcome {} , I am hear to help you".format(b)) print() print("_"*45) print() def FarmersHelpline(): ChosenState=input("Where are you from \n1)KARNATAKA \n2)A...
0582b6b94ee7002ba310ff37d208231c7aa3fe03
mnuman/PythonForInformatics
/Exercise_52.py
762
4.125
4
""" 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and p ut out an appropriate message and ignore the number...
240fe9fe95e57b145d0352aadeacdeebb3b774e9
chasel2361/leetcode
/Algorithms/ValidAnagram/ValidAnagram_1.py
342
3.515625
4
from collections import Counter class Solution: def isAnagram(self, s: str, t: str) -> bool: s = Counter(s) t = Counter(t) for key, value in t.items(): if key not in s.keys() or value != s.pop(key): return False if len(s.keys()) > 0: return Fal...
ea0118e9cc6e1bcf3d104c0f162bbc9cf19fc3d9
IceMIce/LeetCode
/Hash Table/136. Single Number.py
385
3.5625
4
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ dic = {} for num in nums: dic[num] = dic.get(num, 0)+1 for key, value in dic.items(): if value == 1: return key retu...
6bd59668e2554ff12ed4b9f39d765246967f2c0f
gidleyw/web-caesar2
/vigenere.py
966
4.0625
4
from helpers import alphabet_position, rotate_character import string alphabet_list = list(string.ascii_lowercase) def encrypt(text, key): encrpytion_key_list = [] encrypted_list = [] e_counter = 0 for i in key: ### take each letter in encrpytion key and assign alpha value encrpytion_key_list....
9eeb5b7b631df4aa18fe76aae46a654cc277426c
pengnam/DailyCodingProblemSolutions
/Problem2-ReturnArrayCumulativeSum.py
468
3.65625
4
def solution(array): n = len(array) result = [1] * n left_product = array[0] for i in range(1,n): result[i] = left_product * result[i] left_product = left_product * array[i] right_product = array[-1] for i in range(n-2,-1, -1): result[i] = right_product * result[i] ...
ef1fd572b4683cf743c66bb6f8bd6a983514bd9a
ArnyWorld/Intro_Python
/13.-POO_Encapsulamiento.py
1,079
3.75
4
#Una clase debe comenzar con una Mayúscula class Alumno: #Constructor def __init__(self, nombre, registro,sexo, semestre): """Por defecto los atributos son públicos, si se quiere cambiar a privado la variable debe comenzar con doble barra baja (__nombreVariable) si se quiere manejar un...
7b0bc53ccd38450fdbb547ad59a6069005dd816e
jusui/Data_Science
/Basic_Stat/binomial.py
1,928
3.875
4
#coding: utf-8 """ 功する確率がp、失敗する確率がq(=1−p)の実験を、同じ条件で独立に繰り返すことをベルヌーイ試行Bernoulli trial)とよび、 表が出る確率がpのコインを何度も投げる実験がベルヌーイ試行に対応します。 http://lang.sist.chukyo-u.ac.jp/classes/PythonProbStat/Intro2ProbDistri.html """ import matplotlib.pyplot as plt import numpy as np import numpy.random as random def factorial(n): if ( n...
5b0c5705a932946a831e89abf043ed854a83a3e4
ikshitjalan/Django_python
/Python_Beginner/exercise2.py
831
3.78125
4
# list = [1,1,2,3,1] # list = [1,1,2,4,1] # list = [1,1,2,1,2,3] # def arrayCheck(num): # f_list = [] # for i in num: # if ((num[i]==1)or(num[i]==2)or(num[i]==3)): # number = num[i] # f_list = f_list.append(number) # return f_list # result= filter(arrayCheck(),list) # pri...
b025d28f8bfc6238785a73355a11c0af34d26e87
Mohamedking451/robot-pro
/Number_guessing.py
840
3.890625
4
import random list5 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] N = (random.choice(list5) + random.choice(list5)) S = (random.choice(list5) * random.choice(list5)) G = (random.choice(list5) / random.choice(list5)) Fall = [N, S, G] while True: for x in Fall: if x > 50: print(x) print("its larger than then 50") ...
9b954f62ffa00eef0a800aef7bc4c26578028cfa
Oneuri/DAA
/swapping.py
199
4.03125
4
print("Enter value of a") a=int(input()) print("Enter value of b") b=int(input()) a = a+b b = a-b a = a-b print('New value of a is:') print(a) print('New value of b is:') print(b)
8da269f70ca6cee6c08e6de27a6743cdb42d6392
reeshad/OLS-Regression
/new OLS.py
984
3.625
4
import numpy as np import matplotlib.pyplot as plot from matplotlib import style from statistics import mean style.use('ggplot') x_dataset = np.array([10,30,54,67,84,91]) y_dataset = np.array([9,15,43,51,67,87]) #Formulas for linear regression #y = mx + b #Yi = B1*Xi + B0 (without considering random er...
7b9181107bd8fea5db683e5e80a10e978ebd0794
roozemanjari/cyber
/Assignment 3/Question 7.py
479
3.609375
4
def summer_69(arr): if not arr: return 0 else: sum=0 result=True for x in arr: if result: if x!=6: sum+=x else: result=False else: if x==9: ...
b24605eadfef4abdc1c79e47e2ec5c23e9668dda
giinie/CSBootcamp
/src/learn_python_the_right_way/unit_38/judge_try_except_else.py
319
3.578125
4
class NotPalindromeError(Exception): def __init__(self): super().__init__('회문이 아닙니다.') def palindrome(word): if word != word[::-1]: raise NotPalindromeError else: print(word) try: word = input() palindrome(word) except NotPalindromeError as e: print(e)
abf26f1ea68b7e2e18e5a5e2aad48a7165a69cbd
ClarityOfMind/simple-chatty-bot
/Problems/Good rest on vacation/task.py
220
3.75
4
duration = int(input()) food_cost = int(input()) one_way_flight_cost = int(input()) hotel_cost = int(input()) total_cost = (one_way_flight_cost * 2) + (food_cost + hotel_cost) * duration - hotel_cost print(total_cost)
87aeb6f3e69756adbd4eb06eab0074130045159a
veken1199/Algorithms
/Python/HeapSort.py
417
3.609375
4
import DataStructures.BinaryTree as bt tree = bt.BinaryTree() # Duplicates in the array are not supported def insertIntoTree(arr): for num in arr: node = tree.insertNode(num) node.index = arr.index(num) def Heapify(tree): # find the max, replace it with the root, and swap the arra...
8cb26a891ffb8e1b8a27fe34a528b582d7f313ff
sinchanasomayaji/project
/python programs/gcd.py
166
4.15625
4
print('enter 2 numbers to find gcd') num1=int(input()) num2=int(input()) while(num2!=0): temp=num2 num2=num1%num2 num1=temp gcd=num1 print('GCD is ',gcd)
e252416666e6b85d59a2fdc73dcbd22728dc60a3
Aasthaengg/IBMdataset
/Python_codes/p03502/s702128002.py
135
3.53125
4
N=int(input()) temp=N f=0 for i in range(8): f+=N%10 N-=N%10 N=N//10 if temp%f==0: print("Yes") else: print("No")
cc33ff29ebfe3f575a8b27bcfd340246455c8d08
BobGu1978/ScanVBS
/source/ScrolledTreeView.py
1,022
3.609375
4
from tkinter import * from tkinter import ttk class ScrolledTreeview(ttk.Treeview): """this class is to define one tree view with scroll bar at right side""" def __init__(self, parent=None): scb=Scrollbar(parent) scb.pack(side = RIGHT, fill=Y) hscb=Scrollbar(parent , orient = 'horizonta...
4d3813a32fd10eddf50e537791e7aa4ed8e13f32
Tonschi/learn_python
/ex6.py
576
3.953125
4
# start of the binary joke x = "There are %d types or people." % 10 # declare binary variable binary = "binary" # declar do_not variable do_not = "don't" # end of binary joke y = "Those who know %s and those who %s." % (binary, do_not) # print the binary joke print x print y print "I said: %r." % x print "I also s...
81a59b33bf439444a388ab3bc58a3837fd0d56bb
alexforcode/adventofcode
/day07/circus_part1.py
1,605
3.921875
4
'''http://adventofcode.com/2017/day/7''' import re class Tower: def __init__(self, name, weight, branches): self.name = name self.weight = weight self.branches = branches def find_tower(input_str: str) -> Tower: ''' Return Tower object with name, weight and branches from input_...
bdc788ed44675589a5e13b67f69f14d97f186d2a
anyatran/school
/CG/SciPy/walker_spider_1.py
4,478
4.09375
4
""" Program name: walker_spider_1.py Objective: A walking spider with positive and negative knee bends . Keywords: canvas, walk, trigonometry, time, movement ============================================================================79 Explanation: The number of frames in the stride for one foot is the numbe...
d25784eb3e0ca284d960db98175d598defe54af7
emakris1/CheckIO
/sum_numbers.py
396
4.1875
4
#!/bin/python import re def sum_numbers(text: str) -> int: numbers_sum = 0 # use regex to find matches # pattern is one or more digits not contained within a word boundary numbers_matches = re.findall("\\b\\d+\\b", text) # convert string matches to ints and sum them for match in numbers_matc...
97f1273ede7324886c2363513b194c0a0ddd7d35
Cekurok/codes-competition
/hackerrank/python/Strings/string-validators-English.py
391
3.65625
4
if __name__ == '__main__': count = [None]*5 s = input() for i in range(len(s)): if s[i].isalnum(): count[0] = True if s[i].isalpha(): count[1] = True if s[i].isdigit(): count[2] = True if s[i].islower(): count[3] = True if s[i].isupper(): count[4] = True for i i...
3f641c55070343e36c6a09a755dfa8026aace4f9
rbose4/Python-Learning
/Chapter10-Inheritance.py
4,653
4.09375
4
############################## Inheritance ########################## ###################### Example 1 ######################## ## # This module defines a hierarhy of classes that model exam questions # ## A question with a text and an answer # # class Question: # ## Constructs a question with empty question and ...
c9bfacb0fabb55921f3aa4f036c79c34ef842cce
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/f6d037e48f624007a2be9ccf80cf1127.py
952
4.15625
4
# # Skeleton file for the Python "Bob" exercise. # def hey(what): if len(what) == 0 or what.strip() == '': return 'Fine. Be that way!' else: stripped_what = what.strip() last_char = stripped_what[-1] if last_char == "?": """ This fails on the test_force...
2a66adec5387c4319f1e8a89704692873153af53
Master-Issac-Chan/CP1404-PRACTICALS
/Prac_10/recursion.py
1,065
4.28125
4
""" CP1404/CP5632 Practical Recursion """ def do_it(n): """Do... it.""" if n <= 0: return 0 return n % 2 + do_it(n - 1) # TODO: 1. write down what you think the output of this will be, # TODO: 2. use the debugger to step through and see what's actually happening print(do_it(5)) # 5 % 2 = 1 2 +...
3c489b648fd9789de0ff5bd136c4a35e1ef20a6b
rphlgngs/sorted-dico
/SortedDico.py
3,241
3.765625
4
class SortedDico(dict): """Classe permettant de créer un dictionnaire que l'on peut trier""" def __init__(self, **couple): """Constructeur qui créer une liste contenant les clés et une autres contenant les valeurs. Si rien n'est passé en paramètre, on créer un dictionnaire vide.""" self._cle_dico = ...
b5da58614656c0ddb94b2b62f161c4092754e241
adocto/python3
/hackerRankOlder/tictactoe.py
4,950
4.03125
4
# game # initialize game: >>COMPLETE # - set or reset board to empty board # - print board # print board: >>COMPLETE # - print status of board # prompt player for input: >>COMPLETE # - set of coordinates # - if validate move is true: # - set on board (place player marker on spot on board) ...
9f79bdf89a2b4d79e49421b72596be90129001c3
ktram80/PYTHON
/nametag.py
496
4.1875
4
#!/usr/bin/env python3 #The nametag function uses the format method to return first_name and #the first initial of last_name followed by a period. #For example, nametag("Jane", "Smith") should return "Jane S." def nametag(first_name, last_name): return("{} {}.".format(first_name, last_name[0])) print(nametag("Jane...
8b9594c6698cea15a17a1f58ded491ac05d58e4f
olayinkade/LightUpPuzzle
/library.py
2,271
3.828125
4
from typing import List stack = [] variables = [] invalid_wall = [] valid_wall = [] # This function reads in the puzzle from the text file and returns it as a list of lists, where the lists are the rows def read_puzzle(): txt_file = open('puzzle.txt') txt_file.readline() dimension = txt_file.readline().s...
1a3f913a08593aff5ae7261857fdc26502c46fce
MarcosRibas/Projeto100Exercicios
/Python/ex071.py
843
3.859375
4
""" Ex071 ”Simulador de caixa eletrônico” Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunta ao usuário qual será o valor sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: Considere que o caixa possui cédulas de 50, 20, 10 e 1. ""...
3260d751dcec3f9590b241947a088527eefdfadb
tlhlee838/learntocode
/python101/solutions/018_vacation_exercise_DONE.py
4,676
4.03125
4
# this is a little silly, but will reinforce everything # required to start using internet-based APIs # create a dictionary that will represent our checked bag checked_bag = { 'sets of clothes': 5, 'passport': 1, 'toiletries bag': { 'toothbrush': 1, 'toothpaste': 1, 'condi...
db14fc3a3a28b9de7eb36b552bc6d24507c3fa59
MatheusMartins1/AT_DR2_MATHEUS_MARTINS
/q6.py
482
4.3125
4
#Questao 6 # 6. Escreva uma função em Python que leia uma tupla contendo números inteiros, # retorne uma lista contendo somente os números impares # e uma nova tupla contendo somente os elementos nas posições pares. numeros = (7,8,9,11,12,47,2,8,16,21,4,3) impares = [numero for numero in numeros if numero % 2 != 0] pa...
1dc7b8f764c05698b47ee9def0cac67e57bc4d47
rhit-chenh8/21-FunctionalDecomposition
/src/m1_hangman.py
2,433
4.03125
4
""" Hangman. Authors: Hanrui Chen and Yifan Dai. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. # DONE: 2. Implement Hangman using your Iterative Enhancement Plan. import random def get_words(): with open('words.txt') as lib: lib.readline() string = lib.read() words = string.split() ...
aed579a5f07af65744b4dc6b00fcc8b4d35cf2ac
coolsnake/JupyterNotebook
/new_algs/Sequence+algorithms/Selection+algorithm/cycle_detection.py
4,134
3.9375
4
""" @author: David Lei @since: 5/11/2017 https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle/problem A cycle exists if any node is visited once during traversal. Both Passed :) """ def has_cycle_better(head): # a.k.a floyd cycle detection, hare & turtle. # Idea: if a cycle exists...
b30b96ef87a39225000d09c870918f2d225f46ce
couchjd/School_Projects
/Python/CH7.py
3,893
3.953125
4
#1 File Display def printFile(fileName): print(open(fileName, 'r').read()) def main(): printFile('numbers.txt') main() #2 File Head Display def printHead(fileName): with open(fileName) as readFile: for x in range(0, 5): print(readFile.readline(), end='') def main(): print...
8484e6bac9ea6b1772a6216516c8f03488406aef
qeedquan/challenges
/codegolf/codegolf-the-hafnian.py
2,427
3.984375
4
#!/usr/bin/env python """ The challenge is to write codegolf for the Hafnian of a matrix. The Hafnian of an 2n-by-2n symmetric matrix A is defined as: Here S_2n represents the set of all permutations of the integers from 1 to 2n, that is [1, 2n]. The wikipedia link talks about adjacency matrices but your code shoul...
a24f8030cff8b69716b4fd308f94ecca8432b5ac
dawngerpony/sentencer
/sentencer/main.py
2,290
3.65625
4
from sentencer.vocab import vocab_filter, extract_sentences import argparse import csv import functools import operator VOCAB_FILENAME: str = "data/vocabulary.csv" def clean(sentences: list) -> list: """ Clean up sentences by removing newlines. :param sentences: :return: """ cleaned = [sente...
d929f60d0fdb7564f790b0c4bce998b9f507eb0e
leeacer/C4T39-L.H.Phap
/list/test12.py
1,616
4.25
4
lists = [] while True: print("|||||What would you like to do to the list?|||||") option = input("C R U D or done: ") if option == "c": add = input("What would you like to add to the list: ") lists.append(add) for i in range(len(lists)): print(lists[i]...
a8d71afecce3e0ebb9aa34dbcbcd2378c1fb5201
Kimberly07-Ernane/Pythondesafios
/Desafios/Desafio 055 (for) Maior e menor sequência.py
501
3.84375
4
#DESAFIO 55 #Faça um programa que leia o peso de cinco pessoas. #No final, mostre qual foi o maior e o menor peso lidos. maior=0 menor=0 for i in range (1,6): peso = float(input('Peso da {}° pessoa: '.format(i))) if peso == 1: maior= i menor= i else: if peso > maior: maio...
014b423178cd74cab519cf73475ffa71f6406fc6
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/largest-series-product/e8cfbbf923474316befcc0eca581e2e1.py
725
3.78125
4
# Get each substring, convert each to list of chars, # then convert to list of integers. # Return list of all of them. def slices(digits, series_length): if len(digits) < series_length: raise ValueError("series length is longer than number of digits") return [ [int(x) for x in list(digits[series:series...
806d8d4b4f9a10e657edf5e006b390d78e1be178
mandar-degvekar/DataEngineeringGCP
/DataStructure/List/Prob9CommonFunction.py
281
3.5625
4
def commonfind(a,b): for item in a: if item in b: return True akatsuki=['pain','konan','zetsu','obito','madara','itachi','kisame','sasori','deidara','hidan','kakazu'] uchiha=['itachi','obito','madara','sasuke','shisui'] print(commonfind(akatsuki,uchiha))
4e82f3eae7ee3a4ec85cf924c3c32e12447ff019
canattofilipe/python3
/manipulacao_arquivo/desafio_ibge/desafio_ibge_wfc_v1.py
391
3.875
4
#!/usr/bin/python3 """ Desafio: Extrair o nono e o quarto campos do arquivo CSV sobre Região de influência das Cidades do IBGE, """ import csv with open('desafio-ibge.csv', encoding='ISO-8859-1') as file: counter = 0 for line in csv.reader(file): if counter == 0: pass else: ...
0d1a1e77ec22dd49c000302cd51f454ec4e2a880
gennis2008/python_workspace
/OldBoyPython3.5/day6/notes.py
2,723
4
4
__author__ = "gavin li" ''' 面向对象 -- 编程范式 编程:语法+数据结构+算法 1、面向过程编程 procedural programming uses a list of instructions to tell the computer what to do step-by-step 面向过程依赖procedures 一个procedures包含一组要被计算的步骤,面向过程又被称为top-down languages,就是程序从上向下一步一步执行。 2、面向对象编程 OOP(object oriented programmin...
9491daea5e004cfdaf28e1abfe3721df34be70f6
papermashea/ml-2020
/python_work/guests.py
1,101
3.53125
4
guest_list = ['val', 'erica', 'jon', 'bailey'] # print(guest_list) # guest_list.append('rhiannon') # guest_list.remove('jon') guest_list.append('rhiannon') guest_list.remove('jon') invite1 = "hey " + guest_list[0] + " come to dinner party part II next weekend at 5!" invite2 = "hey " + guest_list[1] + " come to dinne...
fdf9bc444afe5c81e940615c69a543b2e57bfa53
SladeWangactionlab/campus-bryce-intersection
/functions/random/gpsMidpoint.py
666
3.8125
4
import math def midpoint(x1, y1, x2, y2): lat1 = math.radians(x1) lon1 = math.radians(x2) lat2 = math.radians(y1) lon2 = math.radians(y2) bx = math.cos(lat2) * math.cos(lon2 - lon1) by = math.cos(lat2) * math.sin(lon2 - lon1) lat3 = math.atan2(math.sin(lat1) + math.sin(lat2), \ ...
4ccdb21258476f7066fe1d6f39cd176957de1fd7
mafrasiabi/probnum
/src/probnum/linalg/linear_operators.py
26,559
3.78125
4
"""Finite dimensional linear operators. This module defines classes and methods that implement finite dimensional linear operators. It can be used to do linear algebra with (structured) matrices without explicitly representing them in memory. This often allows for the definition of a more efficient matrix-vector produ...
9fc4779e0b2cfedebc508e2f12b6e4db9e256783
AndreasMrq/mirror-me
/helpers.py
313
3.578125
4
def get_api_for(website): '''Searches the secrets.txt for the string given as website and returns the value after ":".''' fstream=open("secrets.txt",'r') settings=fstream.read() settings=settings.replace("\n",":").split(":") print(settings) return settings[settings.index(website)+1]
4ea716bac312d24c7eb9c1189e2daaf0628a5ec5
VicnentX/MachineLearning_PorjectsAndNotes
/package_bobo_note/_15_range.py
282
4.0625
4
#循环中遍历用到range # range(end) : 0 - end-1 l3 = list(range(100)) print(l3) # range(start, end): start - end-1 l4 = list(range(4, 12)) print(l4) # range(start, end, step): start - end-1 with step l5 = list(range(3, 9, 2)) print(l5) l6 = tuple(range(3, 9, 2)) print(l6)
baa7d9328eb071b513028fb670662d6b9b98d3ae
nhutphong/python3
/_argparse/actions.py
901
3.5625
4
import argparse """ Positional arguments: python3 test.py thong 27 gialai Optional arguments: python3 test.py -n thong -o 27 -c gialai co -n, --name, -o, --old """ my_parser = argparse.ArgumentParser() my_parser.version = '1.0' my_parser.add_argument('-z', '--name', action='store') # -p or --pi -> se nha...
2f4d748b9a53d9979173faa9e477f2c33b0ad302
JonathanGun/Project-Euler
/Software/Project Euler software.py
11,610
3.765625
4
from tkinter import * from Prob1_source import Prob1Ans from Prob2_source import Prob2Ans from Prob3_source import Prob3Ans from Prob4_source import Prob4Ans from Prob5_source import Prob5Ans from Prob6_source import Prob6Ans from Prob7_source import Prob7Ans # ========================================================...
938107475c6a8b4443d3979f5b93fc5e5bb6031a
mars1198/mars1198
/reversestring.py
154
3.953125
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 7 23:32:48 2018 @author: blixabargeld """ b = "ABC" for char in reversed(b): print( char, end = "" )
db30c4aacf9ebd45eeefa3d7a5fb0cba68f2276a
sashaobucina/interview_prep
/python/medium/coin_change.py
2,044
4.125
4
from typing import List def coin_change(coins: List[int], amount: int) -> int: """ # 322: You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be ...
5cde5cdb7ae88072948c992b2d6d7fdebf3607a7
Prajwalprakash3722/python-programs
/calculator.py
1,185
4.09375
4
# calculator def add(x, y): return x + y def sub(x, y): if x > y: return x - y else: return y - x def div(x, y): return x / y def mul(x, y): return x * y while True: print('''1. Enter "1" for addition. 2. Enter "2" for Subtraction. 3. Enter "3" for Multiplication. 4. Ente...
4e33f5d54fad7f93a7b7ca13e6db8b8abf75aae9
MrzvUz/Python
/Python_Entry/movie_exercise.py
3,376
4.625
5
# Incomplete app! MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: " movies = [] # You may want to create a function for this code title = input("Enter the movie title: ") director = input("Enter the movie director: ") year = input("Enter the movie rele...
b8c9abfae5a898b3ddf5ca314f64497de31f7ae5
algorithm005-class02/algorithm005-class02
/Week_02/G20190343020105/0105_236_twoTree.py
883
3.5
4
class Solution: def lowestCommonAncestor(self, root, p, q): ''' 从根节点开始遍历树 如果节点p和q都在右子树上,那么以右孩子为节点继续1的操作 如果节点p和q都在左子树上,那么以左孩子为根节点继续1的操作 如果条件2和条件3都不成立,这就意味着我们已经找到节点p和节点q的LCA了 https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/ :param root: ...
6c3a690d1c64be2209925b563e260e182b2e5c20
ljsh123ljsh/RTCM1.1
/stable/ConvertDecimal.py
1,441
3.53125
4
class ConvertDecimal: def __init__(self, strbin, least=0, symbol=False): # print(strbin) ''' :param strbin: 需要转换的二进制str :param least: 二进制小数的最低位数(默认为0) :param symbol: 第一位是否为符号位(默认不是符号位) ''' self.strbin = strbin self.least = least self.symbol = s...