blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
aa4f3a2176da1d7817598d0dc676d956c9e188f1
HarryZhang0415/Coding100Days
/100Day_section1/Day36/Sol1.py
580
3.578125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: self.values = [] def search(n...
4ccbbf9c8a20b541d8f4c40ebcbb790cbc446699
AJLightfoot/hello-world
/CH8-User-Album.py
485
3.984375
4
def make_album(artist_nm, album_nm): album_info = {'artist': artist_nm, 'album': album_nm} return album_info while True: print("\nPlease Enter an music artist and album title:") print("(you can quit by entering q at anytime)") artist_name = input("Artist: ") if artist_name == 'q': break...
e4dfdb4eb260363477345cd5fa74d5d115edb1bc
acspike/PythonSamples
/states.py
1,721
3.984375
4
import random # http://geography.about.com/od/lists/a/statecapitals.htm text = '''Alabama - Montgomery Alaska - Juneau Arizona - Phoenix Arkansas - Little Rock California - Sacramento Colorado - Denver Connecticut - Hartford Delaware - Dover Florida - Tallahassee Georgia - Atlanta Hawaii - Honolulu Idaho...
37a90364dc29fea31cfe39ec8f52776780d1ee63
gustavoem/abc-sysbio
/cudasim/relations.py
1,033
3.90625
4
import re def mathml_condition_parser(string): """ Replaces and and or with and_ and or_ in a string and returns the result. """ string = re.compile("and").sub("and_", string) string = re.compile("or").sub("or_", string) return string def eq(a, b): return a == b def neq(a, b): ret...
eacafbe23f2c628b712f7adc1c61d25fd2f9165f
MrGumba/Computer-Guesses-Number
/DatornGissar.py
5,453
3.921875
4
# coding: utf-8 import time import random ''' computerGuesses är funktionen som utför gissningarna och sökningen till talet. Där den gör detta genom att gissa på ett tal mellan intervallet och sedan veta om talet är midnre eller störe och sedan sätta intervallet mellan talet den gissade + 1 och det andra...
86ddeed678d13f354d86b098e73986477bc33ad3
ShreyasGangadhar/Python
/add.py
45
3.65625
4
a=30 b=5 print('''sum of a and b is''',a+b)
5f76276e941d5eabf7db1192923e9b196b834b32
bsuresh0212/Data-Science
/Python/23-09-2017/FILES/file.py
372
3.5625
4
''' read a file from ''' ''' data = open('text.txt','r') for line in data: print(line) data.close() ''' ''' write in a file ''' tar = open('new_file.txt','w') tar.write('Hey i m suresh ') tar.write('Python') tar.write('\n') tar.write('finally i got') tar.close() tar = open('new_file.txt','a') tar.w...
d4acc86fc7d7861d07d80420a92c224b5d85d147
mikiwang820/coding-practice
/class_practice_BankAccount.py
1,203
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 1 14:33:02 2020 @author: wangmeiqi """ #Python coed to create BankAccount class #with deposit() and withdraw() function #Reference https://www.geeksforgeeks.org/python-program-to-create-bankaccount-class-with-deposit-withdraw-function/ class B...
68587de01c8da9979281c0d2aab0570e9fe23ef3
kimjiwook0129/Coding-Interivew-Cheatsheet
/Data-Structures/Trees/BinaryTreeIteration.py
2,114
4.15625
4
from collections import deque # Same BinaryTree, but the print methods are implemented using iterations class BinaryTree: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def preOrderPrint(self): s = deque([self]) ...
3664c7d1578c74a9b03db6542250dae30e5dfbc0
oski89/AoC
/2017/day-09.py
1,407
4.125
4
with open('input/09.txt') as f: INPUT = f.read() # Function that deletes "!" and the character after def ignore(in_tuple): in_string = in_tuple[0] start = in_string.find('!') end = in_string.find('!') + 2 in_string = in_string[:start] + in_string[end:] return in_string, in_tuple[1] # Functio...
8504340b6287a84f16c851de8c13cd0a39078048
liviumihai/practicePython.org
/exercises_page1.py
5,055
4.28125
4
''' Exercise 1: Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. Extras: Add on to the previous program by asking the user for another number and printing out that many copies of the previous mes...
af68fdca1492d905abf142a5cb4d5640e68ffab7
ChuhanXu/LeetCode
/jiuzhang/Two pointer/Two pointer move face to face/TwoSum/twoSum3DatastructureDesign.py
2,246
3.71875
4
# https://www.jiuzhang.com/problem/two-sum-iii-data-structure-design/ # 设计实现一个TwoSum类,支持 add find操作 # add使用hash记录每一个元素的count # find for循环 hash 的key set,看是否value-key在hash列表中,并检查count是否为0 # 考虑添加的时候要不要有序加入 class TwoSum: def __init__(self): self.nums = [] self.count={} # 1.维护有序 直接插入法 O(n),通...
ffda9fc7ee5de8634598498816576ad7adb720be
McSerful/Scrabble_game_final
/main.py
2,575
3.78125
4
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] letters_to_points = {letter: point for letter, point in zip(letters, points)}...
f66bb67555ef428ba2275362ff7c3295e3468c39
Bandit254/IntroToPython
/IntroToPython - Module 2/IntroToPython___Module_2.py
2,022
4.59375
5
#Introduction to functions #Some functions, like print, can take many parameters. #Other functions, like type, can only take one parameter my_type = type(2.2) print(my_type) #Create a function using the 'def' keyword, the function name, parentheses and semicolon #The actual body of the function is defined underneath ...
2976c321a47391632875814f6933a475b5bd472e
logicals7/problems-solving-python
/Bittersweet occasion/task.py
231
3.5625
4
# finish the function def find_the_parent(child_): if issubclass(child_, Drinks): print('Drinks') elif issubclass(child_, Pastry): print('Pastry') elif issubclass(child_, Sweets): print('Sweets')
2d96411cc681604e9e5908108a4e6f42cf0cdbb3
jacob-create/Experimental-evo-bio-code
/Randombutton.py
527
4.15625
4
#This code generates a list of the whole numbers 1-20 and a random button which #causes a random number from that list to be printed and then removed from the list. #The button can be used until all 20 numbers have been picked import random from tkinter import * def randomize(): num = random.choice(lizt) ...
7742aa86b83131c15a82a0a714274d77657017d4
tuobashaoli/LearningPython
/reduce.py
452
3.71875
4
#reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数 #reduce把结果继续和序列的下一个元素做累积计算 #效果如下reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) def add(x,y): return x+y from functools import reduce print(reduce(add,[1,2,3,4,5,6,7,8,9,0])) #把序列[1, 3, 5, 7, 9]变换成整数13579 def fn(x,y): return x*10+y print(reduc...
4806bebbb4759b0b7f85ce6c4b7f77d77dd78b68
annalieb/PythonWork-2018
/al_employeeEarnings.py
2,251
4.15625
4
#Anna Lieb #7/5/18 #Summer Python Work #al_employeeEarnings.py #used this website to learn more about the formatting in histogram(): #https://www.programiz.com/python-programming/methods/string/format#numbers EMPLOYEEMONTHLYSALARY = [5000, 10000, 6500, 3600, 2500, 1200, 5100, 7100, 5900, 7000...
1ef2bd95f22e0358937835907302ed38a68c17ff
Vishal97Singh/OnlineQuiz
/next.py
1,445
3.9375
4
from Tkinter import* top = Tk() a=["Q1)Python is a________","Q2) What is the output of print str * 2 if str = 'Hello World!'?","Q3) What is the output of print tinylist * 2 if tinylist = [123, 'john']?","Q4) Which of the following function convert an integer to octal string in python?","Q5) What is the output of L[2] ...
aecfc4163aad8680623e14cb4d5196114430c548
pkoarmy/Learning-Python
/week3/season.py
902
4.40625
4
# https://github.com/pkoarmy/Learning-Python/blob/master/week1/indent1.py import random print("We are going to calculate season from given Month") print("We call Spring if the month between March and May") print("We call Jun - Aug as Summer") print("We call Sep - Nov as Fall") print("We call Dec - Feb as Winter") mo...
47d5d9207f65b9a32810770a9bbe5d56dbdf76c8
gseeni/HottestDayCalculation
/HottestDay.py
2,163
3.609375
4
#!/usr/bin/env python # coding: utf-8 #Importing the Required classes import pyspark.sql.functions as f import pyspark.sql.types from pyspark.sql import Window from pyspark.sql import SparkSession #Creating Spark Session and Reads the csv files sc = SparkSession.builder.master("local").appName("WeatherTest").getOrC...
1053e5f700e1de2c057baecf1b5f55e965f67895
Horlawhumy-dev/csc_lab_problems
/readletters.py
330
3.90625
4
# Python Program that make special code from lines of file file = open('books.txt', 'r') # opening the file in read only mode Lines = file.readlines() # reading the lines of the file count = 0 # Strips the newline character for line in Lines: word = line.strip() print(f"{word} -> {word[0]}{len(word)}") c...
1705268d791de6c7f976b92ffe69a2a0a2be1914
connorodell/ModelSelection
/ModelSelection.py
3,385
4.15625
4
# Forward stepwise selection for best predictor subset selection import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split class ForwardSelection: '''Class for selecting the best predictor subset to train a linear model such and LinearRegression or LogisticRegres...
879574e0890450544b05c478f9592db464c17f13
thill3-zz/Compute-Total-weekly-Pay
/Assignment4.6.py
652
4.0625
4
hours = input("How many hours did you work?") rate = input("What is your hourly rate?") bonus = input("What is your hourly bonus?") try: hours = float(hours) rate = float(rate) bonus = float(bonus) bonusPay = 0 except Exception as e: print("Invalid input. Rerun the program and input only ...
e3203522a38066c7ba1f18240503ac85b9af11f1
lightengine/gamejam-demo
/lib/position.py
440
3.5625
4
class Position(object): def __init__(self, x=0, y=0): self.x = x self.y = y def __sub__(self, pos): x = self.x - pos.x y = self.y - pos.y return Position(x, y) def __repr__(self): return '<Pos %d,%d>' % (self.x, self.y) def isWithin(self, region): return region.contains(self) def percentTo(self...
929be39726ac8a569a1255a2d99cd656dc7a024a
ya1sec/Advent-of-Code-2020
/8/8.py
898
3.53125
4
fn = "input.txt" dat = [x for x in open(fn).read().split("\n")] dat.remove(dat[-1]) code = [] visited = {} # PART 1 for x in dat: operation, value = x.split() code.append((operation, int(value))) def run(code, visited, a=0, i=0): while i not in visited and i < len(code): visited[i] = a ...
2ae4f6a878b25a035d5a36e9b65b2c45e8c4e2e3
yash-sinha-850/Personal
/dfs_iterative.py
619
3.796875
4
class Node: def __init__(self,name): self.name=name self.adj_list=[] self.visited=False class depth_first_search: def dfs(self,startnode): stack=[] stack.append(startnode) startnode=True while stack: actualnode = stack[-1] stack.pop() print(actualnode.name) for i...
2c1000c5f5a043daf7977cba0f4135cbe707f8a8
LovepreetSingh-09/Machine_Learning_1
/Unsupervised.py
6,576
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 07:38:13 2019 @author: user """ # Unsupervised Learning import graphviz import mglearn import numpy as np import matplotlib.pyplot as plt import pandas as pd import os from IPython.display import display from sklearn.model_selection import train_test_split # Types ...
301a5c8ee7ebb9922cc7624d42d91f605c386262
Velu2498/codekata-array-python
/42.py
566
3.5625
4
""" Given 2 numbers N,X and an array of N elements, check if there exists any 2 numbers in the array with sum equal to X.If found print 'yes' otherwise print 'no' Input Size : N,X <= 100000 Sample Testcase : INPUT 4 4 2 2 0 0 OUTPUT yes """ N,X=map(int,input().split()) m=map(int, input().split()[:N]) m=list(m) count=0...
e1a99c58a88c7d936ae3f5d7f525cce1466a06a1
Anavros/lang
/testing/python/result.py
847
3.546875
4
# file = open("myfile.txt", 'r') err stdin # file = default(open("myfile.txt", 'r'), sys.stdin) class Success: def __init__(self, value): self.result = value class Failure: def __init__(self): pass def force(result): """ Return the result if successful, else raise an exception. ...
a3068dbc3691372be15050bd44384a08fb8c2c09
shu-csas-changgar/assignment-chapter1-matthewjones447
/midterm-project-matthewjones447/Question 5.py
806
3.921875
4
# Write a function the displays the year, count and rank of all WHITE NON HISPANIC males given the name David. # Note: In 2012 the ethnicity is listed as WHITE NON HISP. Please take this into account in your code. (10 points) def five(year, ethnicity, rank, first_name): if ethnicity.startswith("WHITE NON HISP") a...
f4da89fcbb3c3c431cc32b5fddd6648ed2dffa35
chao-ji/LeetCode
/python/string/lc58.py
1,151
3.546875
4
"""58. Length of Last Word Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. Example: Input: "Hello W...
2a499608c62583eb9cdc1911d3157fddca69af0b
gruxic/Ping-Pong
/ball.py
788
3.640625
4
from turtle import Turtle import random class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("white") self.penup() self.goto(random.randint(-100,150),random.randint(-100,150)) self.x_move=10 self.y_move=10 ...
4eab02e7de2af7969bb83120945d4ad69df61ce3
orralacm/LeetCode
/Problem 27/problem_27.py
275
3.71875
4
nums = [0,1,2,2,3,0,4,2] val = 2 x = 0 while x < len(nums) : if (nums[x] == val) : nums.pop(x) nums.append("") print("if") else : x += 1 print("else") print(nums) print("end cycle") print(nums)
d0e17e7f3cf14b5cb48f6e9de3573e21aa15e0a8
JVN313/Rock-Paper-Scissors
/main.py
2,299
3.8125
4
import random from datetime import datetime # Game Variables playing = True player_wins = 0 computer_wins = 0 draws = 0 games_played = 0 error_count = 0 options = ["ROCK","PAPER","SCISSORS"] answer = options[random.randrange(0,3)] user_input = input("Type Rock, Paper, Scissors, or Q to quit the game: ").upper() # Gam...
f3fbd777fdd0bef133cf05de3940619f610143b1
mindprobesven/python-references
/Python References/Syntax Reference/magic_methods.py
2,105
4.28125
4
#!/usr/bin/env python3 """ ---------------------------------------------------------------------------------------------------------------- Magic Methods - Magic methods are most frequently used to define overloaded behaviours of predefined operators in Python ---------------------------------------------------------...
d599567f13b4607445797fb2d02b12448c938b43
kevbradwick/algorithms
/algorithms/euclid.py
404
3.8125
4
def algo(a: int, b: int) -> int: """ Euclid's algorithm for finding the greatest common divisor of two numbers. >>> algo(10, 15) 5 >>> algo(10, 20) 10 >>> algo(10, 0) 10 >>> algo(0, 10) 10 >>> algo(0, 0) 0 >>> algo(10, 10) 10 >>> algo(10, 1) 1 >>> algo...
e4b61f3e977a0bdddf3dc86c081ada7094e59b9c
weady/python
/python.file_dir.py
3,395
4
4
文件读写使用with..as 方式 如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便 f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore') encoding 指定读取文件的编码 linecache,这个模块也可以解决大文件读取的问题,并且可以指定读取哪一行 面对百万行的大型数据使用with open 是没有问题的,但是这里面参数的不同也会导致不同的效率。经过测试发先参数为"rb"时的效率是"r"的6倍 linecache 用以实现高效读取大...
1df5dc60465487a9cbc9dffc27c5e79ba3ac2fe8
cbeloni/python
/PyTestes/InstanciasTestes.py
804
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class A: a = 1 # atributo publico __b = 2 # atributo privado a class A class B(A): __c = 3 # atributo privado def __init__(self): print self.a print self.__c a = A() print isinstance(a, B) # ''Objeto a'' uma instncia da ''classe B''? Falso. a = ...
5ffe1d324e575ffcf495f78b1662e95a447ee8ee
da-ferreira/uri-online-judge
/uri/2149.py
731
3.640625
4
while True: try: entrada = int(input()) if entrada in [1, 2]: print(entrada - 1) else: termo1 = 0 termo2 = 1 alterna = True for i in range(entrada - 2): if alterna: phillbonati ...
c16c13f1e993b1f949157eb810355ecc567fd251
muondu/datatypes
/password/generator.py
238
3.875
4
import random character = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*:;" length = input("Enter password length: ") length = int(length) password = "" for nesh in range(length): password += random.choice(character) print(password)
79fa4fb5c5c42fdd0cbc8b82faae63a70fc722c9
yangzongwu/leetcode
/20200215Python-China/0118. Pascal's Triangle.py
688
3.8125
4
''' Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] ''' class Solution: def generate(self, numRows: int) -> List[List[int]]: if numRows==0: return [] if numR...
d0af2d69a39f1cab99ba594a5431dfd898d164cc
starcigi/MyProjectPythonLearn
/binhanshu.py
142
3.796875
4
def binhanshu(x): result = '' if x: result = binhanshu(x//2) return result + str(x%2) else: return result
725ce6d6e44c8d8eccbf4474f1587331c53b2735
modolee/algorithm-practice
/baekjoon/permutation/10974_STL.py
282
3.5
4
from sys import stdin import itertools if __name__ == '__main__': n = int(stdin.readline()) arr = list(range(1, n + 1)) all_per = list(itertools.permutations(arr)) for values in all_per: for val in values: print(val, end=' ') print('')
458b575e9ccddc5c720f80e7adebeefa80701f10
Sesdesoir/PythonPlay
/player.py
1,060
3.734375
4
from gameObject import GameObject #Player is going to be a sub class of GameObject. GameObject is like the parent #We want everything GameObject has PLUS some stuff exclusive to Player. #This is like when we did the vehicle/car/boat classes class Player(GameObject): #This creates the Player object def __init__(...
6951be258ff1afd30f32d82389dfb6efa8408f94
Flammifer/Cmath
/V/7.6c.py
838
3.5625
4
import matplotlib.pyplot as plt import numpy as np import MyMath as mm def F(x): return x[0]**2+x[1]**2+x[0]*x[1]+x[0]-x[1]+1 def min_lambda(lambda_, args): #функция для нахождения оптимального лямбда w = args[0] fastest_grad = mm.vec_mul(-1, args[1]) return mm.vec_prod(fastest_grad, mm.grad...
64d83e9383ebf22e38342a2fedcdd167c73ee6db
falble/mythinkpython2
/CAP7-Iteration/exercise&solutions/exercise_7_1.py
626
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 2 19:44:59 2019 @author: Utente """ #Chapter 7 - Iteration #Exercise 7.1 import math def mysqrt(a): x = a/5 while True: y = (x+ a/x) / 2 if y == x: return x x = y def test_square_root(): a = 1.0 ...
8752a38795e55dcfb59b7c776bb0c0d7e90b1f46
Apache0001/Curso-de-Python
/Repeticao-while2/ex066.py
216
3.84375
4
n = 0 totn = 0 soma = 0 while n != 999: soma = soma + n n = int(input('Digite um número: ')) if n == 999: break totn = totn + 1 print(f'total de numeros: {totn}') print(f'soma: {soma}')
595d26ff4470b19b198afeefbc6c5998e8f9ac8a
thatchloe/Data_structures-and-algorithms
/Unscramble Computer Science Problems/P0/Task3.py
2,713
4.1875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixe...
b66a4c88f32e3b7c887adee6c9a27d987ad0a446
mcascallares/combinational
/main.py
840
3.578125
4
def combinations(elements, size): if len(elements) == size or size == 1: return elements ret = [] for i, item in enumerate(elements): for j in combinations(elements[i + 1:], size - 1): ret.append(item + j) return ret def variations(elements, size): ret = [] for i in combinations(elements, size): ret.e...
bff521c9cfbdb5da82ab83fffd694c468e77b0ba
yash147/Python_codes
/palindrome.py
317
4.15625
4
a=eval(input("Enter the number to palindrome : ")) reverse=0 temp=a while (temp > 0): reminder =temp % 10 reverse =(reverse * 10)+reminder temp=temp//10 print("reverse of a string is = %d" %reverse) if(a == reverse): print("Number is palindrome") else: print("Number is not palindrome")
46fe52d420028386e4145eca661b6dd691f10372
NonPersistentMind/Python
/Mathematical Statistics/9 Two-Sample Tests/TwoSampleTests.py
6,473
3.765625
4
import numpy as np from math import sqrt import scipy.stats as st import warnings import sys arr = np.array warn = warnings.warn def get_data_from_file(filename): """ Returns a python list of numpy arrays formed from the specified file. Example below will be converted to [np.array(67,80,48), np.array(24,...
93cf62985a4ca3bfae6630c74b56ac33da25d64c
Sebin0123/Pythonbasics
/DAY1/area_rect.py
107
3.796875
4
#Area of rectange l=int(input("Enter length")) b=int(input("Enter breadth")) area=l*b print("area is",area)
9b7ea467d59ba3f4ebd6457d092586f63e40d8d6
wisdonbond/opendreamtest
/solutions/wisdonbond/01.py
168
3.546875
4
input_data = 15 temp = '' if input_data % 3 == 0: temp = temp + 'Fizz' if input_data % 5 == 0: temp = temp + 'Buzz' print(input_data if not temp else temp)
1e6fdf0cb48b0694f74c940a674c9197fd9aa57d
sameersrinivas/AlgoAndDS
/Algorithms/sorting/MergeSort.py
1,364
3.953125
4
""" T(n) = 2 T(n/2) + n n: time spent on merging Time: O(n log n) : Merge n elements log n times Space: O(n + log n) = O(n) : log n for recursive call depth, n for temporary list n: number of elements to sort """ class MergeSort(): def merge_sort(self, nums): if not nums: ...
f2863b3270f49ceb290032917b9e6d52c369ee70
skinder/Algos
/PythonAlgos/Done/revers_str_2.py
1,043
3.921875
4
''' https://leetcode.com/problems/reverse-string-ii/ Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characte...
9c307dcc6667aeae342ff0bd3c4ce3cefb0479f0
keisuke-osone/cedec_ai
/SampleAI.py
10,590
3.890625
4
# -*- coding: utf-8 -*- import copy import sys import random class Heroine: def __init__(self, enthusiasm): self.enthusiasm = enthusiasm self.revealedLove = [] self.myRealLove = 0 # 最初に熱狂度順にソート # sortedEnthusiasm = sorted(self.enthusiasm) def readLine(): return list(m...
a10b09c53c098c89193c4285b833244d0538dd48
samisaf/Learning-Programming
/Learning-Python/TowersOfHanoi.py
296
3.8125
4
cycle = 0 def move_towers(num, fro, to, spare): global cycle cycle = cycle + 1 if num != 0: move_towers(num - 1, fro, spare, to) print "Move tower:", num, "from:", fro, "to:", to move_towers(num - 1, spare, to, fro) move_towers(4, 'A', 'B', 'C') print cycle
f4ea91bf9a11840a5947707ee36e53ac15028cca
Miguel-Duke/introToPython_generalProjects
/project6_Functions.py
5,573
4.5
4
''' PROJECT 6 Functions You are to write a program which: *Defines the following 5 functions: whoamI() This function prints out your name and PRINTS OUT any programming course you have taken prior to this course. sign(number) This function accepts one parameter, a number, and PRINTS OUT a messa...
c0c9822c4c2da4554106f7ae871200d9c65307a2
ysei/project-euler
/pr018.py
2,254
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 17 4...
09019c8c2bfadd70d65bb660a0d5dd99d7fccb4f
RobertHan96/CodeUP_BASIC100_Algorithm
/1068.py
337
3.953125
4
''' 숫자 한개를 입력 받아서 점수에 해당하는 등급 출력하기 90 ~ 100 : A 70 ~ 89 : B 40 ~ 69 : C 0 ~ 39 : D ''' def calc(): a = int(input()) if a >= 90: print('A') elif 70 <= a <= 89: print('B') elif 40 <= a <= 69: print('C') else: print('D') calc()
91821f5413a9e3e7b6fc0289fd1bca98ccdf4520
scyther211/C4E29
/Session 2/hw/3_print_1.py
91
3.65625
4
X = input("Name here bitch: ") print("Hello",end='') print(" My name is ",end='') print(X)
ed102efb4140f7891ed8e33cdbbcbf0eb313ecdf
hendy3/A-beautiful-code-in-Python
/Teil_21_Türme_von_Hanoi.py
210
3.8125
4
def hanoi(anzahl, von, temp, ziel): if anzahl > 0: hanoi(anzahl - 1, von, ziel, temp) print(f'Scheibe {anzahl} von {von} nach {ziel}') hanoi(anzahl - 1, temp, von, ziel) hanoi(3, 'A', 'B', 'C')
1758027caae8127566922e4897649f69bb4d45b7
Gabrielly1234/Python_WebI
/ exercícios senquenciais/questao8.py
307
3.828125
4
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. # Calcule e mostre o total do seu salário no referido mês. print("Horas trabalhadas: ") horas=float(input()) print("Valor da hora:") val=float(input()) salarioh= horas*val print("salário:",salarioh)
4769bf06771ad731216e40dbb1c75b49dba3efa6
MohamedHmini/M2SI-COLLECTIVE-WORK
/COMPLEMENTS_ALGORITHMIQUES/TP/TP1/Moad_Charhbili/Ex10_TD1.py
2,425
3.53125
4
def main(): l=-1 while l!=0: l=int(input("1)Skis avec chaussures :\n 2)Skis sans chaussures \n 3)les batons : 3 euros par jour et 18 euros en forfait semaine \n 0)Exit")) if l==1: c = int(input("1)a la Journee :\n 2)Forfait semaine \n 0)Retour")) if c==1: ...
9eb26c98ee508d911c80b814bcc04ce376316e9c
AmbystomaMexicanum/pcc2e-exerc
/src/ch_04/e_4_2.py
187
3.9375
4
animals = ['dog', 'cat', 'hamster', 'kiwi', 'Ambystoma mexicanum'] for animal in animals: print(f"A(n) {animal} is a very cute animal.") print(f"All these animals are so cute!")
7b02ba7cf3dcb6ae7855f1d6cf6ba326c689dae0
tothefullest08/TIL_algorithm
/2019_Q3_Q4/프로그래머스/Level 1/레벨1-2.py
207
3.625
4
def solution(x): str_x = str(x) my_sum = 0 for i in str_x : my_sum += int(i) answer = False if not x % my_sum: answer = True return answer print(solution(11))
f5e0e08036817e8e9ff846d5ff1377c44de57128
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/7_loops_for-while/7.3.frequent scenarios/13.py
621
3.921875
4
""" На вход программе подается натуральное число n, а затем n различных натуральных чисел, каждое на отдельной строке. Напишите программу, которая выводит наибольшее и второе наибольшее число последовательности. """ n = int(input()) max_total = 0 total = 0 for _ in range(n): num = int(input()) if num >= max_to...
1a6542e8a847b22143eb494632276ac2c2285ac8
junwanghust/PythonCrashCourse-Exercises
/3/name_list_3_1.py
299
3.984375
4
# 将一些朋友的姓名存储在一个列表中,并将其命名为names。依次访问该列表中的每个元素,从而将每个朋友的姓名都打印出来。 names = ['kat', 'lily', 'jack', 'peter', 'bob'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4])
f2fd092c2e0dc6aa84a741a619f3ec2ed19f861b
vicchu/leetcode_101
/数据结构/6-树/树.py
10,604
3.828125
4
#%% class TreeNode: def __init__(self, val=0, left=None, right=None) -> None: self.val = val self.left = left self.right = right class Tree: def __init__(self) -> None: self.root = None def add(self, item): node = TreeNode(item) if self.root is None: ...
797ec2be8f9a66fed8a91bbe3c1413e1ca37e555
Wolffoner/7541-Algoritmos-y-Programacion-II
/Clases/11-Menu-C-Python/menu.py
1,363
3.625
4
contador=0 class Juego: def __init__(self): self.contador = 0 class Comando: def __init__(self, nombre, doc, funcion): self.nombre=nombre self.documentacion=doc self.ejecutar=funcion def mostrar_documentacion(self): print("Esta es mi documentacion") print...
8a0266c185f4e4775aab7a0c4d44e75b8368022b
yoovraj/deeplearning
/Machine Learning A-Z/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/cnn_network.py
1,758
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 14 14:47:36 2017 @author: yoovrajshinde """ # Part 1 - Building the CNN #importing keras libraries from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten fr...
23e9e3949977bff5ae76f92be4212e23b0aa60af
taesookim0412/Python-Algorithms
/2020_/06/LeetCodeJuneChallenge/04E_ReverseString.py
369
3.75
4
from typing import List #28.48% faster runtime class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ n = len(s) - 1 for i in range(len(s)//2): s[i], s[n-i] = s[n-i], s[i] print(s) print(...
b4209da298c976726250a5032a6c2ff6109a6ee5
SilveryM/studypython
/first_stage/practice/practice_98.py
441
3.875
4
#从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。 ''' #!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == ' __main__ ' fp = open ( ' test.txt ' , ' w ' ) string = raw_input ( ' please input a string: \n ' ) string = string . upper ( ) fp . write ( string ) fp = open ( ' test.txt ' , ' r ' ) pri...
f025aba9c5f0812d3610b1fa0922d5ce49a0bb56
StephenRaymond/COMPETITIVE-PROGRAMMING
/Beginner/CountNumericChar.py
83
3.515625
4
n=input() count=0 for x in n: if x.isnumeric(): count+=1 print(count)
8a6e6d3c7c9a7ecd3c56efd32d3bf9b4ce31ae49
Rohitha92/Python
/Sorting/MergeSort.py
812
4.0625
4
#Merge sort -> recursive sort def merge_sort(arr): if len(arr)>1: mid = len(arr)//2 #integer. not float left_half = arr[:mid] right_half = arr[mid:] #divide into single units merge_sort(left_half) merge_sort(right_half) i=0 #left_half index j=0 #right_half index k=0 ...
0f8923f61c8098f13a32d913e0fd587042c0f373
funktor/stokastik
/LeetCode/RecoverBST.py
2,327
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def swap(self, node1, node2): if node1 is not None and node2 is not None: temp = node1.val ...
9530ceb7cd4e1998e84df184bdbb514fd6378be5
beginstudy/python_newstudy
/pets.py
130
3.609375
4
pets = ['猫','狗','蛇','龟','狗','狗','狗','狗',] print(pets) while '狗' in pets: pets.remove('狗') print(pets)
28e782eb90caaf77d1feba8decc389f9372b71f8
ucsb-cs8-f17/cs8-f17-lecture-code
/lec12/ic04.py
2,624
4
4
import pytest def maskedPassword(pw): ''' takes one parameter `pw` and returns a string consisting of the first three characters contained in the variable `pw` followed by 'x's instead of the remaining characters in `pw`. The length of the returned value should be the same as the length of the parameter pa...
b33256a4995aacddb4ec5a8bd5296b22b0bf602e
Samk208/Udacity-Data-Analyst-Python
/Lesson_3_data_structures_loops/nearest_squares.py
851
4.40625
4
# Implement the nearest_square function. The function takes an integer argument limit, and returns the largest square # number that is less than limit. A square number is the product of an integer multiplied by itself, for example 36 # is a square number because it equals 6*6. # There's more than one way to write this...
64bfca61954360e923e808e1141c6514ba45cd94
zzgkly/Mytest
/Python/Stu.py
744
4.0625
4
name = ["jidao" ,"jirui" , "ji" , "xdd" , "rui"] print("这是原来的列表:") print(name) print("-"*50 + "\n") print("这是append操作的列表:") name.append("jidao") print(name) print("-"*50 + "\n") print("这是insert操作的列表") name.insert(0 , "jidao") print(name) print("-"*50 + "\n") print("这是del操作的列表") del(name[0]) print(name) print("-"*50 ...
b8ceabe1af9f24f1acb694641f32f61c05ca34a6
jqnv/python_challenges_Bertelsmann_Technology_Scholarship
/dice_simulation.py
2,603
4.53125
5
# In this exercise you will simulate 1,000 rolls of two dice. Begin by writing a function that simulates rolling # a pair of six-sided dice. Your function will not take any parameters. It will return the total that was rolled on # two dice as its only result. # Write a main program that uses your function to simulate r...
168abd8544f28641d70fa975ef208cf064d69658
RobinRojowiec/log-linear-sentiment-classifier
/tokenizer.py
2,077
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import nltk from nltk import word_tokenize from nltk.stem.porter import PorterStemmer nltk.download('punkt') class Tokenizer: def __init__(self, stop_word_file): """set of stop word tokens to filter""" self.stopwords = set() # patte...
45b97a3c321aed11c8edf69d1f0325ab3a8d33e3
GreedM/test
/spell.py
373
3.828125
4
def spell(n): if n==1: return "one" elif n==2: return "two" elif n==3: return "three" elif n==4: return "four" elif n==5: return "five" else: return f"not implemented: spell({n:d})" if __name__ == "__main__": s = input("Enter number: ") i ...
2ac05670cd25c3505d5575692354cc1963ce5038
AmenehForouz/leetcode-1
/python/problem-0804.py
1,748
3.734375
4
""" Problem 804 - Unique Morse Code Words International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. Now, given a list of words, each word can be written as a concatenation of the ...
a0864602b7d294a8c642b009388c1d9f364bc502
rajtyagi2718/tic-tac-toe
/tree.py
2,302
3.578125
4
from transposition import Table from board import Board class Tree: """Game state tree stored as dict map from board hashes to utility values. Root of complete game state tree is empty board. Each action during game step produces child board. Root has nine children. [X _ _] [_ X _] [_ _ X] [_ _ _] [...
316db008ce9e1dc9478512575af60749eefaef53
davidposs/FacialRecognition
/detector.py
3,637
3.53125
4
""" Created on Thu Nov 16 16:27:29 2017 @author: David Poss Face Detection Program: reads faces from a web cam in the following steps: 1. Get user's name to create a profile 2. Take 11 pictures, one for each (optional) expression 3. Saves to a data folder with other faces from the yale dataset 4. Auto...
6521a3e4330b3be36c88f0f29b303ba700125abe
amitdshetty/PycharmProjects
/PythonSandbox/01 Args and KWArgs/02_KWArgs.py
772
4.28125
4
# Using the dynamic dictionary to retrieve specific key value pairs def callPrint3(key, **kwargs): # Get dictionary keys print(kwargs.get(key)) # Get dictionary key value pairs for oneKey,value in kwargs.items(): print(oneKey + " " + value) # Define both the key and value to specify which argum...
d530bd709ec2183377269a193199fea47180f967
sandeepks23/pythonassignment
/Set1/assignment5.py
132
3.71875
4
tup=(1,2,3,4,5,6,7,8,9,10) lst=[] even_tup=() for i in tup: if i%2==0: lst.append(i) even_tup=tuple(lst) print(even_tup)
a038c63dd3698c4c64d67577fae72ebef1ecf7ad
jtpils/mankei
/mankei/__init__.py
1,335
3.703125
4
"""Collection of mankei functions.""" from ._hillshade import _hillshade def hillshade( elevation, resolution, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0 ): """ Calculate hillshade from elevation data. Parameters ---------- elevation : 2-dimensional array Input elevation data. ...
8a777377c466a1e6bf99b85c186d7f939f151c93
kanuos/python-programs
/Logic 1/sorta_sum.py
306
3.953125
4
# Given 2 ints, a and b, return their sum. However, sums in the range 10..19 # inclusive, are forbidden, so in that case just return 20. def sorta_sum(a, b): result = 20 if 19 >= a + b >= 10 else a + b print(f"sorta_sum({a}, {b}) -> {result}") sorta_sum(3, 4) sorta_sum(9, 4) sorta_sum(10, 11)
2d93798ed9126f997954d5bf5ff38af5a40e3c23
waltonb7944/CTI110
/M6T2_FeetToInches.py
451
4.25
4
# Converting feet to inches # 11/10/17 # M6T2_FeetToInches # Brittani Alvarez # Global constant INCHES_PER_FOOT = 12 #main function def main(): #Get the number of feet from the user. feet = int(input('Enter a number of feet: ')) # Convert that to inches. print(feet, 'equals', feet_t...
b0dd03c794cb31f3c1dec891f9eb8dcd4f5b1fa3
Aasthaengg/IBMdataset
/Python_codes/p03385/s632474056.py
143
3.578125
4
s = input() t1 = s.count('a') t2 = s.count('b') t3 = s.count('c') if t1 == 1 and t2 == 1 and t3 == 1: print('Yes') else: print('No')
817f35820644c2a928183cf04163592e9ecd64f8
mutoulovegc/gaochuang123
/桌面/day.5/while.py
105
3.671875
4
i = 1 while i <= 5: u = 1 if u <= i: print(("*"),end="") u = u + 1 print("")
6507d04e65dc5ae382bb07ad0300df6095cf1066
daki0607/AutomateBoringStuff
/guessinggame.py
702
4.1875
4
import random secretNumber = random.randint(1, 20) print("I have a number between 1 and 20") # Give the player 7 guesses for guessesRemaining in range(7, -1, -1): guess = int(input("Take a guess: ")) if guess > secretNumber: print("Your guess was too high") elif guess < secretNumber: prin...
4d8aef9c24e35aa861903f09c3ee7863c6106756
proghead00/hacktoberfest2020-6
/LCM.py
368
3.921875
4
''' Input : two integer with space in between OutPut : LCM of the number ''' a, b = input().split(" ") a = int(a) b = int(b) assert (a >= 0 and b >= 0), "a,b should be >= 0" def lcm(a, b): if (a > b): for i in range(a, a * b + 1): if (i % a == 0 and i % b == 0): ...
1fd638122437800eb9f03a8f926916d6b8e9b207
devanshu06/LearingCodes
/DSA_Algo/BinarySearch.py
2,021
4.375
4
#Binary Search Algorithm def bs(db, value): #Starting the binary search function start = 0 #String Pointer value is 0 end = db[-1] #End Pointer value is the last value of...
b78eb3219f2d2941183e80d1cdbfa45f3ac915c2
rexayt/Meu-Aprendizado-Python
/Aula10/Ex31.py
271
3.609375
4
n=float(input('Digite a distância da sua viagem: ')) v=n*0.50 m=n*0.45 if n <= 200: print('Sua viagem tem {:.0f} KMs e o valor cobrado será R$ {:.2f}.'.format(n, v)) else: print('Sua viagem tem {:.0f} KMs e o valor cobrado será R$ {:.2f}'.format(n, m))
91a4ab77329cb47a41438d53d010cd7b6ff503a3
iamanobject/Lv-568.2.PythonCore
/HW_7/Taras_Smaliukh/multiples.py
131
3.75
4
def solution(number): sum_0f_numbers = sum([i for i in range(1,number) if i % 3 == 0 or i % 5 == 0]) return sum_0f_numbers
0ff4af764a0c4833f90e1b5860d26a37f7f72fc0
myliu/python-algorithm
/leetcode/palindrome_pairs_v2.py
1,038
3.640625
4
class Solution(object): def palindromePairs(self, words): """ :type words: List[str] :rtype: List[List[int]] """ # Because the index of the word is returned, we need a map to store the word to index mapping idx = {} for i, w in enumerate(words): id...