blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
91bd725cbc0825f2a93e798e4ba60d6ea7a53d76
sanacor/Algorithm
/Valid Anagram/Valid Anagram.py
813
3.53125
4
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t): return False strObj = s # print(s.find('e')) for ch in t: idx = strObj.find(ch) if idx ...
3e8a2353c133fc1a36cf7cc6b583dcdf4a78d0c2
kimroniny/ACM
/LeetCode/0048/48.py
734
3.5625
4
class Solution: def rotate(self, matrix: 'List[List[int]]') -> 'None': """ Do not return anything, modify matrix in-place instead. """ lens = len(matrix) half = (lens-1)/2.0 for i in range(int(lens/2)): for j in range(i, lens-i-1): p = 4 ...
6daa6858776dca5d42067d56a52ab0e2dc23ee29
dawidsielski/Python-learning
/sites with exercises/100+ python challenging programming exercises/Level 13.py
267
3.890625
4
user_input = input() digits, letters = 0, 0 for element in user_input: if element.isdigit() == True: digits += 1 elif (element.isalpha() == True and not element.isspace() == True): letters += 1 print("LETTERS ", letters, "\nDIGITS ", digits)
b7a300264412dd8438a8216168e54a0f2ecd638b
xuanz0216/learn_python_the_hard_way
/concurrent_future.py
1,606
4.03125
4
#The concurrent.future module is part of standard library which provides a high level api #for lauching async tasks #Executor: Executor has two useful concrete subclassesL ThreadPollExecutor and ProcessPoolExecutor from concurrent.futures import ThreadPoolExecutor from concurrent.futures import as_completed from time i...
148d0c4ebf5c2a241f10d352a137b0af902172b6
edu-athensoft/stem1401python_student
/py200510_python2/day01_py200510/func_lambda_filter.py
530
4.09375
4
""" filter() original list of number is [1,2,3,4,5,6,7,8,9,10] pick up every even number in order output the new list """ original_list = [1,2,3,4,5,6,7,8,9,10] print(original_list) a = filter(lambda x: x%2==0, original_list) # print(a, type(a)) # covert to a list which can be read print(list(a)) # in compact styl...
92506839bd13ef244cdca15512fa902343406c06
Cqyreall/rock_paper_scissors
/app/models/computer.py
852
3.734375
4
import random def computer_choice(): rps = ["rock", "paper", "scissors"] choice = random.randint(0,2) return rps[choice] def winner(player, computer): winner = "AI" if player.choice == "rock": if computer == "paper": winner = "Titanius" elif computer == "scissors":...
68846e29aae4632251934cc86e11c1e8642a58b9
harin7/harikrish1python
/alphabet.py
125
3.953125
4
xx=raw_input() if((xx>='a' and xx<='z') or (xx>='A' and xx<='Z')): print('Alphabet') else: print("no")
1d4c73a6c3febeda0886f190c557e617d30aa195
kishan3/leetcode_solutions
/161.py
820
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 2 14:51:40 2019 @author: kishan """ def is_one_edit_distance(str1, str2): len1 = len(str1) len2 = len(str2) if len1 > len2: return is_one_edit_distance(str2, str1) if (len2 - len1) > 1: return False i = 0 ...
6fddaab41ab71cefc0acb618a870a27abdecd719
jamesdchong/BattleShip
/BattleShipFolder/my_module/PlayerInfo.py
769
3.71875
4
from ShipInfo import ShipInfo class PlayerInfo(): """ Class to hold a player's board information """ # Initializes a playerInfo object def __init__(self, playerNum, board, guess, ships, otherPlayer): self.playerNum = playerNum self.board = board self.guess = guess self.ships = [ShipInfo(None, None, None,...
27b708915408cf299d8eb3cdd6471d177511fb92
nielschristiank/DojoAssignments
/Python/pOOP/mathDojo/mathDojo.py
1,420
3.65625
4
class mathDojo(object): def __init__(self): self.total = 0 def add(self, *num): if num is not None: for val in num: self.total += val return self def sub(self, *num): if num is not None: sub_total = 0 for val in num: ...
71e6aaa6a4695d3f4dd78ee2985b27a8305b816e
WAT36/procon_work
/procon_python/src/atcoder/arc/past/A_032.py
223
3.609375
4
import math n=int(input()) if(n==1): print("BOWWOW") else: n=n*(1+n)//2 for i in range(2,int(math.sqrt(n))+1): if(n%i==0): print("BOWWOW") break else: print("WANWAN")
cf3ec9234a92667a82e5f961700c4928ee840d79
wujackjack/LittleMR
/create_data.py
614
3.515625
4
# Program: # This program create random names and corresponding height in a given range # Usage: # create_data.py name_num height_low_bound height_up_bound import sys import random import string if len(sys.argv) != 4: print "Usage: create_data name_num low_bound up_bound" sys.exit() name_num = int(sys.argv[1]) low...
ea1b3fea6ab084904fbd2377f2d5759f04dd6258
shobha-bhagwat/Python
/data_structures/test.py
2,530
3.984375
4
from Node_LinkedList import Node from linked_list import LinkedList from Node_Queue import NodeQ from queue import Queue from Node_Stack import NodeS from stack import Stack from Node_BinaryTree import NodeB from binary_tree import BinaryTree print("---------------------- Linked List -------------------------------...
d32e8f407bd872567a59dfeb8576eb74d5050ecf
Sandon/algrithms
/hackerrank/algorithms/strings/build-a-palindrome[advanced]/test.py
355
3.9375
4
test1 = 'haha' test2 = 'xixi' print ({test1, test2}) print ({'test1': test1, 'test2': test2}) def fn (): return {'x': 'y'} val = fn() print (val) str = 'xyz' r = str[::-1] print (r) objHaha = {1: 'y'} print(not('z' in objHaha)) print(1 in objHaha) print('---------') for i in range(3, 1, -1): print(i) print...
8f521f3e9a2cfbefec453a057912b47ac49b4491
MarcusbeloV2/Codekai_Feedback
/Ex007--Lowest.py
818
4.15625
4
#Write a program that receives 3 numbers and prints the lowest of them print("welcome to the number comparator MK3V2") print("you will send us 3 numbers and I will send u the lowest") x=int(input("please send the first number ")) y=int(input("please send the secound number")) z=int(input("please send the third num...
4fdbc44534343fdba6a27aaef32c5f6e38da5c3d
leighjpeter/python
/generator.py
2,058
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #生成器 一边循环一边计算的机制generator g=( x*x for x in range(10) ) def fib(max): n,a,b = 0,0,1 while n < max: yield b a,b = b,a+b n=n+1 return 'done' # 函数改为generator后 基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代 # 但是for循环拿不到return,如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIterat...
c1d6fe1f950bcea2b0d4b25fb1bb4997ebdb6cfb
AaronRanAn/Python_Programming_MSU
/assignment 7.1.py
260
4.0625
4
# Assignment 7.1 # Use words.txt as the file name import os os.chdir('/Users/aaron.an/Aaron An/MOOC/MU | Python Programming/Assignments') fname = raw_input("Enter file name: ") fh = open(fname) for line in fh: line = line.strip() print line.upper()
a3d119e1db4b1d66b6d98127fcff6c7001def133
yhboo/lemontree
/lemontree/experimentals/sentence_distortion.py
3,268
3.5625
4
""" This code implements sentence distortion to make wrong sentences. Four distortion is introduced. Shuffle (only one pair adjoint) Delete (one) Insert (one) Shuffle (random) """ import numpy as np from lemontree.data.glove import GloveData def sentence_distortion_shuffle_one(words): """ This function shuff...
d5be00eb7ba079c570f1191fcacd4bda8dfa1dcd
zachgarwood/redshelf
/purchase_sort/sorter.py
4,014
3.796875
4
"""Sort purchases into buckets by certain criteria""" """ These criteria are the purchase attributes that we use to sort purchases into the appropriate buckets. They are listed in order from least specific to most, with their index in the list being their implicit specificity weight. See find_specificity(). """ CRITER...
7dbce5c52285c9d947ebbef41179ceaa8675af0d
king-tomi/DS-ALGO-with-python-exercice-files-and-example-codes
/queue.py
1,962
4.09375
4
author = """AYODABO TOMISIN KOLAWOLE""" date_created = """16 August 2020""" """This code is an example from the Data Structures and Algorithms with Python book. You can copy and edit this code as you wish but remember, try not to 'modify' but 'extend' Have a good read and a nice time.""" class E...
6f42c381ec7d7c6d8dbe78a3d718c966f5b3acc0
Naushikha/Old-Projects
/Python/Simple Tutorials/oct_to_deci_with_workings.py
450
3.90625
4
#17 Feb 2017 #Converts a octal into a decimal and shows the workings #Coded by _xXHunt3rXx_ #inputs num=input("Enter an octal number:") n=list(num) n.reverse() p=tot=0 res=[] print()#working #process OCT>DEC for x in n: res.append(int(x)*8**p) print("8 ^ "+str(p)+" x "+x+" = "+str(int(x)*8**p...
24a47e5438f544e703332e4053b113ed1b7a9b94
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4129/codes (1)/1723_2505.py
268
3.90625
4
from math import* x = eval(input("Angulo em radianos:")) k = int(input("Termos:")) m = 1 #Potenciação s = 0 #Termos angulo = 0 n = 2 while(s < k): angulo = angulo + (((x**m)/factorial(m))* (-1)**n) m = m + 2 s = s + 1 n = n + 1 print(round(angulo, 10))
1282fdbd7a3a9dfa1c57dce3fad8c0a66d0753f3
MCOfficer/simple-youtube-api
/simple_youtube_api/LocalVideo.py
2,186
3.53125
4
from simple_youtube_api.Video import Video import os.path import typing class LocalVideo(Video): """ Class for making a video that is uploaded to YouTube Attributes ----------- file_path: Specifies which file is going to be uploaded title: Specifies the title for the video d...
dcf6bdb9b206caf223e4c0c2c678d5d41194f48d
bexcitement/Practice_Python
/palindrome.py
450
3.984375
4
def first(word): return word[0] def last(word): # print word[-1] return word[-1] def middle(word): print word[1:-1] return word[1:-1] middle('no') def is_palindrome(word): first_letter = word[0] last_letter = word[-1] middle_word = word[1: -1] inverse_middle = word[-2: 0: -1] if first_letter == last_le...
5931e261b205e9eaee2c0412ea45117e8728e91f
johnny3young/codingame
/puzzles/python3/dwarfs_giants.py
1,319
3.640625
4
class Person(): def __init__(self, number): self.number = number self.depth = 1 self.dwarfs = set() def add(self, dwarf): if dwarf not in self.dwarfs: self.dwarfs.add(dwarf) def update_depths(self): for dwarf in self.dwarfs: if self.depth >= ...
36528b2222ef67ab80915afcc8d14705010f7d80
kzygmans/project-euler
/solutions/problem_0019.py
260
3.625
4
from datetime import date def solution(): sum = 0 for y in range(1901, 2001): for m in range(1, 13): if(date(y, m, 1).weekday()==6): sum += 1 print 'Answer: %i' % sum if __name__ == '__main__': solution()
d35e048e65960bf962bf8d14625f49a907599fde
bharath210/PythonLearning
/UserInputArray.py
314
3.75
4
from array import * num = array('i') n = int(input('enter the size of array')) for i in range(n): x = int(input(f'Enter the value - {i+1}')) num.append(x) print(num) val = int(input('Enter the value')) for j in range(len(num)): if val == num[j]: print(j) break print(num.index(val))
3a940c81769706b7560626919fd12bb55b681d44
ddfn/CSCI160
/defran__labFunctions.py
1,054
4.15625
4
#Andrew DeFran #CSCI 160 #9/13/2018 #define a function that calculates distance between two points. def distance(x1, y1, x2, y2): from math import sqrt d = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) return d #define a function that calculates the area of a circle using the distance function. def circle_a...
eb669a4c06f0b611540d6522d93c1eab1f1f1f76
lel352/PythonAulas
/PythonExercicios/Desafio054.py
409
3.828125
4
from datetime import date print('=========Desafio 054========') atual = date.today().year maior = menor = 0 for c in range(1, 8): ano = int(input('{}º Ano de nascimento: '.format(c))) idade = atual - ano if idade < 21: menor += 1 else: maior += 1 print('Quantidade de maiores d...
f0b39a4e540fcf690a4cffd76319342ca1a1e2ac
vickysvenson/itedes
/modulo1/segmento2/ejemplo1.py
271
3.890625
4
def exponenciar (base,exponente): resultado = base for i in range(1, exponente): resultado = resultado * base return resultado base = int(input("base: ")) exponente = int(input("exponente: ")) resultado = exponenciar(base,exponente) print(resultado)
d6c3f47d7546588bcd04519444de6daad8f06e82
SergioRyzhov/python
/lesson2/task_3.py
750
4.0625
4
while True: month_number = int(input('Input natural number of the Month: ')) if 13 > month_number > 0: break else: print('You should input a number between 1 and 12!') year_time = ['winter', 'spring', 'summer', 'autumn'] year_time_dict = { 1: 'winter', 2: 'spring', 3: 'summer',...
b656d1b383fcd560350cdad124251e32bee68a69
Goular/PythonModule
/02.天善-Python数据分析与挖掘实战/01.Python语法基础/07.if-else.py
172
3.9375
4
a = 8 # if后面的内容可以是带小括号,也可以不带小括号 # if (a == 7): if a == 7: print(a) elif a < 2: print("89") else: print("a不等于7")
6798cb34a03f3786349ad98bb7e217938db42037
dheinzelman/python-labs
/labs/03_more_datatypes/2_lists/03_09_flatten.py
432
4.21875
4
''' Write a script that "flattens" a list. For example: starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] ''' starting_list = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] flattened_list = [] for i in range(len(starting_list)): for j in range (len(starting_list[i])): flattened...
2ac06048cd823b4acef833c1c8440ac74e9f9233
CaioHRombaldo/PythonClasses
/Ex023.py
409
3.734375
4
number = input('Enter a number from 0 to 9999 to analyze: ') if len(number) > 0: u = number[len(number) - 1] else: u = 0 if len(number) > 1: t = number[len(number) - 2] else: t = 0 if len(number) > 2: h = number[len(number) - 3] else: h = 0 if len(number) > 3: m = number[len(number) - 4] el...
8649a55be0af73ed5c993a7c23b60627b0c416ce
mesa6785/codingground
/New Project-20170126/main.py
1,489
4
4
#input values of A, B, and C for the quadratic formula. import math A = input("A value: ") B = input("B value: ") C = input("C value: ") #I'll just use the discriminant, because that's easier. D = ((B**2)-(4*A*C)) if D <= 0: #if the discriminant is less than 0 the answer is imaginary DTwo = (math.sqrt(math.fabs...
35043cdb8a709732785ef14f0968326012def31f
gschen/where2go-python-test
/1906101001周茂林/day20190929/厘米和英尺英寸的转换.py
106
3.546875
4
CM = input() cm = int(CM) foot =int(cm/100.0/0.3048) inch =int((cm/100.0/0.3048-foot)*12) print(foot,inch)
af211216d6c773a0423c72946ae1781794ec7e14
jedzej/tietopythontraining-basic
/students/wachulec_maria/lesson_05_lists/numbers_filter.py
291
4
4
def numbers_filter(base_list, filter_range): numeric_list = [int(i) for i in base_list if int(i) not in list(filter_range)] return numeric_list list_of_strings = input().split() to_filter_range = range(3) print(numbers_filter(list_of_strings, to_filter_range))
697adc257c569a52800a235f995356357c1dbfee
harshkakaria/python_examples
/functions.py
3,422
3.90625
4
def wish(): print("hello this is user define function") wish() wish() def wish(name): print("hello",name,'good morning') wish('jai') wish('veera') # Return statements: def add(x,y): return x+y result = add(1,20) print('the sum of :',result) print('the sum of ',add(20,40)) def f1(): print('hello') ...
0e28d44f08c8f5a20fe1c58634ed6935681db965
DiegelB/Random-Scripts
/Tip Calculator.py
429
3.890625
4
__author__ = 'BenDiegel' def tipcalc(): mealCost = float(raw_input("What was the cost of your meal?\n")) tipPercent = float(raw_input("Please enter the tip percentage in decimal form.\n")) tipAmount = mealCost * tipPercent mealAmount = mealCost + tipAmount raw_input("Press enter\n") print "Ti...
e9b41e94affe934a26eff75859e61140ea1fc62d
rafaelrds/projetoADSD
/scripts/mongo_populate.py
1,334
4.40625
4
# mongo_hello_world.py # Author: Bruce Elgort # Date: March 18, 2014 # Purpose: To demonstrate how to use Python to # 1) Connect to a MongoDB document collection # 2) Insert a document # 3) Display all of the documents in a collection</code> from pymongo import MongoClient # connect to the MongoDB on MongoLab # to ...
aec9f29d6cd994c0d0fa25753cf8a3b5126bbc8d
filipe-guerra/Python-DS-manual
/pandasManual.py
6,675
3.546875
4
import pandas as pd pd.read_csv('file.csv', header=None) reviews = pd.read_csv('../input/wine-reviews/winemag-data_first150k.csv', index_col=0) fruit_sales = pd.DataFrame({'Apples':[35,41],'Bananas':[21,34]}, index=['2017 Sales', '2018 Sales']) pd.Series([30, 35, 40], index=['2015 Sales', '2016 Sales', '2017 Sales'...
0c3caaa254071af903c6ae72d4abece1dd8cb7b4
sagaraggarwal/python-workshop
/lab4 tuple.py
1,344
4.28125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #tuple 2>create a tuple diff data types var1=(1,"lk",False) print(var1) # In[2]: #1>ceate empty tuple var1=( ) print(var1) # In[3]: #3>print one no var1=(10,20,30) print(var1[1]) # In[3]: #4>several variables var1=(10,20,30) a,b,c=var1 print(a,"",b,c) # In...
1ac911ea65ddd4e9344eb3b5d74e103dcf1b0652
EvelynGraterol/proyectos
/home.py
6,037
3.6875
4
import streamlit as st import pandas as pd def app(): st.title('PROYECTO FINAL DE DATA MINING') #st.write('Grupo 2') st.header ("MODELO DE PREDICCIÖN DE WEB MALICIOSO") st.subheader ('Descripción del problema') st.write("""El proyecto consiste en evaluar diferentes modelos de clasificación para pr...
33477d86e0102f37692a20427159148c8371386c
malaybiswal/python
/misc/iteration.py
110
4.03125
4
def iteration(i): num=1 while(i>1): num=num*i i-=1 return num print(iteration(3))
24be9ca7a93fdd41235807d5ba7592fb2cc69c2e
zulfi127/Data-Structures-Algorithms
/BinarySearchTree.py
3,309
3.953125
4
class BSTree: # Binary Search Tree def __init__(self): self.root = None def depth(self): if self.root == None: return 0 else: return self.root.depth() # BSNode depth as assignment def __str__(self): i...
8436961632314d40b35d60176b6145cd8e43036b
vihaancoderva/Project-97
/GameGuess.py
573
4.28125
4
import random print("Guessing the number!") number = random.randint(1,9) chances = 0 print("Guess a number between 1 to 5, you will only get 5 chances!!") while chances < 5: guess = int(input("Type your guess!:- ")) if guess == number: print("Congratulations! You guessed the right numb...
6aa217e1bdbea2797d55292e3402f5b93eab0bc1
DaZhiZi/chest
/test.py
385
3.78125
4
towns = [ {'name': 'Manchester', 'population': 58241}, {'name': 'Coventry', 'population': 12435}, {'name': 'South Windsor', 'population': 25709} ] print(list(zip(*[(t.get('name'), t.get('population')) for t in towns]))) def get_value(key, lists): return list(map(lambda t: t.get(key), lists)) print(...
845e96c3ed5d3fcaa4c845c07ccab60ba0453dce
AdamZhouSE/pythonHomework
/Code/Cases/2730/.mooctest/answer.py
180
3.796875
4
import functools import operator for t in range(int(input())): input() s = int(input().replace(' ', ''))%3 if s == 0: print(1) else: print(0)
e3dc46220ad0317677ad848b648c2eef15ba7eef
AShoom85/MyPythonCode
/L1/numberL1_3.py
452
4.1875
4
#Напишите программу, которая считывает целое число и выводит текст #The next number for the number число is число+1. The previous #number for the number число is число-1. С начала num = int(input("Input number = ")) print("The next number for the number " + str(num)+" is " + str(num + 1)) print("The previous number fo...
f031592a578fca88667c754b835bf480af19941f
acleee/acleebot
/broiestbot/commands/olympics.py
1,061
3.59375
4
"""2020 Olympics medal leaders""" import pandas as pd from emoji import emojize def get_olympic_medals_per_nation() -> str: """ Return olympic leaders by number of gold medals.py :returns: str """ medals_df = pd.read_html( "https://www.espn.com/olympics/summer/2020/medals/_/view/overall/s...
75ccf8e07bfb5532e4174095a9e0f6de09b88cd8
vnpavlukov/Study
/Coursera/2_Coursers/Basic_progr_in_Py/Week_3/Test_22_replace_two_h.py
436
3.921875
4
l = input() def replace_center(s): first_h = s.find('h') reverse_s = s[::-1] last_h = len(s) - (reverse_s.find('h') + 1) start_string = s[0:first_h + 1] center_string = s[first_h + 1: last_h] big_h_center_string = center_string.replace('h', 'H') finish_string = s[last_h:] return start_...
6be1a800ae10fd03f11b3a8c1035cd62ba810177
tanman13/oopljpl
/myExercises/factorialTests.py
695
3.71875
4
#!/c/Python34/python #------------------ # factorialTests.py #------------------ from unittest import main, TestCase def myFactorial (n) : assert n >= 0 if ( n > 1 ) : return n*myFactorial(n-1) return 1 class FactorialTest(TestCase): def test_0(self): self.assertEq...
4ebaf31ca79d36e406c19e7ada71f395791dfc76
vanis-19/Python_string
/enumanate.py
120
3.8125
4
s='vanisaddala' s1='anu' print(tuple(enumerate(s))) print(list(enumerate(s))) for i,v in enumerate(s1): print(i,v)
5aa7ff836ed2b5d81c116a17d6ac14c10c88e15e
fennea/Python-Files
/save_csv_with_var_data.py
947
3.921875
4
from tkinter.filedialog import asksaveasfilename import csv def cool_function_name(cool_data): print("") # sometimes you help users create a usable filesytem print("Saving File [please type your initials + todays date | Ex: 'AAF01172020']") saved_file = asksaveasfilename(initialdir="C:/Users", filet...
f8f51f789101d485cebdf2fcb1bf83d7c141abc8
benitez96/unsam
/unsam/Clase 2/tabla_informe.py
1,317
3.640625
4
import csv def leer_camion(nombre_archivo): camion = list() with open(nombre_archivo) as f: rows = csv.reader(f) next(rows) for row in rows: lote = {'nombre':row[0], 'cant.':int(row[1]), 'precio': float(row[2])} camion.append(lote) return camion def leer_pre...
8b9852f289ae3cae1d44625ddac2b9c1c9a807e2
nikita-chudnovskiy/ProjectPyton
/00 Базовый курс/Zadachi/07 Деление на Цело/011 Хипстер Вася.py
1,037
3.78125
4
# Хипстер Вася сколько у него насков сейчас и на сколько их хватит a=int(input('Введите количество красных носков: ')) b=int(input('Введите количество синих носков: ')) x1=(min(a,b)) c =((a-min(a,b))//2) d = ((b-min(a,b))//2) x2 =max(c,d) print(x1,x2) #Первое ответное число (количество дней, которое Вася сможет быт...
d45ad82b5bd2e1747bc70c041025ad310326f7e9
visajkapadia/data-structures-python
/BinarySearchTree/height.py
324
3.953125
4
# from BinarySearchTree.binary_search_tree import BinarySearchTree def height(ptr): if ptr is None: return -1 return 1 + max(height(ptr.left), height(ptr.right)) # bst = BinarySearchTree() # bst.insert(3) # bst.insert(1) # bst.insert(5) # bst.insert(6) # bst.insert(8) # print(height(bst.get_root()))...
71e88feffe3d317d4e0019541fa48f1700af5bf6
Jstuff36/InterviewPractice
/AppAcademySkypeInterviewPractice/SmallestMultiple.py
239
3.828125
4
def SmallestMultiple(): num = 2520 flag = 0 while True: print(num) if checker(num): return(num) num += 2520 def checker(num): for i in range(1,21): if num % i != 0: return(False) return(True) print(SmallestMultiple())
c671a044f7ac3283c0e95baaa56deca56822d621
ariel415el/TravelAgentTools
/message.py
4,172
3.734375
4
from consts import * class Time: def __init__(self, date, time_in_day): self.date = date self.time_in_day = time_in_day def __str__(self): return f"{self.date} {self.time_in_day}" class Traveler: def __init__(self, name, is_child): self.name = name self.is_child =...
bceeb82f161e1453062dcd6dd327f9cfad515815
DavidCook12/Python-Things
/untitled/SecondProject.py
351
3.859375
4
r = str(input("What's your name? ")) b = str(input("How old are you? ")) c = str(input("What's your favorite color? ")) w = str(input("Are you happy right now? ")) print("Your answers were:", r + ",", b + ",", c + ",", w) Join = input('Is this what you said?') if Join.lower() == 'yes': print("Great,", r + '!') else:...
52a7ae1573a16f80244500004805a62d0fe8be3a
sigthorz/FORR2FA05BU
/Verkefni3.py
6,036
3.671875
4
#Sigþór Atli Sverrisson import math # <--- Klassar byrja ---> #Liður 1 - Hringur class Hringur(): def __init__(self, radius): self.radius = radius def reikna_ummal(self): #Reiknar Ummál hrings utkoma = (2 * math.pi * self.radius) return round (utkoma,1) def r...
d8ebf6a493dc9b19e0ff6fff87dde04b30d86b9e
Chang-hongyu/leetcode_python
/011-盛最多水的容器.py
601
3.875
4
# -*- coding:utf-8 -*- # /usr/bin/env python # Author: Chang # Function: 给定一个数组 表示各个容器高度 求可以盛最多水 # Version : 1.0 # Contact : 582246340@sjtu.edu.cn def maxArea(nums): if len(nums) <= 1: return 0 ans = 0 left = 0 right = len(nums) - 1 while left < right: ans = max(ans, (right - left...
0712572181efa1b638f2699a778f9b527bfaa8bc
remember-5/python-demo
/com/remember/numpy/np-array.py
1,952
3.921875
4
# @see https://mofanpy.com/tutorials/data-manipulation/np-pd/np-array/ import numpy as np # array:创建数组 # dtype:指定数据类型 # zeros:创建数据全为0 # ones:创建数据全为1 # empty:创建数据接近0 # arrange:按指定范围创建数据 # linspace:创建线段 a = np.linspace(1, 10, 20).reshape(4, 5) print(a) print("================================================") # 用li...
845748b400dcf5381e85f28f449359d48ab7e50a
TomekPk/Python-Crash-Course
/Chapter 3/3.5.Changing Guest List/change_guest_list.py
1,644
4.46875
4
''' 3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations. You’ll have to think of someone else to invite. • Start with your program from Exercise 3-4. Add a print statement at the end of your program stating the name of the guest who ca...
e0ac1959a66a97924dbeb86598420795e528b516
akvara/CodeWars
/4kyu/Range_Extraction.py
1,023
3.578125
4
def solution(args): res = [] begin = None for i in range(1, len(args)): if args[i] - args[i - 1] == 1: if not begin: begin = args[i - 1] else: if begin: range_or_two_separate(begin, args[i - 1], res) begin = None ...
bef9a76248f7793b9f01517f1ce87017bec083cf
markbbbnyc/rollingdie
/Roll_of_the_Die_Game.py
2,133
3.71875
4
import numpy as np import pandas as pd import random import os from tabulate import tabulate # Variables die_roll = 0 die_type = 6 die_payout = die_type player_bet = 1 player_win = 0 player_purse = 100 counter = 0 # Keeping track turn_list = [] purse_list =[] bet_list = [] win_loss_list = [] rolled_number_list = [] pi...
17765aa78bec16d6bb3144e8be62c46529c3cad5
AdirWe/InvestmentFundWebScraping
/subStringFinder.py
4,136
3.75
4
def find_between(s, first_word, last_word): try: start = s.index(first_word) + len(first_word) end = s.index(last_word, start) return s[start:end] # return the string between except ValueError: return "" except: return "" def find_substring_only_after_given_string(...
e662c85702ae36deaeaadd037884ded7dd2d8cbc
rybakovas/Python
/Python/Exercises/exerc5.py
239
3.796875
4
# Remove the duplicate itens in a list numbers = [1, 4, 3, 2, 1, 5, 4, 10] unique =[] for number in numbers: if number not in unique: unique.append(number) print(unique) # By Victor Rybakovas Sep 2019 - http://bit.ly/linkedin-victor
97dbfa4fdad4aeba15feade1b49b2ad6779e9d54
thehealer15/tkinter-tutorials
/homework.py
996
3.71875
4
import tkinter as tk def createFile(): with open("Contacts.txt",'w') as f: f.write("Name,Contact Number\n") def update_file(a,b): with open("Contacts.txt",'a') as f: f.write(f"{a},{b}\n") tk.Label(root,text="Saved Successfully").pack(side='bottom') def fun(): a= name_of_person.get() ...
22c90378a7490741966964362beda7d1a868bae2
desperadosec/variability
/window.py
4,933
3.53125
4
import curses from constants import * from g import * class Window(object): def __init__(self, height, width, begin_y, begin_x): # Perform init for things common to all windows self.begin_y = begin_y self.begin_x = begin_x self.border_width = 2 self.border_height = 1 ...
17d1236477269d6366b4d60bcf282b7031f9a8eb
grmtveeen/Training-on-algorithms-from-Yandex
/2 lesson/A. Возрастает ли список.py
241
3.65625
4
S = [int(i) for i in input().split()] def What_is(S): Ground = True for i in range(len(S) - 1): if S[i] >= S[i + 1]: Ground = False break if Ground: return "YES" return "NO" print(What_is(S))
313195f79fc253ec610ba6173babb18b91c8e5d6
xwang322/Coding-Interview
/python/P7.py
369
3.5625
4
class Solution(object): def reverse(self, x): string = str(x) if string[0] == '-': new_string = ''.join(reversed(string[1:])) return -int(new_string) if -int(new_string)>-2**31-1 else 0 else: new_string = string[::-1] return int(new_st...
87a7bddc8cfce9bf15520d692a822afe8dcfe0af
wendell-priebe/Study-Python
/mundo-1/ex010.py
400
3.8125
4
# crie um programa que leia quanto dinheiro uma pessoa tem na carteira e quantos dolares ela pode comprar #considerar us$1,00=R$3,27 print('\033[30mConversor Real x Dolar') n=float(input('Quantos reais você tem ?R$')) d=n/3.85 print('Você pode comprar US${:.2f} dolares com R$ {:.2f} reais'.format(d,n)) if n >= 1000: ...
f8e8a92dae63c309bcfe37525f9025beaee0c0d0
CharlesPatterson/Project-Euler-Solutions
/Project_Euler_14.py
1,332
3.578125
4
#!/usr/bin/env python """Solution to Problem 14 of Project Euler. See http://projecteuler.net/index.php?section=problems&id=14 for the details. """ import time __author__ = "Charles Patterson" __copyright__ = "Copyright 2010" __credits__ = [] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "Charles Patter...
40d780808b845f98be4bc44a56ba51eb721c5a22
Suykim21/python_references
/data_structures/linked_lists/ll_reverse.py
583
4.15625
4
# Reverse linked list # 1 -> 2 - > 3 => 3 -> 2 -> -1 class Node(object): def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self): self.head = None self.tail = None self.size = 0 # Iterative def reverse(self): ...
0da0f94ea14f4944262a736ba993e24cbb98a161
caiocezarccas/Curso-Python
/ex09.py
717
4.03125
4
print('Você pode digitar qualquer número para saber a tabuada') num = int(input('Digite qualquer número: ')) print('Estou calculando...') n0 = num * 0 n1 = num * 1 n2 = num * 2 n3 = num * 3 n4 = num * 4 n5 = num * 5 n6 = num * 6 n7 = num * 7 n8 = num * 8 n9 = num * 9 n10 = num * 10 print('Já estou com a t...
5a289bd5f396ca038d73c76c169c0b3119f800d8
AustinHodge4/Morph-Tool
/formatPPM.py
3,616
3.5
4
import os def read_file(file_path): ''' Reads the ppm file and creates new list of lines to be added to the new format.''' f = open(file_path, 'r') line_count = 0 color_count = 0 lines = [] color = '' for line in f.readlines(): if line_count <= 3: # First three lines shou...
1c2d64211b46414ba4dbe980611f438385e8cc9b
Dhruvish223/1st_repo
/Book Details.py
1,778
4.4375
4
import sqlite3 BookStore = sqlite3.connect('BookStore.db') cursbs = BookStore.cursor() def tablecreation(): cursbs.execute('''CREATE TABLE Books (Title Text(30) PRIMARY KEY, Author Text(20), Price Float);''') print("Table Created Successfully!") def tableinsertion(): title =...
44ad444c734ebb345246256fc0f6f1b31ed3bc76
anatulea/codesignal_challenges
/Intro_CodeSignal/02_Edge of the Ocean/06_makeArrayConsecutive2.py
1,328
3.984375
4
''' Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some ad...
bb52bc7f40fa5a61b737961a5de7d929a01a92fd
JianghaoPi/LeetCode
/501-600/561.py
1,127
3.953125
4
""" 该题要求将数组中的数字两两配对,然后使得所有对的较小数之和最大,就要让每一对的差最小,不然只取其中的较小值,较大那个就浪费了 所以先排序,然后相邻配对即可 """ class Solution: def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ self.quickSort(nums, 0, len(nums)-1) res = 0 for i in range(0, len(nums), 2): ...
45095adbac9f633d38b54d9da703b7cdef074a35
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_2/desafio065.py
913
4.15625
4
# Crie um programa que leia vários números inteiros pelo teclado. No final da execução, # mostre a média entre todos os valores e qual foi o maior e o menor valor lido. # O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. soma = contador = 0 continuar = 'S' print('========== DADOS DE V...
2a4e78e475d4aa2991ba60f360bf8b90138357e2
junetech/2018_network_theory_homework
/HW4/nt_hw4_fileread_creategraph.py
1,283
3.796875
4
''' Reading file of graph & displaying by networkx Created in 1. Oct. 2018 by JuneTech ''' import json import networkx as nx def read_json_file(filename): ''' Reads json file & returns networkx graph instance ''' with open(filename) as f: js_graph = json.load(f) return nx.readwrite.json_gra...
dde1f8cec0c99fb30adbfe256ffddc02adb06cfe
nikk7007/Python
/Exercícios-do-Curso-Em-Video/01-50/034.py
244
3.890625
4
salario = int(input('Qual o seu salario? R$')) if salario <= 1250: salarioAumento = salario + (salario * (15 / 100)) else: salarioAumento = salario + (salario * (10 / 100)) print('Novo Salario: R${}'.format(salarioAumento))
ee5ed8d3b008455278b17038cf46c22d09ec0b25
wiegandt/week_3
/one two a lot.py
172
3.890625
4
num = int(input("Type number here: ")) if num <= 0: print("Not enough") elif num == 1: print("One") elif num == 2: print("Two") elif num > 2: print("A lot")
64b2f1231620e866a44354f8a72f737e5a6d714b
jeetkhetan24/rep
/Assessment/q25.py
101
3.734375
4
print("Enter the value:") a=int(raw_input()) disp={} for x in range(1,a+1): disp[x]=x*x print(disp)
e8fa2f4e26dad531eae2d447d90ad0f84152ab2a
samkrimmel/unit5
/randomMonth.py
255
4.0625
4
#Sam Krimmel #4/23/18 #randomMonth.py - prints out a random month of the year from random import randint months = ['January','February','March','April','May','June','July','August','September','October','November','December'] print(months[randint(1,12)-1])
504680a85422f6238a8792f342a91c1f41fac36a
geediegram/parsel_tongue
/adesuwa/functions/exercise.py
2,208
4.1875
4
# Question 1: write a python functions to find the maximum of three numbers; import math def max_of_three_numbers(a, b, c): print(max(a, b, c)) # a = int(input()) # b = int(input()) # c = int(input()) # # if a > b and a > c: # print(a) # elif b > c and b > a: # print(b) ...
675427d92e993dc7f379bfccb29850342bda1410
project-eclipse/Programming-Midterms
/과학-응용-문제해결/life_game_1d.py
783
3.859375
4
# 1차원 생명게임 구현하기 data = input().split(",") # 초기 상태 및 구하고자 하는 세대가 몇 번쨰인지를 '0110011', 1 과 같이 입력받는다 data[0] = data[0][1:-1] # 문자열 '0110011' 에서 양쪽에 있는 '를 제거한다 data[1] = int(data[1].strip()) def iteration(data): # 1세대 후의 배치 구하기 result = "" for i in range(len(data)): result += str( ...
59ac8e2a6965a1fb10465ec4a1fd25152702bc4a
prachichouksey/Backtracking-2
/78_Subsets.py
1,135
3.78125
4
# Leetcode problem link : https://leetcode.com/problems/subsets/ # Time Complexity: O(2^n) # Space Complexity: O(n) for Backtracking # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach ''' 1. Start fr...
a4bd279b467167b949e121100949d94079920208
i5ar/eccrypt
/eccrypt/encrypt.py
2,768
3.921875
4
#!/usr/bin/env python """Encrypt a text file. https://www.pycryptodome.org/en/latest/src/examples.html#encrypt-data-with-rsa Because of how the RSA algorithm works it is not possible to encrypt large files therefore the RSA key is used to encrypt the session key and the AES session key is used to encrypt the data. ""...
760050d837b503f0995a24fe4b70985e30746716
yekingyan/python_2.7_practice
/string/ascending.py
708
3.671875
4
#------------------------------------------------------------------------------- # Name: 字符串比较,升序 # Created: 1/05/2018 # coding: utf-8 #------------------------------------------------------------------------------- f = open('names.txt','r') def ascending(name): #判断是否为升序 p = name[0] for c in...
c25bf1a93bb18c4233fac98d88bacbac3cd33e30
mohansinghs/MyPythonLearnings
/HWDay4.py
547
3.78125
4
print('Enter your details in below fields') # quotes used for printing instruction for user name = input('Enter Name:- ') # always use for getting information from user sbu = input('Enter SBU:- ') print('If you want to change SBU please enter new SBU') sbu = inp...
a00e1cd56369301b2ab424cf552a303f1c1482c6
Falonie/Notes
/super1.py
477
3.8125
4
import random class AbstractShape(object): def __init__(self, color): self.color = color class Circle(AbstractShape): def __init__(self, color=None, r=.0): # super().__init__(color) super(Circle, self).__init__(color) self.r = r def __repr__(self): return 'Color is...
fb5cbf595bc57ecbc7f21c769c7040ef9db865eb
Sixtey7/BGT-Backend
/model/models.py
3,076
3.71875
4
from model.database import db from sqlalchemy import Column, String, Integer, Boolean, Date, ForeignKey from sqlalchemy.orm import relationship class Game(db.Model): """Model class used to store Game objects in the database """ __tablename__ = 'game' id = Column(String, primary_key=True) name = Co...
d8e404eae444ead699c83fba8a1a3fe991e0273a
hlissner/practice
/other/numbers/happy_numbers/solution.py
1,128
3.796875
4
#!/usr/bin/env python import sys # How to use: # python solution.py 10 11 12 # Checks if 10, 11 and 12 are happy numbers # python solution.py 10-12 15 19-30 # Checks if 10-12, 15 and 19-30 are happy numbers # python solution.py # Get's first 8 happy numbers def happy_proc(n): sum = 0 ...
641332cd0dbcff79f5cbcd033d627e63fbb55e5a
Vagacoder/Codesignal
/python/Arcade/Core/C30AppleBoxes.py
1,403
3.65625
4
# # * Core 30, Apple Boxes # * Easy # * You have k apple boxes full of apples. Each square box of size m contains m # * × m apples. You just noticed two interesting properties about the boxes: # * The smallest box is size 1, the next one is size 2,..., all the way up to size k. # * Boxes that have an odd size co...
6893eac988fa5c2a79cd7c26ba148cd4defe7558
BlessKingslayer/StartItFromPython
/patterns/abstract-factory.py
925
4.3125
4
#!/usr/local/bin/ python3 # -*- coding: utf-8 -*- import random class PetShop(object): '''A pet shop''' def __init__(self, animal_factory=None): '''pet_factory is our abstract factory''' self.pet_factory = animal_factory def show_pet(self): pet = self.pet_factory() prin...
ecd9d2746ccd35ed85d49c1a54f1d3190948decc
lukwallace/toy-problems-solo
/LinkedLists/sumLists.py
1,634
4
4
#Learning python classes. print 'Running . . .' class Node(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self): self.head = None self.tail = None def __str__(self): i = self.head res = '(' while(i != self.tail): r...
6c91c4d110fc7787911c10de3ab7ecb1432ea9f4
EdIzotov/MachineLearning
/003-Lesson.Python/Project/oop2.py
569
3.765625
4
import math class Circle: def __init__(self, x, y, r): self.x_coordinate = x self.y_coordinate = y self.radius = r def calculate_area(self): area = math.pi * self.radius ** 2 return area class Sphere(Circle): def __init__(self, x, y, z, r): super().__init...
59703af0513cc3e6065cc17b34229a90ddc45599
iam-abbas/cs-algorithms
/Python/invertioncount.py
1,170
3.953125
4
#simple merge sort algorithm with invertion checking while merging def mergeSort(nlist,count): print("Splitting ",nlist) # count=0 if len(nlist)>1: mid = len(nlist)//2 lefthalf = nlist[:mid] righthalf = nlist[mid:] count+=mergeSort(lefthalf,count) count+=mergeSort(rig...