blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
6b3418c122dc4d3aab6c50aba7c6bd1a7ff014b0
tme5/PythonCodes
/CoriolisAssignments/pyScripts/04_is_vowel.py
865
3.984375
4
#!/usr/bin/python ''' Date: 17-06-2019 Created By: TusharM 4) Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise. ''' def is_vowel(inp): '''Check if the input character is vowel Returns True if vowel else False''' vowels=['a','e...
9b436aad58e0616d5d861c80a1f5418f2216b63f
tme5/PythonCodes
/Daily Coding Problem/PyScripts/Program_0013.py
831
4.03125
4
''' This problem was asked by Amazon. Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". Created on 25-Jun-2019 @author: Lenovo ''' def longest_sub...
503355cdd49fa7399ed1062a112b8de55f1c0654
tme5/PythonCodes
/Daily Coding Problem/PyScripts/Program_0033.py
926
4.25
4
''' This problem was asked by Microsoft. Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element. Recall that the median of an even-numbered list is the average of the two middle numbers. For example, given the sequence [2, 1, ...
7b4b12520990261beeab371ddf7c80cfefd80738
tme5/PythonCodes
/Daily Coding Problem/PyScripts/Program_0004.py
1,055
3.953125
4
''' Good morning! Here's your coding interview problem for today. This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates ...
b447e0421109328bbacc97323b9eff9cf1292eb7
tme5/PythonCodes
/Daily Coding Problem/PyScripts/Program_0021.py
1,122
4.03125
4
''' This problem was asked by Snapchat. Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. Created on 25-Jun-2019 @author: Lenovo ''' room_dict={} time_slots=[(3...
90e11da284a4de482fbb14934b039364ec345e88
tme5/PythonCodes
/Daily Coding Problem/PyScripts/Program_0028.py
2,134
4.0625
4
''' This problem was asked by Palantir. Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified. More specifically, you should have as many words as possible in each line. There should be at least one space between ...
76920ffe02e528d209836700c3d512ffee842b13
tme5/PythonCodes
/CoriolisAssignments/pyScripts/32_file_palindrome.py
1,145
3.875
4
#!/usr/bin/python ''' Date: 19-06-2019 Created By: TusharM 32) Write a version of a palindrome recogniser that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome. ''' def in_file_palindrome(file): '''Check if input string in palindrome or not, Re...
42716bcb27499c2079a9eda6925d9ae969217adf
tme5/PythonCodes
/CoriolisAssignments/pyScripts/33_file_semordnilap.py
1,780
4.53125
5
#!/usr/bin/python ''' Date: 19-06-2019 Created By: TusharM 33) According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of wor...
9801097af0d4a761dc1f96039b2cf86cac257c26
tme5/PythonCodes
/CoriolisAssignments/pyScripts/21_char_freq.py
1,200
4.40625
4
#!/usr/bin/python ''' Date: 18-06-2019 Created By: TusharM 21) Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab"). ''' def...
b3342112bb958266c539cda4c81060d8f0fc3dd3
tme5/PythonCodes
/CoriolisAssignments/pyScripts/44_mis_nest.py
1,077
4.03125
4
#!/usr/bin/python ''' Date: 19-06-2019 Created By: TusharM 44) Your task in this exercise is as follows: Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of op...
52d5cf2200752963d7f29a64964266747a0ad4f4
tme5/PythonCodes
/DataStructure&Algorithms/PythonPrimer/Exercises/P_1_31.py
2,103
3.703125
4
#!python ''' Created on Apr 5, 2019 @author: TME5 ''' # +---{ Import Section }---+ import sys,os,time # +---{Supportive Class Section }---+ def elapsed_time(f): def wrapper(): t1 = time.time() f() t2 = time.time() print(f'Elapsed time: {(t2 - t1)} s') return wrapp...
f869321ad3d5a053c4e10c8c0e84c83d25b33974
tme5/PythonCodes
/CoriolisAssignments/pyScripts/30_translate_to_swedish.py
1,031
4.15625
4
#!/usr/bin/python # -*- coding: latin-1 -*- ''' Date: 19-06-2019 Created By: TusharM 30) Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"r"} and use it to translate your Christmas cards from E...
9750b79544423c1ad33910112ffabf24bea08fdf
tme5/PythonCodes
/DataStructure&Algorithms/PythonPrimer/Exercises/R_1_2.py
473
4.09375
4
#!python ''' Created on Apr 2, 2019 @author: TME5 ''' # def is_even(k): # if k%2==0: # return True # else: # return False # def is_even(k): # if k&1==1: # return False # else: # return True def is_even(k): isEven=True for i in range(1,k+1): ...
2a6a60834a667c90877903649c976142244ea191
tme5/PythonCodes
/DataStructure&Algorithms/PythonPrimer/Exercises/C_1_25.py
208
3.5625
4
''' Created on Apr 2, 2019 @author: TME5 ''' import re,string def remPunctuation(strn): return re.sub('['+string.punctuation+']','',strn) strn="Let's try, Mike." print(remPunctuation(strn))
9a59ee62d2416ec111ebf66c96be3e96c3f01411
myHonorABC/Bubble-Sort
/bubble_sort.py
430
3.609375
4
import time def bubble(alist): n=len(alist) for i in range(n-1): count=0 for j in range(n-1-i): if alist[j]>alist[j+1]: alist[j],alist[j+1]=alist[j+1],alist[j] count+=1 if count==0: return if __name__=='__main__': alist=[12,2...
04c2a5346946bea20cabd1d5ba3eb4fe54f058b4
MaciejBlaszczyk/Algorithms
/RootFindingBisectionMethod.py
628
4.03125
4
def function(x): return x * x * x + 5 * x + 1 def bisectionMethod(): point1 = -1 point2 = 1 accuracy = 0.001 value1 = function(point1) value2 = function(point2) if value1 * value2 > 0: print("Error, wrong points") return -1 while abs(point1 - point2) > accuracy: ...
fe872d084d7235ba46621753870a11a85dc4e6f8
david-azevedo/GoogleHashCode
/solutionCPP/pizza.py
2,574
3.578125
4
class Slice(): def __init__(self,pizza,x,y): self.pizza = pizza self.x=x self.y=y self.shape= pizza.maxArea * (pizza.maxArea - 1) + 1 def setArea(self): while True: self.shape-=1 if(self.shape == 0) return False ...
34bf5628fe0ba8ef8d65065cfb3172b781f6ae08
jonathanjchu/algorithms
/fibonacci.py
997
4.4375
4
import math # comparison of different methods of calculating fibonacci numbers def fibonacci_iterative(n): a, b = 0, 1 for i in range(n): a, b = b, a + b return a # slows down after around n=30 def fibonacci_recursive(n): if n < 2: return n elif n < 3: return 1 else: ...
52dd5a18a31a5e87c006c18a6115476e65f4984a
Yangyanging/168206
/168206115/005.py
534
3.9375
4
def merge(a, b): i, j = 0, 0 result = [] while i < len(a) and j < len(b): if a[i]<b[j]: result.append(a[i]) i+=1 else: result.append(b[j]) j+=1 result+= a[i:] result+= b[j:] return result def m...
f08a9bf9a78fea593ed675abb5b3b8cee5f3a203
macabdul9/ml-cb-course-work
/python-practice-problem/increasingDecreasingSequence.py
673
3.75
4
def decreasing(seq, i): if seq[i] == seq[i - 1] - 1: return True else: return False def increasing(seq, i): if seq[i] == seq[i - 1] + 1: return True else: return False if __name__ == '__main__': n = int(input()) seq = [] for i in range(n): seq.ap...
910a09668634d802c863197d94214174d89fc816
anupama-sri/My-First-Repository
/file.py
59
3.5
4
a = 10 b = 20 if a==10: print("Hello World") else print(b)
a5231e94fe673f62c0ac202415612f07c80bb796
HowardHC-Huang/password-retry
/password-retry.py
771
4
4
##密碼重試程式## #1.先設定好密碼 #2.讓使用者最多輸入3次密碼 #3.不對:印出"密碼錯誤, 還有_次機會" #4.對:印出"登入成功" password = 'a123456' #answer = input('請輸入密碼 \n') #這行寫進迴圈較好 n = 3 while n > 0 : answer = input('請輸入密碼 \n') if answer == password: print('登入成功!') break else: n = n - 1 if n <= 0: print('嘗試次數過多, 終止嘗試') else: print('密碼錯誤,還有', ...
b2d2970790c116f2a9e676f21657fdf51d39c52f
stkr1623/Pong-Game
/paddle.py
388
3.828125
4
from turtle import Turtle , Screen screen=Screen() class Paddle(Turtle): def __init__(self,position , colour): super().__init__() self.shape("square") self.color(colour) self.penup() self.position = position self.goto(position) self.turtlesize(...
d8619ab3933c5fd1afe4cf84c494d5cb4607e641
sigvetl/IN3110
/assignment3/wc.py
610
4.03125
4
#!/usr/bin/env python3 import sys """Initializes the three variables to 0, opens the file and parsing each line and incrementing lines, words and chars with a split of " " for words and lenght of line for chars Skips sys.argv[0] as this is the name of the executable """ def wc(fn): lines = 0 words = 0 char...
fb9f6c12e366c4ad0b58ea4f21f81dfad181b00a
sigvetl/IN3110
/assignment4/toGray/numpy_color2gray.py
1,469
3.53125
4
import cv2 import time import numpy as np filename = "rain.jpg" image = cv2.imread(filename) if image is None: raise Exception("Not a valid picture") #A standard for docstrings is to include information about arguments and return values if there are any def numpy_color2gray(img): """ creating a copy of t...
84709436cdba41e70c168f6619041831cac7e7e5
gulsah-hezer/homeworks_2
/hw8.py
1,849
3.75
4
#1. aşama: n=int(input('please enter integers suct that n> 1002:')) if n> 1002: print('you entered it correctly ') else: print('you are supposed to enter integers s.t.n> 1002') #2.aşama:we need to find prime p larger than 2(n^1/4+1)^2 def finding_prime(n): m=n**(1/4) g=2*((m+1)**2) print('g...
c9908ddd070d5cea4abc1eaf3fcde7c53df88f71
DianaKorladinova/goodreads_scraper
/database.py
1,122
4
4
import sqlite3 from sqlite3 import Error def create_connection(): """ create a database connection to a SQLite database """ conn = None try: conn = sqlite3.connect(r"/var/lib/db/pythonsqlite.db") sql_statement = """ CREATE TABLE IF NOT EXISTS Books(id INTEGER PRIMARY KEY, ...
23a4193f7d989f4eab1f2a69ceac61c70bc1f619
angelaza/hello
/lesson1-4/huice/day2/Stack.py
1,198
4.09375
4
class Stack(object): def __init__(self, size): self.__size = size self.__stack = [] def __str__(self): return str(self.__stack) def __isfull(self): if len(self.__stack) == self.__size: return True else: return False def __is...
ad398ff8acc6666a67c423e290b65c6450ed57be
kguidonimartins/intro-prog-python
/cap03/exercicio-3.14.py
263
3.796875
4
# Quanto pagar pelo aluguel do carro? # diária = R$ 60 por dia # km rodado = R$ 0.15 km = float(input("Quilômetros percorridos:")) dias = int(input("Dias com o carro:")) valor = (km * 0.15) + (dias * 60) print("Valor pelo carro alugado é R$ %2.f" % valor)
3a55dc11884ab325f1212fb1437aac96957d9a74
kguidonimartins/intro-prog-python
/cap04/exercicio-4.2.py
230
3.765625
4
velocidade = float(input("Qual era a velocidade do seu veículo?")) if velocidade > 80: print("Você será multado.") excesso = velocidade - 80 multa = excesso * 5 print("O valor da multa é de R$ %2.2f." %multa)
5fe698f8b3a6295c31f3002ac9285c1528c75a39
kguidonimartins/intro-prog-python
/cap03/list-3.10.py
364
3.828125
4
# !/usr/bin/python # -*- coding: utf-8 -*- """ Exemplos de composição com números inteiros """ idade = 22 print("[%d]" % idade) print("[%03d]" % idade) print("[%010d]" % idade) print("[%20d]" % idade) print("[%020d]" % idade) print("[%-020d]" % idade) print("[%-20d]" % idade) print("[%3d]" % idade) print("[%...
2b05c505f88749d30013c16916635e169b2a4a02
kguidonimartins/intro-prog-python
/cap04/exercicio-4.9.py
397
3.828125
4
valor_casa = float(input("Qual é o valor da casa?")) salario = float(input("Qual é a sua renda mensal?")) anos = float(input("Em quantos anos você pretende pagar a casa?")) parcela = valor_casa / (anos * 12) porc_30_sal = (salario * 30) / 100 if parcela > porc_30_sal: print("O empréstimo não pode ser aprovado") e...
165c3a704e31df40fb864d28a04a0f9ef183435c
MilkTangYuan/PythonLearn
/1/homework1.py
68
3.515625
4
name = input("请输入您的姓名") print("你好,"+ name + "!")
c578ccfed00bf12bab5cc628f38189ae9c53251f
MilkTangYuan/PythonLearn
/1/homework40.py
742
3.734375
4
''' 0.issubclass(class,classinfo) 1.isinstance(object,classinfo) 2. 先使用 hasattr(object,name)判断 "name"是否是object的对象,再访问 直接使用 getattr(object,name,err),返回object指向的name 如果name 不存在则返回 err 3. 允许编程人员轻松有效地管理 属性 访问。 4. x = property(getXSize,setXSize,delXSize) ''' import time def timeslong(func): def call(): s...
2ac5b9f180295466d5c10d8e44ca522e92349e4b
sunsushishine/KNB
/knb.py
1,345
3.515625
4
import random, os CountD = 0 # Счетчики - Ничья, Победа, Проигрыш (Draw, Loose, Win) CountL = 0 CountW = 0 l = ['k','n','b'] # Значения для рандомной выборки - Камень, Ножницы, Бумага def inp(): # ввод числа раундов global n while True: try: n = int(input('Введите количество игр n...
784916df25e17e7951ec291a500464579aa26e8f
monkiravn/learnML
/LearnPython/HomeWorkW3AIVN/statisticsbasic.py
710
3.53125
4
from collections import Counter data = ([7,8,9,2,10,9,9,9,9,4,5,6,1,5,6,7,8,6,1,10]) def mean(data): sumData = sum(data) N = len(data) return sumData / N def variance(data): temp = [] meanData = mean(data) for d in data: temp.append((d - meanData)**2) var = mean(temp) return var...
9fe04719915e14e444f415497f8dc5b9af829c4d
MAYANK095/Artificial-Intelligence
/one5.py
240
3.5625
4
import matplotlib.pyplot as plt ages=[12,32,3,43,55,33,56,89,98,53,34,34,34,5,6,7,2,11,34] binsize=10 range=(0,100) plt.hist(ages,binsize,range,color='green',histtype='bar',rwidth=0.8) plt.xlabel('Distribution') plt.ylabel('Age') plt.show()
4c26628f80754aebe2f2e32f08d4137d099e90ee
thien-truong/learn-python-the-hard-way
/ex39internet.py
2,145
4.03125
4
#Dictionaries, Oh Lovely Dictionaries - Online Version stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2} print stuff['name'] print stuff['height'] stuff['city'] = "San Francisco" print stuff['city'] stuff[1] = "Wow" stuff[2] = "Neato" print stuff[1] print stuff[2] print stuff del stuff['city'] del stuff[1] del stu...
46bcbbe3a779b19a3c021be114ebb33846785e49
thien-truong/learn-python-the-hard-way
/ex15.py
617
4.21875
4
from sys import argv script, filename = argv # A file must be opened before it can be read/print txt = open(filename) print "Here's your file {}:".format(filename) # You can give a file a command (or a function/method) by using the . (dot or period), # the name of the command, and parameteres. print txt.read() # ca...
8a745e216a89e5a3f6c9d4111ea2bc38d37e4eb7
thien-truong/learn-python-the-hard-way
/ex18.py
1,209
4.59375
5
# Fuctions: name the pieces of code the way ravirables name strings and numbers. # They take arguments the way your scripts take argv # They let you make "tiny commands" # this one is like your scripts with argv # this function is called "print_two", inside the () are arguments/parameters # This is like your script...
a22254f253ba45e1eaf0f10542f40669bb0eb99b
JennyBloom/DungeonGame
/DungeonGame-submitted.py
1,589
3.796875
4
""" Author: Jenny Bloom Date: 9/5/2015 Class: CSCI 1310 Assignment: HW2 A Dungeon Game! This is a text game in Python, with intention of understanding while loops, if/elif/else statements, all the while looking for a princess and avoiding burning to death. Basic needs: Quitting, Room, Direction """ greeting = "Welco...
128965a6efadb0488df7f4d93d9b3988dc1d4346
ragingra/programming-problems
/crackingCodes_book/transportation/columnar.py
776
3.859375
4
import math def encrypt(text, key): output = [] for num in range(key): output.append(text[num::key]) return ''.join(output) def decrypt(text, key): num_columns = math.ceil(len(text) / key) blanks = (num_columns * key) - len(text) output = [''] * num_columns column = row = 0 fo...
2a1c6141bc0a12a1b58fd495fa8892f7d429563d
dlarner3194/ProjectEuler
/one_1.py
319
3.96875
4
# Problem 1 # all natural numebers 1-infinty # Find the sum of all the multiples of 3 or 5 below 1000. import array # first answer arr = [] for i in xrange(1000): if i % 3 == 0 or i % 5 == 0: arr.append(i) print(sum(arr)) print sum(number for number in xrange(1000) if not (number % 3 and number % 5))
c26e67784bb819b5b870bfd657978c8b9015c6f1
lilsweetcaligula/sandbox-codewars
/solutions/python/3.py
240
3.515625
4
def delete_nth(order,max_e): counter = {} result = [] for item in order: if item not in counter or item in counter and counter[item] < max_e: counter[item] = counter.get(item, 0) + 1 result.append(item) return result
b1f1aa96651c23a2f03fbde3789b8fdfade9d862
lilsweetcaligula/sandbox-codewars
/solutions/python/394.py
464
3.953125
4
def fibs_fizz_buzz(n): previous, current = 0, 1 fibonaccis = [] while n > 0: if current % 3 == 0 and current % 5 == 0: fibonaccis.append('FizzBuzz') elif current % 3 == 0: fibonaccis.append('Fizz') elif current % 5 == 0: fibonaccis.append('Buzz') ...
e15f397eee25fc89efc53685ae9249906197b2c5
lilsweetcaligula/sandbox-codewars
/solutions/python/389.py
275
3.625
4
#fix the function below! def convert_num(number, base): try: if base == 'hex': return hex(number) if base == 'bin': return bin(number) return 'Invalid base input' except TypeError: return 'Invalid number input'
1b39ab020a41ce4eeeb163ea66ba6d8ef9ee2ded
lilsweetcaligula/sandbox-codewars
/solutions/python/9.py
264
3.859375
4
def alphabet_position(text): from string import ascii_lowercase lookup = { letter: index for index, letter in enumerate(ascii_lowercase.casefold(), start = 1) } return ' '.join(str(lookup[char.casefold()]) for char in text if char.casefold() in lookup)
b91ce482398dc5e534f4c616a13223a7cd1a800a
lilsweetcaligula/sandbox-codewars
/solutions/python/208.py
125
3.53125
4
def shifted_diff(first, second): if len(first) != len(second): return -1 return (second + second).find(first)
780dc23b1756aee6ebcf1be6dd840740e036ed73
lilsweetcaligula/sandbox-codewars
/solutions/python/111.py
396
3.625
4
def factorial(n): import functools import operator return functools.reduce(operator.mul, range(1, n + 1), 1)import sys MULTIPLIER = 10 sys.setrecursionlimit(sys.getrecursionlimit() * MULTIPLIER) def factorial(n): return 1 if n < 2 else n * factorial(n - 1)def factorial(n): from operator import mul...
deb8ba1725981a22e3ea437a4a96c98115338da1
lilsweetcaligula/sandbox-codewars
/solutions/python/20.py
164
3.53125
4
def find_it(seq): from collections import Counter for value, occurs in Counter(seq).items(): if occurs % 2: return value return None
bbded6cbd92c0dcc1f1b20523c36ea030e7c2644
lilsweetcaligula/sandbox-codewars
/solutions/python/75.py
139
3.875
4
def vowel_2_index(string): return ''.join(char if char.lower() not in 'aeoui' else str(index + 1) for index, char in enumerate(string))
482e397fd9cc91eb1a07cf602b09886a22f73aba
lilsweetcaligula/sandbox-codewars
/solutions/python/186.py
262
3.59375
4
getCount = (lambda inputStr: len([char for char in inputStr if char.lower() in 'aeoui']))def getCount(inputStr): from collections import Counter counter = Counter(char for char in inputStr if char.lower() in 'aeoui') return sum(counter.values())
abf5ebc9bcc502c23a95455ddac8de2c16991ffb
lilsweetcaligula/sandbox-codewars
/solutions/python/249.py
601
3.609375
4
def add(a,b): i, j = len(a) - 1, len(b) - 1 result_bits = [] carry = 0 while i >= 0 or j >= 0: a_bit = b_bit = 0 if i >= 0: a_bit = 1 if a[i] == '1' else 0 i -= 1 if j >= 0: b_bit = 1 if b[j] == '1' else 0 j -= 1 addition = ...
a961d3c94b09add38b32186fbc8e5176b3cf1ff0
lilsweetcaligula/sandbox-codewars
/solutions/python/492.py
198
3.5
4
def namelist(people): names = [person['name'] for person in people] if len(names) <= 1: return ''.join(names) return ' & '.join((', '.join(names[:-1]), ''.join(names[-1:])))
6c76fbb8769562b03c179453cd18a91a7d24afbe
lilsweetcaligula/sandbox-codewars
/solutions/python/206.py
307
3.53125
4
def sum_consecutives(L): currentSum = 0 result = [] index = 0 while index < len(L): value = L[index] while index < len(L) - 1 and L[index] == L[index + 1]: value += L[index] index += 1 result.append(value) index += 1 return result
2b0032c2452b0d9e996139a518cb11176a0a067f
lilsweetcaligula/sandbox-codewars
/solutions/python/384.py
274
3.8125
4
def add_length(string, separator = " "): return ["{} {}".format(substring, len(substring)) for substring in string.split(separator)]def add_length(string, separator = " "): return ["{0} {1}".format(substring, len(substring)) for substring in string.split(separator)]
e49ef0b7a0a3d70c31a4aa2fa1e53ae701198ae4
lilsweetcaligula/sandbox-codewars
/solutions/python/15.py
126
3.53125
4
def narcissistic( value ): digits = map(int, str(value)) return value == sum(digit ** len(digits) for digit in digits)
e4718104a91801530f8e8c415be3f0a9303d9b67
lilsweetcaligula/sandbox-codewars
/solutions/python/486.py
191
3.546875
4
def group_by_commas(n): s = str(n) subs = [s[:len(s) % 3]] + [s[start:start + 3] for start in range(len(s) % 3, len(s), 3)] return ','.join(filter(lambda sub: len(sub) > 0, subs))
a6b4490784f51efcdffe80bd02764e20b16af249
lilsweetcaligula/sandbox-codewars
/solutions/python/209.py
293
3.59375
4
def two_sum(values, result): from collections import OrderedDict lookup = OrderedDict({ value: index for index, value in enumerate(values) }) for index, x in enumerate(values): y = result - x if y in lookup: return [index, lookup[y]] return [-1, -1]
c262dbe0488f0216fb86040451f6f1514824b27e
lilsweetcaligula/sandbox-codewars
/solutions/python/37.py
417
3.59375
4
class Node(object): def __init__(self, data, next = None): self.data = data self.next = next def remove_duplicates(head): if head == None: return None slow = head fast = head.next while fast != None: if slow.data != fast.data: slow.next = fast ...
58b29eb82daa403901e3ff89cd21237ca1e213e9
lilsweetcaligula/sandbox-codewars
/solutions/python/385.py
191
3.859375
4
def find_average(nums): return sum(nums) / float(len(nums)) if len(nums) != 0 else 0def find_average(nums): if len(nums) == 0: return 0 return sum(nums) / float(len(nums))
43c08971a7c6ea27e44563e794c88e7563db7476
lilsweetcaligula/sandbox-codewars
/solutions/python/283.py
511
3.6875
4
def get_length_of_missing_array(array_of_arrays): lengths = [len(sub) for sub in array_of_arrays or [] if sub] or [0] return( array_of_arrays and all(array_of_arrays) and sum(range(min(lengths), max(lengths) + 1)) - sum(lengths) or 0)def get_length_of_missing_array(array_of_arrays): if ...
3f9460c1fbb2a157ba09b5af7da4c2cdc40f8320
lilsweetcaligula/sandbox-codewars
/solutions/python/426.py
251
3.765625
4
def split_odd_and_even(n): from itertools import groupby digits = map(int, str(n)) result = [] for isEven, values in groupby(digits, lambda digit: digit % 2 == 0): result.append(int(''.join(map(str, values)))) return result
174c97de871df83407ece068bb8467a5b8fbbb54
lilsweetcaligula/sandbox-codewars
/solutions/python/201.py
237
3.6875
4
def insert_dash(num): from itertools import groupby return ''.join( '-'.join(group) if label else ''.join(group) for label, group in groupby( list(str(num)), key = lambda item: int(item) % 2))
7fc3964bd27458a6e8514a856d7a7661077bf5e1
lilsweetcaligula/sandbox-codewars
/solutions/python/268.py
432
4
4
def vowel_shift(text,n): if not text or not n: return text from itertools import chain, cycle vowels = set('aeoui') text_vowels = [char for char in text if char.lower() in vowels] n = n % len(text_vowels) if len(text_vowels) > 0 else 0 vowels_iterator = cycle(chain(text_vowels[-n:], text_vowels[:-n])) ...
096f0a45052be22c182f2f61234c1830b53e83fe
lilsweetcaligula/sandbox-codewars
/solutions/python/483.py
231
3.53125
4
def nth_fib(n): a, b = 0, 1 for times in range(n - 1): a, b = b, a + b return adef nth_fib(n): values = [0, 1] for times in range(n - len(values)): values.append(values[-1] + values[-2]) return values[n - 1]
459cc083083c3d36c90be372521231748db9795f
rajatdiptabiswas/competitive-programming
/HackerRank/Lonely Integer.py
271
3.53125
4
#!/usr/bin/env python3 from functools import reduce def main(): t = int(input()) while (t != 0): array = [int(x) for x in input().split()] print(reduce(lambda x,y : x^y, array)) t -= 1 if __name__ == '__main__': main()
da085cfe41222792c1bf8302a9c82d26cdccf302
rajatdiptabiswas/competitive-programming
/Codeforces/987A.py
447
3.59375
4
#!/usr/bin/env python3 def main(): color_dict = { 'purple':0, 'green':1, 'blue':2, 'orange':3, 'red':4, 'yellow':5 } gems = ['Power','Time','Space','Soul','Reality','Mind'] gauntlet = [False for _ in range(6)] n = int(input()) for _ in range(n): stone = str(input()) gauntlet[color_dict[ston...
788cfd5cddc4f05a47bfda1d323df400fccf8925
rajatdiptabiswas/competitive-programming
/Codeforces/651A.py
399
3.609375
4
#!/usr/bin/env python3 def charge(x): x += 1 return x def discharge(x): x -= 2 return x a,b = map(int, input().split()) # print("a = " + str(a) + " b = " + str(b)) ans = 0 while(a > 0 and b > 0): if a == 1 and b == 1: break elif a >= b: a = discharge(a) b = charge(b) else: a = charge(a) b = dis...
003f3452faccae6494e761f1570a4cc2ff79f0f5
rajatdiptabiswas/competitive-programming
/CodeChef/STRNO-helper.py
1,817
3.78125
4
#!/usr/bin/env python3 import math def factors(n): factor_list = [] for i in range(1, math.floor(n**0.5)+1): if n % i == 0: if i == n//i: factor_list.append(i) else: factor_list.append(i) factor_list.append(n//i) return sorte...
eb53ff2f3e67fb4e974c126f257d3b19c4684430
rajatdiptabiswas/competitive-programming
/CodeChef/BROCLK (try).py
1,122
3.78125
4
#!/usr/bin/env python3 from math import cos,acos from fractions import Fraction,gcd MOD = 1000000007 # Function to find modular inverse of a under modulo m # Assumption: m is prime def modInverse(a, m) : g = gcd(a, m) if (g != 1) : print("Inverse doesn't exist") else : ...
29629bc3d3f67e8c1b443e3a929bb479afad567e
rajatdiptabiswas/competitive-programming
/CodeChef/CHHAPPY.py
591
3.515625
4
#!/usr/bin/env python3 #https://www.codechef.com/NOV18B/problems/CHHAPPY ''' Example Input 4 4 1 1 2 3 4 2 1 3 3 5 5 4 4 3 1 5 3 2 1 1 4 Example Output Truly Happy Poor Chef Poor Chef Truly Happy ''' def main(): t = int(input()) for testcase in range(t): n = int(input()) arr = [int(x) for x in input().split(...
353e8ded2494f754584aac0b3d8af62a41cabe28
WebF0x/Snake
/test_snake.py
2,542
3.546875
4
from position import Position from snake import Snake class TestSnake: def test_get_neck_position(self): snake = Snake(Position(5, 5), 'down') snake.set_orientation('down') assert Position(5, 6) == snake.get_neck_position() snake.set_orientation('up') assert Position(5, 4...
b39f20ebad9f1fbba0471b1b5a700fcb90bba17a
jkcn90/codejam
/2015/qualifying/ominous_omino/ominous_omino.py
3,565
3.734375
4
#!/usr/bin/env python3 import sys import argparse def process_instance(instance): omino_size = instance['omino_size'] number_of_columns = instance['number_of_columns'] number_of_rows = instance['number_of_rows'] # With more than 7 peices you can make a donut if omino_size >= 7: return ...
8139cd0a70de9527915ce1eb9c540929ecc770e0
LittltZhao/python_II
/02_generators.py
1,294
4.09375
4
# -*- coding:utf-8 -*- # 适用情况:不想同一时间将所有计算出来的大量结果集分配到内存当中 # 生成器也是一种迭代器,但是你只能对其迭代一次。这是因为他们并没有把所有的值存在内存中,而是在运行时生成值。 # 区分可迭代对象和迭代器对象: # 一个迭代器是任意一个对象,只要它定义了一个next(Python2) 或者__next__方法 # 可迭代对象是Python中任意的对象,只要它定义了可以返回一个迭代器的__iter__方法,或者定义了可以支持下标索引的__getitem__方法 def generator(): for i in range(3): yield i # for i...
8596ec1aa310685360410a772a9555d645fa08b0
LittltZhao/python_II
/10_comprehension.py
494
4.03125
4
# -*- coding:utf-8 -*- # 推导式 解析式 # 列表解析 multiples=[x for x in range(30) if x%3==0] print multiples squred=[x**2 for x in range(5)] print squred #字典推导 mcase={'a':10,'b':34,'A':7,'Z':3} mcase_fre={ k.lower():mcase.get(k.lower(),0)+mcase.get(k.upper(),0)#统计大小写的总次数 for k in mcase.keys()} print mcase_fre print mca...
9cab5e8cc5240624086fe4cac5a93e5eaebc9a0b
gemifytech/crystal
/src/transaction.py
1,614
3.53125
4
from collections import OrderedDict from utility.printable import Printable class Cube(Printable): """The foundation for the any type of activity that happens in each individual Blockchain """ def __init__(self, sender, signature, type: str): self.sender = sender self.signature = signature self.type = type ...
1c10587a89a14519852b5c96e265fef783f82f0a
esmairi/ummalqura
/tests/ummalqura_test.py
585
3.53125
4
#!/usr/bin/env python3 from ummalqura.hijri_date import HijriDate #create the object with Gregorian date um = HijriDate(1989,1,10,gr=True) #to see the day in Hijri um.day # result : 3.0 #to see the month in Hijri um.month #result is 6.0 #year um.year #1409 #day name in arabic print (um.day_name) #الثلاثاء #day in engl...
59e72b03abde37f3a8c0f17dca0a733d33fa64f8
therichermx/StructuredPrograming2A
/Unit2/Proyect/B2p.py
322
4.09375
4
import sys def result(X): for num in range(X): if num % 3 == 0 and num % 5 == 0: print(str(num)+ " ", end= "\n") else: pass ##Due to result(x), it always appears as "None" when running if __name__ == "__main__": X = int(input(print("Write your range \n"))) result(X...
197e7a1ab120531edb6b33aea2183fd96f56ce7e
tom8u4286/yelp-line
/ReviewClassifier.py
2,827
3.578125
4
import json import os from collections import OrderedDict class ReviewClassifier: """ This program aims to (1) filter out redundant reviews (2) classify the reviews of the matched restaurants """ def __init__(self): self.src_b = "data/new_business_list.json" self.src_r = "data/review_list.jso...
ebf57056725bd96f6cc89a1b0d4c619241126ce9
murbard/money.fish
/island.py
5,267
3.90625
4
import random import math import numpy as np class Order(object): def __init__(self, villager, shells): """ Create an order where a given villager offers or requests a certain number of shells for a fish. :param villager: the villager :param shells: negative to buy fish, po...
640ca619f61d872cbca82fc9c0ff5e23dd0d0b89
Wireframe-Magazine/Code-the-Classics
/cavern-master/cavern.py
32,563
3.65625
4
from random import choice, randint, random, shuffle from enum import Enum import pygame, pgzero, pgzrun, sys # Check Python version number. sys.version_info gives version as a tuple, e.g. if (3,7,2,'final',0) for version 3.7.2. # Unlike many languages, Python can compare two tuples in the same way that you can compare...
8d05a9580c0b1e6ab8182ba94fcfc799c159df3d
AliceMGao/Python_matplot_novel
/alphabet-bar-chart.py
8,334
3.5
4
import requests import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import StrMethodFormatter # Letters variable for the entire alphabet. letters = 'abcdefghijklmnopqrstuvwxyz' # Create the dict to use to store the # counts for the individual letters of the alphabet. letters_counts = ...
0267fc47c656342ae8f4df8aacdcec028505c77e
vinya11/AI561
/path finding algorithms/pathPlanning.py
9,311
3.65625
4
import heapq import collections import time class pathfinding(object): def __init__(self,graph,startX,startY,w,h,rockMaxHeight,settlements): self.graph = graph self.startX =startX self.startY=startY self.w = w self.h = h self.rockMaxHeight = rockMaxHeight self...
fff7ecd42a575a75bd8c70fd7c301b8cd7a6cf9c
PacktPublishing/Hands-On-Enterprise-Application-Development-with-Python
/chapter01/python3_str_types.py
253
3.921875
4
#!/bin/python3 str1 = 'I am a unicode string' print("Type of str1 is " + str(type(str1))) str2 = b"And I can't be concatenated to a byte string" print("Type of str2 is " + str(type(str2))) print("Trying to concatenate str1 and str2") str3 = str1 + str2
3f5f6505a5898c86e95f36345787b61e949d3d72
PacktPublishing/Hands-On-Enterprise-Application-Development-with-Python
/chapter02/abstract_base_classes.py
436
3.921875
4
#!/bin/python3 from abc import ABC, abstractmethod class AbstractUser(ABC): @abstractmethod def return_data(self): pass class User(AbstractUser): def __init__(self, username): self.username = username self.user_data = {} def return_username(self): return self.username def return_data(...
657c93ae0598cd4dbeb0f0bbdc245deecefcc8fb
taquayle/CSS458
/Assignment 5/Tyler Quayle - P1.py
3,867
3.671875
4
################################################################################ # Name: Tyler Quayle # Assignment: Monte Carlo 2, Problem 1 # Date: April 26, 2016 ################################################################################ import random as ra import numpy as np import numpy.ma as ma import ...
67fba9ec80c9d9390900baedcd11fe78dfcf5d9e
skwangdl/python_demo
/base/16_demo_file.py
503
4.0625
4
def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) def demo_openfile(): poem = '''\ hello kepler ''' f = open('D:\\temp\\pome.txt', 'w') f.write(poem) f.close() f = open('D:\\temp\\pome.txt') while True: line = f.readline() ...
7cbcc41c3b7c9ded3e814e40d2f13de7862015b1
skwangdl/python_demo
/base/44_demo_Json.py
860
3.625
4
import json def demo_json(): d = dict(name='kepler', age='27') j = json.dumps(d) print(j) json_str = '{"age": 20, "name": "kepler"}' json_obj = json.loads(json_str) print(json_obj) class Person(object): def __init__(self, name, age): self.name = name self.age = age def obj...
f4edc4cc215d67c54afda9b8adb065c79d306c8e
james-w-balcomb/kaggle--home-credit-default-risk
/jb/ats_get_missing_flags.py
743
3.5
4
import pandas def ats_get_missing_values_flags(data): """ Generates columns with flags indicating missing values in the existing columns Parameters ---------- data : array-like, Series, or DataFrame Returns ------- ats_df_missing_values_flags : DataFrame of {1,0} as object ...
6a6924e2e197b494c293e37ee3eb333b3d360156
IgorSouza4489/Projeto-Python-Banco
/menu.py
6,821
3.78125
4
def teste_arquivo(): if not arquivoExiste(arq): criarArquivo(arq) def arquivoExiste(nome): try: a = open(nome, 'rt') a.close() except FileNotFoundError: return False else: return True def ler_saldo(msg): dado_ok = False while not dado_ok: try...
cbfa1e7c77f026389db57dbc6914264d48ad5b86
rralbritton/python_scripts
/decode_polyline_mod.py
3,239
3.515625
4
#Name: decode_polyline.py #Purpose: decode encoded polylines from ride system JSON service endpoint # And create feature classes of that data #Reference: The decode_polyline definition was slightly modified from # https://stackoverflow.com/questions/15380712/how-to-decode-...
1d0985ea251dc196b7b0d12220533ce687202d27
tengkuhanis/DSA-Project-Group-9
/LAB 1 PROJECT_GROUP 9/HashTable.py
8,997
4.1875
4
# Program to implement Hashing with Quadratic and Cubic Probing ''' ECIE3101 LAB 1 - DATA STRUCTURE AND ALGORITHM DESIGN SEMESTER 1 20/21 PROJECT THEME: VISUALIZATION OF DATA STRUCTURE =============== COLLABORATORS ===================== -Tengku Hanis Sofea Tengku Effendy (1810258) -Muhammad Adhwa Fathullah bin...
2425042069cc1560aadc356f4895195aec570cfe
imsoumen/HackerRank
/Challenges/Lily's_Homework.py
2,831
3.78125
4
""" Lily's Homework --------------------------------------- Link: https://www.hackerrank.com/contests/wissen-coding-challenge-2021/challenges/lilys-homework --------------------------------------- Whenever George asks Lily to hang out, she's busy doing homework. George wants to help her finish it faster, but he's in o...
a1044425f3337e5348943792043388835e79ed3f
imsoumen/HackerRank
/Challenges/ExtraLongFactorials.py
2,195
3.984375
4
""" Extra Long Factorials ----------------------------------- Link: https://www.hackerrank.com/contests/wissen-coding-challenge-2021/challenges/extra-long-factorials ----------------------------------- The factorial of the integer n, written n!, is defined as: n! = n x (n-1) x (n-2) x ....... x 3 x 2 x 1 Calculate...
cca3b9ac98385c51464a5fe08a7e4bfbe96e2fe7
imsoumen/HackerRank
/30_Days_of_Code/Day_10_Binary_Numbers/Python/Day_10_Binary_Numbers.py
1,309
3.921875
4
/* Objective Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video! Task Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation. When ...
fbda320729718b3c338b69d5f6e14fe88d5e56df
imsoumen/HackerRank
/Challenges/Largest_Palindrome_Product.py
1,390
4.0625
4
""" Project Euler #4: Largest palindrome product ------------------------------------------------- Link: https://www.hackerrank.com/contests/wissen-coding-challenge-2021/challenges/euler004 ------------------------------------------------- A palindromic number reads the same both ways. The smallest 6 digit palindrome ...
c69a8d922c8c31914e3b1466a1357674142f1f10
Abhishekdm/text-duplicate-filter-from-file
/source.py
655
3.609375
4
def checkLine(rline): write_file = open('output.txt', 'r') for line in write_file: # elements passed as paramaters for lstrip will remove the matching elements from the leftside of the string wline = line.lstrip('0123456789.') if (wline == rline): return True read_file = op...
2c4cc0d4fab330c0b778f6706d1cc68512452773
ilyakolbafk/abc_dz3
/common.py
1,194
3.6875
4
# ------------------------------------------------------------------------------ # common.py - implementation of functions for common matrix. # ------------------------------------------------------------------------------ import random # ------------------------------------------------------------------------------ ...
11ef7233fc8493797b787e78e4ebd74dedc327f0
Lolhypocrisy/lpthw
/ex5.py
527
4.09375
4
name = 'Aaron A. Thibodeau' age = 28 height = 71 #inches weight = 265 #lbs eyes = 'Brown' teeth = 'White' hair = 'Black' kilos = weight / 2.2 height = height * 2.54 print(f"Let's talk about {name}.") print(f"He's {height} centimeters tall.") print(f"He's {weight} kilograms heavy.") print("Actually that's not too heavy....