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 |
|---|---|---|---|---|---|---|
27a2ee626b34d1662a5d899ddbb760d69379a25f | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/LinkedList/328_OddEvenLinkedList.py | 815 | 3.9375 | 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 oddEvenList(self, head):
if not head or not head.next:
return head
odd = ListNode(0)
even = ListNode(0)
pre_head = odd
pre_mid = even
odd_even_dict = {0: even, 1: odd}
count = 0
while head:
count += 1
odd_even_dict[count & 1].next = head
odd_even_dict[count & 1] = head
head = head.next
odd_even_dict[0].next = None
odd_even_dict[1].next = pre_mid.next
return pre_head.next
"""
[]
[1]
[1,2]
[1,2,3]
[1,2,3,4,5,6,7,8]
"""
|
42cb8106d5e3ebea7ac9d1a87cdf1de4a0e93ebd | syurskyi/Python_Topics | /085_regular_expressions/_exercises/templates/Python 3 Most Nessesary/7.5. Snap to start and end of line.py | 9,734 | 3.625 | 4 | # # -*- coding: utf-8 -*-
#
# # Кроме того, можно указать привязку только к началу или только к концу строки
# _______ __ # Подключаем модуль
# p _ __.c.. _ 0-9 1? 2? __.3?) # 1.One or more occurrences | 2.Ends with
# # 3.Makes a period (dot) match any character, including a newline.
# __ ?.s..("Строка245"):
# print("Есть число в конце строки")
# ____
# print("Нет числа в конце строки")
# # Выведет: Есть число в конце строки
# p _ __.c.. _ 1? 0-9 2? __.3? # 1.Starts with | 2.One or more occurrences
# # 3.Makes a period (dot) match any character, including a newline.
# __ ?.s..("Строка245"):
# print("Есть число в начале строки")
# ____
# print("Нет числа в начале строки")
# # Выведет: Нет числа в начале строки
# input()
#
# # Поддерживаются также два метасимвола, позволяющие указать привязку к началу или концу слова:
# # t \Ь - привязка к началу слова (началом слова считается пробел или любой символ, не
# # являющийся буквой, цифрой или знаком подчеркивания);
# # t \В- привязка к позиции, не являющейся началом слова.
#
#
# p _ __.c.. _ 1? python 1?") # 1.привязка к началу слова
# print("Найдено" __ ?.s..("python") ____ "Нет")
# # Найдено
# print("Найдено" __ ?.s..("pythonware") ____ "Нет")
# # Нет
# p _ __.c.. _ 1? th 1?") # 1.привязка к позиции, не являющейся началом слова.
# print("Найдено" __ ?.s..("python") ____ "Нет")
# # Найдено
# print("Найдено" __ ?.s..("this") ____ "Нет")
# # Нет
#
# # В квадратных скобках [] можно указать символы, которые могут встречаться на этом месте
# # в строке. Можно перечислить символы подряд или указать диапазон через дефис:
# # t [09) - соответствует числу О или 9;
# # t [О-9] - соответствует любому числу от О до 9;
# # t r абв: - соответствует буквам «а». «б» и «в»;
# # t (а-гJ - соответствует буквам «а». «б». «в» и «г»;
# # t [а-яёj - соответствует любой букве от «а» до «я»;
# # t [АБВ] - соответствует буквам «А». «Б» и «В»;
# # t [Ji.-ЯЁJ - соответствует любой букве от «А» до <<Я»;
# # t [а-яА-ЯёЁj - соответствует любой русской букве в любом регистре;
# # t [ О-9а-. .:..::.-яеtа-=.::.-::::: - любая цифра и любая буква независимо от регистра и языка.
# # ВНИМАНИЕ/
# # Буква «ё» не входит в диапазон [а-я:J, а буква «Е» - в диапазон [А-Я].
# # Значение в скобках инвертируется. ес.1и после первой скобки вставить символ ,, . Таким образом можно указать сн,1во.1ы. которых не должно быть на этом месте в строке:
# # t [ · :?: - не uифра О и.1и 9:
# # • [ · c,-sJ - не цифра от О .10 9:
# # t [ · а-�-=-.-.s:ё::::�-=..:..-:: - не буква.
#
# # Как вы уже знаете, точка теряет свое спеuиальное значение. если ее заключить в квадратные скобки. Кроме того, внутри квадратных скобок могут встретиться символы, которые
# # имеют специальное значение (например, ·, и -). Символ · теряет свое спешшльное значение,
# # если он не расположен сразу после открывающей квадратной скобки. Чтобы отменить специальное значение символа -, его необходимо указать после перечисления всех символов,
# # перед закрывающей квадратной скобкой или сразу после открывающей квадратной скобки.
# # Все специальные символы можно сделать обычными, если перед ними указать символ\.
# # Метасимвол I позволяет сделать выбор между альтернативными значениями. Выражение
# # n lm соответствует одному из символов: n или m.
#
#
# p _ __.c.. _ красн( ая 1? ое )") # 1.позволяет сделать выбор между альтернативными значениями.
# print("Найдено" __ ?.s..("красная") ____ "Нет")
# # Найдено
# print("Найдено" __ ?.s..("красное") ____ "Нет")
# # Найдено
# print("Найдено" __ ?.s..("красный") ____ "Нет")
# # Нет
# Вместо перечисления символов можно использовать стандартные классы:
# # • \d- соответствует любой цифре. При указании флага А (AScrr) эквивалентно [О-9];
# # t \w - соответствует любой букве, uифре или символу подчеркивания. При указании флага A(ASCII) эквивалентно
# # [a-zA-Z0-9_];
# # • \s - тобой пробельный символ. При указании флага А (AScrr) эквивалентно
# # [\t\n\r\f\v];
# # t \D- не цифра. При указании флага А (AScrr) эквивалентно [ ЛО-9];
# # • \W - не буква, не цифра и не символ подчеркивания. При указании флага А (ASCII) эквивалентно [
# # л a-zA-Z0-9_];
# # • \S - не пробельный символ. При указании флага А (AScrr) эквивалентно ["\t\n\r\f\v).
# # ПРИМЕЧАНИЕ
# # В Python 3 поддержка Unicode в регулярных выражениях установлена по умолчанию. При
# # этом все классы трактуются гораздо шире. Так, класс \d соответствует не только десятичным цифрам, но и другим цифрам
# # из кодировки Unicode, - например, дробям, класс \w
# # включает не только латинские буквы, но и любые другие, а класс \s охватывает также неразрывные пробелы.
# # Поэтому на практике лучше явно указывать символы внутри квадратных скобок, а не использовать классы.
# # Количество вхождений символа в строку задается с помощью квантификаторов:
# # t { n} - n вхождений символа в строку. Например, шаблон r""' [ 0-9 J { 2 } $" соответствует
# # двум вхождениям любой цифры;
# # t {n,} - n или более вхождений символа в строку. Например, шаблон r"" [О-9) {2, }$"
# # соответствует двум и более вхождениям любой цифры;
# # t {n,m} - не менее n и не более m вхождений символа в строку. Числа указываются через
# # запятую без пробела. Например, шаблон r""' [О-9] {2, 4 }$" соответствует от двух до
# # четырех вхождений любой цифры;
# # t * - ноль или большее число вхождений символа в строку. Эквивалентно комбинации
# # {о' } ;
#
# # + - одно или большее число вхождений символа в строку. Эквивалентно комбинации
# # { 1, } ;
# # • ? - ни одного или одно вхождение символа в строку. Эквивалентно комбинации {о, 1}.
# # Все квантификаторы являются «жадными». При поиске соответствия ищется самая длинная
# # подстрокa соответствующая шаблону, и не учитываются более короткие соответствия. Рассмотрим это на примере и получим
# # содержимое всех тегов <Ь>, вместе с тегами:
#
# s _ "<b>Text1</b>Text2<b>Text3</b>"
# p _ __.c.. _ <b>. 1? </b> __.2? # 1.Zero or more occurrences | 2.Makes a period (dot) match any character, including a newline.
# ?.f.. ?
# # ['<b>Text1</b>Text2<b>Text3</b>']
|
e6729c7cfc3abb4f301d1f09795e975fe7505604 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/DataAnalysis/90/test.py | 207 | 3.53125 | 4 | from collections import defaultdict
from typing import Counter
count = defaultdict(Counter)
count['khoo']['a'] = 1
count['khoo']['b'] = 2
#count['chuan'] += 1
#print(count['chuan'])
print(count['swee']) |
e238bcd4bc432abb27b310e700b6a1bb2c43567a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/773 Sliding Puzzle.py | 3,369 | 4.0625 | 4 | #!/usr/bin/python3
"""
On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and
an empty square represented by 0.
A move consists of choosing 0 and a 4-directionally adjacent number and swapping
it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given a puzzle board, return the least number of moves required so that the
state of the board is solved. If it is impossible for the state of the board to
be solved, return -1.
Examples:
Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Input: board = [[4,1,2],[5,0,3]]
Output: 5
Explanation: 5 is the smallest number of moves that solves the board.
An example path:
After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
Input: board = [[3,2,4],[1,5,0]]
Output: 14
Note:
board will be a 2 x 3 array as described above.
board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5].
"""
____ t___ _______ L..
____ c.. _______ d..
____ c.. _______ d..
_______ h__
final_pos {
1: (0, 0),
2: (0, 1),
3: (0, 2),
4: (1, 0),
5: (1, 1),
0: (1, 2),
}
dirs (
(0, -1),
(0, 1),
(-1, 0),
(1, 0),
)
c_ Solution:
___ slidingPuzzle board: L..[L..[i..]]) __ i..
"""
BFS + visited
=> A*
priority = current_dist + heuristic_dist
Chain the matrix into 1d array. N = R * C
Complexity O(N * N!)
There are O(N!) possible board states. O(N) is the time to scan the board for the operations in the loop.
Possible to reduce the 2D array in a 1D array and do %C and //C, where C is the size of the column
"""
visited d..(b..)
m, n l..(board), l..(board 0
q [(heuristic_dist(board) + 0, 0, board)]
target [
[1, 2, 3],
[4, 5, 0],
]
w.... q:
heu, cur_dist, board h__.heappop(q)
visited[ser(board)] T..
__ board __ target:
r.. cur_dist
cur_dist += 1
i, j zero_pos(board)
___ di, dj __ dirs:
I i + di
J j + dj
__ 0 <_ I < m a.. 0 <_ J < n:
B d..(board) # need a copy in the queue
B[I][J], B[i][j] B[i][j], B[I][J]
__ n.. visited[ser(B)]:
h__.heappush(q, (heuristic_dist(B) + cur_dist, cur_dist, B
r.. -1
___ zero_pos board
___ i, row __ e..(board
___ j, v __ e..(row
__ v __ 0:
r.. i, j
r..
___ heuristic_dist board
"""
manhattan distance
"""
ret 0
___ i, row __ e..(board
___ j, v __ e..(row
__ v !_ 0:
I, J final_pos[v]
ret += a..(i - I) + a..(j - J)
r.. ret
___ ser board
r.. t..(
t..(row)
___ row __ board
)
__ _______ __ _______
... Solution().slidingPuzzle([[1,2,3],[4,0,5]]) __ 1
... Solution().slidingPuzzle([[1,2,3],[5,4,0]]) __ -1
|
58cf2e0e3efb0f44bce7b4ef7c203fc27a443842 | syurskyi/Python_Topics | /095_os_and_sys/examples/realpython/005_Listing All Files in a Directory.py | 2,565 | 4.375 | 4 | # This section will show you how to print out the names of files in a directory using os.listdir(), os.scandir(),
# and pathlib.Path(). To filter out directories and only list files from a directory listing produced by os.listdir(),
# use os.path:
#
import os
# List all files in a directory using os.listdir
basepath = 'my_directory/'
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
print(entry)
print()
print()
#
# Here, the call to os.listdir() returns a list of everything in the specified path, and then that list is filtered
# by os.path.isfile() to only print out files and not directories. This produces the following output:
#
# file1.py
# file3.txt
# file2.csv
#
# An easier way to list files in a directory is to use os.scandir() or pathlib.Path():
#
import os
# List all files in a directory using scandir()
basepath = 'my_directory/'
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_file():
print(entry.name)
print()
print()
# Using os.scandir() has the advantage of looking cleaner and being easier to understand than using os.listdir(),
# even though it is one line of code longer. Calling entry.is_file() on each item in the ScandirIterator returns
# True if the object is a file. Printing out the names of all files in the directory gives you the following output:
#
# file1.py
# file3.txt
# file2.csv
#
# Here’s how to list files in a directory using pathlib.Path():
from pathlib import Path
basepath = Path('my_directory/')
files_in_basepath = basepath.iterdir()
for item in files_in_basepath:
if item.is_file():
print(item.name)
print()
print()
# Here, you call .is_file() on each entry yielded by .iterdir(). The output produced is the same:
#
# file1.py
# file3.txt
# file2.csv
#
# The code above can be made more concise if you combine the for loop and the if statement into
# a single generator expression. Dan Bader has an excellent article on generator expressions and list comprehensions.
#
# The modified version looks like this:
from pathlib import Path
# List all files in directory using pathlib
basepath = Path('my_directory/')
files_in_basepath = (entry for entry in basepath.iterdir() if entry.is_file())
for item in files_in_basepath:
print(item.name)
# This produces exactly the same output as the example before it. This section showed that filtering files
# or directories using os.scandir() and pathlib.Path() feels more intuitive and looks cleaner than using os.listdir()
# in conjunction with os.path. |
29313678d25756a660eef4638259ee18459be08c | syurskyi/Python_Topics | /125_algorithms/_examples/Practice_Python_by_Solving_100_Python_Problems/77.py | 219 | 4.125 | 4 | #Create a script that gets user's age and returns year of birth
from datetime import datetime
age = int(input("What's your age? "))
year_birth = datetime.now().year - age
print("You were born back in %s" % year_birth)
|
f2e58ef8c9a85492f27cb03127880a01715eff43 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id026-GCD_and_LCM.py | 438 | 3.515625 | 4 | ___ lcm(a,b # Least Common Multiple
r..(a * b / gcd(a, b
___ gcd(a,b # Greatest Common Divisor
w.... b:
a, b b, a % b
r.. a
___ findDivisors(pairs
answer # list
___ pair __ r..(pairs
a,b raw_input().s..
a,b i..(a), i..(b)
answer.a..('('+s..(gcd(a,b+' '+s..(lcm(a,b+')')
print(' '.j..(answer
findDivisors(input
|
27ad68ad48e6428b183b837ea941b7673cc19675 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/117 Populating Next Right Pointers in Each Node II.py | 1,210 | 3.703125 | 4 | """
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
"""
__author__ 'Danyang'
# Definition for a binary tree node
c_ TreeNode:
___ - , x
val x
left N..
right N..
next N..
c_ Solution:
___ connect root
"""
bfs
same as Populating Next Right Pointers in Each Node I
:param root: TreeNode
:return: nothing
"""
__ n.. root:
r.. N..
q [root]
w.... q:
current_level q
q # list
___ ind, val __ e..(current_level
__ val.left: q.a..(val.left)
__ val.right: q.a..(val.right)
___
val.next current_level[ind+1]
______ I..
val.next N..
|
cb8edc742b8442363378710ba0e91d7480ce6ca1 | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Auto_Spec.py | 1,771 | 3.53125 | 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.
#
#
# For ensuring that the mock objects in your tests have the same api as the objects they are replacing, you can use auto-speccing. Auto-speccing can be done
# through the autospec argument to patch, or the create_autospec() function. Auto-speccing creates mock objects that have the same attributes and methods as
# the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object.
#
# This ensures that your mocks will fail in the same way as your production code if they are used incorrectly:
#
____ u__.m.. ______ create_autospec
___ function(a, b, c
p..
mock_function _ create_autospec(function, return_value_'fishy')
mock_function(1, 2, 3)
# OUTPUT: 'fishy'
mock_function.a_c_o_w..(1, 2, 3)
mock_function('wrong arguments')
|
08eff574578ac91abce96916bc188833ac922619 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-3-word-values.py | 2,365 | 4.3125 | 4 | """
Calculate the dictionary word that would have the most value in Scrabble.
There are 3 tasks to complete for this Bite:
First write a function to read in the dictionary.txt file (= DICTIONARY constant),
returning a list of words (note that the words are separated by new lines).
Second write a function that receives a word and calculates its value.
Use the scores stored in LETTER_SCORES.
Letters that are not in LETTER_SCORES should be omitted (= get a 0 score).
With these two pieces in place, write a third function that takes a list
of words and returns the word with the highest value.
Look at the TESTS tab to see what your code needs to pass. Enjoy!
"""
import os
import u__.r..
# PREWORK
TMP = os.getenv("TMP", "/tmp")
print(TMP)
S3 = 'https://bites-data.s3.us-east-2.amazonaws.com/'
DICT = 'dictionary.txt'
DICTIONARY = os.path.join(TMP, DICT)
print(DICTIONARY)
u__.r...u..(f'{S3}{DICT}', DICTIONARY)
scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
LETTER_SCORES = {letter: score for score, letters in scrabble_scores
for letter in letters.split()}
# start coding
def load_words_v1():
"""Load the words dictionary (DICTIONARY constant) into a list and return it"""
l = []
with open(DICTIONARY) as file:
for line in file:
l.append(line.strip())
return l
def load_words_v2():
with open(DICTIONARY) as file:
return [word.strip() for word in file.read().split()]
def calc_word_value_v1(word):
"""Given a word calculate its value using the LETTER_SCORES dict"""
value = 0
for char in word.upper():
try:
value += LETTER_SCORES[char]
except:
value = 0
return value
def calc_word_value_v2(word):
return sum(LETTER_SCORES.get(char.upper(), 0) for char in word)
def max_word_value(words):
"""Given a list of words calculate the word with the maximum value and return it"""
max = ()
for word in words:
value = calc_word_value(word)
if max == ():
max = (word, value)
else:
if value > max[1]:
max = (word, value)
return max[0]
def max_word_value_v2(words):
return max(words, key=calc_word_value)
print(max_word_value(['zime', 'fgrtgtrtvv'])) |
b7a799605e9f50f6ab9f363daaf7a18ecae80960 | syurskyi/Python_Topics | /060_context_managers/examples/102. Additional Uses - Coding.py | 10,230 | 4.4375 | 4 | print('#' * 52 + ' ### Additional Uses')
# Additional Uses
# Remember what I said in the last lecture about some common patterns we can implement with context managers:
# Open - Close
# Change - Reset
# Start - Stop
# The open file context manager is an example of the Open - Close pattern. But we have other ones as well.
# Decimal Contexts
# Decimals have a context which can be used to define many things, such as precision, rounding mechanism, etc.
# By default, Decimals have a "global" context - i.e. one that will apply to any Decimal object by default:
import decimal
print(decimal.getcontext())
# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[],
# traps=[InvalidOperation, DivisionByZero, Overflow])
# ######################################################################################################################
# If we create a decimal object, then it will use those settings.
# We can certainly change the properties of that global context:
print('#' * 52 + ' If we create a decimal object, then it will use those settings.')
print('#' * 52 + ' We can certainly change the properties of that global context:')
decimal.getcontext().prec=14
print(decimal.getcontext())
# Context(prec=14, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[],
# traps=[InvalidOperation, DivisionByZero, Overflow])
# ######################################################################################################################
# And now the default (global) context has a precision set to 14.
# Let's reset it back to 28:
print('#' * 52 + ' And now the default (global) context has a precision set to 14.')
print('#' * 52 + ' Lets reset it back to 28:')
decimal.getcontext().prec = 28
# Suppose now that we just want to temporarily change something in the context - we would have to do something like
# this:
old_prec = decimal.getcontext().prec
decimal.getcontext().prec = 4
print(decimal.Decimal(1) / decimal.Decimal(3))
decimal.getcontext().prec = old_prec
print(decimal.Decimal(1) / decimal.Decimal(3))
# 0.3333
# 0.3333333333333333333333333333
# ######################################################################################################################
# Of course, this is kind of a pain to have to store the current value, set it to something new, and then remember
# to set it back to it's original value.
# How about writing a context manager to do that seamlessly for us:
print('#' * 52 + ' Of course, this is kind of a pain to have to store the current value, set it to something new,'
' and then remember to set it back to its original value.')
print('#' * 52 + ' How about writing a context manager to do that seamlessly for us:')
class precision:
def __init__(self, prec):
self.prec = prec
self.current_prec = decimal.getcontext().prec
def __enter__(self):
decimal.getcontext().prec = self.prec
def __exit__(self, exc_type, exc_value, exc_traceback):
decimal.getcontext().prec = self.current_prec
return False
with precision(3):
print(decimal.Decimal(1) / decimal.Decimal(3))
print(decimal.Decimal(1) / decimal.Decimal(3))
# 0.333
# 0.3333333333333333333333333333
# ######################################################################################################################
# And as you can see, the precision was set back to it's original value once the context was exited.
# In fact, the decimal class already has a context manager, and it's way better than ours, because we can set not only
# the precision, but anything else we want:
print('#' * 52 + ' And as you can see, the precision was set back to its original value once the context was exited.')
print('#' * 52 + ' In fact, the decimal class already has a context manager, and its way better than ours,'
' because we can set not only the precision, but anything else we want:')
with decimal.localcontext() as ctx:
ctx.prec = 3
print(decimal.Decimal(1) / decimal.Decimal(3))
print(decimal.Decimal(1) / decimal.Decimal(3))
# 0.333
# 0.3333333333333333333333333333
# ######################################################################################################################
# Timing a with block
#
# Here's another example of a Start - Stop type of context manager. We'll create a context manager to time the code
# inside the with block:
print('#' * 52 + ' #### Timing a with block')
print('#' * 52 + ' Here is another example of a **Start - Stop** type of context manager.')
print('#' * 52 + ' We will create a context manager to time the code inside the `with` block:')
from time import perf_counter, sleep
class Timer:
def __init__(self):
self.elapsed = 0
def __enter__(self):
self.start = perf_counter()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.stop = perf_counter()
self.elapsed = self.stop - self.start
return False
# You'll note that this time we are returning the context manager itself from the __enter__ statement.
# This will allow us to look at the elapsed property of the context manager once the with statement
# has finished running.
with Timer() as timer:
sleep(1)
print(timer.elapsed)
# 0.9993739623039163
# ######################################################################################################################
# Redirecting stdout
# Here we are going to temporarily redirect stdout to a file instead fo the console:
print('#' * 52 + ' #### Redirecting stdout')
print('#' * 52 + ' Here we are going to temporarily redirect `stdout` to a file instead fo the console:')
import sys
class OutToFile:
def __init__(self, fname):
self._fname = fname
self._current_stdout = sys.stdout
def __enter__(self):
self._file = open(self._fname, 'w')
sys.stdout = self._file
def __exit__(self, exc_type, exc_value, exc_tb):
sys.stdout = self._current_stdout
if self._file:
self._file.close()
return False
with OutToFile('test.txt'):
print('Line 1')
print('Line 2')
# As you can see, no output happened on the console... Instead the output went to the file we specified.
# And our print statements will now output to the console again:
print('back to console output')
# back to console output
with open('test.txt') as f:
print(f.r..())
# HTML Tags
# In this example, we're going to basically use a context manager to inject opening and closing html tags as
# we print to the console (of course we could redirect our prints somewhere else as we just saw!):
print('#' * 52 + ' #### HTML Tags')
class Tag:
def __init__(self, tag):
self._tag = tag
def __enter__(self):
print(f'<{self._tag}>', end='')
def __exit__(self, exc_type, exc_value, exc_tb):
print(f'</{self._tag}>', end='')
return False
with Tag('p'):
print('some ', end='')
with Tag('b'):
print('bold', end='')
print(' text', end='')
# <p>some <b>bold</b> text</p>
# ######################################################################################################################
# Re-entrant Context Managers
# We can also write context managers that can be re-entered in the sense that we can call __enter__ and __exit__
# more than once on the same context manager.
# These methods are called when a with statement is used, so we'll need to be able to get our hands on the context
# manager object itself - but that's easy, we just return self from the __enter__ method.
# Let's write a ListMaker context manager to do see how this works.
print('#' * 52 + ' #### Re-entrant Context Managers')
print('#' * 52 + ' Let is write a ListMaker context manager to do see how this works.')
class ListMaker:
def __init__(self, title, prefix='- ', indent=3):
self._title = title
self._prefix = prefix
self._indent = indent
self._current_indent = 0
print(title)
def __enter__(self):
self._current_indent += self._indent
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self._current_indent -= self._indent
return False
def print(self, arg):
s = ' ' * self._current_indent + self._prefix + str(arg)
print(s)
# Because __enter__ is returning self, the instance of the context manager, we can call with on that context manager
# and it will automatically call the __enter__ and __exit__ methods. Each time we run __enter__ we increase
# the indentation, each time we run __exit__ we decrease the indentation.
# Our print method then takes that into account when it prints the requested string argument.
print('#' * 52 + ' Our `print` method then takes that into account when it prints the requested string argument.')
with ListMaker('Items') as lm:
lm.print('Item 1')
with lm:
lm.print('item 1a')
lm.print('item 1b')
lm.print('Item 2')
with lm:
lm.print('item 2a')
lm.print('item 2b')
# Items
# - Item 1
# - item 1a
# - item 1b
# - Item 2
# - item 2a
# - item 2b
# ######################################################################################################################
# Of course, we can easily redirect the output to a file instead, using the context manager we wrote earlier:
print('#' * 52 + ' Of course, we can easily redirect the output to a file instead,'
' using the context manager we wrote earlier:')
with OutToFile('my_list.txt'):
with ListMaker('Items') as lm:
lm.print('Item 1')
with lm:
lm.print('item 1a')
lm.print('item 1b')
lm.print('Item 2')
with lm:
lm.print('item 2a')
lm.print('item 2b')
with open('my_list.txt') as f:
for row in f:
print(row, end='')
# Items
# - Item 1
# - item 1a
# - item 1b
# - Item 2
# - item 2a
# - item 2b
# ######################################################################################################################
|
4ee061f9b2d7ba13ef1d49aa115f9a2e632a2a65 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/1018 Binary Prefix Divisible By 5.py | 1,101 | 4 | 4 | #!/usr/bin/python3
"""
Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i]
interpreted as a binary number (from most-significant-bit to
least-significant-bit.)
Return a list of booleans answer, where answer[i] is true if and only if N_i is
divisible by 5.
Example 1:
Input: [0,1,1]
Output: [true,false,false]
Explanation:
The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer[0] is true.
Example 2:
Input: [1,1,1]
Output: [false,false,false]
Example 3:
Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]
Example 4:
Input: [1,1,1,0,1]
Output: [false,false,false,false,false]
Note:
1 <= A.length <= 30000
A[i] is 0 or 1
"""
____ t___ _______ L..
c_ Solution:
___ prefixesDivBy5 A: L.. i.. __ L..[b..]:
"""
brute force
"""
cur 0
ret # list
___ a __ A:
cur (cur << 1) + a
cur %= 5
__ cur __ 0:
ret.a..(T..)
____
ret.a..(F..)
r.. ret
|
ba236317ae547620e93e529be89885e16c7a39ff | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/Datetimes/73/timezones.py | 734 | 3.671875 | 4 | import pytz
from datetime import datetime
MEETING_HOURS = range(6, 23) # meet from 6 - 22 max
TIMEZONES = set(pytz.all_timezones)
def within_schedule(utc, *timezones):
"""Receive a utc datetime and one or more timezones and check if
they are all within schedule (MEETING_HOURS)"""
utc = pytz.utc.localize(utc)
for timezone in timezones:
if timezone not in TIMEZONES:
raise ValueError
city_local_time = utc.astimezone(pytz.timezone(timezone))
if city_local_time.hour not in MEETING_HOURS:
return False
return True
dt = datetime(2018, 4, 18, 12, 28)
timezones = ['Europe/Madrid', 'Australia/Sydney', 'America/Chicago']
print(within_schedule(dt, *timezones)) |
ac8855cb9b0969981609182736b8de8d4aee60ee | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id018-Square_Root.py | 435 | 3.609375 | 4 | ___ sqRoot(numbers
answer # list
___ number __ r.. ?
data raw_input().s..
value,runs i..(data 0,i..(data[1])
root 1.00
__ root __ 0:
print(1)
____
___ x __ r..(runs
division value / root
a..(root - division)
root (root + division) / 2
answer.a..(s..(root
print(' '.j..(answer
sqRoot(input
|
30ddadd1a69acb89bca5e32d8b221e1a91c09a3a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/504 Base 7.py | 722 | 4.09375 | 4 | #!/usr/bin/python3
"""
Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
"""
c_ Solution:
___ convertToBase7 num
"""
simplfied for negative number
:type num: int
:rtype: str
"""
__ num __ 0:
r.. "0"
ret # list
n a..(num)
w.... n:
ret.a..(n % 7)
n //= 7
ret "".j.. m..(s.., ret||-1]
__ num < 0:
ret "-" + ret
r.. ret
__ _______ __ _______
... Solution().convertToBase7(100) __ "202"
... Solution().convertToBase7(-7) __ "-10"
|
70bdb3d9d47e898a1c9258f312214f2bd9a75f31 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/119_PascalTriangleII.py | 1,006 | 3.828125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
rowIndex += 1
row_nums = [0 for i in range(rowIndex)]
row_nums[0] = 1
# Use the post part of pre row to update the current row.
for i in range(1, rowIndex):
symmetry_count = (i+1)/2 # The symmetry element's numbers
for j in range(symmetry_count):
num = row_nums[i-1-j]
if i > j-1 >= 0:
num += row_nums[i-j]
row_nums[j] = num
# Get the mid num in odd rows
if (i+1) % 2 != 0:
row_nums[symmetry_count] = 2 * row_nums[i/2]
symmetry_count += 1
# Update the post (symmetry) part of current row
for k in range(symmetry_count, i+1):
row_nums[k] = row_nums[i-k]
return row_nums
"""
0
3
8
"""
|
14cbcea8d1beff63273b32a89811b85c8e5e5a3e | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Python_OOP_Object_Oriented_Programming/Section 15/project/deck.py | 1,350 | 3.9375 | 4 | import random
from card import Card
class Deck:
# The four types of suits for the card.
suits = ["Spades", "Clubs", "Diamonds", "Hearts"]
def __init__(self):
# The deck starts with an empty list of cards.
# It is protected and it doesn't have a getter
# setter because they are not needed.
self._cards = []
# Then this is populated when we build the deck.
self.build()
def build(self):
# For every suit and value, create the corresponding cards
# with a value from 1 to 11 (the end value is not included in range()).
for suit in Deck.suits:
for value in range(1, 12):
self._cards.append(Card(suit, value))
def show(self):
# For every card in the list of cards of the deck,
# show the information of the card.
for card in self._cards:
card.show()
def shuffle(self):
# Use the Fisher-Yates algorithm to shuffle the deck.
for i in range(len(self._cards)-1, 0, -1):
rand = random.randint(0, i)
self._cards[i], self._cards[rand] = self._cards[rand], self._cards[i]
def draw(self):
# Remove the card from the deck (if the deck is not empty)
# and return the card.
if self._cards:
return self._cards.pop()
|
d2630a69f253c4a3f1ffee2df7647db7e68b46eb | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/164_MaximumGap.py | 945 | 3.5625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
c.. Solution o..
"""
Radix sort, you can see the explanation follow the links.
https://www.cs.usfca.edu/~galles/visualization/RadixSort.html
And here is a java solution in leetcode's discuss:
https://leetcode.com/discuss/53636/radix-sort-solution-in-java-with-explanation
"""
___ maximumGap nums
__ n.. nums:
r_ 0
max_num = m..(nums)
bucket = [[] ___ i __ r..(10)]
exp = 1
_____ max_num / exp > 0:
___ num __ nums:
bucket[(num / exp) % 10].a.. num)
nums # list
___ each __ bucket:
nums.e..(each)
bucket = [[] ___ i __ r..(10)]
exp *= 10
max_gap = 0
___ i __ r..(1, l..(nums)):
max_gap = m..(max_gap, nums[i] - nums[i - 1])
r_ max_gap
"""
[]
[1]
[9,12,4,8,6,16,23]
[2,99999999]
"""
|
f9fb672650bbe3689cdaa4cf085865635f4a54b2 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/480 Sliding Window Median.py | 4,006 | 4.28125 | 4 | #!/usr/bin/python3
"""
Median is the middle value in an ordered integer list. If the size of the list
is even, there is no middle value. So the median is the mean of the two middle
value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Given an array nums, there is a sliding window of size k which is moving from
the very left of the array to the very right. You can only see the k numbers in
the window. Each time the sliding window moves right by one position. Your job
is to output the median array for each window in the original array.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Window position Median
--------------- -----
[1 3 -1] -3 5 3 6 7 1
1 [3 -1 -3] 5 3 6 7 -1
1 3 [-1 -3 5] 3 6 7 -1
1 3 -1 [-3 5 3] 6 7 3
1 3 -1 -3 [5 3 6] 7 5
1 3 -1 -3 5 [3 6 7] 6
Therefore, return the median sliding window as [1,-1,-1,3,5,6].
Note:
You may assume k is always valid, ie: k is always smaller than input array's
size for non-empty array.
"""
____ t___ _______ L..
_______ h__
c_ DualHeap:
___ -
"""
---- number line --->
--- max heap --- | --- min heap ---
"""
max_h # list # List[Tuple[comparator, num]]
min_h # list
max_sz 0
min_sz 0
to_remove s..() # value, error mapping index in nums
___ insert num
__ max_h a.. num > max_h[0][1]:
h__.heappush(min_h, (num, num
min_sz += 1
____
h__.heappush(max_h, (-num, num
max_sz += 1
balance()
___ pop num
to_remove.add(num)
__ max_h a.. num > max_h[0][1]:
min_sz -_ 1
____
max_sz -_ 1
balance()
___ clean_top
w.... max_h a.. max_h[0][1] __ to_remove:
_, num h__.heappop(max_h)
to_remove.remove(num)
w.... min_h a.. min_h[0][1] __ to_remove:
_, num h__.heappop(min_h)
to_remove.remove(num)
___ balance
# keep skew in max sz
w.... max_sz < min_sz :
clean_top()
_, num =h__.heappop(min_h)
h__.heappush(max_h, (-num, num
min_sz -_ 1
max_sz += 1
w.... max_sz > min_sz + 1:
clean_top()
_, num h__.heappop(max_h)
h__.heappush(min_h, (num, num
min_sz += 1
max_sz -_ 1
clean_top()
___ get_median k
clean_top()
__ k % 2 __ 1:
r.. max_h[0][1]
____
r.. 0.5 * (max_h[0][1] + min_h[0][1])
c_ Solution:
___ medianSlidingWindow nums: L..[i..], k: i.. __ L..[f__]:
"""
1. BST, proxied by bisect
dual heap + lazy removal + balance the valid element
--- max heap --- | --- min heap ---
but need to delete the start of the window
Lazy Removal with the help of hash table of idx -> remove?
Hash table mapping idx will fail
Remove by index will introduce bug for test case [1,1,1,1], 2: when poping,
we cannot know which heap to go to by index since decision of which heap to pop
is only about value.
Calculating median also doesn't care about index, it only cares about value
"""
ret # list
dh DualHeap()
___ i __ r..(k
dh.i.. nums[i])
ret.a..(dh.get_median(k
___ i __ r..(k, l..(nums:
dh.i.. nums[i])
dh.p.. nums[i-k])
ret.a..(dh.get_median(k
r.. ret
__ _______ __ _______
... Solution().medianSlidingWindow([-2147483648,-2147483648,2147483647,-2147483648,-2147483648,-2147483648,2147483647,2147483647,2147483647,2147483647,-2147483648,2147483647,-2147483648], 2)
... Solution().medianSlidingWindow([1,1,1,1], 2) __ [1, 1, 1]
... Solution().medianSlidingWindow([1,3,-1,-3,5,3,6,7], 3) __ [1,-1,-1,3,5,6]
|
dccee39c84fc8a8b20b0cb56c22b64111a294a7d | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/intro/intro-bite102-infinite-loop-input-continue-break.py | 1,151 | 4.15625 | 4 | VALID_COLORS = ['blue', 'yellow', 'red']
def my_print_colors():
"""Ask for color, lowercase it, check if 'quit' is entered, if so print
'bye' and break, next check if given color is in VALID_COLORS, if not,
continue, finally if that check passes, print the color"""
while True:
inp = input("Enter color:").lower()
if inp == 'quit':
print("bye")
break
if inp not in VALID_COLORS:
print("Not a valid color")
continue
# this else is useless
else:
print(inp)
# thou shall not stop after a match!!!
break
def print_colors():
"""Ask for color, lowercase it, check if 'quit' is entered, if so print
'bye' and break, next check if given color is in VALID_COLORS, if not,
continue, finally if that check passes, print the color"""
while True:
color = input('Enter a color: ').lower()
if color == 'quit':
print('bye')
break
if color not in VALID_COLORS:
print('Not a valid color')
continue
print(color)
print_colors() |
9294859713e8ecd586fea0bc599290d57c8bcb64 | syurskyi/Python_Topics | /100_databases/003_mongodb/examples/realpython_Introduction to MongoDB and Python/001_Establishing a Connection.py | 4,459 | 4 | 4 | # To establish a connection we’ll use the MongoClient object.
# The first thing that we need to do in order to establish a connection is import the MongoClient class.
# We’ll use this to communicate with the running database instance. Use the following code to do so:
from pymongo import MongoClient
client = MongoClient()
# Using the snippet above, the connection will be established to the default host (localhost) and port (27017).
# You can also specify the host and/or port using:
client = MongoClient('localhost', 27017)
# Or just use the Mongo URI format:
client = MongoClient('mongodb://localhost:27017')
# All of these calls to MongoClient will do the same thing; it just depends on how explicit you want to be in your code.
# Accessing Databases
#
# Once you have a connected instance of MongoClient, you can access any of the databases within that Mongo server.
# To specify which database you actually want to use, you can access it as an attribute:
db = client.pymongo_test
# Or you can also use the dictionary-style access:
db = client['pymongo_test']
# It doesn’t actually matter if your specified database has been created yet. By specifying this database
# name and saving data to it, you create the database automatically.
# Inserting Documents
#
# Storing data in your database is as easy as calling just two lines of code. The first line specifies
# which collection you’ll be using (posts in the example below). In MongoDB terminology, a collection is a group
# of documents that are stored together within the database. Collections and documents are akin to SQL tables and rows,
# respectively. Retrieving a collection is as easy as getting a database.
#
# The second line is where you actually insert the data in to the collection using the insert_one() method:
posts = db.posts
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))
# We can even insert many documents at a time, which is much faster than using insert_one()
# if you have many documents to add to the database. The method to use here is insert_many().
# This method takes an array of document data:
post_1 = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
post_2 = {
'title': 'Virtual Environments',
'content': 'Use virtual environments, you guys',
'author': 'Scott'
}
post_3 = {
'title': 'Learning Python',
'content': 'Learn Python, it is easy',
'author': 'Bill'
}
new_result = posts.insert_many([post_1, post_2, post_3])
print('Multiple posts: {0}'.format(new_result.inserted_ids))
# When ran, you should see something like:
#
# One post: 584d947dea542a13e9ec7ae6
# Multiple posts: [
# ObjectId('584d947dea542a13e9ec7ae7'),
# ObjectId('584d947dea542a13e9ec7ae8'),
# ObjectId('584d947dea542a13e9ec7ae9')
# ]
#
# NOTE: Don’t worry that your ObjectIds don’t match those shown above. They are dynamically generated
# when you insert data and consist of a Unix epoch, machine identifier, and other unique data.
#
# Retrieving Documents
#
# To retrieve a document, we’ll use the find_one() method. The lone argument that we’ll use here
# (although it supports many more) is a dictionary that contains fields to match. In our example below,
# we want to retrieve the post that was written by Bill:
bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)
# Run this:
#
# {
# 'author': 'Bill',
# 'title': 'Learning Python',
# 'content': 'Learn Python, it is easy',
# '_id': ObjectId('584c4afdea542a766d254241')
# }
#
# You may have noticed that the post’s ObjectId is set under the _id key, which we can later use to uniquely identify
# it if needed. If we want to find more than one document, we can use the find() method. This time,
# let’s find all of the posts written by Scott:
scotts_posts = posts.find({'author': 'Scott'})
print(scotts_posts)
# Run:
#
# <pymongo.cursor.Cursor object at 0x109852f98>
#
# The main difference here is that the document data isn’t returned directly to us as an array. Instead we get an
# instance of the Cursor object. This Cursor is an iterable object that contains quite a few helper methods
# to help you work with the data. To get each document, just iterate over the result:
for post in scotts_posts:
print(post)
|
f252694f5d82de1e74c5b076691bdb9206f88ab3 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/272/strings.py | 949 | 4.0625 | 4 | 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.
"""
common = set()
sentence2 = list(map(lambda x: x.lower(), sentence2))
for word in sentence1:
word_lower = word.lower()
if word_lower in sentence2:
common.add(word_lower)
return sorted(common, key=len)
# if __name__ == "__main__":
# S = ['You', 'can', 'do', 'anything', 'but', 'not', 'everything']
# T = ['We', 'are', 'what', 'we', 'repeatedly', 'do', 'is', 'not', 'an', 'act']
# print(common_words(S, T)) |
1e8a48df594f0922144abcc2efffca5050573d49 | syurskyi/Python_Topics | /070_oop/007_exceptions/examples/GoCongr/001_Processing division by zero.py | 422 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# Processing division by zero
try: # Перехватываем исключения
x = 1 / 0 # Ошибка: деление на 0
except ZeroDivisionError: # Указываем класс исключения
print("Обработали деление на 0")
x = 0
print(x) # Выведет: 0 |
9cc244acec4107266c37331c8ae7c7067055e478 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Math/09_PalindromeNumber.py | 506 | 3.859375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def isPalindrome(self, x):
if x < 0:
return False
reversed_x = 0
original_x = x
while x > 0:
reversed_x = reversed_x * 10 + x % 10
x /= 10
return reversed_x == original_x
# Pythonic way.
class Solution_2(object):
def isPalindrome(self, x):
return x >= 0 and str(x) == str(x)[::-1]
"""
9
10
-2147483648
32023
320023
98765432123456789
"""
|
297ab8211294239fd5c2fc1f6a9056d4670c88ff | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/Trie.py | 3,833 | 3.90625 | 4 | """
前缀树又叫字典树,该树会覆盖多个相同的字符以形成空间上的优势。
如:
rat 与 rain
r
a
t i
n
最终会形成这样的树。
字典树有多种实现方式,下面直接用了列表(数组)来实现。
测试用例:
https://leetcode.com/problems/implement-trie-prefix-tree/description/
使用Python 中的字典可以直接形成这种树,所以弃用这种方式,用类的思路实现了一下。
"""
c.. TrieNode o..
# __slots__ 考虑到TrieNode会大量创建,使用 __slot__来减少内存的占用。
# 在测试的15个例子中:
# 使用 __slots__会加快创建,平均的耗时为290ms-320ms。
# 而不使用则在 340ms-360ms之间。
# 创建的越多效果越明显。
# 当然,使用字典而不是类的方式会更加更加更加高效。
__slots__ = {'value', 'nextNodes', 'breakable'}
___ __init__ value, nextNode=None
self.value = value
__ nextNode:
self.nextNodes = [nextNode]
____
self.nextNodes # list
self.breakable = F..
___ addNext nextNode
self.nextNodes.a.. nextNode)
___ setBreakable enable
self.breakable = enable
___ __eq__ other
r_ self.value __ other
c.. Trie o..
___ __init__(self
"""
Initialize your data structure here.
"""
self.root # list
___ insert word
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
self.makeATrieNodes(word)
___ search word
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
___ i __ self.root:
__ i __ word[0]:
r_ self._search(i, word[1:])
r_ F..
___ _search root, word
__ n.. word:
__ root.breakable:
r_ True
r_ F..
__ n.. root.nextNodes:
r_ F..
___ i __ root.nextNodes:
__ i __ word[0]:
r_ self._search(i, word[1:])
r_ F..
___ startsWith prefix
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
___ i __ self.root:
__ i __ prefix[0]:
r_ self._startWith(i, prefix[1:])
r_ F..
___ _startWith root, prefix
__ n.. prefix:
r_ True
__ n.. root.nextNodes:
r_ F..
___ i __ root.nextNodes:
__ i __ prefix[0]:
r_ self._startWith(i, prefix[1:])
r_ F..
___ makeATrieNodes word
___ j __ self.root:
__ word[0] __ j:
rootWord = j
______
____
rootWord = TrieNode(word[0])
self.root.a.. rootWord)
___ i __ word[1:]:
nextNode = TrieNode(i)
rootWord.addNext(nextNode)
rootWord = nextNode
rootWord.setBreakable(True)
r_
# has the letter.
word = word[1:]
_____ 1:
__ n.. word:
rootWord.setBreakable(True)
______
___ i __ rootWord.nextNodes:
__ i __ word[0]:
rootWord = i
word = word[1:]
______
____
___ i __ word:
nextNode = TrieNode(i)
rootWord.addNext(nextNode)
rootWord = nextNode
rootWord.setBreakable(True)
______ |
e39c69fb749b5a25bdc0efa116ca5b1645e0ef7e | syurskyi/Python_Topics | /018_dictionaries/examples/dictionary_003.py | 5,009 | 4.0625 | 4 | # Методы для работы со словарями
# keys () - Одинаковые ключи
d1, d2 = {"a": 1, "b": 2}, {"a": 3, "c": 4, "d": 5}
print(d1.keys() & d2.keys())
# {'a'}
# Методы для работы со словарями
# keys () - Уникальные ключи
d1, d2 = {"a": 1, "b": 2}, {"a": 3, "c": 4, "d": 5}
print(d1.keys() ^ d2.keys())
# {'c', 'b', 'd'}
# Методы для работы со словарями
# values ()
# возвращает объект dict_ values, содержащий все значения словаря. Этот
# объект поддерживает итерации.
d = {"a": 1, "b": 2}
print(d.values()) # Получаем объект dict_values
# dict_values([1, 2])
print(list(d.values())) # Получаем список значений
# [1, 2]
print([v for v in d.values()])
# [1, 2]
# items ()
# возвращает объект dict_items, содержащий все юпочи и значения в виде кортежей.
# Этот объект поддерживает итерации.
d = {"a": 1, "b": 2}
print(d.items()) # Получаем объект dict_items
# dict_items([('a', 1), ('b', 2)])
print(list(d.items())) # Получаем список кортежей
# [('a', 1), ('b', 2)]
# <Ключ> in <Словарь>
# проверяет существование указанного юпоча в словаре. Если kluch найден,
# то возвращается значение тrue, в противном случае - False.
d = {"a": 1, "b": 2}
print("a" in d) # Ключ существует
# True
print("c" in d) # Ключ не существует
# False
# <Ключ> not in <Словарь>
# проверяет отсутствие указанного юпоча в словаре. Если такового Ключа нет, то возвращается значение True,
# в противном случае - False. Примеры:
d = {"a": 1, "b": 2}
print("c" not in d) # Ключ не существует
# True
print("a" not in d) # Ключ существует
# False
# get ( <Ключ> [, <Значение по умолчанию>] )
# если ключ присутствует в словаре, то метод
# возвращает значение, соответствующее этому Ключу. Если ключ отсутствует, то возвращается None или значение,
# указанное во втором параметре
d = {"a": 1, "b": 2}
print(d.get("a"), d.get("c"), d.get("c", 800))
# (1, None, 800)
# setdefault (<Ключ> [, <Значение по умолчанию>])
# если Ключ присутствует в словаре,
# то метод возвращает значение, соответствующее этому ключу. Если ключ отсутствует, то создает в словаре новый элемент
# со значением, указанным во втором параметре. Если второй параметр не указан, значением нового элемента будет None.
d = {"a": 1, "b": 2}
print(d.setdefault("a"), d.setdefault("c"), d.setdefault("d", 0))
# (1, None, 0)print()
print(d)
# {'a': 1, 'c': None, 'b': 2, 'd': 0}
# рор ( <Ключ> [, <Значение по умолчанию> ])
# удаляет элемент с указанным ключ ом и
# возвращает его значение. Если ключ отсутствует, то возврашается значение из второго параметра.
# Если ключ отсутствует, и второй параметр не указан, возбуждается исключение KeyError.
#
d = {"a": 1, "b": 2, "c": 3}
print(d.pop("a"), d.pop("n", 0))
# popitem()
# удаляет произвольный элемент и возвращает кортеж из ключа и значения.
# Если словарь пустой, возбуждается исключение KeyError.
#
d = {"a": 1, "b": 2}
print(d.popitem())
# ('a', 1)
print(d.popitem())
# clear ()
# удаляет все элементы словаря. Метод ничего не возвращает в качестве значения.
#
d = {"a": 1, "b": 2}
d.clear() # Удаляем все элементы
print(d) # Словарь теперь пустой
# {}
# update ()
# uрdаtе(<Ключ1>=<Значение1>[, ... , <КлючN>=<ЗначениеN>])
# добавляет элементы в словарь. Метод изменяет текущий словарь и ничего
# не возвращает.
#
d = {"a": 1, "b": 2}
d.update(c=3, d=4)
print(d)
# update ()
# uрdаtе(<Словарь>)
d = {"a": 1, "c": 3, "b": 2, "d": 4}
d.update({"c": 10, "d": 20}) # Словарь
print(d) # Значения элементов перезаписаны |
b7bad63ce92b0c02cb75adfbd722b04af3be1127 | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 93 - SpiralMatrix.py | 1,543 | 4.15625 | 4 | # Spiral Matrix
# Question: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
# For example:
# Given the following matrix:
# [ [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ] ]
# You should return [1,2,3,6,9,8,7,4,5].
# Solutions:
class Solution:
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
if matrix == []:
return []
res = []
maxUp = maxLeft = 0
maxDown = len(matrix) - 1
maxRight = len(matrix[0]) - 1
direct = 0 # 0 go right, 1 go down, 2 go left, 3 go up
while True:
if direct == 0: # go right
for i in range(maxLeft, maxRight + 1):
res.append(matrix[maxUp][i])
maxUp += 1
elif direct == 1: # go down
for i in range(maxUp, maxDown + 1):
res.append(matrix[i][maxRight])
maxRight -= 1
elif direct == 2: # go left
for i in reversed(range(maxLeft, maxRight + 1)):
res.append(matrix[maxDown][i])
maxDown -= 1
else: # go up
for i in reversed(range(maxUp, maxDown + 1)):
res.append(matrix[i][maxLeft])
maxLeft += 1
if maxUp > maxDown or maxLeft > maxRight:
return res
direct = (direct + 1) % 4
Solution().spiralOrder([ [ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ] ]) |
e4504b274522db17826e696e8541a6f7f1d83b05 | syurskyi/Python_Topics | /110_concurrency_parallelism/002_threads/_exercises/exercises/Module Threading overview/008 - threading.main_thread.py | 1,350 | 3.5625 | 4 | import threading, time, logging
def worker():
name = threading.current_thread().name
time.sleep(1)
logging.debug(f'Ending {name}')
logging.basicConfig(
level=logging.DEBUG,
format='[%(levelname)s] %(message)s',
)
# использование 'threading.main_thread()'
# получаем экземпляр основного потока
main_thread = threading.main_thread()
# получаем имя основного потока
main_thread_name = main_thread.name
logging.debug(f'{main_thread_name} starting...')
for _ in range(3):
thread = threading.Thread(target=worker)
thread.start()
for t in threading.enumerate():
# Список 'threading.enumerate()' включает в себя основной
# поток и т.к. присоединение основного потока самого к себе
# приводит к тупиковой ситуации, то его необходимо пропустить
if t is main_thread:
continue
thead_name = t.name
logging.debug(f'{main_thread_name} joining {thead_name}')
thread.join()
# [DEBUG] MainThread starting...
# [DEBUG] MainThread joining Thread-1
# [DEBUG] Ending Thread-1
# [DEBUG] MainThread joining Thread-2
# [DEBUG] Ending Thread-3
# [DEBUG] Ending Thread-2
# [DEBUG] MainThread joining Thread-3 |
3e660c161e74fbbb940d1562747d229af9997926 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/002_list_comprehension/_exercises/exercises/002_list_comprehension_template.py | 2,696 | 3.953125 | 4 | # # List Comprehensions A First Detailed Look
#
# L _ 1 2 3 4 5 # List
#
# ___ i __ r... le. L # how to use range to change a list as we step across it
# L|i += 10
#
# printL
#
# L _ x + 10 ___ ? __ L #list comprehension expression
# print ?
#
#
# # List Comprehension Basics
#
# L _ 1 2 3 4 5
#
# L _ x + 10 ___ ? __ L] # list comprehension simply looks like a backward for loop.
# print ?
#
#
# res _
# ___ x __ L
# ?.a.. ? + 10
#
# print ?
#
# # Using List Comprehensions on Files
#
# f _ o... script1.py
# lines _ ?.r...
# print ?
#
# lines _ line.r.. ___ li.. __ li..
# print ?
#
#
# lines _ l__.rst.. ___ l.. __ o... script1.py
# print ?
#
# print l___.u.. ___ l___ i_ o... script1.py
#
# print l___.rst__.u.. ___ l___ __ o... script1.py
#
# print l___.sp.. ___ l___ __ o... script2.py
#
# print l___.rep..' '; '!') ___ l___ i_ o... script2.py
#
# print'sys' __ l___; l___|0 ___ l___ i_ o... script1.py
#
# # Extended List Comprehension Syntax
#
# lines _ l___.rst... ___ l___ i_ o... script2.py i_ l___|0] __ p
# print l...
#
# res _
# ___ l___ i_ o... script2.py
# __ l___ 0 __ p
# ?.a... l___.rst...
# print ?
#
#
# print x + y ___ ? __ abc ___ ? __ lmn
#
# res _ |
# ___ x __ abc
# ___ y __ lmn
# r__.a.. x + y
# print r..
#
# # Why You Will Care List Comprehensions and map
# print o... myfile.rea..
#
# print l___.rst... ___ l___ i_ o... myfile .rea...
#
# print l___.rst... ___ l___ i_ o... myfile
#
# print l.. m.. l_____ l___ l___.rst...; o... myfile
#
# listoftuple _ 'bob', 35, 'mgr'|, |'mel', 40, 'dev'
#
# print age ___ |name age job| i_ li.....
#
# print l.. m.. l_____ row; row 1 ; li.....
#
#
# # Comprehension Syntax Summary
# # List comprehension: builds list
#
# print x * x ___ x __ r... 10
#
# # Comprehension Syntax Summary
# # Generator expression: produces items
# # Parens are often optional
#
# print x * x ___ ? __ r... 10
#
# # Comprehension Syntax Summary
# # Set comprehension, new in 3.0, {x, y} is a set in 3.0 too
#
# print x * x ___ ? __ r... 10
#
# # And re-working this into a list comprehension:
# #
# n _ 10
# iter_cycl _ CyclicIterator('NSWE')
# _*|i||n..|iter_cycl||* ___ i i_ r...|1; n+1
# #
# # Of course, there's an easy alternative way to do this as well, using: repetition, zip
# # a list comprehension
#
# n _ 10
# l... z.. r... 1; n+1 ; 'NSWE' * n//4 + 1
#
# # There's actually an even easier way yet, and that's to use our CyclicIterator, but instead of building it ourselves, we can simply use the one provided by Python in the standard library!!
#
# import itertools
# n _ 10
# iter_cycl _ CyclicIterator('NSWE')
# _*|i||n...|i.._c..||* ___ i i_ r... 1; n+1
#
# n _ 10
# iter_cycl _ i |
7bf9169ff6beefc28c02ca3594388262c8b3f138 | syurskyi/Python_Topics | /120_design_patterns/013_chain_of_responsibility/examples/Section_13_Chain of Responsibility/exercise.py | 2,189 | 3.515625 | 4 | import unittest
from abc import ABC
from enum import Enum
# creature removal (unsubscription) ignored in this exercise solution
class Creature(ABC):
def __init__(self, game, attack, defense):
self.initial_defense = defense
self.initial_attack = attack
self.game = game
@property
def attack(self): pass
@property
def defense(self): pass
def query(self, source, query): pass
class WhatToQuery(Enum):
ATTACK = 1
DEFENSE = 2
class Goblin(Creature):
def __init__(self, game, attack=1, defense=1):
super().__init__(game, attack, defense)
@property
def attack(self):
q = Query(self.initial_attack, WhatToQuery.ATTACK)
for c in self.game.creatures:
c.query(self, q)
return q.value
@property
def defense(self):
q = Query(self.initial_defense, WhatToQuery.DEFENSE)
for c in self.game.creatures:
c.query(self, q)
return q.value
def query(self, source, query):
if self != source and query.what_to_query == WhatToQuery.DEFENSE:
query.value += 1
class GoblinKing(Goblin):
def __init__(self, game):
super().__init__(game, 3, 3)
def query(self, source, query):
if self != source and query.what_to_query == WhatToQuery.ATTACK:
query.value += 1
else:
super().query(source, query)
class Query:
def __init__(self, initial_value, what_to_query):
self.what_to_query = what_to_query
self.value = initial_value
class Game:
def __init__(self):
self.creatures = []
class FirstTestSuite(unittest.TestCase):
def test(self):
game = Game()
goblin = Goblin(game)
game.creatures.append(goblin)
self.assertEqual(1, goblin.attack)
self.assertEqual(1, goblin.defense)
goblin2 = Goblin(game)
game.creatures.append(goblin2)
self.assertEqual(1, goblin.attack)
self.assertEqual(2, goblin.defense)
goblin3 = GoblinKing(game)
game.creatures.append(goblin3)
self.assertEqual(2, goblin.attack)
self.assertEqual(3, goblin.defense) |
ddedc104cb1b08f182806cc3623960d34c8c4224 | syurskyi/Python_Topics | /079_high_performance/exercises/template/Writing High Performance Python/item_16.py | 1,475 | 3.609375 | 4 | import logging
from pprint import pprint
from sys import stdout as STDOUT
# Example 1
def index_words(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ' ':
result.append(index + 1)
return result
# Example 2
address = 'Four score and seven years ago...'
address = 'Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.'
result = index_words(address)
print(result[:3])
# Example 3
def index_words_iter(text):
if text:
yield 0
for index, letter in enumerate(text):
if letter == ' ':
yield index + 1
# Example 4
result = list(index_words_iter(address))
print(result[:3])
# Example 5
def index_file(handle):
offset = 0
for line in handle:
if line:
yield offset
for letter in line:
offset += 1
if letter == ' ':
yield offset
# Example 6
address_lines = """Four score and seven years
ago our fathers brought forth on this
continent a new nation, conceived in liberty,
and dedicated to the proposition that all men
are created equal."""
with open('address.txt', 'w') as f:
f.write(address_lines)
from itertools import islice
with open('address.txt', 'r') as f:
it = index_file(f)
results = islice(it, 0, 3)
print(list(results))
|
b9078848e7b70ef142ad2c86cc0be0f1e4c83099 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/LinkedList/148_SortList.py | 2,122 | 3.75 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
# @Last Modified time: 2016-09-06 20:03:53
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Merge Sort
c.. Solution o..
___ sortList head
__ n.. head or n.. head.next:
r_ head
# Get the two half parts.
pre_slow = None
slow = fast = head
_____ fast a.. fast.next:
pre_slow = slow
slow = slow.next
fast = fast.next.next
pre_slow.next = None # Cut the linked list to two parts.
left_list = self.sortList(head)
right_list = self.sortList(slow)
r_ self.merge(left_list, right_list)
# Operator merge.
___ merge left_list, right_list
pre_head = dummy = ListNode(None)
_____ left_list a.. right_list:
__ left_list.val < right_list.val:
dummy.next = left_list
left_list = left_list.next
____
dummy.next = right_list
right_list = right_list.next
dummy = dummy.next
dummy.next = left_list or right_list
r_ pre_head.next
# Quick sort: Time Limit Exceeded
c.. Solution_2 o..
___ partition begin, end
__ n.. begin or begin.next __ end:
r_ begin
pivot = begin.val
keep, pos = begin, begin
scan = begin.next
_____ scan != end:
__ scan.val <= pivot:
pos = pos.next
__ scan != pos:
scan.val, pos.val = pos.val, scan.val
scan = scan.next
pos.val, keep.val = keep.val, pos.val
r_ pos
___ quick_sort begin, end
__ begin __ end or begin.next __ end:
r_ begin
pos = self.partition(begin, end)
head = self.quick_sort(begin, pos)
self.quick_sort(pos.next, end)
r_ head
___ sortList head
r_ self.quick_sort(head, None)
"""
[]
[1]
[1,2]
[5,1,2]
[5,1,2,3]
[5,1,2,3,6,7,8,9,12,2]
"""
|
93b461451168835895e44e1235a700d78eac7972 | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python 3 Most Nessesary/13.4.1.Listing 13.13. Expansion of class functionality by impurity.py | 778 | 3.859375 | 4 | class Mixin: # Определяем сам класс-примесь
attr = 0 # Определяем атрибут примеси
def mixin_method(self): # Определяем метод примеси
print("Метод примеси")
class Class1 (Mixin):
def method1(self):
print("Метод класса Class1")
class Class2 (Class1, Mixin):
def method2(self):
print("Метод класса Class2")
c1 = Class1()
c1.method1()
c1.mixin_method() # Class1 поддерживает метод примеси
c2 = Class2()
c2.method1()
c2.method2()
c2.mixin_method() # Class2 также поддерживает метод примеси |
05c42d3fc3d3e6041d27797b1e6fc2dd6d6c07c4 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/157_v2/accents.py | 430 | 3.921875 | 4 | import unicodedata
def filter_accents(text):
"""Return a sequence of accented characters found in
the passed in lowercased text string
"""
text = text.lower()
result = []
s = unicodedata.normalize('NFD',text).encode("ascii",'ignore').decode('utf-8')
for character_1,character_2 in zip(text,s):
if character_1 != character_2:
result.append(character_1)
return result
|
4879c43d50d6386e3de45553d948c1785d3b8361 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Practical_Python_Programming_Practices/Practice 52. Longest ordered sequence in ascending order NUKE.py | 433 | 3.875 | 4 | ____ r__ _______ r__
num 20
listitem [0]*num
___ i __ r..(num):
listitem[i] i..(r__()*50)
print(listitem)
maxi 1
mylength 1
mycode 0
___ i __ r..(1,num):
__ listitem[i] > listitem[i-1]:
mylength + 1
____:
__ mylength > maxi:
maxi mylength
mycode i
mylength 1
print("The maximum lenght = ",maxi)
print("The ordered values are = ",listitem[mycode-maxi : mycode]) |
f5487e3f92d7ad320f07be4fb59581ff4e2c5be0 | syurskyi/Python_Topics | /010_strings/_exercises/ITVDN Python Starter 2016/11-string-operations.py | 837 | 3.578125 | 4 | str1 = 'hel'
str2 = 'lo'
result = str1 + str2 # конкатенация строка
print(result)
# форматирование строк
a = 48
b = 73
message1 = '%d + %d = %d' % (a, b, a + b)
print(message1)
message2 = '{} - {} = {}'.format(a, b, a - b)
print(message2)
# индексация строк
s = 'Hello, World!'
# (вернуться в седьмом уроке)
print(s[0]) # индексация начинается с нуля
print(s[4]) # четвёртый (пятый логически) элемент (символ)
print(s[-1]) # отрицательные числа – индексация с конца
print(s[2:7]) # символы со второго (включительно) по пятый (не включительно)
print(s[2:7:2]) # то же, но с шагом два |
712c693e7db9a2438e596103fb89b966e68521d1 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/1022 Sum of Root To Leaf Binary Numbers.py | 1,355 | 3.96875 | 4 | #!/usr/bin/python3
"""
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path
represents a binary number starting with the most significant bit. For example,
if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary,
which is 13.
For all leaves in the tree, consider the numbers represented by the path from
the root to that leaf.
Return the sum of these numbers.
Example 1:
Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
Note:
The number of nodes in the tree is between 1 and 1000.
node.val is 0 or 1.
The answer will not exceed 2^31 - 1.
"""
# Definition for a binary tree node.
c_ TreeNode:
___ - , x
val x
left N..
right N..
c_ Solution:
___ -
ret 0
lst # list
___ sumRootToLeaf root: TreeNode) __ i..
"""
Brute force, keep a lst, space O(log n)
Error-prone
"""
dfs(root)
r.. ret
___ dfs node
__ n.. node:
r..
lst.a..(node.val) # error prone
__ n.. node.left a.. n.. node.right:
# leaf
cur 0
___ a __ lst:
cur <<= 1
cur += a
ret += cur
____
dfs(node.left)
dfs(node.right)
lst.p.. )
|
2f0bbaccfffd2a6b9611bd515ce4ad87aa2873c7 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/Search2DMatrix.py | 3,025 | 3.953125 | 4 | """
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
给一个2d数组,给一个数字,找是否存在于其中。
思路:
两个二分法:
一个竖着的二分法,
一个横着的二分法。
竖着的二分法返回下标,横着的返回是否存在。
竖着的:
处理仅有一个的情况:
<= 都返回len()-1也就是下标
> 返回 -1 表示不存在。
其他情况下寻找 left <= x <= right.
由于 right一定大于left。所以left <= 可以放在一起判断,返回的是基础下标+当前二分的len()-1。
right == 的情况则不-1。
横着的没啥好说的,普通二分法即可。
最差是O(logm + logn)两次二分法的耗时。
beat 100%.
测试用例:
https://leetcode.com/problems/search-a-2d-matrix/description/
"""
class Solution(object):
def binarySearch(self, rawList, target, index=0):
if target >= rawList[-1]:
return len(rawList) - 1
if target < rawList[0]:
return -1
split = len(rawList) // 2
leftList = rawList[:split]
rightList = rawList[split:]
if leftList[-1] <= target and rightList[0] > target:
return len(leftList) + index - 1
if rightList[0] == target:
return len(leftList) + index
if leftList[-1] > target:
return self.binarySearch(leftList, target, index=index)
if rightList[0] < target:
return self.binarySearch(rightList, target, index=index+len(leftList))
def binarySearch2(self, rawList, target):
split = len(rawList) // 2
left = rawList[:split]
right = rawList[split:]
if not left and not right:
return False
if left and left[-1] == target:
return True
if right and right[0] == target:
return True
if len(left) > 1 and left[-1] > target:
return self.binarySearch2(left, target)
if len(right) > 1 and right[0] < target:
return self.binarySearch2(right, target)
return False
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not any(matrix):
return False
column = [i[0] for i in matrix]
column_result = self.binarySearch(column, target)
if column_result == -1:
return False
return self.binarySearch2(matrix[column_result], target)
|
274b44dada6dcbc7ae5424b9c929e6396365dc10 | syurskyi/Python_Topics | /085_regular_expressions/_exercises/templates/Section 34 Regular Expressions/349.Parsing Bytes Exericse SOLUTION.py | 658 | 3.75 | 4 | # # Parsing Bytes Solution
# #
# # My regex looks like this: '\b[10]{8}\b' It consists of eight 1s or 0s, surrounded by word boundaries on either side.
# # Remember a word boundary is either a space or the start/end of a line.
# # I then used findall rather than search, to return a list of all matches. Here's the final solution:
# #
#
# ______ __
# # ___ parse_bytes input
# # binary_regex _ __.c.. _ 1? 10 2? 1? # 1. Returns a match where the specified characters are at the beginning or at the end of a word
# # # 2. любую цифру ровно 8 раз
# # results = ?.f_a_ ?
# # r_ ? |
7f8d74217b2cbc3a38cc6e89865437c81073b62f | syurskyi/Python_Topics | /018_dictionaries/_exercises/Python 3 Deep Dive (Part 3)/10. Creating Dictionaries - Coding.py | 4,327 | 4.5625 | 5 | # a = {'k1': 100, 'k2': 200}
# print(a)
#
# print h.. 1, 2, 3
#
# # hash([1, 2, 3]) TypeError: unhashable type: 'list'
#
# print('#' * 52 + ' So we can create dictionaries that look like this: ')
#
# a = {('a', 100): ['a', 'b', 'c'], 'key2': {'a': 100, 'b': 200}}
# print(a)
#
# print('#' * 52 + ' Interestingly, functions are hashable: ')
#
# ___ my_func a, b, c
# print(a, b, c)
#
# print(h.. ?
#
# print('#' * 52 + ' Which means we can use functions as keys in dictionaries: ')
# d = ? 10, 20, 30
# print ?
#
# print('#' * 52 + ' A simple application of this might be to store the argument values we want to use to call the '
# 'function at a later time: ')
#
# ___ fn_add a, b
# r_ a + b
#
# ___ fn_inv a
# r_ 1/a
#
# ___ fn_mult a, b
# r_ a * b
#
# funcs = {f._a. (10, 20 , f._i. (2,), f_m. 2, 8
# print ?
#
# print('#' * 52 + ' Remember that when we iterate through a dictionary we are actually iterating through the keys: ')
#
# ___ f in ?
# print ?
#
# ___ f in ?
# result = ? $? ?
# print ?
#
# print('#' * 52 + ' We can also iterate through the items (as tuples) in a dictionary as follows: ')
#
# ___ f, args __ ?.it..
# print ? a..
#
# ___ f, args __ ?.it..
# result = ? $?
# print ?
#
# print('#' * 52 + ' #### Using the class constructor ')
#
# d = di.. a=100, b=200)
# print ?
#
# print('#' * 52 + ' We can also build a dictionary by passing it an iterable containing the keys and the values: ')
#
# d = di.. 'a' 100 'b' 200
# print ?
#
# print('#' * 52 + ' The restriction here is that the elements of the iterable must themselves be iterables with exactly'
# ' two elements. ')
#
# d = di.. 'a ', 100 , 'b' 200
# print(d)
#
# print('#' * 52 + ' Of course we can also pass a dictionary as well: ')
#
# d = {'a': 100, 'b': 200, 'c': {'d': 1, 'e': 2}}
#
# print(id(d))
#
# print('#' * 52 + ' And lets create a dictionary: ')
#
# new_dict = dict(d)
# print(new_dict)
# print(id(new_dict))
#
# print('#' * 52 + ' As you can see, we have a new object - however, what about the nested dictionary? ')
#
# print(id(d['c']), id(new_dict['c']))
#
# print('#' * 52 + ' #### Using Comprehensions ')
#
# keys = ['a', 'b', 'c']
# values = (1, 2, 3)
#
# print('#' * 52 + ' We can then easily create a dictionary this way - the non-Pythonic way! ')
#
# d # creates an empty dictionary
# ___ k, v __ z.. k.. v..
# ? k _ v
#
# print(d)
#
# print('#' * 52 + ' But it is much simpler to use a dictionary comprehension: ')
#
# d = k v ___ k, ? __ z.. k.. v..
# print ?
#
# print('#' * 52 + ' Dictionary comprehensions support the same syntax as list comprehensions - you can have'
# ' nested loops, `if` statements, etc. ')
#
# keys = ['a', 'b', 'c', 'd']
# values = (1, 2, 3, 4)
#
# d = k v ___ k, ? __ z.. k.. v.. i_ ? % 2 __ 0
# print ?
#
# print('#' * 52 + ' ')
#
# x_coords = (-2, -1, 0, 1, 2)
# y_coords = (-2, -1, 0, 1, 2)
#
# grid = [(x, y)
# ___ x in x_coords
# ___ y in y_coords]
# print(grid)
#
# print('#' * 52 + ' We can use the `math` modules `hypot` function to do calculate these distances ')
#
# import math
# print(math.hypot(1, 1))
#
# grid_extended = x, y, m__.hy.. x, y ___ x y i. g..
# print ?
#
# print('#' * 52 + ' 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.. x, y ___ x, y i_ g..
# print ?
#
# print('#' * 52 + ' #### Using `fromkeys` ')
# print('#' * 52 + ' The `dict` class also provides the `fromkeys` method that we can use to create dictionaries.'
# ' This class method is used to create a dictionary from an iterable containing the keys, and'
# ' a **single** value used to assign to each key. ')
#
# counters = di__.f.k. 'a', 'b', 'c'], 0)
# print ?
#
# print('#' * 52 + ' If we do not specify a value, then `None` is used: ')
#
# d = di__.f_k_ abc
# print ?
#
# print('#' * 52 + ' Notice how I used the fact that strings are iterables to specify the three single character '
# 'keys ___ this dictionary! ')
# print('#' * 52 + ' `fromkeys` method will insert the keys in the order in which they are retrieved from the iterable: ')
#
# d = di__.f..k.. python
# print ?
# print((?))
|
98c56b89578656d7339dee729ebca6e2fc87b2d0 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id009-Triangles.py | 518 | 3.59375 | 4 | ___ triangle(calculations
answer # list
___ calculation __ r..(calculations
[a,b,c] raw_input().s..
[a,b,c] i..(a),i..(b),i..(c)
minNum m..(i..(a),i..(b),i..(c
maxNum m..(i..(a),i..(b),i..(c
___ x __ [a,b,c]:
__ i..(x) ! minNum a.. i..(x) ! maxNum:
midNum x
a,b,c minNum, midNum, maxNum
__ (a+b) > c:
answer.a..(s..('1'
____
answer.a..(s..('0'
print(' '.j..(answer
triangle(input
|
9b650a0d9be51d84b4ae0da975ad0d44d515bd88 | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 9 Project 4/110. Solution - Part 2.py | 11,592 | 3.734375 | 4 | # %%
'''
### Solution - Part 2
'''
# %%
'''
Here's where we left off in the last video:
'''
# %%
import numbers
import unittest
# %%
class TestIntegerField(unittest.TestCase):
@staticmethod
def create_test_class(min_, max_):
obj = type('TestClass', (), {'age': IntegerField(min_, max_)})
return obj()
def test_set_age_ok(self):
"""Tests that valid values can be assigned/retrieved"""
min_ = 5
max_ = 10
obj = self.create_test_class(min_, max_)
valid_values = range(min_, max_)
for i, value in enumerate(valid_values):
with self.subTest(test_number=i):
obj.age = value
self.assertEqual(value, obj.age)
def test_set_age_invalid(self):
"""Tests that invalid values raise ValueErrors"""
min_ = -10
max_ = 10
obj = self.create_test_class(min_, max_)
bad_values = list(range(min_ - 5, min_))
bad_values += list(range(max_ + 1, max_ + 5))
bad_values += [10.5, 1 + 0j, 'abc', (1, 2)]
for i, value in enumerate(bad_values):
with self.subTest(test_number=i):
with self.assertRaises(ValueError):
obj.age = value
def test_class_get(self):
"""Tests that class attribute retrieval returns the descriptor instance"""
obj = self.create_test_class(0, 0)
obj_class = type(obj)
self.assertIsInstance(obj_class.age, IntegerField)
def test_set_age_min_only(self):
"""Tests that we can specify a min value only"""
min_ = 0
max_ = None
obj = self.create_test_class(min_, max_)
values = range(min_, min_ + 100, 10)
for i, value in enumerate(values):
with self.subTest(test_number=i):
obj.age = value
self.assertEqual(value, obj.age)
def test_set_age_max_only(self):
"""Tests that we can specify a max value only"""
min_ = None
max_ = 10
obj = self.create_test_class(min_, max_)
values = range(max_ - 100, max_, 10)
for i, value in enumerate(values):
with self.subTest(test_number=i):
obj.age = value
self.assertEqual(value, obj.age)
def test_set_age_no_limits(self):
"""Tests that we can use IntegerField without any limits at all"""
min_ = None
max_ = None
obj = self.create_test_class(min_, max_)
values = range(-100, 100, 10)
for i, value in enumerate(values):
with self.subTest(test_number=i):
obj.age = value
self.assertEqual(value, obj.age)
class TestCharField(unittest.TestCase):
@staticmethod
def create_test_class(min_, max_):
obj = type('TestClass', (), {'name': CharField(min_, max_)})
return obj()
def test_set_name_ok(self):
"""Tests that valid values can be assigned/retrieved"""
min_ = 1
max_ = 10
obj = self.create_test_class(min_, max_)
valid_lengths = range(min_, max_)
for i, length in enumerate(valid_lengths):
value = 'a' * length
with self.subTest(test_number=i):
obj.name = value
self.assertEqual(value, obj.name)
def test_set_name_invalid(self):
"""Tests that invalid values raise ValueErrors"""
min_ = 5
max_ = 10
obj = self.create_test_class(min_, max_)
bad_lengths = list(range(min_ - 5, min_))
bad_lengths += list(range(max_ + 1, max_ + 5))
for i, length in enumerate(bad_lengths):
value = 'a' * length
with self.subTest(test_number=i):
with self.assertRaises(ValueError):
obj.name = value
def test_class_get(self):
"""Tests that class attribute retrieval returns the descriptor instance"""
obj = self.create_test_class(0, 0)
obj_class = type(obj)
self.assertIsInstance(obj_class.name, CharField)
def test_set_name_min_only(self):
"""Tests that we can specify a min length only"""
min_ = 0
max_ = None
obj = self.create_test_class(min_, max_)
valid_lengths = range(min_, min_ + 100, 10)
for i, length in enumerate(valid_lengths):
value = 'a' * length
with self.subTest(test_number=i):
obj.name = value
self.assertEqual(value, obj.name)
def test_set_name_min_negative_or_none(self):
"""Tests that setting a negative or None length results in a zero length"""
obj = self.create_test_class(-10, 100)
self.assertEqual(type(obj).name._min, 0)
self.assertEqual(type(obj).name._max, 100)
obj = self.create_test_class(None, None)
self.assertEqual(type(obj).name._min, 0)
self.assertIsNone(type(obj).name._max)
def test_set_name_max_only(self):
"""Tests that we can specify a max length only"""
min_ = None
max_ = 10
obj = self.create_test_class(min_, max_)
valid_lengths = range(max_ - 100, max_, 10)
for i, length in enumerate(valid_lengths):
value = 'a' * length
with self.subTest(test_number=i):
obj.name = value
self.assertEqual(value, obj.name)
def test_set_name_no_limits(self):
"""Tests that we can use CharField without any limits at all"""
min_ = None
max_ = None
obj = self.create_test_class(min_, max_)
valid_lengths = range(0, 100, 10)
for i, length in enumerate(valid_lengths):
value = 'a' * length
with self.subTest(test_number=i):
obj.name = value
self.assertEqual(value, obj.name)
def run_tests(test_class):
suite = unittest.TestLoader().loadTestsFromTestCase(test_class)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
# %%
class IntegerField:
def __init__(self, min_, max_):
self._min = min_
self._max = max_
def __set_name__(self, owner_class, prop_name):
self.prop_name = prop_name
def __set__(self, instance, value):
if not isinstance(value, numbers.Integral):
raise ValueError(f'{self.prop_name} must be an integer.')
if self._min is not None and value < self._min:
raise ValueError(f'{self.prop_name} must be >= {self._min}.')
if self._max is not None and value > self._max:
raise ValueError(f'{self.prop_name} must be <= {self._max}')
instance.__dict__[self.prop_name] = value
def __get__(self, instance, owner_class):
if instance is None:
return self
else:
return instance.__dict__.get(self.prop_name, None)
class CharField:
def __init__(self, min_=None, max_=None):
min_ = min_ or 0 # in case min_ is None
min_ = max(min_, 0) # replaces negative value with zero
self._min = min_
self._max = max_
def __set_name__(self, owner_class, prop_name):
self.prop_name = prop_name
def __set__(self, instance, value):
if not isinstance(value, str):
raise ValueError(f'{self.prop_name} must be a string.')
if self._min is not None and len(value) < self._min:
raise ValueError(f'{self.prop_name} must be >= {self._min} chars.')
if self._max is not None and len(value) > self._max:
raise ValueError(f'{self.prop_name} must be <= {self._max} chars')
instance.__dict__[self.prop_name] = value
def __get__(self, instance, owner_class):
if instance is None:
return self
else:
return instance.__dict__.get(self.prop_name, None)
# %%
'''
And of course, our unit tests should run just fine:
'''
# %%
run_tests(TestIntegerField)
# %%
run_tests(TestCharField)
# %%
'''
As you may noticed, quite a bit of code was redundant between the `IntegerField` and `CharField` descriptors.
So, let's restructure things a bit to make use of inheritance for the common bits.
'''
# %%
'''
Notice that the implementation of `__set_name__` and `__get__` are actually identical. The `__init__` methods are
slightly different, but there is still some commonality. And same goes for the `__set__` - although the validations
are different, the storage mechanism is the same - so we could factor that out.
'''
# %%
'''
We're going to create a base class as follows:
'''
# %%
class BaseValidator:
def __init__(self, min_=None, max_=None):
self._min = min_
self._max = max_
def __set_name__(self, owner_class, prop_name):
self.prop_name = prop_name
def __get__(self, instance, owner_class):
if instance is None:
return self
else:
return instance.__dict__.get(self.prop_name, None)
def validate(self, value):
# this will need to be implemented specifically by each subclass
# here we just default to not raising any exceptions
pass
def __set__(self, instance, value):
self.validate(value)
instance.__dict__[self.prop_name] = value
# %%
'''
Of course we can use this `BaseValidator` directly, but it won't be very useful:
'''
# %%
class Person:
name = BaseValidator()
# %%
p = Person()
# %%
p.name = 'Alex'
# %%
p.name
# %%
'''
Now let's leverage this class to create our integer and char descriptors:
'''
# %%
class IntegerField(BaseValidator):
def validate(self, value):
if not isinstance(value, numbers.Integral):
raise ValueError(f'{self.prop_name} must be an integer.')
if self._min is not None and value < self._min:
raise ValueError(f'{self.prop_name} must be >= {self._min}.')
if self._max is not None and value > self._max:
raise ValueError(f'{self.prop_name} must be <= {self._max}')
# %%
class CharField(BaseValidator):
def __init__(self, min_, max_):
min_ = max(min_ or 0, 0)
super().__init__(min_, max_)
def validate(self, value):
if not isinstance(value, str):
raise ValueError(f'{self.prop_name} must be a string.')
if self._min is not None and len(value) < self._min:
raise ValueError(f'{self.prop_name} must be >= {self._min} chars.')
if self._max is not None and len(value) > self._max:
raise ValueError(f'{self.prop_name} must be <= {self._max} chars')
# %%
'''
And this should work just as before. Lucky for us we don't have to test anything manually, we can just re-run
our unit tests and make sure nothing broke!
'''
# %%
run_tests(TestIntegerField)
# %%
run_tests(TestCharField)
# %%
'''
Woohoo!!
'''
# %%
'''
One thing I want to mention here: now that we are using unittests, and iterating our development,
using Jupyter notebooks, even with relatively simple programs like this one, is getting unwieldy.
Best would be to use a proper Python app, with a root and multiple modules, including one for unit tests.
An IDE like PyCharm or VSCode works really great, but of course you can choose to use any text editor,
and the command line to run your app instead of an IDE.
'''
# %%
|
2f93eb2caf06c52f626405f769f6f76e151b919b | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/NumberOfIslands.py | 1,740 | 3.96875 | 4 | """
与今日头条的秋招第一题差不多的题:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
分析看 FootbalFans.py
passed.
测试地址:
https://leetcode.com/problems/number-of-islands/description/
"""
class Solution(object):
def makeXY(self, x, y):
return ((x, y-1),
(x, y+1),
(x-1, y),
(x+1, y))
def numIslands(self, court):
"""
:type grid: List[List[str]]
:rtype: int
"""
fans_groups = []
x = 0
y = 0
if not court:
return 0
x_length = len(court[0])
y_length = len(court)
def helper(x, y):
Xy = self.makeXY(x, y)
for i in Xy:
try:
if i[1] < 0 or i[0] < 0:
continue
if court[i[1]][i[0]] == '1':
court[i[1]][i[0]] = '0'
t = helper(i[0], i[1])
except IndexError:
continue
else:
return 1
for y in range(y_length):
for x in range(x_length):
if court[y][x] == '1':
court[y][x] = '0'
fans_groups.append(helper(x, y))
if not fans_groups:
return 0
return len(fans_groups)
|
3070b9084f00b2448b6ac064a90ea2bd3e4146ad | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/advanced/31/matmul.py | 1,178 | 3.734375 | 4 | from copy import deepcopy
class Matrix(object):
def __init__(self, values):
self.values = values
@property
def nrows(self):
return len(self.values)
@property
def ncols(self):
return len(self.values[0])
def __matmul__(self,other):
rows_1,cols_1 = len(self.values),len(self.values[0])
rows_2,cols_2 = len(other.values),len(other.values[0])
result_rows,result_cols = rows_1,cols_2
result_matrix = [[None for _ in range(result_cols)] for _ in range(result_rows)]
for row in range(result_rows):
for col in range(result_cols):
value = 0
for c in range(cols_1):
value += self.values[row][c] * other.values[c][col]
result_matrix[row][col] = value
return Matrix(result_matrix)
def __imatmul__(self,other):
result = self @ other
self.values = deepcopy(result.values)
return self
def __rmatmul__(self,other):
return self @ other
def __repr__(self):
return f'<Matrix values="{self.values}">'
|
fadffaf739e2355d3c6b270c6f9f140026a81beb | syurskyi/Python_Topics | /110_concurrency_parallelism/002_threads/examples/Module Threading overview/025 - Examples of installing flow barriers.py | 1,468 | 3.609375 | 4 | import threading, time
def worker(barrier):
th_name = threading.current_thread().name
print(f'{th_name} в ожидании барьера с {barrier.n_waiting} другими')
worker_id = barrier.wait()
print(f'{th_name} прохождение барьера {worker_id}')
# число потоков, при использовании
# барьеров оно должно быть постоянным
NUM_THREADS = 3
# установка барьера
barrier = threading.Barrier(NUM_THREADS)
threads = []
# создаем и запускаем потоки
for i in range(NUM_THREADS):
th = threading.Thread(name=f'Worker-{i}',
target=worker,
args=(barrier,),
)
threads.append(th)
print(f'Запуск {th.name}')
th.start()
time.sleep(0.3)
# блокируем основной поток программы
# до завершения работы всех потоков
for thread in threads:
thread.join()
# Запуск Worker-0
# Worker-0 в ожидании барьера с 0 другими
# Запуск Worker-1
# Worker-1 в ожидании барьера с 1 другими
# Запуск Worker-2
# Worker-2 в ожидании барьера с 2 другими
# Worker-2 прохождение барьера 2
# Worker-0 прохождение барьера 0
# Worker-1 прохождение барьера 1 |
eb74ec0a560fd5194d36c90b72ff1321bf60f62a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/topics/Datetimes/186/books.py | 1,255 | 3.640625 | 4 | ____ d__ _______ d__
____ d__.p.. _______ p..
# work with a static date for tests, real use = datetime.now()
NOW d__(2019, 3, 17, 16, 28, 42, 966663)
WEEKS_PER_YEAR 52
___ get_number_books_read books_per_year_goal i..
at_date s.. N.. __ i..
"""Based on books_per_year_goal and at_date, return the
number of books that should have been read.
If books_per_year_goal negative or 0, or at_date is in the
past, raise a ValueError."""
in_date NOW __ at_date __ N.. ____ p..(at_date)
__ books_per_year_goal <_ 0 o. in_date < NOW:
r.. V...
# TODOs
# 1. use dateutil's parse to convert at_date into a
# datetime object
# 2. check books_per_year_goal and at_date and raise
# a ValueError if goal <= 0 or at_date in the past (< NOW)
# 3. check the offset of at_date in the year ("week of the
# year" - e.g. whatweekisit.com) and based on the books_per_year_goal,
# calculate the number of books that should have been read / completed
#print(in_date)
#print(type(in_date.isocalendar()[1]))
r.. i..((in_date.isocalendar()[1]/52)*books_per_year_goal)
#print(NOW)
print(get_number_books_read(52, 'Sunday, March 18th, 2019'
#get_number_books_read(52) |
5335830eee81de3bf01a54a70432f593654252a7 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Learning Python/028_008_Namespace Links.py | 782 | 3.515625 | 4 | # ### File: classtree.py
#
# """
# Climb inheritance trees using namespace links,
# displaying higher superclasses with indentation
# """
#
# ___ classtree ___ indent
# print('.' * i... + ___. -n # Print class name here
# ___ supercls i_ ___. -b # Recur to all superclasses
# c.. s.., i..+3 # May visit super > once
#
# ___ instancetree inst
# print('Tree of *_' / i.. # Show instance
# cl... i__. -c 3 # Climb to its class
#
# ___ selftest
# c_ A: pass
# c_ B(A): pass
# c_ C(A): pass
# c_ D(B,C): pass
# c_ E: pass
# c_ F(D,E): pass
# i... B
# i... F
#
# __ _______ __ _______
# s..
#
#
#
#
# c_ Emp p___
#
# c_ Person Emp p..
# bob = ?
#
# import classtree
# ?.i... ?
#
#
|
dd857cdd956437eba2ac2bd9f395c2e5a8eb6f4f | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Python 3 Most Necessary/13.1.Listing 13.1. Creating a class definition.py | 689 | 3.796875 | 4 | # -*- coding: utf-8 -*-
class MyClass:
def __init__(self): # Конструктор
self.x = 10 # Атрибут экземпляра класса
def print_x(self): # self — это ссылка на экземпляр класса
print(self.x) # Выводим значение атрибута
c = MyClass() # Создание экземпляра класса
# Вызываем метод print_x()
c.print_x() # self не указывается при вызове метода
print(c.x) # К атрибуту можно обратиться непосредственно |
c5b6f4d3d3de4708ba6f18ebb5923b17b8e4ed63 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/149 Max Points on a Line.py | 4,502 | 3.5 | 4 | """
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
"""
__author__ 'Danyang'
#Definition for a point
c_ Point:
___ - , a=0, b=0
"""
:param a: int
:param b: int
:return:
"""
x a
y b
c_ Solution:
___ maxPoints_complicated points
"""
:param points: a list of Points
:return: int
"""
hash_map # dict # key -> inner_dict, where key = (k, b), inner_dict is index -> list
length l..(points)
___ i __ x..(length
___ j __ x..(i+1, length
point1 points[i]
point2 points[j]
__ point1.x __ point2.x:
key (1 << 32, point1.x)
____
slope f__(point1.y-point2.y)/(point1.x-point2.x)
intersection slope*point1.x - point1.y
slope i..(slope*1000) # avoid numeric errors
intersection i..(intersection*1000) # avoid numeric errors
key (slope, intersection) # only tuples can be hashed, whereas lists cannot
__ key n.. __ hash_map:
hash_map[key] [0 ___ _ __ points]
hash_map[key][i] 1 # avoid duplicate
hash_map[key][j] 1
__ (length<_1
r.. length
__(l..(hash_map)__0
r.. 0
maxa -1<<32
___ key, item __ hash_map.i..
# current = len(filter(lambda x: x==1, item)) # increase complexity
current item.c.. 1)
__ current>maxa:
maxa current
r.. maxa
___ maxPoints points
"""
reference: http://fisherlei.blogspot.sg/2013/12/leetcode-max-points-on-line-solution.html
:param points: a list of Points
:return: int
"""
maxa -1<<32
length l..(points)
__ (length<_1
r.. length
___ i __ x..(length
hash_map # dict
duplicate 1 # point_i itself
___ j __ x..(length
__ i__j:
_____
point1 points[i]
point2 points[j]
__ point1.x__point2.x a.. point1.y__point2.y:
duplicate += 1
_____
__ point1.x__point2.x:
key 1<<32
____
slope f__(point1.y-point2.y)/(point1.x-point2.x)
slope i..(slope*10000) # avoid numeric errors
# no need to calculate intersection. During this iteration, all lines pass point1
key slope
__ key n.. __ hash_map:
hash_map[key] 0
hash_map[key]+=1
__ hash_map:
max_key m..(hash_map, key=hash_map.get)
max_value hash_map[max_key]
____
max_value = 0
maxa m..(maxa, max_value+duplicate)
r.. maxa
__ _____ __ ____
points [(560, 248), (0, 16), (30, 250), (950, 187), (630, 277), (950, 187), (-212, -268), (-287, -222), (53, 37),
(-280, -100), (-1, -14), (-5, 4), (-35, -387), (-95, 11), (-70, -13), (-700, -274), (-95, 11), (-2, -33),
(3, 62), (-4, -47), (106, 98), (-7, -65), (-8, -71), (-8, -147), (5, 5), (-5, -90), (-420, -158),
(-420, -158), (-350, -129), (-475, -53), (-4, -47), (-380, -37), (0, -24), (35, 299), (-8, -71), (-2, -6),
(8, 25), (6, 13), (-106, -146), (53, 37), (-7, -128), (-5, -1), (-318, -390), (-15, -191), (-665, -85),
(318, 342), (7, 138), (-570, -69), (-9, -4), (0, -9), (1, -7), (-51, 23), (4, 1), (-7, 5), (-280, -100),
(700, 306), (0, -23), (-7, -4), (-246, -184), (350, 161), (-424, -512), (35, 299), (0, -24), (-140, -42),
(-760, -101), (-9, -9), (140, 74), (-285, -21), (-350, -129), (-6, 9), (-630, -245), (700, 306), (1, -17),
(0, 16), (-70, -13), (1, 24), (-328, -260), (-34, 26), (7, -5), (-371, -451), (-570, -69), (0, 27),
(-7, -65), (-9, -166), (-475, -53), (-68, 20), (210, 103), (700, 306), (7, -6), (-3, -52), (-106, -146),
(560, 248), (10, 6), (6, 119), (0, 2), (-41, 6), (7, 19), (30, 250)]
points [Point(point[0], point[1]) ___ point __ points]
print Solution().maxPoints(points)
... Solution().maxPoints(points)__22 |
ee61d59b5c973aa7e2a71fe4c9b424658c461a7e | syurskyi/Python_Topics | /115_testing/examples/The_Ultimate_Python_Unit_Testing_Course/Section 4 Coding Challenge #1 - Testing Functions/tests/test_chanllege.py | 1,431 | 3.6875 | 4 | import unittest
from challenge import counter
class EasyTestCase(unittest.TestCase):
def test_easy_input(self):
# Todo: make sure that your program returns 2 given the string 'Mo'
self.assertEqual(counter('Mo'), 2)
def test_easy_input_two(self):
# Todo: make sure that your program returns 8 given the string 'Mohammad'
self.assertEqual(counter('Mohammad'), 8)
class MediumTestCase(unittest.TestCase):
def test_medium_input(self):
# Todo: make sure that the program raises an exception whenever there is any non-english charts. Ex. !@#$%^.
with self.assertRaises(Exception):
self.assertEqual(counter('Mo?'), 2)
def test_medium_input_two(self):
# Todo: make sure that your program does not count paces. It should only count english alpha.
# with self.assertRaises(Exception):
self.assertEqual(counter('Mohammad Mahjoub'), 15)
class HardTestCase(unittest.TestCase):
def test_hard_input(self):
# Todo: make sure that the program raises an exception whenever an empty string is given.
with self.assertRaises(Exception):
self.assertEqual(counter(' '), 0)
def test_hard_input_two(self):
# Todo: make sure that your program does not accept a None input.
with self.assertRaises(Exception):
self.assertEqual(counter(None), 0)
if __name__ == '__main__':
unittest.main()
|
831a963bfc1edcc21568b45528a30db38ddd8eb7 | syurskyi/Python_Topics | /060_context_managers/_exercises/100. Not just a Context Manager.py | 2,710 | 3.703125 | 4 | # # Just because our class implements the context manager protocol does not mean it cannot do other things as well!
# # In fact the open function we use to open files can be used with or without a context manager:
#
# print('#' * 52 + ' ### Not Just a Context Manager')
#
# f _ o.. test.txt '_'
# f.w..l.. 'this is a test'
# f.c..
#
# # Here we did not use a context manager - the open function simply returned the file object - but we had to close
# # the file ourselves - there was not context used.
# # On the other hand we can also use it with a context manager:
#
# print('#' * 52 + ' On the other hand we can also use it with a context manager:')
#
# w___ o.. test.txt a_ f
# print(f.r.l.
# # ['this is a test']
# # ######################################################################################################################
#
# print('#' * 52 + ' We can implement classes that implement their own functionality'
# ' as well as a context manager if we want to.')
#
# # We can implement classes that implement their own functionality as well as a context manager if we want to.
#
# c_ DataIterator:
# ___ __i______ fname
# ____._f.. _ f..
# ____._f _ N..
#
# ___ __i__ ____
# r_ ____
#
# ___ __n__ ____
# row _ n.. ____._f
# r_ ro_.st.. '\n' .sp.. ','
#
# ___ __e__ ____)
# ____._f _ o... ____._fn..
# r_ ____
#
# ___ __e__ ____ exc_type exc_value exc_tb
# i_ n.. ____._f.c..
# ____._f.c..
# r_ F...
#
#
# w___ D... 'nyc_parking_tickets_extract.csv' a_ data
# ___ row i_ d..
# print r..
#
# print('#' * 52 + ' Of course, we cannot use this iterator without also using the context manager'
# ' since the file would not be opened otherwise:')
#
# data _ D... 'nyc_parking_tickets_extract.csv'
#
# # for row in data:
# # print(row) # TypeError: 'NoneType' object is not an iterator
# # ######################################################################################################################
#
# # But I want to point out that creating the context manager and using the with statement can be done in two steps
# # if we want to:
# print('#' * 52 + ' But I want to point out that creating the context manager and using the `with` statement'
# ' can be done in two steps if we want to:')
#
# data_iter _ D.. 'nyc_parking_tickets_extract.csv'
#
# # At this stage, the object has been created, but the __enter__ method has not been called yet.
# # Once we use with, then the file will be opened, and the iterator will be ready for use:
#
# w... d._i. a_ data
# ___ row i_ d..
# print r..
#
|
1dde8cb11156223aecd6a4a81853f4045270155d | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/299_v4/base_converter.py | 780 | 4.34375 | 4 | def digit_map(num):
"""maps numbers greater than a single digit to letters (UPPER)"""
return chr(num + 55) if num > 9 else str(num)
def convert(number: int, base: int = 2) -> str:
"""Converts an integer into any base between 2 and 36 inclusive
Args:
number (int): Integer to convert
base (int, optional): The base to convert the integer to. Defaults to 2.
Raises:
Exception (ValueError): If base is less than 2 or greater than 36
Returns:
str: The returned value as a string
"""
if base < 2 or base > 36:
raise ValueError
digits = []
while number > 0:
digits.append(number % base)
number //= base
digits = list(map(digit_map, digits))
return ''.join(reversed(digits))
|
84e80040d8810125c7e40338d95c3e292e9f0ec5 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+89 How to Raise Exceptions.py | 131 | 3.953125 | 4 | x ['a','b','c','d','e']
y input("Insert a letter: ")
__ y __ x:
print(1)
____:
r.. ValueError("Letter does not exist!")
|
c26969bd41bbf3ee69cd7b2dbfefe18866603861 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Backtracking/52_NQueensII.py | 2,093 | 3.703125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
countNQueens = 0
def totalNQueens(self, n):
self.countNQueens = 0
cols_used = [-1 for i in range(n)]
self.solveNQueens(0, cols_used, n)
return self.countNQueens
def solveNQueens(self, row, cols_used, n):
for col in range(n):
if self.isValid(row, col, cols_used, n):
if row == n - 1:
self.countNQueens += 1
return
cols_used[row] = col
self.solveNQueens(row + 1, cols_used, n)
cols_used[row] = -1
def isValid(self, row, col, cols_used, n):
""" Can check isvalid with using hash, implemented by c++.
Refer to:
https://discuss.leetcode.com/topic/13617/accepted-4ms-c-solution-use-backtracking-and-bitmask-easy-understand
The number of columns is n, the number of 45° diagonals is 2 * n - 1,
the number of 135° diagonals is also 2 * n - 1.
When reach [row, col], the column No. is col,
the 45° diagonal No. is row + col and the 135° diagonal No. is n - 1 + col - row.
| | | / / / \ \ \
O O O O O O O O O
| | | / / / / \ \ \ \
O O O O O O O O O
| | | / / / / \ \ \ \
O O O O O O O O O
| | | / / / \ \ \
3 columns 5 45° diagonals 5 135° diagonals (when n is 3)
"""
for i in range(row):
# Check for the according col above the current row.
if cols_used[i] == col:
return False
# Check from left-top to right-bottom
if cols_used[i] == col - row + i:
return False
# Check from right-top to left-bottom
if cols_used[i] == col + row - i:
return False
return True
"""
1
5
8
"""
|
3a3600127741a8b4970e5295538eb6b4db2156b8 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/910 Smallest Range II.py | 1,867 | 3.703125 | 4 | #!/usr/bin/python3
"""
Given an array A of integers, for each integer A[i] we need to choose either
x = -K or x = K, and add x to A[i] (only once).
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B and the
minimum value of B.
Example 1:
Input: A = [1], K = 0
Output: 0
Explanation: B = [1]
Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Example 3:
Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
"""
____ t___ _______ L..
c_ Solution:
___ smallestRangeII A: L..[i..], K: i.. __ i..
"""
Say A[i] is the largest i that goes up. A[i+1] would be the smallest
goes down
Then A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K
"""
A.s..()
mn m..(A)
mx m..(A)
ret mx - mn
___ i __ r..(l..(A) - 1
cur_mx m..(mx - K, A[i] + K)
cur_mn m..(mn + K, A[i+1] - K)
ret m..(ret, cur_mx - cur_mn)
r.. ret
___ smallestRangeII_error A: L..[i..], K: i.. __ i..
"""
find the min max is not enough, since the min max after +/- K may change
"""
mini m..(A)
maxa m..(A)
# mini + K, maxa - K
B # list
max_upper_diff 0
max_lower_diff 0
upper m..(mini + K, maxa - K) # may cross
lower m..(mini + K, maxa - K)
___ a __ A:
diffs [(a + K) - upper, lower - (a - K)]
cur_diff m..(diffs)
__ cur_diff __ diffs[0] a.. cur_diff >_ max_upper_diff:
max_upper_diff cur_diff
____ cur_diff __ diffs[1] a.. cur_diff >_ max_lower_diff:
max_lower_diff cur_diff
r.. upper + max_upper_diff - (lower + max_lower_diff)
|
ebfd4ced041ba4376999eabe481caec712b356f2 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/AddTowNumbersII.py | 3,449 | 3.96875 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
这次给定的正序排列的,而且不允许翻转链表。
思路:
先遍历一遍,为短的一个链表填充0。
(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
↓
(7 -> 2 -> 4 -> 3) + (0 -> 5 -> 6 -> 4)
之后用递归:
def x(l1, l2):
# 退出的条件是 l1 和 l2 均为 None.
# 当然因为事先做了长度相同的处理这里判断一个即可。
# 返回的是 (rest, ListNode)
if l1 is None:
return (0, None)
nextValue = x(l1.next, l2.next)
get_value = getValue(l1, l2, nextValue[0])
myNode = ListNode(get_value[0])
myNode.next = nextValue[1]
return (get_value[1], myNode)
之后在最外层做一次rest判断。
Ok,一遍过,beat 89%.
还有一种方法是不断 * 10,相加后不断 % 10, // 10。
效率都是一样的。
测试地址:
https://leetcode.com/problems/add-two-numbers-ii/description/
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1, l2 = self.getEqualNodes(l1, l2)
# return l1, l2
result = self._addTwoNumbers(l1, l2)
if result[0]:
node = ListNode(result[0])
node.next = result[1]
return node
return result[1]
def _addTwoNumbers(self, l1, l2):
if l1 is None:
return (0, None)
nextValue = self._addTwoNumbers(l1.next, l2.next)
get_value = self.getRest(l1, l2, nextValue[0])
myNode = ListNode(get_value[0])
myNode.next = nextValue[1]
return (get_value[1], myNode)
# get_value = self.getRest()
def getEqualNodes(self, l1, l2):
# Get equal length.
b_l1 = l1
b_l2 = l2
while b_l1 is not None and b_l2 is not None:
b_l1 = b_l1.next
b_l2 = b_l2.next
if b_l1:
# l1 is longer than l2
t_lx = b_l1
fix_lx = l2
raw_lx = l1
else:
t_lx = b_l2
fix_lx = l1
raw_lx = l2
if t_lx:
root = ListNode(0)
b_root = root
t_lx = t_lx.next
while t_lx:
node = ListNode(0)
root.next = node
root = node
t_lx = t_lx.next
root.next = fix_lx
return (raw_lx, b_root)
return (l1, l2)
def getRest(self, l1, l2, rest=0):
# return (val, rest)
# 9+8 (7, 1)
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
return ((l1_val + l2_val + rest) % 10, (l1_val + l2_val + rest) // 10)
|
38a9936f1417ee98bedafae7b7f8d2a23c328c22 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Stack/32_LongestValidParentheses.py | 1,145 | 3.671875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def longestValidParentheses(self, s):
"""
According to:
https://leetcode.com/discuss/7609/my-o-n-solution-using-a-stack
If current character is '(', push its index to the stack.
If current character is ')':
1. top of stack is '(', just find a matching pair so pop from the stack.
2. Otherwise, we push the index of ')' to the stack.
Finally the stack will only contain the indices of characters which cannot be matched.
Then the substring between adjacent indices should be valid parentheses.
"""
stack, longest = [0], 0
for i in xrange(1, len(s)):
if s[i] == '(':
stack.append(i)
else:
if stack and s[stack[-1]] == '(':
stack.pop()
valid_len = (i - stack[-1]) if stack else i + 1
longest = max(longest, valid_len)
else:
stack.append(i)
return longest
"""
""
")"
"()"
"))"
"(((()()()))("
"(((()()()))())"
"""
|
2320ff2a2f62a49a58ed296a3886563432f3132f | syurskyi/Python_Topics | /070_oop/004_inheritance/_exercises/templates/super/Python Super/002_ Single Inheritance.py | 2,396 | 4.28125 | 4 | # # Inheritance is the concept in object-oriented programming in which a class derives (or inherits) attributes
# # and behaviors from another class without needing to implement them again.
#
# # See the following program.
#
# # app.py
#
# c_ Rectangle
# __ - length width
# ? ?
# ? ?
#
# __ area
# r_ ? * ?
#
# __ perimeter
# r_ 2 * l.. + 2 * w..
#
#
# c_ Square
# __ - length
# ? ?
#
# __ area
# r_ l.. * l..
#
# __ perimeter
# r_ 4 * l..
#
#
# sqr _ S.. 4
# print("Area of Square is:", ?.a..
#
# rect _ R.. 2 4
#
# # See the output.
# #
# # pyt python3 app.py
# # Area of Square is: 16
# # Area of Rectangle is: 8
# # pyt
#
# # In the above example, you have two shapes that are related to each other: The square is, which is the particular
# # kind of rectangle.
# #
# # The code, however, doesn't reflect the relationship between those two shapes and thus has code that is necessarily
# # repeated. We need to apply basic code principles like Do not repeat yourself.
# #
# # By using the proper way of inheritance, you can reduce the amount of code you write while simultaneously
# # reflecting the real-world relationship between those shapes like rectangles and squares.
#
# # app.py
#
# c_ Rectangle
# __ - lengt width
# ? ?
# ? ?
#
# __ area
# r_ ? * ?
#
# __ perimeter
# r_ 2 * ? + 2 * ?
#
# c_ Square R..
# __ - length
# s__. - l.. l..
#
#
# sqr _ S.. 4
# print("Area of Square is:" ?.a..
#
# rect _ R. 2 4
# print("Area of Rectangle is:" ?.a..
#
# # In this example, a Rectangle is a superclass, and Square is a subclass because the Square and Rectangle __init__()
# # methods are so related, we can call a superclass's __init__() method (Rectangle.__init__()) from that of Square
# # by using a super() keyword.
# #
# # This sets the length and width attributes even though you just had to supply the single length parameter to a Square constructor.
# #
# # When you run this, even though your Square class doesn't explicitly implement it, the call to .area() will use
# # an area() method in the superclass and print 16.
# #
# # The Square class inherited .area() from the Rectangle class.
# #
# # See the output.
# #
# # pyt python3 app.py
# # Area of Square is: 16
# # Area of Rectangle is: 8
# # pyt
# # It is the same as above.
#
|
961312152de7cdc52600dbbce3f98d379605f5a4 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/159/calculator.py | 724 | 4.125 | 4 | # _______ o..
#
# ___ simple_calculator calculation
# """Receives 'calculation' and returns the calculated result,
#
# Examples - input -> output:
# '2 * 3' -> 6
# '2 + 6' -> 8
#
# Support +, -, * and /, use "true" division (so 2/3 is .66
# rather than 0)
#
# Make sure you convert both numbers to ints.
# If bad data is passed in, raise a ValueError.
# """
# ___
# num1 op num2 ?.s.. " "
# num1, num2 i.. ? i.. ?
# ______ V..
# r.. V...
#
# ops
# "+": o__.a..
# "-": o__.s..
# "*": o__.m..
# "/": o__.t..
#
#
# ___
# r.. ? o. ? ?
# ______ K.. Z..
# r.. V...
#
#
# __ _______ __ _______
# print ? "2 * 3" |
7cd8898e0e3005975525306f1622e0d54d94136b | syurskyi/Python_Topics | /140_gui/pyqt_pyside/examples/PyQt5/Chapter13_Running Python Scripts on Android and iOS/demoMultipleSelection.py | 573 | 3.578125 | 4 | import android
app = android.Android()
app.dialogCreateAlert("Select your food items")
app.dialogSetMultiChoiceItems(['Pizza', 'Burger', 'Hot Dog'])
app.dialogSetPositiveButtonText('Done')
app.dialogShow()
app.dialogGetResponse()
response = app.dialogGetSelectedItems()
print(response)
selectedResult=response[1]
n=len(selectedResult)
print("You have selected following food items: ")
for i in range(0, n):
if selectedResult[i]==0:
print("Pizza")
elif selectedResult[i]==1:
print("Burger")
elif selectedResult[i]==2:
print("Hot Dog")
|
354ed6c7930439d2e79545bf55140158e4b16571 | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Test_Mock_Same_Patch.py | 2,770 | 3.578125 | 4 | # Python Test Mock
# unittest.mock � mock object library
# unittest.mock is a library for testing in Python.
# It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
# unittest.mock provides a core Mock class removing the need to create a host of 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.
#
#
# Applying the same patch to every test method:
#
# If you want several patches in place for multiple test methods the obvious way is to apply the patch decorators to every method.
# This can feel like unnecessary repetition. For Python 2.6 or more recent you can use patch() (in all its various forms) as a class decorator.
# This applies the patches to all test methods on the class.
# A test method is identified by methods whose names start with test:
#
?p..('mymodule.SomeClass')
c_ MyTest(T..
___ test_one MockSomeClass
assertIs(mymodule.SomeClass, MockSomeClass)
___ test_two MockSomeClass
assertIs(mymodule.SomeClass, MockSomeClass)
___ not_a_test
r_ 'something'
MyTest('test_one').test_one()
MyTest('test_two').test_two()
MyTest('test_two').not_a_test()
# OUTPUT: 'something'
#
# An alternative way of managing patches is to use the patch methods: start and stop.
# These allow you to move the patching into your setUp and tearDown methods.
#
c_ MyTest(T..
___ setUp
patcher _ patch('mymodule.foo')
mock_foo _ patcher.start()
___ test_foo
assertIs(mymodule.foo, mock_foo)
___ tearDown
patcher.stop()
MyTest('test_foo').run()
#
# If you use this technique you must ensure that the patching is �undone� by calling stop.
# This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. unittest.TestCase.addCleanup()
# makes this easier:
#
c_ MyTest(T..
___ setUp
patcher _ patch('mymodule.foo')
addCleanup(patcher.stop)
mock_foo _ patcher.start()
___ test_foo
assertIs(mymodule.foo, mock_foo)
MyTest('test_foo').run()
|
ba9e2387988e23705a9539d684650e4bc759fd9d | syurskyi/Python_Topics | /115_testing/examples/The_Ultimate_Python_Unit_Testing_Course/Section 3 Testing Functions/first_project.py | 258 | 4 | 4 | def avg(*list_numbers: float) -> float:
total = 0
for num in list_numbers:
if isinstance(num, (int, float)):
total += num
else:
raise TypeError("Wrong input data. Please make sure that everything is a number. ")
return total / len(list_numbers)
|
262ad1be65d99d0c1f3a8b681e9667ccade6f919 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/284/pascal_triangle.py | 361 | 3.609375 | 4 | from typing import List
def pascal(N: int) -> List[int]:
current_row = [1]
for _ in range(N - 1):
new_row = [1]
for i in range(0,len(current_row) - 1):
new_row.append(current_row[i] + current_row[i +1])
new_row.append(1)
current_row = new_row
return current_row
|
c6621220c758d9a85e9ec856d95a1c91a57aa809 | syurskyi/Python_Topics | /120_design_patterns/020_state/examples/8-python-design-patterns-building-more-m8-exercise-files/State/empty.py | 511 | 3.546875 | 4 | from abs_state import AbsState
class Empty(AbsState):
def add_item(self):
self._cart.items += 1
print('You added the first item')
self._cart.state = self._cart.not_empty
def remove_item(self):
print('Your cart is empty! Nothing to remove!!')
def checkout(self):
print("Your cart is empty. Go shopping!")
def pay(self):
print("Your cart is empty. How did you get here?")
def empty_cart(self):
print("Your cart is already empty.")
|
5f905b04ff0f16e20c86b5ec77de3e99deae2a21 | syurskyi/Python_Topics | /110_concurrency_parallelism/002_threads/_exercises/exercises/Module Threading overview/012 - Thread.join.py | 2,064 | 4.0625 | 4 | import threading, time
def worker(i):
n = i + 1
print(f'Запуск потока №{n}')
time.sleep(2)
print(f'Поток №{n} выполнился.')
for i in range(2):
thread = threading.Thread(target=worker, args=(i,))
thread.start()
# если присоединять 'thread.join()' потоки здесь,
# то они будут запускаться по очереди, т.к.
# основной поток программы будет ждать конца
# выполнения присоединенного потока, прежде
# чем запустить следующий
print('Потоки запущены, основной поток программы так же выполняется')
# получаем экземпляр основного потока
main_thread = threading.main_thread()
# объединим потоки, что бы дождаться их выполнения
for t in threading.enumerate():
# Список 'threading.enumerate()' включает в себя основной
# поток и т.к. присоединение основного потока самого к себе
# вызывает взаимоблокировку, то его необходимо пропустить
if t is main_thread:
continue
print(f'Ожидание выполнения потока {t.name}')
t.join()
print('Основной поток программы после ожидания продолжает работу')
# Запуск потока №1
# Запуск потока №2
# Потоки запущены, основной поток программы так же выполняется
# Ожидание выполнения потока Thread-1
# Поток №2 выполнился.
# Поток №1 выполнился.
# Ожидание выполнения потока Thread-2
# Основной поток программы после ожидания продолжает работу |
dc8846f3e74b784dcee36049f2735d7dd2ae3c4d | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/581 Shortest Unsorted Continuous Subarray.py | 2,052 | 4.3125 | 4 | #!/usr/bin/python3
"""
Given an integer array, you need to find one continuous subarray that if you
only sort this subarray in ascending order, then the whole array will be sorted
in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the
whole array sorted in ascending order.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
"""
____ t___ _______ L..
c_ Solution:
___ findUnsortedSubarray nums: L.. i.. __ i..
"""
Sorted at both ends
Then search for the two ends by nums[i+1] > nums[i] on the left side
(right side similar)
Problem: may over-include, consider 1 2 5 9 4 6 ...
need to shrink from 1 2 5 9 to 1 2 according to min value
nums[lo - 1] <= min && max <= nums[hi + 1]
"""
n l..(nums)
lo, hi 0, n - 1
w.... lo < hi a.. nums[lo] <_ nums[lo + 1]:
lo += 1
w.... lo < hi a.. nums[hi - 1] <_ nums[hi]:
hi -_ 1
__ hi <_ lo:
r.. 0
mini f__('inf')
maxa -f__('inf')
___ i __ r..(lo, hi + 1
mini m..(mini, nums[i])
maxa m..(maxa, nums[i])
w.... lo - 1 >_ 0 a.. nums[lo - 1] > mini:
lo -_ 1
w.... hi + 1 < n a.. nums[hi + 1] < maxa:
hi += 1
r.. hi - lo + 1
___ findUnsortedSubarray_sort nums: L.. i.. __ i..
"""
Brute force sort and compare O(n lgn)
"""
e.. l..(s..(nums
i 0
w.... i < l..(nums) a.. nums[i] __ e..[i]:
i += 1
j l..(nums) - 1
w.... j >_ i a.. nums[j] __ e..[j]:
j -_ 1
r.. j - i + 1
__ _______ __ _______
... Solution().findUnsortedSubarray([2, 1]) __ 2
... Solution().findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15]) __ 5
|
360c3a434eac8d2d88ad21b5c7d798da56172b02 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/802 Find Eventual Safe States.py | 2,256 | 3.828125 | 4 | #!/usr/bin/python3
"""
In a directed graph, we start at some node and every turn, walk along a directed
edge of the graph. If we reach a node that is terminal (that is, it has no
outgoing directed edges), we stop.
Now, say our starting node is eventually safe if and only if we must eventually
walk to a terminal node. More specifically, there exists a natural number K so
that for any choice of where to walk, we must have stopped at a terminal node in
less than K steps.
Which nodes are eventually safe? Return them as an array in sorted order.
The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length
of graph. The graph is given in the following form: graph[i] is a list of
labels j such that (i, j) is a directed edge of the graph.
Example:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.
Illustration of graph
Note:
graph will have length at most 10000.
The number of edges in the graph will not exceed 32000.
Each graph[i] will be a sorted list of different integers, chosen within the
range [0, graph.length - 1].
"""
____ t___ _______ L.., S..
c_ Solution:
___ eventualSafeNodes graph: L..[L..[i..]]) __ L.. i..
"""
detect cycle in the node
prune by nodes with no cycle
"""
visit: L..[i..] [0 ___ _ __ graph] # 0 not visted, 1 processing, 2 visited
acyclic: S..[i..] s..()
___ u __ r..(l..(graph:
__ visit[u] __ 0:
dfs(graph, u, visit, acyclic)
r.. [
u
___ u __ r..(l..(graph
__ u __ acyclic
]
___ dfs graph, cur, visit, acyclic
visit[cur] 1
___ nbr __ graph[cur]:
__ visit[nbr] __ 2:
__ nbr __ acyclic:
_____
____
_____
__ visit[nbr] __ 1:
_____
__ visit[nbr] __ 0 a.. n.. dfs(graph, nbr, visit, acyclic
_____
____
acyclic.add(cur)
visit[cur] 2
r.. T..
visit[cur] 2
r.. F..
__ _______ __ _______
... Solution().eventualSafeNodes([[1,2],[2,3],[5],[0],[5], # list,[]]) __ [2,4,5,6]
|
ccb13b4be8add167329e354bf2a16f3cc92f08ab | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/605 Can Place Flowers.py | 1,264 | 3.796875 | 4 | #!/usr/bin/python3
"""
Suppose you have a long flowerbed in which some of the plots are planted and
some are not. However, flowers cannot be planted in adjacent plots - they would
compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means
empty and 1 means not empty), and a number n, return if n new flowers can be
planted in it without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size.
"""
____ t___ _______ L..
c_ Solution:
___ canPlaceFlowers flowerbed: L..[i..], n: i.. __ b..
"""
greedy
"""
__ n __ 0:
r.. T..
___ i __ r..(l..(flowerbed:
__ (
flowerbed[i] !_ 1 a..
(i + 1 >_ l..(flowerbed) o. flowerbed[i+1] !_ 1) a..
(i - 1 < 0 o. flowerbed[i - 1] !_ 1)
n -_ 1
flowerbed[i] 1
__ n __ 0:
r.. T..
r.. F..
|
a84e29f50c480a6d7b1968a3005aa42da6080a3a | syurskyi/Python_Topics | /021_module_collection/chainmap/_exercises/exercises/chainmap_001_template.py | 9,849 | 4 | 4 | # # Remember the chain function i_ the itertools module? That allowed us to chain multiple iterables together to look like
# # a single iterable.
# #
# # The C... i_ the collections module is somewhat similar - it allows us to chain multiple dictionaries
# # (mapping types more generally) so it looks like a single mapping type. But there are some wrinkles:
# #
# # when we request a key lookup, what happens if the same key occurs i_ more than one dictionary?
# # we can actually up____, insert and delete elements from a C... - how does that work?
# #
# # Let's look at some simple examples where we do not have key collisions first:
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
#
# # Now we can always create a new dictionary that contains all those keys by using unpacking,
# # or even starting with an empty dictionary and updating it three times with each of the dicts d1, d2 and d3:
d = {**d1, **d2, **d3}
print(d)
# # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
#
# # or:
#
d = {}
d.update(d1)
d.update(d2)
d.update(d3)
print(d)
# # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
#
# # But i_ a way this is wasteful because we had to copy the data into a new dictionary.
# # Instead we can use C...:
#
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
d = ChainMap(d1, d2, d3)
print(d)
# C...({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
print(isinstance(d, dict))
# False
# So, the result is not a dictionary, but it is a mapping type that we can use almost like a dictionary:
d['a']
# 1
d['c']
# 3
for k, v in d.items():
print(k, v)
#
# # d 4
# # c 3
# # f 6
# # b 2
# # a 1
# # e 5
#
# # Note that the iteration order here, unlike a regular Python dictionary, is not guaranteed!
# # Now what happens if we have key 'collisions'?
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'b' 20 'c' 3
# d3 _ 'c' 30 'd' 4
# d _ C... d1 d2 d3
#
# print d 'b'
# # 2
#
# print d'c'
# # 3
#
# # As you can see, the value returned corresponds to the the value of the first key found i_ the chain. (
# # So note the difference between this and when we unpack the dictionaries into a new dictionary, where the "last" key
# # effectively overwrite any "previous" key.)
# # i_ fact, if we iterate through all the it.., you'll notice that, as we would expect from a mapping type,
# # we do not have duplicate keys, and moreover the associated value is the first one encountered i_ the chain:
#
# ___ k v i_ d.it..
# print k v
#
# # d 4
# # c 3
# # b 2
# # a 1
#
# # Now let's look at how C... objects handle inserts, deletes and updates:
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'c' 3 'd' 4
# d3 _ 'e' 5 'f' 6
# d _ C... d1 d2 d3
# d['z'] _ 100
# print(d)
# # C...({'a': 1, 'b': 2, 'z': 100}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
#
# # As you can see the element 'z': 100 was added to the chain map. But what about the underlying dictionaries
# # that make up the map?
#
# print(d1)
# print(d2)
# print(d3)
#
# # {'a': 1, 'b': 2, 'z': 100}
# # {'c': 3, 'd': 4}
# # {'e': 5, 'f': 6}
#
# # When mutating a chain map, the first dictionary i_ the chain is used to handle the mutation - even updates:
# # Let's try to up____ c, which is i_ the second dictionary:
#
# d['c'] _ 300
# print(d)
#
# # C...({'a': 1, 'b': 2, 'z': 100, 'c': 300}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
#
# # As you can see the first dictionary i_ the chain was "updated" - since the key did not exist,
# # the key with the "updated" value was added to the underlying dictionary:
#
# print(d1)
# print(d2)
# print(d3)
#
# # {'a': 1, 'b': 2, 'z': 100, 'c': 300}
# # {'c': 3, 'd': 4}
# # {'e': 5, 'f': 6}
#
# # As you can see, a new element c was created i_ the first dict i_ the chain. When we view it from the chain map
# # perspective, it looks like c was updated because it was actually inserted i_ the first dict,
# # so that key is encountered i_ that dict first, and hence that new value is used.
# # What about deleting an item?
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'c' 3 'd' 4
# d3 _ 'e' 5 'f' 6
# d _ C... d1 d2 d3
#
# del d 'a'
# print l... d.it..
# # [('d', 4), ('f', 6), ('b', 2), ('c', 3), ('e', 5)]
#
# print(d1)
# print(d2)
# print(d3)
#
# # {'b': 2}
# # {'c': 3, 'd': 4}
# # {'e': 5, 'f': 6}
#
# # As you can see a was deleted from the first dict.
# # Something important to note here when deleting keys, is that deleting a key does not guarantee the key no
# # longer exists i_ the chain! It could exist i_ one of the parents, and only the child is affected:
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'a' 100
# d _ C... d1 d2
# d['a']
# # 1
#
# del d['a']
# d['a']
# # 100
#
# # Since we can only mutate the first dict i_ the chain, trying to delete an item that is present i_ the chain,
# # but not i_ the child will cause an exception:
#
# # del d['c'] # KeyError: "Key not found i_ the first mapping: 'c'"
#
# # A C... is built as a view on top of a sequence of mappings, and those maps are incorporated by reference.
# # This means that if an underlying map is mutated, then the C... instance will see the change:
#
# d1 _ {'a' 1 'b' 2
# d2 _ {'c' 3 'd' 4
# d3 _ {'e' 5 'f' 6
# d _ C... d1 d2 d3
# print l... d.it..
#
# # [('d', 4), ('c', 3), ('f', 6), ('b', 2), ('a', 1), ('e', 5)]
#
# d3['g'] _ 7
# print(l... d.it..
# # [('d', 4), ('g', 7), ('c', 3), ('f', 6), ('b', 2), ('a', 1), ('e', 5)]
#
# # We can even chain ChainMaps. ___ example, we can use this approach to "append" a new dictionary to a chain map,
# # i_ essence create a new chain map containing the maps from one chain map and adding one or more maps to the l...:
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'c' 3 'd' 4
# d _ C... d1 d2
# d3 _ 'd'400 'e' 5
# d _ C... d d3
# print(d)
# # C...(C...({'a': 1, 'b': 2}, {'c': 3, 'd': 4}), {'d': 400, 'e': 5})
#
# # Of course, we could place d3 i_ front:
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'c' 3 'd' 4
# d _ C... d1 d2
# d3 _ 'd' 400 'e' 5
# d _ C... d3 d
# print(d)
# # C...({'d': 400, 'e': 5}, C...({'a': 1, 'b': 2}, {'c': 3, 'd': 4}))
#
# # So the ordering of the maps i_ the chain matters!
# # Instead of adding an element to the beginning of the chain l... using the technique above,
# # we can also use the new_child method, which returns a new chain map with the new element added to the beginning of
# # the l...:
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'c' 3 'd' 4
# d _ C... d1 d2
# d3 _ 'd' 400 'e' 5
# d _ d.n.._c.. d3
# print(d)
# # C...({'d': 400, 'e': 5}, {'a': 1, 'b': 2}, {'c': 3, 'd': 4})
#
# # And as you can see the key d: 400 is i_ our chain map.
# # There is also a property that can be used to return every map i_ the chain except the first map:
#
# d1 _ {'a' 1 'b' 2
# d2 _ {'c' 3 'd' 4
# d3 _ {'e' 5 'f' 6
# d _ C... d1 d2 d3
# print(d)
# # C...({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
#
# d _ d.pa..
# print(d)
# # C...({'c': 3, 'd': 4}, {'e': 5, 'f': 6})
#
# # The chain map's l... of maps is accessible via the maps property:
#
# d1 _ 'a' 1 'b' 2
# d2 _ 'c' 3 'd' 4
# d _ C... d1 d2
# print ty.. d.ma.. d.ma..
# # (l..., [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}])
#
# # As you can see this is a l..., and so we can actually manipulate it as we would any l...:
#
# d3 _ 'e' 5 'f' 6
# d.ma__.ap.. d3
# print d.ma..
# # [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
#
# # We could equally well remove a map from the l... entirely, insert one wherever we want, etc:
#
# d.maps.in.. 0 'a' 100
# print d.ma..
# # [{'a': 100}, {'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
#
# print l... d.it..
# # [('d', 4), ('c', 3), ('f', 6), ('b', 2), ('a', 100), ('e', 5)]
#
# # As you can see a now has a value of 100 i_ the chain map.
# # We can also delete a map from the chain entirely:
#
# del d.ma.. 1
# print d.ma..
# # [{'a': 100}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
#
# # Example
# # A typical application of a chain map, apart from "merging" multiple dictionaries without incurring extra overhead
# # copying the data, is to create a mutable version of merged dictionaries that does not mutate the underlying
# # dictionaries.
# # Remember that mutating elements of a chain map mutates the elements of the first map i_ the l... only.
# # Let's say we have a dictionary with some settings and we want to temporarily modify these settings, but without
# # modifying the original dictionary.
# # We could certainly copy the dictionary and work with the copy, discarding the copy when we no longer need it -
# # but again this incurs some overhead copying all the data.
# # Instead we can use a chain map this way, by making the first dictionary i_ the chain a new empty dictionary -
# # any updates we make will be made to that dictionary only, thereby preserving the other dictionaries.
config = {
'host': 'prod.deepdive.com',
'port': 5432,
'database': 'deepdive',
'user_id': '$pg_user',
'user_pwd': '$pg_pwd'}
local_config = ChainMap({}, config)
print(list(local_config.items()))
# [('user_pwd', '$pg_pwd'),
# ('database', 'deepdive'),
# ('port', 5432),
# ('user_id', '$pg_user'),
# ('host', 'prod.deepdive.com')]
# And we can make changes to local_config:
local_config['user_id'] = 'test'
local_config['user_pwd'] = 'test'
print(list(local_config.items()))
# [('host', 'prod.deepdive.com'),
# ('database', 'deepdive'),
# ('port', 5432),
# ('user_id', 'test'),
# ('user_pwd', 'test')]
# But notice that our original dictionary is unaffected:
print(list(config.items()))
# [('host', 'prod.deepdive.com'),
# ('port', 5432),
# ('database', 'deepdive'),
# ('user_id', '$pg_user'),
# ('user_pwd', '$pg_pwd')]
# That's because the changes we made were reflected i_ the first dictionary i_ the chain - that empty dictionary:
print(local_config.maps)
# [{'user_id': 'test', 'user_pwd': 'test'},
# {'host': 'prod.deepdive.com',
# 'port': 5432,
# 'database': 'deepdive',
# 'user_id': '$pg_user',
# 'user_pwd': '$pg_pwd'}]
|
7b5a0849ccdf86762859091fc794e746027acab7 | syurskyi/Python_Topics | /045_functions/008_built_in_functions/zip/examples/005_Passing n Arguments.py | 307 | 3.90625 | 4 | numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
zipped # Holds an iterator object
# <zip object at 0x7fa4831153c8>
type(zipped)
# <class 'zip'>
list(zipped)
# [(1, 'a'), (2, 'b'), (3, 'c')]
s1 = {2, 3, 1}
s2 = {'b', 'a', 'c'}
list(zip(s1, s2))
# [(1, 'a'), (2, 'c'), (3, 'b')] |
81165ad590797c9cff487e643ab10c45e3cda4ad | syurskyi/Python_Topics | /115_testing/examples/ITVDN_Python_Advanced/007_Модульное тестирование/007_Samples/example4_simple.py | 1,158 | 3.96875 | 4 | import unittest
def sum_two_values(a, b):
return a + b
def power(x, n):
return x ** n
def concat_values(*args):
result = ''
for item in args:
result += str(item)
return result
def desc(x, y):
if x == 0:
raise ValueError('`x` should not be equal 0')
return y / x
class UtilsTestCase(unittest.TestCase):
def test_sum_two_values(self):
value1 = 10
value2 = 20
result = sum_two_values(value1, value2)
self.assertEqual(result, value1 + value2)
def test_power(self):
value = 2
st = 8
result = power(value, st)
expected_value = value ** st
self.assertEqual(result, expected_value)
def test_concat_values(self):
values = 1, 2, 3, 4
result = concat_values(*values)
expected_result = '1234'
self.assertEqual(result, expected_result)
def test_desc(self):
x, y = 10, 20
result = desc(x, y)
expected_result = y / x
self.assertEqual(result, expected_result)
def test_desc_with_zero(self):
with self.assertRaises(ValueError):
desc(0, 20)
|
7b08368a570b5d8225073e9729e254c81e71de1b | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/UnitTesting-master/Proj2/shapes.py | 823 | 3.5625 | 4 | ____ math ______ pi, cos, sin
c_ ShapesArea:
___ -
p..
___ value_check r
# Check to make sure user input is of acceptable type and value
__ ty..(r) no. __ [float, __.]:
r_ T..("Please enter a valid number greater than 0.")
__ r < 0:
r_ V..("Length from center to edge must be greater than 0.")
___ circle_area r
# Calculate the area of a circle with radius r
value_check(r)
r_ pi*(r**2)
___ triangle_area r
# Calculate the area of an equilateral triangle with center to corner length r
value_check(r)
r_ 1/2*(r*sin(pi/3)+r)*(r*cos(pi/3))
___ square_area r
# Calculate the area of a square with center to corner length r
value_check(r)
r_ 2*r*sin(pi/4)
|
c44520ab92e64dccd4856848075e9794ea1ff740 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/925 Long Pressed Name.py | 1,465 | 3.90625 | 4 | #!/usr/bin/python3
"""
Your friend is typing his name into a keyboard. Sometimes, when typing a
character c, the key might get long pressed, and the character will be typed 1
or more times.
You examine the typed characters of the keyboard. Return True if it is possible
that it was your friends name, with some characters (possibly none) being long
pressed.
Example 1:
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
Example 3:
Input: name = "leelee", typed = "lleeelee"
Output: true
Example 4:
Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.
Note:
name.length <= 1000
typed.length <= 1000
The characters of name and typed are lowercase letters.
"""
c_ Solution:
___ isLongPressedName name: s.., typed: s..) __ b..
"""
two pointers
"""
m, n l..(name), l..(typed)
i, j 0, 0
w.... i < m a.. j < n:
__ name[i] __ typed[j]:
i += 1
j += 1
____ j - 1 >_ 0 a.. typed[j-1] __ typed[j]:
j += 1
____
r.. F..
# tail
w.... j - 1 >_ 0 a.. j < n a.. typed[j-1] __ typed[j]:
j += 1
r.. i __ m a.. j __ n
|
f70d21c83d2a3358e063561e80f8b683efd22d7d | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/_properties_templates/Python_OOP_Object_Oriented_Programming/Section 14/Inheritance-Methods-Code/1 - Shape, Triangle, Circle.py | 653 | 3.515625 | 4 | # c_ Shape:
#
# ___ - color is_polygon description
# ____.? ?
# ____.? ?
# ____.? ?
#
# ___ display_data ____
# print(_*\n=== .d__.ca..| ===
# print("Color:", .c..
# print("Is the shape a polygon?", "Yes" if .i.. else "No")
#
# c_ Triangle ?
#
# ___ - color vertices base height
# ?. - c.. T.. "Triangle")
# ____.? ?
# ____.? ?
# ____.? ?
#
# c_ Circle ?
#
# ___ - ____ color radius
# ?. - c.. F.. "Circle")
# ____.? ?
#
#
# triangle = T..("red", [(-2, 0), (2, 0), (0, 7)], 4, 7)
# circle = C..("blue", 6.3)
#
# t__.d..
# c__.d..
#
|
e5d8d2c92b90ca3ee027e52fa3303be838e4ae6b | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BreadthFirstSearch/103_BinaryTreeZigzagLevelOrderTraversal.py | 815 | 3.90625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
if not root:
return []
left2right = 1
# 1. scan the level from left to right. -1 reverse.
ans, stack, temp = [], [root], []
while stack:
temp = [node.val for node in stack]
stack = [child for node in stack
for child in (node.left, node.right) if child]
ans += [temp[::left2right]] # Pythonic way
left2right *= -1
return ans
"""
[]
[1]
[1,2,3]
[0,1,2,3,4,5,6,null,null,7,null,8,9,null,10]
"""
|
94f25a94f89bd31421515bc201727e6530947fab | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/417 Pacific Atlantic Water Flow.py | 4,163 | 3.84375 | 4 | #!/usr/bin/python3
"""
Given an m x n matrix of non-negative integers representing the height of each
nit cell in a continent, the "Pacific ocean" touches the left and top edges of
the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to
another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and
Atlantic ocean.
Note:
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
Example:
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with
parentheses in above matrix).
"""
dirs ((0, 1), (0, -1), (1, 0), (-1, 0
c_ Solution:
___ pacificAtlantic matrix
"""
dfs, visisted O(1)
Similar to Trapping Rainwater II (BFS + heap), but no need to record
volume, thus, dfs is enough.
Similar to longest increasing path
Starting from the edge point rather than any point, dfs visit the
possible cell
Complexity analysis, although a cell can be checked multiple times
(at most 4 times); but only perform 1 dfs on each cell; thus
O(mn)
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
__ n.. matrix o. n.. matrix[0]:
r.. # list
m, n l..(matrix), l..(matrix 0 # row, col
# don't do [[False] * n ] * m, memory management, all rows reference the same row
P [[F.. ___ _ __ r..(n)] ___ _ __ r..(m)]
A [[F.. ___ _ __ r..(n)] ___ _ __ r..(m)]
# starting from edge point
___ i __ r..(m
dfs(matrix, i, 0, P)
dfs(matrix, i, n-1, A)
___ j __ r..(n
dfs(matrix, 0, j, P)
dfs(matrix, m-1, j, A)
ret [
[i, j]
___ i __ r..(m)
___ j __ r..(n)
__ P[i][j] a.. A[i][j]
]
r.. ret
___ dfs matrix, i, j, C
# check before dfs (to be consistent)
C[i][j] T..
m, n l..(matrix), l..(matrix 0
___ x, y __ dirs:
I i + x
J j + y
__ 0 <_ I < m a.. 0 <_ J < n a.. matrix[i][j] <_ matrix[I][J]:
__ n.. C[I][J]:
dfs(matrix, I, J, C)
___ pacificAtlantic_error matrix
"""
DP
dfs, visisted O(1)
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
__ n.. matrix o. n.. matrix[0]:
r.. # list
m, n l..(matrix), l..(matrix 0 # row, col
P [[F..] * n ] * m
A [[F..] * n ] * m
visisted [[F..] * n ] * m
___ i __ r..(m
___ j __ r..(n
dfs_error(matrix, i, j, visisted, P, l.... i, j: i < 0 o. j <0)
visisted [[F..] * n ] * m
___ i __ r..(m
___ j __ r..(n
dfs_error(matrix, i, j, visisted, A, l.... i, j: i >_ m o. j >_ n)
ret [
[i, j]
___ i __ r..(m)
___ j __ r..(n)
__ P[i][j] a.. A[i][j]
]
r.. ret
___ dfs_error matrix, i, j, visisted, C, predicate
m, n l..(matrix), l..(matrix 0
__ visisted[i][j]:
r.. C[i][j]
visisted[i][j] T..
___ x, y __ dirs:
i2 i + x
j2= j + y
__ 0 <_ i2 < m a.. 0 <_ j2 < n:
__ dfs_error(matrix, i2, j2, visisted, C, predicate) a.. matrix[i][j] >_ matrix[i2][j2]:
C[i][j] T..
____ predicate(i2, j2
C[i][j] T..
r.. C[i][j]
__ _______ __ _______
... Solution().pacificAtlantic([
[1,2,2,3,5],
[3,2,3,4,4],
[2,4,5,3,1],
[6,7,1,4,5],
[5,1,1,2,4]
]) __ [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]
|
555ed89f50df9e41ebaf09f27132f620c38cf7fa | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/129_rehashing.py | 879 | 3.765625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
c_ Solution:
"""
@param hash_table: A list of The first node of linked list
@return: A list of The first node of linked list which have twice size
"""
___ rehashing hash_table
__ n.. hash_table:
r..
CAPACITY l..(hash_table) * 2
heads [N..] * CAPACITY
tails [N..] * CAPACITY
curr _node i N..
___ node __ hash_table:
curr node
w.... curr:
i curr.val % CAPACITY
_node ListNode(curr.val)
__ heads[i]:
tails[i].next _node
____
heads[i] _node
tails[i] _node
curr curr.next
r.. heads
|
bd9859f05ef620d248fdfb970ca1b48e96118ec7 | syurskyi/Python_Topics | /045_functions/008_built_in_functions/sort/examples/004_Key also takes user-defined functions as its value for the basis of sorting..py | 278 | 3.890625 | 4 | # Sort a list of integers based on
# their remainder on dividing from 7
def func(x):
return x % 7
L = [15, 3, 11, 7]
print "Normal sort :", sorted(L)
print "Sorted with key:", sorted(L, key = func)
# Output :
# Normal sort : [3, 7, 11, 15]
# Sorted with key: [7, 15, 3, 11] |
eec917248b747e015e7dbc2f30c0340d1e8440b3 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/084_Largest_Rectangle_in_Histogram.py | 992 | 3.515625 | 4 | c_ Solution o..
___ largestRectangleArea heights
"""
:type heights: List[int]
:rtype: int
"""
# https://leetcode.com/discuss/70983/4ms-java-solution-using-o-n-stack-space-o-n-time
largest_rectangle = 0
ls = l.. heights)
# heights[stack[top]] > heights[pos] > heights[stack[top - 1]]
# keep the increase order
stack = [-1]
top, pos = 0, 0
___ pos __ r.. ls
w.. top > 0 a.. heights[stack[top]] > heights[pos]:
largest_rectangle = m..(largest_rectangle, heights[stack[top]] * (pos - stack[top - 1] - 1))
top -= 1
stack.pop()
stack.a.. pos)
top += 1
w.. top > 0:
largest_rectangle = m..(largest_rectangle, heights[stack[top]] * (ls - stack[top - 1] - 1))
top -= 1
r_ largest_rectangle
__ __name__ __ "__main__":
s ?
print s.largestRectangleArea([2,1,5,6,2,3])
|
3dd313538384bc7963aa08ed3bda52bffaf47228 | syurskyi/Python_Topics | /125_algorithms/002_linked_lists/_exercises/templates/Linked Lists/Linked Lists Interview Problems/PRACTICE/Singly Linked List Cycle Check.py | 1,451 | 4 | 4 | # # Singly Linked List Cycle Check
# # Problem
# # Given a singly linked list, write a function which takes in the first node in a singly linked list and returns
# # a boolean indicating if the linked list contains a "cycle".
# # A cycle is when a node's next point actually points back to a previous node in the list. This is also sometimes known
# # as a circularly linked list.
# # You've been given the Linked List Node class code:
# #
# c_ Node o..
#
# ___ - value
#
# ? ?
# nextnode _ N..
#
# # Solution
# # Fill out your solution:
# #
# ___ cycle_check node
# # Use fast and slow pointer
# fast, slow _ ? ?
# w__ f.. an. ?.n..
# f.. _ ?.n..
# __ f.. __ s..
# r_ T..
# f.. _ ?.n..
# s.. _ ?.n..
# r_ F..
# p.. #Your function should return a boolean
#
# # Test Your Solution
#
# """
# RUN THIS CELL TO TEST YOUR SOLUTION
# """
# from nose.tools import assert_equal
#
# # CREATE CYCLE LIST
# a = Node(1)
# b = Node(2)
# c = Node(3)
#
# a.nextnode = b
# b.nextnode = c
# c.nextnode = a # Cycle Here!
#
#
# # CREATE NON CYCLE LIST
# x = Node(1)
# y = Node(2)
# z = Node(3)
#
# x.nextnode = y
# y.nextnode = z
#
#
# #############
# c_ TestCycleCheck o..
#
# ___ test sol
# a_e.. ? a , T..
# a_e.. ? x , F..
#
# print ("ALL TEST CASES PASSED")
#
# # Run Tests
#
# t = TestCycleCheck()
# t.test(cycle_check)
# #
# # ALL TEST CASES PASSED
|
804d661b03b980700a07d8182ab1cf5e95d6d855 | syurskyi/Python_Topics | /012_lists/examples/ITVDN Python Starter 2016/08-string-indexing.py | 214 | 3.625 | 4 | # -*- coding: utf-8 -*-
# Создание строки
string = "a string"
# Вывод отдельных символов строки
print(string[0]) # 'a'
print(string[2]) # 's'
print(string[-1]) # 'g' |
2e80ba9976807b162b6dd922326df973cc8451c9 | syurskyi/Python_Topics | /140_gui/pyqt_pyside/examples/PyQt5/Chapter13_Running Python Scripts on Android and iOS/demoDialog.py | 649 | 3.546875 | 4 | import android
app = android.Android()
title = 'Understanding Dialog Buttons'
message = ('Do you want to Place the Order?')
app.dialogCreateAlert(title, message)
app.dialogSetPositiveButtonText('Yes')
app.dialogSetNegativeButtonText('No')
app.dialogSetNeutralButtonText('Cancel')
app.dialogShow()
response = app.dialogGetResponse().result
print(response)
app.dialogDismiss()
result=response["which"]
if result=="positive":
print ("You have selected Yes button")
elif result=="negative":
print ("You have selected No button")
elif result=="neutral":
print ("You have selected Cancel button")
else:
print ("Invalid response",response)
|
4cbe452c0972d738a2d511bac2a930e8675f5ce1 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/002_dictionary_comprehension/examples/007.py | 5,442 | 4.15625 | 4 | # List comprehension
# ==================
# new_list = [new_item for item in list_or_range]
numbers = [1, 2, 3, 4, 5]
new_numbers = [n + 1 for n in numbers]
print(new_numbers)
nato_phonetic_alphabet = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet",
"Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango",
"Uniform", "Victor", "Whisky", "X-ray", "Yankee", "Zulu"]
name = "John Patmore"
letters_list = [letter.upper() for letter in name]
print(letters_list)
double = [n * 2 for n in range(1, 5)]
print(double)
# Conditional list comprehension
# ==============================
# new_list = [new_item for item in list if test]
names = ["Alex", "Beth", "Caroline", "Dave", "Eleanor", "Freddie"]
short_name = [name for name in names if len(name) < 5]
print(short_name)
caps_names = [name.upper() for name in names if len(name) > 5]
print(caps_names)
# Tests
# =====
numbers = [1, 1]
for i in range(2, 10):
numbers.append(numbers[i-2] + numbers[i-1])
print(numbers)
squared_numbers = [n**2 for n in numbers] # ** = exponent operator
print(squared_numbers)
result = [n for n in numbers if n % 2 == 0]
print(result)
# Create a list called result which contains the numbers
# that are common in both files file1.txt and file2.txt.
# The result should be a list that contains Integers, not Strings.
with open("file1.txt") as file:
file1 = [int(n.strip()) for n in file.r..] # .r.. returns a list!
print(file1)
with open("file2.txt") as file:
file2 = [int(n.strip()) for n in file.r..] # .r.. returns a list!
print(file2)
result = [n for n in file1 if n in file2]
print(result)
# Dictionary Comprehension
# ========================
# new_dict = {new_key:newvalue for item in list}
# new_dict = {new_key:newvalue for item in list if test}
# new_dict = {new_key:newvalue for (key,value) in dict.items()}
# new_dict = {new_key:newvalue for (key,value) in dict.items() if test}
import random
names = ["Alex", "Beth", "Caroline", "Dave", "Eleanor", "Freddie"]
student_scores = {name: random.randint(0,100) for name in names}
print(student_scores)
for item in student_scores.items():
print(item)
# passed_students = {item[0]: item[1] for item in student_scores.items() if item[1] >= 60}
passed_students = {student: score for (student, score) in student_scores.items() if score >= 60}
print(passed_students)
# Tests
# =====
# Create a dictionary called result that takes each word in the given sentence
# and calculates the number of letters in each word
sentence = "What is the Airspeed Velocity of an Unladen Swallow?"
# Break sentence into words list
result = {word: len(word) for word in sentence.strip("?").split()}
print(result)
# Create a dictionary called weather_f that takes each temperature in degrees Celcius
# and converts it into degrees Fahrenheit.
weather_c = {
"Monday": 12,
"Tuesday": 14,
"Wednesday": 15,
"Thursday": 14,
"Friday": 21,
"Saturday": 22,
"Sunday": 24,
}
weather_f = {day: (C * 9 / 5 + 32) for (day, C) in weather_c.items()}
print(weather_f)
# Iterate over a Pandas DataFrame
# ===============================
# new_dict = {new_key:new_value for (index, row) in df.iterrows()}
student_dict = {
"student": ["Angela", "James", "Lily"],
"score": [56, 76, 98],
}
# Looping through dictionaries:
for (key, value) in student_dict.items():
print(key, value)
import pandas
# Create Pandas DataFrame
student_dataframe = pandas.DataFrame(student_dict)
print(student_dataframe)
# Looping through DataFrame
for (key, value) in student_dataframe.items():
print(key)
print(value)
# Pandas in-built loop - iterrows() - Loops through rows instead of columns
# Because iterrows returns a Series for each row, it does not preserve dtypes across the rows
# To preserve dtypes while iterating over the rows, it is better to use itertuples()
# which returns namedtuples of the values and which is generally faster than iterrows.
# You should never modify something you are iterating over.
# This is not guaranteed to work in all cases.
# Depending on the data types, the iterator returns a copy and not a view,
# and writing to it will have no effect.
for (index, row) in student_dataframe.iterrows():
print("row = \n", row) # Each row is a Pandas Series object
print("row.student = \n", row.student)
print("row.score = \n", row.score)
# Create dictionary from DataFrame
new_dict = {row.student: row.score for (index, row) in student_dataframe.iterrows()}
print(new_dict)
"""{'Angela': 56, 'James': 76, 'Lily': 98}"""
# Challenge
# =========
password_list = []
nr_letters = random.randint(8, 10)
nr_numbers = random.randint(2, 4)
nr_symbols = random.randint(2, 4)
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
symbols = ["!", "£", "$", "%", "^", "&", "*", "(", ")", "_"]
for char in range(nr_letters):
password_list.append(random.choice(letters))
# Convert the above for loop to a list comprehension
# new_list = [new_item for item in list if test]
pwd_letters = [random.choice(letters) for _ in range(nr_letters)]
pwd_numbers = [random.choice(numbers) for _ in range(nr_numbers)]
pwd_symbols = [random.choice(symbols) for _ in range(nr_symbols)]
password_list = pwd_letters + pwd_numbers + pwd_symbols |
281fab13317e229e8b7819c410b29c89d66bf562 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/873 Length of Longest Fibonacci Subsequence.py | 2,842 | 4.0625 | 4 | #!/usr/bin/python3
"""
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence,
find the length of the longest fibonacci-like subsequence of A. If one does not
exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any
number of elements (including none) from A, without changing the order of the
remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
"""
____ t___ _______ L..
c_ Solution:
___ lenLongestFibSubseq A: L.. i.. __ i..
"""
F[i][j] longest fib subsequence ending at A[i] with 2nd last element
A[j]
F[k][i] = F[i][j] + 1 if A[i] + A[j] = A[k]
O(N^2) * O(N) = O(N^3)
can be optimized to O(N^2) by look forward
"""
n l..(A)
F [[0 ___ _ __ r..(n)] ___ _ __ r..(n)]
___ i __ r..(n
F[i][i] 1
___ j __ r..(i
F[i][j] 2
idxes # dict
___ i __ r..(n
idxes[A[i]] i
___ i __ r..(n
___ j __ r..(i
Ak A[i] + A[j]
__ Ak __ idxes:
k idxes[Ak]
F[k][i] m..(F[k][i], F[i][j] + 1)
r.. m..(
F[i][j] __ F[i][j] > 2 ____ 0
___ i __ r..(n)
___ j __ r..(i)
)
___ lenLongestFibSubseq_TLE A: L.. i.. __ i..
"""
F[i][j] longest fib subsequence ending at A[i] with 2nd last element
A[j]
F[k][i] = F[i][j] + 1 if A[i] + A[j] = A[k]
O(N^2) * O(N) = O(N^3)
can be optimized to O(N^2) by look forward
"""
n l..(A)
F [[0 ___ _ __ r..(n)] ___ _ __ r..(n)]
___ i __ r..(n
F[i][i] 1
___ j __ r..(i
F[i][j] 2
___ k __ r..(n
___ i __ r..(k
___ j __ r..(i
__ A[i] + A[j] __ A[k]:
F[k][i] m..(F[k][i], F[i][j] + 1)
r.. m..(
F[i][j] __ F[i][j] > 2 ____ 0
___ i __ r..(n)
___ j __ r..(i)
)
__ _______ __ _______
... Solution().lenLongestFibSubseq([1,2,3,4,5,6,7,8]) __ 5
|
150d0efefb3c712edc14a5ff039ef2082c43152b | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/111_Minimum_Depth_of_Binary_Tree.py | 1,281 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
c_ Solution o..
# def minDepth(self, root):
# """
# :type root: TreeNode
# :rtype: int
# """
# # Recursion
# if root is None:
# return 0
# ld = self.minDepth(root.left)
# rd = self.minDepth(root.right)
# if ld != 0 and rd != 0:
# # handle 0 case!
# return 1 + min(ld, rd)
# return 1 + ld +rd
___ minDepth root
# BFS
__ root is N..:
r_ 0
queue = [root]
depth, rightMost = 1, root
w.. l.. queue) > 0:
node = queue.pop(0)
__ node.left is N.. a.. node.right is N..:
______
__ node.left is n.. N..:
queue.a.. node.left)
__ node.right is n.. N..:
queue.a.. node.right)
__ node __ rightMost:
# reach the current level end
depth += 1
__ node.right is n.. N..:
rightMost = node.right
____
rightMost = node.left
r_ depth
|
7a183c9f407ec53a128bb57bfd6e5f0f9e10df7d | syurskyi/Python_Topics | /070_oop/008_metaprogramming/_exercises/templates/Abstract Classes in Python/a_004_Concrete Methods in Abstract Base Classes.py | 848 | 4.21875 | 4 | # # Concrete Methods in Abstract Base Classes :
# # Concrete classes contain only concrete (normal)methods whereas abstract class contains both concrete methods
# # as well as abstract methods. Concrete class provide an implementation of abstract methods, the abstract base class
# # can also provide an implementation by invoking the methods via super().
# # Let look over the example to invoke the method using super():
#
# # Python program invoking a
# # method using super()
#
# _____ a..
# ____ a.. _____ A.. a..
#
#
# c_ R A...
# ___ rk
# print("Abstract Base Class")
#
#
# c_ K R
# ___ rk
# s__ .?
# print("subclass ")
#
# # Driver code
#
#
# r = K()
# r.rk()
#
# # Output:
# #
# # Abstract Base Class
# # subclass
# # In the above program, we can invoke the methods in abstract classes by using super().
|
e6cd52ea2f93f9d6b604a86199e13e1062c077c6 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Learning Python/029_002_Indexing and Slicing __getitem__ and __setitem__.py | 1,711 | 3.65625 | 4 | # c_ Indexer:
# ___ -g ____ index
# r_ ? ** 2
#
# X = I.
# print('#' * 23 + ' X[i] calls X.__getitem__(i)')
# print(X[2]) # X[i] calls X.__getitem__(i)
#
#
# # for i in range(5):
# # print(X[i], end=' ') # Runs __getitem__(X, i) each time
#
#
# L = [5, 6, 7, 8, 9]
# print('#' * 23 + ' Slice with slice syntax')
# print(L[2:4]) # Slice with slice syntax
#
# print(L[1:])
#
# print(L[:-1])
#
# print(L[::2])
#
# print('#' * 23 + ' Slice with slice objects')
# print(L[slice(2, 4)]) # Slice with slice objects
#
# print(L[slice(1, None)])
#
# print(L[slice(None, -1)])
#
# print(L[slice(None, None, 2)])
#
#
# c_ Indexer
# data = [5, 6, 7, 8, 9]
# ___ -g ____ index # Called for index or slice
# print('getitem:' ?
# r_ ____.d. i.. # Perform index or slice
#
# X = I...
# print('#' * 23 + ' Indexing sends __getitem__ an integer')
# (X[0]) # Indexing sends __getitem__ an integer
#
# X[1]
#
# X[-1]
#
# print('#' * 23 + ' Slicing sends __getitem__ a slice object')
# X[2:4] # Slicing sends __getitem__ a slice object
#
# X[1:]
#
# # X[:-1]
#
# X[::2]
#
#
# ___ -s_i_ ____ index value # Intercept index or slice assignment
#
# ____.data i.. = v.. # Assign index or slice
#
#
# # method __index is only in Python 3.0
# c_ C
# ___ -i ____
# r_ 255
#
# X = C()
# # print(hex(X)) # Integer value
#
# print(bin(X))
#
# # print(oct(X))
#
#
# print(('C' * 256)[255])
#
# print(('C' * 256)[X]) # As index (not X[i])
#
# print(('C' * 256)[X:]) # As index (not X[i:])
#
|
fc0b28844054dba6e018c3e64422087aa81fb1fe | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/861 Score After Flipping Matrix.py | 1,280 | 3.953125 | 4 | #!/usr/bin/python3
"""
We have a two dimensional matrix A where each value is 0 or 1.
A move consists of choosing any row or column, and toggling each value in that
row or column: changing all 0s to 1s, and all 1s to 0s.
After making any number of moves, every row of this matrix is interpreted as a
binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.
Example 1:
Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Note:
1 <= A.length <= 20
1 <= A[0].length <= 20
A[i][j] is 0 or 1.
"""
____ t___ _______ L..
c_ Solution:
___ matrixScore A: L..[L..[i..]]) __ i..
"""
MSB > sum of remaining digit
=> Toggle rows to set MSB to 1
Then we cannot toggle row anymore
Toggle the col if #0's < #1's
"""
m, n l..(A), l..(A 0
ret 0
ret += (1 << (n-1 * m # all rows with MSB being 1
___ j __ r..(1, n
cnt 0
___ i __ r..(m
__ A[i][j] __ A[i][0]:
cnt += 1 # number of 1's
# toggle
cnt m..(cnt, m-cnt)
ret += (1 << (n-1-j * cnt
r.. ret
|
40d52cb329b0c0128ad81af19b9966cde8a4b9fe | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 32 - 3SumClosest.py | 940 | 3.765625 | 4 | # 3 Sum Closest
# Question: Given an array S of n integers, find three integers in S such that the sum is closest to a given number,
# target. Return the sum of the three integers. You may assume that each input would have exactly one solution
# For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2.
# (-1 + 2 + 1 = 2).
# Solutions:
class Solution:
def threeSumClosest(self, numbers, target):
numbers.sort()
ans = None
for i in range(len(numbers)):
l, r = i + 1, len(numbers) - 1
while (l < r):
sum = numbers[l] + numbers[r] + numbers[i]
if ans is None or abs(sum- target) < abs(ans - target):
ans = sum
if sum <= target:
l = l + 1
else:
r = r - 1
return ans
Solution().threeSumClosest([-1, 2, 1, -4], 1) |
7e74db4c09ec16f6fced7843cda365bcf245d0df | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DynamicProgramming/70_ClimbingStairs.py | 393 | 3.59375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if not n:
return 1
dp = [0 for i in range(n)]
dp[0] = 1
if n > 1:
dp[1] = 2
for i in range(2, n):
dp[i] = dp[i-1] + dp[i-2]
return dp[n-1]
|
ed94d2c495b0969bd089bc2d0847bde79526a5f2 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-22-write-a-decorator-with-argument-a.py | 609 | 3.703125 | 4 | """
Write a decorator called make_html that wraps text inside one or more html tags.
As shown in the tests decorating get_text with make_html twice should wrap the text in the corresponding html tags, so:
@make_html('p')
@make_html('strong')
def get_text(text='I code with PyBites'):
return text
- would return: <p><strong>I code with PyBites</strong></p>
"""
# Approach 1 - working
from functools import wraps
def make_html(func):
def wrapped_func():
print("<p>" + func() + "</p>")
return wrapped_func
@make_html
def get_text(text='I code with PyBites'):
return text
get_text() |
98357c37192a91a3dc3afbe121908ae36db45019 | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 84 - ReverseInt.py | 382 | 4.15625 | 4 | # Reverse Integer
# Question: Reverse digits of an integer.
# Example1: x = 123, return 321
# Example2: x = -123, return -321.
# Solutions:
class Solution:
# @return an integer
def reverse(self, x):
if x<0:
sign = -1
else:
sign = 1
strx=str(abs(x))
r = strx[::-1]
return sign*int(r)
Solution().reverse(123) |
09af2eff3aa3ec127997bcbdb995ace63a092772 | syurskyi/Python_Topics | /070_oop/001_classes/examples/ITVDN_Python_Advanced/006_Типизированный Python/example1.py | 467 | 3.609375 | 4 | # untyped
value = 10
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def create_new_user(first_name, last_name):
# неоднозначность типов и преобразований
# first_name.???
print(first_name)
return User(first_name=first_name, last_name=last_name)
# user1 = create_new_user(value, value)
user2 = create_new_user('Test1', 'Test2')
|
4b9257954ef3f32e2dfcfb4f964f7e0b669b2d7a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/013 Roman to Integer.py | 767 | 3.65625 | 4 | """
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
"""
__author__ 'Danyang'
roman2int {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
c_ Solution:
___ romanToInt s
"""
What happens if current roman char larger than the previous roman char?
:param s: String
:return: integer
"""
result 0
___ ind, val __ e..(s
__ ind > 0 a.. roman2int[val] > roman2int[s[ind-1]]: # e.g. XIV
result -_ roman2int[s[ind-1]] # reverse last action
result += roman2int[val]-roman2int[s[ind-1]]
____
result += roman2int[val]
r.. ?
|
c9481862292b011e70bf73b3d62078e3a0122ab7 | syurskyi/Python_Topics | /120_design_patterns/025_without_topic/examples/MonoState.py | 2,609 | 4.28125 | 4 | #!/usr/bin/env python
# Written by: DGC
# python imports
#==============================================================================
class MonoState(object):
__data = 5
@property
def data(self):
return self.__class__.__data
@data.setter
def data(self, value):
self.__class__.__data = value
#==============================================================================
class MonoState2(object):
pass
def add_monostate_property(cls, name, initial_value):
"""
Adds a property "name" to the class "cls" (should pass in a class object
not a class instance) with the value "initial_value".
This property is a monostate property so all instances of the class will
have the same value property. You can think of it being a singleton
property, the class instances will be different but the property will
always be the same.
This will add a variable __"name" to the class which is the internal
storage for the property.
Example usage:
class MonoState(object):
pass
add_monostate_property(MonoState, "data", 5)
m = MonoState()
# returns 5
m.data
"""
internal_name = "__" + name
def getter(self):
return getattr(self.__class__, internal_name)
def setter(self, value):
setattr(self.__class__, internal_name, value)
def deleter(self):
delattr(self.__class__, internal_name)
prop = property(getter, setter, deleter, "monostate variable: " + name)
# set the internal attribute
setattr(cls, internal_name, initial_value)
# set the accesser property
setattr(cls, name, prop)
#==============================================================================
if (__name__ == "__main__"):
print("Using a class:")
class_1 = MonoState()
print("First data: " + str(class_1.data))
class_1.data = 4
class_2 = MonoState()
print("Second data: " + str(class_2.data))
print("First instance: " + str(class_1))
print("Second instance: " + str(class_2))
print("These are not singletons, so these are different instances")
print("")
print("")
print("Dynamically adding the property:")
add_monostate_property(MonoState2, "data", 5)
dynamic_1 = MonoState2()
print("First data: " + str(dynamic_1.data))
dynamic_1.data = 4
dynamic_2 = MonoState2()
print("Second data: " + str(dynamic_2.data))
print("First instance: " + str(dynamic_1))
print("Second instance: " + str(dynamic_2))
print("These are not singletons, so these are different instances")
|
4bfbc07c20a755a3e9607e00fe19deb57556f077 | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 78 - RmDupArr.py | 923 | 3.765625 | 4 | # # Remove Duplicates from Sorted Array
# # Question: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
# # Do not allocate extra space for another array, you must do this in place with constant memory.
# # For example: Given input array nums = [1,1,2],
# # Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
# # Solutions:
#
#
# c_ Solution
# """
# @param A: a list of integers
# @return an integer
# """
# ___ removeDuplicates A
# # write your code here
# __ ? __ # list:
# r_ 0
# count _ 0
# ___ i __ ra.. 0, le. ?
# __ ? ? __ ? ? - 1
# c..
# ____
# ? c.. _ ? ?
# ? +_ 1
# r_ ?
#
#
# ? .? 1,1,2 |
dcd947e7c695994dce361540224d3b63d3bb4d7a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/336 Palindrome Pairs.py | 2,980 | 4.125 | 4 | #!/usr/bin/python3
"""
Given a list of unique words, find all pairs of distinct indices (i, j) in the
given list, so that the concatenation of the two words, i.e. words[i] + words[j]
is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:
Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
"""
____ t___ _______ L..
____ c.. _______ d..
c_ TrieNode:
___ -
pali_prefix_idxes # list # suffix ends, prefix pali
word_idx N..
children d..(TrieNode)
c_ Solution:
___ palindromePairs words: L..s.. __ L..[L..[i..]]:
"""
Brute force, i, j and then check palindrom
O(N^2 * L)
Reverse the str, and then check O(N * L). Does it work actually?
Check: map str -> idx
|---s1---|---s2--| |---s1---|-s2-| |-s1-|---s2---|
Need to check whether part of the str is palindrome.
Part of str -> Trie.
How to check part of the str. Useful
Better way of checking palindrome? Infamouse Manacher
word_i | word_j
abc pppp | cba
abc | pppp cba
If palindrome suffix in work_i, we only need to check the "abc" against word_j
Similarly for palindrome prefix in word_j
Construct Trie for word_j reversely, since word_j is being checked
"""
root TrieNode()
___ idx, w __ e..(words
cur root
___ i __ r..(l..(w) - 1, -1, -1
# cur.children[w[i]] # error, pre-advancing the trie is unable to handle empty str
__ is_palindrome(w, 0, i + 1
cur.pali_prefix_idxes.a..(idx)
cur cur.children[w[i]]
cur.pali_prefix_idxes.a..(idx) # empty str is palindrome
cur.word_idx idx # word ends
ret # list
___ idx, w __ e..(words
cur root
___ i __ r..(l..(w:
# cur.children.get(w[i], None) # error, pre-advancing the trie is unable to handle empty str
__ is_palindrome(w, i, l..(w a.. cur.word_idx __ n.. N.. a.. cur.word_idx !_ idx:
ret.a..([idx, cur.word_idx])
cur cur.children.g.. w[i], N..)
__ cur __ N..
_____
____
___ idx_j __ cur.pali_prefix_idxes:
__ idx !_ idx_j:
ret.a..([idx, idx_j])
r.. ret
___ is_palindrome w, lo, hi
i lo
j hi - 1
w.... i < j:
__ w[i] !_ w[j]:
r.. F..
i += 1
j -_ 1
r.. T..
__ _______ __ _______
... Solution().palindromePairs(["a", ""]) __ [[0,1],[1,0]]
... Solution().palindromePairs(["abcd","dcba","lls","s","sssll"]) __ [[0,1],[1,0],[2,4],[3,2]]
|
d133419e4fcee49cdb10319bc4e000ce04751748 | syurskyi/Python_Topics | /010_strings/_exercises/_templates/Learning Python/019_Advanced Formatting Expression Examples.py | 466 | 3.609375 | 4 | # x = 1234
# res = 'integers: ...@...@-6_...$_6_' % (x, x, x) # | digit
# print(res)
# x = 1.23456789
# print(x) # Shows more digits before 2.7 and 3.1
# print('@ | @ | @' _ x, x, x # |exponential | float | shot of exponential
# print('@' _ x) # |exponential big letter
# print('_-6.2_ | __5.2_ | _+_6.1_' _ x, x, x # float
# print('@' _ x, st_ x # | string
# print('@, _.2_, _.$_' _ 1/3.0, 1/3.0, 4, 1/3.0 # |float
|
947d2727d45716aefa420d81b442014928e09d91 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-111.py | 1,438 | 3.96875 | 4 | """
In this Bite you will use the requests library to make a GET request to the ipinfo service.
Use IPINFO_URL and parse the (2 char) country code from the obtained json response.
Note how we mocked out the requests.get call in the tests, you can see another example of
this in our Parsing Twitter Geo Data and Mocking API Calls by Example article.
Querying APIs is a common need so this should become second nature :) - enjoy!
"""
_______ r__
_______ j__ __ j
# https://stackoverflow.com/questions/58048879/what-is-the-difference-between-json-method-and-json-loads
IPINFO_URL 'http://ipinfo.io/{ip}/json'
___ get_ip_country_2(ip_address
response r__.g.. IPINFO_URL.f..(ip=ip_address
print(t..(?.t..
print(?.t..)
jso j.l.. (?.t..)
print(t..(jso
print(jso 'country' )
___ get_ip_country ip_address
"""Receives ip address string, use IPINFO_URL to get geo data,
parse the json response returning the country code of the IP"""
# Execute HTTP GET request, this method returns requests.models.Response object
response r__.g.. IPINFO_URL.f..(ip=ip_address
# Returns json-encoded value of the response object, throws ValueError if the response body does not contain a valid json
# So dzejson is a dict
___
dzejson response.j..
______ V..
print("Response did not contain a valid JSON")
r..(dzejson 'country' )
print(get_ip_country_2(ip_address="8.8.8.8"
|
42ea23542608d894bf2c4c50394464b9d68d0eeb | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/769 Max Chunks To Make Sorted.py | 1,315 | 4.28125 | 4 | #!/usr/bin/python3
"""
Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we
split the array into some number of "chunks" (partitions), and individually sort
each chunk. After concatenating them, the result equals the sorted array.
What is the most number of chunks we could have made?
Example 1:
Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2],
which isn't sorted.
Example 2:
Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks
possible.
Note:
arr will have length in range [1, 10].
arr[i] will be a permutation of [0, 1, ..., arr.length - 1].
"""
____ t___ _______ L..
c_ Solution:
___ maxChunksToSorted arr: L.. i.. __ i..
"""
compared to the sorted
[0, 1, 2, 3, 4]
[1, 0, 2, 3, 4]
The largest number in the chunk determines the ending index of the chunk
"""
ret 0
cur_max_idx 0
___ i __ r..(l..(arr:
cur_max_idx m..(cur_max_idx, arr[i])
__ i __ cur_max_idx:
ret += 1
r.. ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.