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
d05beffef5f7bfc91922e44ce4091c080d7ed63e
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/python-nosetest-class-master/words.py
1,705
3.5625
4
from collections import defaultdict _punct = '.,;?:' def _normalize(fragment): fragment = fragment.lower() while len(fragment) > 0 and fragment[-1] in _punct: fragment = fragment[:-1] while len(fragment) > 0 and fragment[0] in _punct: fragment = fragment[1:] return fragment def numwords...
87034a3b828c0767c200a6f834524a6c9eeb6eb3
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Test_Mock_Same_Patch.py
2,922
3.765625
4
# Python Test Mock # unittest.mock mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stu...
98b04c908b9ee96b5460f6265780590ac4a969e8
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/156_merge_intervals.py
595
3.71875
4
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ c_ Solution: ___ merge intvs """ :type intvs: List[Interval] :rtype: List[Interval] """ ans # list __ n.. intvs: ...
86070cd7fe5080766149afef78c3059e13c1d18a
syurskyi/Python_Topics
/012_lists/examples/Python 3 Most Nessesary/8.6.Listing 8.6. An example of using the filter () function.py
409
3.921875
4
# -*- coding: utf-8 -*- def func(elem): return elem >= 0 arr = [-1, 2, -3, 4, 0, -20, 10] arr = list(filter(func, arr)) print(arr) # Результат: [2, 4, 0, 10] # Использование генераторов списков arr = [-1, 2, -3, 4, 0, -20, 10] arr = [ i for i in arr if func(i) ] print(arr) ...
9668ed9b59dffd211b71d671e99bff049ca83215
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/232 Implement Queue using Stacks.py
1,349
4.28125
4
""" Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You must use only standard operations of a stack -- which means only...
99e0d1b96397498ae343b4eae4e4b23307e59dbe
syurskyi/Python_Topics
/020_sequences/examples/ITVDN Python Essential 2016/12-mutable_sequences_methods.py
365
4.25
4
""" Примеры других общих для изменяемых последовательностей методов. """ sequence = list(range(10)) print(sequence) # Неполное копирование copy = sequence.copy() # copy = sequence[:] print(copy) # Разворот в обратном порядке sequence.reverse() print(sequence)
46b95cecb37be01d2c4ced998e143f9f08a7b9b2
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-13-convert-dict-to-namedtuple-json.py
2,029
4.1875
4
""" TASK DESCRIPTION: Write a function to convert the given blog dict to a namedtuple. Write a second function to convert the resulting namedtuple to json. Here you probably need to use 2 of the _ methods of namedtuple :) """ ____ c.. _______ n.. ____ c.. _______ O.. ____ d__ _______ d__ _______ j__ # Q: What is the ...
35fdbbaaeae2b4f71a1e2b719034235c6918b130
syurskyi/Python_Topics
/100_databases/003_mongodb/_exercises/exercises/w3schools_Python MongoDB/002_Creating a Collection.py
954
4.0625
4
# # Creating a Collection # # To create a collection in MongoDB, use database object and specify the name of the collection you want to create. # # MongoDB will create the collection if it does not exist. # # _____ ? # # myclient _ ?.M.. "mongodb://localhost:27017/") # mydb _ ? "mydatabase" # # mycol _ ? "customers" # ...
3fe411003aa7831e2d946ab7e657c9297d6c352d
syurskyi/Python_Topics
/120_design_patterns/001_SOLID_design_principles/examples/Isp/i.py
1,127
3.78125
4
""" Interface Segregation Principle bad - Circle class does not need draw_rectangle and draw_square. if we want to add new shapes, we have to change all classes. """ class IShape: def draw_square(self): raise NotImplementedError def draw_rectangle(self): raise NotImplementedError def ...
93ab25cc25e52713114cf3182a7b9b6cf3ab10d0
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Heap/KthSmallestElementInASortedMatrix.py
7,123
4.0625
4
""" Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 1...
6331a1ab8839a37e0f4e26c238395af367e109b1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/230 Kth Smallest Element in a BST.py
916
3.5625
4
# -*- coding: utf-8 -*- """ Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? H...
c44c2a5714d92fc881306db6cdde4e3ef4c06dd3
syurskyi/Python_Topics
/045_functions/008_built_in_functions/enumerate/_exercises/templates/004.py
1,981
3.953125
4
# # Enumerate a List # # L = ['apples', 'bananas', 'oranges'] # ___ idx val __ ? ? # print("index is $ and value is $" ? ? # # # # index is 0 and value is apples # # index is 1 and value is bananas # # index is 2 and value is oranges # # # # Enumerate a Tuple # # t = ('apples', 'bananas', 'oranges') # ___ idx val __...
e21e74189a2b880b6c0a2c8fdeb7ef3663708645
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Magic_Mock.py
1,858
3.796875
4
# Python Unittest # unittest.mock mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stub...
1af8cd8a831f0b63b8c77d2ff35f4ec3e6a1b3f8
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 60 - MergeSortLists.py
1,158
4.15625
4
# Merge Sorted Lists # Question: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. # Solutions: class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param two ListNo...
373b2e600995ec2dc414eee59493a2cbe93a118c
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/113_v3/non_ascii.py
313
4
4
def extract_non_ascii_words(text): """Filter a text returning a list of non-ascii words""" words = text.split() result = [] for word in words: try: word.encode('ascii') except Exception as e: print(e) result.append(word) return result
56ff56c9d7977a59184e97c87a15187edbd1a63f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/520 Detect Capital.py
1,228
4.375
4
#!/usr/bin/python3 """ Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only t...
392e525fb8bacb0f76c87b70bf0782b3fd60f4fe
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/029_martins_iq_test/save1_nopass.py
504
3.828125
4
def get_index_different_char(chars): correct = [correct for correct in str(chars) if correct.isalnum()] not_correct = [not_correct for not_correct in chars if not str(not_correct).isalnum()] if len(correct) > len(not_correct): not_c...
b7cd9d35064542f85f302b3c2ab375a447497601
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Test_Mock_Partial_Mocking.py
1,883
3.6875
4
# Python Test Mock # unittest.mock � mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of st...
2a2dd9b0637c9f1d82e18a5e55dc77f662dc1a3a
syurskyi/Python_Topics
/125_algorithms/001_arrays/_exercises/_templates/Array Sequences/Array Sequences Interview Questions/PRACTICE/Anagram Check .py
1,906
4.09375
4
# # %% # ''' # # Anagram Check # ## Problem # Given two strings, check to see i_ they are anagrams. An anagram is when the two strings can be written using # the exact same letters (so you can just rearrange the letters to get a different phrase or word). # For example: # "public relations" is an anagram of "crap b...
254755cc6671c42fd959d4425deadbf69fce1780
syurskyi/Python_Topics
/085_regular_expressions/_exercises/templates/Python 3 Most Nessesary/7.4. Lack of binding to the beginning or end of the line.py
595
3.59375
4
# # -*- coding: utf-8 -*- # # Если убрать привязку к началу и концу строки, то любая строка, содержащая хотя бы одну # цифру, будет распознана как число # # _______ __ # Подключаем модуль # p = __.c.. _ 0-9 1? .2? # 1.One or more occurrences | 2.Makes a period (dot) match any character, inclu...
ccfc3515015748270dd73cedbff571fd2750ca6b
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/exercises/Python_3_Deep_Dive_Part_4/Section 02 - Classes/03-Callable_Class_Attributes.py
771
3.71875
4
# # %% # ''' # ### Callable Class Attributes # ''' # # # %% # ''' # Class attributes can be any object type, including callables such as functions: # ''' # # # %% # c_ Program # language _ 'Python' # # ___ say_hello # print(_*Hello from ?.l.. !* # # # %% # print ?.-d # # # # # %% # # ''' # # As we can ...
042c2a04af69bfaab7f5fbe77793c41d4e89d9f1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_Python_Exercises_Evaluate_and_Improve_Your_Skills/Exercise 89 - Database Filter NUKE.py
458
3.984375
4
#Please download the database file database.db. The file contains a table with 50 country names along with their area in square km and population. #Please use Python to print out those countries that have an area of greater than 2,000,000. _______ sqlite3 conn sqlite3.connect("database.db") cur conn.cursor() cur.exe...
b8657fd9854b6e406dec4ae63bf4ce1336df307d
syurskyi/Python_Topics
/121_refactoring/Code_Smells/Bloaters/Long_Method/Replace_Temp_with_Query/005.py
1,080
3.9375
4
# Problem def calculateGrade(): totalScore = midtermScore + finalScore + assignmentScore averageScore = totalScore / 3 if averageScore >= 90: grade = "A" elif averageScore >= 80: grade = "B" elif averageScore >= 70: grade = "C" elif averageScore >= 60: grade = "...
2590ab4756df40525216d2a169c509dacac2ba36
syurskyi/Python_Topics
/070_oop/004_inheritance/examples/super/Understanding Python super()/004.py
807
3.59375
4
class A(object): def __init__(self, i, **kwargs): super(A, self).__init__(**kwargs) self.i = i def run(self, value): return self.i * value class B(A): def __init__(self, j, **kwargs): super(B, self).__init__(**kwargs) self.j = j def run(self, value): retu...
d1cca3de84367b208ee27acfe410ffec6a4f69f5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/100_SameTree.py
725
3.671875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None c.. Solution o.. ___ isSameTree p, q """ :type p: TreeNode :type q: Tre...
0e260d563115adc1074d6e6135c4d62085b1f48f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+13 How to create quadratic Equation.py
331
4.34375
4
____ math _______ sqrt x float(input("Insert x = ")) y float(input("Insert y = ")) z float(input("Insert z = ")) a y*y-4*x*z __ a>0: x1 (-y + sqrt(a))/(2*x) x2 (-y - sqrt(a))/(2*x) print("x1 = %.2f; x2 = %.2f" % (x1,x2)) ____ a__0: x1 -y/(2*x) print("x1 = %.2f" % x1) ____: print("No ro...
d30652b267569247f9d3c6a1f20ad03f3f902250
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/UnitTesting-master/Proj4/ListsAndTuples/listAndTuples.py
2,218
4.375
4
______ ___ ______ timeit # https://www.youtube.com/watch?v=NI26dqhs2Rk # Tuple is a smaller faster alternative to a list # List contains a sequence of data surrounded by brackets # Tuple contains a squence of data surrounded by parenthesis """ Lists can have data added, removed, or changed Tuples cannot change. Tu...
fcac989dc3c9d7454b7f7cf9d4caf0d977144993
syurskyi/Python_Topics
/110_concurrency_parallelism/_examples/Learn Parallel Computing in Python/005_barriers/matrix_multiply_single.py
1,099
3.609375
4
import time from random import Random matrix_size = 200 # matrix_a = [[3, 1, -4], # [2, -3, 1], # [5, -2, 0]] # matrix_b = [[1, -2, -1], # [0, 5, 4], # [-1, -2, 3]] matrix_a = [[0] * matrix_size for a in range(matrix_size)] matrix_b = [[0] * matrix_size for b in range(matrix...
a51e653d17ccdefa013f6915d43344c176e57fb1
syurskyi/Python_Topics
/012_lists/_exercises/_templates/ITVDN Python Starter 2016/15-list-traversal.py
213
3.578125
4
# -*- coding: utf-8 -*- # # Создание списка чисел # my_list = 5, 1, 5, 7, 8, 1, 0, -23 # # # Вывод квадратов этих чисел # ___ x __ ? # print '@ ^ 2 = @'.f.. x, x ** 2
4a920bacfcb09c3f17ccc27d7e49ed3415f7240d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BreadthFirstSearch/199_BinaryTreeRightSideView.py
793
3.84375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None c.. Solution o.. # Breadth First Search ___ rightSideView root __ n.. root: ...
ff55229df681d9bb62d831cec5b66fe7ec203c1c
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 12 Regex/remove_parenthesis_solution.py
772
3.6875
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # Write a Python program to remove the parenthesis area in a string. # # Input # ["example (.com)", "w3resource", "github (.com)", "stackoverflow (.com)"] # # Output # example ...
98d01ea24418a470927f2b7cfda199f8c7a15a83
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/TwoPointers/75_SortColors.py
734
3.640625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def sortColors(self, nums): len_n = len(nums) # pos_put_0: next position to put 0 # pos_put_2: next position to put 2 pos_put_0 = 0 pos_put_2 = len_n - 1 index = 0 while index <= pos_put_...
ed2c72f3d8b7d3da15b93c53f0f8a83d5607d12f
syurskyi/Python_Topics
/014_tuples/examples/Learning Python/009_001_Tuples in Action.py
187
4
4
print((1, 2) + (3, 4)) # Concatenation # (1, 2, 3, 4) print((1, 2)) * 4 # Repetition # (1, 2, 1, 2, 1, 2, 1, 2) T = (1, 2, 3, 4) # Indexing, slicing print(T[0], T[1:3]) # (1, (2, 3))
c035fcefec027a5b8e1c619b49d09c7c96cbc330
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/beginner-bite-169-simple-length-converter.py
1,245
4.34375
4
''' Your task is to complete the convert() function. It's purpose is to convert centimeters to inches and vice versa. As simple as that sounds, there are some caveats: convert(): The function will take value and fmt parameters: value: must be an int or a float otherwise raise a TypeError fmt: string containing either ...
6875e7dcbedb3d6dff5c4554e0659921519f0224
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/111_MinimumDepthofBinaryTree.py
745
3.859375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None c.. Solution o.. ___ minDepth root """ :type root: TreeNode :rtype: int...
4e4ffc46df598ca4b6990664d765f2ee36ca9c63
syurskyi/Python_Topics
/012_lists/examples/Python 3 Most Nessesary/8.1. Listing 8.1. Create a shallow copy of the list.py
1,169
4.375
4
# -*- coding: utf-8 -*- x = [1, 2, 3, 4, 5] # Создали список # Создаем копию списка y = list(x) # или с помощью среза: y = x[:] # или вызовом метода copy(): y = x.copy() print(y) # [1, 2, 3, 4, 5] print(x is y) # Опе...
0e1f60a4dd71d99753e8a19d3f767d8d2815615d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/768 Max Chunks To Make Sorted II.py
1,673
4.40625
4
#!/usr/bin/python3 """ This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8. Given an array arr of integers (not necessarily distinct), we split the array into some...
8199e90857ce7ac268a79d59098e31bfebc1b0d0
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/LinkedList/02.AddTwoNumbers.py
1,184
3.703125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode ...
4212e36d8f58c6daa1eca4f90874a489d4a8f3b0
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/fibonacci sequence index.py
381
4.0625
4
fib_store [0,1] #generating the fibonacci Sequence ___ i __ r..(2,1000 fib_store.a..(fib_store[-2] + fib_store[-1]) #searching for the index of the given element from Fibonacci Sequence ___ i __ r..(i..(i.. ))): fib_num i..(input #using index to find the index of the element from fibonacci sequence ...
add65a1168b59f9cfa32fdce22b0caa4321fd5f7
syurskyi/Python_Topics
/050_iterations_comprehension_generations/004_coroutines/examples/004_coroutines.py
4,071
4.125
4
# -*- coding: utf-8 -*- # producer-consumer-coroutines # """ # Сопрограмма (англ. coroutine) — компонент программы, обобщающий понятие # подпрограммы, который дополнительно поддерживает множество входных точек # (а не одну, как подпрограмма) и остановку и продолжение выполнения с # сохранением определённого положения...
32756e47a525d9265a1658da0e13ff9cbcdee87f
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/120_v2/validate.py
430
3.78125
4
from functools import wraps def int_args(func): @wraps(func) # complete this decorator def wrapper(*args): for arg in args: if type(arg) != int: raise TypeError("All arguments passed in must be integers") if arg <0: raise Val...
9680a5cff98db7015326444222cba49bc3c99421
syurskyi/Python_Topics
/100_databases/001_sqlite/examples/PYnative/005_Insert multiple rows.py
1,253
3.625
4
import sqlite3 def insertMultipleRecords(recordList): try: sqliteConnection = sqlite3.connect('SQLite_Python.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_insert_query = """INSERT INTO SqliteDb_developers (id, name, email, joi...
0b1fd052ca6b3b22072b44bbdd1212e15f6bcddd
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/exercises/Python_3_Deep_Dive_Part_4/Section 14 Metaprogramming/157. Metaprogramming Application 3.py
8,307
3.65625
4
# %% ''' ### Metaprogramming - Application 3 ''' # %% ''' Let's say we have some `.ini` files that hold various application configurations. We want to read those `.ini` files into an object structure so that we can access the data in our config files using dot notation. ''' # %% ''' Let's start by creating some `.in...
e2eeb69f75ae0eae849eb1708cf0b81d90eb5583
syurskyi/Python_Topics
/121_refactoring/Code_Smells/Bloaters/Long_Method/Replace_Temp_with_Query/007.py
1,106
3.734375
4
# Problem def calculateTotalAmount(): subtotal = calculateSubtotal() taxRate = getTaxRate() taxAmount = subtotal * taxRate totalAmount = subtotal + taxAmount return totalAmount def calculateSubtotal(): pass # calculation logic for subtotal def getTaxRate(): pass # logic to fetch...
902ad12fab4277f162fb97899caedb82e403a078
syurskyi/Python_Topics
/012_lists/examples/Python 3 Most Nessesary/8.12. Filling the list with numbers.py
387
3.59375
4
print(list(range(11))) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(range(1, 16))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print(list(range(15, 0, -1))) # [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] import random arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(random.sample(arr, 3)) # [1, 9, ...
e5309aa50d37717ff0f75cd5c12bb3422a00ad35
syurskyi/Python_Topics
/095_os_and_sys/_exercises/templates/Python pathlib tutorial/011_parts.py
658
3.5625
4
# Path consists of subelements, such as drive or root. # parts.py # #!/usr/bin/env python ____ p.. ______ P__ path = P__('C:/Users/Jano/Documents') print(path.parts) print(path.drive) print(path.root) # The program prints some parts of a path. print(path.parts) # The parts gives access to the path’s various comp...
17c9922315777a98beb9a4799bad497699ecd265
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/299/base_converter.py
859
4.5
4
# ___ convert number i.. base i.. 2 __ s.. # """Converts an integer into any base between 2 and 36 inclusive # # Args: # number (int): Integer to convert # base (int, optional): The base to convert the integer to. Defaults to 2. # # Raises: # Exception (ValueError): If base is less t...
c38dd68bbeecd9d6126d1c37d9900b615c3e1e88
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Tree/PathSumII.py
1,632
3.953125
4
""" Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 Return: [ [5,4,11,2], [5,8,4,5] ]...
1cb2e490da0eb7d7dcf491ade9fbfb576807c9ce
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BitManipulation/78_Subsets.py
808
3.65625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ subsets = [] n = len(nums) nums.sort() # We know there are totally 2^n subsets, # becase ev...
22f8974676203d4efb0a4e4280a30a93413e3d6e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-78-find-programmers-with-common-languages.py
1,319
3.96875
4
""" Similar as last Bite we do another comparison of sequences exercise. Here is the deal: you are in charge of huge org of many software devs. You need as many devs for a new app you want to build so let's do an inventory of the most common languages across the board. Your input data is a dict of this format: {'bob'...
0087f05b3409c4d03e75075c0e2d0ac68fb14a9e
syurskyi/Python_Topics
/115_testing/examples/Test-Driven Python Development/Chapter 8/test_driven_python-chapter-8/test_driven_python-chapter-8/stock_alerter/tests/test_timeseries.py
763
3.5
4
import unittest from datetime import datetime from ..timeseries import TimeSeries class TimeSeriesTestCase(unittest.TestCase): def assert_has_price_history(self, price_list, series): for index, expected_price in enumerate(price_list): actual_price = series[index].value if actual_p...
38231747e6d91a361d2015bbb2816d4e3383ae94
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_2/unittest-master/python/basics.py
1,386
3.765625
4
# assignment03.py # @author: Shubham Sachdeva # @email: # @date: 18-10-09 import csv CONST_AUTHOR = "Shubham Sachdeva" # REF_DATE GEO DGUID Food categories Commodity class Product: # initialisation def __init__(self, year, geo, guid, category, commodity): self.id = 0 self.year...
2a941e251d78633d70caf05e60efa864cc49aba9
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/701 Insert into a Binary Search Tree.py
1,190
4.375
4
#!/usr/bin/python3 """ Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Note that there may exist multiple valid ways fo...
e153092a6a9d922dcaa9be6eebae3e003802110f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/079 Combinations.py
1,138
3.78125
4
""" Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] """ __author__ 'Danyang' c_ Solution: ___ combine n, k """ Similar to 045 Permutation :p...
4424a0e72f4df9b61cb9b4d66b3e78ab0964ee61
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/025_Reverse_Nodes_i_ k-Group.py
1,099
3.765625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # class Solution(object): # def reverseKGroup(self, head, k): # """ # :type head: ListNode # :type k: int # :rtype: ListNode # """ c_...
f50b7d8beae1763ff2665416301bec37eff8fc53
syurskyi/Python_Topics
/050_iterations_comprehension_generations/009_permutations/examples/009_permutations.py
1,745
4.46875
4
# Permutations # In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence # or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. # These differ from combinations, which are selections of some members o...
ea94e97ae81c46d16d5b7fb99e9776dca336fe57
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/121 Best Time to Buy and Sell Stock II.py
1,065
3.765625
4
""" Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same ti...
c3cac517a34075d13cc9839c5aafffab20eefd1d
syurskyi/Python_Topics
/045_functions/007_lambda/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 67 sum_even_values.py
566
4.21875
4
# Sum Even Values Solution # # I define a function called sum_even_values which accepts any number of arguments, thanks to *args # I grab the even numbers using the generator expression (arg for arg in args if arg % 2 == 0) # (could also use a list comp) # I pass the even numbers I extracted into sum()...
e68fa28abb8eb130145171dbbaadced13f473c6d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/953 Verifying an Alien Dictionary.py
1,996
4.21875
4
#!/usr/bin/python3 """ In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if th...
f0e8cad843cb9ecf98ad007c178056965a0ad12b
amuralitharan/ML-Algorithms
/linear_regression.py
511
3.765625
4
import os import numpy as np from matplotlib import pyplot def cost(theta, y, X): n = y.size prediction = np.sum(np.square(y - np.transpose(theta[1:])*X + theta[0]))/n print(prediction.shape) def gradient_descent(): return 1 def predict(): return 1 def main(): #load data data = np.genfromtxt(os.path.join('Da...
5fda98f6aefa499a9f3c89c28db5d61304241337
lggurgel/python
/prime_v2.py
245
3.890625
4
def fib(n): """Returns a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result def func(a, L=[]): L.append(a) return L
2c191b2346b933eb372c0d2a6001cc40b50ef013
AhmedOAshour/File-Allocation-Simulator
/file_allocation.py
9,844
3.9375
4
import random class File: def __init__(self, size, name): # Constructor self.size = size self.name = name self.start = None self.end = None def display(self): # How the console will display the allocated Files if self.start is None: print("Name: ", self....
c7fde44dbdbdd8fbf0a8f75bc98819f46a6d2dd2
Nunziatellanicolepalarymzai/Python-104
/mean.py
883
4.375
4
# Python program to print # mean of elements # list of elements to calculate mean import csv with open('./height-weight.csv', newline='') as f: reader = csv.reader(f) #csv.reader method,reads and returns the current row and then moves to the next file_data = list(reader) #list(reader) adds the...
f2b95c8cfb31b7bda19f595933464f7c00b8484d
kremenovic96/mitxpy
/textbook/sqr.py
406
3.703125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 6 09:54:49 2016 @author: ranko """ x = 25 epsilon = 0.01 step = epsilon ** 2 numGuesses = 0 ans = 0.0 while abs(ans ** 2-x) >= epsilon and ans <= x: ans += step numGuesses += 1 print("Numguesses: "+ str(numGuesses)) if abs(ans ** 2 -x) >= epsilon: print("fai...
581eb4f8342ca1603abb22b42b2b710f4ff33951
aleshkoa/python_exercise
/question2.py
156
3.734375
4
celsius = float(raw_input('Enter Temperature in Celsius ')) fahrenheit = 9.0/5.0 * celsius + 32 print 'Temperature in Fahrehnheit is: ' + str(fahrenheit)
4027c95a7a449d9c46b21c2b08ca93ca51f37b8b
AngelTNP/Entrenamiento
/ProjectEuler/7.py
300
3.703125
4
import math def primo(x): if(x%2==0): return False for i in range(3,math.floor(math.sqrt(x))+1,2): if(x%i==0): return False return True def __main__(): x = 1 #uno por el dos prim = 1 while(x!=10001): prim+=2 if(primo(prim)): x+=1 print(prim) __main__()
4018f88f3fe2adff2ffd46ea33fa91976ee6e837
AngelTNP/Entrenamiento
/ProjectEuler/15.py
184
3.6875
4
def factorial(x): if(x<=1): return 1 else: return x*factorial(x-1) def __main__(): tam = 20 routes = factorial(2*tam)/(factorial(tam)**2) print(routes) __main__()
34b74af222fda40f35d744e2909cde08df0f3092
ravis3517/i-neuron-assigment-and-project-
/i neuron_python_prog_ Assignment_3.py
1,845
4.34375
4
#!/usr/bin/env python # coding: utf-8 # 1. Write a Python Program to Check if a Number is Positive, Negative or Zero # In[25]: num = float(input("Enter a number: ")) if num >0: print("positive") elif num <0 : print("negative") else: print(" number is zero") # 2. Wri...
ec03cd41e2133e9853dd508b691bc926da35dfb2
naveenailawadi/old
/roku/json_parser.py
3,481
3.5625
4
''' This script is designed to pull many objects in JSON from an api. It then formats it into a csv file. This was done to research the every screensaver that roku had to offer. ''' import requests from bs4 import BeautifulSoup as bs import json import pandas as pd import csv # obtain the channel and key --> input to...
a028274caf752af14baee2af8545bc6cda42735b
naveenailawadi/old
/reddit scraper/initializer.py
937
3.671875
4
''' In order to run any reddit scraper using the PRAW API, you have to register yourself with reddit. To avoid reeditting each script with the user's API keys, this script inputs them all into a central CSV which will later be referred to in each script. ''' import csv print('Follow the instructions below to input the...
f00a9c43628e75670b8dbea28eda0b0b5e792c25
naveenailawadi/old
/reddit scraper/all_searcher.py
4,835
3.5
4
''' In addition to the reguilar reddit scraper, the same client wanted to scrape all of reddit for specific search terms. This was not difficult to implement as the subreddit for all of reddit is simply "all". ''' import praw import pandas as pd import datetime # read login information name = 'reddit_login_info.csv' ...
f6e90f66de85f270c174bf3d5d0b0aa40a5135ce
bowie2k3/cos205
/COS-205_assignment4a_AJ.py
526
4.0625
4
# COS-205_assignment4a_AJ.py # Write a program that calculates and prints out the numeric value # of a single name provided as input by the user. # The value of a name is determined by summing up the values of the letters # of the name where “a” or “A” is 1, “b” or “B” is 2, and so on, up to “z” or “Z” being 26 name ...
07540d509c99f96db7fcc7f7362a36f5dc52d36d
bowie2k3/cos205
/COS-205_assignment4b_AJ.py
683
4.5
4
# Write a program that counts the number of words in a text file. # the program should print out [...] the number of words in the file. # Your program should prompt the user for the file name, which # should be stored at the same location as the program. # It should consider anything that is separated by white space o...
492e5b9f3c3a540ede56386dd10e8fb0961ee7cd
iaen7/leetcode
/leetcode12.py
1,247
3.671875
4
def intToRoman(num): One = num % 10 num = num/10 Ten = num % 10 num = num/10 Hundred = num % 10 num = num/10 Thousand = num % 10 num = num/10 Roman = '' if Thousand > 0: for i in range(0,Thousand): Roman += 'M' if Hundred == 9: Roma...
cf72a8464f464469a57fb5703814c2916673ba3b
iaen7/leetcode
/leetcode13.py
870
3.6875
4
def romanToInt(s): Length = len(s) Number = 0 for i in range(0,Length): if s[i] == 'M': Number += 1000 elif s[i] == 'C': if i<Length-1 and (s[i+1] == 'M' or s[i+1] == 'D'): Number -= 100 else: Number += 100 ...
b6d35f31562d97ec2fe4c6d9a1d349d23a45e7ea
jmmalnar/python_projects
/primes.py
1,896
4.40625
4
import unittest # Find all the prime numbers less than a given integer def is_prime(num): """ Iterate from 2 up to the (number-1). Assume the number is prime, and work through all lower numbers. If the number is divisible by ANY of the lower numbers, then it's not prime """ prime_status = ...
d938f0710f5c181262274d7214da083cc6407b26
lfcten/DataStructure
/search/sequential_search.py
659
3.71875
4
import time import datetime def sequential_search(a_list,item): pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos + 1 return found def sequential_search1(a_list,item): for num in a_list: ...
f46a8f7543a65eee3bb63829d3cf1f31de951fd3
nnegri/hackbright-dicts-word-count
/wordcount.py
1,404
4
4
import string, sys from collections import Counter def word_count(file_name): """ Create function to count occurances of each words in file_name""" #Created a function called word_tally pointing to file_name that is undefined atm text = open(file_name) #word_tally = {} # Empty dictionary wor...
f0df69ad43bba6758269865bf50cb68ac9ea5ade
DenisZun/data_sturcture
/double_list.py
3,863
4
4
# python双向链表 class Node(object): """双向链表的节点""" def __init__(self, data): # data为节点的元素域 # pre为节点的头链接部 # next为节点的尾链接部 self.data = data self.pre = None self.next = None class DoubleLinkedList(object): """双向链表""" def __init__(self, node=None): """双向链...
14095826ac80567341236e436622a8fea5ad1840
kapil-varshney/byte_ds
/Week4/terminal_trader/controller.py
7,661
3.53125
4
#!/usr/bin/env python3 import model class Controller: username = '' @classmethod def navigate(cls): print("Welcome to the Terminal Trading Platform") cls.new_or_returning_user() cls.tasks() @classmethod def new_or_returning_user(cls): print("Are you a returnin...
7f073591b7025d0e1d72e4c619d071f93be9779a
lmhavrin/python-crash-course
/chapter-seven/movie_tickets.py
491
4.09375
4
# Exercise 7-5: Movie Tickets prompt = "\nWelcome to the movies; What is your age?" prompt += "\nEnter quit when finished." while True: age = input(prompt) if age == "quit": break # break # if statment true loop will stop #if statement false loop will run rest of code age = int(age) ...
7565f46abf62cc1f1e217d137bc6371c19bcf480
lmhavrin/python-crash-course
/chapter-ten/read_number.py
347
3.59375
4
# Exercise 10-11 Favorite Number CTD import json def read_number(): """Get stored number if available""" try: filename = "favorite_num.json" with open(filename) as f_obj: number = json.load(f_obj) print(number) except FileNotFoundError: print("This file was n...
ec0e546c9a0937008130754b59a79f0d7e58e405
lmhavrin/python-crash-course
/chapter-three/intentional_error.py
130
3.734375
4
# Exercise 3-11: Intentional Error my_list = ["Lauren", "David", "David"] print(my_list[3]) # there is no index 3 in this list
adf06b4c6190e34261f401f24721faff2ecb22e8
lmhavrin/python-crash-course
/chapter-nine/login_attempts.py
1,437
4.03125
4
# Exercise 9-5: Login Attempts class User(): """Making a brief user profile""" def __init__(self, first_name, last_name, gender, age, hometown): self.first_name = first_name self.last_name = last_name self.gender = gender self.age = age self.hometown = hometown ...
5dc67e88fd9e6aff3a243bf3f52bc0390952be18
lmhavrin/python-crash-course
/chapter-seven/rental_car.py
136
3.796875
4
# Exercise 7-1 Rental Car car = input("What type of car would you like?") print("Let me see if I can find you a " + car.title() + ".")
6e684cde8f5f356821dbe73f929b05632e8bc61b
lmhavrin/python-crash-course
/chapter-ten/verify_user.py
1,466
4.09375
4
# Exercise 10-13: Verfiy User import json #Load the username, if it has been stored previously. # Otherwise, prompt for the username and store it. # Refactoring- Breaking up code into a series of functions that have specific jobs def get_stored_username(): """Get stored username if available.""" filename = "...
7cbacc84c82a73b1510646bdcb58bbd37992724c
lmhavrin/python-crash-course
/chapter-eight/user_albums.py
569
4.0625
4
# Exercise 8-8: Albums def make_album(artist, title, tracks=0): album = { "artist": artist.title(), "title": title.title() } if tracks: album["tracks"] = tracks return album while True: artist = input("Enter artists name; Press 'q' to quit ") if artist == "q": ...
1ac43c7e43e37fd03241cd9b29d7d37738dd0817
lmhavrin/python-crash-course
/chapter-five/conditional_tests.py
903
3.875
4
# Exercise 5-1: Conditional Tests cat = "pregnant" print("Is cat == 'pregnant'? I predict true.") print(cat == "pregnant") print("\nIs cat == 'not pregnant'? I predict false.") print(cat == "not pregnant") color = "purple" print("\n Is color == 'purple', I predict true:") print(color == 'purple') print("\n Does co...
f863b89f876e1848266043ec729b8e0de5008907
lmhavrin/python-crash-course
/chapter-six/favorite_places.py
452
4.09375
4
# Exercise 6-9: Favortie Places favorite_places = { "david": ["netherlands", "romania", "germany"], "lauren": ["bahamas", "chicago"], "bob": ["pennsylvania"] } # EVERYTHING MUST BE IN LIST FORMAT EVEN IF ONE ITEM #INSIDE DICTIONARY for person, places in favorite_places.items(): print(person.title...
69d63e236fd5585208ec5bebab45137c260c3562
lmhavrin/python-crash-course
/chapter-seven/deli.py
536
4.4375
4
# Exercise: 7-8 Deli # A for loop is useful for looping through a list # A while loop is useful for looping through a list AND MODIFYING IT sandwich_orders = ["turkey", "roast beef", "chicken", "BLT", "ham"] finished_sandwiches = [] while sandwich_orders: making_sandwich = sandwich_orders.pop() print("I made...
928b6669af9290b2b79f38fd90800525698b44da
lmhavrin/python-crash-course
/chapter-nine/user.py
801
3.71875
4
# 9-12 Multiple Modules class User(): """Making a brief user profile""" def __init__(self, first_name, last_name, gender, age, hometown): self.first_name = first_name.title() self.last_name = last_name.title() self.gender = gender.title() self.age = age self.hometown = ...
729921c5bff22cfb4e82d496f4ae654b629f5071
lmhavrin/python-crash-course
/chapter-two/famous_quote_two.py
584
3.546875
4
# what should have been done in Exercise 2-5 Famous Quote #print(""" Vince, Lombardi once said, "The difference between a successful person and others #is not a lack of strength, not a lack of knowledge, but rather a lack of will." """) # Exercise 2-6: Famous Quote famous_person = "Vince Lombardi" message = """ "The ...
cb4880043372a403c524628588983e8a2027cbd7
Anjal17122/Python_Tkinter_Library
/database.py
2,318
3.75
4
import sqlite3 username = 'admin' password = 'admin' PATH = r'C:\Users\User\Desktop\AnjalSaps\projects\pythondjangoprojects\pythontkinterfinalproject\tkinterr\lib_mngmt' def connect(): conn = sqlite3.connect(PATH) return conn def create_table_book(): conn=connect() c=conn.cursor() c.execute('''crea...
864c84af3931c74fa40eb0d5f3175450abc2dda0
athawley/learnictnow.com
/programming/python/turtle_multiple.py
662
3.828125
4
# Set up the window and its attributes import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") # create tess and set some attributes tess = turtle.Turtle() tess.color("hotpink") tess.pensize(5) # create alex, who is a second turtle object alex = turtle.Turtle() # Let tess draw an equilateral triangle tess.forwar...
637260eab712b7cca3c5f0f9e058fcd3639ffa96
bqr407/PyIQ
/bubble.py
1,671
4.15625
4
class Bubble(): """Class for bubble objects""" def __init__(self, id, x, y, x2, y2, value): """each bubble object has these values associated with it""" self.x = x self.y = y self.x2 = x2 self.y2 = y2 self.id = id self.value = value def getX(self): ...
833bfb2748edd83bf2848768c2fd7f5f75175731
hhxxss0722/double
/PyQt5-Chinese-tutoral-master/test/threadEvent_test.py
980
3.671875
4
# coding:utf-8 import threading import time event = threading.Event() def chihuoguo(name): # 等待事件,进入等待阻塞状态 print('%s 已经启动' % threading.currentThread().getName()) print('小伙伴 %s 已经进入就餐状态!'%name) time.sleep(1) event.wait() # 收到事件后进入运行状态 print('%s 收到通知了.' % threading.currentTh...
66a7ca9ef390456166a01c10d56b3e168e4cc015
rishipandey125/Machine-Learning-Classification
/random_forest.py
4,641
3.65625
4
import decision_tree import random """ Random forest Machine Learning Model by Rishi Pandey. Generates a Random forest Machine Learning Model. Model is trained based off of data loaded as CSV. """ """ Object for a Random Forest ML Model. Contains a forest of decision trees, accuracy of model, and differences between a...
f32de78f226af34b14d0bf5ca4c2356c19da1107
Saf1n/python_algorythm
/HomeWork3/test3_9.py
548
3.78125
4
__author__ = 'Сафин Ильшат' # 9. Найти максимальный элемент среди минимальных элементов столбцов матрицы. print('Введите 12 цифр:') matrix = [[int(input()) for _ in range(4)] for _ in range(3)] for i in range(3): print(matrix[i]) mx = -1 for i in range(3): mn = 10 for j in range(4): if matrix[i][...
195ee70ab12758814791e0b9d1a3c1e318420d7d
Saf1n/python_algorythm
/HomeWork2/test2_7.py
767
4.0625
4
__author__ = 'Сафин Ильшат' # coding: utf-8 # 7. Написать программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется равенство: # 1+2+...+n = n(n+1)/2, где n – любое натуральное число. # Докажем равенство через отдельное вычисление левой и правой сторон n = int(input('Введите предел вы...
6d666cef9d012833d19e3038bf923158aabc9da4
manuelcabral524/Agent0_Grupo5
/Grupo 5 Agent0 A Star Base/Agent0_minotauro/client/example_agent_search_profundidade.py
12,539
3.640625
4
import client import ast import random VISITED_COLOR = "#400000" # Vermelho escuro. FRONTIER_COLOR = "red3" # Vermelho claro. # AUXILIAR class Stack: def __init__(self): self.stack_data = [] def isEmpty(self): if len(self.stack_data) == 0: return True else: r...