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
ce9483de3859c90453180d8882467c9bc4918f3b
syurskyi/Python_Topics
/100_databases/001_sqlite/examples/PYnative/021_Retrieve Image and File stored as a BLOB.py
1,919
3.796875
4
import sqlite3 def writeTofile(data, filename): # Convert binary data to proper format and write it on Hard Disk with open(filename, 'wb') as file: file.write(data) print("Stored blob data into: ", filename, "\n") def readBlobData(empId): try: sqliteConnection = sqlite3.connect('SQLite...
b4b1f5d0b406903fbd9accc83d8ead1b3d2f313c
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/035 Valid Sudoku.py
2,647
3.640625
4
""" Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. Note: A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells nee...
d6512208970b85c245726cea6f6184d5102f2f5d
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Backtracking/51_NQueens.py
2,091
4.03125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): allNQueens = [] def solveNQueens(self, n): self.allNQueens = [] self.cols = [True] * n self.left_right = [True] * (2 * n - 1) self.right_left = [True] * (2 * n - 1) queueMatrix = [["."] * n for row ...
67b17f468709a0bd849b347549a5368901b8c703
syurskyi/Python_Topics
/100_databases/002_posgresql/examples/Python PostgreSQL tutorial zetcode/005_lastrowid.py
707
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import psycopg2 con = psycopg2.connect(database='testdb', user='syurskyi', password='1234') with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS words") cur.execute("CREATE TABLE words(id SERIAL PRIMARY KEY, word VARCHAR(255...
01add743d7f439dc80af9f7fdff5d6a9b03d3591
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/DP/NumberofLongestIncreasingSubsequence.py
2,961
3.828125
4
""" Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing sub...
8bafad1c847f74fd960cc1ba8d1b2fc9e3990b7d
syurskyi/Python_Topics
/018_dictionaries/examples/dictionary_002.py
4,912
4.03125
4
# Проверить существование кточа можно с помощью оператора in. Если ключ найден, то # возвращается значение тrue, в противном случае - False. d = {"a": 1, "b": 2} print("a" in d) # Ключ существует # True print("c" in d) # Ключ не существует # False # Проверить, отсутствует ли какой-либо ключ в словаре, позволит операто...
048985656c8b9aa4fdd20d5f4485302a9059ebe2
syurskyi/Python_Topics
/095_os_and_sys/examples/pathlib — Filesystem Paths as Objects/009_Deleting/001_pathlib_rmdir.py
926
4.28125
4
# There are two methods for removing things from the file system, depending on the type. To remove an empty directory, use rmdir(). # pathlib_rmdir.py # # import pathlib # # p = pathlib.Path('example_dir') # # print('Removing {}'.format(p)) # p.rmdir() # # A FileNotFoundError exception is raised if the post-conditions ...
b731a29689c1a5581bdfffa60a057285bfde5f1d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/057 Insert Interval.py
2,077
3.765625
4
""" Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,...
4279b993e6542713b54086d7dfb5402bd881718a
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/293_n_digit_numbers/save1_nopass.py
376
3.90625
4
car_brands = ['Mazda', 'McLaren', 'Opel', 'Toyota', 'Honda'] def convert_to_tuple(car_brands): static_cars = tuple(car_brands) return static_cars # Complete this function such that it prints the return value from the convert_to_tuple function def print_tuples(car_brands): car_brands = convert_to_tuple()...
a3454f6bccbdab70c6f468c6ccdcf190f4f58041
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/String/28_ImplementstrStr.py
541
3.5625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- c.. Solution o.. # Not notoriously hard-to-understand algorithm KMP ___ strStr haystack, needle # Return 0 if needle is "" __ n.. needle: r_ 0 length = l..(haystack) # If one char in haystack is same with needle[0], ...
da202821fc99a138bd2433255172ae6abbc181ef
syurskyi/Python_Topics
/125_algorithms/005_searching_and_sorting/_exercises/exersises/05_Merge Sort/6 - Insertion Sort vs. Merge Sort vs. Quicksort - timeit.py
2,117
3.65625
4
# ______ t.. # # NUM_REPETITIONS _ 100 # # SETUP_CODE _ "from random import shuffle" # # # First test case - Insertion Sort # # ___ insertion_sort lst # ___ i __ ra.. 1 le. ? # elem_selected _ ?|? # # w__ i > 0 an. ? < ?|?-1 # ?|? _ ?|?-1 # ? -_ 1 # # ?|? _ ? # # # te...
10bd5d84d5136fffe530c59b8d5e36e8704782fb
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id047-Caesar_Shift_Cipher.py
994
3.515625
4
# Python 2.7 _______ s__ ___ encrypt(msg_count, key alphabet s__.a.. alphabet_shifted alphabet[key:] + alphabet[:key] caesar_shift s__.maketrans(alphabet, alphabet_shifted) answer # list ___ msg __ r..(msg_count unencrypted_msg raw_input().u.. encrypted_msg unencrypted_msg....
a6ec84041a9603243a0fa4b44d23bb4559fb2d8c
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/122/anagram.py
409
3.984375
4
# ___ is_anagram word1 word2 # """Receives two words and returns True/False (boolean) if word2 is # an anagram of word1. # About anagrams: https://en.wikipedia.org/wiki/Anagram""" # word1 word1.r.. " ", "" .l.. # word2 word2.r.. " ", "" .l.. # __ s.. ? __ s.. ? # r.. T.. # ____ # ...
295485bae68497f341317233ecec2b9e9948fa32
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/324 Wiggle Sort II py3.py
1,944
4.0625
4
#!/usr/bin/python3 """ Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... Example 1: Input: nums = [1, 5, 1, 1, 6, 4] Output: One possible answer is [1, 4, 1, 5, 1, 6]. Example 2: Input: nums = [1, 3, 2, 2, 3, 1] Output: One possible answer is [2, 3, 1, 3, 1, 2]. Note: You m...
3cab568123c4abca6add09b7d7f5cca55a1deb15
syurskyi/Python_Topics
/125_algorithms/_exercises/exercises/_algorithms_challenges/leetcode/LeetCode_with_solution/002 Median of Two Sorted Arrays.py
2,014
3.6875
4
# """ # There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall # run time complexity should be O(log (m+n)). # """ # __author__ = 'Danyang' # # # c_ Solution # ___ findMedianSortedArrays A B # """ # Merge two arrays to get the median,...
a465d0633d6d9c4d2e6a449a7fcfcd752e01e882
syurskyi/Python_Topics
/070_oop/001_classes/examples/ITVDN_Python_Advanced/004_Метаклассы/example1_type.py
1,027
3.609375
4
def get_first_name(self): return self.first_name def get_last_name(self): return self.last_name def get_middle_name(self): return self.middle_name def init(self, first_name, last_name, middle_name): self.first_name = first_name self.last_name = last_name self.middle_name = middle_name cl...
c14b314ac98a05946788391f5f896b8103c43b17
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/TwoPointers/16_3SumClosest.py
1,323
3.984375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() min_distance = 2 ** 31 - 1 length = len(nums) # keep the s...
8fd1a408e3ec25d95cb5d15473e4cdf8ec4682a9
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/49_v2/packt.py
797
3.609375
4
from collections import namedtuple from bs4 import BeautifulSoup as Soup import requests PACKT = 'https://bites-data.s3.us-east-2.amazonaws.com/packt.html' CONTENT = requests.get(PACKT).text Book = namedtuple('Book', 'title description image link') def get_book(): """make a Soup object, parse the relevant html...
1137b851ed42a42ceb79c41d8c446b23bbba51ad
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 6 Dynamic Programming/FibonacciDP.py
696
3.90625
4
___ fibonacci_recursion(n __ n __ 0: r_ 1 __ n __ 1: r_ 1 r_ fibonacci_recursion(n-1) + fibonacci_recursion(n-2) # top-down approach ___ fibonacci_memoization(n, table __ n no. __ table: table[n] fibonacci_memoization(n-1, table) + fibonacci_memoization(n-2, table) #...
6f3453f7739bdb26b9c6e82a6379a385af806970
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 15 Sort/insertion_sort_implement_solution.py
881
4
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # Write a Python program to sort a list of elements using the insertion sort algorithm. # Note: According to Wikipedia "Insertion sort is a simple sorting algorithm that builds # the final sorted array (or list) one item at a ti...
bf804b07bca29cd832ad306060165f29a7ca6499
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/647_substring_anagrams.py
912
3.71875
4
""" REF: https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/ """ c_ Solution: ___ findAnagrams s, t """ :type s: str :type t: str :rtype: List[int] """ ans # list __ n.. s o. n.. t o. l..(t) > l..(s r.. ans F ...
d4450b0c6d0c8606e68e61901bc5d21cb770cc72
syurskyi/Python_Topics
/090_logging/examples/Python Logging – Simplest Guide with Full Code and Examples/008_9. How to include traceback information in logged messages.py
974
3.5625
4
# Besides debug, info, warning, error, and critical messages, you can log exceptions that will include any # associated traceback information. # With logger.exception, you can log traceback information should the code encounter any error. logger.exception will log # the message provided in its arguments as well as the ...
e17d04f9383cce416b49a61d78ab5eb167365d45
syurskyi/Python_Topics
/110_concurrency_parallelism/_exercises/templates/The_Complete_Python_Course_l_Learn_Python_by_Doing/projects/async_scraping/app.py
2,648
3.53125
4
""" You can see when running this file, that the amount of time it takes for the requests is actually quite long— and they don't seem to all happen at the same time. That's because the toscrape websites actually limit us to a single connection at a time, so making multiple requests using aiohttp and waiting for them t...
331eab5b8eafeadd1f9d83d27280117a4daea3b8
syurskyi/Python_Topics
/012_lists/_exercises/Python 3 Most Nessesary/8.1. Listing 8.1. Create a shallow copy of the list.py
1,202
4.1875
4
# # -*- coding: utf-8 -*- # # x = [1, 2, 3, 4, 5] # Создали список # # Создаем копию списка # y = l.. ? # или с помощью среза: y = x[:] # # или вызовом метода copy(): y = x.copy() # print ? # # [1, 2, 3, 4, 5] # print(x i_ y) ...
41d8a0a50decf51faf898a7346ce1a70f5aecbd9
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/74/bday.py
411
4.09375
4
import calendar #from datetime import date #weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] def weekday_of_birth_date(date): """Takes a date object and returns the corresponding weekday string""" #return weekdays[calendar.weekday(date.year, date.month, date.day)] ...
0e890772ec0a6827e48ad8346929b77e8f0fe3a2
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Stack/85_MaximalRectangle.py
2,216
3.65625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def maximalRectangle(self, matrix): """ :type matrix: List[list[str]] :rtype: int """ if not matrix: return 0 m_rows = len(matrix) n_cols = len(matrix[0]) # Pre-pro...
b6867543f492e1bcfa7895806ebafe55df328da2
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/_templates/Python_OOP_Object_Oriented_Programming/Section 15/project/player.py
1,786
3.8125
4
class Player: def __init__(self, name, is_dealer=False): # The player has a name # and a hand that is initially empty self._name = name # The hand attribute is protected # and it doesn't have getters and setters # because it doesn't have to be read or set. # ...
7f9dd6edcea8dd4778d92a344fc7a71b91ad7977
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BinarySearch/81_SearchInRotatedSortedArrayII.py
1,429
4
4
#! /usr/bin/env python # -*- coding: utf-8 -*- c.. Solution o.. ___ search nums, target """ :type nums: List[int] :type target: int :rtype: bool """ nums_size = l..(nums) start = 0 end = nums_size - 1 _____ start <= end: mid = ...
c49c16103e4d0ab711c90be31e2a7a50caa6b8bf
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/560 Subarray Sum Equals K.py
679
3.75
4
#!/usr/bin/python3 """ Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range o...
0d6d149314dd679711f911de27eab09d0f4bd677
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/896 Monotonic Array.py
1,080
3.96875
4
#!/usr/bin/python3 """ An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Example 1: Inpu...
3b3ba828e754b1e81eb8f704a676888517e1ba25
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/117_PopulatingNextRightPointersInEachNodeII.py
2,466
4.09375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for binary tree with next pointer. # class TreeLinkNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None c.. Solution o.. ___ connect root __ n.. roo...
0ad31500f7c294e13cb17da3508cf79b21c293d1
syurskyi/Python_Topics
/045_functions/008_built_in_functions/zip/examples/002_How zip() works in Python.py
400
3.703125
4
numberList = [1, 2, 3] strList = ['one', 'two', 'three'] # No iterables are passed result = zip() print(result) # Converting itertor to list resultList = list(result) print(resultList) # # Two iterables are passed result = zip(numberList, strList) print(list(result)) # # # Converting itertor to set # resultSet = set(...
ef173fde8a3cf0c4fb66bddea7262bcda0c64b5f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/643 Maximum Average Subarray I.py
789
3.890625
4
#!/usr/bin/python3 """ Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. Example 1: Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 N...
d4ad996d8e156d70426d88f1ed7f01d4c338b492
syurskyi/Python_Topics
/050_iterations_comprehension_generations/004_coroutines/_exercises/templates/003_Coroutine in Python.py
6,369
4.1875
4
# # -*- coding: utf-8 -*- # # We all are familiar with function which is also known as a subroutine, procedure, subprocess etc. A function is a # # sequence of instructions packed as a unit to perform a certain task. When the logic of a complex function is divided # # into several self-contained steps that are themsel...
e75c9f4ba6bf90421edc4795266c2180b7f90c88
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Combination/300_LongestIncreasingSubsequence.py
1,468
3.59375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com c.. Solution o.. """ Clear explanation is here: https://leetcode.com/discuss/67687/c-o-nlogn-solution-with-explainations-4ms https://leetcode.com/discuss/67643/java-python-binary-search-o-nlogn-time-with-explanation The...
caf7fefdcb95d72d6bc06e78f40a618c39fd80b5
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DFS/WordSearch.py
12,281
3.90625
4
""" Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','...
8ce70b6bef2ddd80f99bd12adce0f1c88733d146
syurskyi/Python_Topics
/115_testing/_exercises/exercises/The_Modern_Python_3_Bootcamp/295. Assertions.py
481
3.546875
4
# # Example 1 # ___ add_positive_numbers x, y # a.. x > 0 an. y > 0, "Both numbers must be positive!" # r_ x + y # # # print ? 1, 1) # 2 # ? 1, -1 # AssertionError: Both numbers must be positive! # # # Example 2 # # # ___ eat_junk food # a.. food __ [ # "pizza", # "ice cream", # "ca...
76d1213f90d810ba33560e60191988dc7f7464a8
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 2 - Add Binary.py
1,423
3.9375
4
# Add Binary # Question: Given two binary strings, return their sum (also a binary string). # For example, # a = "11" # b = "1" # Return "100". # Solutions: class Solution: def addBinary( a, b): length = max(len(a),len(b)) + 1 sum = ['0' for i in range(length)] if len(a) <= len(b): ...
3452335bdf32e92235ec2f2886bbaa734c3f1134
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/377 Combination Sum IV.py
1,359
3.921875
4
""" Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different seque...
7d224673021096bc698a88ba105df03da80950bd
syurskyi/Python_Topics
/110_concurrency_parallelism/_exercises/templates/Gitlab/Python-multi-threading-examples/pyth_01.py
637
3.984375
4
print "Hello" xxa = raw_input("Enter a number\n") ___ num1= float(xxa) _______ print "Invalid input. Please insert a number or type done to finish" loop= 0 count= 0 running_total= 0 w___ loop ==0: inp = raw_input("Enter a number:") __ inp== "done" or inp== "Done" : ____ ...
de858ef574b405fb7b63b49157118cc320ac5197
syurskyi/Python_Topics
/050_iterations_comprehension_generations/002_list_comprehension/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 21 More List Comprehension Exercises.py
461
4.03125
4
# Using list comprehensions(the more Pythonic way): answer = [val for val in [1, 2, 3, 4] if val in [3, 4, 5, 6]] # the slice [::-1] is a quick way to reverse a string answer2 = [val[::-1].lower() for val in ["Elie", "Tim", "Matt"]] # Without list comprehensions, things are a bit longer: answer = [] for x in [1,2,3,...
5e29b94012ca18356083d3227a38a1ea08c5d309
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/109 Convert Sorted List to Binary Search Tree.py
1,364
3.546875
4
""" Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. """ __author__ 'Danyang' # Definition for a binary tree node c_ TreeNode: ___ - , x val x left N.. right N.. # Definition for singly-linked list. c_ ListNode: ___ - , x ...
9704cae30d70ad976d7e0d9eb0d2456cfeb753cb
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/450_reverse_nodes_in_k_group.py
1,038
3.578125
4
""" Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None """ c_ Solution: """ @param: head: a ListNode @param: k: An integer @return: a ListNode """ ___ reverseKGroup head, k __ n.. head: r.. d...
6b442f9d5799c3bf2b6fa7c18e4fbd4848523d28
syurskyi/Python_Topics
/070_oop/008_metaprogramming/_exercises/templates/Expert Python Programming/new_method_instance_counting.py
936
3.75
4
# """ # "Using the __new__() method to override instance creation process" section # example of overriding `__new__()` method to count class instances # # """ # ____ ra... ______ r_i.. # # # c_ InstanceCountingClass: # instances_created _ 0 # # ___ -n ___ $ $$ # print('__new__() called with:' ___ a....
b4e8b3336ffe59ee90ac13455c7237726b99a433
syurskyi/Python_Topics
/125_algorithms/_examples/Practice_Python_by_Solving_100_Python_Problems/86.py
356
3.8125
4
#Create a script that checks a list against countries_clean.txt #and creates a list with items that were in that file checklist = ["Portugal", "Germany", "Munster", "Spain"] with open("countries_clean.txt", "r") as file: content = file.r.. content = [i.rstrip('\n') for i in content] checked = [i for i in content...
1bd3d72efbeb37edd891d8998bbf617539ec7735
syurskyi/Python_Topics
/050_iterations_comprehension_generations/001_iterations_and_iteration_tool/examples/007_Python Built-In Iterables and Iterators.py
3,503
4.40625
4
# Python Built-In Iterables and Iterators # for the list # Since the list l is an iterable it also implements the __iter__ method: # Of course, since lists are also sequence types, they also implement the __getitem__ method: l = [1, 2, 3] iter_l = iter(l) #or could use iter_1 = l.__iter__() type(iter_l) next(iter_l) n...
ef65f3e6ecf0a06432245913a1d0baaef73b08f7
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/339 Nested List Weight Sum.py
1,282
3.78125
4
""" Premium Question """ __author__ 'Daniel' """ This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation """ c_ NestedInteger(o.. ___ isInteger """ @return True if this NestedInteger holds a single integer, rather than a nes...
aa6cf1b7b7180c938be13cb74af56767ff6b8a9f
syurskyi/Python_Topics
/045_functions/005_decorators/_exercises/_templates/The_Modern_Python_3_Bootcamp/279. Higher Order Functions_higher-order.py
260
3.875
4
# We can pass funcs as args to other funcs def sum(n, func): total = 0 for num in range(1, n+1): total += func(num) return total def square(x): return x*x def cube(x): return x*x*x print(sum(3, cube)) print(sum(3, square))
2c45f7d0fe5178ddb632cdf3b52a141ff1f572e2
syurskyi/Python_Topics
/070_oop/008_metaprogramming/examples/Interface/Implementing an Interface in Python/a_001_Informal Interfaces.py
3,805
4.375
4
# In certain circumstances, you may not need the strict rules of a formal Python interface. Python's dynamic nature # allows you to implement an informal interface. An informal Python interface is a class that defines methods that # can be overridden, but there's no strict enforcement. # # In the following example, you...
bb11a7e5db0d8020050c2498d675d260e42736cd
syurskyi/Python_Topics
/060_context_managers/_exercises/templates/99. Caveat when used with Lazy Iterators.py
1,665
3.6875
4
# # We have to be careful when working with context managers and lazy iterators. # # Consider this example where we want to create a generator from a file: # # print('#' * 52 + ' ### Caveat with Lazy Iterators') # # ______ cs # # # ___ read_data # w___ o... 'nyc_parking_tickets_extract.csv' __ f # r_ cs_.r...
8e95f3a8844ab693ff4caf46ceb24ae26cafc62b
syurskyi/Python_Topics
/045_functions/008_built_in_functions/zip/examples/007_Passing One Argument.py
262
3.75
4
a = [1, 2, 3] zipped = zip(a) list(zipped) # [(1,), (2,), (3,)] integers = [1, 2, 3] letters = ['a', 'b', 'c'] floats = [4.0, 5.0, 6.0] zipped = zip(integers, letters, floats) # Three input iterables list(zipped) # [(1, 'a', 4.0), (2, 'b', 5.0), (3, 'c', 6.0)]
86820b97e77fd23dc64e58e2e45ceb3e7497f642
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/234/sentences.py
636
3.859375
4
from test_sentences import * import re def capitalize_sentences(text: str) -> str: """Return text capitalizing the sentences. Note that sentences can end in dot (.), question mark (?) and exclamation mark (!)""" text_metacharacters = re.findall("[\\!\\.\\?]", text.strip()) text_raw = re.split("[\\!\\.\...
3b177753265b1d2c5fa8ee6aa75088b55ab35e62
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/4/pipe.py
360
3.6875
4
# message = """Hello world! # We hope that you are learning a lot of Python. # Have fun with our Bites of Py. # Keep calm and code in Python! # Become a PyBites ninja!""" # # ___ split_in_columns message_? # """Split the message by newline (\n) and join it together on '|' # (pipe), return the obtained output...
7f571f75e4cde471f37e78d7b6e3f64255c5e9dd
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/topics/String/8/test_rotate.py
1,794
4.46875
4
____ rotate _______ rotate ___ test_small_rotate ... rotate('hello', 2) __ 'llohe' ... rotate('hello', -2) __ 'lohel' ___ test_bigger_rotation_of_positive_n s__ 'bob and julian love pybites!' e.. 'love pybites!bob and julian ' ... rotate(s__, 15) __ e.. ___ test_bigger_rotation_of_negative_n ...
937e349234190b8b96f3d110593259c411c01014
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/374_Guess_Number_Higher_or_Lower.py
567
3.59375
4
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): c_ Solution o.. ___ guessNumber n """ :type n: int :rtype: int """ # binary search begin, end = 1,...
68fbe016da1345b61f863902bbeadf29b279c3f9
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/The Complete Data Structures and Algorithms Course in Python/Section 18 Cracking Linked List Interview Questions/Q4_SumLists.py
648
4.03125
4
# Created by Elshad Karimov on 18/05/2020. # Copyright © 2020 AppMillers. All rights reserved. # Question 4 - Sum Lists ____ LinkedList _____ LinkedList ___ sumList(llA, llB n1 llA.head n2 llB.head carry 0 ll LinkedList() w__ n1 o. n2: result carry __ n1: res...
bd06af8192fae584aff2a1e7421e9c2f6cf5bd79
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/99_v2/sequence_generator.py
293
3.84375
4
import string import itertools def sequence_generator(): numbers = list(range(1,27)) sequence = [numbers[i//2] if i % 2 == 0 else string.ascii_uppercase[i//2] for i in range(52)] yield from itertools.cycle(sequence) if __name__ == "__main__": sequence_generator()
c8543619c1c3a6ddccda7adc21b50209c03d8ee2
syurskyi/Python_Topics
/120_design_patterns/002_builder/_exercises/_templates/001_builder.py
1,978
3.75
4
# #!/usr/bin/python # # -*- coding : utf-8 -*- # # """ # *What is this pattern about? # It decouples the creation of a complex object and its representation, # so that the same process can be reused to build objects from the same # family. # This is useful when you must separate the specification of an object # from it...
c168bbdfaf22f4cd88103d7151e0dc8b3b738b86
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/091 Decode Ways.py
1,390
3.90625
4
""" A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The n...
7aabe12258ce1b1a2d3f8fccf590467bc5663eb1
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/73_SetMatrixZeroes.py
1,459
3.875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ if not matrix: return [] m = len(matrix) ...
6b853a583be5728336bfbb3368fb53ef4a3af8e1
syurskyi/Python_Topics
/070_oop/004_inheritance/examples/super/Supercharge Your Classes With Python super()/005_Method Resolution Order.py
6,828
3.921875
4
# The method resolution order (or MRO) tells Python how to search for inherited methods. # This comes in handy when you're using super() because the MRO tells you exactly where Python will look for # a method you're calling with super() and in what order. # # Every class has an .__mro__ attribute that allows us to insp...
08928a50181feb1eb774eee5cedef8be10e5ec2e
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Mock_Helpers.py
6,507
3.625
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 stu...
1f7c2a005ecc688598dfc11cf3b382430a32452d
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/advanced/196/js.py
561
3.640625
4
class JsObject(dict): """A Python dictionary that provides attribute-style access just like a JS object: obj = JsObject() obj.cool = True obj.foo = 'bar' Try this on a regular dict and you get AttributeError: 'dict' object has no attribute 'foo' """ def __init_...
ad5aba4dbdde1d5f8411a9e973c6e3be08354238
syurskyi/Python_Topics
/070_oop/_examples/Python-from-Zero-to-Hero/08/06-Additional Dunder Methods.py
937
3.546875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: lst = [1, 2, 3] # In[ ]: repr(lst) # In[ ]: print(lst) # In[ ]: eval(repr(lst)) == lst # In[ ]: from datetime import datetime dt = datetime.now() # In[ ]: repr(dt) # In[ ]: print(dt) # In[ ]: class Character(): def __init__(self, ra...
de990ba8869438b5cf1479fddc2be99591708692
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Practice_Python_by_Solving_100_Python_Problems/50.py
256
3.640625
4
# #A: str and i.. do not support a minus operand. It doesn't make sense to substract a text from a number or the other way around. # # change age-1 to i..(age)-1 # age = i.. ? What's your age? # age_last_year = ? - 1 # print("Last year you were __." _ ?
ce65f63521103a3b65819c8bdf7daaaf479a51ef
syurskyi/Python_Topics
/012_lists/_exercises/ITVDN Python Starter 2016/03-slicing.py
822
4.4375
4
# -*- coding: utf-8 -*- # Можно получить группу элементов по их индексам. # Эта операция называется срезом списка (list slicing). # Создание списка чисел my_list = [5, 7, 9, 1, 1, 2] # Получение среза списка от нулевого (первого) элемента (включая его) # до третьего (четвёртого) (не включая) sub_list = my_list[0:3] ...
9be84fae16d54e85eb80347ea8f192154d068db5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/299_v4/base_converter.py
735
4.09375
4
# ___ digit_map num # """maps numbers greater than a single digit to letters (UPPER)""" # r.. c.. ?+ 55 __ ? > 9 ____ s.. ? # # ___ 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 (...
7104d7c1fad82e692e0ea015c9ba8cf58c45576a
syurskyi/Python_Topics
/070_oop/001_classes/examples/ITVDN_Python_Advanced/006_Типизированный Python/example5.py
727
3.5625
4
from typing import Dict, Tuple, List def generate_tuple(data) -> list: result = [] for key, value in data.values(): result.append((key, value)) return result test_data1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} test_data2 = {'k1': 'v1', 'k2': 'v2', 'k3': 10} test_data3 = {'k1': 'v1', 'k2': 'v2', 'k...
171d8a178003fc0c6367908f3ecc1cdfc9b62152
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/289_GameOfLife.py
1,461
3.765625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com class Solution(object): def gameOfLife(self, board): if not board: return m_rows = len(board) n_cols = len(board[0]) count = [[0 for j in range(n_cols)] for i in range(m_rows)] for i i...
9584dadc060d867434c2d901d3b37841a1f1995e
syurskyi/Python_Topics
/065_serialization_and_deserialization/002_json/examples/49. Custom JSON Encoding - Coding.py
19,581
4.1875
4
# Custom JSON Serialization # As we saw in the previous video, certain data types cannot be serialized to JSON using Python's defaults. # Here's a simple example of this: from datetime import datetime current = datetime.utcnow() print(current) # datetime.datetime(2018, 12, 29, 22, 26, 35, 671836) print('#' * 52 + '...
e67b4827167a7ec9f6e26214dd62b0cda65bd647
syurskyi/Python_Topics
/100_databases/003_mongodb/examples/w3schools_Python MongoDB/006_Find One.py
332
3.765625
4
# Find One # # To select data from a collection in MongoDB, we can use the find_one() method. # # The find_one() method returns the first occurrence in the selection. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] x = mycol.find_one...
a3019df68c1e9b08178180fe9f44dd54cb3cd213
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 14 Array/array_two_sum_solution.py
635
3.984375
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% """ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: ...
ade7d89656382c39b72c08bf1c6c2b6e9311c097
syurskyi/Python_Topics
/125_algorithms/_exercises/exercises/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/check_triange_solution.py
794
4.03125
4
# # To add a new cell, type '# %%' # # To add a new markdown cell, type '# %% [markdown]' # # %% # # --------------------------------------------------------------- # # python best courses https://courses.tanpham.org/ # # --------------------------------------------------------------- # # Write a Python program to chec...
afca8fe2b6189f257f765e893191ba7b41902f18
syurskyi/Python_Topics
/070_oop/001_classes/examples/Learning Python/026_006_Classes Versus Dictionaries.py
789
3.90625
4
rec = {} rec['name'] = 'mel' # Dictionary-based record rec['age'] = 45 rec['job'] = 'trainer/writer' print(rec['name']) class rec: pass rec.name = 'mel' # Class-based record rec.age = 45 rec.job = 'trainer/writer' print(rec.age) class rec: pass pers1 = rec() ...
c10b1e6b2a1946e418dc762ecf783326ff98c4d3
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/_templates/Python_3_Deep_Dive_Part_4/Section 4 Polymorphism and Special Methods/58. Callables - Coding.py
12,211
4.6875
5
# %% ''' ### Making Objects Callable ''' # %% ''' We can make instances of our classes callables by implementing the `__call__` method. ''' # %% ''' Let's first see a simple example: ''' # %% class Person: def __call__(self): print('__call__ called...') # %% p = Person() # %% ''' And now we can use `p`...
0c7741c528c1a2723425cc410a7158bee2f3989c
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/83/timezone.py
720
3.71875
4
from pytz import timezone, utc from datetime import datetime AUSTRALIA = timezone('Australia/Sydney') SPAIN = timezone('Europe/Madrid') def what_time_lives_pybites(naive_utc_dt): """Receives a naive UTC datetime object and returns a two element tuple of Australian and Spanish (timezone aware) datetimes"""...
6001a7741fa8ca503a6a9cc3338b0d350473fc9b
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/152 Maximum Product Subarray.py
4,720
3.6875
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6 """ __author__ 'Danyang' c_ Solution(o.. ___ maxProduct_oneline nums r.. m..(r.. l.... A, n:...
b7e851d5b33ddd5933ece43eb486bf591e622816
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/template.py
3,596
3.765625
4
___ checkdupsorting(myarray myarray.s..() print(myarray) ___ i __ r..(0, l..(myarray) - 1 #print "in for loop:", myarray # #print "comparing", myarray[i],"and",myarray[i + 1] __(myarray[i] __ myarray[i + 1] print("Duplicates present:", myarray[i]) r.. print("There are No duplicates present in the give...
6b580a86576e8fd66da3913d387948f109435da3
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+26 How to get Factorial using for loop.py
142
3.71875
4
x abs(i..(input("Insert any number: "))) factorial 1 ___ i __ r..(2, x+1): factorial * i print("The result of factorial = ",factorial)
81ce3ec1a4145c7283bdd087437cbc247b8113b5
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BinarySearch/35_SearchInsertPosition.py
623
3.984375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): # Pythonic way. def searchInsert(self, nums, target): return len([x for x in nums if x < target]) class Solution_2(object): def searchInsert(self, nums, target): left, right = 0, len(nums) - 1 while left <= ri...
a64c2c4481a7f03ccad171656f3430c81f4496db
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-18-find-the-most-common-word.py
2,185
4.25
4
""" Write a function that returns the most common (non stop)word in this Harry Potter text. Make sure you convert to lowercase, strip out non-alphanumeric characters and stopwords. Your function should return a tuple of (most_common_word, frequency). The template code already loads the Harry Potter text and list of s...
36508bf3a8e3ce4e963ed1bd87cd4cc8a3ea544c
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/HashTable/03_LongestSubstringWithoutRepeatingCharacters.py
978
3.796875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ max_length = 0 start = 0 # Start index of the substring without repeating characters end = 0 # End index of ...
371efe88e7ca05680323f02cfe926236502cfe7f
syurskyi/Python_Topics
/045_functions/007_lambda/examples/011_Reduce.py
776
3.6875
4
# -*- coding: utf-8 -*- import functools pairs = [(1, 'a'), (2, 'b'), (3, 'c')] functools.reduce(lambda acc, pair: acc + pair[0], pairs, 0) # 6 # Более идиоматический подход, использующий выражение генератора в качестве аргумента для sum() в следующем примере: pairs = [(1, 'a'), (2, 'b'), (3, 'c')] sum(x[0] for x in...
00749bb2dd415c70b26415b5422978884a33734b
syurskyi/Python_Topics
/125_algorithms/_exercises/exercises/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 7 - Binary Tree Preorder Traversal.py
679
3.546875
4
# # Return Binary Pre-order Traversal # # Question: Given a binary tree, return the preorder traversal of its nodes' values. # # For example: # # Given binary tree # # 1 # # \ # # 2 # # / # # 3 # # return [1,2,3]. # # Solutions: # # c_ TreeNode # ___ - x # val _ x # left _ N.. # right _ N....
d6457e1f59aa2e7f58e030cdc15209bc2e73432b
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 3 Search Algorithms/LinearSearch.py
489
4.1875
4
___ linear_search(container, item # the running time of this algorithms is O(N) # USE LINEAR SEARCH IF THE DATA STRUCTURE IS UNORDERED !!! ___ index __ ra__(le_(container)): __ container[index] __ item: # if we find the item: we return the index of that item r_ index ...
64ca8b540ac52c773140d97d22196aaf7268d94b
syurskyi/Python_Topics
/070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 8 Descriptors/89. Descriptors - Coding.py
3,231
4.28125
4
# %% ''' ### Descriptors ''' # %% ''' Python **descriptors** are simply objects that implement the **descriptor protocol**. The protocol is comprised of the following special methods - not all are required. - `__get__`: used to retrieve the property value - `__set__`: used to store the property value (we'll see where ...
4702c698e5276bb8733860edc189cfd5a221607f
syurskyi/Python_Topics
/070_oop/008_metaprogramming/examples/abc – Abstract Base Classes/a_005_abc_abc_base.py
1,052
3.875
4
# abc_abc_base.py import abc # Forgetting to set the metaclass properly means the concrete implementations do not have their APIs enforced. # To make it easier to set up the abstract class properly, a base class is provided that sets the metaclass # automatically. class PluginBase(abc.ABC): @abc.abstractmethod...
12d56a34a5952ccbb85cdb40137861ddad6e95b8
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 40 - BTSTIV.py
1,642
3.859375
4
# Best Time to Buy and Sell Stock IV # Question: 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 at most k transactions. # Note: You may not engage in multiple transactions at the same time (ie, you must sell the st...
b98b1c46993120ba213c3f1d0d80c523fe44c395
syurskyi/Python_Topics
/125_algorithms/_examples/100_Python_Exercises_Evaluate_and_Improve_Your_Skills/Exercise 88 - Data Filter NUKE.py
375
3.875
4
#Create a script that uses countries_by_area.txt file as data sourcea and prints out the top 5 most densely populated countries import pandas data = pandas.read_csv("countries_by_area.txt") data["density"] = data["population_2013"] / data["area_sqkm"] data = data.sort_values(by="density", ascending=False) for index,...
a06fe4550d4ccb21f4ad485acd3b9264c58ba76b
syurskyi/Python_Topics
/045_functions/007_lambda/__for_nuke/01-lambda_expressions.py
240
3.71875
4
# -*- coding: utf-8 -*- """Пример использования лямбда-выражений""" operations = { '+': lambda x, y: x + y, '-': lambda x, y: x - y } print(operations['+'](2, 3)) print(operations['-'](2, 3))
c858a7abbe63bd79904515fc6f70faf9e0f7eec2
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BitManipulation/78_Subsets.py
783
3.671875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- c.. Solution o.. ___ subsets nums """ :type nums: List[int] :rtype: List[List[int]] """ subsets # list n = l..(nums) nums.s.. ) # We know there are totally 2^n subsets, # becase every num may...
2e672e363875afa8a54d9c5726393acc3cd84ce5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/LinkedList/21_MergeTwoSortedLists.py
1,523
4
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 # Recursive way. c.. Solution o.. ___ mergeTwoLists l1, l2 __ n.. l1: r_ l2 __ n.. l2: ...
c1ce4711d2e14d61f0439136c8c3880790dd30f6
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Return_Value.py
1,503
3.765625
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 stu...
1b3f0818e49049b987df39945952e8017642aa19
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/topics/Itertools/99/seq_gen.py
298
3.890625
4
from string import ascii_uppercase from itertools import cycle def sequence_generator(): alphabet_list = cycle(ascii_uppercase) number_list = cycle(range(1,27)) for i in range(100): yield next(number_list) yield next(alphabet_list) print(list(sequence_generator()))
ab0688242ee45e648ef23c6aea22c389a47fb746
syurskyi/Python_Topics
/095_os_and_sys/_exercises/exercises/realpython/017_Deleting Files in Python.py
2,381
4.28125
4
# # To delete a single file, use pathlib.Path.unlink(), os.remove(). or os.unlink(). # # os.remove() and os.unlink() are semantically identical. To delete a file using os.remove(), do the following: # # ______ __ # # data_file _ 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt' # __.r.. ? # # # Deleting a file using os.un...
b8c6ccb80410275e974422a96b02f43f9351a69f
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Others/220_ContainsDuplicateIII.py
1,580
3.71875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com class Solution(object): """ Bucket sort. Refer to: https://leetcode.com/discuss/48670/o-n-python-using-buckets-with-explanation-10-lines 1. Each bucket i save one number, which satisfy val/(t+1) == i. 2. For each number,...
b6e934cfc5af74841bd8c4a8f951220163ce6bb0
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 92 - SortColours.py
757
4.15625
4
# Sort Colours # Question: Given an array with n objects coloured red, white or blue, sort them so that objects of the same colour are adjacent, with the colours in the order red, white and blue. # Here, we will use the integers 0, 1, and 2 to represent the colour red, white, and blue respectively. # Note: You are not ...
8b3ff422b9e6313a0af0302c628c4179f750d85e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/227 Basic Calculator II py3.py
2,303
4.21875
4
#!/usr/bin/python3 """ Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: "3+2*2" Output: 7 Example 2: Input: " 3/2 " Output: 1 Exa...
488ebbd9ad22d6996f92b80296358d32ca941bb1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/96_partition_list.py
759
3.921875
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ c_ Solution: """ @param: head: The first node of linked list @param: x: An integer @return: A ListNode """ ___ partition head, x __ n.. head:...
5f751b07f60be785b4018628e54e9d82da661f04
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/088 Merge Sorted Array.py
1,051
3.71875
4
""" Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. """ __author__ 'Danyang' c_ Solution(o.. ...