blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7000aa9557c9ec4d01ff94c201d65fdaac96371c
uchenna-j-edeh/dailly_problems
/g_prep/largest_sum_contiguous_subarray.py
1,363
4
4
""" Taken from: https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ """ # Python program to find maximum contiguous subarray # Function to find the maximum contiguous subarray from sys import maxsize def maxSubArraySum(a,size): max_so_far = -maxsize - 1 max_ending_here = 0 ...
b36ea86ab103d2ff603e09e4bf77e2f088c3483d
uchenna-j-edeh/dailly_problems
/after_twittr/unique_char.py
531
4.125
4
""" Implement an algorithm to determine if a string has all unique characters What if you can not use additional data structures? example: input: 'uchenna' output: false """ def is_unique_char(text): #assuming it's ascii char which is 256 characters my_list = [] for i in range(256): my_list.append(...
e6aa1fc31893a65606e16abf84d605a55a52173a
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/is_str_equal.py
548
3.859375
4
# write a code to check if two str are equal def is_equal(s1, s2): for i in range(len(s1)): # if len(s2) - 1 >= i: # return False if len(s2) - 1 >= i or (s1[i].lower() != s2[i].lower()): return False for i in range(len(s2)): # if len(s1) - 1 >...
3536e46cfcc15206ca8083cf23fdf8d954eb11c6
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/first_missing_positve_int_in_array.py
1,363
3.5
4
""" Author: Uchenna Edeh Challenge: Given an array of integers, find the first missing positive in linear time and constant space. In other words, find the lowest positve int that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3,4,-1,1] should give 2...
8de8035244e78cbd3170e4b63931832c343cb35f
uchenna-j-edeh/dailly_problems
/after_twittr/split_arrs.py
530
3.859375
4
"""Given a list [1,2,3,10,9,8,4,5,7,6]. return half of entire sum """ def split_arr(my_list): # first find total sum # iterate until sum reaches half. Note the index # use the index to slice off the half total = sum(my_list) half = total // 2 total_so_far = 0 for i in range(len(my_list)): ...
cf8511288d210127ef288632db2b482defb3e9cf
uchenna-j-edeh/dailly_problems
/example_generator.py
328
3.796875
4
class Bank(object): # let's create a bank, building ATMs crisis = False def create_atm(self): while not self.crisis: yield "$100" hsbc = Bank() corner_street_atm = hsbc.create_atm() print(type(corner_street_atm)) print(dir(corner_street_atm)) print([corner_street_atm.__next__() for cash in ran...
6d2ff34fc6d3e357f9b23614a92e27c4647e6194
uchenna-j-edeh/dailly_problems
/ik_patterns/arrays/grump_bs_owner.py
1,686
3.671875
4
""" There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the e...
31dd876001bb403ef0b1adc4c49b123f9f12bb2d
uchenna-j-edeh/dailly_problems
/backtracking-algo/subset_sum.py
1,374
3.953125
4
""" Subset Sum | Backtracking-4 Subset sum problem is to find subset of elements that are selected from a given set whose sum adds up to a given number K. We are considering the set contains non-negative values. It is assumed that the input set is unique (no duplicates are presented). Exhaustive Search Algorithm for S...
7445049ea6d54ea088a55bc133574212d68e1be3
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/two_num_sum_to_k.py
1,063
3.953125
4
""" Author Uchenna Edeh given a list example [10, 4, 3,9, 7]. Figure if given a number k. There two numbers that sums up to k. If k is 7, then 10 + 7 is 17. Algo: As you take a pass at the list. Store each one is dictionary. Check if the difference between k and current number i is alredy in the dctionary. At the end, ...
728085d564db3266966877795e87d5d666734dbc
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/justify_text.py
3,330
4.03125
4
""" Author: Uchenna Edeh 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 each word. Pad...
44e056559e28ba778759365ed8b7f0ffc8425c3c
uchenna-j-edeh/dailly_problems
/g_prep/compress_decompress_str_v2.py
1,278
4.15625
4
""" The Challenge In this exercise, you're going to decompress a compressed string. Your input is a compressed string of the format number[string] and the decompressed output form should be the string written number times. For example: The input 3[abc]4[ab]c Would be output as abcabcabcababababc Other rules Numbe...
f58a28b4eefce45707dced9d8aaf1e1c902db670
uchenna-j-edeh/dailly_problems
/after_twittr/choose_team.py
1,633
3.890625
4
def teamFormation2(score, team_size, k): # Write your code here result = [] for i in range(team_size): len_score = len(score) first_elem = score[0:k] last_elem = score[len_score-k:] max_first_elem = max(score[0:k]) max_last_elem = max(score[len_score-k:]) ...
8ffe318d30bcfb7cef8e74c01e4e8ba5643a1c01
uchenna-j-edeh/dailly_problems
/after_twittr/is_rotated.py
429
4.21875
4
""" Assume you have a method isSubstring which checks if one word is a substring of another Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i e , “waterbottle” is a rotation of “erbottlewat”) """ def is_rotation(si, s2): if len(s1) == len(s2) and s2...
c6527a4e739dd6b18ff00f0e518b9094ca163ffd
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/comp_decomp_sol.py
809
3.65625
4
""" Author: Uchenna Edeh This work is copyright protected... translate '3[abc]4[ab]c' into abcabcabcabababc """ import sys final_str = '' def decompress(args): _digits = '' _characters = '' start_bracket = False original_str = '' #import pdb; pdb.set_trace() for i in args: if i.isdigi...
8148f1e27034c66c39d8be7b3def72c93ebe7b4f
uchenna-j-edeh/dailly_problems
/g_prep/rat_in_maze.py
4,100
3.71875
4
""" https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/ A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move...
891beae53c960a48450da28a82ffee690a119eb7
uchenna-j-edeh/dailly_problems
/math/pascal_triangle.py
973
3.859375
4
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """ from pprint import pprint as pp class Solution: def generate(self, numRows): pas_tri = [] for i in range(numRows)...
05a0c376530214349c31f147b072bc318b85253d
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/water_isles_simulation.py
1,546
4.09375
4
""" write a function that receives a position in 2 dimentions (x, y) array, which was intially initialized with 'o' (signals 'water'), the function changes the value/state of that position to 'x' (signals 'land') and returns the number of isles in the board for example, for 3x3 board, it will initially look like the f...
fa69f522a631c9e8d58cd210b5dce0dac5cc9b28
uchenna-j-edeh/dailly_problems
/recursion/problems/how_many_bst.py
897
4.09375
4
""" Write a function that returns the number of distinct binary search trees that can be constructed with n nodes. For the purpose of this exercise, do solve the problem using recursion first even if you see some non-recursive approaches. Example One Input: 1 Output: 1 Example Two Input: 2 Output: 2 S...
a4331531524b0d97cbf8e562b9049c045e90657f
uchenna-j-edeh/dailly_problems
/trees_algorithms/find_longest_path_file.py
1,811
3.875
4
""" Author: Uchenna Edeh Suppose we represent our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The dire dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. The string...
76bbe4c76c82dff2b4e96b3325d39593a241bec5
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/diagonal_matrix.py
678
3.625
4
""" Author: Uchenna J. Edeh Given a matrix, print the diagonals... """ def solution1(matrix): left_diagonals = [] right_diagonals = [] for i, val0 in enumerate(matrix): for j, _ in enumerate(val0): if i == j: tab = '-'*(i+1) print(tab + repr(matrix[i][j])...
fb94411d30eacea9849973e92c139f962c028602
prudhvirdy25/PythonProject
/CodeSnippets/16_Class_Objects.py
513
4.0625
4
# Python program to create classes and object instantiation class customer(): # A simple class # attributes custid=1234 custname="Prudhvi" # A sample method def getCustDetails(self): print("Customer ID is: ", self.custid) print("Customer Name is:", self.custname) # Driver cod...
a4f544a3cbe0dac590c7b8dd07b4b804892fb511
prudhvirdy25/PythonProject
/CodeSnippets/6_PythonSelectionIfElifElse.py
386
4.3125
4
# Python Program to use the selection based on if , elif and else num=13 if (num < 10): print ("Number is less than 10") elif (num <20): print ("Number is less than 20") elif (num <30): print ("Number is less than 30") elif (num <40): print ("Number is less than 40") elif (num <50): print ("Number is...
fe118bb60adfb64f9e519c354438254577cef33d
UlvacMoscow/InitialTasks
/example_with_cicle.py
214
3.765625
4
default = [1, 2] def add_list(lis, a): lis.append(a) return lis default = add_list(default, 5) print(default) default = add_list(default, 5) print(default) default = add_list(default, 5) print(default)
c3f691fc5d9cf5f2879f19a91f90ad8a18f68dc0
UlvacMoscow/InitialTasks
/filter.py
355
3.578125
4
# filter (func, iterable) def check_o(string): return 'o' in string.lower() lst = ['global', 'local', 'place', '34343', 'oooo'] new_lst = list(filter(check_o, lst)) print(new_lst) new_lst_2 = list(filter(lambda string: 'o' in string.lower(), lst)) print(new_lst_2) new_lst_3 = [string for string in lst if ...
269827b6030567e01ac6d643b04096ff2de09a30
UlvacMoscow/InitialTasks
/string_test.py
211
3.578125
4
s1 = 'string1' s2 = 'string2' print(s1 + s2) print(s1 * 20) #s[0] = 's' Error print(-11 // 10) # -2 print(-11 % 10) # 9 for x in range(5): #0,1,2,3,4 print(x) for y in range(1, 5): #1,2,3,4 print(y)
45ffc0668c497b04615d3da35d6c46f284960e76
AdamSierzan/python_poczatek
/week6/homeworks/homework_4/name_letters.py
495
3.96875
4
class NumberParsingError(Exception): pass def three_letters(): name = input("Napisz trzy piersze litery swojego imienia: ") name_len = len(name) if name_len < 3 or name_len> 3: raise ValueError("Wprowadz 3 litery, nie więcej nie mniej") print("Dziękuję, dobranoc") def run_example(): t...
a5c7362c4c4542d751a93a2b65878c46ebf21254
AdamSierzan/python_poczatek
/Week2/0.excercises/2.Constructors.py
2,138
4.03125
4
import random class Product: def __init__(self, name, category_name, price): self.name = name self.category_name = category_name self.price = price class Order: def __init__ (self, name, last_name, list_of_products = None): self.name = name self.last_name = ...
6af3411fd4eb7af5a00a82fbd5a83098b77f34bf
AdamSierzan/python_poczatek
/week6/lesson_3/example_9.py
1,031
4
4
# Możemy przenieść odpowiedzialność za przetworzenie tych danych z zewnątrz # do wnętrza funcji Handle_even_number class NumberParsingError(Exception): pass def handle_even_number(number_str): # jeśli przyjmiemy, że funcja odbiera stringa i dalej jest odpowiedzialna # za przetworzenie go wewnątrz sie...
dd57e01be8fd0ec7a1ace584ee5984c171d286d6
AdamSierzan/python_poczatek
/Week2/0.excercises/5.Dunder_methods.py
3,423
3.65625
4
import random class Product: def __init__(self, name, category_name, price): self.name = name self.category_name = category_name self.price = price def __str__(self): return (f"Product name{self.name} | Category{self.category_name} | Price{self.price}") def __eq__(se...
611665a7b1036451c1a68b3218059acf6fdeee5a
AdamSierzan/python_poczatek
/Week2/2.3 Function_as_object.py
1,299
3.90625
4
# W pythonie wszystko możemy uznać za obiekt # Także funkcję, jest to niezwykle przydatne gdyż możemy ją # póżniej przypisać do zmiennej def say_hello_name(name): print(f"hello {name}!") def run_example(): hello_name = say_hello_name hello_name("Adam") run_example() # Taka funkcja może też zwracać jak...
93c0c8398cf5b22842a85a236f81a2651b7b9a3b
AdamSierzan/python_poczatek
/week6/homeworks/Homework_lesson_3/main.py
1,040
3.671875
4
# Rozbuduj własną klasę wyjątku dodając do niej pole domyślną wiadomość i pole “allowed_limit” import data_generator from order import Order from product import Product from errors import ElementsInOrderLimitError def run_homework(): order_elements_on_limit = data_generator.generate_order_elements(products_to_ge...
06d5bc3e73f140d369e22a32e177f220eb0101c3
AdamSierzan/python_poczatek
/Week2/1.4 Constructors/1.7 Constructors_4.py
1,021
4.3125
4
class School: # constructor with the default argument - mind defualf list def __init__(self, name, students = None): self.name = name if students is None: students = [] self.students = students class Student: def __init__(self, first_name, last_name): ...
d34e3cac5aa15f9e9fc79c4beb4363bc8c498dba
AdamSierzan/python_poczatek
/week4/homeworks/lesson 3/Homework2.py
186
3.640625
4
favourite_sports = input("Type your favourite sports for me, separate them with spaces") favourite_sports = favourite_sports.split() print(favourite_sports) print(favourite_sports[::2])
d6036c33429330fe6c7a8d0e2f4bc82651237066
joshrands/MakeHarvard
/final/vis.py
866
3.859375
4
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # Create figure for plotting fig = plt.figure() ax = fig.add_subplot(1, 1, 1) xs = [] ys = [] # This function is called periodically from FuncAnimation def animate(i, xs, ys): # read from file file = open("data.csv", "r") p...
3296bae08dc384a6b79801cdbdfc11a97a211c9a
neo0311/pyannet
/src/pyannet/data_prep.py
17,791
3.828125
4
import numpy as np import matplotlib.pyplot as plt def LHCSampling(numSamples=int, numDimensions=int, numDivisions=int, dimensionSpans='array', plot=False): """ Implementation of Latin Hypercube Sampling The implementation works by dividing each dimensions equally like a square matrix. Then, like t...
ab96c8589accfa0f2642249c06234316a6929d4d
VictorFAL/PythonProjects
/Submarine/standard_version/Submarine.py
1,994
3.828125
4
class Submarine: def __init__(self, x = 0, y = 0, z = 0, direction = 0): self.__x = x self.__y = y self.__z = z self.__direction = direction self.__cardinal = ('NORTH', 'EAST', 'SOUTH', 'WEST') @property def x(self): return self.__x @x.setter def ...
2cebd9b016c9691d4113f38ce523478da66c6958
sfortson/random-scripts
/src/binary_search_trees/binary_search_trees.py
1,473
4.21875
4
"""Binary search tree algorithms""" def inorder_tree_walk(node): """Inorder tree walk :param node: node :type node: Node """ if node is not None: inorder_tree_walk(node.left) print(node.key) inorder_tree_walk(node.right) def tree_search(node, key): """Search in a tree...
a71b748f58f99e3978f97536dbf50712b7202210
durgaprasad-palanati-AI/python-topicwise-notebooks
/py-files/for-1.py
750
4.15625
4
#Collection-Based or Iterator-Based Loop ''' for i in <collection> <loop body> ''' # List of numbers numbers = [10,20,30,40,50] for num in numbers: print(num) # variable to store the sum sum = 0 # iterate over the list for num in numbers: sum = sum+num print("The sum is", sum) #for loop with else prin...
82a44022229d310d4b6e9832c3dd044bd9a8be20
muktagupta/MyFirstRepo
/Sum_of_two_numbers.py
113
3.84375
4
def sum(): a= input("First Number:") b= input("Second Number:") print"Sum of the Numbers:",a+b sum()
37a8583bf6c5e24423ba3881af1dea7e54acf69c
quantwizard-com/pythonbacktest
/pythonbacktest/strategy/strategystatemachine.py
6,411
3.5
4
# this class is indended to help building state machine # for trading strategies import abc from pythonbacktest.strategy import AbstractTradingStrategy class StrategyStateMachine(AbstractTradingStrategy): def __init__(self): # map between state names and handling methods self.__states_map = {} ...
79a8a69cdf4e2d168aef4ab845d83e6a7207cc97
quantwizard-com/pythonbacktest
/testcases/indicator_tests/datadifferencetests.py
1,631
3.546875
4
import unittest from pythonbacktest.indicator import DataDifference import math class DataDifferenceTests(unittest.TestCase): def test_number_set_individual_numbers(self): input_values_1 = [1, 4, None, 2, 8, 12, 14, None, 1] input_values_2 = [3, 1, None, 0, None, 3, 8, 6, 2] all_expecte...
f155e05ce5b8f086f76a54aa91080caed17a9f9e
pixxon/aoc-2016
/01/tests.py
3,504
3.640625
4
import unittest from solution import Direction, Position, first, second import os import sys class TestDirectionTurn(unittest.TestCase): def testLeftTurn(self): direction = Direction.NORTH direction = Direction.turn(direction, 'L') self.assertEqual(direction, Direction.WEST) direction = Direction.turn(directi...
aff7e40bdfebebe2e19baf555d470fbf960a7b02
limasclayton/census-income
/source/EDA.py
2,284
3.640625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.preprocessing import LabelEncoder # caminhos dataset_path = "input/census_income_dataset.csv" # lendo df = pd.read_csv(dataset_path) df.drop(['capital_loss', 'capital_gain'], inplace=True, axis=1) # Pr...
f6016ee17bcc51e7b72d62954f3dc8c3e6faf6ea
BatuhanAtabey/MyWorks
/Python/Work - Object Oriented/2- objectoriented2.py
938
3.734375
4
class Programmer(): def __init__(self, name, surname, number, salary, languages): self.name = name self.surname = surname self.number = number self.salary = salary self.languages = languages def viewDetails(self): print(""" Programmer Na...
11146067bd2c79802b366b8e53b957aba322d1f5
JoLeungGitHub/AdventOfCode2017
/Day11.py
2,169
3.859375
4
''' --- Day 11: Hex Ed --- Crossing the bridge, you've barely reached the other side of the stream when a program comes up to you, clearly in distress. "It's my child process," she says, "he's gotten lost in an infinite grid!" Fortunately for her, you have plenty of experience with infinite grids. Unfortunately for ...
ddfd59715f3601648dc2738fa17edbbeb626c0e9
Deonisii/work
/stepik/work6_1.py
97
3.6875
4
x=0 s=int(input()) while s!=0: x=s+x s=int(input()) if s==0: break print(x)
37015627d626e17cce7bfdfa9236a54d3ce3b254
Deonisii/work
/expression.py
222
3.703125
4
length = 5 # length- длина breadth = 2 # breadth - ширина area = length * breadth # area - площадь print('Площадь равна', area) print('Периметр равен', 2 * (length + breadth))
185f704760909d1b3f1337502140d85fcf2b54e7
diego40g/Advanced_Programming
/Labs/Phython/FirstDay/firstClass.py
911
3.765625
4
class Student: color = 'Red' class Meta: name = 'This is a metaClass' def __init__(self, _id, _name, _age,_cell_number): ##def __init__(self, _id, _name, _age): self.id = _id self.name = _name self.age = _age ##genera modificadores de estado 2 guion bajo ...
82c39399a88675c62e035b627e6cc04b554c7c59
brahma2625/calendar-by-user
/calendar.py.py
116
3.859375
4
import calendar y = int(input("enter the year")) m = int(input("enter the month")) print(calendar.month(y,m))
8739956a167b275c6bc9d76d7c10c18231326b3a
sunxiaolei/python-note
/note/day5.py
2,838
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #返回函数 Python中,一切皆对象!!! def l_sum(l): def lazy_sum(): return sum(l) return lazy_sum l = [1,2,3,4] f = l_sum(l)#返回的是函数 print f()#调用函数 #闭包 def count(): fs = [] for x in range(1,4): def f(): return x fs.append(f) return fs f1,f2,f3 = count() print f1(),f2(),f3()...
85d0de1d1809f7b64bd0af7eada1c30a0124f785
sunxiaolei/python-note
/note/day4.py
1,736
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #map()函数 #接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回 def format_name(s): return s[0].upper()+s[1:].lower() print map(format_name, ['adam', 'LISA', 'barT'])#['Adam','Lisa','Bart'] print('\n') #----------------------------------------------------------...
f671ab17d71114bce110afd438506249d014da35
chrishuskey/Intro-Python-I
/src/10_functions.py
752
4.28125
4
""" Program that asks for a number from the user, and returns whether that number is even or odd. """ # Write a function is_even that will return true if the passed-in number is even. def is_even(number:int): """ Determines if the input integer is an even number or not. """ if number % 2 == 0: ...
9ffe2bc5522321e14e72f318003fd5f6ad0632d5
HoracioXel/janeDroidAssistant
/paciencia.py
1,754
3.78125
4
# -*-coding:utf8;-*- # Michel Horacio # Paciência assim como outros estados vão compor um estado emocional totalizando 100% import random as r class Paciencia(): paciencia="" # Setando nível de paciência def __init__(self): self.paciencia=r.randrange(2,5) # 20-01-18 Quantas vezes uma mesma repos...
0af5ddb56880b9ddd29ebc143b33333075e81881
honeykpatel/DSA-Notes
/Arrays/Problem6.py
405
3.546875
4
a = [2,5,9,6,9,3,8,9,7,1] #initialize fast and slow pointer fast = a[0] slow = a[0] while True: slow = a[slow] #slow will take one step fast = a[a[fast]] #fast will take two steps if slow==fast: #collision break fast = a[0] #move fast to initial while True: slow=a[slow] #take one step fa...
9796539627328ed6ccf2742cb1cc75e243e555fa
Meliowant/python_class
/03/Lect/01_if_example.py
230
3.921875
4
a = input("Введіть перше число: ") b = input("Введіть друге число: ") if (a + b)%2: print("Введено парне число.") else: print("Введено непарне число.")
6cce1d75ddfc50df519d89e75d8cb37b279cf71a
yinweiwen/study
/silabs/src/iot-led/LED.py
1,257
3.75
4
from machine import PWM from machine import Pin class Led(): """ 创建LED类 """ def __init__(self, rpin, gpin, bpin, freq=1000): """ 构造函数 :param pin: 接LED的管脚,必须支持PWM :param freq: PWM的默认频率是1000 """ self.pin_red = Pin(rpin) self.pin_green = Pin(gpin) ...
5d5d27e0caac16fdcfcea6e3c4f8eea4a337335e
slsavin/magic_list
/main.py
470
3.6875
4
from dataclasses import dataclass @dataclass class Person: age: int = 1 class MagicList(list): def __init__(self, cls_type=None, *args, **kwargs): super().__init__(*args, **kwargs) def __setitem__(self, key, value): if len(self) == 0: self.append(value) else: ...
d071d9de2e7f86264516372985cf57db6cf87bbe
xiaooodd/CS362-H7
/leapyear.py
264
4.125
4
def is_Leap(y): if y % 400 == 0: return "Leap year" elif y % 100 == 0: return "Not leap year" elif y % 4 == 0: return "Leap year" else: return "Not leap year" year = int(input("Enter a year:")) print(is_Leap(year))
90074cd7241bc1a6220bd9d5cc2b8a8882dd91b0
SophieO1970/Password-Locker
/user.py
555
3.640625
4
import pyperclip #for copying and pasting to our clipboard class User: ''' Create class that generates new instances of users. ''' user_list = [] def __init__(self, username, password): ''' Method that defines the properties of a user. ''' ...
1539d6ab08bd04f00e449fc4b7d77323612425f5
jgumoes/Project-Euler
/5.py
226
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 26 12:11:47 2017 @author: Jack project euler question 5 """ def check(num): c = 20 while c > 0: if num%c != 0: print c c-=1 return num
6880d8fbf9519c250af34e4b3a50265a307c379c
marat2183/Useful_tips
/merge_sort.py
560
3.71875
4
def merge(a, b): i = 0 j = 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:] + b[j:] return result def merge_sorti(a): if len(a) > 1: ...
54371fc70e5788498233030aac1467ca9ff7ef99
kanxul/masterarbeit
/oops_basics_02.py
741
3.859375
4
# OOP in Pyhton class My_Calc: # Class Attributes/Variables # Class Constructor/Initializer (Method with a special name) def __init__(self, num1, num2): # Object Attributes/Variables self.num1 = num1 self.num2 = num2 # Methods def total(self): ...
e08469c946314b2fb5fd5940d9e2b32c106f1624
faizansarfaraz/PIAIC-Projects.
/marksheet.py
903
4.25
4
print("Marksheet") print() name=input("Enter Student Name:") roll_num=input("Enter Roll Number:") phy_marks=int(input("Enter Physics Marks:")) chem_marks=int(input("Enter Chemistry Marks:")) math_marks=int(input("Enter Math Marks:")) urdu_marks=int(input("Enter Urdu Marks:")) eng_marks=int(input("Enter English Marks:")...
9a49a340a7bc892d0b411e7dc221af7781be39bc
elemosjr/trab1_estr_dados
/py/ex2.py
964
3.890625
4
#!/bin/python ## Exercício 1.8 import re def main(): valor = int(input("Qual o valor? ")) notas_valor(valor) def notas_valor(valor): resto = valor quant = [] nota = [100,50,10,5,2,1] for i in nota: quant.append(int(resto/i)) resto = valor%i if resto == 0: break quant += list(map...
901e93d340670bd91b03489cc10e4eabca983dd1
ManideepNadimpelli/Python_ICP1
/ICP1_replace.py
160
3.640625
4
Uinput = input("Enter something...") Eword = input("Enter which word to replace") Rword = input("Enter replace word") print(Uinput.replace(Eword, Rword))
cec0b17e979106d62e5207992a880589f57a1157
Jing-Yan/record-python
/python 基础算法/二分查找.py
593
3.84375
4
# -*- coding:utf-8 -*- def BinarySearch(arr, key): min = 0 max = len(arr)-1 if key in arr: while True: mid = (min + max) // 2 if arr[mid] > key: max = mid - 1 elif arr[mid] < key: min = mid + 1 elif arr[mid] == key: ...
6fb21a5d117f7b4a9a373353107a7705f1d158b9
jackwallace180/GamesDBHW
/run.py
2,745
3.8125
4
from game_class import * from database_class import * conn_db =database( 'localhost,1433', 'GamesMarketplaceHW', 'SA', 'Passw0rd2018') print('Welcome to Games! Games? Games...') input1 = int(input( 'press 1 to list all games, 2 to find a game, 3 to add/delete a game, press 4 to update price, press 5 to exit ')) w...
41357bb12afc7cb165d872d10b1ceaa7f3636c4d
deartc/Fitnesspythonproject
/dancestepsthree.py
938
3.9375
4
import random ### Here you must define random for use. Otherwise, python3 will return as "radiant" not defined player = input("Player, choose your dance: ").lower() rand_num = random.randint(0,2) if rand_num == 0: computer = "bolero" elif rand_num == 1: computer = "hustle" else: computer = "samba" ...
bd71eef8806b68e41f6eec95a67eaa67a8271922
nikhilcusc/HRP-1
/UnNecCompliProblems/UNCP4.py
1,278
3.78125
4
''' You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump. The second kangaroo starts at location x2...
f64acc6f42539374697ba12ec8b8ea19e4ac6f2d
nikhilcusc/HRP-1
/GeneralCode/Sort/heapSort1.py
565
3.78125
4
import GeneralCode.Heap.popFromHeap as HEAP def heapS(arr): #this stores the sorted array in another Something does not work with last list endInd = len(arr) arr = HEAP.buildMaxHeap(arr) SortedL=[] while endInd>1: [a, maxEle] = HEAP.popMaxHeap(arr) #print(a, maxEle) #SortedL.a...
8debc797057846af2db8ec07b4e9dc5c9c5134ef
nikhilcusc/HRP-1
/GeneralCode/andInt.py
432
3.625
4
#useful in traversing BIT (Binary Indexed Tree) for i in range(0,21): print(i,' & ',-i,' i&-i:',i&-i,'\tParents i-=i&-i',i-(i&-i),'\tChild (next branch) i+=i&-i',i+(i&-i)) def getSum(BITree,index): gsum=0 while index>0: gsum+=BITree[index] index-=index&(-index) return gsum def updateBI...
bc4959b0fbeb1485fb6082d3eff062e01ba10569
nikhilcusc/HRP-1
/UnNecCompliProblems/UNCP10.py
990
4.21875
4
''' Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day. Given a range of numbered days, [i..j...
b3ec2350b806c47b122dbd5ecf588ec34a27e045
nikhilcusc/HRP-1
/ProbSol/DP/abb.py
1,872
3.84375
4
''' https://www.hackerrank.com/challenges/abbr/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dynamic-programming ''' ''' def abbreviation(a, b): def compareChars(c1,c2): val=False if ord(c1)-32 == ord(c2): val=True return val whi...
c0f7bfd346c8e500cfad4e8bc077027c67db0f3c
nikhilcusc/HRP-1
/GeneralCode/LCM.py
464
3.765625
4
def LCM(x,y): # x and y should be positive if x>0 or y>0: greater=0 if x>y: greater = x elif x==y: return x else: greater = y while 1: if greater%x==0 and greater%y==0: return greater greater+=1 ...
4b2316a702edcf698e00a3a4472fe7eb1c502c17
nikhilcusc/HRP-1
/GeneralCode/Sort/quickSort1.py
782
3.90625
4
#divide the array in 3 parts #first sublist which is smaller than pivot, second equal and third which is larger def divQuickSort(arr): #uses extra mem pivot=arr[0] temparr=[] for i in range(len(arr)): if arr[i]<pivot: temparr.insert(0,arr[i]) else: temparr.append(arr...
ba82a4ed4c640d021f0e50d43f3d4bf7869a5854
nikhilcusc/HRP-1
/UnNecCompliProblems/UNCP9.py
2,125
3.5
4
''' Lena is preparing for an important coding competition that is preceded by a number of sequential preliminary contests. Initially, her luck balance is 0. She believes in "saving luck", and wants to check her theory. Each contest is described by two integers, L[i] and T[i]: L[i] is the amount of luck associated with...
342744341855de267b4969acc235de82c7bf2ae1
nikhilcusc/HRP-1
/GeneralCode/Sort/quickSortPL.py
632
3.796875
4
def divQuickSortInP(arr,low,high): #inplace, pivot low #pivot index pi=low pivot = arr[pi] for i in range(pi+1,high+1 ): if arr[i]<=pivot: temp=arr[i] for i1 in range(i,pi,-1): arr[i1] = arr[i1-1] arr[pi] = temp #print(temp, ar...
b25f40f83b5e67c7800432625a7bb1d13f7b1a42
nikhilcusc/HRP-1
/UnNecCompliProblems/UNCP2.py
1,425
4.5625
5
''' Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, , or a downhill, step. Gary's hikes start and end at sea level and each step up or down represents a ...
2614640f869977311e34581df3b3c55552283fb1
nikhilcusc/HRP-1
/ProbSol/minmax.py
646
4.03125
4
''' Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers. ''' def miniMaxSum(arr): # with copy time: O(n), space O(n) m = 4 ...
a41a7318be422c37e0e9c178c4d99d825586a8a7
nikhilcusc/HRP-1
/UnNecCompliProblems/UNCP3.py
816
4.1875
4
''' HackerLand University has the following grading policy: Every student receives a grade in the inclusive range from 0 to 100 . Any grade less than 40 is a failing grade. Sam is a professor at the university and likes to round each student's grade according to these rules: If the difference between the grade and...
283e205b601f61a2931fd6b8f9a8009d37904b6c
bot-coder101/Binary_Operations
/UpDown_Counter.py
2,288
3.546875
4
import sys def subtract(num_1,num_2): #Two's complement of number 2 num2_tc=twos_comp(num_2,one) #Addition of tc and num_1 diff=bin_addition(num_1[::-1],num2_tc[::-1]) omit_carry='' for i in range(1,len(diff)): omit_carry+=diff[i] return omit_carry def ones_comp(bin_value): new_num='' for i in range(len(bi...
67e04b84411fb50e9afcff5a1ddf0cc41898568c
bot-coder101/Binary_Operations
/Bitwise_Addition.py
1,777
3.859375
4
def binary(number): bin_value='' while(number>0): bin_value+=str(number%2) number=number//2 if number==1: bin_value+='1' break return bin_value[::-1] def append_zeros(number,count): new_num=''.join(('0'*count,number)) return new_num def decimal(bin_value): result=0 for i in range(len(bin_value)): ...
11495d35ed3e3af88a9e9f46eddeca72ffcffd23
Pierina0410/Palacios.Ulloque.PierinaYasmin
/5.py
337
3.6875
4
#Calculadora 4 #este programa nos ayudara a calcular la distancia #declaracion de variables velocidad, tiempo= 0 , 0 #calculadora velocidad=10 tiempo=20 distancia=(velocidad*tiempo) #mostrar datos print("el valor de velocidad=",velocidad) print ("el valor de tiempo=",tiempo) print ("el valor de distancia=",d...
c2d9c37378e47526bfc0d6b7a5844fd22f3e69bd
smritiyadav17/games-in-python
/numberGuessing.py
947
4.1875
4
""" Number Guessing Game ---- Console Game """ #Step 1: # Generate a random number between 0 and N. """ random.randrange(start, stop[, step]) random.randint(start, stop, [,step]) """ print("Welcome to Number Guessing Game") import random randomNumGen = random.randint(1,10) print(randomNumGen) #Step...
6b0e960e31a0cd4d1a3d8fb242ba301f6f32be7f
emptycastlepark/TIL
/Algorithm/BOJ/14499. 주사위 굴리기.py
1,026
3.5625
4
dice = [0] * 6 def move(x, y, c): if board[x][y] == 0: board[x][y] = dice[5] else: dice[5] = board[x][y] board[x][y] = 0 print(dice[2]) N, M, x, y, K = map(int, input().split()) board = [None] * N for i in range(N): board[i] = list(map(int, input().split())) command = list(map(...
9bce7647d6b7c660211ed252c770b55302baad46
kyon0304/python-challenge
/challenge_3.py
424
3.78125
4
# gives http://www.pythonchallenge.com/pc/def/linkedlist.php #! /usr/bin/env python import re def re_find(s): pattern = re.compile('[^A-Z][A-Z]{3}[a-z]{1}[A-Z]{3}[^A-Z]') return pattern.findall(s) if __name__ == '__main__': clue = '' with open("challenge_3_clue") as f: clue = f.read() can...
4145311a670d20e55a2b8ff407e4d48d5f501613
rblack42/sphinxcontrib-pylit
/sphinxcontrib/pylit/cli.py
436
3.53125
4
import click def about_me(your_name): return "The wise {} loves Python.".format(your_name) class ExampleClass: """An example docstring for a class definition.""" def __init__(self, name): self.name = name def about_self(self): return "I am a very smart {} object.".format(self.name)...
65e3eaeacb7580fb0db74019420b755aa9e96067
mquabba/CP1404-Pracs
/Prac 4/quick_picks.py
567
4.0625
4
import random NUMBERS_PER_LINE = 6 MINIMUM = 1 MAXIMUM = 45 def main(): The_number_of_quick_picks = int(input("How many quick picks? ")) for i in range(The_number_of_quick_picks): quick_pick = [] for a in range(NUMBERS_PER_LINE): number = random.randint(MINIMUM, MAXI...
2d6bfffd9d7df801ba943d33aad7129f0e61e206
JonMunoz/CS2302
/draw_squares.py
1,630
4.09375
4
#Jon Munoz #CS2302 Data Structures #Lab 1 #Instructor:Olac Fuentes #TA:Anindita Nath #Last Modified 2/8/19 import numpy as np import matplotlib.pyplot as plt def draw_squares(ax,n,p,w): if n>0: i1 = [1,2,3,0,1] q = p*w + p[i1]*(1-w) ax.plot(p[:,0],p[:,1],color='k') draw_squares(ax,...
aab89ea6aa71d18a3b729b6b5bea1f349d056282
lanyshi/python_database
/mongodb_app.py
1,148
3.671875
4
import pymongo # Connect to database and collection client = pymongo.MongoClient("mongodb://localhost") db = client["my_db"] col = db["pet"] # Insert one document into collection doc = {"name": "Coco", "owner": "Amanda", "species": "Cat", "sex": "F"} x = col.insert_one(doc) # Print the _id of the inserted doc print(x...
37616e648a7225cd9bf261b7576f8ec92380d2db
omputle/image2pdf
/rename.py
512
3.921875
4
import os class Rename(): """ This class renames images in target folder for easy sorting """ def __init__(self, target_folder): os.chdir(target_folder) def rename_images(self): images = os.listdir() images.sort() for f in images: f_name, f_ext = os....
eca41f28ace31d071d73e0d4858f4855600d56b7
tt810/HeuristicProblemSolving
/TravelingSalesmanProblem/tsp.py
9,684
3.8125
4
import math import copy import itertools import sys from collections import deque def makeGraph(fileName): def reader(): """ Read the text file and process it """ listCity = [] with open(fileName, 'r') as f: listCity = [line.split(' ') for line in f.read().split('\n')] return filter(lambda x: x!=[''],...
d43abe5f7b4920ba078160e36586a46189dc794a
PyDataWorkshop/BokehWorkshop
/00-HelloWorld/01-A-WigglyLine.py
547
3.53125
4
# Import Bokeh modules for interactive plotting import bokeh.io as bi import bokeh.plotting as bp # Set up Bokeh for inline viewing bi.output_notebook() # Set up plot p = bp.figure(width=650, height=400, x_axis_label='x', y_axis_label='dy/dx', tools='pan,wheel_zoom,box_zoom,resize,reset') # Populate gl...
e13b8ae54b18e3f54daacb4f37f4ea00cdf971cc
ilyxenc/simple-RSA-signature
/functions.py
4,191
3.578125
4
import random import math import sys import hashlib sys.setrecursionlimit(1500) # генерация большого простого числа def randPrime(n): rangeStart = 10 ** (n-1) rangeEnd = (10 ** n) - 1 while True: num = random.randint(rangeStart, rangeEnd) if isPrime(num): return num # определен...
fdf4727ab6ca4dde9ed8494e3e04fd2c5f8c7e99
mateusz-wasilewski-it/enigma_pattern_task
/Database.py
863
3.75
4
import _sqlite3 class Database: def __init__(self): self.conn = _sqlite3.connect("flick_images.db") self.cursor = self.conn.cursor() def createTable(self): with self.conn: self.cursor.execute("""CREATE TABLE images_urls ( url text ...
a77143a6b18e2f3b3052406958a0ec3ac69ea22b
rparthas/Repository
/Python/replaceWords.py
1,157
3.84375
4
class Trie: def __init__(self): self.isEndOfWord = False self.children = {} self.value = None def insert(self, word): node = self for char in word: if char not in node.children: node.children[char] = Trie() node.children[char]...
bd6a739b27f393ec3882d27a2f5660aaf3bd6cbf
rparthas/Repository
/Python/dijikstra.py
1,707
3.59375
4
import functools class Edge: def __init__(self, node1, node2, weight): self.node1 = node1 self.node2 = node2 self.weight = weight def __str__(self): return self.node1 + "->" + self.node2 + "=" + str(self.weight) edges = {"A": [Edge("A", "B", 5), Edge("A", "C", 2)], ...
53d3d87772f0dfe0d40617501649d195b72f4824
mjtv128/codework
/stack/reverse_string.py
403
3.953125
4
from stack import Stack def reverse_string(stack, input): for i in range(len(input)): stack.push(input[i]) new = '' # for i in range(len(input)): # new.append(stack.pop()) # print('new', ''.join(new)) while not stack.is_empty(): new += stack.pop() return new ...
eafcf04b2871bf8a03b0992f5b6bb26cde09a494
Eloiza/Naive-KNN
/my_knn.py
1,761
3.5
4
#calcula distancia euclidiana entre dois vetores def euclidean_distance(v1, v2): total = 0 for i in range(len(v1)): middle_sum = (v1[i] - v2[i]) total += middle_sum**2 return total**(0.5) #encontra as k amostras mais proximas da amostra X_test def find_neighbour(X_train, y_train, sample, k): k_nearestn = [...
c0061e887beca254b57cf119f8654c0d64732c76
ChristopherHaydenTodd/ctodd-templates
/python/general/executable/execute_script.py
2,953
3.5625
4
#!/usr/bin/env python3 """ Purpose: Do Something Steps: - Do Something Usage: execute_script.py [-h] --required-arg REQUIRED_ARG [--optional-arg OPTIONAL_ARG] [--optional-required] Example Script Template optional arguments: ...