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
0291f8953312c8c71a778cb5defd91ca5c24ef09
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/AdvancedPython_OOP_with_Real_Words_Programs/App-6-Project-Calorie-Webapp/src/calorie.py
564
4.125
4
____ temperature _____ Temperature c_ Calorie: """Represents optimal calorie amount a person needs to take today""" ___ - weight, height, age, temperature): weight weight height height age age temperature temperature ___ calculate _ result 10 * weight + 6.5 * height + 5 - temperature * 10 r_ result __ _______ __ _______ temperature Temperature(country"italy", city"rome").get() calorie Calorie(weight70, height175, age32, temperaturetemperature) print(calorie.calculate())
242a80f51b4940791d36fd79320394742aaf4aa5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/Double Dice rolling.py
262
3.671875
4
#accept the range ___ i __ r..(i..(i.. ))): #accept the random numbers to be converted to double dice value a,b l.. m..(i..,i.. ).s..())) #calculate the double dice value res (a % 6 + 1 ) + (b % 6 + 1) #print the result print(res,end=' ')
23c0c2ee5b6165c16168522bf61bc190696b3161
syurskyi/Python_Topics
/079_high_performance/examples/Writing High Performance Python/item_49.py
1,819
4.15625
4
import logging from pprint import pprint from sys import stdout as STDOUT # Example 1 def palindrome(word): """Return True if the given word is a palindrome.""" return word == word[::-1] assert palindrome('tacocat') assert not palindrome('banana') # Example 2 print(repr(palindrome.__doc__)) # Example 3 """Library for testing words for various linguistic patterns. Testing how words relate to each other can be tricky sometimes! This module provides easy ways to determine when words you've found have special properties. Available functions: - palindrome: Determine if a word is a palindrome. - check_anagram: Determine if two words are anagrams. ... """ # Example 4 class Player(object): """Represents a player of the game. Subclasses may override the 'tick' method to provide custom animations for the player's movement depending on their power level, etc. Public attributes: - power: Unused power-ups (float between 0 and 1). - coins: Coins found during the level (integer). """ # Example 5 import itertools def find_anagrams(word, dictionary): """Find all anagrams for a word. This function only runs as fast as the test for membership in the 'dictionary' container. It will be slow if the dictionary is a list and fast if it's a set. Args: word: String of the target word. dictionary: Container with all strings that are known to be actual words. Returns: List of anagrams that were found. Empty if none were found. """ permutations = itertools.permutations(word, len(word)) possible = (''.join(x) for x in permutations) found = {word for word in possible if word in dictionary} return list(found) assert find_anagrams('pancakes', ['scanpeak']) == ['scanpeak']
22055e3af9f95eb89f34a2f28ba24c3fe1c6584c
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Graph/133_CloneGraph.py
1,075
3.71875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a undirected graph node # class UndirectedGraphNode(object): # def __init__(self, x): # self.label = x # self.neighbors = [] c.. Solution o.. ___ cloneGraph node __ n.. node: r_ None copyed_node_pair _ # dict copy_head = UndirectedGraphNode(node.label) copy_head.neighbors # list copyed_node_pair[node] = copy_head nodes_stack # list nodes_stack.a.. node) _____ nodes_stack: one_node = nodes_stack.pop() ___ neighbor __ one_node.neighbors: __ neighbor n.. __ copyed_node_pair: copy_node = UndirectedGraphNode(neighbor.label) copy_node.neighbors # list copyed_node_pair[neighbor] = copy_node nodes_stack.a.. neighbor) copyed_node_pair[one_node].neighbors.a.. copyed_node_pair[neighbor]) r_ copy_head """ {0,0,0} {0,1,2#1,2#2,2} """
7b534d6967a16e1c6752b6ecf484d6d8c1d25a9e
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Math/335_SelfCrossing.py
1,428
3.96875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com # @Last Modified time: 2016-04-05 16:17:53 """ According to: https://leetcode.com/discuss/88153/another-python Draw a line of length a. Then draw further lines of lengths b, c, etc. How does the a-line get crossed? From the left by the d-line or from the right by the f-line. b b +----------------+ +----------------+ | | | | | | | | a c | | c | | | | a | | f +------------------> | <---------+ d | | | | e | | | +-----------------------+ d The "special case" of the e-line stabbing the a-line from below. """ class Solution(object): def isSelfCrossing(self, x): if not x or len(x) < 4: return False b = c = d = e = f = 0 # Initinal for a in x: if d >= b > 0 and (a >= c > 0 or (a >= c-e >= 0 and f >= d-b)): return True b, c, d, e, f = a, b, c, d, e return False """ [] [2,2] [1,1,1,1] [6,4,3,2,2,1,5] [1,1,2,2,3,3,4,4] """
cc75cc8322dfc9ae9ef6a5ccb943a848537c9be8
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/36_reverse_linked_list_ii.py
1,012
4.03125
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ c_ Solution: """ @param: head: ListNode head is the head of the linked list @param: m: An integer @param: n: An integer @return: The head of the reversed ListNode """ ___ reverseBetween head, m, n __ n.. head: r.. """ to get to `n`th node from `m`th node needs `n - m` operations """ n -_ m """ `A` will stay at `m-1`th node """ A dummy ListNode(-1, head) w.... m > 1: m -_ 1 A A.next """ `B` will stay at `n+1`th node `cur` stay at (`m`th -> `n`th) node """ B cur A.next pre nxt N.. w.... n >_ 0: n -_ 1 nxt B.next B.next pre pre B B nxt A.next pre cur.next B r.. dummy.next
2f0cd45309945619d5e95e75abf7be9718989ddf
syurskyi/Python_Topics
/120_design_patterns/009_decorator/_exercises/templates/decorator_003.py
1,334
4.1875
4
# """Decorator pattern # # Decorator is a structural design pattern. It is used to extend (decorate) the # functionality of a certain object at run-time, independently of other instances # of the same class. # The decorator pattern is an alternative to subclassing. Subclassing adds # behavior at compile time, and the change affects all instances of the original # class; decorating can provide new behavior at run-time for selective objects. # """ # # # c_ Component o.. # # # method we want to decorate # # ___ whoami # print("I am @".f.. i. ? # # # method we don't want to decorate # # ___ another_method # print("I am just another method of @".f.. -c. -n # # # c_ ComponentDecorator o.. # # ___ - decoratee # _? ? # reference of the original object # # ___ whoami # print("start of decorated method") # _d___.w.. # print("end of decorated method") # # # forward all "Component" methods we don't want to decorate to the # # "Component" pointer # # ___ -g name # r_ g.. _d... ? # # # ___ main # a = C... # original object # b = CD__ ? # decorate the original object at run-time # print("Original object") # a.w... # a.a.. # print("\nDecorated object") # b.w.. # b.a.. # # # __ _______ __ ______ # ?
19a961e8b85c8e1ed1babc8cf85b01cf04441e95
syurskyi/Python_Topics
/080_tracing/_exercises/templates/traceback — Exceptions and Stack Traces/007_Low-level Exception APIs.py
1,170
3.640625
4
# print_exception() uses format_exception() to prepare the text. # traceback_format_exception.py import traceback import sys from pprint import pprint from traceback_example import produce_exception try: produce_exception() except Exception as err: print('format_exception():') exc_type, exc_value, exc_tb = sys.exc_info() pprint( traceback.format_exception(exc_type, exc_value, exc_tb), width=65, ) # The same three arguments, exception type, exception value, and traceback, are used with format_exception(). # # $ python3 traceback_format_exception.py # # format_exception(): # ['Traceback (most recent call last):\n', # ' File "traceback_format_exception.py", line 17, in # <module>\n' # ' produce_exception()\n', # ' File ' # '".../traceback_example.py", ' # 'line 17, in produce_exception\n' # ' produce_exception(recursion_level - 1)\n', # ' File ' # '".../traceback_example.py", ' # 'line 17, in produce_exception\n' # ' produce_exception(recursion_level - 1)\n', # ' File ' # '".../traceback_example.py", ' # 'line 19, in produce_exception\n' # ' raise RuntimeError()\n', # 'RuntimeError\n']
3e287897a85f9b2c948f37a3ffe3c6b265490943
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Stack/ReverseAStackByRecursive.py
510
3.75
4
""" 只能用递归不能用其他数据结构来逆序一个栈。 可以用另一个新栈的话比较容易。 """ from GetMinStack import Stack def reverseStack(stacks): new_stack = Stack() def helper(stacks): if stacks.empty(): return new_stack.push(stacks.pop()) helper(stacks) helper(stacks) return new_stack # 测试用例。 a = range(10) b = Stack() for i in a: b.push(i) # 不用assert了。 print(b) print(reverseStack(b))
3ce6a0530910c15c3b0f97ad0a7a4b9fddf627c3
syurskyi/Python_Topics
/045_functions/007_lambda/_exercises/exercises/007_lambda_template.py
3,654
4.25
4
# -*- coding: utf-8 -*- # An example of using anonymous functions # f1 = l_: 10 + 20 # Функция без параметров # f2 = l_ x_ y_ x + y # Функция с двумя параметрами # f3 = l_ x y z_ x + y + z # Функция с тремя параметрами # print(f1()) # Выведет: 30 # print(f2(5, 10)) # Выведет: 15 # print(f3(5, 10, 30)) # Выведет: 45 # print() # ###################################################################################################################### # Optional parameters in anonymous functions # f = l_ x y=2_ x + y # print(f(5)) # Выведет: 7 # print(f(5, 6)) # Выведет: 11 # # print() # ###################################################################################################################### # Lambda Expressions # l_ x| x**2 # # print() # ###################################################################################################################### # Lambda Assigning to a Variable # func _ l_ x| x**2 # # type func # func 3 # # print() # ###################################################################################################################### # We can specify arguments for lambdas just like we would for any function created using def, except for annotations: # func_1 _ l_ x y_10| (x y) # func_1 1 2 # func_1 1 # # print() # ###################################################################################################################### # Lambda We can even use * and **: # func_2 _ l_ x _args y __kwargs| (x _args y {__kwargs}) # # func_2 1 'a' 'b' y_100 a_10 b_20 # # print() # ###################################################################################################################### # Lambda # Passing as an Argument # Lambdas are functions, and can therefore be passed to any other function as an argument # (or returned from another function) # ___ apply_func x fn # r_ fn x # apply_func 3 l_ x| x**2 # apply_func 3 l_ x| x**3 # # print() # ###################################################################################################################### # Lambda # Passing as an Argument # Lambdas are functions, and can therefore be passed to any other function as an argument # (or returned from another function) # we can make this even more generic: # ___ apply_func fn _args __kwargs # r_ fn _args __kwargs # # apply_func l_ x y| x+y 1 2 # apply_func l_ x _ y| x+y 1 y_2 # apply_func l_ _args| s_ args 1 2 3 4 5 # # print() # ###################################################################################################################### # Lambdas and Sorting # l = ['a', 'B', 'c', 'D'] # s_ l # s_ l key_s_.u_ # # # We could have used a lambda here (but you should not, this is just to illustrate using a lambda in this case): # # s_ l key _ l_ s| s.u_ # # print() # ###################################################################################################################### # Lambdas and Sorting # Let's look at how we might create a sorted list from a dictionary: # d = {'def': 300, 'abc': 200, 'ghi': 100} # d # s_ d # # s_ d key_l_ k| d|k| # # print() # ###################################################################################################################### # Пример использования лямбда-выражений # # operations = { # '+': l_ x, y: x + y, # '-': l_ x, y: x - y # } # # print(oper___['+'](2, 3)) # print(oper___['-'](2, 3)) # # print()
1e11e649770bc1016e7babd381ba315750367a03
syurskyi/Python_Topics
/045_functions/008_built_in_functions/map/examples/006_Python map() with string.py
2,072
4.375
4
def to_upper_case(s): return str(s).upper() def print_iterator(it): for x in it: print(x, end=' ') print('') # for new line # map() with string map_iterator = map(to_upper_case, 'abc') print(type(map_iterator)) print_iterator(map_iterator) # Output: # <class 'map'> # A B C # Python map() with tuple # map() with tuple map_iterator = map(to_upper_case, (1, 'a', 'abc')) print_iterator(map_iterator) # Output: # 1 A ABC # Python map() with list map_iterator = map(to_upper_case, ['x', 'a', 'abc']) print_iterator(map_iterator) # X A ABC # Converting map to list, tuple, set map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_list = list(map_iterator) print(my_list) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_set = set(map_iterator) print(my_set) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_tuple = tuple(map_iterator) print(my_tuple) # Output: # ['A', 'B', 'C'] # {'C', 'B', 'A'} # ('A', 'B', 'C') # Python map() with lambda list_numbers = [1, 2, 3, 4] map_iterator = map(lambda x: x * 2, list_numbers) print_iterator(map_iterator) # Output: # 2 4 6 8 # map() with multiple iterable arguments list_numbers = [1, 2, 3, 4] tuple_numbers = (5, 6, 7, 8) map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers) print_iterator(map_iterator) # Output: 5 12 21 32 # map() with multiple iterable arguments of different sizes list_numbers = [1, 2, 3, 4] tuple_numbers = (5, 6, 7, 8, 9, 10) map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers) print_iterator(map_iterator) map_iterator = map(lambda x, y: x * y, tuple_numbers, list_numbers) print_iterator(map_iterator) # Output: # 5 12 21 32 # 5 12 21 32 # Python map() with function None # map_iterator = map(None, 'abc') # print(map_iterator) # for x in map_iterator: # print(x) # Output: # # # Traceback (most recent call last): # File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_map_example.py", line 3, in <module> # for x in map_iterator: # TypeError: 'NoneType' object is not callable
68185a6fd9ceb61e1933d9edb9d0f79a7efe2073
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/MinimumIndexSumOfTwoLists.py
2,157
3.984375
4
""" Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. Example 1: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: ["Shogun"] Explanation: The only restaurant they both like is "Shogun". Example 2: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["KFC", "Shogun", "Burger King"] Output: ["Shogun"] Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1). Note: The length of both lists will be in the range of [1, 1000]. The length of strings in both lists will be in the range of [1, 30]. The index is starting from 0 to the list length minus 1. No duplicates in both lists. 给两个列表,求加起来的索引是最小的重合部分,若有多个相同的则输出多个相同的,无顺序要求。 思路: 直接判断的话是 O(mn),利用哈希表(字典)来减少查询时间。 可优化部分: 第二次不用哈希表,用两个变量,一个代表当前的最小值,一个代表所存数据,不断替换,追加。 测试用例: https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/ """ class Solution(object): def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ list1_dict = {value:index for index, value in enumerate(list1)} commonInterest = {} for index, value in enumerate(list2): if list1_dict.get(value) is not None: try: commonInterest[index + list1_dict.get(value)].append(value) except KeyError: commonInterest[index + list1_dict.get(value)] = [value] return commonInterest[min(commonInterest)]
ee5aada9b9038f1262e4b8d07a2ad5bdeb8a076c
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/advanced/42/guess.py
2,517
4.15625
4
# _______ r__ # MAX_GUESSES 5 # START, END 1, 20 # # # ___ get_random_number # """Get a random number between START and END, returns int""" # r.. r__.r.. ? # # # c_ Game # """Number guess class, make it callable to initiate game""" # # ___ - # """Init _guesses, _answer, _win to set(), get_random_number(), False""" # _guesses s.. # _answer ? # _win F.. # # # # # # ___ guess # """Ask user for input, convert to int, raise ValueError outputting # the following errors when applicable: # 'Please enter a number' # 'Should be a number' # 'Number not in range' # 'Already guessed' # If all good, return the int""" # # w... T... # ___ # number i.. "Guess a number between 1 and 20: ") # result i.. ? # ______: # __ ? __ N.. o. l.. ? __ 0 # print('Please enter a number') # ____ # print('Should be a number') # r.. V... # ____ # __ n.. ? <_ ? <_ ? # print('Number not in range') # ____ ? __ _? # print('Already guessed') # ____ # _?.a.. ? # r.. ? # r.. V... # # # # # # # # # # ___ _validate_guess guess # """Verify if guess is correct, print the following when applicable: # {guess} is correct! # {guess} is too low # {guess} is too high # Return a boolean""" # # correct F.. # __ ? __ _answer # print _*? is correct! # ? T.. # ____ ? > _? # print _*? is too high # ____ # print _*? is too low # # r.. ? # ___ -c # """Entry point / game loop, use a loop break/continue, # see the tests for the exact win/lose messaging""" # # # ___ i __ r.. 1 M.. + 1 # w... T... # ___ # user_guess ? # ______ V.. # p.. # ____ # _____ # # # _win _v.. u.. # # # __ ? # _____ # # # __ ? # print _*It took you ? guesses # ____ # print _*Guessed 5 times, answer was ? # # # # # # # # # # # # __ _____ __ _____ # game ? # g?
8025d7201eedf7d82b483310c569a1fbd7f599bd
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/78/common.py
644
3.84375
4
programmers = dict(bob=['JS', 'PHP', 'Python', 'Perl', 'Java'], tim=['Python', 'Haskell', 'C++', 'JS'], sara=['Perl', 'C', 'Java', 'Python', 'JS'], paul=['C++', 'JS', 'Python']) def common_languages(programmers): """Receive a dict of keys -> names and values -> a sequence of of programming languages, return the common languages""" lang_list = [set(lang_list) for lang_list in programmers.values()] return_set = lang_list[0] for lang_set in lang_list[1:]: return_set = return_set.intersection(lang_set) return return_set print(common_languages(programmers))
08beeeeeb4f848ab756f2c8a3fdd0f6189b58349
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 2 Recursion/TowersHanoi.py
436
3.65625
4
# # ___ hanoi disk, source, middle, destination # # # this is the base case -index 0 is always the smallest plate # # we manipulate the smallest plate in the base case # __ ? __ 0 # print('Disk @ from @ to @' ? ? ? # r_ # # ? ? - 1 ? ? ? # # this is not necessarily the largest plate - this is not the plate 0 # print('Disk @ from @ to @' ? ? ? # ? ? - 1 ? ? ? # # # ? (20, 'A', 'B', 'C')
0fec0dfce518432a333ceae9e8ab900dfa7f5340
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/37/countdown.py
251
3.703125
4
# ___ countdown_for start=10 # ___ i __ r.. r.. 1, ? + 1 # print ? # print('time is up') # # # ___ countdown_recursive start=10 # # __ ? __ 0 # print('time is up') # r.. # # # print ? # # ? ? -1 # # # # # #
72882dfdf8cdecafedab9859163028bb722a2ee9
syurskyi/Python_Topics
/090_logging/examples/Logging in Python/008_Other Configuration Methods_conf.py
1,179
3.53125
4
# You can configure logging as shown above using the module and class functions or by creating a config file or # a dictionary and loading it using fileConfig() or dictConfig() respectively. These are useful in case you want # to change your logging configuration in a running application. # # Here is an example file configuration: # In the above file, there are two loggers, one handler, and one formatter. After their names are defined, # they are configured by adding the words logger, handler, and formatter before their names separated by an underscore. # # To load this config file, you have to use fileConfig(): import logging import logging.config logging.config.fileConfig(fname='file.conf', disable_existing_loggers=False) # Get the logger specified in the file logger = logging.getLogger(__name__) logger.debug('This is a debug message') # 2018-07-13 13:57:45,467 - __main__ - DEBUG - This is a debug message # The path of the config file is passed as a parameter to the fileConfig() method, and the disable_existing_loggers # parameter is used to keep or disable the loggers that are present when the function is called. It defaults to True if # not mentioned.
b4ac71ff4822751cff631103d7e2f9e52c9caeb6
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/LinkedList/234_PalindromeLinkedList.py
1,096
4.0625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): slow, fast, new_head = head, head, None # Reverse the first half while finding the middle. while fast and fast.next: fast = fast.next.next # Reverse the slow nodes, Pythonic way new_head, new_head.next, slow = slow, new_head, slow.next """ More general way next_node = slow.next slow.next = new_head new_head = slow slow = next_node """ # Midle node is slow or slow.next according to the len of list. if fast: slow = slow.next # Compare the reversed(pre_half) and post half while new_head and new_head.val == slow.val: new_head, slow = new_head.next, slow.next return not new_head """ [] [1] [1,2,2,1] [1,2,3,2,1] [1,2,3,4] """
d1d21e09f523d5c36453086f6f8a0c5c8a141b27
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/290_newbie_bite/save1_nopass.py
204
3.78125
4
# # List of car brands for you to iterate through # car_brands = 'Mazda', 'McLaren', 'Opel', 'Toyota', 'Honda' # # # # Pass in the car_brands list and code the for loop. # ___ list_cars # print(cars)
236cfd3e2f62c7660216fb0a30c1c12c01fe791e
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/exercises/Learning Python/039_003_Classes Are Instances of type.py
1,685
3.625
4
# print(ty..([])) # In 3.0 list is instance of list type # # <class 'list'> # print(ty..(ty..([]))) # Type of list is type class # # <class 'type'> # # print(ty..(li.. # Same, but with type names # # <class 'type'> # print(ty..(ty..)) # Type of type is type: top of hierarchy # # <class 'type'> # # print(ty..([])) # In 2.6, type is a bit different # # <type 'list'> # print(ty..(ty..([]))) # # <type 'type'> # # print(ty..(li.. # # <type 'type'> # print(ty..(ty..)) # # <type 'type'> # # class C: pass # 3.0 class object (new-style) # # X = C() # Class instance object # # print(ty..(X)) # Instance is instance of class # # <class '__main__.C'> # print(X.__class__) # Instance's class # # <class '__main__.C'> # # print(ty..(C)) # Class is instance of type # # <class 'type'> # print(C.__class__) # Class's class is type # # <class 'type'> # # # c_ C(o.. p.. # In 2.6 new-style classes, # # classes have a class too # X = C() # # print(ty..(X)) # # <class '__main__.C'> # print(ty..(C)) # # <type 'type'> # # print(X.__class__) # # <class '__main__.C'> # print(C.__class__) # # <type 'type'> # # c_ C p... # In 2.6 classic classes, # # classes have no class themselves # X = C() # # print(ty..(X)) # # <type 'instance'> # print(ty..(C)) # # <type 'classobj'> # # print(X.__class__) # # <class __main__.C at 0x005F85A0> # print(C.__class__) # # AttributeError: class C has no attribute '__class__' #
5d2f7f98d7e2ab0ff8346c87ca49169d64c51faa
syurskyi/Python_Topics
/095_os_and_sys/examples/realpython/021_Copying Directories.py
741
3.515625
4
# While shutil.copy() only copies a single file, shutil.copytree() will copy an entire directory and everything # contained in it. shutil.copytree(src, dest) takes two arguments: a source directory and the destination directory # where files and folders will be copied to. # # Here’s an example of how to copy the contents of one folder to a different location: # import shutil shutil.copytree('data_1', 'data1_backup') # 'data1_backup' # # In this example, .copytree() copies the contents of data_1 to a new location data1_backup and returns the destination # directory. The destination directory must not already exist. It will be created as well # as missing parent directories. shutil.copytree() is a good way to back up your files.
0530bc18101b06050dfc0fe9b215b99276a45bcd
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Practice_Python_by_Solving_100_Python_Problems/59.py
162
3.8125
4
# #Print out three lines saying for instance item 1 has index 0, and so on. # a = [1, 2, 3] # # ___ index, item __ e__ ? # print("Item __ has index __" _ ? ?
4c3aa79a386db44a2bb76cfbf551c8f2d1d0fb88
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/900_closest_binary_search_tree_value.py
725
3.625
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ c_ Solution: ___ closestValue root, target """ :type root: TreeNode :type target: float :rtype: int """ __ n.. root: r.. f__ '-inf' __ root.left a.. target < root.val: left closestValue(root.left, target) __ a..(left - target) < a..(root.val - target r.. left __ root.right a.. target > root.val: right closestValue(root.right, target) __ a..(right - target) < a..(root.val - target r.. right r.. root.val
386c91256cdd3ee4cca357d861887ab923830c6f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/738 Monotone Increasing Digits.py
1,014
4.03125
4
#!/usr/bin/python3 """ Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9]. """ c_ Solution: ___ monotoneIncreasingDigits N: i.. __ i.. """ 332 322 222 fill 9 299 """ d.. [i..(e) ___ e __ s..(N)] pointer l..(d..) ___ i __ r..(l..(d..) - 1, 0, -1 __ d..[i - 1] > d..[i]: pointer i d..[i - 1] -_ 1 ___ i __ r..(pointer, l..(d..: d..[i] 9 r.. i..("".j.. m..(s.., d..))) __ _______ __ _______ ... Solution().monotoneIncreasingDigits(10) __ 9 ... Solution().monotoneIncreasingDigits(332) __ 299
1be54b84d0949dc683432acfc41b13cde9f570c1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+99 How to calculate the Area and Perimeter of Right Angle Triangle.py
276
4.1875
4
_______ math x float(input("Insert length of x: ")) y float(input("Insert length of y: ")) z math.sqrt((pow(x,2)+pow(y,2))) Area (x*y)/2 Perimeter x+y+z print("Area of right angled triangle = %.2f" % Area) print("Perimeter of right angled triangle = %.2f" % Perimeter)
b7e17d3710c68df3ebf3b937d389f40cf4257d7e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/959 Regions Cut By Slashes.py
2,876
4.1875
4
#!/usr/bin/python3 """ In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space. These characters divide the square into contiguous regions. (Note that backslash characters are escaped, so a \ is represented as "\\".) Return the number of regions. Example 1: Input: [ " /", "/ " ] Output: 2 Explanation: The 2x2 grid is as follows: Example 2: Input: [ " /", " " ] Output: 1 Explanation: The 2x2 grid is as follows: Example 3: Input: [ "\\/", "/\\" ] Output: 4 Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.) The 2x2 grid is as follows: Example 4: Input: [ "/\\", "\\/" ] Output: 5 Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.) The 2x2 grid is as follows: Example 5: Input: [ "//", "/ " ] Output: 3 Explanation: The 2x2 grid is as follows: Note: 1 <= grid.length == grid[0].length <= 30 grid[i][j] is either '/', '\', or ' '. """ ____ t___ _______ L.. c_ DisjointSet: ___ - """ unbalanced DisjointSet """ pi # dict ___ union x, y pi_x f.. x) pi_y f.. y) pi[pi_y] pi_x ___ find x # LHS self.pi[x] __ x n.. __ pi: pi[x] x __ pi[x] !_ x: pi[x] f.. pi[x]) r.. pi[x] c_ Solution: ___ regionsBySlashes grid: L..s.. __ i.. """ in 1 x 1 cell 3 possibilities ___ | | |___| ___ | /| |/__| ___ |\ | |__\| 4 regions in the ___ |\ /| |/_\| """ m, n l..(grid), l..(grid 0 ds DisjointSet() T, R, B, L r..(4) # top, right, bottom, left ___ i __ r..(m ___ j __ r..(n e grid[i][j] __ e __ "/" o. e __ " ": ds.union((i, j, B), (i, j, R ds.union((i, j, T), (i, j, L __ e __ "\\" o. e __ " ": # not elif ds.union((i, j, T), (i, j, R ds.union((i, j, B), (i, j, L # nbr __ i - 1 >_ 0: ds.union((i, j, T), (i-1, j, B __ j - 1 >_ 0: ds.union((i, j, L), (i, j-1, R # unnessary, half closed half open # if i + 1 < m: # ds.union((i, j, B), (i+1, j, T)) # if j + 1 < n: # ds.union((i, j, R), (i, j+1, L)) r.. l..(s..( ds.f.. x) ___ x __ ds.pi.k.. __ _______ __ _______ ... Solution().regionsBySlashes([ " /", "/ " ]) __ 2 ... Solution().regionsBySlashes([ "//", "/ " ]) __ 3
12c9d4674dd76d33772547c20f2324989c6c0c0f
syurskyi/Python_Topics
/110_concurrency_parallelism/002_threads/_exercises/exercises/ITVDN_Python_Advanced/example3_local.py
1,557
3.609375
4
import threading print(threading.active_count()) current = threading.current_thread() print(current.getName()) print(current.is_alive()) # # что произойдет, если попробуем еще раз его запустить try: current.start() except RuntimeError as e: print('ERROR: {error}'.format(error=e)) current.setName('SuperThread') print(current.getName()) # # # на самом деле setName, getName - это просто старый интерфейс. # # В реальных задачах вы смело можете работаь напрямую с атрибутом name current.name = 'SuperThread1' print(current.name) print(current.getName()) # # # вывод всех запущенных и живых трэдов print(threading.enumerate()) # # # Напишем пример для демонстрации потокобезопасного хранилища данных. thread_data = threading.local() thread_data.value = 5 def print_results(): print(threading.current_thread()) print('Result: {}'.format(thread_data.value)) def counter(started, to_value): print(hasattr(thread_data, 'value')) thread_data.value = started for i in range(to_value): thread_data.value += 1 print_results() task1 = threading.Thread(target=counter, args=(0, 10), name='Task1') task2 = threading.Thread(target=counter, args=(100, 3), name='Task2') task1.name = 'task1' task2.name = 'task2' task1.start() task2.start() print_results() task1.join() task2.join() print_results()
2901e2dbaab6f155dfd2d32feeed803ef2d07a5d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/674 Longest Continuous Increasing Subsequence.py
978
4.15625
4
#!/usr/bin/python3 """ Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. Example 2: Input: [2,2,2,2,2] Output: 1 Explanation: The longest continuous increasing subsequence is [2], its length is 1. Note: Length of the array will not exceed 10,000. """ ____ t___ _______ L.. c_ Solution: ___ findLengthOfLCIS nums: L.. i.. __ i.. """ pointer is sufficient """ __ n.. nums: r.. 0 ret 1 i 1 w.... i < l..(nums cur 1 w.... i < l..(nums) a.. nums[i] > nums[i-1]: cur += 1 i += 1 i += 1 ret m..(ret, cur) r.. ret
7e268f53812fe3b81eeda97a72fb4f36320cafe9
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/57_v2/calculator.py
1,811
3.578125
4
# _______ a__ # _______ f.. # # ___ calculator f numbers # """TODO 1: # Create a calculator that takes an operation and list of numbers. # Perform the operation returning the result rounded to 2 decimals""" # # # # r.. r.. f...r.. l.... x,y| ? ? ? ? 2 # # # # ___ create_parser # """TODO 2: # Create an ArgumentParser object: # - have one operation argument, # - have one or more integers that can be operated on. # Returns a argparse.ArgumentParser object. # # Note that type=float times out here so do the casting in the calculator # function above!""" # ap a__.A..("A simple calculator") # group ?.a.. required=T.. # ?.a.. "-m",'--mul',a.._'store_true' h.._"Multiplies numbers" # ?.a.. "-s",'--sub',a.._'store_true' h.._"Subtracts numbers" # ?.a.. "-a",'--add',a.._'store_true' h.._"Sums numbers" # ?.a.. "-d",'--div',a.._'store_true' h.._"Divides numbers" # ap.a..('numbers' nargs_'+' t.._f__ # # r.. ap # # # ___ call_calculator args=N.., stdout=F.. # """Provided/done: # Calls calculator with provided args object. # If args are not provided get them via create_parser, # if stdout is True print the result""" # parser ? # # __ args __ N.. # a.. v.. ?.p.. # # taking the first operation in args namespace # # if combo, e.g. -a and -s, take the first one # ____ # ? v.. ? # numbers ? 'numbers' # __ ? 'mul' # f l.... x,y ? * ? # ____ ? 'sub' # f l.... x,y ? - ? # ____ ? 'add' # f l.... x,y ? + ? # ____ ? 'div' # f l.... x,y ? / ? # # # ___ # res ? ? n.. # ______ Z.. # ? 0 # # # __ stdout # print ? # # r.. ? # # # # __ _____ __ _____ # ? s.._T..
e666a664cc341955d01a29a7ca86400c0596f039
syurskyi/Python_Topics
/018_dictionaries/_templates/sort_dictionary/004.py
1,328
3.796875
4
# # Sort Dictionary Using a for Loop # # dict1 = {1: 1, 2: 9, 3: 4} # sorted_values = s.. ?.v.. # Sort the values # sorted_dict # dict # # ___ i __ ? # ___ k __ ?.k.. # __ ? ? __ ? # ? ? = ? ? # b.. # # print ? # # # Sort Dictionary Using the sorted() Function # # dict1 {1: 1, 2: 9, 3: 4} # sorted_dict # dict # sorted_keys s.. ? k.._?.g.. # [1, 3, 2] # # ___ w __ ? # ? ? = ? ? # # print ? # {1: 1, 3: 4, 2: 9} # # # Sort Dictionary Using the operator Module and itemgetter() # # _____ o__ # # dict1 {1: 1, 2: 9} # get_item_with_key_2 o__.i.. 2 # # print ? ? # 9 # # _____ o__ # # dict1 {1: 1, 2: 9, 3: 4} # sorted_tuples s.. ?.i.., k.._o__.i.. 1 # print ? # [(1, 1), (3, 4), (2, 9)] # sorted_dict k v ___ ? ? __ ? # # print ? # {1: 1, 3: 4, 2: 9} # # # Sort Dictionary Using a Lambda Function # # dict1 {1: 1, 2: 9, 3: 4} # sorted_tuples s.. ?.i.. k.._l... item ? 1 # print ? # [(1, 1), (3, 4), (2, 9)] # sorted_dict k v ___ ? ? __ ? # # print ? # {1: 1, 3: 4, 2: 9} # # # Returning a New Dictionary with Sorted Values # # _____ o__ # _____ c.. _____ O.. # # dict1 {1: 1, 2: 9, 3: 4} # sorted_tuples s.. ?.i.. k.._o__.i.. 1 # print ? # [(1, 1), (3, 4), (2, 9)] # # sorted_dict O.. # ___ k v __ ? # ? ? = ? # # print ? # {1: 1, 3: 4, 2: 9}
d7aaee2fc6997e16c23a8fb52674cda37660967e
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 74 - PermutationsII.py
833
3.859375
4
# Permutations II # Question: Given a collection of numbers that might contain duplicates, return all possible unique permutations. # For example: # [1,1,2] have the following unique permutations: # [ [1,1,2], [1,2,1], [2,1,1] ] # Solutions: class Solution: # @param num, a list of integer # @return a list of lists of integers def permuteUnique(self, num): length = len(num) if length == 0: return [] if length == 1: return [num] num.sort() res = [] previousNum = None for i in range(length): if num[i] == previousNum: continue previousNum = num[i] for j in self.permuteUnique(num[:i] + num[i+1:]): res.append([num[i]] + j) return res Solution().permuteUnique([1,1,2])
7281ca5442e46a66c75d4a2d2a4e77e7f30298cc
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/leetcode/124_binary_tree_maximum_path_sum.py
1,239
3.90625
4
""" Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ c_ Solution: ___ maxPathSum root """ :type root: TreeNode :rtype: int """ __ n.. root: r.. 0 ans, _ divide_conquer(root) r.. ans ___ divide_conquer node __ n.. node: r.. f__ '-inf', 0 max_left, left divide_conquer(node.left) max_right, right divide_conquer(node.right) # 0 means discard the negative path res m..(max_left, max_right, node.val + left + right) p.. m..(node.val + left, node.val + right, 0) r.. res, p.. c_ Solution: ___ maxPathSum root """ :type root: TreeNode :rtype: int """ __ n.. root: r.. 0 ans f__ '-inf' divide_conquer(root) r.. ans ___ divide_conquer node __ n.. node: r.. 0 left m..(0, divide_conquer(node.left right m..(0, divide_conquer(node.right __ node.val + left + right > ans: ans node.val + left + right r.. node.val + m..(left, right)
69accf57e5d5b8c3921c910a0f19e3b4def863dc
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/topics/supplementary exercises/e0001-zip.py
857
4.53125
5
# zip(), lists, tuples # list is a sequence type # list can hold heterogenous elements # list is mutable - can expand, shrink, elements can be modified # list is iterable # tuple is a sequence type # tuple can hold heterogeneous data # tuple is immutable # tuple is iterable # Test case 1 - when iterables are of equal length def test_case1(): list1 = [ 1, 2, 3] list2 = [ 'a', 'b', 'c'] list3 = [ 'red', 'blue', 'green'] result = zip(list1, list2, list3) print(type(result)) for e in result: print(e) print(type(e)) # Test case 2 - when iterables are of unequal length def test_case2(): list1 = [ 1, 2, 3] list2 = [ 'a', 'b', 'c'] list3 = [ 'red', 'blue'] result = zip(list1, list2, list3) print(type(result)) for e in result: print(e) print(type(e)) test_case2()
fb32447bdacb68f154c47ea7b0640257c71e104c
syurskyi/Python_Topics
/095_os_and_sys/_exercises/exercises/Python pathlib tutorial/013_list_dirs.py
358
3.796875
4
# The iterdir() yields path objects of the directory contents. # list_dirs.py #!/usr/bin/env python from pathlib import Path path = Path('C:/Users/Jano/Documents') dirs = [e for e in path.iterdir() if e.is_dir()] print(dirs) # The example prints the subdirectories of the specified directory. # We check if the path object is a directory with is_dir().
240c7407c29123e8f2818d72b6ffe2b826671ab3
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 17 Recursion/greatest_gcd_solution.py
352
3.75
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # Write a Python program to find the greatest common divisor (gcd) of two integers. def Recurgcd(a, b): low = min(a, b) high = max(a, b) if low == 0: return high elif low == 1: return 1 else: return Recurgcd(low, high%low) print(Recurgcd(12,14))
1a44eeb8a042f963e304b61740de0d81c59b234b
syurskyi/Python_Topics
/070_oop/001_classes/examples/ITDN Python RUS/002_Nasledovanie i Polimorfizm/08-isinstance.py
807
3.640625
4
# -*- coding: utf-8 -*- """ isinstance(obj, cls) проверяет, является ли obj экземпляром класса cls или класса, который является наследником класса cls """ print(isinstance(8, int)) # True print(isinstance('str', int)) # False print(isinstance(True, bool)) # True print(isinstance(True, int)) # True, так как bool -- подкласс int print(isinstance('a string', object)) # True, всё является объектами print(isinstance(None, object)) # True, даже None print(isinstance(False, str)) # False print(isinstance(int, type)) # True, любой класс -- объект-экземпляр метакласса type print(isinstance(42, type)) # False, 42 -- это не тип данных
390f3dfa31af8cd69e4ba47d4e9af1a33788ff2f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 86 - ReverseLLII.py
1,243
3.796875
4
# # Reverse Linked List II # # Question: Reverse a linked list from position m to n. Do it in-place and in one-pass. # # For example: # # Given 1->2->3->4->5->NULL, m = 2 and n = 4, # # Return 1->4->3->2->5->NULL. # # Note: Given m, n satisfy the following condition: # # 1 ≤ m ≤ n ≤ length of list. # # Solutions: # # # c_ ListNode object # ___ - x # val _ x # next _ N.. # # ___ to_list # r_ v.. + n__.t.. __ ? ____ v.. # # # c_ Solution object # ___ reverseBetween head m n # """ # :type head: ListNode # :type m: i.. # :type n: i.. # :rtype: ListNode # """ # dummy _ ? -1 # ?.n.. _ h.. # node _ d.. # ___ __ __ ra.. m - 1 # n.. _ ?.n.. # prev _ ?.n.. # curr _ p__.n.. # ___ __ __ ra.. ? - ? # n.. _ c__.n.. # c__.n.. _ p.. # p.. _ c.. # c.. _ n.. # ?.n...n.. _ c.. # ?.n.. _ p.. # r_ d__.n.. # # # __ -n __ _____ # n1 _ ? 1 # n2 _ ? 2 # n3 _ ? 3 # n4 _ ? 4 # n5 _ ? 5 # n1.n.. _ n2 # n2.n.. _ n3 # n3.n.. _ n4 # n4.n.. _ n5 # r _ ? .? n1, 2, 4 # print .to_list
d2e70c091928cc0ab6f68873256037160b147bec
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/673 Number of Longest Increasing Subsequence.py
1,683
4.0625
4
#!/usr/bin/python3 """ 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 subsequence is 1, and there are 5 subsequences' length is 1, so output 5. Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. """ ____ t___ _______ L.. c_ LenCnt: ___ - , l, c l l c c ___ -r r.. r.. ((l, c c_ Solution: ___ findNumberOfLIS A: L.. i.. __ i.. """ Two pass - 1st pass find the LIS, 2nd pass find the number Let F[i] be the length of LIS ended at A[i] """ __ n.. A: r.. 0 n l..(A) F [LenCnt(l=1, c=1) ___ _ __ A] mx LenCnt(l=1, c=1) ___ i __ r..(1, n ___ j __ r..(i __ A[i] > A[j]: __ F[i].l < F[j].l + 1: F[i].l F[j].l + 1 F[i].c F[j].c ____ F[i].l __ F[j].l + 1: F[i].c += F[j].c __ F[i].l > mx.l: # mx = F[i] error, need deep copy mx.l F[i].l mx.c F[i].c ____ F[i].l __ mx.l: mx.c += F[i].c r.. mx.c __ _______ __ _______ ... Solution().findNumberOfLIS([1,1,1,2,2,2,3,3,3]) __ 27 ... Solution().findNumberOfLIS([1, 3, 5, 4, 7]) __ 2 ... Solution().findNumberOfLIS([2, 2, 2, 2, 2]) __ 5
8c9a8c9553dc6c8bc38392d192baf0d77e08c6f3
syurskyi/Python_Topics
/030_control_flow/001_if/examples/ITVDN Python Starter 2016/09-truth-value-testing.py
336
4.0625
4
# -*- coding: utf-8 -*- string = input('Enter a string: ') # то же самое, что if string is not None and string != '' if string: print('The string is {}'.format(string)) number = int(input('Enter a number: ')) if number: print('Число не равно нулю') else: print('Число равно нулю')
558a0fcd7e7e7ea3511d06cda1d68132db9682dc
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DP/InterleavingString.py
6,232
3.6875
4
""" Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. Example 1: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Example 2: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false 经过s1和s2的不断削减组合,最终是否能形成s3. 在最初使用了搜索的递归方法后进行学习DP以及改良,最终beat 85%以上。 思路: 最开始的思路就是搜索,符合条件就开启一个递归,符合条件就开启一个递归,毫不意外的TTL。 当时以为自己用的DP,怎么还会超时了呢。后来学习一下之后,发现自己只是用了一个搜索,而不是DP。 DP的主要任务时找到子问题,通过解决子问题来解决上层问题。还有就是子问题可以有多种解时,保留下来的子问题是哪个。 知道了这个之后,此问题的子问题是 「是否可以组成当前的字符串」。 例: s1 = "aabcc" s2 = "dbbca" s3 = "aadbbcbcac" s3_0 = s1[0] or s2[0] s3_1 = for i in s3_0 if s1[1] + i or if s2[0] + i ... 这样直至最后,看是否能够找到,如果其中的一环中出现了空,那么肯定是组不成了。 经过初版的测试后,发现比递归的搜索还要慢很多很多。甚至出现了MLE(内存占用太多)。 最终定位到原因是含有非常多同样的数据。 如这个测试用例: s1 = aabc s2 = abad s3 = aab.... 在判断s3_0时会加入两个可能的结果 分别是s1 = abc s2 = abad 和 s1 = aabc s2 = bad 这样在s3_1时就会有多个同样的数据 s1 = abc s2 = bad 从s3_0[0][1] 也就是s2中取a. s1 = abc s2 = bad 从s3_1[0][0] 也就是s1中取a. 这两个最终结果相同,对下一次结果没有影响,只取一个即可。 这仅仅是一个小例子,如果这样的数量过多,会形成非常大的冗余数据,只要出现20次这样的情况就会让最终的列表变成100多W个,而且一个很小的数据量即可达到20次。 但这100多W个所导致的下个结果是同一种,所以我们根本不需要这么多,只保留一个即可。 再思考一下,最初只定位了子问题,没有考虑保留哪些子问题的解,而是全部留下来。现在将缺少的「保留」条件加上。 所以在组成数据时判断是否已经重复即可解决此问题。 这样每次的迭代量变成1+个,基本不会超过4个。 但也有例外,如果 s1 == s2, s3 == s1+s2直接用不加判断的话会耗费大量时间, 如下: print(Solution().isInterleave('c'*1000, 'c'*1000, 'c'*2000)) 大概要半分钟。 因为此时我们制定的子问题规则毫无用处。每一个都可以避开。 或者 s1 == s2, s3 == s1与s2的前一部分相同的部分相加 + 后一部分相同的部分相加。 如 'ccb' 'ccb' 'ccccbb' Leetcode 中的测试数据并不存在这样的情况。 如果遇到此种情况,可以用DFS来结合,确定一个子问题,一条路走到底,可以完美解决此问题。 不是这种情况下,也可以用DFS结合使用,不过效率差不多,没有此种情况也不需要再重写改写了。 测试用例: https://leetcode.com/submissions/detail/165737688/ """ ''' 此版本 TTL MLE。 class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ """ recursive. """ if len(s3) != len(s1) + len(s2): return False if not s3: return True dp = {} # s3 index, s1, s2 for i, d in enumerate(s3): if i == 0: temp = [] if s1 and s1[0] == d: temp.append((s1[1:], s2)) if s2 and s2[0] == d: temp.append((s1, s2[1:])) dp[str(i)] = temp continue temp = [] if dp[str(i-1)]: for j in dp[str(i-1)]: s1, s2 = j[0], j[1] if s1 and s1[0] == d: temp.append((s1[1:], s2)) if s2 and s2[0] == d: temp.append((s1, s2[1:])) dp[str(i)] = temp else: return False # print(dp) try: for i in dp[str(len(s3)-1)]: if not any(i): return True else: return False except KeyError: return False ''' class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ """ recursive. """ if len(s3) != len(s1) + len(s2): return False if not s3: return True dp = {} # s3 index, s1, s2 for i, d in enumerate(s3): if i == 0: temp = [] if s1 and s1[0] == d: temp.append((s1[1:], s2)) if s2 and s2[0] == d: temp.append((s1, s2[1:])) dp[str(i)] = temp continue temp = [] if dp[str(i-1)]: for j in dp[str(i-1)]: s1, s2 = j[0], j[1] if s1 and s1[0] == d: if (s1[1:], s2) not in temp: temp.append((s1[1:], s2)) if s2 and s2[0] == d: if (s1, s2[1:]) not in temp: temp.append((s1, s2[1:])) dp[str(i)] = temp else: return False # print(len(dp[str(i-1)])) del dp[str(i-1)] # print(dp) try: for i in dp[str(len(s3)-1)]: if not any(i): return True else: return False except KeyError: return False print(Solution().isInterleave('c'*500+'d', 'c'*500+'d', 'c'*1000+'dd'))
eb259aa8ef480717e23897aa3f32812135533765
syurskyi/Python_Topics
/070_oop/001_classes/examples/Python_OOP_Object_Oriented_Programming/Section 14 Inheritance - Methods/Inheritance-Methods-Code/1 - Shape, Triangle, Circle.py
879
3.859375
4
class Shape: def __init__(self, color, is_polygon, description): self.color = color self.is_polygon = is_polygon self.description = description def display_data(self): print(f"\n=== {self.description.capitalize()} ===") print("Color:", self.color) print("Is the shape a polygon?", "Yes" if self.is_polygon else "No") class Triangle(Shape): def __init__(self, color, vertices, base, height): Shape.__init__(self, color, True, "Triangle") self.vertices = vertices self.base = base self.height = height class Circle(Shape): def __init__(self, color, radius): Shape.__init__(self, color, False, "Circle") self.radius = radius triangle = Triangle("red", [(-2, 0), (2, 0), (0, 7)], 4, 7) circle = Circle("blue", 6.3) triangle.display_data() circle.display_data()
5f6790b885f92ac670bab82149f7044e7ade4ca6
syurskyi/Python_Topics
/125_algorithms/_exercises/exercises/100_Interactive_Python_Exercises_to_Boost_Your_Python_Skill/Section 4 Data Structures and Algorithms/Coding Exercise 22 Number Info NUKE.py
220
3.6875
4
def foo(number): return dict(sign = "positive" if number > 0 else ("negative" if number < 0 else "zero"), parity = "odd" if number % 2 == 1 else ("even" if number % 2 == 0 else "non integer"))
e145836dcf4ea4126c17ec1ff0816d0aeaee2ddd
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Unittest_examples-master(2)/Unittest_examples-master/pyexample_2.py
738
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Пример модуля с классами """ import unittest class FirstTestClass(unittest.TestCase): def test_add(self): self.assertEqual(120, 100 + 20) class SecondTestClass(unittest.TestCase): def setUp(self): """ Данный метод выполняется перед каждым тестом (Test Case) в наборе (Test Suite) """ self.val = 210 def test_sub(self): self.assertEqual(210, self.val) self.val -= 40 self.assertEqual(170, self.val) def test_mul(self): self.assertEqual(420, self.val * 2) if __name__ == '__main__': unittest.main()
20c81149bf6ebde49eeec890443a40a5e67c085c
syurskyi/Python_Topics
/065_serialization_and_deserialization/002_json/_exercises/_templates/55. Using JSONDecoder - Coding.py
14,559
3.953125
4
# # Using JSONDecoder # # Just like we can use a subclass of JSONEncoder to customize our json encodings, we can use a subclass of # # the default JSONDecoder class to customize decoding our json strings. # # It works quite differently from the JSONEncoder subclassing though. # # When we subclass JSONEncoder we override the default method which then allows us to intercept encoding of specific # # types of objects, and delegate back to the parent class what we don't want to handle specifically. # # With the JSONDecoder class we override the decode function which passes us the entire JSON as a string and we have # # to return whatever Python object we want. There's no delegating anything back to the parent class unless we want # # to completely skip customizing the output. # # Let's first see how the functions work: # # ______ j___ # # j _ ''' # { # "a": 100, # "b": [1, 2, 3], # "c": "python", # "d": { # "e": 4, # "f": 5.5 # } # } # ''' # # c_ CustomDecoder j___.J..D.. # ___ decode ____ ar. # print("decode:", ty.. ar. ar. # r_ "a simple string object" # # print j___.lo.. ? cl._C.. # # # As you can see, whatever we return from the decode method is the result of calling loads. # # So, we might want to intercept certain JSON strings, handling them in some custom way, and delegate back to # # the parent class if it's not a string we want to handle ourselves - but it's all or nothing: # # Let's see an example of how we might want to use this: # # print('#' * 52 + ' As you can see, whatever we return from the `decode` method is the **result** of calling `loads`.') # print('#' * 52 + ' So, we might want to intercept certain JSON strings, handling them in some custom way, ' # ' and delegate back to the parent class if its not a string we want to handle ourselves -' # ' but its all or nothing:') # # c_ Point # ___ __i___ ___ x y # ____.x _ x # ____.y _ y # # ___ __re__ ____ # r_ _*P.. x_|____.x y_ ____.y * # # j_points _ ''' # { # "points": [ # [10, 20], # [-1, -2], # [0.5, 0.5] # ] # } # ''' # # j_other _ ''' # { # "a": 1, # "b": 2 # } # ''' # # c_ CustomDecoder j___.J..D.. # ___ decode ____ ar. # i_ 'points' i_ ar. # obj _ j___.lo.. ar. # r_ "parsing object for points" # e___ # r_ su__.de.. ar. # # print j___.lo.. j_po.. cl._C..De.. # print j___.lo.. j_o.. cl._C..De.. # # {'a': 1, 'b': 2} # # ###################################################################################################################### # # print('#' * 52 + ' So, lets implement the custom decoder now, assuming that `points` will be a top level node' # ' in the JSON object:') # # # c_ CustomDecoder j___.J..D.. # ___ decode ____ ar. # obj _ j___.lo.. ar. # i_ 'points' i_ obj # top level # ob. 'points'| _ P... x y # ___ x y i_ ob. |'points' # r_ ob. # # # print j___.lo.. j_po.. cl._Cu.. # # {'points': [Point(x=10, y=20), Point(x=-1, y=-2), Point(x=0.5, y=0.5)]} # # ###################################################################################################################### # # print j___.lo.. j_ot.. cl._Cu.. # # {'a': 1, 'b': 2} # # ###################################################################################################################### # # # Of course, we can be more fancy and maybe handle points by specifying the data type in the JSON object # # (and again, this is just how we, the developer, decide to make that specification). # # Here I am going to specify that a Point object in the JSON document should be specified using this format: # # {"_type": "point", "x": x-coord, "y": y-coord} # # So, when we parse the JSON string we are going to look for such a structure, and do the appropriate type conversion # # if needed. Of course, we'll have to look recursively in the JSON for this structure. We'll follow the same approach # # as before, first deserializing to a "generic" Python dict, then replacing any Point structure as we find them. # # To avoid having to iterate through the deserialized JSON object when we don't have that structure there in the first # # place, I'm going to look for "_type": "point" in the string. Technically we also need to look for "_type":"point" # # since both, from a JSON object perspective, are the same thing. In fact any amount of whitespace surrounding the : # # is acceptable. It would be possible but result in very unwieldy and concoluted code if we were to use an ordinary # # string search, so I'm going to use a regular expression instead (if you need help getting started with regular # # expressions, I highly recommend using this site: # # # print('#' * 52 + ' ') # print('#' * 52 + ' ') # print('#' * 52 + ' ') # # ______ r_ # pattern _ r'"_type"\s*:\s*"point"' # # # In this pattern, \s simply means a whitespace character, and the * right after it means zero or more times. # # Also note that we prefix that string with r to tell Python not to interpret the \ as anything special - # # otherwise Python will try to escape that, or interpet it, when conbined with another character, as an escape sequence. # # Let's see a quick example of this first: # # print('word1\tword2') # # word1 word2 # # ###################################################################################################################### # # print(r'word1\tword2') # # word1\tword2 # # ###################################################################################################################### # # # Notice the difference? Since we use the \ character a lot in regular expressions, we should always use this r prefix # # which indicates a raw string, and Python will not try to recognize escape sequences in our pattern. # # So, now let's continue testing out our regular expression pattern. We'll compile it so we can re-use it, but you # # dont have to. # # Once we have it compiled, we can use the search method that will find the first occurrence of the pattern in our # # search string, or return None if it was not found: # # regexp _ r_.co.. pa.. # print re__.se.. '"a": 1' # # None # # ###################################################################################################################### # # print r..e...se.. '"_type": "point"' # # <_sre.SRE_Match object; span=(0, 16), match='"_type": "point"'> # # ###################################################################################################################### # # print r__e__.se.. '"_type" : "point"' # # <_sre.SRE_Match object; span=(0, 19), match='"_type" : "point"'> # # ###################################################################################################################### # # print('#' * 52 + ' Alternatively, if we dont want to compile it' # ' (if we only use it once, there is no real need to do so), we can do a search this way:') # # print r_.se.. pa.. '"_type" : "point"' # # <_sre.SRE_Match object; span=(0, 19), match='"_type" : "point"'> # # ###################################################################################################################### # # print('#' * 52 + ' OK, now that we have a working regular expression pattern we can implement our custom j___ decoder.') # # # c_ CustomDecoder j___.J..D.. # ___ decode ____ ar. # obj _ j___.lo.. ar. # pattern _ r'"_type"\s*:\s*"point"' # i_ r_.se.. p... ar. # # we have at least one `Point' # obj _ ____.make_pts ob. # r_ ob. # # ___ make_pts ____ ob. # # recursive function to find and replace points # # received object could be a dictionary, a list, or a simple type # i_ isi.. ob. di.. # # first see if this dictionary is a point itself # i_ '_type' i_ ob. an. ob. '_type'| __ 'point' # # could have used: if obj.get('_type', None) == 'point' # obj _ P... ob.|'x' obj|'y' # e___ # # root object is not a point # # but it could contain a sub-object which itself # # is or contains a Point object # ___ key value i_ ob_.it.. # obj key| _ ____.make_pts va.. # e___ isi.. ob. li.. # ___ index item i_ en.. ob. # ob_ in..| _ ____.make_pts it.. # r___ ob. # # # j _ ''' # { # "a": 100, # "b": 0.5, # "rectangle": { # "corners": { # "b_left": {"_type": "point", "x": -1, "y": -1}, # "b_right": {"_type": "point", "x": 1, "y": -1}, # "t_left": {"_type": "point", "x": -1, "y": 1}, # "t_right": {"_type": "point", "x": 1, "y": 1} # }, # "rotate": {"_type" : "point", "x": 0, "y": 0}, # "interior_pts": [ # {"_type": "point", "x": 0, "y": 0}, # {"_type": "point", "x": 0.5, "y": 0.5} # ] # } # } # ''' # # print j___.lo.. ? # # {'a': 100, # # 'b': 0.5, # # 'rectangle': {'corners': {'b_left': {'_type': 'point', 'x': -1, 'y': -1}, # # 'b_right': {'_type': 'point', 'x': 1, 'y': -1}, # # 't_left': {'_type': 'point', 'x': -1, 'y': 1}, # # 't_right': {'_type': 'point', 'x': 1, 'y': 1}}, # # 'rotate': {'_type': 'point', 'x': 0, 'y': 0}, # # 'interior_pts': [{'_type': 'point', 'x': 0, 'y': 0}, # # {'_type': 'point', 'x': 0.5, 'y': 0.5}]}} # # ###################################################################################################################### # # f___ pp.. _______ pp.. # pprint j___.lo.. ? cl._Cu.. # # {'a': 100, # # 'b': 0.5, # # 'rectangle': {'corners': {'b_left': Point(x=-1, y=-1), # # 'b_right': Point(x=1, y=-1), # # 't_left': Point(x=-1, y=1), # # 't_right': Point(x=1, y=1)}, # # 'interior_pts': [Point(x=0, y=0), Point(x=0.5, y=0.5)], # # 'rotate': Point(x=0, y=0)}} # # ###################################################################################################################### # # print('#' * 52 + ' The `JSONDecoder` class also has arguments such as `parse_int`, ' # ' `parse_float`, etc we saw in the previous lecture.') # print('#' * 52 + ' We can use those to define a custom `JSONEncoder` class if we wanted to - lets say we want to use' # ' `Decimals` instead of floats - just like before,') # print('#' * 52 + ' but instead of specifying this each and every time we calls `loads`, ' # ' we can bundle this up into a custom decoder instead:') # # f___ de... _____ D.. # CustomDecoder _ j___.J..D.. parse_float=D.. # # d _ Cu___.de.. ? # pprint(d) # # {'a': 100, # # 'b': Decimal('0.5'), # # 'rectangle': {'corners': {'b_left': {'_type': 'point', 'x': -1, 'y': -1}, # # 'b_right': {'_type': 'point', 'x': 1, 'y': -1}, # # 't_left': {'_type': 'point', 'x': -1, 'y': 1}, # # 't_right': {'_type': 'point', 'x': 1, 'y': 1}}, # # 'interior_pts': [{'_type': 'point', 'x': 0, 'y': 0}, # # {'_type': 'point', # # 'x': Decimal('0.5'), # # 'y': Decimal('0.5')}], # # 'rotate': {'_type': 'point', 'x': 0, 'y': 0}}} # # ###################################################################################################################### # # print('#' * 52 + ' Of course, we can combine this with our custom decoder too:') # # # c_ CustomDecoder(j___.J..D..): # base_decoder _ j___.J..D.. parse_float_D... # # ___ decode ____ ar. # obj _ ____.ba.._de...de.. ar. # pattern _ r'"_type"\s*:\s*"point"' # i_ r_.se.. pa.. ar. # # we have at least one `Point' # obj _ ____.m.._p.. ob. # r_ ? # # ___ make_pts ____ obj # # recursive function to find and replace points # # received object could be a dictionary, a list, or a simple type # i_ isi.. ob. di.. # # first see if this dictionary is a point itself # i_ '_type' i_ ob. an. ob.|'_type' __ 'point': # obj _ P... ob.|'x' obj|'y' # e___ # # root object is not a point # # but it could contain a sub-object which itself # # is or contains a Point object nested at some level # # maybe another dictionary, or a list # ____ key value i_ ob_.it.. # ob. |k.. _ ____.m.._p.va.. # e___ isi.. ob. li.. # # received a list - need to run each item through make_pts # ___ index, item i_ en... ob. # ob. i_...| _ ____.ma.._p.. it.. # r_ o.. # # # pprint j___.lo.. ? cls_Cu__ # # {. # # 'b': Decimal('0.5'), # # 'rectangle': {'corners': {'b_left': Point(x=-1, y=-1), # # 'b_right': Point(x=1, y=-1), # # 't_left': Point(x=-1, y=1), # # 't_right': Point(x=1, y=1)}, # # 'rotate': Point(x=0, y=0), # # 'interior_pts': [Point(x=0, y=0), Point(x=0.5, y=0.5)]}} # # ###################################################################################################################### # # print('#' * 52 + ' Its not evident that our `Point(x=0.5, y=0.5)` actually contains `Decimal` objects - ' # ' that is really just the string representation - so lets just make sure they are indeed ' # ' `Decimal` objects:') # # result _ j___.lo.. ? cl._Cu.. # pt _ re... 'rectangle' 'interior_pts' 1 # print ty.. p_.x ty.. p_.y # # <class 'decimal.Decimal'> <class 'decimal.Decimal'> # # ###################################################################################################################### # # # As you can see, decoding JSON into custom objects is not exactly easy - the basic reason being that JSON does not # # support anything other than simple data types such as integers, floats, strings, booleans, constants and objects and lists. # # The rest is up to us. # # This is one of the reasons there are quite a few 3rd party libraries that allow us to serialize and deserialize # # JSON objects that follow a certain schema. # # I'll discuss some of those in upcoming lectures.
bb5ea1238c5f902ce796ef0ed8929eb33d954eae
syurskyi/Python_Topics
/050_iterations_comprehension_generations/002_list_comprehension/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 20 List Comprehension Exercises.py
373
3.65625
4
# Using list comprehensions: answer = [person[0] for person in ["Elie", "Tim", "Matt"]] answer2 = [val for val in [1, 2, 3, 4, 5, 6] if val % 2 == 0] print(answer) # Using good old manual loops: answer = [] for person in ["Elie", "Tim", "Matt"]: answer.append(person[0]) answer2 = [] for num in [1, 2, 3, 4, 5, 6]: if num % 2 == 0: answer2.append(num)
da7fa62688eef77231aefdd7f7ee6d33d6ff222c
syurskyi/Python_Topics
/070_oop/008_metaprogramming/_exercises/templates/python_cookbook/9.17_enforcing_coding_conventions_in_classes/example1.py
4,314
3.65625
4
# A metaclass that disallows mixed case identifier names class NoMixedCaseMeta(type): def __new__(cls, clsname, bases, clsdict): for name in clsdict: if name.lower() != name: raise TypeError('Bad attribute name: ' + name) return super().__new__(cls, clsname, bases, clsdict) class Root(metaclass=NoMixedCaseMeta): pass class A(Root): def foo_bar(self): # Ok pass print('**** About to generate a TypeError') class B(Root): def fooBar(self): # TypeError pass # Problem # Your program consists of a large class hierarchy and you would like to enforce certain # kinds of coding conventions (or perform diagnostics) to help maintain programmer # sanity. # Solution # If you want to monitor the definition of classes, you can often do it by defining a # metaclass. A basic metaclass is usually defined by inheriting from type and redefining # its __new__() method or __init__() method. For example: # To use a metaclass, you would generally incorporate it into a top-level base class from # which other objects inherit. For example: # A key feature of a metaclass is that it allows you to examine the contents of a class at the # time of definition. Inside the redefined __init__() method, you are free to inspect the # class dictionary, base classes, and more. Moreover, once a metaclass has been specified # for a class, it gets inherited by all of the subclasses. Thus, a sneaky framework builder # can specify a metaclass for one of the top-level classes in a large hierarchy and capture # the definition of all classes under it. # As a concrete albeit whimsical example, here is a metaclass that rejects any class definition # containing methods with mixed-case names (perhaps as a means for annoying # Java programmers): # As a more advanced and useful example, here is a metaclass that checks the definition # of redefined methods to make sure they have the same calling signature as the original # method in the superclass. # Such warnings might be useful in catching subtle program bugs. For example, code that # relies on keyword argument passing to a method will break if a subclass changes the # argument names. # Discussion # In large object-oriented programs, it can sometimes be useful to put class definitions # under the control of a metaclass. The metaclass can observe class definitions and be # used to alert programmers to potential problems that might go unnoticed (e.g., using # slightly incompatible method signatures). # One might argue that such errors would be better caught by program analysis tools or # IDEs. To be sure, such tools are useful. However, if you’re creating a framework or library # that’s going to be used by others, you often don’t have any control over the rigor of their # development practices. Thus, for certain kinds of applications, it might make sense to # put a bit of extra checking in a metaclass if such checking would result in a better user # experience. # The choice of redefining __new__() or __init__() in a metaclass depends on how you # want to work with the resulting class. __new__() is invoked prior to class creation and # is typically used when a metaclass wants to alter the class definition in some way (by # changing the contents of the class dictionary). The __init__() method is invoked after # a class has been created, and is useful if you want to write code that works with the fully # formed class object. In the last example, this is essential since it is using the super() # function to search for prior definitions. This only works once the class instance has been # created and the underlying method resolution order has been set. # The last example also illustrates the use of Python’s function signature objects. Essentially, # the metaclass takes each callable definition in a class, searches for a prior definition # (if any), and then simply compares their calling signatures using inspect.signature(). # Last, but not least, the line of code that uses super(self, self) is not a typo. When # working with a metaclass, it’s important to realize that the self is actually a class object. # So, that statement is actually being used to find definitions located further up the class # hierarchy that make up the parents of self.
438cb7633c606ebafa831e5a24a8ceb3ae2ba851
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-272-find-common-words.py
1,862
4.34375
4
""" Given two sentences that each contains words in case insensitive way, you have to check the common case insensitive words appearing in both sentences. If there are duplicate words in the results, just choose one. The results should be sorted by words length. The sentences are presented as list of words. Example: S = ['You', 'can', 'do', 'anything', 'but', 'not', 'everything'] ## ** ** T = ['We', 'are', 'what', 'we', 'repeatedly', 'do', 'is', 'not', 'an', 'act'] ## ** ** Result = ['do', 'not'] """ from typing import List def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]: """ Input: Two sentences - each is a list of words in case insensitive ways. Output: those common words appearing in both sentences. Capital and lowercase words are treated as the same word. If there are duplicate words in the results, just choose one word. Returned words should be sorted by word's length. """ lower_s1 = [e.lower() for e in sentence1 ] lower_s2 = [e.lower() for e in sentence2 ] result = list(set(lower_s1) & set(lower_s2)) return sorted(result, key=len) """ Approach: First, eliminate duplicates within each sentence. Second, use a intersection on both lists to find common elements. """ sentence1 = ['To', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'a', 'question'] sentence2 = ['To', 'strive', 'to', 'seek', 'to', 'find', 'and', 'not', 'to', 'yield'] sentence3 = ['No', 'two', 'persons', 'ever', 'to', 'read', 'the', 'same', 'book', 'You', 'said'] sentence4 = ['The', 'more', 'read', 'the', 'more', 'things', 'will', 'know'] sentence5 = ['be', 'a', 'good', 'man'] print(common_words(sentence1, sentence5))
bee3d292f0898daadf8cbb51ccc92ae93139b520
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Patch_Multiple.py
2,236
3.671875
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 stubs throughout your test suite. # After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. # You can also specify return values and set needed attributes in the normal way. # # Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel # for creating unique objects. # # Mock is very easy to use and is designed for use with unittest. Mock is based on the �action -> assertion� pattern instead of �record -> replay� used by # many mocking frameworks. # # # If you want patch.multiple() to create mocks for you, then you can use DEFAULT as the value. # If you use patch.multiple() as a decorator then the created mocks are passed into the decorated function by keyword. # thing = object() other = object() @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) def test_function(thing, other): assert isinstance(thing, MagicMock) assert isinstance(other, MagicMock) test_function() # # patch.multiple() can be nested with other patch decorators, but put arguments passed by keyword after any of the standard arguments created by patch(): # @patch('sys.exit') @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) def test_function(mock_exit, other, thing): assert 'other' in repr(other) assert 'thing' in repr(thing) assert 'exit' in repr(mock_exit) test_function() # # If patch.multiple() is used as a context manager, the value returned by the context manger is a dictionary where created mocks are keyed by name: # with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values: assert 'other' in repr(values['other']) assert 'thing' in repr(values['thing']) assert values['thing'] is thing assert values['other'] is other
235fee728f7853aa65b05a101deeb1dfeb5ebf8f
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DynamicProgramming/198_HouseRobber.py
469
3.609375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): # Dynamic Programming def rob(self, nums): if not nums: return 0 pre_rob = 0 pre_not_rob = 0 for num in nums: cur_rob = pre_not_rob + num cur_not_rob = max(pre_rob, pre_not_rob) pre_rob = cur_rob pre_not_rob = cur_not_rob return max(pre_rob, pre_not_rob) """ [] [1,2] [12, 1,1,12,1] """
e5963c5c51190c7231e249ac9a9dc30f2a3e0296
syurskyi/Python_Topics
/090_logging/_exercises/exercises/Good logging practice in Python/005_Capture exceptions with the traceback.py
1,020
3.609375
4
# # Capture exceptions with the traceback # # While its a good practice to log a message when something goes wrong, but it wont be helpful if there is no # # traceback. You should capture exceptions and record them with traceback. Following is an example: # # t__ # o.. '/path/to/does/not/exist' __ # e___ S.. K.. # r___ # e___ E.. a_ exception # ?.e.. 'Failed to open file' e.._T... # # # By calling logger methods with exc_info=True parameter, the traceback will be dumped to the logger. # As you can see the result # # # # ERROR:__main__:Failed to open file # # Traceback (most recent call last): # # File "example.py", line 6, in <module> # # open('/path/to/does/not/exist', 'rb') # # IOError: [Errno 2] No such file or directory: '/path/to/does/not/exist' # # Since Python 3.5, you can also pass the exception instance to exc_info parameter. Besides exc_info parameter, # you can also call logger.exception(msg, *args), it is the same as calling to logger.error(msg, *args, exc_info=True).
ae706f18b09e6de72457f1ac23cf5ed37a7ebab3
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Test_Prefix.py
1,699
3.6875
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 stubs throughout your test suite. # After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. # You can also specify return values and set needed attributes in the normal way. # # Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel # for creating unique objects. # # Mock is very easy to use and is designed for use with unittest. Mock is based on the �action -> assertion� pattern instead of �record -> replay� used by # many mocking frameworks. # # # TEST_PREFIX: # All of the patchers can be used as class decorators. # When used in this way they wrap every test method on the class. # The patchers recognise methods that start with 'test' as being test methods. # This is the same way that the unittest.TestLoader finds test methods by default. # # It is possible that you want to use a different prefix for your tests. # You can inform the patchers of the different prefix by setting patch.TEST_PREFIX: # patch.TEST_PREFIX _ 'foo' value _ 3 ?p..('__main__.value', 'not three') c_ Thing: ___ foo_one print(value) ___ foo_two print(value) Thing().foo_one() # OUTPUT: 'not three' Thing().foo_two() # OUTPUT: 'not three' value # OUTPUT: '3'
e862d9cb13ed41dcf00350945782f41db0205e5b
syurskyi/Python_Topics
/030_control_flow/example/Python-from-Zero-to-Hero/03-Коллеции, циклы, логика/13-ДЗ-Опреляем Flush_solution.py
635
3.625
4
table_cards = ["A_S", "J_H", "7_D", "8_D", "10_D"] hand_cards = ["J_D", "3_C"] # ниже ваша реализация: suites = 'CHSD' flush = False table_suites = [i[-1] for i in table_cards] hand_suites = [i[-1] for i in hand_cards] suites_in_game = table_suites + hand_suites # and either with a list comprehension: flush = any([suites_in_game.count(suit) >= 5 for suit in suites]) if flush: print('Flush!') else: print('No Flush!') # or more procedural flush = False for suit in suites: if suites_in_game.count(suit) >= 5: flush = True if flush: print('Flush!') else: print('No Flush!')
97142a394d8c9bf78c236b4f597a59d092108f01
syurskyi/Python_Topics
/045_functions/007_lambda/_exercises/exercises/001_Python lambda expressions who are they_!cool!.py
492
3.640625
4
# -*- coding: utf-8 -*- # Лямдба-выражения позволяют нам превратить следующий код: colors = ["Goldenrod", "Purple", "Salmon", "Turquoise", "Cyan"] def normalize_case(string): return string.casefold() normalized_colors = map(normalize_case, colors) # Вот в такой код: colors = ["Goldenrod", "Purple", "Salmon", "Turquoise", "Cyan"] normalized_colors = map(lambda s: s.casefold(), colors) print(list(normalized_colors))
fc42c1a94d6d942bc21ac8b03a1e7290ce6a8bbc
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/87_remove_node_in_binary_search_tree.py
1,132
3.578125
4
""" Main Concept: https://discuss.leetcode.com/topic/65792/recursive-easy-to-understand-java-solution Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ c_ Solution: """ @param: root: The root of the binary search tree. @param: target: Remove the node with given value. @return: The root of the binary search tree after removal. """ ___ removeNode root, target __ n.. root: r.. root __ root.val __ target: __ n.. root.left: r.. root.right __ n.. root.right: r.. root.left min_node find_min(root.right) root.val min_node.val root.right removeNode(root.right, root.val) r.. root __ target < root.val: root.left removeNode(root.left, target) ____ root.right removeNode(root.right, target) r.. root ___ find_min node __ n.. node: r.. node w.... node.left: node node.left r.. node
61a04b3aa15caa8791f7420325e8b2ab08af676a
syurskyi/Python_Topics
/125_algorithms/_examples/100_Python_Exercises_Evaluate_and_Improve_Your_Skills/Exercise 51 - EOF.py
220
3.703125
4
#The script is trying to print out the type of the last character of updated string. #A: One more bracket is needed to close the print function print(type("Hey".replace("ey","i")[-1])) print("Hey".replace("ey","i")[-1])
196c3043137ac8a37d8ea496793847367cdecc60
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/399 Evaluate Division.py
2,383
3.671875
4
""" Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0. Example: Given a / b = 2.0, b / c = 3.0. queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? . return [6.0, 0.5, -1.0, 1.0, -1.0 ]. The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>. According to the example above: equations = [ ["a", "b"], ["b", "c"] ], values = [2.0, 3.0], queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. """ ____ c.. _______ d.. ____ i.. _______ izip __author__ 'Daniel' c_ Solution(o.. ___ calcEquation equations, values, queries """ transitive closure :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] """ G d..(d..) ___ edge, val __ izip(equations, values s, e edge G[s][e], G[e][s] val, 1/val G[s][s], G[e][e] 1, 1 r.. [dfs(G, s, e, s.. ___ s, e __ queries] ___ dfs G, s, e, p.. __ s n.. __ G o. e n.. __ G: r.. -1.0 __ e __ G[s]: r.. G[s][e] ___ nbr __ G[s]: __ nbr n.. __ p..: p...add(nbr) val dfs(G, nbr, e, p..) __ val !_ -1.0: r.. val * G[s][nbr] p...remove(nbr) r.. -1.0 c_ Solution(o.. ___ calcEquation equations, values, queries """ Floyd-Warshall algorithm transitive closure :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] """ G d..(d..) ___ edge, val __ izip(equations, values s, e edge G[s][e], G[e][s] val, 1/val G[s][s], G[e][e] 1, 1 # Floyd-Warshall ___ mid __ G: ___ s __ G[mid]: ___ e __ G[mid]: G[s][e] G[s][mid] * G[mid][e] r.. [G[s].g.. e, -1.0) ___ s, e __ queries]
ab296e2bb06b26e229bf476a06432826585dbbb5
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/2_dimensional_array_solution.py
1,011
4.375
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 which takes two digits m (row) and n (column) as input and generates a two-dimensional array. # The element value in the i-th row and j-th column of the array should be i*j. # Note : # i = 0,1.., m-1 # j = 0,1, n-1. # Input # Input number of rows: 3 # Input number of columns: 4 # Output # [[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6]] row_num = int(input("Input number of rows: ")) col_num = int(input("Input number of columns: ")) multi_list = [[0 for col in range(col_num)] for row in range(row_num)] for row in range(row_num): for col in range(col_num): multi_list[row][col]= row*col print(multi_list)
12caeb8af4b04ae3cf6150a0d8847676f4a70fc2
syurskyi/Python_Topics
/115_testing/examples/ITVDN_Python_Advanced/007_Модульное тестирование/007_Samples/example0_custom.py
765
3.59375
4
def concat(x, y): return '{} {}'.format(x, y) def sum_3_elem(a, b, c): return a + b + c def multiply_3_elem(a, b, c): return a * b * c def test_concat(): assert concat(1, 2) == '1 2' assert concat(10, 20) == '10 20' def test_sum_3_elem(): assert sum_3_elem(0, 2, 3) == 5 assert sum_3_elem(1, 2, 3) == 6 assert sum_3_elem(1, 3, 7) == 11 def test_multiply_3_elem(): assert multiply_3_elem(1, 2, 3) == 6 assert multiply_3_elem(2, 3, 4) == 24 test_functions = [ test_concat, test_sum_3_elem, test_multiply_3_elem ] if __name__ == '__main__': for func in test_functions: try: func() except Exception as e: print('Failed: {} => {}: {}'.format(func, type(e), e))
f41b074a2c82c8a2ef811bbea596c6a375ef557b
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 3 Search Algorithms/linear_search_recursive.py
389
3.734375
4
___ linear_search_recursive(container, item, index0 # base case for search miss (when item is not present in the container) __ index > le_(container r_ -1 # base case when we find the item __ container[index] __ item: r_ index r_ linear_search_recursive(container, item, index + 1) nums [1, 4, 6, -4, 0, 100] print(linear_search_recursive(nums, 0))
153eb2c8ad7e84e5cad4123398b8aec710d3ffc1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/451 Sort Characters By Frequency.py
833
4.03125
4
#!/usr/bin/python3 """ Given a string, sort it in decreasing order based on the frequency of characters. """ ____ c.. _______ d.. c_ Solution(o.. ___ frequencySort s """ Brute force: counter, sort O(n log n) There is a uppper limit of the counter, thus bucket sort possible :type s: str :rtype: str """ counter d.. i.. ___ c __ s: counter[c] += 1 bucket {count: # list ___ count __ r..(1, l..(s)+1)} ___ k, v __ counter.i.. bucket[v].a..(k) ret # list ___ count __ r..(r..(1, l..(s) + 1: __ bucket[count]: ___ c __ bucket[count]: ret.a..(c * count) r.. "".j..(ret) __ _______ __ _______ ... Solution().frequencySort("tree") __ "eetr"
d6547e1f12d4fb2f6683397346a4a5e0fd4583d3
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/043 Wildcard Matching.py
3,172
3.5
4
""" Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") -> false isMatch("aa","aa") -> true isMatch("aaa","aa") -> false isMatch("aa", "*") -> true isMatch("aa", "a*") -> true isMatch("ab", "?*") -> true isMatch("aab", "c*a*b") -> false """ __author__ 'Danyang' c_ Solution: ___ isMatch_MLE s, p """ dp, similar to 011 Regular Expression Matching. Backward dp but Memory Limit Exceeds :param s: tape, an input string :param p: pattern, a pattern string :return: boolean """ tape s pattern p m l..(tape) n l..(pattern) dp [[F.. ___ _ __ x..(n+1)] ___ _ __ x..(m+1)] # edge cases dp[m][n] T.. ___ j __ x..(n-1, -1 , -1 __ pattern[j]__"*": dp[m][j] dp[m][j+1] # transition ___ i __ x..(m-1, -1, -1 ___ j __ x..(n-1, -1, -1 __ tape[i]__pattern[j] o. pattern[j]__"?": dp[i][j] dp[i+1][j+1] ____ pattern[j]__"*": dp[i][j] dp[i][j+1] o. dp[i+1][j] # zero or more ____ dp[i][j] F.. r.. dp 0 0 ___ isMatch_forward s, p """ "?" is not the problem "*" is the problem Forward dp: dp starting from -1 if pattern[j]!="*", dp[i][j] = dp[i-1][j-1] && tape[i] matches pattern[j] if pattern[j]=="*", dp[i][j] = any(dp[m][j-1]) w.r.t m Compact the 2-D dp to 1-D dp: iterate through j, since we only need know j-1 state, thus dropping the dimension for j in dp :param s: tape, an input string :param p: pattern, a pattern string :return: boolean """ tape s pattern p m l..(tape) n l..(pattern) __ n - l..(pattern).c.. "*") > m: r.. F.. dp [F.. ___ _ __ x..(m+1)] dp[0] T.. # dummy ___ j __ x..(1, n+1 __ pattern[j-1]__"*": # for i in xrange(m, 0, -1): # dp[i] = any(dp[k] for k in xrange(i)) # Time Complexity k 0 w.... k<m+1 a.. dp[k]!_T.. k+= 1 ___ i __ x..(k, m+1 dp[i] T.. ____ ___ i __ x..(m, 0, -1 dp[i] dp[i-1] a.. (tape[i-1]__pattern[j-1] o. pattern[j-1]__"?") dp[0] dp[0] a.. pattern[j-1]__"*" # !!, pattern no longer match the empty string r.. dp[m] __ _____ __ ____ ... Solution().isMatch("aab", "c*a*b")__False ... Solution().isMatch("aa","a")__False ... Solution().isMatch("aa", "aa")__True ... Solution().isMatch("aaa", "aa")__False ... Solution().isMatch("aaa", "*")__True ... Solution().isMatch("aa", "a*")__True ... Solution().isMatch("ab", "?*")__True
fd8c3565c4951a7497a53ff3c1eb3d172425bd8a
syurskyi/Python_Topics
/055_modules/001_modules/examples/Python 3 Most Nessesary/12.1.Listing 12.4. Attribute existence check.py
329
3.640625
4
import math def hasattr_math(attr): if hasattr(math, attr): return "Атрибут существует" else: return "Атрибут не существует" print(hasattr_math("pi")) # Атрибут существует print(hasattr_math("x")) # Атрибут не существует
650b2156b592b55355fcd441cdf6a29ba8760226
syurskyi/Python_Topics
/050_iterations_comprehension_generations/006_nested_comprehensions/examples/006_nested_comprehensions.py
1,954
4.75
5
# Nested Comprehensions # Just as with list comprehensions, we can nest generator expressions too: # A multiplication table: # Using a list comprehension approach first: # The equivalent generator expression would be: # We can iterate through mult_list: # But you'll notice that our rows are themselves generators! # o fully materialize the table we need to iterate through the row generators too: start = 1 stop = 10 mult_list = [ [i * j for j in range(start, stop+1)] for i in range(start, stop+1)] mult_list start = 1 stop = 10 mult_list = ( (i * j for j in range(start, stop+1)) for i in range(start, stop+1)) mult_list table = list(mult_list) table table_rows = [list(gen) for gen in table] table_rows # Nested Comprehensions # Of course, we can mix list comprehensions and generators. # In this modification, we'll make the rows list comprehensions, and retain the generator expression in the outer # comprehension: # Notice what is happening here, the table itself is lazy evaluated, i.e. the rows are not yielded until they # are requested - but once a row is requested, the list comprehension that defines the row will be entirely # evaluated at that point: start = 1 stop = 10 mult_list = ( [i * j for j in range(start, stop+1)] for i in range(start, stop+1)) for item in mult_list: print(item) # Let's try Pascal's triangle again: # Here's how we did it using a list comprehension: from math import factorial def combo(n, k): return factorial(n) // (factorial(k) * factorial(n-k)) size = 10 # global variable pascal = [ [combo(n, k) for k in range(n+1)] for n in range(size+1) ] # Let's try Pascal's triangle again: # # If we want to materialize the triangle into a list we'll need to do so ourselves: size = 10 # global variable pascal = ( (combo(n, k) for k in range(n+1)) for n in range(size+1) ) [list(row) for row in pascal]
9652c845bbb6af2b08cca30ed454e17570bcd220
syurskyi/Python_Topics
/090_logging/examples/github/_logging_examples-master(2)/logging_examples-master/logger_example_2.py
756
3.515625
4
import argparse import logging import sys logging.basicConfig(filename='ex2_log.log', level=logging.DEBUG) def simple_parser(): logging.info("Command Line inputs: " + ' '.join(sys.argv[1:])) parser = argparse.ArgumentParser() parser.add_argument('A', type=int) parser.add_argument('B', type=int) parser.add_argument('C', type=int) args = parser.parse_args() return args.A, args.B, args.C def foo(A, B, C): """Demonstrate basic logging functionality with file output.""" logging.info(f'args: ({A}, {B}, {C})') result = (A + B) * C logging.info(f'result: {result}') return result if __name__ == '__main__': args = simple_parser() print(foo(*args))
0e75f1f8b46a9230a3c40c7a337864925c591d29
syurskyi/Python_Topics
/045_functions/007_lambda/_exercises/templates/010_Filter.py
558
3.671875
4
# -*- coding: utf-8 -*- # even _ l_____ x ? % 2 __ 0 # print li.. f.. ? ra.. 11 # # [0, 2, 4, 6, 8, 10] # # # Обратите внимание, что filter() возвращает итератор, поэтому необходимо вызывать list, # # который создает список с заданным итератором. # # # # Реализация, использующая конструкцию генератора списка, дает следующее: # # print x ___ ? __ ra.. 11 __ ? % 2 __ 0 # # [0, 2, 4, 6, 8, 10]
f171b8efbcf102bd8a563c2367ccff88912e1dcb
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DynamicProgramming/10_RegularExpressionMatching.py
1,932
3.765625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def isMatch(self, s, p): """ Dynamic Programming dp[i][j] represents isMatch(p[0...i], s[0...j]), default is False; dp[i][-1] represents isMatch(p[0...i], "") dp[-1][j] represents isMatch("", s[0...j]) """ if not s: # .*.*.*.* Return True, others return False. if len(p) % 2 != 0: return False for k in range(1, len(p), 2): if p[k] != "*": return False return True # dp = [[False] * (len(s)+1)] * (len(p)+1) dp = [[False for col in range(len(s) + 1)] for row in range(len(p) + 1)] dp[-1][-1] = True for i in range(len(p)): for j in range(len(s)): """ p[i] is "*", so dp[i][j] = 1. dp[i-2][j] # * matches 0 element in s; 2. dp[i-2][j-1] # * matches 1 element in s; 3. dp[i][j-1] # * matches more than one in s. """ if p[i] == "*": m_0 = dp[i - 2][j] m_1 = (p[i - 1] == "." or p[i - 1] == s[j]) and dp[i - 2][j - 1] m_more = (p[i - 1] == "." or p[i - 1] == s[j]) and dp[i][j - 1] dp[i][j] = m_0 or m_1 or m_more # p[i] matches "" is equal p[i-2] matches "". dp[i][-1] = dp[i - 2][-1] else: dp[i][j] = (dp[i - 1][j - 1] and (p[i] == s[j] or p[i] == ".")) # p[i] doesn't match "" dp[i][-1] = False return dp[len(p) - 1][len(s) - 1] """ "aaa" "ab*a" "" "c*c*" "aaa" "aaaa" "aaabc" "a*bc" "aab" "c*a*b" "ab" ".*c" "aaaaabaccbbccababa" "a*b*.*c*c*.*.*.*c" """
f0deed5e91dc4476292f10ac0e544bd0a8290bb1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/746 Min Cost Climbing Stairs.py
1,291
4.125
4
#!/usr/bin/python3 """ On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. Note: cost will have a length in the range [2, 1000]. Every cost[i] will be an integer in the range [0, 999]. """ ____ t___ _______ L.. c_ Solution: ___ minCostClimbingStairs cost: L.. i.. __ i.. """ dp let F[i] be the cost to reach i-th stair F[i] = min F[i-2] + cost[i-2] F[i-1] + cost[i-1] """ n l..(cost) F [f__('inf') ___ _ __ r..(n+1)] F[0] 0 F[1] 0 ___ i __ r..(2, n+1 F[i] m..( F[i-2] + cost[i-2], F[i-1] + cost[i-1] ) r.. F[-1] __ _______ __ _______ ... Solution().minCostClimbingStairs([10, 15, 20]) __ 15
12037708f7862d5be05538280cac4e7fa580660c
syurskyi/Python_Topics
/010_strings/_exercises/Learning Python/017_String Formatting Expressions.py
366
3.578125
4
# -*- coding: utf-8 -*- print('That is %s %s bird!' % (1, 'dead')) # Format expression print('The knights who say %s!' % 'exclamation') # String substitution print('%d %s %g you' % (1, 'spam', 4.0)) # Type-specific substitutions | - эквивалентно f или е print('%s -- %s -- %s' % (42, 3.14159, [1, 2, 3])) # All types match a %s target |list
7051770e9ce69ac4044e38df4bad8e2ec92bc703
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Mocks_As_Attributes.py
2,996
3.609375
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 stubs throughout your test suite. # After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. # You can also specify return values and set needed attributes in the normal way. # # Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel # for creating unique objects. # # Mock is very easy to use and is designed for use with unittest. Mock is based on the action -> assertion pattern instead of record -> replay used by # many mocking frameworks. # # # Attaching Mocks as Attributes. # When you attach a mock as an attribute of another mock (or as the return value) it becomes a child of that mock. Calls to the child are recorded in the # method_calls and mock_calls attributes of the parent. This is useful for configuring child mocks and then attaching them to the parent, or for attaching # mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks: # parent = MagicMock() child1 = MagicMock(return_value=None) child2 = MagicMock(return_value=None) parent.child1 = child1 parent.child2 = child2 child1(1) child2(2) parent.mock_calls # OUTPUT: '[call.child1(1), call.child2(2)]' # # The exception to this is if the mock has a name. # This allows you to prevent the parenting if for some reason you dont want it to happen. # mock = MagicMock() not_a_child = MagicMock(name='not-a-child') mock.attribute = not_a_child mock.attribute() # OUTPUT: '<MagicMock name='not-a-child()' id='...'>' mock.mock_calls # OUTPUT: '[]' # # Mocks created for you by patch() are automatically given names. # To attach mocks that have names to a parent you use the attach_mock() method: # thing1 = object() thing2 = object() parent = MagicMock() with patch('__main__.thing1', return_value=None) as child1: with patch('__main__.thing2', return_value=None) as child2: parent.attach_mock(child1, 'child1') parent.attach_mock(child2, 'child2') child1('one') child2('two') parent.mock_calls # OUTPUT: '[call.child1('one'), call.child2('two')]' # # The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). # Mock doesnt create these but instead raises an AttributeError. # This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic # method. # If you need magic method support see magic methods. #
f2a195534b38ecc53de8f47c4f25be48b7dbd9fa
syurskyi/Python_Topics
/090_logging/_exercises/exercises/Python Logging – Simplest Guide with Full Code and Examples/006_7. How to create a new logger.py
1,508
3.609375
4
# # You can create a new logger using the logger.getLogger(name) method. If a logger with the same name exists, # # then that logger will be used. # # # # While you can give pretty much any name to the logger, the convention is to use the __name__ variable like this: # # # ______ l____ # logger _ l____.gL_ -n # ?.i.. 'my logging message' # # But, why use __name__ as the name of the logger, instead of hardcoding a name? # # # # Because the __name__ variable will hold the name of the module (python file) that called the code. So, when used # # inside a module, it will create a logger bearing the value provided by the module's __name__ attribute. # # By doing this, if you end up changing module name (file name) in future, you dont have to modify the internal code. # # Now, once you've created a new logger, you should remember to log all your messages using the new logger.info() # # instead of the root's logging.info() method. # # # # Another aspect to note is, all the loggers have a built-in hierarchy to it. # # What do I mean by that? # # # # For example, if you have configured the root logger to log messages to a particular file. You also have # # a custom logger for which you have not configured the file handler to send messages to console or another log file. # # In this case, the custom logger will fallback and write to the file set by the root logger itself. # # Until and unless you configure the log file of your custom logger. # # So what is a file handler and how to set one up?
ccc30660ab3a95002188a82d1634e305f7e867bb
syurskyi/Python_Topics
/050_iterations_comprehension_generations/002_dictionary_comprehension/examples/002_dictionary_comprehension.py
1,330
4.09375
4
# Comprehension Syntax Summary # Dictionary comprehension print({x: x * x for x in range(10)}) # Comprehending Set and Dictionary Comprehensions # Comprehension # Generator and type name # Set comprehension equivalent # Dict comprehension equivalent print({x * x for x in range(10)}) set(x * x for x in range(10)) print({x: x * x for x in range(10)}) print(dict((x, x * x) for x in range(10))) res = set() for x in range(10): res.add(x * x) print(res) res = {} for x in range(10): res[x] = x * x print(res) # Notice that although both forms accept iterators, they have no notion of generating # results on demand—both forms build objects all at once. If you mean to produce keys # and values upon request, a generator expression is more appropriate: G = ((x, x * x) for x in range(10)) print(next(G)) print(next(G)) # Extended Comprehension Syntax for Sets and Dictionaries # Lists are ordered # But sets are not # Neither are dict keys # Lists keep duplicates # But sets do not # Neither do dict keys print([x * x for x in range(10) if x % 2 == 0]) print({x * x for x in range(10) if x % 2 == 0}) print({x: x * x for x in range(10) if x % 2 == 0}) print([x + y for x in [1, 2, 3] for y in [4, 5, 6]]) print({x + y for x in [1, 2, 3] for y in [4, 5, 6]}) print({x: y for x in [1, 2, 3] for y in [4, 5, 6]})
fa729e7509e45d58afe1c792d586072f89546cd6
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/124 Binary Tree Maximum Path Sum.py
1,717
3.5625
4
""" Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / \ 2 3 Return 6. """ __author__ 'Danyang' # Definition for a binary tree node c_ TreeNode: ___ - , x val x left N.. right N.. c_ Solution: global_max -1<<31 ___ maxPathSum root """ :param root: TreeNode :return: integer """ get_max_component(root) # global_max can in ANY path in the tree r.. global_max ___ get_max_component root """ Algorithm: dfs The path may start and end at any node in the tree. parent / cur / \ L R at current: the candidate max (final result) is cur+L+R at current: the max component (intermediate result) is cur or cur+L or cur+R Reference: http://fisherlei.blogspot.sg/2013/01/leetcode-binary-tree-maximum-path-sum.html :param root: :return: """ __ n.. root: r.. 0 left_max_component get_max_component(root.left) right_max_component get_max_component(root.right) # update global max current_max_sum m..(root.val, root.val+left_max_component, root.val+right_max_component, root.val+left_max_component+right_max_component) # four situations global_max m..(global_max, current_max_sum) # return value for upper layer to calculate the current_max_sum r.. m..(root.val, root.val+left_max_component, root.val+right_max_component) # excluding arch (i.e. root.val+left_max_component+right_max_component)
f18c667920fd2bd0879cf08aefccec88f5ab5424
syurskyi/Python_Topics
/021_module_collection/ordereddict/examples/ordereddict_001.py
3,195
4.5
4
# OrderedDict # # Prior to Python 3.7, dictionary key order was not guaranteed. This became part of the language in 3.7, # so the usefullness of this OrderedDict is diminished - but necessary if you want your dictionaries to maintain key # order and be compatible with Python versions earlier then 3.6 (technically dicts are ordered in 3.6 as well, # but it was considered an implementation detail, and not actually guaranteed). # # We'll come back to a direct comparison of OrderedDict and plain dict in a subsequent video. For now let's look at # the OrderedDict as if we were targeting our code to be compatible with earlier versions of Python. from collections import OrderedDict # Once again, OrderedDict is a subclass of dict. # # We can also pass keyword arguments to the constructor. However, in Python versions prior to 3.5, the order of # the arguments is not guaranteed to be preserved - so to be fully backward-compatible, insert keys into the dictionary # after you have created it as an empty dictionary. d = OrderedDict() d['z'] = 'hello' d['y'] = 'world' d['a'] = 'python' d # OrderedDict([('z', 'hello'), ('y', 'world'), ('a', 'python')]) # And if we iterate through the keys of the OrderedDict we will retain that key order as well: for key in d: print(key) # z # y # a # The OrderedDict also supports reverse iteration using reversed(): for key in reversed(d): print(key) # a # y # z # This is not the case for a standard dictionary, even in Python 3.5+ where key order is maintained! # In the next video we'll dig a little more into a comparison between OrderedDicts and dicts. d = {'a': 1, 'b': 2} # for key in reversed(d): # print(key) # ERROR TypeError: 'dict' object is not reversible # OrderedDicts are a subclass of dicts so all the usual operations and methods apply, # but OrderedDicts have a couple of extra methods available to us: # # popitem(last=True) # move_to_end(key, last=True) # # Since an OrderedDict has an ordering, it is natural to think of the first or last element in the dictionary. # # The popitem allows us to remove the last (by default) or first item (setting last=False): d = OrderedDict() d['first'] = 10 d['second'] = 20 d['third'] = 30 d['last'] = 40 d # OrderedDict([('first', 10), ('second', 20), ('third', 30), ('last', 40)]) d.popitem() # ('last', 40) d # OrderedDict([('first', 10), ('second', 20), ('third', 30)]) # As you can see the last item was popped off (and returned as a key/value tuple). To pop the first item we can do this: d.popitem(last=False) # ('first', 10) d # OrderedDict([('second', 20), ('third', 30)]) # The move_to_end method simply moves the specified key to the end (by default), or to the beginning # (if last=False is specified) of the dictionary: d = OrderedDict() d['first'] = 10 d['second'] = 20 d['third'] = 30 d['last'] = 40 d.move_to_end('second') d # OrderedDict([('first', 10), ('third', 30), ('last', 40), ('second', 20)]) d.move_to_end('third', last=False) d # OrderedDict([('third', 30), ('first', 10), ('last', 40), ('second', 20)]) # Be careful if you specify a non-existent key, you will get an exception: d.move_to_end('x') # ERROR KeyError: 'x'
629afab9d1f2edc335686eb9ba3c22d711437bff
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/LinkedList/143_ReorderList.py
1,737
4.0625
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 reorderList(self, head): """ Firstly, use two pointer to find the mid node_keep, Then reverse the post half nodes, and merge the pre half and post reversed half. """ if not head or not head.next or not head.next.next: return slow = fast = head while fast.next: if fast.next.next: slow = slow.next fast = fast.next.next else: break post_half_start = slow.next slow.next = None reverse_head = self.reverse_list(post_half_start) while head and reverse_head: node_keep = head.next reverse_node_keep = reverse_head.next head.next = reverse_head reverse_head.next = node_keep head = node_keep reverse_head = reverse_node_keep # Reverse a linked list def reverse_list(self, head): pre_node = None post_node = None while head: post_node = head.next head.next = pre_node pre_node = head head = post_node return pre_node # RuntimeError: maximum recursion depth exceeded """ def reverse_list(self, head): if not head.next: return head next_node = head.next new_head = self.reverse_list(next_node) next_node.next = head head.next = None return new_head """ """ [] [1] [1,2] [1,2,3,4,5,6] [1,2,3,4,5] """
5fdfd19366e69ce4f6d38a4fe3aa289881847a5f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Algorithms in Python Live Coding & Design Techniques/002_backtracking/004_word-search-puzzle/Boggle.py
770
3.59375
4
my_dict {'RAY', 'APPLE', 'FAKE', 'BOOKS'} m 4 n 4 ___ find_words(boggle, visited, i, j, word visited[i][j] 1 word ''.j..([word, boggle[i][j]]) __ word __ my_dict: print(word) ___ row __ ra__(i-1, i+2 ___ col __ ra__(j-1, j+2 __ is_valid(row, col, visited find_words(boggle, visited, row, col, word) visited[i][j] 0 ___ is_valid(row, col, visited __ 0 < row < m a__ 0 < col < n a__ visited[row][col] __ 0: r_ T.. r_ F.. boggle [['T', 'Y', 'R', 'S'], ['N', 'U', 'A', 'K'], ['Z', 'F', 'E', 'O'], ['A', 'C', 'B','O']] visited [[0 ___ j __ ra__(n)] ___ i __ ra__(m)] ___ i __ ra__(m ___ j __ ra__(n find_words(boggle, visited, i, j, '')
dfad7dd31f2f90a1aa05d52dae88ac20f145b5f6
syurskyi/Python_Topics
/065_serialization_and_deserialization/001_pickle/examples/45. Pickling - Coding_002.py
11,845
4.59375
5
# n this part of the course I am only going to discuss pickling basic data types such as numbers, strings, tuples, # lists, sets and dictionaries. # In general tuples, lists, sets and dictionaries are all picklable as long as their elements are themselves picklable. # Let's start by serializing some simple data types, such as strings and numbers. # Instead of serializing to a file, I will store the resulting pickle data in a variable, so we can easily # inspect it and unpickle it: import pickle ser = pickle.dumps('Python Pickled Peppers') print(ser) # b'\x80\x03X\x16\x00\x00\x00Python Pickled Peppersq\x00.' # ###################################################################################################################### print('#' * 52 + ' We can deserialize the data this way: ') deser = pickle.loads(ser) print(deser) # 'Python Pickled Peppers' # ###################################################################################################################### print('#' * 52 + ' We can do the same thing with numerics ') ser = pickle.dumps(3.14) print(ser) deser = pickle.loads(ser) print(deser) # 3.14 # ###################################################################################################################### print('#' * 52 + ' We can do the same with lists and tuples: ') d = [10, 20, ('a', 'b', 30)] ser = pickle.dumps(d) print(ser) # b'\x80\x03]q\x00(K\nK\x14X\x01\x00\x00\x00aq\x01X\x01\x00\x00\x00bq\x02K\x1e\x87q\x03e.' # ###################################################################################################################### deser = pickle.loads(ser) print(deser) # [10, 20, ('a', 'b', 30)] # ###################################################################################################################### print('#' * 52 + ' Note that the original and the deserialized objects are equal, but not identical:') print(d is deser, d == deser) # (False, True) # ###################################################################################################################### print('#' * 52 + ' This works the same way with sets too:') s = {'a', 'b', 'x', 10} print(s) # {10, 'a', 'b', 'x'} # ###################################################################################################################### ser = pickle.dumps(s) print(ser) # b'\x80\x03cbuiltins\nset\nq\x00]q\x01(X\x01\x00\x00\x00aq\x02K\nX\x01\x00\x00\x00xq\x03X\x01\x00\x00\x00bq\x04e\x85q\x05Rq\x06.' # ###################################################################################################################### deser = pickle.loads(ser) print(deser) # {'a', 10, 'b', 'x'} # ###################################################################################################################### print('#' * 52 + ' And finally, we can pickle dictionaries as well:') d = {'b': 1, 'a': 2, 'c': {'x': 10, 'y': 20}} print(d) # {'b': 1, 'a': 2, 'c': {'x': 10, 'y': 20}} # ###################################################################################################################### ser = pickle.dumps(d) print(ser) # b'\x80\x03}q\x00(X\x01\x00\x00\x00bq\x01K\x01X\x01\x00\x00\x00aq\x02K\x02X\x01\x00\x00\x00cq\x03}q\x04(X\x01\x00\x00\x00xq\x05K\nX\x01\x00\x00\x00yq\x06K\x14uu.' # ###################################################################################################################### deser = pickle.loads(ser) print(deser) # {'b': 1, 'a': 2, 'c': {'x': 10, 'y': 20}} # ###################################################################################################################### print(d == deser) # True print('#' * 52 + ' What happens if we pickle a dictionary that has two of its values set to another dictionary?') d1 = {'a': 10, 'b': 20} d2 = {'x': 100, 'y': d1, 'z': d1} print(d2) # {'x': 100, 'y': {'a': 10, 'b': 20}, 'z': {'a': 10, 'b': 20}} # ###################################################################################################################### ser = pickle.dumps(d2) d3 = pickle.loads(ser) print(d3) # {'x': 100, 'y': {'a': 10, 'b': 20}, 'z': {'a': 10, 'b': 20}} # ###################################################################################################################### print('#' * 52 + ' That seems to work... Is that sub-dictionary still the same as the original one?') print(d3['y'] == d2['y']) # True # ###################################################################################################################### print(d3['y'] is d2['y']) # False # ###################################################################################################################### print('#' * 52 + ' But consider the original dictionary d2: both the x and y keys referenced the same dictionary d1:') print(d2['y'] is d2['z']) # True # ###################################################################################################################### print('#' * 52 + ' How did this work with our deserialized dictionary?') print(d3['y'] == d3['z']) # True # ###################################################################################################################### # As you can see the relative shared object is maintained. # As you can see our dictionary d looks like the earlier one. So, when Python serializes the dictionary, # it behaves very similarly to serializing a deep copy of the dictionary. The same thing happens with other collections # types such as lists, sets, and tuples. # What this means though is that you have to be very careful how you use serialization and deserialization. # Consider this piece of code: print('#' * 52 + ' As you can see the relative shared object is maintained.') print('#' * 52 + ' ') print('#' * 52 + ' What this means though is that you have to be very careful how you use serialization and ' 'deserialization.') d1 = {'a': 1, 'b': 2} d2 = {'x': 10, 'y': d1} print(d1) print(d2) d1['c'] = 3 print(d1) print(d2) # {'a': 1, 'b': 2} # {'x': 10, 'y': {'a': 1, 'b': 2}} # {'a': 1, 'b': 2, 'c': 3} # {'x': 10, 'y': {'a': 1, 'b': 2, 'c': 3}} # ###################################################################################################################### print('#' * 52 + ' Now suppose we pickle our dictionaries to restore those values the next time around, ' ' but use the same code, expecting the same result:') d1 = {'a': 1, 'b': 2} d2 = {'x': 10, 'y': d1} d1_ser = pickle.dumps(d1) d2_ser = pickle.dumps(d2) # simulate exiting the program, or maybe just restarting the notebook del d1 del d2 # load the data back up d1 = pickle.loads(d1_ser) d2 = pickle.loads(d2_ser) # and continue processing as before print(d1) print(d2) d1['c'] = 3 print(d1) print(d2) # {'a': 1, 'b': 2} # {'x': 10, 'y': {'a': 1, 'b': 2}} # {'a': 1, 'b': 2, 'c': 3} # {'x': 10, 'y': {'a': 1, 'b': 2}} # ###################################################################################################################### # So just remember that as soon as you pickle a dictionary, whatever object references it had to another object is # essentially lost - just as if you had done a deep copy first. It's a subtle point, but one that can easily lead # to bugs if we're not careful. # However, the pickle module is relatively intelligent and will not re-pickle an object it has already pickled - # which means that relative references are preserved. # Let's see an example of what I mean by this: print('#' * 52 + ' So just remember that as soon as you pickle a dictionary, ' ' whatever object references it had to another object is essentially lost - ' ' just as if you had done a deep copy first. ' ' It is a subtle point, but one that can easily lead to bugs if we are not careful.') print('#' * 52 + ' ') print('#' * 52 + ' However, the pickle module is relatively intelligent and will not re-pickle an object it has' ' already pickled - which means that relative references are preserved.') class Person: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return self.name == other.name and self.age == other.age def __repr__(self): return f'Person(name={self.name}, age={self.age})' john = Person('John Cleese', 79) eric = Person('Eric Idle', 75) michael = Person('Michael Palin', 75) parrot_sketch = { "title": "Parrot Sketch", "actors": [john, michael] } ministry_sketch = { "title": "Ministry of Silly Walks", "actors": [john, michael] } joke_sketch = { "title": "Funniest Joke in the World", "actors": [eric, michael] } fan_favorites = { "user_1": [parrot_sketch, joke_sketch], "user_2": [parrot_sketch, ministry_sketch] } from pprint import pprint pprint(fan_favorites) # {'user_1': [{'actors': [Person(name=John Cleese, age=79), # Person(name=Michael Palin, age=75)], # 'title': 'Parrot Sketch'}, # {'actors': [Person(name=Eric Idle, age=75), # Person(name=Michael Palin, age=75)], # 'title': 'Funniest Joke in the World'}], # 'user_2': [{'actors': [Person(name=John Cleese, age=79), # Person(name=Michael Palin, age=75)], # 'title': 'Parrot Sketch'}, # {'actors': [Person(name=John Cleese, age=79), # Person(name=Michael Palin, age=75)], # 'title': 'Ministry of Silly Walks'}]} # ###################################################################################################################### print('#' * 52 + ' As you can see we have some shared references, for example:') print(fan_favorites['user_1'][0] is fan_favorites['user_2'][0]) # True # ###################################################################################################################### print('#' * 52 + ' Lets store the id of the parrot_sketch for later reference:') parrot_id_original = id(parrot_sketch) print('#' * 52 + ' Now lets pickle and unpickle this object:') ser = pickle.dumps(fan_favorites) new_fan_favorites = pickle.loads(ser) print(fan_favorites == new_fan_favorites) # True # ###################################################################################################################### print('#' * 52 + ' And lets look at the id of the parrot_sketch object in our new dictionary' ' compared to the original one:') print(id(fan_favorites['user_1'][0]), id(new_fan_favorites['user_1'][0])) # (4554999848, 4555001288) # ###################################################################################################################### print('#' * 52 + ' As expected the ids differ - but the objects are equal:') print(fan_favorites['user_1'][0] == new_fan_favorites['user_1'][0]) # True # ###################################################################################################################### print('#' * 52 + ' But now lets look at the parrot sketch that is in both user_1 and user_2 - ' ' remember that originally the objects were identical (is):') print(fan_favorites['user_1'][0] is fan_favorites['user_2'][0]) # True # ###################################################################################################################### print('#' * 52 + ' and with our new object:') print(new_fan_favorites['user_1'][0] is new_fan_favorites['user_2'][0]) # True # ###################################################################################################################### print('#' * 52 + ' As you can see the relative relationship between objects that were pickled is preserved.') # And that's all I'm really going to say about pickling objects in Python. Instead I'm going to focus more on what # is probably a more relevant topic to many of you - JSON serialization/deserialization.
4bdc3e5c0b1cb56581808303ac989ea1c599c5d1
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/234_capitalize_sentences/save5_passed.py
332
3.875
4
import re def capitalize_sentences(text: str) -> str: '''Returns sentence with correct capitalisation.''' def upper_it(m): return m.group().upper() sentence = re.split(r'([!?.])\s', text) output = ' '.join([re.sub(r'^\w', upper_it, line) for line in sentence]) return re.sub(r'\s([?.!])', r'\1', output)
4aa523e8b89b526e154a27c9d0b45f5056a4be9c
syurskyi/Python_Topics
/065_serialization_and_deserialization/002_json/_exercises/_templates/53. Custom JSON Decoding - Coding.py
21,723
3.9375
4
# # Custom JSON Decoding # # So far we have looked at how to encode (serialize) Python objects to JSON, using the standard as well as custom # # object serializers. # # Now we need to turn our attention to teh reverse process - deserializing (decoding) JSON data. # # Once again, the standard simple types such as strings, numbers (ints and floats), arrays, and objects with key/value # # pairs. JSON does not differentiate between mutable and immutable lists - so everything that is an array ([...]) # # in JSON will get decoded into a list object. # # Let's see a quick example of how to do this: # # print('#' * 52 + ' Once again, the standard simple types such as strings, numbers (ints and floats), ' # ' arrays, and objects with key/value pairs. ') # print('#' * 52 + ' JSON does not differentiate between mutable and immutable lists - ' # ' so everything that is an array ([...]) in JSON will get decoded into a list object.') # # j = ''' # { # "name": "Python", # "age": 27, # "versions": ["2.x", "3.x"] # } # ''' # # ______ j___ # print j___.l... ? # # {'name': 'Python', 'age': 27, 'versions': ['2.x', '3.x']} # # ###################################################################################################################### # # print('#' * 52 + ' But what about other data types, such as a date for example. How can we handle that?') # # p _ ''' # { # "time": "2018-10-21T09:14:00", # "message": "created this json string" # } # ''' # print j___.l... ? # # # # {'time': '2018-10-21T09:14:00', 'message': 'created this json string'} # # ###################################################################################################################### # # # The deserialization worked just fine, but you'll notice that the dictionary entry for time contains a string, not a date. # # This is not a trivial problem, and many 3rd party libraries have been written to deserialize specialized JSON # # structures into custom Python objects. It basically boils down to having a specific structure (schema) in the # # JSON and manually loading up some custom (or standard) Python object by specifically looking for certain elements # # and objects in the JSON object. Remember that JSON only supports a few basic types, so anything beyond that is really # # a custom interpretation of the data in the JSON object. # # For example, suppose we have a JSON object where any object that contains the key/value pair "objecttype": "datetime" # # is guaranteed to contain another key called "value" containing a date time in the format %Y-%m-%dT%H:%M:%S. # # We could easily do the following: # print('#' * 52 + ' For example, suppose we have a JSON object where any object that contains' # ' the key/value pair `"objecttype": "datetime"` is guaranteed to contain another key' # ' called `"value"` containing a date time in the format %Y-%m-%dT%H:%M:%S. ') # # p _ ''' # { # "time": { # "objecttype": "datetime", # "value": "2018-10-21T09:14:15" # }, # "message": "created this json string" # } # ''' # # d _ j___.l... ? # print(d) # # {'time': {'objecttype': 'datetime', 'value': '2018-10-21T09:14:15'}, # # 'message': 'created this json string'} # # ###################################################################################################################### # # print('#' * 52 + ' We could now run through our dictionary (top level only, we will come back to that), ' # ' and convert any datetime structures (schema) into actual datetime objects:') # # f... d..t.. ______ d..t.. # # ___ key value i_ d.it.. # i_ isi... v.. di.. an. # 'objecttype' i_ va.. an. # va.. 'objecttype'| __ 'datetime' # d key| _ da__ti__.st..ti. va.. |'value' %Y-%m-%dT%H:%M:%S # # print(d) # # {'time': datetime.datetime(2018, 10, 21, 9, 14, 15), # # 'message': 'created this json string'} # # ###################################################################################################################### # # # As you can see that worked just fine. We can do this with other "custom" JSON schemas as well. # # Let's say we have a JSON schema that will encode fractions using a fraction type indicator and associated keys # # numerator and denominator with integer values, such as: # # # # "pieSlice": { # # "objecttype": "fraction", # # "numerator": 1, # # "denominator": 3 # # } # # We can deal with this in the same way as before: # # print('#' * 52 + ' We can do this with other "custom" JSON schemas as well.') # print('#' * 52 + ' Lets say we have a JSON schema that will encode fractions using a `fraction` type indicator' # ' and associated keys `numerator` and `denominator` with integer values,') # # j _ ''' # { # "cake": "yummy chocolate cake", # "myShare": { # "objecttype": "fraction", # "numerator": 1, # "denominator": 8 # } # } # ''' # # d _ j___.l... ? # print(d) # # {'cake': 'yummy chocolate cake', # # 'myShare': {'objecttype': 'fraction', 'numerator': 1, 'denominator': 8}} # # ###################################################################################################################### # # print('#' * 52 + ' ') # print('#' * 52 + ' ') # print('#' * 52 + ' ') # # f... fr.. ______ F... # # ___ key value i_ d.it.. # i_ (isi... va.. di.. an. # 'objecttype' i_ va.. an. # va.. 'objecttype'| __ 'fraction' # numerator _ va.. 'numerator'| # denominator _ va.. 'denominator'| # d|key _ F.. n.. d... # # print(d) # # {'cake': 'yummy chocolate cake', 'myShare': Fraction(1, 8)} # # ###################################################################################################################### # # print('#' * 52 + ' ') # print('#' * 52 + ' ') # print('#' * 52 + ' ') # # # We can extend this to even custom objects as long as they follow a specific structure (schema). # # We could put all this code into a function, even one that can handle multiple types and clean it up quite a bit. But... # # A few things: # # It's a real pain having to go through the dictionary after the fact and convert the objects # # Our conversion code only considered top-level objects - what if they are nested deeper in the JSON object - # # we would need to deal with that possibility. # # There has to be a better way! # # And indeed, there is - but all in all it's still relatively clunky in some respects. Let's look at the # # `load`/`loads` functions first. They have an optional argument named `object_hook` that can reference a callable. # # This is very similar to the `default` argument we saw in the `dump`/`dumps` functions - but works for decoding # # instead of encoding. That callable, if specified, will be called for every value in the JSON object that is itself # # an object (including the root object). That dictionary will then be replaced by whatever that decoder returns. # # Let's first write a dummy decoder, just to see how and when it gets called: # # # ___ custom_decoder arg # print 'decoding: ' a.. # r_ a.. # # # j _ ''' # { # "a": 1, # "b": 2, # "c": { # "c.1": 1, # "c.2": 2, # "c.3": { # "c.3.1": 1, # "c.3.2": 2 # } # } # } # ''' # # d _ j___.l... ? o.._h.._cu... # # decoding: {'c.3.1': 1, 'c.3.2': 2} # # decoding: {'c.1': 1, 'c.2': 2, 'c.3': {'c.3.1': 1, 'c.3.2': 2}} # # decoding: {'a': 1, 'b': 2, 'c': {'c.1': 1, 'c.2': 2, 'c.3': {'c.3.1': 1, 'c.3.2': 2}}} # # ###################################################################################################################### # # # As you can see it called our decoder three times, the value for the key c.3, the value for the key c and the root # # object itself. # # Now, let's write a decoder that will handle the datetime JSON we worked with earlier: # print('#' * 52 + ' As you can see it called our decoder three times, ' # ' the value for the key `c.3`, the value for the key `c` and the root object itself.') # # j _ ''' # { # "time": { # "objecttype": "datetime", # "value": "2018-10-21T09:14:15" # }, # "message": "created this json string" # } # ''' # # # ___ custom_decoder arg # i_ 'objecttype' i_ ar. an. ar.|'objecttype' __ 'datetime' # r_ d..ti__.st..t. ar. 'value'| '%Y-%m-%dT%H:%M:%S' # e___ # r___ a.. # important, otherwise we lose anything that's not a date! # # # print('#' * 52 + ' Lets just see how it works as a plain function first:') # # print cu... di.. ob..ty.._'datetime' va.._2018-10-21T09:14:15 # # datetime.datetime(2018, 10, 21, 9, 14, 15) # # ###################################################################################################################### # # print cu... di.. a_1 # # {'a': 1} # # ###################################################################################################################### # # d _ j___.l... ? o.._h._cu. # print(d) # # {'time': datetime.datetime(2018, 10, 21, 9, 14, 15), # # 'message': 'created this json string'} # # ###################################################################################################################### # # print('#' * 52 + ' The nice thing about this approach, is our code is simpler, and this works for nested items too:') # # j = ''' # { # "times": { # "created": { # "objecttype": "datetime", # "value": "2018-10-21T09:14:15" # }, # "updated": { # "objecttype": "datetime", # "value": "2018-10-22T10:00:05" # } # }, # "message": "log message here..." # } # ''' # # d _ j___.l... ? o...._cu.. # # print(d) # # {'times': {'created': datetime.datetime(2018, 10, 21, 9, 14, 15), # # 'updated': datetime.datetime(2018, 10, 22, 10, 0, 5)}, # # 'message': 'log message here...'} # # ###################################################################################################################### # # # We can also extend this custom decoder to include other structures (schemas). Let's add in our fraction decoder: # # print('#' * 52 + ' ') # print() # print() # print('#' * 52 + ' We can also extend this custom decoder to include other structures (schemas).') # # # ___ custom_decoder arg # ret_value _ ar. # i_ 'objecttype' i_ ar. # i_ ar. 'objecttype'| __ datetime # ret_value _ da..ti__.s..ti.. ar. 'value'| %Y-%m-%dT%H:%M:%S # e___ ar. 'objecttype'| __ 'fraction' # ret_value _ F... a.. 'numerator'| ar. 'denominator'| # r_ r.. # # # j _ ''' # { # "cake": "yummy chocolate cake", # "myShare": { # "objecttype": "fraction", # "numerator": 1, # "denominator": 8 # }, # "eaten": { # "at": { # "objecttype": "datetime", # "value": "2018-10-21T21:30:00" # }, # "time_taken": "30 seconds" # } # } # ''' # # d _ j___.l... ? o.._h..=cu... # print(d) # # {'cake': 'yummy chocolate cake', 'myShare': Fraction(1, 8), 'eaten': {'at': datetime.datetime(2018, 10, 21, 21, 30), 'time_taken': '30 seconds'}} # # ###################################################################################################################### # # # We can't really use a generic single dispatch approach we took with the encoder though - the decoder always receives # # a dictionary, so we can't build it that way. # # We still have the issue of custom objects and classes - how do we handle those? # # Well, in pretty much the same way as before - the content of the JSON has to indicate that the object is of # # a certain "type", and we can then decode it ourselves. # # Let's see a simple example: # # print('#' * 52 + ' ') # print() # print() # print('#' * 52 + ' We cant really use a generic single dispatch approach we took with the encoder though -' # ' the decoder always receives a dictionary, so we cant build it that way.') # print('#' * 52 + ' We still have the issue of custom objects and classes - how do we handle those?') # print('#' * 52 + ' Well, in pretty much the same way as before - ' # ' the content of the JSON has to indicate that the object is of a certain "type", ' # ' and we can then decode it ourselves.') # # # c_ Person # ___ __i__ ____ name ssn # ____.n.. _ n.. # ____.s.. _ s.. # # ___ __re__ ____ # r_ _*P.. n.._|____.name s.._|____.ssn # # # j _ ''' # { # "accountHolder": { # "objecttype": "person", # "name": "Eric Idle", # "ssn": 100 # }, # "created": { # "objecttype": "datetime", # "value": "2018-10-21T03:00:00" # } # } # ''' # # # ___ custom_decoder arg) # ret_value _ ar. # i_ 'objecttype' i_ arg # i_ ar. 'objecttype'| __ 'datetime # ret_value _ da..ti__.st..ti.. ar. 'value'| %Y-%m-%dT%H:%M:%S # e___ ar. 'objecttype'| __ 'fraction' # ret_value _ F... ar. |'numerator' arg|'denominator' # e__ ar. 'objecttype'| __ 'person' # ret_value _ P.. ar. 'name'| ar. 'ssn' # r_ r.. # # # d _ j___.l... ? o.._h.._cu.. # print(d) # # {'accountHolder': Person(name=Eric Idle, ssn=100), # # 'created': datetime.datetime(2018, 10, 21, 3, 0)} # # ###################################################################################################################### # # print('#' * 52 + ' We could also provide our custom JSON encoder in the person class to serialize ' # ' that class in the way we expect when deserializing, as we saw in an earlier video:') # # # c_ Person # ___ __init__ ____ name ssn # ____.n.. _ n.. # ____.s.. _ s.. # # ___ __r__ ____ # r_ _*P.. n.._|____.n.. s.._|____.ssn # # ___ toJSON ____ # r_ di.. ob..t.._'person' n.._____.n.. s.._____.s.. # # # We can then encode using the techniques we have seen before, and decode using the technique we learned in this video. # # There are also a few customized hooks for integers, floats and certain special strings (-Infinity, Infinity and NaN). # # For example, we may want to encode floats using a Decimal instead of the standard float. # # We could do this by using the parse_float argument as follows: # # f... d... ______ D... # # ___ make_decimal arg # print 'Received:' ty.. ar. ar. # r_ D... ar. # # # j = ''' # { # "a": 100, # "b": 0.2, # "c": 0.5 # } # ''' # # d _ j___.l... ? parse_float_ma.._d.. # # # Received: <class 'str'> 0.2 # # # Received: <class 'str'> 0.5 # # ###################################################################################################################### # # print(d) # # {'a': 100, 'b': Decimal('0.2'), 'c': Decimal('0.5')} # # ###################################################################################################################### # # # As you can see we have decimals in our dictionary, instead of floats. Note also that the argument we receive # # is a string - it would make little sense for us to receive a float since our function is the one that wants # # to specifically handle converting a JSON string to some particular type. # # We can also intercept handling of integers and those constant values I mentioned. # print('#' * 52 + ' As you can see we have decimals in our dictionary, instead of floats.') # print('#' * 52 + ' Note also that the argument we receive is a string - it would make little sense for us to receive' # ' a float since our function is the one that wants to specifically handle converting ' # ' a JSON string to some particular type.') # print('#' * 52 + ' We can also intercept handling of integers and those constant values I mentioned.') # # j = ''' # { # "a": 100, # "b": Infinity # } # ''' # # print j___.l... ? # # {'a': 100, 'b': inf} # # ###################################################################################################################### # # ___ make_int_binary arg # print('Received:' ty.. ar. ar. # r_ bi. in. ar. # # # ___ make_const_none arg # print('Received:' ty.. ar. ar. # r_ N.. # # # print(j___.l... j # parse_int_ma... # parse_constant_ma_no.. # # Received: <class 'str'> 100 # # Received: <class 'str'> Infinity # # {'a': '0b1100100', 'b': None} # # ###################################################################################################################### # # # Again note that in all cases, the received argument is the string read f... the json string. # # Finally we have the object_pairs_hook argument. It works similarly to the object_hook with two differences: # # the argument is a list of 2-tuples - the first value is the key, the second is the value # # the list is ordered in the same order as the keys in the json document. # # Remember that the dictionary is not guaranteed to be ordered in the same order as the keys in the json document - # # given Python 3.6+ has guaranteed dictionary order, this is likely to be true, but the documents do not mention this # # specifically, so at this point it should be considered an implementation detail and not relied on - if you must have # # gauranteed key order, then you will have to use the object_pairs_hook. # # Also, you should not specify both object_hook and object_pairs_hook - if you do, then the object_pairs_hook will # # be used and object_hook will be ignored. # # # print('#' * 52 + ' Also, you should not specify both `object_hook` and `object_pairs_hook` - if you do, ' # ' then the `object_pairs_hook` will be used and `object_hook` will be ignored.') # # j _ ''' # { # "a": [1, 2, 3, 4, 5], # "b": 100, # "c": 10.5, # "d": NaN, # "e": null, # "f": "python" # } # ''' # # # ___ float_handler ar. # print('float handler' ty.. ar. ar. # r_ fl.. ar. # # # ___ int_handler arg # print 'int handler' ty.. ar. ar. # r_ in. ar. # # # ___ const_handler arg # print 'const handler', ty.. ar. ar. # r.. N.. # # # ___ obj_hook(arg): # print('obj hook' ty.. ar. ar. # r_ ar. # # # ___ obj_pairs_hook ar. # print('obj pairs hook' ty.. ar. ar. # return arg # # print j___.l... ? # # {'a': [1, 2, 3, 4, 5], 'b': 100, 'c': 10.5, 'd': nan, 'e': None, 'f': 'python'} # # ###################################################################################################################### # # # print j___.l... ? # object_hook _ o._h.. # parse_float _ fl.._h.. # parse_int _ in.._ha_ # parse_constant _ c._h.. # )) # # int handler <class 'str'> 1 # # int handler <class 'str'> 2 # # int handler <class 'str'> 3 # # int handler <class 'str'> 4 # # int handler <class 'str'> 5 # # int handler <class 'str'> 100 # # float handler <class 'str'> 10.5 # # const handler <class 'str'> NaN # # obj hook <class 'dict'> {'a': [1, 2, 3, 4, 5], 'b': 100, 'c': 10.5, 'd': None, 'e': None, 'f': 'python'} # # {'a': [1, 2, 3, 4, 5], # # 'b': 100, # # 'c': 10.5, # # 'd': None, # # 'e': None, # # 'f': 'python'} # # ###################################################################################################################### # # print j___.l... ? # object_pairs_hook_ob._p.._h.. # parse_float _ f.._ha.. # parse_int _ in._ha.. # parse_constant _ c.._ha.. # )) # # int handler <class 'str'> 1 # # int handler <class 'str'> 2 # # int handler <class 'str'> 3 # # int handler <class 'str'> 4 # # int handler <class 'str'> 5 # # int handler <class 'str'> 100 # # float handler <class 'str'> 10.5 # # const handler <class 'str'> NaN # # obj pairs hook <class 'list'> [('a', [1, 2, 3, 4, 5]), ('b', 100), ('c', 10.5), ('d', None), ('e', None), ('f', 'python')] # # [('a', [1, 2, 3, 4, 5]), # # ('b', 100), # # ('c', 10.5), # # ('d', None), # # ('e', None), # # ('f', 'python')] # # ###################################################################################################################### # # print('#' * 52 + ' And if we specify both object hooks, then `object_hook` is basically ignored:') # # print j___.l... j # object_hook _ ob._h.. # object_pairs _ hook_o._p._h. # parse_float _ fl.._ha.. # parse_int _ in._ha.. # parse_constant _ c.._h.. # )) # # int handler <class 'str'> 1 # # int handler <class 'str'> 2 # # int handler <class 'str'> 3 # # int handler <class 'str'> 4 # # int handler <class 'str'> 5 # # int handler <class 'str'> 100 # # float handler <class 'str'> 10.5 # # const handler <class 'str'> NaN # # obj pairs hook <class 'list'> [('a', [1, 2, 3, 4, 5]), ('b', 100), ('c', 10.5), ('d', None), ('e', None), ('f', 'python')] # # [('a', [1, 2, 3, 4, 5]), # # ('b', 100), # # ('c', 10.5), # # ('d', None), # # ('e', None), # # ('f', 'python')] # # ###################################################################################################################### # # # As we saw in the decoding videos, we can also subclass the JSONDecoder class (just like we subclassed the JSONEncoder - we'll look at this next.
914cb8894d8d1e56c11d8be861b274e3df13d1fa
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BinarySearch/81_SearchInRotatedSortedArrayII.py
1,464
4.09375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ nums_size = len(nums) start = 0 end = nums_size - 1 while start <= end: mid = (start + end) / 2 num_mid = nums[mid] # Mid is in the left part of the rotated(if it's rotated) array. if num_mid > nums[start]: if nums[start] <= target < num_mid: end = mid - 1 elif target == num_mid: return True else: start = mid + 1 # The array must be rotated, and mid is in the right part elif num_mid < nums[start]: if num_mid < target <= nums[end]: start = mid + 1 elif target == num_mid: return True else: end = mid - 1 # Can't make sure whether mid in the left part or right part. else: # Find the target. if target == num_mid: return True # Just add start with one until we can make sure. # Of course, you can also minus end with one. start += 1 return False """ [] 0 [1] 1 [7,8,7,7,7] 8 [7,7,7,8,8] 8 """
2f3eadacf6838ceff698dd25a24084b7774dcfe5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/820 Short Encoding of Words.py
1,347
4.09375
4
#!/usr/bin/python3 """ Given a list of words, we may encode it by writing a reference string S and a list of indexes A. For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5]. Then for each index, we will recover the word by reading from the reference string from that index until we reach a "#" character. What is the length of the shortest reference string S possible that encodes the given words? Example: Input: words = ["time", "me", "bell"] Output: 10 Explanation: S = "time#bell#" and indexes = [0, 2, 5]. Note: 1 <= words.length <= 2000. 1 <= words[i].length <= 7. Each word has only lowercase letters. """ ____ t___ _______ L.. c_ Solution: ___ minimumLengthEncoding words: L..s.. __ i.. """ suffix trie only suffix matters fast trie with dict """ root # dict ends # list ___ word __ s..(words cur root ___ c __ word ||-1 nxt cur.g.. c, {}) cur[c] nxt cur nxt ends.a..((cur, l..(word))) r.. s..( l + 1 ___ node, l __ ends __ l..(node) __ 0 # no child ) __ _______ __ _______ ... Solution().minimumLengthEncoding(["time", "me", "bell"]) __ 10
69fb9eab9782d4b53bbd781db80061561795fe8e
syurskyi/Python_Topics
/045_functions/013_switch_simulation/003.py
922
4.125
4
def add(x, to=1): return x + to def divide(x, by=2): return x / by def square(x): return x ** 2 def invalid_op(x): raise Exception("Invalid operation") def perform_operation(x, chosen_operation, operation_args=None): # If operation_args wasn't provided (i.e. it is None), set it to be an empty dictionary operation_args = operation_args or {} ops = { "add": add, "divide": divide, "square": square } chosen_operation_function = ops.get(chosen_operation, invalid_op) return chosen_operation_function(x, **operation_args) def example_usage(): x = 1 x = perform_operation(x, "add", {"to": 4}) # Adds 4 print(x) x = perform_operation(x, "add") # Adds 1 since that's the default for 'add' x = perform_operation(x, "divide", {"by": 2}) # Divides by 2 x = perform_operation(x, "square") # Squares the number example_usage()
3ea498eec2df07acc5a10ff3b8daaa0ef24ef0f6
syurskyi/Python_Topics
/070_oop/007_exceptions/_exercises/templates/The_Complete_Python_Course_l_Learn_Python_by_Doing/74. Solution raising an error.py
154
3.8125
4
def count_from_zero_to_n(n): if n < 0: raise ValueError('Input should be a non-negative integer') for x in range(0, n+1): print(x)
a04255385772dd5f31a54968965cd6fd354b0f77
syurskyi/Python_Topics
/012_lists/examples/ITVDN Python Starter 2016/12-append.py
291
3.78125
4
# -*- coding: utf-8 -*- # Создание пустого списка my_list = [] # Метод append добавляет значение в список my_list.append(3) my_list.append(5) my_list.append(my_list[0] + my_list[1]) # Вывод списка на экран print(my_list)
c0f57ca64556bc368879e4ac1eed4a88eb6997cc
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/033 Search in Rotated Sorted Array.py
2,174
3.875
4
""" Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. """ __author__ 'Danyang' c_ Solution: ___ s.. A, target """ assume no duplicate exists in the array Algorithm: modification of binary search reference: http://fisherlei.blogspot.sg/2013/01/leetcode-search-in-rotated-sorted-array.html start mid end Case 1: no rotation, just normal binary search 1, 2, 3, 4, 5, 6, 7 Case 2: rotate a little (rotate right) (i.e. A[mid]<A[start] and A[mid]<A[end]) 7, 1, 2, 3, 4, 5, 6 if target<A[mid]: search left if target>A[mid] and target<A[end]: search right if target>A[mid] and target>A[end]: search left Case 3: rotate a lot (rotate left) (i.e. A[mid]>A[start] and A[mid]>A[end]) 2, 3, 4, 5, 6, 7, 1 if target>A[mid]: search right if target<A[mid] and target>A[start]: search left if target<A[mid] and target<A[start]: search right :param A: a list of integers :param target: an integer to be searched :return: index, integer """ length l..(A) start 0 end length-1 # [start, end] w.... start<_end: mid (start+end)/2 # found __ A[mid]__target: r.. mid # case 1 __ A[start]<A[mid]<A[end]: __ target>A[mid]: start mid+1 ____ end mid-1 # case 2 ____ A[start]>A[mid] a.. A[mid]<A[end]: __ target>A[mid] a.. target<_A[end]: start mid+1 ____ end mid -1 # case 3 ____ __ target<A[mid] a.. target>_A[start]: end mid-1 ____ start mid+1 r.. -1 __ _____ __ ____ print Solution().s..([5,1,3], 5)
0cbbda0d988063e9926a52ca93580e511a91c11b
syurskyi/Python_Topics
/045_functions/_examples/The_Modern_Python_3_Bootcamp/369. SOLUTIONS Part 2.py
910
3.6875
4
# SOLUTIONS # Part # 2 # Solutions # Part # 2 # # Titleize def titleize(string): return ' '.join(s[0].upper() + s[1:] for s in string.split(' ')) # find_factors def find_factors(num): factors = [] i = 1 while (i <= num): if (num % i == 0): factors.append(i) i += 1 return factors # includes def includes(item, val, start=None): if type(item) == dict: return val in item.values() if start is None: return val in item return val in item[start:] # repeat def repeat(string, num): if (num == 0): return '' i = 0 newStr = '' while (i < num): newStr += string i += 1 return newStr # truncate def truncate(string, n): if (n < 3): return "Truncation must be at least 3 characters." if (n > len(string) + 2): return string return string[:n - 3] + "..."
dac3d95d56aaa07793ef86204efb0194e6709b9a
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/String/FindAndReplacePattern.py
2,144
4.09375
4
""" You have a list of words and a pattern, and you want to know which words in words matches the pattern. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. (Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.) Return a list of the words in words that match the given pattern. You may return the answer in any order. Example 1: Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. Note: 1 <= words.length <= 50 1 <= pattern.length = words[i].length <= 20 判断是否与给定的字符串模式是一样的。 思路是把所有的字符串转换为同一种编码的格式之后与pattern对比即可。 用的 str 直接就过了,beat 95%。 换成 set 取交集应该更快一些。 测试地址: https://leetcode.com/contest/weekly-contest-98/problems/find-and-replace-pattern/ beat: 95% 24ms. """ class Solution(object): def findAndReplacePattern(self, words, pattern): """ :type words: List[str] :type pattern: str :rtype: List[str] """ def translate_pattern(word): result = ['0'] current = '0' patterns = {word[0]: '0'} for i in word[1:]: if patterns.get(i) is not None: result.append(patterns.get(i)) else: current = str(int(current)+1) patterns[i] = current result.append(current) return ''.join(result) x = translate_pattern(pattern) result = [] for i in words: if x == translate_pattern(i): result.append(i) return result
be6d3b624bf38e6ed7cf8c93a26d4c6cb6cd7269
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+12 How to check if a point belongs to Circle.py
286
4.3125
4
_______ math x float(input("Insert point x: ")) y float(input("Insert point y: ")) r float(input("Insert the radius: ")) hypotenuse math.sqrt(pow(x,2) + pow(y,2)) __ hypotenuse < r: print("The point belongs to circle.") ____: print("The point does not belong to circle.")
a122ea2b3ce98e94a4d01e71fec488efeb01c53d
syurskyi/Python_Topics
/045_functions/008_built_in_functions/zip/_exercises/templates/015_zip() in Python.py
564
3.84375
4
# # Python code to demonstrate the working of # # zip() # # # initializing lists # name _ "Manjeet" "Nikhil" "Shambhavi" "Astha" # list # roll_no _ 4 1 3 2 # list # marks _ 40 50 60 70 # list # # # using zip() to map values # mapped _ z_ ? ? ? # # # converting values to print as set # mapped _ se. ? # # # printing resultant values # print The zipped result is : *; e.._** # print ? # # # # The zipped result is : {('Shambhavi', 3, 60), ('Astha', 2, 70), # # ('Manjeet', 4, 40), ('Nikhil', 1, 50)} #
0f7c3a814f2b69aa6b40bee42ff5ce60d131aed0
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/308_calculate_median_from_dictionary/save4_nopass.py
879
3.75
4
from collections import OrderedDict def calc_median_from_dict(d: dict) -> float: """ :param d: dict of numbers and their occurrences :return: float: median Example: {1: 2, 3: 1, 4: 2} -> [1, 1, 3, 4, 4] --> 3 is median """ values_sorted = dict(OrderedDict(sorted(d.items(), key=lambda t: t[0]))) if len(values_sorted) == 1: return list(values_sorted.keys())[0] number = sum(values_sorted.values()) determinate = number / 2 i = 0 i2 = 0 the_key = [] for key, value in values_sorted.items(): if i < determinate: i += value else: the_key.append(key) i2 += value the_key_true = the_key[0] before = [key for key in values_sorted.keys() if key < the_key_true][-1] if i == i2: return (before + the_key_true) / 2 else: return before
428f83dfc61311945f20d61ded25298f643ed0ef
syurskyi/Python_Topics
/080_tracing/_exercises/templates/traceback – Extract, format, and print exceptions and stack traces/005_.py
1,293
3.796875
4
# Working With the Stack # There are a similar set of functions for performing the same operations with the current call stack instead of # a traceback. # # print_stack() import traceback import sys from traceback_example import call_function def f(): traceback.print_stack(file=sys.stdout) print 'Calling f() directly:' f() print print 'Calling f() from 3 levels deep:' call_function(f) # $ python traceback_print_stack.py # # Calling f() directly: # File "traceback_print_stack.py", line 19, in <module> # f() # File "traceback_print_stack.py", line 16, in f # traceback.print_stack(file=sys.stdout) # # Calling f() from 3 levels deep: # File "traceback_print_stack.py", line 23, in <module> # call_function(f) # File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function # return call_function(f, recursion_level-1) # File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function # return call_function(f, recursion_level-1) # File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 24, in call_function # return f() # File "traceback_print_stack.py", line 16, in f # traceback.print_stack(file=sys.stdout)
79d56b1c2ecb5089792f5bdeb2ee0a55fbbc81d6
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/123/friends.py
1,080
3.890625
4
from collections import defaultdict names = 'bob julian tim martin rod sara joyce nick beverly kevin'.split() ids = range(len(names)) users = dict(zip(ids, names)) # 0: bob, 1: julian, etc friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5, 6), (5, 7), (5, 9), (6, 8), (7, 8), (8, 9)] def get_friend_with_most_friends(friendships, users=users): """Receives the friendships list of user ID pairs, parse it to see who has most friends, return a tuple of (name_friend_with_most_friends, his_or_her_friends)""" friend_frequency = defaultdict(list) for f1, f2 in friendships: friend_frequency[f1].append(f2) friend_frequency[f2].append(f1) most_friends = 0 previous_value = 0 for key, value in friend_frequency.items(): if len(value) >= previous_value: most_friends = key previous_value = len(value) return (users[most_friends], sorted([users[friend] for friend in friend_frequency[most_friends]])) # if __name__ == "__main__": # print(get_friend_with_most_friends(friendships))
fd930311925951b334d9b3f209d6d6a319ec9db5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/621 Task Scheduler.py
2,660
4
4
#!/usr/bin/python3 """ Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. You need to return the least number of intervals the CPU will take to finish all the given tasks. Example: Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. Note: The number of tasks is in the range [1, 10000]. The integer n is in the range [0, 100]. """ ____ t___ _______ L.. ____ c.. _______ d.., d.. _______ h__ c_ Solution: ___ leastInterval tasks: L..[s..], n: i.. __ i.. """ Gap is n Find the idle count use the max letter to construct page, # of page is max - 1 (need also consider duplicate) Each page size is n + 1 Free page size is n + 1 - (# of max) Find the idle count """ counter d.. i.. ___ t __ tasks: counter[t] += 1 maxa 0 max_cnt 0 ___ v __ counter.v.. __ v > maxa: maxa v max_cnt 1 ____ v __ maxa: max_cnt += 1 page_cnt maxa - 1 free_page_size n + 1 - max_cnt small_tasks l..(tasks) - max_cnt * maxa idle m..(0, page_cnt * free_page_size - small_tasks) r.. l..(tasks) + idle ___ leastInterval_complicated tasks: L..[s..], n: i.. __ i.. """ greedy max heap, most tasks first cool down queue """ counter d.. i.. ___ t __ tasks: counter[t] += 1 pq [ (-v, k) ___ k, v __ counter.i.. ] h__.heapify(pq) q d..() # stores (t, k) clock 0 w.... pq o. q: __ q a.. q 0 0 <_ clock: # don't do while in while when clock++ _, k q.popleft() h__.heappush(pq, (-counter[k], k __ pq: _, k h__.heappop(pq) counter[k] -_ 1 __ counter[k] > 0 q.a..((clock + 1 + n, k clock += 1 r.. clock __ _______ __ _______ ... Solution().leastInterval(["A","A","A","B","B","B"], 0) __ 6 ... Solution().leastInterval(["A","A","A","B","B","B"], 2) __ 8
40eb42e068769236a6f86af3da263cae1f533a6c
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/topics/OOP/313/constructors.py
1,016
3.703125
4
import re class DomainException(Exception): """Raised when an invalid is created.""" class Domain: def __init__(self, name): # validate a current domain (r'.*\.[a-z]{2,3}$' is fine) # if not valid, raise a DomainException self.name = name if not re.match(r'.*\.[a-z]{2,3}$', self.name): raise DomainException # next add a __str__ method and write 2 class methods # called parse_from_url and parse_from_email to construct domains # from an URL and email respectively @classmethod def parse_url(cls, url): url_domain = re.findall(r"(?:^https?:\/\/([^\/]+)(?:[\/,]|$)|^(.*)$)", url) return Domain(url_domain[0][0]) @classmethod def parse_email(cls, email): email_domain = re.findall(r'@(.*\.[a-z]+)', email) return Domain(email_domain[0]) def __str__(self) -> str: return f'{self.name}' print(Domain.parse_url('http://www.khooville.com')) #print(Domain.parse_email('sckhoo@khooville.com'))
f9e455c84aafd33dd75558bfbb089e9b43f1fd4c
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/553_bomb_enemy.py
2,959
3.546875
4
""" Cache sharing nodes Main Concept: 1. the number of enemies killed is same between the two walls in line y 0 1 2 3 4 x 0 W 1 k 0 k W l 2 n 3 W 4 m the number of enemies killed is `n + k` at (1, 1) 2. since the iteration order, we can optimize the space complexity in row x y 0 1 2 3 0 [[ | 0, | E, | 0, | 0 ], --1--> 1 [ | E, | 0, v W, | E ], --2--> 2 [ v 0, v E, v 0, v 0 ]] --3--> """ c_ Solution: WALL 'W' ENEMY 'E' EMPTY '0' ___ maxKilledEnemies grid """ :type grid: list[list[str]] :rtype: int """ ans 0 __ n.. grid o. n.. grid[0]: r.. ans m, n l..(grid), l..(grid 0 row, cols 0, [0] * n ___ x __ r..(m ___ y __ r..(n # calculate bomb in cur section [x, 'WALL' | m) in col __ x __ 0 o. grid[x - 1][y] __ WALL: cols[y] 0 ___ i __ r..(x, m __ grid[i][y] __ WALL: _____ __ grid[i][y] __ ENEMY: cols[y] += 1 # calculate bomb in cur section [y, 'WALL' | n) in row __ y __ 0 o. grid[x][y - 1] __ WALL: row 0 ___ i __ r..(y, n __ grid[x][i] __ WALL: _____ __ grid[x][i] __ ENEMY: row += 1 __ grid[x][y] __ EMPTY a.. row + cols[y] > ans: ans row + cols[y] r.. ans """ TLE time: O(m^2 * n^2) """ c_ Solution: WALL 'W' ENEMY 'E' EMPTY '0' ___ maxKilledEnemies grid """ :type grid: list[list[str]] :rtype: int """ ans 0 __ n.. grid o. n.. grid[0]: r.. ans ___ x __ r..(l..(grid: ___ y __ r..(l..(grid[0]: __ grid[x][y] __ EMPTY: ans m..( ans, get_killed_cnt(grid, x, y) ) r.. ans ___ get_killed_cnt grid, i, j m, n l..(grid), l..(grid 0 cnt 0 # up ___ x __ r..(i, -1, -1 __ grid[x][j] __ WALL: _____ __ grid[x][j] __ ENEMY: cnt += 1 # down ___ x __ r..(i, m __ grid[x][j] __ WALL: _____ __ grid[x][j] __ ENEMY: cnt += 1 # left ___ y __ r..(j, -1, -1 __ grid[i][y] __ WALL: _____ __ grid[i][y] __ ENEMY: cnt += 1 # right ___ y __ r..(j, n __ grid[i][y] __ WALL: _____ __ grid[i][y] __ ENEMY: cnt += 1 r.. cnt
9927cba2ecbde550aadadc9ca4f15a1b6faa5276
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/286_newbie_bite/save1_passed.py
251
3.84375
4
# Enter your code within the following function def get_username(): while True: username = input("Please type in the name 'PyBites':") if username == "PyBites": break else: print("Invalid username.")
9b0c5d18598425fafb0e07bc6bce6707020665ca
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/LinkedList/02.AddTwoNumbers.py
1,152
3.71875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for singly-linked list. c.. ListNode o.. ___ __init__ x self.val = x self.next = None c.. Solution o.. ___ addTwoNumbers l1, l2 """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry_in = 0 head = ListNode(0) l_sum = head _____ l1 a.. l2: l_sum.next = ListNode((l1.val + l2.val + carry_in) % 10) carry_in = (l1.val + l2.val + carry_in) / 10 l1 = l1.next l2 = l2.next l_sum = l_sum.next __ l1: _____ l1: l_sum.next = ListNode((l1.val + carry_in) % 10) carry_in = (l1.val + carry_in) / 10 l1 = l1.next l_sum = l_sum.next __ l2: _____ l2: l_sum.next = ListNode((l2.val + carry_in) % 10) carry_in = (l2.val + carry_in) / 10 l2 = l2.next l_sum = l_sum.next __ carry_in != 0: l_sum.next = ListNode(carry_in) r_ head.next
007503cf68313ea40c7b4ba5c843ed9c8e0fb404
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/leetcode/382_linked_list_random_node.py
791
3.65625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None ____ r__ _______ r.. c_ Solution: ___ - , head """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode """ head head ___ getRandom """ Returns a random node's value. :rtype: int """ res node head i 0 w.... node: __ r..(0, i) __ i: res node node node.next i += 1 r.. res.val # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom()
0aa08a662cb93ae1b78a565535806c5f649c40c2
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/triangle_types_solution.py
645
4.125
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # Write a Python program to check a triangle is equilateral, isosceles or scalene. # Note : # An equilateral triangle is a triangle in which all three sides are equal. # A scalene triangle is a triangle that has three unequal sides. # An isosceles triangle is a triangle with (at least) two equal sides. print("Input lengths of the triangle sides: ") x = int(input("x: ")) y = int(input("y: ")) z = int(input("z: ")) if x == y == z: print("Equilateral triangle") elif x != y != z: print("Scalene triangle") else: print("isosceles triangle")
0533fe5dc87e34a79264ebf2b8ea6853312df088
syurskyi/Python_Topics
/018_dictionaries/_templates/dictionary_009.py
3,751
3.59375
4
# # -*- coding: utf-8 -*- # # # Keyword Arguments # d _ di__ a_100 b_200 # d # d _ di__ | 'a' 100 'b' 200 | # d # d _ di__ | 'a' 100 |'b', 200| # d # d _ |'a' 100 'b' 200 'c' |'d' 1, 'e' 2}} # d # # # We can also create dictionaries using a dictionary comprehension. # keys _ |'a' 'b' 'c'| # values _ 1 2 3 # # # We can then easily create a dictionary this way - the non-Pythonic way! # # d _ || # creates an empty dictionary # ___ k, v i_ zi. ? '? # ? ? _ ? # d # # # But it is much simpler to use a dictionary comprehension: # # d _ |k v ___ ? ? __ z.. ? ? | # # # list comprehensions - you can have nested loops, i_ statements, etc. # keys _ |'a' 'b' 'c' 'd'| # values _ 1 2 3 4 # # d _ |k v ___ ? ? __ z.. ? ? __ ? % 2 __ 0| # d # # # create a grid of 2D coordinate pairs, and calculate their distance from the origin: # x_coords _ -2, -1, 0, 1, 2 # y_coords _ -2, -1, 0, 1, 2 # grid _ | x, y # ___ ? __ ? # ___ ? __ ?| # grid # ______ math # grid_extended _ | x, y, ma__.hy___ ? ? ___ ? ? __ g..| # grid_extended # # # We can now easily tweak this to make a dictionary, where the coordinate pairs are the key, and the distance the value: # # grid_extended _ | x, y ma__.hy__ ? ? ___ ? ? __ ?| # # grid_extended # # # Using fromkeys # counters _ di__.f___ |'a', 'b', 'c'|, 0 # counters # # # i_ we do not specify a value, then None is used: # d _ di__.f.. 'abc' # d # # # Dictionaries support the len function - this simply returns the number of key/value pairs i_ the dictionary: # d _ di__ z.. 'abc' ra... 1, 4 # d # le. d # # # Here we have a string where we want to count the number of each character that appears i_ the string. # # Since we know the alphabet is a-z, we could create a dictionary with these initial keys - # # but maybe the string contains characters outside of that, maybe punctuation marks, emojis, etc. So it's not really # # feasible to take that approach. # # text _ 'Put here some long text' # counts _ di__ # ___ c __ ? # co...|?| _ co___.ge. c, 0 + 1 # print counts # # # We can refine this a bit - first we'll ignore spaces, then we'll want to consider lowercase and uppercase # # characters as the same: # # counts _ di__ # ___ c __ text # key _ ?.lo.. .str.. # __ ? # co...|?| _ co___.ge. k.. 0 + 1 # print counts # # # Membership Tests # d _ di__ a_1, b_2, c_3 # 'a' i_ d # 'z' i_ d # 'z' no. i_ d # # # Removing elements from a dictionary # # del # d _ di__.fr... 'abcd', 0 # d # de. d|'a'| # d # # # Removing elements from a dictionary # # pop # d _ di__.fr... 'abcd', 0 # d # result _ d.po. 'b' # result # d # # result _ d.po. 'z' # Error # # result _ d.po. 'z', 'Not found!' # result # # # Removing elements from a dictionary # # popitem # # simply removes an element from the dictionary unless the dictionary is empty, i_ which case it will result i_ # # a KeyError. The method returns a tuple containing the key and the value that was just removed. # # # d _ |'a' 10, 'b' 20, 'c' 30| # d.p_i_ # d.p_i_ # d.p_i_ # # # Inserting keys with a default # # Sometimes we may want to insert an element i_ a dictionary with a default value, but only i_ the element is not # # already present: # d _ |'a' 1 'b' 2, 'c' 3| # i_ 'z' no. i_ d # d|'z'| _ 0 # d # # # Function # # ___ insert_if_not_present d, key, value : # __ k.. no. __ d # ?|k..| _ v.. # r_ v... # ____ # r_ ? k..| # # print d # # result _ ? d, 'a', 0 # print r.... d # # print d # # result _ insert_if_not_present d, 'y', 10 # print r...., d # # # setdefault # d _ |'a' 1 'b' 2 'c' 3| # result _ d.s_d_ 'a', 0 # print r... # print d # # result _ d.s_d_ 'z', 100 # print r... # print d # # # Clearing All Items # d _ |'a' 1 'b' 2 'c' 3| # d # d.c___ # d # #
aa70609eea170cb390ca53f697c3ff76f170d6c5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/104_Maximum_Depth_of_Binary_Tree.py
407
3.625
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None c_ Solution: ___ maxDepth root """ :type root: TreeNode :rtype: int """ __ root is N..: r_ 0 ld = maxDepth(root.left) rd = maxDepth(root.right) r_ 1 + m..(ld, rd)