blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
def7dc7dc7df68acab39702c78cba860f8f1970e
adeelnasimsyed/Interview-Prep
/countTriplets.py
743
4.28125
4
''' In an array check how many triplets exist of a common ration R example: ratio: 4 [1,4,16,64] triplets: [1,4,16] and [4,16,64] returns 2 method: read array in reverse order have two dicts, one for each number and one for each pair that meet criteria if a num*ratio exists in dic that means we have a pair if n...
9a8ae8a9e977f11922c650ce9685723097051aaa
adeelnasimsyed/Interview-Prep
/reverseAdd.py
409
3.515625
4
def reverseAdd(arr): endZeroes = 0 temp = "" total = 0 for num in arr: endZeroes = 0 tempNum = num while(tempNum % 10 == 0): endZeroes += 1 tempNum /= 10 temp = str(num) temp = temp[::-1] temp = int(temp) while(endZeroes): temp *= 10 endZeroes -= 1 ...
4838d53732c26d615745909381f566c278577f3b
adeelnasimsyed/Interview-Prep
/freqQueries.py
1,391
3.640625
4
''' input queries in the format: q = [[1,2], [1,8], [2,2], [3,1]] where q[row][0]: 1: add q[row][1] to a data structure, or increase freq if already there 2: remove q[row][1] from data structure, or decrease freq if there 3: check if q[row][1] is present in data strcuture.values() ...
d77ceace5c510db775ecdb68209c6482138651af
tw-alexander/CodeHS-Intro_To_Computer_Science-Answers-Python
/CodeHs/1.Basic Python And Console Interaction/5.String Operators/3.5.6 Introduce Yourself Part 2.py
98
3.765625
4
name = "Nores" age = 16 print("Hi! My name is " + name + " and I am "+ str(age)+ " years old.")
c9fd1b394d8508e7e1f4da6db9917295a60b19fa
tw-alexander/CodeHS-Intro_To_Computer_Science-Answers-Python
/CodeHs/2.Conditionals/3. Comparision Operators/4.3.7 Postive Zero Negative.py
188
4.3125
4
Number=int(input("What is the number ")) if(Number==0): print("That number is zero!") elif(Number<0): print("That number is negative!") else: print("That number is positive!")
6493fdf256e4e130cc62dab87aa4218ac458b006
theopsbadger/advent-of-code
/2019/day3/day3.py
2,690
3.765625
4
#!/usr/bin/env python3 class Wire: def __init__(self): self.current = (0,0) self.points = {} self._counter = 0 def right(self, spaces): x, y = self.current for _ in range(spaces): x += 1 self._update((x,y)) def left(self, spaces): x...
c3bdcf67e887f1417b9143c4069c75afd0a07204
tris790/bloom-filter
/src/bloom_filter_test.py
636
3.78125
4
import bloom_filter print("---------------- Bloom filters test ----------------") print("Creating the bloom filter data structure") bf = bloom_filter.BloomFilter(8, 5) val1 = "Monkey" val2 = "Computer" print(f"Making sure that the word '{val1}' isn't in the bloom filter yet") print(f"'{val1}' exists? {bf.exists(val1...
37f4ac4962c3c369fe2f4fadf1e7f09287bd2d0f
magni2de/NeNeP
/Utils.py
1,941
3.5625
4
# -*- coding: utf-8 -*- __author__ = 'olegtroitskiy' import math def get_first(iterable): """ Функция помогает получить доступ к первому элементу объектов set() :param iterable: Любой объект, с которым работает itarable :return: Первый элемент """ try: return iter(iterable).next() ...
38b421a0609cdce13ea6f2be111a77bd87a00a87
Glooow1024/CourseCode
/uav-course/findPath/5chess.py
3,864
3.671875
4
'''from tkinter import * app = Tk() #通过event形参来获取对应事件描述 def callback(event): print("当前位置:",event.x,event.y) #创建框架,窗口尺寸 frame = Frame(app, width = 200, height = 200) #frame.bind("<Motion>",callback) frame.bind("<Button-1>",callback) frame.bind("<Button-2>",callback) frame.bind("<Button-3>",callback) frame.pack()...
4cc35d7e15a1e30016d16ef459f89e8380d7f8f8
shadow1666/Tkinter-Projects
/2_basics/basics3_frames.py
1,408
3.953125
4
#Frames import tkinter from tkinter import BOTH #Define window root = tkinter.Tk() root.title('Frame Basics!') root.iconbitmap('thinking.ico') root.geometry('500x500') #Example of why to use frames #name_label = tkinter.Label(root, text='Enter your name') #name_label.pack() #name_button = tkinter.Button(...
f5a335f5bd2534b84d14e075fb4671eff8815ad1
joeld3/Ball_balance_cv
/center_detect_algs.py
2,633
3.765625
4
""" center_detect.py: Contains different algorithms for finding a circle within an image.""" import cv2 import numpy as np def contour_center(img, show_img = False): """Uses color filtering to mask an image and then detects a contour within the image. Notes: This function assumes the image is filter...
801b996afe7610f29d26637fc9d1946e3cc0005c
Ashi-00/Basic-Python-based-Games
/highLow.py
868
4.0625
4
#GAME TIME -->> HIGH LOW import random def guess(x): hidden=random.randint(1,x) n=0 #intialising with a number thats out of the ranges so that the loop can begin since loop welcomes a number!=hidden while (n != hidden): n=int(input(f"Enter a number between 1 and {x} = ")) if hi...
6684a93cb4a99eb0cc8760681c0db8113be0bd31
SamwelOpiyo/Coding_Challenges
/sum.py
250
4.03125
4
def sum_string(): number=raw_input("Input a string of numbers separated by spaces eg 1 2 3 4 5:") number_list=number.split() numbers=[] for r in number_list: numbers.append(int(r)) return sum(numbers) print sum_string()
19fd1bcd0bfe48d896af72d75b73957b792757df
SamwelOpiyo/Coding_Challenges
/product_without_item_at_i.py
613
3.984375
4
""" Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected...
c52a9c034a64bc4535e60e3becd4d3b9ea583f26
antonln/programming-challenges
/prime_factorization.py
953
4.09375
4
def prime_factors(n): """ Find all prime factors of inputted number. """ all_primes = [2] p_factors = [] for j in range(2,n+1): k = 0 for prime in all_primes: if j % prime == 0: k += 1 if k == 0: all_primes.append(...
8c9c3a867e9a3d81b0b30ac5ca8f3259d84cf899
miaomc/homingmissile
/tmp/plane_ABSTRACT2.py
2,575
3.5625
4
# -*- coding: cp936 -*- class Plane(pygame.sprite.Sprite): def __init__(self,VELOCITY=100): self.velocity = VELOCITY # 㶨 self.accelerate = [0,0] # ûмٶָбʱ򣬼ٶĬΪ0 pass def update(self, trace): self.accelerate = self.pop_first() self.velocity += self.accelerate sel...
79ff9476ded6d3eb48bb8a98389a16c84b163510
1131057908/-1
/函数.py
2,624
4.125
4
""" 座右铭:将来的你一定会感激现在拼命的自己 @project:7-23 @author:Mr.Zhang @file:函数.PY @ide:PyCharm @time:2018-07-23 09:05:17 """ #函数:为什么使用函数?因为没有函数的编程只是在单纯的写代码逻辑,如果想重用代码逻辑,只能够copy一份代码。但是一旦使用函数,就可以将一些相同的代码逻辑封装起来,这样可以提高代码的重复使用率,提升开发效率。 #第一步:声明一个函数,在函数里面写逻辑代码 #第二步:调用函数,执行编写的逻辑代码 # print('今天是周一') # print('明天是周二') # print('后...
80f9786198ceea177986e170f042175c95e9bf55
matcha-cuyitos-brigade/cpu-simulator
/source/Components/ALU.py
2,850
3.8125
4
from Components.IntegratedCircuit import * class ALU(IntegratedCircuit): def __init__(self): self._input_a = 0 self._input_b = 0 self._opcode = 0 self._output = 0 self._flag_overflow = 0 self._flag_zero = 0 self._flag_negative = 0 IntegratedCircuit....
778d76b42567ba6862fcef3c4822dc6ad82e78d5
Zenfeuer/courses
/Coursera/DSAS/AT/largest_number_digits.py
1,060
3.96875
4
#!/bin/python3 # @author: Darwing Hernandez <darwinghga@gmail.com> # Maximazing Number using Digits # # Input: import random # Read the input n = int(input()) digits = [int(x) for x in input().split()] digits = sorted(digits, reverse = True) def largestNumber(digits): bigNumber = "" for digit in di...
8199541dea518ab2c4fe161372b9067652a46ad7
Zenfeuer/courses
/Coursera/DSAS/AT/pairwise_distinct_summands.py
1,649
3.8125
4
#!/bin/python3 # @author: Darwing Hernandez <darwinghga@gmail.com> # Pairwise Distinct Summand # # Represent a given positive integer number n as a sum of as many pairwise distinct positive integer # as possible. # # n = a1 + a2 + ... + ak; ai > 0; ai != aj for all 1 <= i <= k # # Input: integer n, 1 <= n <= 10^9...
7bfbcbdad20f63a543615279d2ed0b090a6d288c
liangshinegood/lg-Python
/hackrank/company_logo.py
461
3.765625
4
# 本质上也是根据条件进行筛选 # 统计每一个字母出现的次数,并排序 # 选择排名前三位的字符 # 如果出现相同则根据字母排序进行,最后输出 from collections import Counter,OrderedDict # 从新继承Counter,OrderedDict,Counter 计数,OrderedDict 排序 # .most_common(3) 为前3个值 class OrderedCounter(Counter,OrderedDict): pass [print(*c) for c in OrderedCounter(sorted(input())).most_common(3)]
6800434f4cbe23a81f6d023acc6559f4ce1821df
liangshinegood/lg-Python
/the_hard_way/Nested_Lists.py
626
3.703125
4
listPhysics = [] for _ in range(int(input("请输入学生的个数:"))): nameScore = [] name = input("请输入学生的姓名:") score = float(input("请输入学生的分数:")) nameScore.append(name) nameScore.append(score) listPhysics.append(nameScore) listScore = [] for a in listPhysics: listScore.append(a[1]) setScore = set(listSco...
5451782ca02c2d354e77432d95ffb82a01e19fc8
liangshinegood/lg-Python
/the_hard_way/9_9loop.py
527
3.90625
4
# 错误1,用列的方式来思考是错误的 # for j in range(1,10): # for i in range(1,10): # if (i >= j): # print(i,"*",j,"=",i*j) # 1. 横向看计算机的输出方式;2.如何打印出2*1,2*2的方式 表达;3.i的值决定了j的循环方式;4.i打印完就会换行;5.同时解决print 换行问题 for i in range(1,10): for j in range(1,i+1): print(i,"*",j,"=",i*j,end='\t') print('\r') #...
08fe3bc66acd6a2662498e5a8636bffe34e0404a
liangshinegood/lg-Python
/hackrank/arrays.py
121
3.765625
4
# ˼·numpy.arrayforѭȻת def arrays(arr): return(numpy.array(arr[::-1],float))
8376a7262ccfb6f4b474fbdf7af98b13a9366dc8
liangshinegood/lg-Python
/the_hard_way/string_use_function.py
5,786
4.15625
4
number = "-290" number1 = " abc aefg" number2 = 'abc' number3 = '123' print('zfill的使用:',number.zfill(8)) print('index方法的使用:',number.index('2')) print('find方法使用:',number.find('9')) print('find方法使用:',number.find('+')) print('rfind方法使用:',number.rfind('9')) print('rindex方法使用:',number.rindex('9')) print('rsplit方法使用:',num...
33ff41536705b89a97c4b485e13a51071f663c7a
liangshinegood/lg-Python
/hackrank/gsd02.py
696
3.828125
4
class Email: username = 'zhangsan' password = None def __init__(self): self.myname = 'lisi' def setusername(self,value): self.myname = value def getusername(self): # print(self.username)#不可以打印出username result = self.myname[0] + '*' + self.myname[1] return res...
c37972d105df2a8f9d4f3b9d234a1554ecf7af75
liangshinegood/lg-Python
/hackrank/gsd_attr.py
899
3.9375
4
class Human: age = 18 name = 'zhangsan' def run(self): print("lallalallal") def __getattr__(self,attrname): print(attrname) if attrname == 'height': print("this is getattr") return 120 else: return 110 pass def __...
294c5d4ca00acef2c2a6cdb5444d9f3ba489f83a
congminh1406/DesignPatternTrain
/StrategyPattern.py
1,017
3.671875
4
from abc import ABCMeta, abstractmethod class Duck(metaclass=ABCMeta): flyBehavior = None quackBehavior = None @abstractmethod def display(self): pass def perform_fly(self): self.flyBehavior.fly() def perform_quack(self): self.quackBehavior.quack() def set_fly_b...
ece02450c97d4da0db9391f9d019728a8ea708b0
sasokan5197/ML_Algorithims
/Part 2 - Regression/Section 9 - Random Forest Regression/Random_Forest_Regression/Random_Forest_Trees_practice
1,777
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 18 14:05:27 2020 @author: sahanaasokan """ #Ensemble Forest Intuition # Pick a random k data points from the training set # we are picking a decision tree based on a subset #Decision Tree regression splits based on all the data points # Forest spl...
09924299f90040c6cbc076204c1c9afd6d0d9866
Fangqihan/pythonfull_stack_exercises
/3.2、开发一个支持多用户在线的FTP程序/db/alex/doc/2.1、员工信息增删改查/v2/simulate_mysql.py
2,415
3.578125
4
""" 增加: add staff_table Alex Li,25,134435344,IT,2015‐10‐29 步骤: 1、分析query语句:将数据处理成特定格式; 2、加载文件数据转换成特定格式; 3、判断记录唯一性,并写入文件; 4、返回受影响行数。 删除: del from staff where id=3 步骤: 1、分析query语句:解析出key、value、operator; 2、加载文件数据转换成特定格式; 3、根据分析结果并根据条件进行处理,并写入文件; 4、返回...
c0266c634d344d80568401efc1506dea4e4a22a5
ericgreveson/projecteuler
/p_030_039/problem32.py
688
3.875
4
import math from digit_tools import num_digits, test_pandigital_9 def main(): """ Entry point """ # Brute force: try all products to 10000x1000, skipping those when the digit total is too high products = set() for a in range(1, 1000): for b in range(a+1, 10000): # Stop ...
c38d9712748df645991a786b90673a8a8e641a8d
ericgreveson/projecteuler
/problem76.py
1,638
3.984375
4
def count_ways(target, max_integer=None, cache=None): """ Count the number of ways of making target from sum of at least 1 integers with max_integer as the largest integer in the sum. If max_integer is not provided, count all possible ways from sum of at least 2 integers. """ # Special cases: be...
4f05d7f3571834cdda9108c00a4a7821294d07d2
ericgreveson/projecteuler
/problem75.py
1,978
4
4
from math import gcd def get_primitive_pythagorean_triples(max_length): """ Get Pythagorean triples up to a+b+c <= max_length """ # Use Euclid's formula: choose coprime numbers m, n with m > n > 0, m, n not both odd # Then a = m^2 - n^2, b = 2*m*n, c = m^2 + n^2 triples = [] n = 1 while...
600e81e81fa1422ee04e73e97bf56f0913207a8d
ericgreveson/projecteuler
/p_050_059/problem50.py
1,397
3.546875
4
from factor_tools import get_primes def main(): """ Entry point """ print("Get primes below one million...") primes = get_primes(1000000) prime_set = set(primes) # Now get the n-consecutive sums for each n-length starting from 6 longest = None for n in range(6, len(primes)): ...
2d1e425c878658733f1d32f2e5edcdbcc39e47fd
ericgreveson/projecteuler
/p_020_029/problem23.py
888
4.1875
4
from factor_tools import compute_factors def main(): """ Entry point """ # Compute set of all abundant numbers up to the limit we know all integers above can be # expressed as a sum of two abundant numbers sum_abundant_limit = 28123 abundant = {i for i in range(1, sum_abundant_limit) if sum...
1395b4459d1a03c952e5b877acf64ba01c4c6322
isakura313/second_prohect_free_it
/rozigrish.py
309
3.8125
4
import random spisok = ['bmw', 'audi', 'jigul', "suzuki"] while True: print("Примите участие в розыгрыше") flag = input("y/n - y чтобы принять, n - отказаться:\n") if flag == "n": break if flag == "y": print(random.choice(spisok))
df60ed989510ef40d71937cfc7249001f04ad903
hwjfurther/hm_-
/hm_01_引用.py
600
3.515625
4
def test(num): print("在函数内部%d对应的地址为%d"%(num,id(num))) #定义一个字符串变量 result = "hello" print("函数要返回数据的内存地址%d"%id(result)) #将字符串变量返回,返回的是数据的引用,而不是数据本身 return result #pass #定义一个数字变量 a = 10 #数据的地址本质上就是一个数字 print("a变量保存数据的内存地址是%d"%id(a)) #调用test函数,本质上传递的实参是传递数据的引用,而不是数据本身 r = test(a) #test(a) pri...
aa0b2a13162c6799a183535aec68552208bc9480
noungajo/resilient_DSGD
/network.py
1,580
3.65625
4
import numpy as np class Network: def __init__(self): self.layers = [] self.loss = None self.loss_prime = None self.espion = None self.back =None #add layer to network def add(self, layer): self.layers.append(layer) #set loss to use def use(self, loss, loss_prime): self....
97bbb9cf6502b3d419f4add764ec9a7f536259e3
SerikDanaaa/Python_
/midterms/Midterm 2/g.py
121
3.640625
4
import re txt = input() t = input() s = input() f = input() txt1 = txt.replace(t,s) x = re.findall(f,txt1) print(len(x))
47b914e2d62258813328c0970baa645bbf2c76ad
SerikDanaaa/Python_
/midterms/Midterm 2/h.py
402
3.65625
4
n = int(input()) inlist = list(map(str,input().split())) m = int(input()) group = list(map(str,input().split())) mis = list() notin = list() for i in inlist: if i not in group: mis.append(i) for i in group: if i not in inlist: notin.append(i) print("Missed students:") for i in mis: print...
0f75afda37f443f4879b19719adb83b56f8fc4f0
SerikDanaaa/Python_
/TSIS4/Task 2/phone.py
197
3.625
4
import re n = int(input()) while n: txt = input() pattern = r'^[7-9]\d{9}\b' ans = re.search(pattern,txt) if ans: print("YES") else: print("NO") n -= 1
df196a9207e99d3154d91deca5899eaa2ca4c55b
SerikDanaaa/Python_
/midterms/Midterm 1/g.py
351
3.5625
4
n, words, ans = int(input()), [], [] for i in range(n): words.append(input()) for char in words[0]: ok = True for i in range(n): if words[i].find(char) == -1: ok = False break if ok == True: ans.append(char) if len(ans) != 0: print(*sorted(set(ans))) else: ...
333b29ded05dc3bb8281291d87077768dc71ea8a
ychnlgy/Chebyshev-Lagrange
/src/modules/CosineSimilarity.py
1,692
3.59375
4
''' Note: The PyTorch CosineSimilarity operation requires that the input and target be of the same size. This may be computationally expensive if we wish to compare inputs to targets of unit size, since we will have to repeat the target to the size of the input in order to use the PyTorch implement...
de1c37645d58898828ec4d4b1ec85588065cf75e
The-Kernel-Panic/HackerRank-Solutions
/Algorithms/Day of the Programmer.py
1,241
4.375
4
#Practice > Algorithms > Implementation > Day of the Programmer #Julian -> after 1918 (leap year is divisible by 4) #Gregorian -> from 1919 #During 1918 feb starts from 14. #Jan + Mar + April + May + June + July + Aug = 215 def dayOfProgrammer(year): if year < 1917: if year % 4 == 0: #Leap Year ...
89f50e615348321f0e455c6e829326a44e46ec04
artin-hackers/entry-test-python
/sum.py
427
3.984375
4
print("Yo, cholo! Gimme numba: ", end="") while True: number = input() try: if int(number) > 0: the_sum = 0 for i in range(1, int(number)+1): the_sum += i print("Da sum is %d, mon." % the_sum) break else: print("No negat...
cddf29c0c486d0fc078be0ed3e0b2b9b897a14e8
Voland2578/descrete_opt_knapsack
/utils.py
4,140
3.703125
4
import sys # return the index and the value # of the maximum number < value passed in # if nothing is found, return -1 def searchMinNumber(l, val): start_idx, end_idx = 0, len(l) - 1 curr_idx, curr_val = -1, -1 while True: # check for the end of the list if val > l[end_idx]: ret...
742f70020cc36513b1f7216c776ad702bfee2875
gavinmcguigan/gav_euler_challenge_100
/Problem_65/ConvergentsOfe.py
1,660
3.734375
4
from globs import * from math import e """ Hence the sequence of the first ten convergents for 2–√ are: 1,3/2,7/5,17/12,41/29,99/70,239/169,577/408,1393/985,3363/2378,... What is most surprising is that the important mathematical constant, e=[2;1,2,1,1,4,1,1,6,1,...,1,2k,1,...]. The first ten...
9d52cfb887e1a6e98ab7b5d151311bf11038029f
gavinmcguigan/gav_euler_challenge_100
/Problem_56/PowerfulDigitSum.py
920
4.03125
4
from globs import * """ A googol (10**100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, ab, where a, b < 100, wha...
63355b1480d43c45707af4d27ada2ab208e883dd
gavinmcguigan/gav_euler_challenge_100
/Problem_30/DigitFifthPowers.py
830
4
4
from globs import * """ Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1**4 + 6**4 + 3**4 + 4**4 8208 = 8**4 + 2**4 + 0**4 + 8**4 9474 = 9**4 + 4**4 + 7**4 + 4**4 As 1 = 1**4 is not a sum it is not included. The sum of the...
408ff33b2cf19a5daf9944fd87b7ca7445529f31
gavinmcguigan/gav_euler_challenge_100
/Problem_68/magic_5gon_ring.py
3,295
3.796875
4
from globs import * """ Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), each solution can be described uniquely. For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3. It is possible to complete the...
aa40cd418fbcf7475c8c1d80989136029ba887e6
gavinmcguigan/gav_euler_challenge_100
/Problem_22/NamesScores.py
1,390
4.03125
4
"""" Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted ...
226c50533b37b929e298301d18b43b2ac2624ca5
gavinmcguigan/gav_euler_challenge_100
/Problem_53/CombinatoricSelections.py
1,117
3.75
4
from globs import * """ There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 In combinatorics, we use the notation, (5/3)=10. In general, (nr)=n!r!(n−r)!, where r≤n, n!=n×(n−1)×...×3×2×1, and 0!=1. It is not until n=23,...
159cdae23d6e3e19c73eb74eb39bdc8e42554574
gavinmcguigan/gav_euler_challenge_100
/Problem_59/XOR_Decryption.py
2,417
4.1875
4
from globs import * """ Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text file, convert the ...
769836cb18a5f7bd6851f28792daebd0f561d5fb
aldzor/School-python-projects
/calculator.py
1,397
4.15625
4
# An even better calculator import math def asking(): loop = True while loop == True: givenNum = input("Give a number:") try: givenNum = int(givenNum) return givenNum loop = False except Exception: print("This input is invalid.") def operation(): loop = True while loop == True: operation = in...
68eb5ccf6669f3159bb6e4718d0295cb85c62acb
vivianakinyi/pep8
/comparison.py
669
3.53125
4
"""Comparison to singletons should use "is" or "is not". Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators. Okay: if arg is not None: E711: if arg != None: E711: if None == arg: E712: if arg == True: E712: if False == arg: Also, beware of writing if x ...
aef2289b8d1e3b58f924fa4ae1325186865ac404
AlejandroParra10/hangmangame
/hangmanpro.py
602
3.65625
4
# Alejandro Parra # Period 6 # 10/21/2019 # These are just notes # Optionals (at least 2 must be done along with all of the above to get an A) # Show an ASCII art picture representing the “hangman” # Choose the mystery word at random from a list # Allow the user to choose the number of misses it takes to lose ...
c4d2f88ede5a3b373ce8e6912c70c71d9de7d863
Jeffreyo3/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,277
4.15625
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) # create a list with lenght # equal to total incoming elemnts merged_arr = [0] * elements a_idx = 0 # keep track of current arrA index b_idx = 0 # keep track of current a...
0cef0ba9f285f5b47d7a7b9e4698093476f9cf02
plokamar1/pythonMicroParsers
/passGenerator.py
2,703
3.765625
4
from sys import argv import random from random import randint import codecs import string sCharsFlag = False def standartChars( repeats, sCharsFlag): chars = "!@#$^&*()_+}{|[]:'\/\"?><,." passesL = [] passStr = [] i = 0 while i < repeats:#we use this one to emulate the repeats for every line ...
83eccb3bd371aa3f7ad7deba24e010705e12a46a
cadumas01/CSCI2243
/homework00/prime_factorization.py
649
4.09375
4
import math def is_prime(n): if n < 2: return False for i in range(2, int(math.sqrt(n) + 1)): if n % i == 0: return False return True def prime_factorization(n): factors = [] if n < 2: return [] while not is_prime(n): i = 2 while i < int(ma...
316713fab27ecc337237085069bcf54f343f792e
GaryKellyIT/ImageProcessing
/Week3/Project.py
2,152
3.515625
4
import numpy as np import cv2 from matplotlib import pyplot as plt import easygui #change to user picked image I = cv2.imread("../input/GreenLight.jpg") output = I.copy() gray_image = cv2.cvtColor(I,cv2.COLOR_BGR2GRAY) # Blur using 3 * 3 kernel. gray_blurred = cv2.blur(gray_image, (3, 3)) cv2.imshow("gray_blur...
5ae7ea2798c46c25ac0e6301bcabc3141cf2beea
nx6110a5100/Internshala-Python-Training
/prime_check.py
187
4.25
4
num=int(input("Enter the number:")) for x in range(2,num): if num%x==0: print("{} is not prime".format(num)) break else: print("{} is prime".format(num))
3ee2de79f4d44091b41ff3bed79e3d118feb16b2
nx6110a5100/Internshala-Python-Training
/fetchall.py
217
3.5
4
import sqlite3 MySchool=sqlite3.connect('schooltest.db') sql="SELECT * from student;" curschool=MySchool.cursor() curschool.execute(sql) result=curschool.fetchall() for record in result: print (record)
d419165170842721430371d9e293b0658d965a35
nx6110a5100/Internshala-Python-Training
/fn_with_return_type.py
363
3.875
4
def food(f): tip=0.1*f total=f+tip per_person=total/num return per_person def movie(m): return m/num num=int(input("Enter the no of persons:")) total_food=int(input("Enter amonut spend on food:")) total_movie=int(input("Entet the amount spend on movie:")) x=food(total_food) y=movie(total_movie) prin...
9136d269ad920365c747a0fefcf3ad8e238e20c6
nx6110a5100/Internshala-Python-Training
/while.py
235
4.125
4
day=0 sq=0 total=0 print('Enter number of quats each day') while day<=6: day=day+1 sq=int(input('Enter the number of quats on {} day '.format(day))) total+=sq avg=total/day print('Average sqats is {} per day'.format(avg))
2ee3b49fc6085f2a2d74ce4c970e5c39cc4eaa89
Mape-ht/AlgoTD-TD2
/Programme_Python/exo14.py
696
3.8125
4
# programme anneeBissextile ''' Faire un programme qui saisit une date (jour, mois et année) et qui indique si l’année est bissextile ''' #saisir l'année, si elles est multiple de 400 alors bissextile an = int(input("Saisir une année")) print (an) if (an > 1582) : if (an % 4 == 0) : #si elle est divisible par ...
8426ce1a43b76042c1293c37e93ce74763ad2cde
Mape-ht/AlgoTD-TD2
/Programme_Python/exo25.py
671
3.875
4
#Programme suiteNombre ''' ==========================Sujet========================== Faire un programme qui saisit une suite de nombre et qui dit les si les nombres saisis sont dans l’ordre croissant ou décroissant ou quelconque ========================================================= ''' #saisir des nombres rangé dan...
0939fd2ac434bbc8498804c3a866310046168e40
magsandve/fotballnavn
/kode2.py
174
3.5625
4
qiz = "skriv et land" print (qiz) land=input() if land=="Norge": print ("oslo") elif land=="sverige": print ("stockholm") else: print ("Du kan ikke hovedstaden")
3c60f04722d4a8dafce045bfc47982a179fc6445
paohuz/TempProj
/ForexRL/test/design_pattern/test_singleton.py
503
3.734375
4
class Singleton: instance = None @classmethod def Instance(cls): if cls.instance == None: cls.instance = Singleton() return cls.instance def __init__(self): if self.instance != None: raise ValueError('A Singleton instance is already existing') def s...
bfd58a191c030136732f08e61ab49a124178fdbd
roblivesinottawa/problem_solving
/weektwo/format_name.py
754
4.5
4
"""Question 6 Complete the body of the format_name function. This function receives the first_name and last_name parameters and then returns a properly formatted string""" def format_name(first_name, last_name): # code goes here string = '' if first_name!= '' and last_name != '': return f"Name: {last_name}, {...
89ea598b8aa32d54d9dfa1fd76151b55a2a5d718
roblivesinottawa/problem_solving
/weektwo/tip.py
173
3.609375
4
def calculate_tip(bill, tip): return (bill + tip ) / 2 bill = 47.28 tip = bill * 0.15 share = calculate_tip(bill, tip) print(f"each person needs to pay {str(share)}")
519141822d77e1cc19c19e2261c942a6fc95c94b
roblivesinottawa/problem_solving
/weektwo/fractional_part.py
938
4.375
4
""" Question 10 The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1). Complete the body of the function so that it returns the right number. Note: Since division by 0 produces an error, if the denominator is 0, the function should retu...
faf34385f2a7c0186d0484138653a0875e7f1933
roblivesinottawa/problem_solving
/weektwo/triangle.py
163
3.703125
4
def triangle_area(base=5, height=3): return base * height / 2 area_a = triangle_area(5,4) area_b = triangle_area(7,3) sum_ = area_a + area_b print(str(sum_))
09bf65e210a5275d244546818f73edc903a0a673
Anura52/compoundinterestcalc
/CompoundInterestCalc.py
2,905
3.578125
4
initialCapital = int(input("How much capital do you have? (in USD)\n> ")) timeModifierFloat = 24.0 timeModifierInt = int(timeModifierFloat) dailyInterest = float(input("What daily returns do you expect? (%)\n> ")) interestRate = (dailyInterest/100)/timeModifierFloat idealAmtOfComps = 4 intervalForOptimum = ...
f5bcf5c69a5d4dfd80463b8d2b66f46fa1551404
affectalways/Data-Structures-and-Algorithms
/tree/heap.py
6,717
4.1875
4
# -*- coding: utf-8 -*- # @Time : 2018/4/16 16:12 # @Author : affectalways # @Site : # @Contact : affectalways@gmail.com # @File : heap.py # @Software: PyCharm # 堆,该代码创建最小堆 # 用 是一种特殊的完全二叉树 class Heap(object): def __init__(self): pass # 创建堆, 这个方法要在完全二叉树 广度优先遍历后 才能使用 def create_heap(self,...
42155f3022b586c91539306294eba8f7a8c8e109
vikaskharkwal/Terminal-Tac-Toe
/game/vs2player.py
3,098
3.734375
4
import valuecheck import playagain def game(player1, player2): grid = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "],] valid_moves = [1, 2, 3, 4, 5, 6, 7 ,8, 9] print("\nGrid (for reference):\n 1 | 2 | 3\n-----------------\n 4 | 5 | 6\n-----------------\n 7 | 8 | 9\n") while True: w...
78279ce8c48f746121c66a5297a044dee410ef9c
NicholasBreazeale/NB-springboard-projects
/python-syntax/words.py
288
4.1875
4
def print_upper_words(wordList, must_start_with): """Print out a list of words if they start with a specific letter, each on separate lines, and all uppercase""" for word in wordList: for letter in must_start_with: if word[0] == letter[0]: print(word.upper()) break
ca148c1d083dcd7bbfbf3511d00bdde76509eab7
alfabr90/dtqw
/dtqw/utils/logger.py
2,486
3.8125
4
import logging __all__ = ['Logger'] class Logger: """Generate a log file and write log data into it.""" def __init__(self, name, path, level=logging.DEBUG): """ Build a logger object. Parameters ---------- name : str The name of the class that is providin...
e6983d219c813d704f70443bfc23ee3c72e8fca2
MSBeni/DesignPaterns_py
/1-python_essentials/9_decorative_class.py
746
3.625
4
class Dec: def __init__(self, a, b): self.a = a self.b = b def __call__(self, *args, **kwargs): return "The values are {}, {}, and {}".format(self.a, self.b, args) obj = Dec(10, 20) print(obj(5)) #######################################################################################...
1545a8a64e9014e3162382b034cf38c5181932ae
yucheno8/news_python
/LiaoSirWeb/do_pickling.py
423
3.796875
4
#尝试把一个对象序列化写入文件 import pickle d = dict(name = 'Bob', age = 20, score = 88) #pickle.dumps()方法把任意对象序列化成一个bytes,然后,就可以把这个bytes写入文件。 s = pickle.dumps(d) print(s) #或者用另一个方法pickle.dump()直接把对象序列化后写入一个file-like Object: f = open('dump.txt','wb') pickle.dump(d,f) f.close() re = f.readline() print(re)
61030e3224d56d81a599d9dfa33f55914e982299
INFO3401/problem-set-12-lubo4991
/nbaML.py
2,479
3.65625
4
#Lucas Bouchard #Problem Set 12 import pandas as pd import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.cluster import KMeans #PROBLEM 1: Classify a player's position using k-NN and the provided classification data. def loadD...
0cb399a6d2714bf71bf0838a6934dc9572d4bed7
gcostaa/Estudos
/Python/OO/OO1/conta.py
1,929
3.75
4
class Conta: #definir metodo construtor def __init__(self, numero, titular, saldo, limite): #self -> referencia em memoria a propria clase, seria como se fosse o this print("Construiindo objeto....{}".format(self)) #__ dois undrline é igaul a private self.__numero = numero ...
489ea654064e270a307b8ae1b247bee26056df00
yedhink/pyquiz
/pyquiz/welcome.py
2,652
3.875
4
from colors import bcolors def give_tips(student): welcome = "Hi {}. See if you can crack this quiz.".format( student.name) print(''' ||{:=<93}|| ||\t{:^89}|| ||\t{:<89}|| ||\t{:<89}|| ||\t{:<89}|| ||\t{:<89}|| ||\t{:<89}|| ...
7afe56ea1fd531da0c721a6dfa6d552b5ba4dbde
seanjohnite/PTENpred
/predict/output_scores.py
10,119
3.625
4
""" Score outputter. Stores scores in a list of dictionaries with these keys: 'category', 'codon', 'wtres', 'mutres', 'numCancerMuts', 'avgSampleMutCount', 'mutMAPPscore', 'wtMAPPscore', 'pph2_prob', 'pph2_FPR', 'pph2_TPR', 'pph2_FDR', 'pph2_dScore', 'SuspectScore...
74b92ec02440aa5980ea1dff14115ce3603d60fc
mimikrija/ProjectEuler.py
/01.py
616
4.34375
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def is_multiple_of_any(num, divisors): "returns if `num` is divisible by any of the `divisors`" return any(num % diviso...
9628ac93ce37e5daa926a5ded58885d7360566a7
wisesky/LeetCode-Practice
/src/107. Binary Tree Level Order Traversal II.py
1,026
3.8125
4
from typing import List # 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]: res = [] self.h...
f1751dca7aab07b38374b9173587166b41cdcf6e
wisesky/LeetCode-Practice
/src/150. Evaluate Reverse Polish Notation.py
1,439
3.609375
4
from typing import List class Solution: def evalRPN(self, tokens: List[str]) -> int: length = len(tokens) if length == 0: return 0 if length == 1: return tokens[0] operations = ['+','-','*', '/'] nums = [] for token in tokens: if to...
8aac741feb4fe862a15147e4d8e3d504cacf2d1c
wisesky/LeetCode-Practice
/src/127. Word Ladder.py
989
3.59375
4
from typing import List import heapq import string from collections import deque class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: q = deque() q.append((1,beginWord)) wordList_set = set(wordList) - set([beginWord]) if endWord not in wo...
5a6ce78cc15bd98e1df2fb7098ebe5b72563f2f9
wisesky/LeetCode-Practice
/src/345.reverse-vowels-of-a-string.py
1,521
3.84375
4
# # @lc app=leetcode id=345 lang=python3 # # [345] Reverse Vowels of a String # # https://leetcode.com/problems/reverse-vowels-of-a-string/description/ # # algorithms # Easy (46.07%) # Likes: 1271 # Dislikes: 1640 # Total Accepted: 311K # Total Submissions: 673.3K # Testcase Example: '"hello"' # # Given a string...
433a5906f6ce17539b9a8eb6ac1be4d638ca84ab
wisesky/LeetCode-Practice
/hw-oj/hw-hj28-learned.py
924
3.578125
4
# 二分图最大匹配 # 匈牙利算法 def issu(x): tem = 2 while tem**2<=x: if x%tem==0: return False tem+=1 return True def find(a,used,match,even): for i in range(0,len(even)): if issu(a+even[i]) and used[i]==0: used[i]=1 if match[i]==0 or find(match[i],used,ma...
627f34981b3d3426f3b33cf8bf1dd37187b453d8
wisesky/LeetCode-Practice
/src/74. Search a 2D Matrix.py
1,164
3.953125
4
from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: l1 = len(matrix) if l1 == 0: return False l2 = len(matrix[0]) if l2 == 0: return False # flag = False for i in range(l1): ...
02508c66a29f6609c7cc83fa29740a247d844d6c
wisesky/LeetCode-Practice
/src/229.majority-element-ii.py
1,471
3.640625
4
# # @lc app=leetcode id=229 lang=python3 # # [229] Majority Element II # # https://leetcode.com/problems/majority-element-ii/description/ # # algorithms # Medium (39.68%) # Likes: 3011 # Dislikes: 229 # Total Accepted: 215.3K # Total Submissions: 542.5K # Testcase Example: '[3,2,3]' # # Given an integer array of...
ac7bc6fc6f1c126e8dc60f06d90410645a61a41e
wisesky/LeetCode-Practice
/src/27. Remove Element.py
639
3.59375
4
class Solution: # def removeElement(self, nums: List[int], val: int) -> int: def removeElement(self, nums, val) : if len(nums) == 0: return 0 # for _ in range(len(nums)): # num = nums.pop() # if num == val: # continue # nums.insert...
f39663c4adbdb87ef091083cd4181a1be6cf27b2
wisesky/LeetCode-Practice
/src/204.count-primes.py
1,206
3.53125
4
# # @lc app=leetcode id=204 lang=python3 # # [204] Count Primes # # https://leetcode.com/problems/count-primes/description/ # # algorithms # Easy (32.80%) # Likes: 3356 # Dislikes: 820 # Total Accepted: 502K # Total Submissions: 1.5M # Testcase Example: '10' # # Count the number of prime numbers less than a non-...
747b75bb7da863914fe257a467dd983badb60899
wisesky/LeetCode-Practice
/src/148. Sort List.py
4,831
4.125
4
# Definition for singly-linked list. from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: if head == None or head.next == None: return head # cal...
ffb0646e464eb01f8759ff6adc2cbd3111527608
wisesky/LeetCode-Practice
/src/215.kth-largest-element-in-an-array.py
906
3.671875
4
# # @lc app=leetcode id=215 lang=python3 # # [215] Kth Largest Element in an Array # # https://leetcode.com/problems/kth-largest-element-in-an-array/description/ # # algorithms # Medium (59.69%) # Likes: 6114 # Dislikes: 378 # Total Accepted: 944.8K # Total Submissions: 1.6M # Testcase Example: '[3,2,1,5,6,4]\n2...
1b77fe056340d4361686e9ad1a45bf576492f71f
wisesky/LeetCode-Practice
/src/273.integer-to-english-words.py
3,864
3.5625
4
# # @lc app=leetcode id=273 lang=python3 # # [273] Integer to English Words # # https://leetcode.com/problems/integer-to-english-words/description/ # # algorithms # Hard (28.66%) # Likes: 1623 # Dislikes: 3983 # Total Accepted: 251.9K # Total Submissions: 876K # Testcase Example: '123' # # Convert a non-negative...
aa78da28f1847d84f7ab36017da14bd474522e6a
wisesky/LeetCode-Practice
/src/263.ugly-number.py
1,831
3.890625
4
# # @lc app=leetcode id=263 lang=python3 # # [263] Ugly Number # # https://leetcode.com/problems/ugly-number/description/ # # algorithms # Easy (41.67%) # Likes: 900 # Dislikes: 867 # Total Accepted: 252.3K # Total Submissions: 605.2K # Testcase Example: '6' # # An ugly number is a positive integer whose prime f...
47734f1982d6ad94cd0c7e6b16cdf466d973c17d
wisesky/LeetCode-Practice
/src/101. Symmetric Tree.py
1,203
3.921875
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 isSymmetric(self, root: TreeNode) -> bool: if root == None: return True return self.h...
8caa60fb9f3b6c6220988ff55c3d02743b34704d
wisesky/LeetCode-Practice
/src/75. Sort Colors.py
1,030
3.890625
4
from typing import List class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ self.quick3Way(nums, 0, len(nums)-1) def quick3Way(self, nums, lo, hi): if lo >= hi: return ...
d8b821320dd09a734fbac25fa185c1797b447185
wisesky/LeetCode-Practice
/src/367.valid-perfect-square.py
1,366
3.6875
4
# # @lc app=leetcode id=367 lang=python3 # # [367] Valid Perfect Square # # https://leetcode.com/problems/valid-perfect-square/description/ # # algorithms # Easy (42.56%) # Likes: 1661 # Dislikes: 209 # Total Accepted: 305.2K # Total Submissions: 716.5K # Testcase Example: '16' # # Given a positive integer num, ...