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
e79be156fc9fa86f86179e21c7f84cacf06cc72b
kovsaw/Hand-vessel-identification
/binary_array.py
304
3.71875
4
import numpy def _binary_array_to_hex(arr): """ internal function to make a hex string out of a binary array. """ bit_string = ''.join(str(b) for b in 1 * arr.flatten()) width = int(numpy.ceil(len(bit_string)/4)) return '{:0>{width}x}'.format(int(bit_string, 2), width=width) A
b792612970f4dc773371a0f09b50f39457d570cb
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/beer-song/cb3fcb6f7f0246698078861a61ef5a00.py
918
3.890625
4
class Beer: """ Counts down the bottles of beer on the wall song""" def verse(self, n): if n == 0: return "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n" b = "bottles" c = n - 1 d =...
fb1287b49b4a2b7a498ec1c26a22c0fa6390b8db
JMCCMJ/CSCI-220-Introduction-to-Programming
/HW12/hw12.py
13,950
3.921875
4
#hw12.py #Jan-Michael Carrington #Purpose: To construct a class for a deck of cards. #Authenticity: I certify this code is my own work. from graphics import * from random import * from time import sleep class Button: """A button is a labeled rectangle in a window. It is activated or deactivated with the acti...
8fef5bc6a5090423c79d925793663e82a52a7ba8
s-touchstone/College
/Advanced Computer Languages - Python/CantorStart - Bonus.py
940
4.21875
4
#Steven Touchstone #Advanced Programming Language (Python) #Professor Vladimir Ufimtsev #Cantor Lines Assignment (Bonus) import turtle as T #raise/lower pen for drawing lines def _bwswitch(): if T.isdown(): T.up() else: T.down() #drawing the white lines over the black to cut in thirds def _cant...
20b2cc8ce0b04d20556c29bf7ae9fe7882006691
HarlanJ/CS-Python
/PrimeNumber.py
2,070
4.21875
4
#John Harlan #Prime Number function #CS 100 #------Algorithm------ #1. Ask user for a number to test #2. store answer (query) #3a. If query is prime #3a1a.create a place to store if the query is prime,defaulting to True #(prime) #...
e75513836ed2379ad2fcf345b93b3b1c32f26b7d
nhuntwalker/canvas-automation
/pair-maker.py
1,433
3.953125
4
"""This module can be used to form pairs for students. David Smith - 2017 """ import random def make_better_pairs(num_days, students): """Print out some pairs for a given number of days.""" student_dict = {} for student in students: temp = dict({}) for s in students: if s !...
45b68b6e15e92d3b650cdcc3d25df202085c1f4b
codexnubes/Coding_Dojo
/api_ajax/OOP/car/car.py
1,078
3.921875
4
class Car(object): def __init__(self,price,speed,fuel,mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage if price > 10000: self.tax = 0.15 else: self.tax = 0.12 self.display_all() def display_a...
bc7e4baf2b40dd67c4d35a7d9468a10075605965
jupiterangulo/randomDraftOrder2018
/draftOrderPublic.py
886
4.03125
4
# import libraries import random import time # create function for Draft Order def assignDraftOrder(): # enter number of players in your league size = 10 #default to 10 # insert players names here players = ['Bob', 'Ray', 'Fred', 'Leroy', 'Otis', 'Chet', 'Chad', 'Miles', 'Guy'...
26bcef22ef45b73215765abb4c42704e6facdd8b
craignicol/adventofcode
/2020/day.1.py
906
3.796875
4
#!/usr/bin/env python3 def execute(): with open('2020/input/1.txt') as inp: lines = inp.readlines() numbers = [int(l.strip()) for l in lines if len(l.strip()) > 0] return multiply_to_2020(numbers), multiply_3_to_2020(numbers) def verify(a, b): if (a == b): print("✓") return ...
57b5de8d87c1184fd1d2b19081949016653a9b2f
Web-Dev-Collaborative/Lambda-Final-Backup
/7-assets/past-student-repos/Sorting-master/src/recursive_sorting/recursive_sorting.py
3,245
4.125
4
import random # TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # Iterate through marged_arr to insert smallest item in arrA and arrB until merged_arr is full for i in range(0, len(merged_arr))...
5d16d2431314f3918a84614867e4e8fb00a7370b
iamreebika/Python-Assignment2
/Examples/19.py
1,537
4.34375
4
""" 19. Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' and ']. These brackets must be close in the correct order, for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid """ class ParenthesesValidation: paragraph = '' open_parentheses = tuple(...
799d206f0c25d5a6f2e405582f54f48c2e024a29
RizwanRumi/python_Learning
/try6_assert.py
293
4.03125
4
""" print(1) assert 2 + 2 == 4 print(2) assert 1 + 1 == 3 print(3) """ def KelvinToFahrenheit(Temp): assert (Temp >= 0), "colder than absolute zero" return ((Temp-273)*1.8)+32 print( KelvinToFahrenheit(273) ) print( int(KelvinToFahrenheit(505.78)) ) print( KelvinToFahrenheit(-5) )
6b2811985f6fe2537bf2a4dc134b8f411d888fe2
claireyegian/unit1
/nameAge.py
336
3.890625
4
#Claire Yegian #8/31/17 #nameAge.py - characters in a name and age next year name = input('Enter your first and last name: ') name1, name2 = name.split() print('Your first name has', len(name1), 'letters, and your last name has', len(name2), 'letters.') age = int(input('Enter your age: ')) print('Next year you will be...
03bda825834035b06a91c3d876bc06a2269c229c
jrantunes/URIs-Python-3
/URIs/URI1072.py
277
3.59375
4
#Interval 2 in_interval = [] out_interval = [] for i in range(int(input())): x = int(input()) if x in range(10, 21): in_interval.append(x) else: out_interval.append(x) print("{} in\n{} out".format(len(in_interval), len(out_interval)))
03c64189622b6ee5710b7c5b0e5532cb7a356591
lama-imp/python_basics_coursera
/Week5_tasks/10_sumfact.py
184
3.96875
4
def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) n = int(input()) sum = 0 for i in range(1, n + 1): sum += factorial(i) print(sum)
b87b690823dd5501ff4418ae82c52f20d3d634d0
Niloy28/Python-programming-exercises
/Solutions/Q11.py
501
4
4
# Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and # then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. # Example: # 0100,0011,1010,1001 # Then the output should be: # 1010 str...
fc7f962d046c49ffceb31f3339249be47152a464
maza2580/test
/hello.py
85
3.5625
4
#!/usr/bin/python3 import math a = float(input("Lederlappen: ")) print(math.sqrt(a))
97b55981ca2941e887a8611d4b22f2dadc71e934
anvartdinovtimurlinux/py-30
/py_homework_basic/2_3_exceptions.py
2,181
4.3125
4
# Нужно реализовать Польскую нотацию для двух положительных чисел. # Реализовать нужно будет следующие операции: # 1) Сложение # 2) Вычитание # 3) Умножение # 4) Деление # Например, пользователь вводит: + 2 2 Ответ должен быть: 4 def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a,...
f56e9923dfba17788a0677dde1e03f9bc0170cb9
navyifanr/LeetCode-Source
/LeetCode-Py/Array/[14]最长公共前缀.py
1,053
3.671875
4
# 编写一个函数来查找字符串数组中的最长公共前缀。 # # 如果不存在公共前缀,返回空字符串 ""。 # # # # 示例 1: # # # 输入:strs = ["flower","flow","flight"] # 输出:"fl" # # # 示例 2: # # # 输入:strs = ["dog","racecar","car"] # 输出:"" # 解释:输入不存在公共前缀。 # # # # 提示: # # # 1 <= strs.length <= 200 # 0 <= strs[i].length <= 200 # strs[i] 仅由小写英文字母组...
7ecc1c16af906a9a41b8ac01a74f158a14ae80e0
armut/thinkcs-solutions
/chapter-04/4-4.py
252
3.8125
4
# exercise 4.4 import turtle def draw_poly(t, n, sz): for i in range(n): t.forward(sz) t.left(360//n) t.left(18) wn = turtle.Screen() turtl = turtle.Turtle() for i in range(20): draw_poly(turtl, 4, 75) wn.mainloop()
3a79cd425c6081b78fdbd103fd147f7f3c151a6d
MrDeshaies/NOT-projecteuler.net
/euler_028.py
1,424
3.765625
4
# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral # is formed as follows: # # 21 22 23 24 25 # 20 7 8 9 10 # 19 6 1 2 11 # 18 5 4 3 12 # 17 16 15 14 13 # # It can be verified that the sum of the numbers on the diagonals is 101. # # What is the sum of the numbers on ...
8bf98b8bd11962c739b4d82c65a2d0dbc0ecfb60
StefanRvO/ProjectEuler
/Solved/problem51.py
1,641
3.828125
4
#/usr/bin/python import sys from itertools import combinations def isprime(num): if num<1: return False prime=0 for i in range(2,int(num**0.5)+1): if num%i==0: prime=1 break if prime==0: return True else: return False def GetPrimeCount(numbe...
428834812b707058cab25b0e252703754a25979c
sheikh210/LearnPython
/functions/star_examples.py
922
4.96875
5
numbers = (1, 2, 3, 4, 5) # Using * unpacks the sequence (tuple in this example) # The first print statement won't print any separators, as it is only 1 value # This ensures that Python is, in fact, unpacking our sequence type, then printing it as separate values print(numbers, sep=";") print(*numbers, sep=";") pr...
792145573e43f93b292693392934792c7093ab0f
jonnor/datascience-master
/inf250/assignment3/bd_backend.py
3,840
3.578125
4
# -*- coding: utf-8 -*- """ Backend for the blob detection coursework for INF250 at NMBU. """ __author__ = "Yngve Mardal Moe" __email__ = "yngve.m.moe@gmail.com" import numpy as np from threshold import threshold, histogram import sys def _remove_and_relabel_blobs(labeled, wanted_blobs): """This function remov...
1420b400e45bf4fe105d1410dc2c5636e29e7f8e
phillui-37/FP
/compose.py
1,905
3.671875
4
from functools import reduce from typing import Callable, Union class compose: """ Compose functions into a pipeline, which the result will pass over functions Function invocation order: left->right(default) Examples: .. code-block:: python # order is filter->map co...
9d57e5e5138d777802b5bf598628a5e56b52239b
cseibm/19113016_ShreyaKishore
/print a range from a starting number.py
128
4.15625
4
a=int(input("enter the starting number:")) n=int(input("Enter nth Number: ")) for i in range(a, n+1): print (i, end = " ")
9dc27a1193dd4aaaed7517e5da680342459e26f9
fdfzjxxxStudent/CS001
/CS001-lesson3/relation.py
102
3.5625
4
print(5 > 3) print('5' < '3') print(5 >= 3) print('A' <= 'a') print(3 == 3.0) print('A' != 'a')
5bb9f5fbeee4b12f3601c61317387e13f62a0e90
Ahmet-Kirmizi/Fibbonaci-sequence
/fibonacci.py
695
4.40625
4
# lets create a input variable that ask for the sequence nth_term = int(input('please enter the number of sequences you want to see: ')) # count variable that will be used to break the while loop count = 0 # everytime the loop starts over it will update count # it will have 2 numbers number1, number2 = 0, 1 ...
acd71875a340eef6303f23ef4d386049155b9e4c
leni1/python-fizzbuzz
/fizzbuzz.py
379
3.625
4
def fizzbuzz(a, b): if isinstance(a, list) and isinstance(b, list): len_sum = len(a) + len(b) if len_sum % 3 == 0 and len_sum % 5 == 0: return 'fizzbuzz' if len_sum % 3 == 0: return 'fizz' if len_sum % 5 == 0: return 'buzz' else: ...
ac1225f1825495ae659c0fec5b9149517d32f0ca
aditya-doshatti/Leetcode
/consecutive_characters_1446.py
775
3.8125
4
''' 1446. Consecutive Characters Easy Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character. Return the power of the string. Example 1: Input: s = "leetcode" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' ...
e9c180bbf754bc3cce0081988dc4289410a25f11
mariojerez/Space-Impact
/Space Impact final.py
16,594
3.703125
4
## Mario Jerez ## Mini Project ## Space Impact import os os.chdir("/Users/mariojerez/Documents/Computer Science/MarioMiniProject") from graphics import * import math, time, random ##Button code borrowed from class class Button: # constructor def __init__(self, win, graphicsObject, color, label): graph...
c7b91c51f3a9ef49798c53e321c86df3a93d1ddf
dpmanoj/Kaio-machine-learning-human-face-detection
/server/predicting.py
4,856
3.625
4
############################################################# # Predict methods supporting to test accuracy and perfomance ############################################################# # Import from collections import Counter import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import learn...
67a6ade34169bbe8226562b49ed975b10869afea
pheninmay/practice
/challenge7/challenge7_4.py
867
3.78125
4
# 無限ループする数字当てプログラムを書こう。ユーザーに文字を入力してもらい # qが入力されたら終了、数字が入力されたら正解がどうか判定しよう。正解の数値は # プログラム内にいくつかリストで持たせておいて、ユーザーが入力した数字がそのどれかと # 一致したら「正解」、一致しなかったら「不正解」と表示しよう。もし数字かq以外の文字が # 入力されたら、「数字を入力するか、qで終了します」と表示しよう。 ans = ["1","5","7"] while True: f = input("数字を入力するか、qで終了します") if f == "q": break elif f in ans:...
1824b0ef9897f7602e41827c17e2c2b6aa0c1ac3
aabramson/python
/Alunos com média e aprovação.py
2,535
4.03125
4
# Cadastro de alunos com notas e médias print () print ('Bem vindo ao sistema de cadastro da escola Raimundão. CHAMA!!!') print () alunos = [] notas_p1 = [] notas_p2 = [] notas_p3 = [] notas_p4 = [] while 1: aluno = input ('Por favor, insira o nome do aluno, ou aperte ENTER para terminar a operação: ') if not ...
a41cdb0113b5a984a0f3e26f62699d8f697e15fd
Isoxazole/Python_Class
/HW1/hm1_william_morris.py
4,549
4.375
4
"""Homework1 William Morris 1/29/2019 This is a 'security program' that will loop through a series of questions until the user answers all the questions successfully. If the user fails to answer a question correctly, the program will restart. After answering all the questions successfully, the secret message will be di...
5d1e38c30ff8ea0dd885e93db5e982f1839488f7
green-fox-academy/balazsbarni
/week04/11-sharpie-set.py
696
3.796875
4
#### Sharpie Set #- Reuse your `Sharpie` class #- Create `SharpieSet` class # - it contains a list of Sharpie # - count_usable() -> sharpie is usable if it has ink in it # - remove_trash() -> removes all unusable sharpies class Sharpie(object): def __init__(self, color, width, ink): self.color = color ...
b224bdd749e6827209502c081609a1c9d018322c
rajput-shivam/BSC-CS-Sem4-FundamentalOfAlgoPracticals
/MergeSortAlgorithm.py
932
4.0625
4
def mergeSort(a): if len(a)>1: mid = len(a)//2 left= a[:mid] right= a[mid:] print("before left and right: ",left,right) mergeSort(left) mergeSort(right) print("after left and right: ",left,right) i=j=k=0 print("\nbefore a:",a) ...
2ea945fc304127793364d9b2fb05c6ad03f8f250
Ressull250/code_practice
/part4/268.py
252
3.578125
4
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) summ = sum(nums) return n*(n+1)/2 - summ print Solution().missingNumber([0,1,3])
08848d4a5dc8bed2ba25214cd700e114eecdfc3b
willykurmann/PythonScriptingCourse
/PythonAutomation/classes.py
322
3.53125
4
class A: d = 100 def __init__(self): print("This is constructor") def display(self): print("This is display method") def sum(self,a,b): print(a+b) def classvar(self): print("this is class variable d: {}".format(A.d)) a = A() a.display() a.sum(1,2) a.classvar(...
498914bf0789e4a8d8b48876e99757ca2ffd6ee5
AdamZhouSE/pythonHomework
/Code/CodeRecords/2346/60635/242681.py
1,080
3.71875
4
count = int(input()) def add_to_list (matrix, ans): if len(matrix) == 0: return elif len(matrix) == 1: for m in matrix[0]: ans.append(m) return elif len(matrix) <= 2: for m in matrix[0]: ans.append(m) for i in range(len(matrix[0])-1,-1,-1): ...
b79c016c80d8e48b35abc08c819a22ac01e5ecde
miyagipipi/studying
/最长回文子串.py
1,387
3.953125
4
'''5 最长回文子串''' '''给定一个字符串 s,找到 s 中最长的回文子串''' #优化解法 def longestPalindrome(self, s): if not s: return "" length = len(s) if length == 1 or s == s[::-1]: return s max_len,start = 1,0 for i in range(1, length): even = s[i-max_len:i+1] odd = s[i-max_len-1:i+1] if i - max_len - 1 >= ...
ca026b4eb27dd9e38577713e81eed7ba66bb3b4a
eminem18753/hackerrank
/Problem solving/Algorithm/between_two_sets.txt
939
3.59375
4
#!/bin/python from __future__ import print_function import os import sys import math # # Complete the getTotalX function below. # def gcd(a,b): if b==0: return a else: return gcd(b,a%b) def getTotalX(a, b): # # Write your code here. # count=0 first=1 second=b[0] for...
a31b58c56d15c32b7633163c65c503ea7f75b54e
juneltx/qcb-78
/python_class/ui_lesson_01.py
1,548
3.796875
4
"""接口自动化、UI自动化(人工点、浪费时间,效率低下。枯燥)、APP自动化 UI自动化是人和浏览器界面的互动,代码代替人实现和浏览器之间的互动 代码---通过 浏览器驱动 将代码指令翻译给浏览器,使得浏览器做出响应 Chromedriver(如果用最新的可以,没有最新的可以用71版本,比较稳定,可以向前兼容高版本。低版本的驱动可以翻译高版本的浏览器 geckodriver ieserverdriver 下载解压为chromedriver.exe,放至python安装目录文件夹下""" ##2、selenium工具,UI自动化工具,也是第三方库文件 '''selenium工具包括三个部分: 1、ide 用来录制脚本,用得少,不好...
3e77e9357c2028d159e3263c2c7ecc3aa4ef8d57
AChen24562/Python-QCC
/Week-13-File-Day2/FilesExamples_II/Ex6_file_append.py
423
4.375
4
# To write to an existing file, # you must add a parameter to the open() function: # "a" - Append - will append to the end of the file # "w" - Write - will overwrite any existing content # Open the file and append content to the file: file = 'myfile1.txt' f = open(file, "a") f.write("Now the file has more content!\n")...
940905bb36d700f194bf6e28645a9b0174e1c692
SinghHrmn/PythonProgramsV2
/start printing.py
119
3.875
4
i=1 n=int(input("enter the number of stars ")) ans="" for i in range(1,n+1): ans=ans+"*" print (ans) i=i+1
8c7ab83cc7a2d37745ff4b9549e8e4b639e48100
Chrisgarlick/Python_Projects
/My_Projects/Mean_median_mode.py
517
3.84375
4
import math lst = [1, 4, 5, 67, 2, 3, 5, 6, 1, 23, 4, 6, 7, 1, 2, 2, 234, 3, 32, 1, 12, 2, 2] # Mean - Add all up and divide by length def mean(lst): total = sum(lst) average = total / len(lst) return average # Median - Sort and find middle number def median(lst): lst.sort() length = len(lst) ...
ee811133389acbabdefc8dc0eb6e82690d530673
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_397.py
799
4.0625
4
def main(): userTemp = float(input("Please enter the temperature: ")) tempVari = input("Please enter 'C' for Celsius, or 'K' for Kelvin: ") if userTemp <= 0 and tempVari == C: print("At this temperature, water is a (frozen) solid.") if userTemp > 0 or userTemp < 100 and tempVari == C: pr...
0ecb51ea9cde416e316a0d2d4f36221b2296477e
dalexach/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/0-norm_constants.py
540
3.9375
4
#!/usr/bin/env python3 """ Normalization Constants """ import numpy as np def normalization_constants(X): """ Function that calculates the normalization (standardization) constants of a matrix: Arguments: - X: is the numpy.ndarray of shape (m, nx) to normalize * m is the number of data ...
aece6d1fa40aa6b2ca3da1decb18948521d72c89
BHUVANESHWARI12/py
/b-8.py
109
3.984375
4
s=0 print("sum of natural numbers upto N") n= int(input("N=")) for x in range(1,n+1): s=s+x print(s)
e89dc35b5897cd9c7003969dc42e91fa5c09be2f
yasas100/Python
/beginner/madlibs.py
749
4.1875
4
#!/usr/bin/env python """ File: madlibs.py Author: Tem Tamre A madlibs adventure! Concepts covered: Strings, IO, printing """ __author__ = "Tem Tamre" __copyright__ = "ttamre@ualberta.ca" def main(): name = input("Enter a name: ") place = input("Enter a place: ") vehicle = input("Enter the name o...
c62eb787de5a33b3e6dcf5db50bf08a5da118224
angelxehg/utzac-python
/Unidad 2/Ejercicios Clases/Ejercicio3.py
637
3.921875
4
class Numbers(): def __init__(self, num1, num2): self.__num1 = num1 self.__num2 = num2 def added(self): return self.__num1 + self.__num2 def subtracted(self): return self.__num1 - self.__num2 def multiplied(self): return self.__num1 * self.__num2 def divi...
d92d752f1f34f63eb77649741754b0091ee6a949
sohag2018/Python_G5_6
/FromAnkur/password_generate.py
327
3.65625
4
import string import random '''def add(x,y,z=0): return x+y+z print(add(5,6)) print(add(5,6,10))''' def pw_generate (size=1,chars=string.ascii_letters+string.digits+string.punctuation): return ''.join(random.choice(chars) for _ in range (size)) print(pw_generate(int(input('How many characters in your passwor...
618a07b7b92daab28be4fd1911611699e33e4846
arahant/Science-Simulator-Calculator
/python/physics/mechanics/motion/generic/Projectile.py
1,902
3.6875
4
import math import numpy as nm import matplotlib.pyplot as plt def calculateTime(iVy,g): return float(iVy)/g def calculateRange(time,iVx): return float(iVx)*time def calculateHeight(iVy,g): return float(math.pow(iVy,2))/(2*g) def getY_X_TrajectoryEquation(x,iVx,g,angle): return nm.tan(nm.pi*angle/18...
ca3cb64788663f8024317fd9fc0f08c7c627b422
programmingkids/python-level1
/chapter06/work10.py
91
3.53125
4
num = 10 if : print("5以上です") else : print("5より小さいです")
ba16629db78b9de869df678c1fb86173ef837412
uutzinger/BucketVision
/2018 Pipeline/framerate.py
1,180
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 24 20:46:25 2017 @author: mtkes """ import time class FrameRate: def __init__(self): # store the start time, end time, and total number of frames # that were examined between the start and end intervals self._start = None self._end = ...
2528f5525d9f0d6928ed7eb1df8198b98f8a70b9
goodluckcwl/LeetCode-Solution
/树/687. 最长同值路径/longestUnivaluePath.py
582
4.0625
4
# -*- coding: utf-8 -*- # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ i...
77c1879079cfe2338a272d7690caf34f93220263
savourylie/cracking_the_code_interview
/ch1/1_8_zero_matrix.py
607
3.828125
4
def zero_matrix(mat): zero_rows = set() zero_cols = set() for i in range(len(mat)): for j in range(len(mat[0])): if mat[i][j] == 0: zero_rows.add(i) zero_cols.add(j) return [[mat[i][j] if i not in zero_rows and j not in zero_cols else 0 for j in range(len(mat[0]))] for i in range(len(mat))] if __na...
b2bae9ea05229da1a496eb0e7a0425a9e17f0bdf
fausrguez/python-exercises
/4/main.py
2,442
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Crea un programa en Python que pida un número n al usuario, y a continuación cree una lista con las n palabras pedidas al usuario. Una vez creada la lista la imprimes en pantalla, y a continuación le pide al usuario dos palabras más pal1 y pal2. Se pide que cuente l...
cb7ce78db7d8eb358281114d39fba3d2077201ed
coreyadkins/codeguild
/practice/tic-tac-toe/coords_board.py
3,711
4.15625
4
"""This module performs the functions for Tic-Tac-Toe (TTT) program of placing a token on the board, determining the winner of a game, and returning a str version of the board, using tuples data type. """ from operator import itemgetter class CoordsTTTBoard: """Contains a blank TTT board as list of tuples items, ...
2d411489254cb6e7ff470bb4a20e8cb2c732dc03
mEyob/ds-challenge
/prepare_data.py
1,187
3.65625
4
import boto3 from zipfile import ZipFile BUCKET_NAME = "fairmarkit-hiring-challenges" OBJECT_NAME = "California Purchases.zip" def download_from_s3(download_path, bucket_name=BUCKET_NAME, object_name=OBJECT_NAME): """Utility function for downloading data from S3 Args: download_path (string): The file...
420350a9edbfe751376913fb6bdf65cb7565a6b5
GrantRedfield/SemesterProject
/TimeAnalysis/Day_Of_The_Week.py
1,286
3.515625
4
import datetime import pandas as pd import matplotlib.pyplot as plt import folium import folium.plugins as fplug from IPython.display import display import os Path = 'C:\\Users\\Grant\\Desktop\\Random\\CS_Group_Project\\' Path_alt = "C:/Users/Grant/Desktop/Random/CS_Group_Project/map.html" week_days_lookup...
f239617568f5b65cb1013d0d909a7043de125fb7
1van-me/telebot
/ivan-me/12.py
385
3.5625
4
spisok=[["qwerty", "12345"]] while True: answer=input("Введите команду: ") if answer=="войти": user=enter(spisok) if user==True: print:("Вход выполнен") elif user==False: print:("Ошибка входа") elif answer=="выход": exit() elif answer=="вход": ...
fb85be46a92c302c8b231548624f5c2030e969b2
flyingdutch20/tiny_python_projects
/07_gashlycrumb/gashlycrumb.py
1,420
3.796875
4
#!/usr/bin/env python3 """ Author : Ted <ted@bracht.uk> Date : 25 June 2020 Purpose: Return a name and a ghastly way to end """ import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description="Retur...
93a4b5fe38655a57586201d63daea2213da13f5c
SupakornNetsuwan/Prepro64
/I N T E G E R is useful (Extra).py
150
3.8125
4
"""function print""" def func(): """Convert base of number""" number = input() base = int(input()) print(int(number, base)) func()
00d8754d65a4900323ec8f8eb744272d6902843c
Ivaylo-Atanasov93/The-Learning-Process
/Python Advanced/Functions_Advanced-Exercise/Function Executor.py
659
3.796875
4
def func_executor(*args): result = [] for argument in args: func = argument[0] arguments = argument[1] result.append(func(*arguments)) return result # def func_executor1(*args): # result = [] # for element in args: # func_name = element[0] # func_input = el...
f1c69510db8950c6019234a6e817b4031c75d2a6
nationalarchives/ds-alpha-es-ingest
/date_handling.py
3,911
3.5625
4
from datetime import datetime import calendar from collections import namedtuple import json import requests def parse_eras(): era_data = {} r = requests.get("https://alpha.nationalarchives.gov.uk/staticdata/eras.json") if r.status_code == requests.codes.ok: eras = r.json() else: with ...
cf50fd569f432e1e3fb54b2e9fefcf5fe27674b5
akhileshcheguisthebestintheworld/pythonrooom
/menu.py
280
4.21875
4
# author: akhileshcheguisthebestintheworld menu = ["pizza","pasta","cake"] for thing in menu: answer = input("Do you like " + thing +"?") if answer == "yes": print "Have it" + "." elif answer == "no": print "Okay." else: print "I do not understand what that was" + "."
6cf069ae7c7973604be3a67851ab37539a2c43ee
dotKuro/vorsemesterWISE19-20
/loesung/blatt1b_4d.py
321
3.578125
4
# Hier sollen alle Zahlen von 1 bis 4 in jeder Kombination mit einander # multipliziert und sinnvoll ausgegeben werden. for factor1 in range(1, 5): for factor2 in range(1, 5): # Die Platzhalter werden von links nach rechts eingesetzt. print("{} * {} = {}".format(factor1, factor2, factor1*factor2))...
50dbfb31aa5ae3b6cd03f3dde738db91a5e3bb59
Arun101308/Arun101308
/fibonacci.py
485
4.0625
4
n = int(input("ENTER NUMBER")) # INPUT VALUE def fibonacci(n): # FIBONACCI IN VAL N a = 0 b = 1 if n < 0: # IF VAL N GRATERTHEN 0 print("Incorrect input") elif n == 0: # ELSE IF N INEQUALEN 0 return 0 elif n == 1: # ELIF N INEQUALEN 1 return b else: fo...
6d755034bf6d3cefc1a453a179f9b8618e6c699d
doubleZ0108/Mathematic-Model
/DataVisualization/Plot/subplot.py
387
3.578125
4
# -*- coding: utf-8 -*- ''' @program: subplot.py @description: 子图 @author: doubleZ @create: 2020/02/10 ''' import matplotlib.pyplot as plt import numpy as np def drawSubplots(): x = np.linspace(0,5,10) fig, axes = plt.subplots(figsize=(8,6),dpi=100) axes.plot(x, x**2, 'r') axes.set_title('y=x^2')...
1d2b37893687ef2246a1eea28c068d0258a4db9e
smohapatra1/scripting
/python/practice/start_again/2021/06022021/valid_mountain_array.py
520
3.921875
4
#Valid Mountain Array # 353 - > A mountain Array # 01321 - > Not an montain array def ma(nums): # Need minimum 3 inputs if len(nums) <3: return False i = 1 #Increasing hill while i < len(nums) and nums[i] > nums[i-1]: i+=1 if i == 1 or i ==len(nums): return False ...
9db62ab284e542e4d3269c308dd63ec89d75fde8
tshev/pybind-experiments
/python_example/usage.py
389
3.578125
4
import python_example import numpy as np import timeit n = 10**7 a = np.random.random(n) b = np.random.random(n) def dot_product(x, y): r = 0.0 for a, b in zip(x, y): r += a * b return r print(timeit.timeit(lambda: python_example.dot_product(a, b), number=1)) print(timeit.timeit(lambda: a.dot(b), ...
bd66561939c33ccc90275a4e1ce3a6edc40c7d99
BTomlinson/PFB_problemsets
/python_probset6.py
751
3.796875
4
#! /usr/bin/env python3 opPython = open('Python_06.txt', 'r') newPython = open('NewPython.txt','w') #simply open and read the contents of Python_06.txt print(opPython.read()) print() #uppercase everything line by line in Python_06.txt and print the result opPython = open('Python_06.txt','r') for line in opPyth...
a5d832ce3b9fbea2f294c8b0bd7aee6e37fba9f8
half-cat/gu-chatbot-01
/clients/exceptions.py
713
3.59375
4
"""Модуль исключений, связанных с работой клиентов социальных платформ.""" class OkServerError(Exception): """Возникает при возврате invocation-error в заголовках ответа от ОК.""" def __init__(self, code: str, text: str) -> None: super().__init__( f'OK error: code {code} -> {text}"' ...
be5f965a5026f5c62f98600f321ecf39807fb02b
sunyi1001/leetcode
/49.py
990
3.640625
4
class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ # find_map = {} # returnData = [] # for item in strs: # sortedStr = ''.join(sorted(item)) # if sortedStr in find_map.keys(): # ...
7fc2d1ab4aa20cfc5b35316eef60d38297785b12
bmoretz/Daily-Coding-Problem
/py/dcp/leetcode/hashtable/duplicate_subtrees.py
1,420
3.78125
4
''' 652. Find Duplicate Subtrees Example 1: Input: root = [1,2,3,4,null,2,4,null,null,4] Output: [[2,4],[4]] Example 2: Input: root = [2,1,1] Output: [[1]] Example 3: Input: root = [2,2,2,3,null,3,null] Output: [[2,3],[3]] Constraints: The number of the nodes in the tree will be in the range [1, 10^4] -200 <= Nod...
b4afe175a25e09a6ba0e0752ad6ca12ee2914ae2
rdsilvalopes/python-exercise
/estruturasequencial04.py
876
3.828125
4
#! usr/bin/env python3 ################################################################## #Faça um Programa que peça as 4 notas bimestrais e mostre a média. ################################################################## def media_prova(): #uma lista para armazenar números. lista_numeros = [] tr...
45c63f2733cee7c8fcb70a3ae1d5c9fbcd166cee
zhangwei1989/algorithm
/Python/242-valid_anagram_first_2.py
645
3.59375
4
# Difficulty - Easy # Url - https://leetcode.com/problems/valid-anagram/ # Time complexity: O(N); # Space complexity: O(1); class Solution: def isAnagram(self, s, t): dict = {} li = [chr(i) for i in range(ord("a"), ord("z") + 1)] for i in li: dict[i] = 0 for i in s: ...
63e2cf18e18d3e52142efed40810667feebff805
HeatherHeath5/progcon
/08/spring/failed/quodigious/1.py
473
3.546875
4
def digits(n): return [int(digit) for digit in str(n)] def prod(li): return reduce(lambda x, y: x*y, li) def quodigious(n): return n % sum(digits(n)) == 0 and n % prod(digits(n)) == 0 if __name__ == '__main__': while 1: try: inp = int(raw_input()) except: break fo...
05c36fafea97cac580118af7f81aa3b4483fb1b6
karimm25/Karim
/TSIS 2/Lecture6/4.py
58
3.890625
4
# Python program to reverse a string print(input()[::-1])
2d1562551b73c03be83864f84b7ed326f191db24
DalavanCloud/UGESCO
/functions/test_levensthein.py
1,459
3.53125
4
import Levenshtein as L string1 = "Musée royal de l'Afrique centrale" string2 = "musée colonial de Tervueren" print('Levenshtein is ', L.distance(string1, string2)) print('jaro-winkler is ', L.jaro_winkler(string1, string2)) print('jaro is ', L.jaro(string1, string2)) from difflib import SequenceMatcher def simil...
195f6ca5897a34a376237e69c400b9d093bc00da
YunsongZhang/lintcode-python
/VMWare/380. Intersection of Two Linked Lists.py
913
3.765625
4
class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param headA: the first list @param headB: the second list @return: a ListNode """ def getIntersectionNode(self, headA, headB): if headA is None or headB i...
f18eb6e4269d282b98c74646ef1acc41e4f3cf55
jduell12/cs-module-project-hash-tables
/d2_lecture.py
1,795
4.09375
4
#linked list for Hash tables class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None self.count = 0 def insert_at_head(self, node): node.next = self.head self.head = no...
e89084c121b88ccdeb8269d231e2c57fd71ad6dd
cwebrien/tiger-sat-generator
/tigersatgenerator/uniformksat/generator.py
1,820
3.75
4
#!/usr/bin/env python3 """ tigersatgenerator/uniformksat/generator.py Generates k-SAT formulae. """ from typing import List import random def random_ksat_clauses(k: int, num_clauses: int, num_variables: int, seed: int = None) -> List[List[int]]: ''' Generates a list of lists which represent SAT clau...
82de1455f60d8a35b7cb52aae5799f973f6e3816
Nordenbox/Nordenbox_Python_Fundmental
/.history/sortAlgorithm_20201120222047.py
800
3.765625
4
import random import time def findMin(L): # find a minist element in a certain list min = L[0] # surppose the first element in the list is the minist element for i in L: # map every element of the list if i < min: # if some element is less than surpposed minist, it replace the minist ...
9573f6207433978dc8aa73d7f54606f6117c4d9b
Danang691/Euler.Py
/euler/solutions/euler35.py
1,507
3.5625
4
# -*- coding: utf-8 -*- from euler.baseeuler import BaseEuler from euler.sequences import PrimeRange from euler.util import is_prime class Euler(BaseEuler): def solve(self): # all primes less than 1M primes = list(PrimeRange(1, 1000000)) res = [] for prime in primes: ...
dcc6aa5ca326063a7b4ed9eb1c2b4f9f67229e86
nanjekyejoannah/ginter
/Cracking-the-coding-interview-solutions/Datastructures/chapter-3-stacks-and-queues/stack.py
301
3.65625
4
class Stack(object): def __init__(self): self.stack = [] def pop(self): self.stack.pop() def push(self, data): return self.stack.append(data) def peek(self): return self.stack[len(slef.stack)-1] def size(self): return len(self.stack) def is_empty(self): return self.stack == []
121062666fbd2e39ff7efe9dff2f5e3b9e0f4818
alexbenko/pythonPractice
/classes/ticTac.py
4,633
3.9375
4
class TicTacToe: player1 = '' player2 = '' currentPiece = '' row1 = ['','',''] row2 = ['','',''] row3 = ['','',''] moves = 0 def __init__(this): print('Tic Tac Toe Game Initialized...') this.render() def displayBoard(this): print('-----------Tic-Tac-Toe------------') print('\n') ...
fd5e24f97c7a979d2e96097f1ad4986a93a2a2b0
adamdevelops/Anagram
/q1.py
698
4
4
''' Question 1 Given two strings s and t, determine whether some anagram of t is a substring of s. For example: if s = "udacity" and t = "ad", then the function returns True. Your function definition should look like: question1(s, t) and return a boolean True or False. ''' # is_anagram() def ques1(s, t): str...
8d32fe3b441d9e2a7345822b5fec33e2ba5645ef
AlexGeorgeLain/SSD_CodeSnippets
/towers_of_hanoi.py
413
4.03125
4
"""A recursive solution for the Towers of Hanoi problem.""" def hanoi(n, A, C, B): if n == 1: print(f'{n} from {A} to {C}') else: hanoi(n-1, A, B, C) print(f'{n} from {A} to {C}') hanoi(n-1, B, C, A) # 2^n - 1 moves. # this solution allows that positions can be passed over. ...
2c1cac12783dddaf0534d0c5d8025c79e639be34
jkmeyer1010/DSC530_Course_Assignments
/Week_2/Exercise_2.1_Jake_Meyer.py
989
4.40625
4
# -*- coding: utf-8 -*- """ Author: Jake Meyer Assignment 2.1: Preparing for EDA Date: 03/25/2021 """ # Display the text “Hello World! # I wonder why that is always the default coding text to start with” print("Hello World! I wonder why that is always " "the default coding text to start with") # Add two number...
f324e01d5250fdc871fa16610dd6c823df5b0ef7
ShadowLore/hw_3
/ito.py
849
4.375
4
homework_list = ['Пропылесосить', 'Помыть полы', 'Погладить белье', 'Приготовить ужин', 'Повесить полку', 'Отдохнуть', 'Помочь с уроками'] # 0 1 2 3 4 5 6 print(homework_list[2]) print(homework_list[len(hom...
dcc20982f7141004b20e0d70c52a379d51decfb9
MiniWong101/rock-paper-scissors
/main.py
930
4.21875
4
print("Welcome to rock paper scissors games") import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ...
75c08ea66b0faa2cb49b766226d5cc169f6256e2
skjha1/Algo_Ds
/Sorting Algorithms/Python/bubblesort.py
255
4.03125
4
def bubble_sort(arr): changed = True while changed: changed = False for i in range(len(arr) - 1): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] changed = True return None
164c0a872d37c6cb55426f1fd75b432e735b590d
BCookies222/Python-Codes
/Ch11_ch1.py
5,557
4.125
4
"""Challenge 1: Increase the difficulty as the game progresses. +Increase the speed of the pizzas and chef. +Raise the pan to a higher level. +Increase the number of crazy chef's flinging pizzas.""" # Import the games and color module from livewires package for creating a game and allowing to choose from a set of ...
c3315098c4b84554bda9e88d7236a2f8621e5e6f
mepallabiroy/Hacktoberfest2020
/Algorithms/Python/Probability of item drop/items_drop_chance.py
2,206
4.1875
4
# This is a small script I've made for counting how many times you should fight # an enemy, in any RPG game, in order to get a specific drop. # If you enter the percentage of this specific item drop, this script will tell # you how many times you should fight this enemy or event, in order to be almost # sure you are g...
30fb71aca94fc814dd4deacfd51f439db978a04b
JuniorMSG/python_study
/Coding_Test/CodingTest/01_Level_01_for/Q_2438.py
614
4.09375
4
""" https://www.acmicpc.net/step/3 Subject : Coding Test For """ """ https://www.acmicpc.net/problem/2438 def Q_2438(): 첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제 입력 첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다. 출력 첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다. 예제 입력 1 5 예제 출력 1 * ...
8c18f4f0963e08ca10cdc416c4aa3901b5e2b43e
EuganeLebedev/Python_for_test
/lections/lesson7/my_files/lesson_7_decorator.py
354
3.828125
4
def square(number): return number ** 2 def cube(fn): def wrapper(number): result = fn(number) result = result + number return result return wrapper def square_2(number): return number**2 decorated_square = cube(square_2) @cube def square(number): return number**2...
3a16d67663722d4281518119f2606a18131dafe8
ArturAlvs/filomilitar
/code/classes/conhecimento.py
2,644
3.75
4
class Conhecimento(): def __init__(self, tipo_conhecimento, valor_inicial_conhecimento, n_ru): self.tipo_conhecimento = tipo_conhecimento # self.n_ru = n_ru # numero de filosofos ou militares self.lista_conhecimento = [valor_inicial_conhecimento] # valor inicial do conhecimento eh o valor inicial da lista, m...
e9ea1f7ac35a2886804f577291d0c070e7e127b5
garyblocks/leetcode
/round1/22_GenerateParentheses.py
777
3.5625
4
class Solution(object): def add(self,out,n,check,num,s,p,left,right): if p=='(': s+=p; check-=1; num+=1; left-=1 elif check<0: s+=p; check+=1; num+=1; right-=1 else: return None if num<2*n: if left>0: self.add(...