blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ce9483de3859c90453180d8882467c9bc4918f3b | syurskyi/Python_Topics | /100_databases/001_sqlite/examples/PYnative/021_Retrieve Image and File stored as a BLOB.py | 1,919 | 3.796875 | 4 | import sqlite3
def writeTofile(data, filename):
# Convert binary data to proper format and write it on Hard Disk
with open(filename, 'wb') as file:
file.write(data)
print("Stored blob data into: ", filename, "\n")
def readBlobData(empId):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sql_fetch_blob_query = """SELECT * from new_employee where id = ?"""
cursor.execute(sql_fetch_blob_query, (empId,))
record = cursor.fetchall()
for row in record:
print("Id = ", row[0], "Name = ", row[1])
name = row[1]
photo = row[2]
resumeFile = row[3]
print("Storing employee image and resume on disk \n")
photoPath = "E:\pynative\Python\photos\db_data\\" + name + ".jpg"
resumePath = "E:\pynative\Python\photos\db_data\\" + name + "_resume.txt"
writeTofile(photo, photoPath)
writeTofile(resumeFile, resumePath)
cursor.close()
except sqlite3.Error as error:
print("Failed to read blob data from sqlite table", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("sqlite connection is closed")
readBlobData(1)
readBlobData(2)
# Output:
#
# Connected to SQLite
# Id = 1 Name = Smith
# Storing employee image and resume on disk
#
# Stored blob data into: E:\pynative\Python\photos\db_data\Smith.jpg
#
# Stored blob data into: E:\pynative\Python\photos\db_data\Smith_resume.txt
#
# sqlite connection is closed
#
# Connected to SQLite
# Id = 2 Name = David
# Storing employee image and resume on disk
#
# Stored blob data into: E:\pynative\Python\photos\db_data\David.jpg
#
# Stored blob data into: E:\pynative\Python\photos\db_data\David_resume.txt
#
# sqlite connection is closed |
b4b1f5d0b406903fbd9accc83d8ead1b3d2f313c | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/035 Valid Sudoku.py | 2,647 | 3.640625 | 4 | """
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
"""
__author__ 'Danyang'
c_ Solution:
___ isValidSudoku board
"""
Brute force - check rows, cols, and squares and maintain a hashmap to store the previously seen elements
Notice how check the square in the board.
Save space by one iterations.
9 squares are iterated by i
9 cells are iterated by j
Squares lie on 3 big rows; index for the 3 big rows: i/3*3-th, thus iteration pattern: 000, 333, 666
Subdivide the 1 big rows into 3 small rows; index for the 3 small rows: j/3-th, thus iteration pattern 000, 111, 222)
Squares lie on 3 big column; index for the 3 big column: i%3*3-th, thus iteration pattern: (036, 036, 036)
Subdivide the 1 big column into 3 small column; index for the 3 small columns: j%3-th, thus iteration pattern 012, 012, 012)
thus, iterate by board[i/3*3 + j/3][i%3*3 + j%3]
:param board: a 9x9 2D array
:return: boolean
"""
# check row & column
___ i __ x..(9
row # list # change to hashamp
column # list
square # list
___ j __ x..(9
# check row
___
row_element i..(board[i][j])
__ row_element __ row:
r.. F..
____
row.a..(row_element)
______ V..
p..
# check column
___
column_element i..(board[j][i])
__ column_element __ column:
r.. F..
____
column.a..(column_element)
______ V..
p..
# check square
___
square_element i..(board[i/3*3 + j/3][i%3*3 + j%3])
__ square_element __ square:
r.. F..
____
square.a..(square_element)
______ V..
p..
r.. T..
__ _____ __ ____
... Solution().isValidSudoku(
["..4...63.", ".........", "5......9.", "...56....", "4.3.....1", "...7.....", "...5.....", ".........",
"........."]
)__False
|
d6512208970b85c245726cea6f6184d5102f2f5d | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Backtracking/51_NQueens.py | 2,091 | 4.03125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
allNQueens = []
def solveNQueens(self, n):
self.allNQueens = []
self.cols = [True] * n
self.left_right = [True] * (2 * n - 1)
self.right_left = [True] * (2 * n - 1)
queueMatrix = [["."] * n for row in range(n)]
self.solve(0, queueMatrix, n)
return self.allNQueens
def solve(self, row, matrix, n):
"""
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)
"""
# Get one Queen Square
if row == n:
result = ["".join(r) for r in matrix]
self.allNQueens.append(result)
return
for col in range(n):
if self.cols[col] and self.left_right[row + n - 1 - col] and self.right_left[row + col]:
matrix[row][col] = "Q"
self.cols[col] = self.left_right[row + n - 1 - col] = self.right_left[row + col] = False
# Solve the child question
self.solve(row + 1, matrix, n)
# Backtracking here.
matrix[row][col] = "."
self.cols[col] = self.left_right[
row + n - 1 - col] = self.right_left[row + col] = True
"""
1
5
8
"""
|
67b17f468709a0bd849b347549a5368901b8c703 | syurskyi/Python_Topics | /100_databases/002_posgresql/examples/Python PostgreSQL tutorial zetcode/005_lastrowid.py | 707 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import psycopg2
con = psycopg2.connect(database='testdb', user='syurskyi',
password='1234')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS words")
cur.execute("CREATE TABLE words(id SERIAL PRIMARY KEY, word VARCHAR(255))")
cur.execute("INSERT INTO words(word) VALUES('forest') RETURNING id")
cur.execute("INSERT INTO words(word) VALUES('cloud') RETURNING id")
cur.execute("INSERT INTO words(word) VALUES('valley') RETURNING id")
last_row_id = cur.fetchone()[0]
print(f"The last Id of the inserted row is {last_row_id}")
# $ lastrowid.py
# The last Id of the inserted row is 3 |
01add743d7f439dc80af9f7fdff5d6a9b03d3591 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/DP/NumberofLongestIncreasingSubsequence.py | 2,961 | 3.828125 | 4 | """
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.
思路:
Dp,
Dp子问题:
分成两个子问题:
第一个子问题是length,第二个是count,记录的话肯定是要记录最长最多的。
第一个子问题:
length:
每个单独的可以看做是1
[4,3,2,0,3,1,7,9,1,7,9]
[1,1,1,1,1,1,1,1,1,1,1]
初始化每个长度均为1。
若现在的num比之前的num大,长度上则在这个长度的基础上+1。
[4,3,2,0,3,1,7,9,1,7,9]
3>2,3>0,最大都是2。
[1,1,1,1,2, 1,1,1,1,1,1]
...
第二个子问题:
count:
[4,3,2,0,3,1,7,9,1,7,9]
[1,1,1,1,1,1,1,1,1,1,1]
初始化每个count也都是1。
若现在的num比之前的num要大,若是第一次出现,则等于这个次数,否则加上这个次数。
[4,3,2,0,3,1,7,9,1,7,9]
3>2,由于是第一次出现,数量变为2所记录的数量。
3>0,第二次出现,数量加上0所记录的数量。
[1,1,1,1,2, 1,1,1,1,1,1]
关于如何判断是不是第一次出现:
首先全部初始化为1。若当前num大于之前num时,可以判断长度是否与之前的相等:
3>2时,此时应该为 (2, 3),
2 所记录的长度数量为 (1, 1)
3 此时记录的长度数量为 (1, 1)
这时由于是第一次出现,3处长度应为2([2, 3]),但还未变化,所以可以由长度判断是否为第一次。
经过此轮循环后,3处所记录的长度数量应为:(2, 1)
3>0时,这时
0 所记录的长度数量为 (1, 1)
3 所记录的长度数量为 (2, 1)
这时可以直接加。
测试地址:
https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/
O(n^2) 题目最大只有2000个数据,勉强通过。
"""
c.. Solution o..
___ findNumberOfLIS nums
"""
:type nums: List[int]
:rtype: int
"""
__ n.. nums:
r_ 0
length = [1] * l..(nums)
count = [1] * l..(nums)
maxLength = 1
___ i __ r..(l..(nums)):
___ j __ r..(i
__ nums[i] > nums[j]:
__ length[j] __ length[i]:
count[i] = count[j]
__ length[j]+1 __ length[i]:
count[i] += count[j]
x = m..(length[j]+1, length[i])
length[i] = x
maxLength = m..(maxLength, x)
r_ s..([count[i] ___ i,j __ enumerate(length) __ j __ maxLength])
|
8bafad1c847f74fd960cc1ba8d1b2fc9e3990b7d | syurskyi/Python_Topics | /018_dictionaries/examples/dictionary_002.py | 4,912 | 4.03125 | 4 | # Проверить существование кточа можно с помощью оператора in. Если ключ найден, то
# возвращается значение тrue, в противном случае - False.
d = {"a": 1, "b": 2}
print("a" in d) # Ключ существует
# True
print("c" in d) # Ключ не существует
# False
# Проверить, отсутствует ли какой-либо ключ в словаре, позволит оператор not in. Если
# ключ отсутствует, возвращается True, иначе - False.
d = {"a": 1, "b": 2}
print("c" not in d) # Ключ не существует
# True
print("a" not in d) # Ключ существует
# False
# get ( <Ключ> [, <Значение по умолчанию> ] )
# позволяет избежать возбуждения исключения KeyError при отсуtствии в словаре указанного ключа.
# Если ключ присутствует в словаре, то метод возвращает значение, соответствующее этому ключу.
# Если ключ отсутствует, то возвращается None или значение, указанное во втором параметре.
#
d = {"a": 1, "b": 2}
print(d.get("a"), d.get("c"), d.get("c", 800))
# # # (1, None, 800)
# setdefault ( <Kлюч> [, <Значение по умолчанию>])
# Если ключ присутствует в словаре, то метод возвращает значение, соответствующее
# этому ключу. Если ключ отсутствует, то в словаре создается новый элемент со значением, указанным во втором параметре.
# Если второй параметр не указан, значением нового элемента будет None.
#
d = {"a": 1, "b": 2}
print(d.setdefault("a"), d.setdefault("c"), d.setdefault("d", 0))
# (1, None, 0)
print(d)
# {'a': 1, 'c': None, 'b': 2, 'd': 0}
# Изменение элемента по ключу
d = {"a": 1, "b": 2}
d["a"] = 800 # Изменение элемента по ключу
d["c"] = "string" # Будет добавлен новый элемент
print(d)
# {'a': 800, 'c': 'string', 'b': 2}
# len ( )
d = {"a": 1, "b": 2}
print(len(d)) # Получаем количество ключей в словаре
# 2
# del()
d = {"a": 1, "b": 2}
del d["b"]; print(d) # Удаляем элемент с ключом "b" и выводим словарь
# {'a': 1}
# Perebor elementov slovarja
d = {"x": 1, "y": 2, "z": 3}
for key in d.keys():
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (y => 2) (x => 1) (z => 3)
for key in d:
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (y => 2) (x => 1) (z => 3)
# Получаем список ключей
d = {"x": 1, "y": 2, "z": 3}
k = list(d.keys()) # Получаем список ключей
k.sort() # Сортируем список ключей
for key in k:
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (x => 1) (y => 2) (z => 3)
# sorted ( )
d = {"x": 1, "y": 2, "z": 3}
for key in sorted(d.keys()):
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (x => 1) (y => 2) (z => 3)
# Так как на каждой итерации возвращается кmоч словаря, функции sorted ( ) можно сразу передать объект словаря,
# а не результат выполнения метода keys () :
d = {"x": 1, "y": 2, "z": 3}
for key in sorted(d):
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (x => 1) (y => 2) (z => 3)
# Методы для работы со словарями
# keys ()
# возвращает объект dict_keys, содержащий все ключи словаря. Этот объект
# поддерживает итерации, а также операции над множествами
#
d1, d2 = {"a": 1, "b": 2 }, {"a": 3, "c": 4, "d": 5}
print(d1.keys(), d2.keys()) # Получаем объект dict_keys
# (dict_keys(['a', 'b']), dict_keys(['a', 'c', 'd']))
print(list(d1.keys()), list(d2.keys()))
# Получаем список ключей
# (['a', 'b'], ['a', 'c', 'd'])
for k in d1.keys():
print(k, end=" ")
# Методы для работы со словарями
# keys () - Объединение
d1, d2 = {"a": 1, "b": 2}, {"a": 3, "c": 4, "d": 5}
print(d1.keys() | d2.keys())
# {'a', 'c', 'b', 'd'}
# Методы для работы со словарями
# keys () - Разница
d1, d2 = {"a": 1, "b": 2}, {"a": 3, "c": 4, "d": 5}
print(d1.keys() - d2.keys())
# {'b'}
print(d2.keys() - d1.keys())
# {'c', 'd'} |
048985656c8b9aa4fdd20d5f4485302a9059ebe2 | syurskyi/Python_Topics | /095_os_and_sys/examples/pathlib — Filesystem Paths as Objects/009_Deleting/001_pathlib_rmdir.py | 926 | 4.28125 | 4 | # There are two methods for removing things from the file system, depending on the type. To remove an empty directory, use rmdir().
# pathlib_rmdir.py
#
# import pathlib
#
# p = pathlib.Path('example_dir')
#
# print('Removing {}'.format(p))
# p.rmdir()
#
# A FileNotFoundError exception is raised if the post-conditions are already met and the directory does not exist. It is also an error to try to remove a directory that is not empty.
#
# $ python3 pathlib_rmdir.py
#
# Removing example_dir
#
# $ python3 pathlib_rmdir.py
#
# Removing example_dir
# Traceback (most recent call last):
# File "pathlib_rmdir.py", line 16, in <module>
# p.rmdir()
# File ".../lib/python3.6/pathlib.py", line 1270, in rmdir
# self._accessor.rmdir(self)
# File ".../lib/python3.6/pathlib.py", line 387, in wrapped
# return strfunc(str(pathobj), *args)
# FileNotFoundError: [Errno 2] No such file or directory:
# 'example_dir'
|
b731a29689c1a5581bdfffa60a057285bfde5f1d | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/057 Insert Interval.py | 2,077 | 3.765625 | 4 | """
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
"""
__author__ 'Danyang'
# Definition for an interval.
c_ Interval(o..
___ - , s=0, e=0
start s
end e
___ -s
r.. "[_d, _d]" % (start, end)
___ -r
r.. r.. (-s
c_ Solution(o..
___ insert itvls, newItvl
s, e newItvl.start, newItvl.end
left f.. l.... x: x.end < s, itvls)
right f.. l.... x: x.start > e, itvls)
__ l..(left)+l..(right) !_ l..(itvls
s m..(s, itvls[l..(left)].start)
e m..(e, itvls[-l..(right)-1].end)
r.. left + [Interval(s, e)] + right
___ insert_itr itvls, newItvl
"""
iterator TODO
"""
c_ SolutionSlow(o..
___ insert itvls, newItvl
"""
:param itvls: a list of Intervals
:param newItvl: a Interval
:return: a list of Interval
"""
r.. merge(itvls+[newItvl])
___ merge itvls
"""
sort first by .start
then decide whether to extend the .end
:param itvls: list of Interval
:return: list of Interval
"""
itvls.s..(cmp=l.... a, b: a.start - b.start)
ret [itvls[0]]
___ cur __ itvls 1|
pre ret[-1]
__ cur.start <_ pre.end: # overlap
pre.end m..(pre.end, cur.end)
____
ret.a..(cur)
r.. ret
__ _______ __ _______
lst [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]
insert [4, 9]
lst_interval # list
___ item __ lst:
lst_interval.a..(Interval(item[0], item[1]
print Solution().i.. lst_interval, Interval(insert[0], insert[1]
|
4279b993e6542713b54086d7dfb5402bd881718a | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/293_n_digit_numbers/save1_nopass.py | 376 | 3.90625 | 4 | car_brands = ['Mazda', 'McLaren', 'Opel', 'Toyota', 'Honda']
def convert_to_tuple(car_brands):
static_cars = tuple(car_brands)
return static_cars
# Complete this function such that it prints the return value from the convert_to_tuple function
def print_tuples(car_brands):
car_brands = convert_to_tuple()
if car_brands:
print(car_brands)
return |
a3454f6bccbdab70c6f468c6ccdcf190f4f58041 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/String/28_ImplementstrStr.py | 541 | 3.5625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
c.. Solution o..
# Not notoriously hard-to-understand algorithm KMP
___ strStr haystack, needle
# Return 0 if needle is ""
__ n.. needle:
r_ 0
length = l..(haystack)
# If one char in haystack is same with needle[0],
# then verify the other chars in needle.
___ i __ r..(length-l..(needle)+1
__ haystack[i:i+l..(needle)] __ needle:
r_ i
r_ -1
"""
""
""
"abaa"
"aa"
"aaabbb"
"abbb"
"""
|
da202821fc99a138bd2433255172ae6abbc181ef | syurskyi/Python_Topics | /125_algorithms/005_searching_and_sorting/_exercises/exersises/05_Merge Sort/6 - Insertion Sort vs. Merge Sort vs. Quicksort - timeit.py | 2,117 | 3.65625 | 4 | # ______ t..
#
# NUM_REPETITIONS _ 100
#
# SETUP_CODE _ "from random import shuffle"
#
# # First test case - Insertion Sort
#
# ___ insertion_sort lst
# ___ i __ ra.. 1 le. ?
# elem_selected _ ?|?
#
# w__ i > 0 an. ? < ?|?-1
# ?|? _ ?|?-1
# ? -_ 1
#
# ?|? _ ?
#
#
# test_code_1 _ '''
#
# a _ [i for i in range(1000)]
#
# shuffle(a)
#
# insertion_sort(a)
#
# '''
#
# print("\n==> Testing Insertion Sort")
#
# time _ t__.t.. _1 s.. n.. g..
#
# print("Total time to sort the list:" ?
# print("Average time per repetition:" t../N..
#
#
# # Second test case - Merge Sort
#
# ___ merge_sort lst
#
# __ le.(?) __ 0 o. le.(?) __ 1
# r_ ?
# else:
# middle_index _ le.(?)//2
#
# left _ ? ?|;?
# right _ ? ?|?;
#
# r_ ? ? ?
#
#
# ___ merge left_half right_half
#
# __ no. ? o. no. ?
# r_ ? o. ?
#
# result _ # list
# i j _ 0 0
#
# w__ T..
#
# __ ?|? < right_half|?
# ?.ap.. ?|?
# i +_ 1
# ____
# ?.ap..?|?
# j +_ 1
#
# __ i __ le. ? o. j __ le. ?
# ?.ex.. ?|?; o. ?|?;
# b..
#
# r_ ?
#
#
# test_code_2 _ '''
#
# b _ [i for i in range(1000)]
#
# shuffle(b)
#
# merge_sort(b)
#
# '''
#
# print("\n==> Testing Merge Sort")
#
# time _ t__.t.. _2, s.. n.. g..
#
# print("Total time to sort the list:", time)
# print("Average time per repetition:", time/NUM_REPETITIONS)
#
#
# # Third test case - Quicksort
#
# ___ quicksort lst low high
# __ ? < ?
# pivot_index _ ?|? ? ?
#
# ? ? ? ?-1
# ? ? ?+1 ?
#
# ___ partition lst low high
# pivot _ ?|?
#
# i _ ? - 1
#
# ___ j __ ra.. ? ?
# __ ?|? <_ ?
# ? +_ 1
# ?|? ?|? _ ?|? ?|?
#
# ?+1 ?|? _ ?|? ?|?+1
# r_ ?+1
#
# test_code_3 _ '''
#
# c _ [i for i in range(1000)]
#
# shuffle(c)
#
# quicksort(c, 0, len(c)-1)
#
# '''
#
# print("\n==> Testing Quicksort")
#
# time _ t__.t.. _3, s.. n.. g..
#
# print("Total time to sort the list:" ?
# print("Average time per repetition:" t../N..
|
10bd5d84d5136fffe530c59b8d5e36e8704782fb | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id047-Caesar_Shift_Cipher.py | 994 | 3.515625 | 4 | # Python 2.7
_______ s__
___ encrypt(msg_count, key
alphabet s__.a..
alphabet_shifted alphabet[key:] + alphabet[:key]
caesar_shift s__.maketrans(alphabet, alphabet_shifted)
answer # list
___ msg __ r..(msg_count
unencrypted_msg raw_input().u..
encrypted_msg unencrypted_msg.translate(caesar_shift)
answer.a..(encrypted_msg)
print(' '.j..(answer
___ decrypt(msg_count, key
key 26 - key
alphabet s__.a..
alphabet_shifted alphabet[key:] + alphabet[:key]
caesar_shift s__.maketrans(alphabet, alphabet_shifted)
answer # list
___ msg __ r..(msg_count
unencrypted_msg raw_input().u..
encrypted_msg unencrypted_msg.translate(caesar_shift)
answer.a..(encrypted_msg)
print(' '.j..(answer
___ caesar_cipher
encrypted_msg_count, shift_key [i..(x) ___ x __ raw_input().s.. ]
decrypt(encrypted_msg_count, shift_key)
#encrypt(encrypted_msg_count, shift_key)
caesar_cipher()
|
a6ec84041a9603243a0fa4b44d23bb4559fb2d8c | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/122/anagram.py | 409 | 3.984375 | 4 | # ___ is_anagram word1 word2
# """Receives two words and returns True/False (boolean) if word2 is
# an anagram of word1.
# About anagrams: https://en.wikipedia.org/wiki/Anagram"""
# word1 word1.r.. " ", "" .l..
# word2 word2.r.. " ", "" .l..
# __ s.. ? __ s.. ?
# r.. T..
# ____
# r.. F..
#
#
# # if __name__ == "__main__":
# # print(is_anagram("restful", "fluster")) |
295485bae68497f341317233ecec2b9e9948fa32 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/324 Wiggle Sort II py3.py | 1,944 | 4.0625 | 4 | #!/usr/bin/python3
"""
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2]
< nums[3]....
Example 1:
Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].
Example 2:
Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].
Note:
You may assume all input has valid answer.
Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?
"""
____ t___ _______ L..
c_ Solution:
___ wiggleSort nums: L.. i.. __ N..
"""
Do not return anything, modify nums in-place instead.
Median + 3-way partitioning
"""
n l..(nums)
# mid = self.find_kth(nums, 0, n, (n - 1) // 2)
# median = nums[mid]
median l..(s..(nums[n//2]
# three way pivot
odd 1
even n - 1 __ (n - 1) % 2 __ 0 ____ n - 2
i 0
w.... i < n:
__ nums[i] < median:
__ i >_ even a.. i % 2 __ 0:
i += 1
_____
nums[i], nums[even] nums[even], nums[i]
even -_ 2
____ nums[i] > median:
__ i <_ odd a.. i % 2 __ 1:
i += 1
_____
nums[i], nums[odd] nums[odd], nums[i]
odd += 2
____
i += 1
___ find_kth A, lo, hi, k
p pivot(A, lo, hi)
__ k __ p:
r.. p
____ k > p:
r.. find_kth(A, p + 1, hi, k)
____
r.. find_kth(A, lo, p, k)
___ pivot A, lo, hi
# need 3-way pivot, otherwise TLE
p lo
closed lo
___ i __ r..(lo + 1, hi
__ A[i] < A[p]:
closed += 1
A[closed], A[i] A[i], A[closed]
A[closed], A[p] A[p], A[closed]
r.. closed
__ _______ __ _______
Solution().wiggleSort([1, 5, 1, 1, 6, 4])
|
3cab568123c4abca6add09b7d7f5cca55a1deb15 | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/_algorithms_challenges/leetcode/LeetCode_with_solution/002 Median of Two Sorted Arrays.py | 2,014 | 3.6875 | 4 | # """
# There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall
# run time complexity should be O(log (m+n)).
# """
# __author__ = 'Danyang'
#
#
# c_ Solution
# ___ findMedianSortedArrays A B
# """
# Merge two arrays to get the median, O((m+n)/2)
#
# Algorithm: Find k-th element in 2 array
#
# A: A_left A[m/2] A_right
# B: B_left B[n/2] A_right
# if A[m/2]>B[n/2] and k>m/2+n/2, then disregard B_left and B[n/2]
# if A[m/2]>B[n/2] and k<=m/2+n/2, then disregard A_right and A[m/2]
# if A[m/2]<=B[n/2] and k>m/2+n/2, then disregard A_left and A[m/2]
# if A[m/2]<=B[n/2] and k<=m/2+n/2, then disregard B_right and B[n/2]
#
# whether to disregard A[m/2] or B[n/2] takes time to consider
#
# T(N) = T(3/4 N) + O(1), thus T(N) = O(lg N) where N = |A|+|B|
# O(log (m+n)), thus binary search.
#
# :param A: list
# :param B: list
# :return: float
# """
# m l.. A
# n l.. B
# __ ?+? &1 __ 0)
# r.. ? ? ? ?+?/2 + ? ? ? ?+?/2-1))/2.0
# ____:
# r.. ? ? ? ?+?/2
#
# ___ find_kth A B k
# """
#
# :param A:
# :param B:
# :param k: index starting from 0
# :return:
# """
# __ n.. A r.. ? ?
# __ n.. B r.. ? ?
# __ k __ 0 r.. m.. ? 0 ? 0
#
# m, n =l.. ? l.. ?
# # pay attention to consider the equal sign. Assigning equal sign is an art.
# __ ? ?/2 >_ ? ?/2
# __ k > ?/2+?/2:
# r.. ? ? ? ?/2+1| ?-?/2-1 # exclude B[n/2] to make progress
# ____:
# r.. ? ? |?/2] ? ? # exclude A[m/2] to make progress
# ____:
# r.. ? ? ? ?
#
#
# __ _______ __ _______
# ... ?.f.. 1, 2], [1, 2, 3]) __ 2
# ... ?.f.. 1, 2], [3]) __ 2
# ... ?.f.. 1], [2, 3]) __ 2
# ... ?.f.. 1, 2], [1, 2]) __ 1.5
|
a465d0633d6d9c4d2e6a449a7fcfcd752e01e882 | syurskyi/Python_Topics | /070_oop/001_classes/examples/ITVDN_Python_Advanced/004_Метаклассы/example1_type.py | 1,027 | 3.609375 | 4 | def get_first_name(self):
return self.first_name
def get_last_name(self):
return self.last_name
def get_middle_name(self):
return self.middle_name
def init(self, first_name, last_name, middle_name):
self.first_name = first_name
self.last_name = last_name
self.middle_name = middle_name
class BaseUser(object):
def __str__(self):
return '<user-object/>'
attrs = {
'first_name': '',
'last_name': '',
'middle_name': '',
'get_first_name': get_first_name,
'get_last_name': get_last_name,
'get_middle_name': get_middle_name,
'__init__': init
}
bases = (
BaseUser,
)
User = type('User', bases, attrs)
user1 = User('John', 'Test', 'Te100vi4')
print(str(user1))
print(user1.get_first_name())
print(user1.get_last_name())
print(user1.get_middle_name())
def build_class(class_name, base_classes, attrs):
new_attrs = {}
for attr, value in attrs.items():
new_attrs[attr.lower()] = value
return type(class_name, base_classes, new_attrs)
|
c14b314ac98a05946788391f5f896b8103c43b17 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/TwoPointers/16_3SumClosest.py | 1,323 | 3.984375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
min_distance = 2 ** 31 - 1
length = len(nums)
# keep the sum of three nums
solution = 0
for i in range(length-2):
cur_num = nums[i]
left = i + 1
right = length - 1
while left < right:
left_num = nums[left]
right_num = nums[right]
three_sum = cur_num + left_num + right_num
# the right point go back
if three_sum > target:
right -= 1
if min_distance > three_sum - target:
solution = three_sum
min_distance = three_sum - target
# the left point go forward
elif three_sum < target:
if min_distance > target - three_sum:
solution = three_sum
min_distance = target - three_sum
left += 1
else:
return three_sum
return solution
"""
[0,0,0]
1
[-1,-1,-1,-2,-3,1,2]
5
"""
|
8fd1a408e3ec25d95cb5d15473e4cdf8ec4682a9 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/49_v2/packt.py | 797 | 3.609375 | 4 | from collections import namedtuple
from bs4 import BeautifulSoup as Soup
import requests
PACKT = 'https://bites-data.s3.us-east-2.amazonaws.com/packt.html'
CONTENT = requests.get(PACKT).text
Book = namedtuple('Book', 'title description image link')
def get_book():
"""make a Soup object, parse the relevant html sections, and return a Book namedtuple"""
soup = Soup(CONTENT,"html.parser")
title = soup.find('div',class_='dotd-title').getText(strip=True)
description = soup.select_one('div[class="dotd-main-book-summary float-left"] > div:nth-child(4)').getText(strip=True)
link = soup.select_one('div.dotd-main-book-image > a')['href']
image = soup.select_one('div.dotd-main-book-image > a > img')['data-original']
return Book(title,description,image,link)
|
1137b851ed42a42ceb79c41d8c446b23bbba51ad | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 6 Dynamic Programming/FibonacciDP.py | 696 | 3.90625 | 4 |
___ fibonacci_recursion(n
__ n __ 0:
r_ 1
__ n __ 1:
r_ 1
r_ fibonacci_recursion(n-1) + fibonacci_recursion(n-2)
# top-down approach
___ fibonacci_memoization(n, table
__ n no. __ table:
table[n] fibonacci_memoization(n-1, table) + fibonacci_memoization(n-2, table)
# O(1) running time
r_ table[n]
# bottom-up approach
___ fibonacci_tabulation(n, table
___ i __ ra__(2, n+1
table[i] table[i-1] + table[i-2]
r_ table[n]
t {0: 1, 1: 1}
# exponential running time
print(fibonacci_recursion(1))
# these are the O(N) linear running time approaches
print(fibonacci_tabulation(50, t))
print(fibonacci_memoization(40, t))
|
6f3453f7739bdb26b9c6e82a6379a385af806970 | syurskyi/Python_Topics | /125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 15 Sort/insertion_sort_implement_solution.py | 881 | 4 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
# Write a Python program to sort a list of elements using the insertion sort algorithm.
# Note: According to Wikipedia "Insertion sort is a simple sorting algorithm that builds
# the final sorted array (or list) one item at a time. It is much less efficient on large
# lists than more advanced algorithms such as quicksort, heapsort, or merge sort."
# %% [markdown]
# 
# %%
def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)
|
bf804b07bca29cd832ad306060165f29a7ca6499 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/647_substring_anagrams.py | 912 | 3.71875 | 4 | """
REF: https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/
"""
c_ Solution:
___ findAnagrams s, t
"""
:type s: str
:type t: str
:rtype: List[int]
"""
ans # list
__ n.. s o. n.. t o. l..(t) > l..(s
r.. ans
F # dict
___ c __ t:
F[c] F.g.. c, 0) + 1
n, m, cnt l..(s), l..(t), l..(F)
left right 0
w.... right < n:
__ s[right] __ F:
F[s[right]] -_ 1
__ F[s[right]] __ 0:
cnt -_ 1
right += 1
w.... cnt __ 0:
__ s[left] __ F:
F[s[left]] += 1
__ F[s[left]] __ 1:
cnt += 1
__ right - left __ m:
ans.a..(left)
left += 1
r.. ans
|
d4450b0c6d0c8606e68e61901bc5d21cb770cc72 | syurskyi/Python_Topics | /090_logging/examples/Python Logging – Simplest Guide with Full Code and Examples/008_9. How to include traceback information in logged messages.py | 974 | 3.5625 | 4 | # Besides debug, info, warning, error, and critical messages, you can log exceptions that will include any
# associated traceback information.
# With logger.exception, you can log traceback information should the code encounter any error. logger.exception will log
# the message provided in its arguments as well as the error message traceback info.
#
# Below is a nice example.
import logging
# Create or get the logger
logger = logging.getLogger(__name__)
# set log level
logger.setLevel(logging.INFO)
def divide(x, y):
try:
out = x / y
except ZeroDivisionError:
logger.exception("Division by zero problem")
else:
return out
# Logs
logger.error("Divide {x} / {y} = {c}".format(x=10, y=0, c=divide(10,0)))
#> ERROR:__main__:Division by zero problem
#> Traceback (most recent call last):
#> File "<ipython-input-16-a010a44fdc0a>", line 12, in divide
#> out = x / y
#> ZeroDivisionError: division by zero
#> ERROR:__main__:None |
e17d04f9383cce416b49a61d78ab5eb167365d45 | syurskyi/Python_Topics | /110_concurrency_parallelism/_exercises/templates/The_Complete_Python_Course_l_Learn_Python_by_Doing/projects/async_scraping/app.py | 2,648 | 3.53125 | 4 | """
You can see when running this file, that the amount of time it takes for the requests is actually quite long—
and they don't seem to all happen at the same time.
That's because the toscrape websites actually limit us to a single connection at a time,
so making multiple requests using aiohttp and waiting for them to come back is completely useless.
Indeed, if we use a different site (e.g. you can try with http://google.com), you'll see the requests
all seem to happen at once.
The speed at which we can request pages is not only a product of the speed of our Python program, but
also the speed of the server giving us the responses back (and, in this case, any artificial limitations that
have been put in place to prevent us from making too many requests at once!).
Servers sometimes do this so that you can't make 1000 simultaneous requests and crash the server.
"""
______ _
______ aiohttp
______ async_timeout
______ requests
______ l__
______ t___
____ pages.all_books_page ______ AllBooksPage
l__.?(?_'%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] _ m.. _,
datefmt='%d-%m-%Y %H:%M:%S',
?_l__.D..
filename='logs.txt')
logger = l__.getLogger('scraping')
loop = _.get_event_loop()
print('Loading books list...')
logger.info('Loading books list.')
logger.info('Requesting http://books.toscrape.com')
page_content = requests.get('http://books.toscrape.com').content
logger.d..('Creating AllBooksPage from page content.')
page = AllBooksPage(page_content)
_books # list
@ ___ fetch_page(session, url):
page_start = t___.t___()
logger.info(f'Requesting {url}')
@ w__ session.get(url) __ response:
print(f'{url} took {t___.t___() - page_start}')
r.. await response.text()
@ ___ get_multiple_pages(loop, *urls):
tasks # list
@ w__ aiohttp.ClientSession(loop=loop) __ session:
___ url __ urls:
tasks.a..(fetch_page(session, url))
r.. await _.gather(*tasks)
logger.info(f'Going through {page.page_count} pages of books...')
# other URLs to try:
# https://www.johnlewis.com/herman-miller-new-aeron-office-chair-graphite-polished-aluminium/p3177260
# http://google.com
urls = [f'http://books.toscrape.com/catalogue/page-{page_num+1}.html' ___ page_num __ r...(page.page_count)]
start = t___.t___()
pages = loop.run_until_complete(get_multiple_pages(loop, *urls))
print(f'Total page requests took {t___.t___() - start}')
___ page_content __ pages:
logger.d..('Creating AllBooksPage from page content.')
page = AllBooksPage(page_content)
_books.extend(page.books)
books = _books
|
331eab5b8eafeadd1f9d83d27280117a4daea3b8 | syurskyi/Python_Topics | /012_lists/_exercises/Python 3 Most Nessesary/8.1. Listing 8.1. Create a shallow copy of the list.py | 1,202 | 4.1875 | 4 | # # -*- coding: utf-8 -*-
#
# x = [1, 2, 3, 4, 5] # Создали список
# # Создаем копию списка
# y = l.. ? # или с помощью среза: y = x[:]
# # или вызовом метода copy(): y = x.copy()
# print ?
# # [1, 2, 3, 4, 5]
# print(x i_ y) # Оператор показывает, что это разные объекты
# # False
# y[1] = 100 # Изменяем второй элемент
# print(x, y) # Изменился только список в перемеой y
# # ([1, 2, 3, 4, 5], [1, 100, 3, 4, 5])
#
#
# x = [1, [2, 3, 4, 5]] # Создали вложенный список
# y = l.. ? # Якобы сделали копию списка
# print(x i_ y) # Разные объекты
# # False
# y 1 1 = 100 # Изменяем элемент
# print(x, y) # Изменение затронуло переменную x!!!
# # ([1, [2, 100, 4, 5]], [1, [2, 100, 4, 5]])
|
41d8a0a50decf51faf898a7346ce1a70f5aecbd9 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/74/bday.py | 411 | 4.09375 | 4 | import calendar
#from datetime import date
#weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
def weekday_of_birth_date(date):
"""Takes a date object and returns the corresponding weekday string"""
#return weekdays[calendar.weekday(date.year, date.month, date.day)]
return calendar.day_name[date.weekday()]
#print(weekday_of_birth_date(date(1965, 4, 4))) |
0e890772ec0a6827e48ad8346929b77e8f0fe3a2 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Stack/85_MaximalRectangle.py | 2,216 | 3.65625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[list[str]]
:rtype: int
"""
if not matrix:
return 0
m_rows = len(matrix)
n_cols = len(matrix[0])
# Pre-process: to make every row be a histogram
process_matrix = [
[0 for col in range(n_cols)] for row in range(m_rows)]
for row in range(m_rows):
for col in range(n_cols):
if row == 0:
if matrix[row][col] == "1":
process_matrix[row][col] = 1
else:
num = 1 if matrix[row][col] == "1" else 0
process_matrix[row][col] = num * (
num + process_matrix[row-1][col])
# Find every max size of row.
max_size = 0
for row in range(m_rows):
max_row_size = self.largestRectangleArea(process_matrix[row])
max_size = max(max_row_size, max_size)
return max_size
# Find the largest rectangle in a histogram
def largestRectangleArea(self, height):
# Add a bar of height 0 after the tail.
height.append(0)
size = len(height)
no_decrease_stack = [0]
max_size = height[0]
i = 0
while i < size:
cur_num = height[i]
# If the height of current bar is higher than the stack top,
# or the stack is empty, push current index to stack
if (not no_decrease_stack or
cur_num > height[no_decrease_stack[-1]]):
no_decrease_stack.append(i)
i += 1
# The current height is lower or same than the top,
# then pop until current height is higher than the top.
else:
index = no_decrease_stack.pop()
if no_decrease_stack:
width = i - no_decrease_stack[-1] - 1
else:
width = i
max_size = max(max_size, width * height[index])
return max_size
"""
[]
[["1","0","1","0"], ["1","1","1","1"]]
"""
|
b6867543f492e1bcfa7895806ebafe55df328da2 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/_templates/Python_OOP_Object_Oriented_Programming/Section 15/project/player.py | 1,786 | 3.8125 | 4 | class Player:
def __init__(self, name, is_dealer=False):
# The player has a name
# and a hand that is initially empty
self._name = name
# The hand attribute is protected
# and it doesn't have getters and setters
# because it doesn't have to be read or set.
# These processes are handled differently
# by the existing methods.
self._hand = []
self._is_dealer = is_dealer
# Read-only Properties
@property
def name(self):
return self._name
@property
def is_dealer(self):
return self._is_dealer
def draw(self, deck):
# Take a card from the deck and add it to the hand.
# Then, return a reference to the instance.
self._hand.append(deck.draw())
return self
def show_hand(self, reveal_card=False):
# For every card in the player's hand,
# show the data of the card.
if not self.is_dealer:
for card in self._hand:
card.show()
# If the player is the dealer,
# hide the value of the last card
# unless the card should be revealed.
else:
for i in range(len(self._hand)-1):
self._hand[i].show()
# Show the hidden card or not.
if reveal_card:
self._hand[-1].show()
else:
print("X")
def discard(self):
# Discard a card and return it.
return self._hand.pop()
def get_hand_value(self):
# Find the value of the current hand
# by adding the values of the cards
# and return the result.
value = 0
for card in self._hand:
value += card.value
return value
|
7f9dd6edcea8dd4778d92a344fc7a71b91ad7977 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BinarySearch/81_SearchInRotatedSortedArrayII.py | 1,429 | 4 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
c.. Solution o..
___ search nums, target
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
nums_size = l..(nums)
start = 0
end = nums_size - 1
_____ start <= end:
mid = (start + end) / 2
num_mid = nums[mid]
# Mid is in the left part of the rotated(if it's rotated) array.
__ num_mid > nums[start]:
__ nums[start] <= target < num_mid:
end = mid - 1
____ target __ num_mid:
r_ True
____
start = mid + 1
# The array must be rotated, and mid is in the right part
____ num_mid < nums[start]:
__ num_mid < target <= nums[end]:
start = mid + 1
____ target __ num_mid:
r_ True
____
end = mid - 1
# Can't make sure whether mid in the left part or right part.
____
# Find the target.
__ target __ num_mid:
r_ True
# Just add start with one until we can make sure.
# Of course, you can also minus end with one.
start += 1
r_ F..
"""
[]
0
[1]
1
[7,8,7,7,7]
8
[7,7,7,8,8]
8
"""
|
c49c16103e4d0ab711c90be31e2a7a50caa6b8bf | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/560 Subarray Sum Equals K.py | 679 | 3.75 | 4 | #!/usr/bin/python3
"""
Given an array of integers and an integer k, you need to find the total
number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer
k is [-1e7, 1e7].
"""
____ t___ _______ L..
____ c.. _______ d..
c_ Solution:
___ subarraySum nums: L..[i..], k: i.. __ i..
"""
prefix sum
"""
h d.. i..
ret 0
s 0
h[s] += 1
___ n __ nums:
s += n
ret += h[s - k]
h[s] += 1
r.. ret
|
0d6d149314dd679711f911de27eab09d0f4bd677 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/896 Monotonic Array.py | 1,080 | 3.96875 | 4 | #!/usr/bin/python3
"""
An array is monotonic if it is either monotone increasing or monotone
decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A
is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
"""
____ t___ _______ L..
c_ Solution:
___ isMonotonic A: L.. i.. __ b..
mono 0 # 0 undecided, 1 decr, 2 incr
___ i __ r..(1, l..(A:
__ mono __ 0:
__ A[i] > A[i-1]:
mono 2
____ A[i] < A[i-1]:
mono 1
____
__ A[i] > A[i-1] a.. mono __ 1:
r.. F..
____ A[i] < A[i-1] a.. mono __ 2:
r.. F..
____
r.. T..
|
3b3ba828e754b1e81eb8f704a676888517e1ba25 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/117_PopulatingNextRightPointersInEachNodeII.py | 2,466 | 4.09375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for binary tree with next pointer.
# class TreeLinkNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
c.. Solution o..
___ connect root
__ n.. root:
r_ None
cur_head = root
next_head = None
# Breadth-first Scan
_____ cur_head:
# Get the next node cur_head's child point to.
next_node = cur_head.next
_____ next_node:
__ next_node.left:
next_node = next_node.left
______
__ next_node.right:
next_node = next_node.right
______
next_node = next_node.next
__ cur_head.left:
__ n.. next_head:
next_head = cur_head.left
__ cur_head.right:
cur_head.left.next = cur_head.right
____
cur_head.left.next = next_node
__ cur_head.right:
__ n.. next_head:
next_head = cur_head.right
cur_head.right.next = next_node
cur_head = cur_head.next
# Go to next level.
__ n.. cur_head:
cur_head = next_head
next_head = None
""" Readable implementation
class Solution(object):
def connect(self, root):
# For all the non-empty nodes:
# node.left.next = right(or next_node)
# node.right.next = next_node, (or right)
if not root:
return None
next_node = root.next
while next_node:
if next_node.left:
next_node = next_node.left
break
if next_node.right:
next_node = next_node.right
break
next_node = next_node.next
if root.left:
if root.right:
root.left.next = root.right
else:
root.left.next = next_node
if root.right:
root.right.next = next_node
# Get root.right done firstly because when we compute root.left,
# we may use the node's next relationship in connect(root.right).
self.connect(root.right)
self.connect(root.left)
"""
"""
[0]
[1,2,3,4,5,null,7]
"""
|
0ad31500f7c294e13cb17da3508cf79b21c293d1 | syurskyi/Python_Topics | /045_functions/008_built_in_functions/zip/examples/002_How zip() works in Python.py | 400 | 3.703125 | 4 | numberList = [1, 2, 3]
strList = ['one', 'two', 'three']
# No iterables are passed
result = zip()
print(result)
# Converting itertor to list
resultList = list(result)
print(resultList)
#
# Two iterables are passed
result = zip(numberList, strList)
print(list(result))
#
# # Converting itertor to set
# resultSet = set(result)
# print(resultSet)
#
# # []
# # {(2, 'two'), (3, 'three'), (1, 'one')}
|
ef173fde8a3cf0c4fb66bddea7262bcda0c64b5f | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/643 Maximum Average Subarray I.py | 789 | 3.890625 | 4 | #!/usr/bin/python3
"""
Given an array consisting of n integers, find the contiguous subarray of given
length k that has the maximum average value. And you need to output the maximum
average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].
"""
____ t___ _______ L..
c_ Solution:
___ findMaxAverage nums: L..[i..], k: i.. __ f__:
"""
two pointers
"""
cur_sum s..(nums[:k])
maxa cur_sum
i k
w.... i < l..(nums
cur_sum += nums[i]
cur_sum -_ nums[i-k]
maxa m..(maxa, cur_sum)
i += 1
r.. maxa / k
|
d4ad996d8e156d70426d88f1ed7f01d4c338b492 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/004_coroutines/_exercises/templates/003_Coroutine in Python.py | 6,369 | 4.1875 | 4 |
# # -*- coding: utf-8 -*-
# # We all are familiar with function which is also known as a subroutine, procedure, subprocess etc. A function is a
# # sequence of instructions packed as a unit to perform a certain task. When the logic of a complex function is divided
# # into several self-contained steps that are themselves functions, then these functions are called helper functions or
# # subroutines.
# # Subroutines in Python are called by main function which is responsible for coordination the use of these subroutines.
# # Subroutines have single entry point.
#
# # Coroutines are generalization of subroutines. They are used for cooperative multitasking where a process voluntarily
# # yield (give away) control periodically or when idle in order to enable multiple applications to be run simultaneously.
# # The difference between coroutine and subroutine is :
# # Unlike subroutines, coroutines have many entry points for suspending and resuming execution. Coroutine can suspend
# # its execution and transfer control to other coroutine and can resume again execution from the point it left off.
# # Unlike subroutines, there is no main function to call coroutines in particular order and coordinate the results.
# # Coroutines are cooperative that means they link together to form a pipeline. One coroutine may consume input data
# # and send it to other which process it. Finally there may be a coroutine to display result.
#
# # Now you might be thinking how coroutine is different from threads, both seems to do same job.
# # In case of threads, it’s operating system (or run time environment) that switches between threads according to
# # the scheduler. While in case of coroutine, it’s the programmer and programming language which decides when to switch
# # coroutines. Coroutines work cooperatively multi task by suspending and resuming at set points by programmer.
# #
# # Python Coroutine
# #
# # In Python, coroutines are similar to generators but with few extra methods and slight change in how we use yield
# # statement. Generators produce data for iteration while coroutines can also consume data.
# # In Python 2.5, a slight modification to the yield statement was introduced, now yield can also be used as expression.
# # For example on the right side of the assignment –
# # line = (yield)
# #
# # whatever value we send to coroutine is captured and returned by (yield) expression.
# # A value can be send to the coroutine by send() method. For example, consider this coroutine which print out name
# # having prefix “Dear” in it. We will send names to coroutine using send() method.
#
# # Python3 program for demonstrating
# # coroutine execution
#
# ___ print_name prefix
# print("Searching prefix: |".f... ?
# w___ T...
# name _ |y..
# __ ? __ ?
# print ?
#
# # calling coroutine, nothing will happen
# corou = ? Dear
#
# # This will start execution of coroutine and
# # Prints first line "Searchig prefix..."
# # and advance execution to the first yield expression
# corou. -n
#
# # sending inputs
# ?.se.. Atul
# ?.se.. Dear Atul
#
# # Output:
# #
# # Searching prefix:Dear
# # Dear Atul
#
# # Execution of coroutine is similar to the generator. When we call coroutine nothing happens, it runs only in response
# # to the next() and send() method. This can be seen clearly in above example, as only after calling __next__() method,
# # out coroutine starts executing. After this call, execution advances to the first yield expression, now execution
# # pauses and wait for value to be sent to corou object. When first value is sent to it, it checks for prefix and print
# # name if prefix present. After printing name it goes through loop until it encounters name = (yield) expression again.
# #
# # Closing a Coroutine
# #
# # Coroutine might run indefinitely, to close coroutine close() method is used. When coroutine is closed it generates
# # GeneratorExit exception which can be catched in usual way. After closing coroutine, if we try to send values,
# # it will raise StopIteration exception. Following is a simple example :
#
#
# # Python3 program for demonstrating
# # closing a coroutine
#
# ___ print_name prefix
# print("Searching prefix: |".f... ?
# ___
# w___ T...
# name = |y..
# __ ? __ ?
# print ?
# _____ G...
# print("Closing coroutine!!")
#
#
# corou = print_name("Dear")
# ?.__next__()
# ?.s..("Atul")
# ?.s..("Dear Atul")
# ?.c..
#
# # Output:
# #
# # Searching prefix:Dear
# # Dear Atul
# # Closing coroutine!!
#
# # Chaining coroutines for creating pipeline
# #
# # Coroutines can be used to set pipes. We can chain together coroutines and push data through pipe using send() method. A pipe needs :
# #
# # An initial source(producer) which derives the whole pipe line. Producer is usually not a coroutine, it’s just a simple method.
# # A sink, which is the end point of the pipe. A sink might collect all data and display it.
# #
# # pipeline
# # Following is a simple example of chaining –
#
#
# # Python3 program for demonstrating
# # coroutine chaining
#
# ___ producer sentence, next_coroutine
# '''
# Producer which just split strings and
# feed it to pattern_filter coroutine
# '''
# tokens = s__.sp.. (" ")
# ___ token __ ?
# n___.se.. ?
# n___.cl..
#
#
# ___ pattern_filter pattern_"ing" n...._N..
# '''
# Search for pattern in received token
# and if pattern got matched, send it to
# print_token() coroutine for printing
# '''
# print("Searching for | ".f... p..
# ___
# w___ T...
# token _ |y..
# __ p.. __ ?
# n____.se.. ?
# _____ G..
# print("Done with filtering!!")
#
#
# ___ print_token
# '''
# Act as a sink, simply print the
# received tokens
# '''
# print("I'm sink, i'll print tokens")
# ___
# w___ T...
# token _ |y..
# print ?
# ____ G...
# print("Done with printing!")
#
#
# pt = ?
# ?. -n
# pf = pa.._fi.. next_coroutine=pt
# ?. -n
#
# sentence = "Bob is running behind a fast moving car"
# producer(sentence, pf)
#
# # Output:
# #
# # I'm sink, i'll print tokens
# # Searching for ing
# # running
# # moving
# # Done with filtering!!
# # Done with printing!
|
e75c9f4ba6bf90421edc4795266c2180b7f90c88 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Combination/300_LongestIncreasingSubsequence.py | 1,468 | 3.59375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
c.. Solution o..
"""
Clear explanation is here:
https://leetcode.com/discuss/67687/c-o-nlogn-solution-with-explainations-4ms
https://leetcode.com/discuss/67643/java-python-binary-search-o-nlogn-time-with-explanation
The key to the solution is: build a ladder for numbers: dp.
dp[i]: the smallest num of all increasing subsequences with length i+1.
When a new number x comes, compare it with the number in each level:
1. If x is larger than all levels, append it, increase the size by 1
2. If dp[i-1] < x <= dp[i], update dp[i] with x.
For example, say we have nums = [4,5,6,3],
then all the available increasing subsequences are:
len = 1: [4], [5], [6], [3] => dp[0] = 3
len = 2: [4, 5], [5, 6] => dp[1] = 5
len = 3: [4, 5, 6] => dp[2] = 6
"""
___ lengthOfLIS nums
dp = [0] * l..(nums)
size = 0
___ n __ nums:
# Binary search here.
left, right = 0, size
_____ left < right:
mid = (left + right) / 2
__ dp[mid] < n:
left = mid + 1
____
right = mid
# Append the next number
dp[right] = n
# Update size
__ right __ size:
size += 1
r_ size
"""
[]
[3]
[1,1,1,1]
[10,9,2,5,3,7,101,18]
"""
|
caf7fefdcb95d72d6bc06e78f40a618c39fd80b5 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DFS/WordSearch.py | 12,281 | 3.90625 | 4 | """
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
给定一个2D数组,找到是否该字符串存在于其中。
首先进行了一次失败的尝试....
没读第二行,直接用二叉树做搜索,理想情况下就是O(nlogn)。
发现没通过,要 「相邻」 的字符才可以。
那这可以用DFS深度优先。找到合适的点就一直深入下去,如果找到了就返回True。
如果没找到就找其他相邻的还有没有,没有就False有就继续寻找下去,直到word耗尽。
测试用例:
https://leetcode.com/problems/word-search/description/
"""
'''python
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
self.count = 1
class binarySearchTree(object):
"""
二叉搜索树,
它的性质是左边节点都小于根节点,右边的都大于根节点。
而且一般来说它是不存在重复元素的。
"""
def __init__(self, root):
if isinstance(root, TreeNode):
self.root = root
else:
self.root = TreeNode(root)
def add(self, value):
# 从顶点开始遍历,找寻其合适的位置。
root = self.root
if self.searchAndAddOne(value):
return
while 1:
if root.val < value:
if root.right is None:
# if self.search(value):
# break
root.right = TreeNode(value)
break
else:
root = root.right
continue
if root.val > value:
if root.left is None:
# if self.search(value):
# break
root.left = TreeNode(value)
break
else:
root = root.left
continue
if root.val == value:
root.count += 1
break
def searchAndAddOne(self, value):
# 查找一个值是否存在于这颗树中,如果存在则计数+1
return self._search(self.root, value, add=True)
def searchAndReduceOne(self, value):
return self._search(self.root, value, reduce=True)
def _search(self, root, value, add=False, reduce=False):
if root.val == value:
if add:
root.count += 1
if reduce:
print(root.count, root.val)
if root.count > 0:
root.count -= 1
else:
return False
return True
if root.right:
if root.val < value:
return self._search(root.right, value, add=add, reduce=reduce)
if root.left:
if root.val > value:
return self._search(root.left, value, add=add, reduce=reduce)
return False
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
myTree = binarySearchTree(TreeNode('-'))
for i in board:
for j in i:
myTree.add(j)
for i in word:
if not myTree.searchAndReduceOne(i):
return False
return True
a = Solution()
print(a.exist([['A']*2], "AAA"))
'''
"""
这一个的思路是从第一个开始,寻找其上下左右,如果有合适的则进入那个继续寻找,直到找到合适的或耗尽。
此版本TTL.
多次失败的尝试后,终于找到快速的方法。
思路仍然是DFS。之前写的时候,使用了deepcopy,每次都会生成一个全新的地图,这样做的坏处是每次生成一个新的地图都会耗费大量时间和空间。
经过测试,一个大点的地图(最下面的那个例子)生成100次会花费大约400ms。
改进后的思路是不在生成新的地图,只在原地图上捣鼓。
思路是这样:
如果此点与word中第一个相同,则将其覆盖。之后进行上下左右移动,有一个命中就会一直判断,如果全不命中就会收回。再从上一个点开始判断。
覆盖的原因是如果不替换那么可能形成环。但一个字符只允许使用一次。
```
FRANCE
0 1 2 3 4 5 6
"F" "Y" "C" "E" "N" "R" "D"
list
0 1 2 3 4 5 6
"K" "L" "N" "F" "I" "N" "U"
list
0 1 2 3 4 5 6
"A" "A" "A" "R" "A" "H" "R"
list
0 1 2 3 4 5 6
"N" "D" "K" "L" "P" "N" "E"
list
0 1 2 3 4 5 6
"A" "L" "A" "N" "S" "A" "P"
list
0 1 2 3 4 5 6
"O" "O" "G" "O" "T" "P" "N"
list
0 1 2 3 4 5 6
"H" "P" "O" "L" "A" "N" "O"
```
第一个 F 0, 0处命中,然后继续上下左右找有没有R命中的。结果没有。那么被替换的F就会还原。
第二个 F 2, 3处命中,然后继续上x,下命中,则替换掉然后继续判断。直到A处判断了FRA但断开了,
这时会还原A,但R的左边还有A同样进行判断但之后也断开了。到R上下左右都没有则还原回F,上下左右又没有则还原到初始。
"""
import copy
import pdb
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for i, d in enumerate(board):
for i2, d2 in enumerate(d):
if d2 == word[0]:
if self.search(board, i2, i, word):
return True
return False
def search(self, board, x, y, word):
"""
"""
if not word:
return True
# if x == len(board[0][0]) and y == len(board):
# return False
if board[y][x] != word[0]:
return False
if board[y][x] == word[0]:
word = word[1:]
temp_data = board[y][x]
board[y][x] = '#'
# if not word:
# return True
# up
if y-1 >= 0:
if board[y-1][x] != '#':
if self.search(board, x, y-1, word): # u
return True
# down
if y+1 < len(board):
if board[y+1][x] != '#':
if self.search(board, x, y+1, word): #d
return True
# left
if x-1 >= 0:
if board[y][x-1] != '#':
if self.search(board, x-1, y, word): #l
return True
# right
if x+1 < len(board[0]):
if board[y][x+1] != '#':
if self.search(board, x+1, y, word): # r
return True
board[y][x] = temp_data
return False
# return
# if not word:
# return True
# # up
# if y-1 >= 0:
# if board[y-1][x] == word[0]:
# temp_board = board
# # temp_board = copy.deepcopy(board)
# temp_board[y-1][x] = '#'
# if self.search(temp_board, x, y-1, word[1:]):
# return True
# # down
# if y+1 < len(board):
# if board[y+1][x] == word[0]:
# temp_board = board
# #
# # temp_board = copy.deepcopy(board)
# temp_board[y+1][x] = '#'
# if self.search(temp_board, x, y+1, word[1:]):
# return True
# # left
# if x-1 >= 0:
# if board[y][x-1] == word[0]:
# temp_board = board
# # temp_board = copy.deepcopy(board)
# temp_board[y][x-1] = '#'
# if self.search(temp_board, x-1, y, word[1:]):
# return True
# # right
# if x+1 < len(board[0]):
# if board[y][x+1] == word[0]:
# temp_board = board
# # temp_board = copy.deepcopy(board)
# temp_board[y][x+1] = '#'
# if self.search(temp_board, x+1, y, word[1:]):
# return True
# return False
"""
改进一下,还是用DFS,不过这次不会在预先去寻找入口。
结果更慢。
"""
# class Solution(object):
# def exist(self, board, word):
# """
# :type board: List[List[str]]
# :type word: str
# :rtype: bool
# """
# return self.search(board, 0, 0, word)
# def search(self, board, x, y, word):
# """
# """
# # return
# if not word:
# return True
# # if x == len(board[0][0]) and y == len(board):
# # return False
# if board[y][x] == word[0]:
# word = word[1:]
# board[y][x] = '#'
# # if not word:
# # return True
# # up
# if y-1 >= 0:
# if board[y-1][x] != '#':
# temp_board = copy.deepcopy(board)
# if self.search(temp_board, x, y-1, word):
# return True
# # down
# if y+1 < len(board):
# if board[y+1][x] != '#':
# temp_board = copy.deepcopy(board)
# if self.search(temp_board, x, y+1, word):
# return True
# # left
# if x-1 >= 0:
# if board[y][x-1] != '#':
# temp_board = copy.deepcopy(board)
# if self.search(temp_board, x-1, y, word):
# return True
# # right
# if x+1 < len(board[0]):
# if board[y][x+1] != '#':
# temp_board = copy.deepcopy(board)
# if self.search(temp_board, x+1, y, word):
# return True
# return False
"""
2018/10/25
刷 Word Search II 时重新回顾了一下。
用这次刷II的方法重新测试,
beat
84%
测试地址:
https://leetcode.com/problems/word-search/description/
练习是有效果的。 ^_^
"""
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def find(board, x, y, word):
if not word:
return True
if board[y][x] == word[0]:
raw = board[y][x]
board[y][x] = 0
if len(word) == 1:
board[y][x] = raw
return True
else:
return False
# up
if y-1 >= 0 and board[y-1][x] == word[1]:
if find(board, x, y-1, word[1:]):
board[y][x] = raw
return True
# down
if y+1 < len(board) and board[y+1][x] == word[1]:
if find(board, x, y+1, word[1:]):
board[y][x] = raw
return True
# left
if x-1 >= 0 and board[y][x-1] == word[1]:
if find(board, x-1, y, word[1:]):
board[y][x] = raw
return True
# right
if x+1 < len(board[0]) and board[y][x+1] == word[1]:
if find(board, x+1, y, word[1:]):
board[y][x] = raw
return True
board[y][x] = raw
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if find(board, j, i, word):
return True
return False
|
8ce70b6bef2ddd80f99bd12adce0f1c88733d146 | syurskyi/Python_Topics | /115_testing/_exercises/exercises/The_Modern_Python_3_Bootcamp/295. Assertions.py | 481 | 3.546875 | 4 | # # Example 1
# ___ add_positive_numbers x, y
# a.. x > 0 an. y > 0, "Both numbers must be positive!"
# r_ x + y
#
#
# print ? 1, 1) # 2
# ? 1, -1 # AssertionError: Both numbers must be positive!
#
# # Example 2
#
#
# ___ eat_junk food
# a.. food __ [
# "pizza",
# "ice cream",
# "candy",
# "fried butter"
# ], "food must be a junk food!"
# r_ _*NOM NOM NOM I am eating ?"
#
#
# food _ in..("ENTER A FOOD PLEASE: ")
# print ? ?
|
76d1213f90d810ba33560e60191988dc7f7464a8 | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 2 - Add Binary.py | 1,423 | 3.9375 | 4 | # Add Binary
# Question: Given two binary strings, return their sum (also a binary string).
# For example,
# a = "11"
# b = "1"
# Return "100".
# Solutions:
class Solution:
def addBinary( a, b):
length = max(len(a),len(b)) + 1
sum = ['0' for i in range(length)]
if len(a) <= len(b):
a = '0' * ( len(b) - len(a) ) + a
if len(a) > len(b):
b = '0' * ( len(a) - len(b) ) + b
Carry = 0
i = len(a) - 1
while i >= 0:
if int(a[i]) + int(b[i]) + Carry == 3:
sum[i+1] = '1'
Carry = 1
elif int(a[i]) + int(b[i]) + Carry == 2:
sum[i+1] = '0'
Carry = 1
elif int(a[i]) + int(b[i]) + Carry == 1:
sum[i+1] = '1'
Carry = 0
else:
sum[i+1] = '0'
Carry = 0
i = i - 1
if Carry == 1:
sum[0] = '1'
if Carry == 0:
sum = sum[1:length]
sum = ''.join(sum)
return sum
Solution.addBinary("11","1")
class Solution:
def addBinary(a, b):
bia = int(a, 2)
bib = int(b, 2)
sum = bia + bib
return str("{0:b}".format(sum))
Solution.addBinary("1","11")
# *Should only use if asked for shorter solution. It converts binary to integers; sum the integers. And finally formats the answer as binary. |
3452335bdf32e92235ec2f2886bbaa734c3f1134 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/377 Combination Sum IV.py | 1,359 | 3.921875 | 4 | """
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up
to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
"""
__author__ 'Daniel'
c_ Solution(o..
___ combinationSum4 nums, target
"""
Let F[i] be the number of combinations ways for number i
F[i] = sum(F[i-k] for k in nums)
If negative number allowed, [1, -1], 1, then infinite combinations.
If the target is large, recursion & memoization is more space saving
:type nums: List[int]
:type target: int
:rtype: int
"""
F [0 ___ _ __ x..(target + 1)]
nums f.. l.... x: x <_ target, nums)
___ k __ nums:
F[k] 1
___ i __ x..(target + 1
___ k __ nums:
__ i - k >_ 0:
F[i] += F[i-k]
r.. F[target]
__ _______ __ _______
... Solution().combinationSum4([1, 2, 3], 4) __ 7
|
7d224673021096bc698a88ba105df03da80950bd | syurskyi/Python_Topics | /110_concurrency_parallelism/_exercises/templates/Gitlab/Python-multi-threading-examples/pyth_01.py | 637 | 3.984375 | 4 |
print "Hello"
xxa = raw_input("Enter a number\n")
___
num1= float(xxa)
_______
print "Invalid input. Please insert a number or type done to finish"
loop= 0
count= 0
running_total= 0
w___ loop ==0:
inp = raw_input("Enter a number:")
__ inp== "done" or inp== "Done" :
____
___
num= float(inp)
_______
print "Invalid input. Please insert a number or type done to finish"
______
count= count + 1
running_total= running_total + num
print count," numbers input"
print running_total," total"
print "and average:", running_total/count |
de858ef574b405fb7b63b49157118cc320ac5197 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/002_list_comprehension/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 21 More List Comprehension Exercises.py | 461 | 4.03125 | 4 | # Using list comprehensions(the more Pythonic way):
answer = [val for val in [1, 2, 3, 4] if val in [3, 4, 5, 6]]
# the slice [::-1] is a quick way to reverse a string
answer2 = [val[::-1].lower() for val in ["Elie", "Tim", "Matt"]]
# Without list comprehensions, things are a bit longer:
answer = []
for x in [1,2,3,4]:
if x in [3,4,5,6]:
answer.append(x)
answer2 = []
for name in ["Elie", "Tim", "Matt"]:
answer2.append(name[::-1].lower())
|
5e29b94012ca18356083d3227a38a1ea08c5d309 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/109 Convert Sorted List to Binary Search Tree.py | 1,364 | 3.546875 | 4 | """
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
"""
__author__ 'Danyang'
# Definition for a binary tree node
c_ TreeNode:
___ - , x
val x
left N..
right N..
# Definition for singly-linked list.
c_ ListNode:
___ - , x
val x
next N..
c_ Solution:
# class attribute to keep trace the currently processing nodes
# current_node = None
___ -
current_node N.. # !important, avoid time complexity of look up
___ sortedListToBST head
"""
dfs
No O(1) access.
Bottom-up construction
:param head: ListNode
:return: TreeNode
"""
__ n.. head:
r.. head
current_node head
length getLength(head)
r.. sortedListToBST_dfs(0, length-1)
___ sortedListToBST_dfs start, end
__ start>end:
r..
mid (start+end)/2
left_subtree sortedListToBST_dfs(start, mid-1)
root TreeNode(current_node.val)
current_node current_node.next
right_subtree sortedListToBST_dfs(mid+1, end)
root.left left_subtree
root.right right_subtree
r.. root
___ getLength head
count 0
w.... head:
head head.next
count += 1
r.. count |
9704cae30d70ad976d7e0d9eb0d2456cfeb753cb | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/450_reverse_nodes_in_k_group.py | 1,038 | 3.578125 | 4 | """
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
c_ Solution:
"""
@param: head: a ListNode
@param: k: An integer
@return: a ListNode
"""
___ reverseKGroup head, k
__ n.. head:
r..
dummy ? 0
dummy.next head
head dummy
w.... head:
head reverse_next_kth(head, k)
r.. dummy.next
___ find_kth head, k
___ i __ r..(k
__ n.. head:
r..
head head.next
r.. head
___ reverse head
pre nxt N..
w.... head:
nxt head.next
head.next pre
pre head
head nxt
r.. pre
___ reverse_next_kth head, k
nk find_kth(head, k)
__ n.. nk:
r..
nk_nxt nk.next
n1_pre head
n1 head.next
nk.next N..
reverse(n1)
n1_pre.next nk
n1.next nk_nxt
r.. n1
|
6b442f9d5799c3bf2b6fa7c18e4fbd4848523d28 | syurskyi/Python_Topics | /070_oop/008_metaprogramming/_exercises/templates/Expert Python Programming/new_method_instance_counting.py | 936 | 3.75 | 4 | # """
# "Using the __new__() method to override instance creation process" section
# example of overriding `__new__()` method to count class instances
#
# """
# ____ ra... ______ r_i..
#
#
# c_ InstanceCountingClass:
# instances_created _ 0
#
# ___ -n ___ $ $$
# print('__new__() called with:' ___ a.. kw..
# instance _ s___ . -n ___
# ?.nu.. _ ___.i_c..
# ___.i_c.. +_ 1
#
# r_ i...
#
# ___ - attribute
# print('__init__() called with:' ? ?
# ? ?
#
#
# __ _______ __ _______
# print(
# "InstanceCountingClass.instances_created _",
# I___.i_c..
# )
#
# desired_count _ r_i.. 2 10
# print(
# "Creating @ instances of InstanceCountingClass..."
# "".f... ?
# )
#
# ___ number __ ra.. ?
# I___ ?
#
# print(
# "InstanceCountingClass.instances_created _",
# I____.i_c..
# )
|
b4e8b3336ffe59ee90ac13455c7237726b99a433 | syurskyi/Python_Topics | /125_algorithms/_examples/Practice_Python_by_Solving_100_Python_Problems/86.py | 356 | 3.8125 | 4 | #Create a script that checks a list against countries_clean.txt
#and creates a list with items that were in that file
checklist = ["Portugal", "Germany", "Munster", "Spain"]
with open("countries_clean.txt", "r") as file:
content = file.r..
content = [i.rstrip('\n') for i in content]
checked = [i for i in content if i in checklist]
print(checked)
|
1bd3d72efbeb37edd891d8998bbf617539ec7735 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/001_iterations_and_iteration_tool/examples/007_Python Built-In Iterables and Iterators.py | 3,503 | 4.40625 | 4 | # Python Built-In Iterables and Iterators
# for the list
# Since the list l is an iterable it also implements the __iter__ method:
# Of course, since lists are also sequence types, they also implement the __getitem__ method:
l = [1, 2, 3]
iter_l = iter(l)
#or could use iter_1 = l.__iter__()
type(iter_l)
next(iter_l)
next(iter_l)
next(iter_l)
'__iter__' in dir(l)
'__getitem__' in dir(l)
# But what does the iterator for a dictionary actually return?
# To iterate over the values, we could use the values() method which returns an iterable over the values of the dictionary:
# And to iterate over both the keys and values, dictionaries provide an items() iterable:
d = dict(a=1, b=2, c=3)
iter_d = iter(d)
next(iter_d)
# Dictionary iterators will iterate over the keys of the dictionary.
iter_vals = iter(d.values())
next(iter_vals)
iter_items = iter(d.items())
next(iter_items)
# Cyclic Iterators
class CyclicIterator:
def __init__(self, lst):
self.lst = lst
self.i = 0
def __iter__(self):
return self
def __next__(self):
result = self.lst[self.i % len(self.lst)]
self.i += 1
return result
iter_cycl = CyclicIterator('NSWE')
for i in range(10):
print(next(iter_cycl))
#
n = 10
iter_cycl = CyclicIterator('NSWE')
for i in range(1, n+1):
direction = next(iter_cycl)
print(f'{i}{direction}')
# Python's Built-In Iterables and Iterators
# Let's look at the simple range function first:
# But it is not an iterator:
# However, we can request an iterator by calling the __iter__ method, or simply using the iter() function:
# And of course this is now an iterator:
r_10 = range(10)
'__iter__' in dir(r_10)
'__next__' in dir(r_10)
r_10_iter = iter(r_10)
'__iter__' in dir(r_10_iter)
'__next__' in dir(r_10_iter)
# Python's Built-In Iterables and Iterators
# zip
# Just like range() though, it also uses lazy evaluation, so we need to iterate through the iterator and make a list
# for example in order to see the contents:
# Even reading a file line by line is done using lazy evaluation:
# As you can see, the open() function returns an iterator (of type TextIOWrapper), and we can read lines from the file
# one by one using the next() function, or calling the __next__() method. The class also implements a readline()
# method we can use to get the next row:
z = zip([1, 2, 3], 'abc')
z
print('__iter__' in dir(z))
print('__next__' in dir(z))
list(z)
with open('cars.csv') as f:
print(type(f))
print('__iter__' in dir(f))
print('__next__' in dir(f))
with open('cars.csv') as f:
print(next(f))
print(f.__next__())
print(f.readline())
# Python's Built-In Iterables and Iterators
# The enumerate function is another lazy iterator:
#
# As we can see, the object and its iterator are the same object.
#
# But enumerate is also lazy, so we need to iterate through it in order to recover all the elements:
# Of course, once we have exhausted the iterator, we cannot use it again:
e = enumerate('Python rocks!')
print('__iter__' in dir(e))
print('__next__' in dir(e))
iter(e)
e
list(e)
list(e)
# Python's Built-In Iterables and Iterators
# The dictionary object provides methods that return iterables for the keys, values or tuples of key/value pairs:
#
# More simply, we can just test to see if iter(keys) is the same object as keys - if not then we are dealing with an iterable.
d = {'a': 1, 'b': 2}
keys = d.keys()
'__iter__' in dir(keys), '__next__' in dir(keys)
iter(keys) is keys
|
ef65f3e6ecf0a06432245913a1d0baaef73b08f7 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/339 Nested List Weight Sum.py | 1,282 | 3.78125 | 4 | """
Premium Question
"""
__author__ 'Daniel'
"""
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
c_ NestedInteger(o..
___ isInteger
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"""
___ getInteger
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
:rtype int
"""
___ getList
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
:rtype List[NestedInteger]
"""
c_ Solution(o..
___ -
s.. 0
___ depthSum nestedList
"""
NestedInteger is a union type
:type nestedList: List[NestedInteger]
:rtype: int
"""
___ elt __ nestedList:
dfs(elt, 1)
r.. s..
___ dfs ni, depth
__ ni.isInteger
s.. += ni.getInteger() * depth
____
lst ni.getList()
___ elt __ lst:
dfs(elt, depth + 1)
|
aa6cf1b7b7180c938be13cb74af56767ff6b8a9f | syurskyi/Python_Topics | /045_functions/005_decorators/_exercises/_templates/The_Modern_Python_3_Bootcamp/279. Higher Order Functions_higher-order.py | 260 | 3.875 | 4 | # We can pass funcs as args to other funcs
def sum(n, func):
total = 0
for num in range(1, n+1):
total += func(num)
return total
def square(x):
return x*x
def cube(x):
return x*x*x
print(sum(3, cube))
print(sum(3, square))
|
2c45f7d0fe5178ddb632cdf3b52a141ff1f572e2 | syurskyi/Python_Topics | /070_oop/008_metaprogramming/examples/Interface/Implementing an Interface in Python/a_001_Informal Interfaces.py | 3,805 | 4.375 | 4 | # In certain circumstances, you may not need the strict rules of a formal Python interface. Python's dynamic nature
# allows you to implement an informal interface. An informal Python interface is a class that defines methods that
# can be overridden, but there's no strict enforcement.
#
# In the following example, you will take the perspective of a data engineer who needs to extract text from various
# different unstructured file types, like PDFs and emails. You will create an informal interface that defines the methods
# that will be in both the PdfParser and EmlParser concrete classes:
class InformalParserInterface:
def load_data_source(self, path: str, file_name: str) -> str:
"""Load in the file for extracting text."""
pass
def extract_text(self, full_file_name: str) -> dict:
"""Extract text from the currently loaded file."""
pass
# InformalParserInterface defines the two methods .load_data_source() and .extract_text(). These methods are defined
# but not implemented. The implementation will occur once you create concrete classes that inherit from
# InformalParserInterface.
# you define two classes that implement the InformalParserInterface. To use your interface, you must create
# a concrete class. A concrete class is a subclass of the interface that provides an implementation of the interface's
# methods. You'll create two concrete classes to implement your interface. The first is PdfParser, which you'll use
# to parse the text from PDF files:
class PdfParser(InformalParserInterface):
"""Extract text from a PDF"""
def load_data_source(self, path: str, file_name: str) -> str:
"""Overrides InformalParserInterface.load_data_source()"""
pass
def extract_text(self, full_file_path: str) -> dict:
"""Overrides InformalParserInterface.extract_text()"""
pass
# The concrete implementation of InformalParserInterface now allows you to extract text from PDF files.
# The second concrete class is EmlParser, which you'll use to parse the text from emails:
class EmlParser(InformalParserInterface):
"""Extract text from an email"""
def load_data_source(self, path: str, file_name: str) -> str:
"""Overrides InformalParserInterface.load_data_source()"""
pass
def extract_text_from_email(self, full_file_path: str) -> dict:
"""A method defined only in EmlParser.
Does not override InformalParserInterface.extract_text()
"""
pass
# The concrete implementation of InformalParserInterface now allows you to extract text from email files.
#
# So far, you've defined two concrete implementations of the InformalPythonInterface. However, note that EmlParser
# fails to properly define .extract_text(). If you were to check whether EmlParser implements InformalParserInterface,
# then you'd get the following result:
# Check if both PdfParser and EmlParser implement InformalParserInterface
issubclass(PdfParser, InformalParserInterface)
# True
issubclass(EmlParser, InformalParserInterface)
# True
# Now check the method resolution order (MRO) of PdfParser and EmlParser. This tells you the superclasses of
# the class in question, as well as the order in which they're searched for executing a method. You can view
# a class's MRO by using the dunder method cls.__mro__:
print(PdfParser.__mro__)
# (__main__.PdfParser, __main__.InformalParserInterface, object)
print(EmlParser.__mro__)
# (__main__.EmlParser, __main__.InformalParserInterface, object)
# Such informal interfaces are fine for small projects where only a few developers are working on the source code.
# However, as projects get larger and teams grow, this could lead to developers spending countless hours looking for
# hard-to-find logic errors in the codebase!
|
bb11a7e5db0d8020050c2498d675d260e42736cd | syurskyi/Python_Topics | /060_context_managers/_exercises/templates/99. Caveat when used with Lazy Iterators.py | 1,665 | 3.6875 | 4 | # # We have to be careful when working with context managers and lazy iterators.
# # Consider this example where we want to create a generator from a file:
#
# print('#' * 52 + ' ### Caveat with Lazy Iterators')
#
# ______ cs
#
#
# ___ read_data
# w___ o... 'nyc_parking_tickets_extract.csv' __ f
# r_ cs_.re.. f delimiter_',', quotechar_'"'
#
# # for row in read_data():
# # print(row) # ValueError: I/O operation on closed file.
#
# # As you can see, read_data returns a lazy iterator (csv.reader), but by the time we iterate over it, the with context
# # that opened the file was exited, and the file was closed!
# # We have two possible solutions here:
# # The first one is not very desirable since it involves reading the entire file into memory by iterating the file
# # and putting it into a list before we exit the with block:
#
#
# print('#' * 52 + ' The first one is not very desirable since it involves reading the entire file into memory'
# ' by iterating the file and putting it into a list before we exit the `with` block:')
#
#
# ___ read_data
# w___ o.. 'nyc_parking_tickets_extract.csv') __ f
# r_ li cs_.re.. delimiter_',', quotechar_'"'
#
#
# ___ row __ ?
# print ?
#
# # The second method, the one we have used quite a bit, involves yielding each row from the csv reader:
#
# print('#' * 52 + ' The second method, the one we have used quite a bit,'
# ' involves yielding each row from the csv reader:')
#
#
# ___ read_data
# w___ o.. ('nyc_parking_tickets_extract.csv') __ f
# y_____ f.. cs_.re.. f de..._',' quot.._'"'
#
#
# ___ row __ ?
# print ?
|
8e95f3a8844ab693ff4caf46ceb24ae26cafc62b | syurskyi/Python_Topics | /045_functions/008_built_in_functions/zip/examples/007_Passing One Argument.py | 262 | 3.75 | 4 | a = [1, 2, 3]
zipped = zip(a)
list(zipped)
# [(1,), (2,), (3,)]
integers = [1, 2, 3]
letters = ['a', 'b', 'c']
floats = [4.0, 5.0, 6.0]
zipped = zip(integers, letters, floats) # Three input iterables
list(zipped)
# [(1, 'a', 4.0), (2, 'b', 5.0), (3, 'c', 6.0)] |
86820b97e77fd23dc64e58e2e45ceb3e7497f642 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/234/sentences.py | 636 | 3.859375 | 4 | from test_sentences import *
import re
def capitalize_sentences(text: str) -> str:
"""Return text capitalizing the sentences. Note that sentences can end
in dot (.), question mark (?) and exclamation mark (!)"""
text_metacharacters = re.findall("[\\!\\.\\?]", text.strip())
text_raw = re.split("[\\!\\.\\?]\s", text.strip())
text_clean = []
for i in range(len(text_raw)):
text_clean.append(f"{text_raw[i].capitalize()}{(text_metacharacters[i] if i != len(text_metacharacters) -1 else '')}")
return " ".join(text_clean)
if __name__ == "__main__":
print(capitalize_sentences(" ".join(text2).lower())) |
3b177753265b1d2c5fa8ee6aa75088b55ab35e62 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/4/pipe.py | 360 | 3.6875 | 4 | # message = """Hello world!
# We hope that you are learning a lot of Python.
# Have fun with our Bites of Py.
# Keep calm and code in Python!
# Become a PyBites ninja!"""
#
# ___ split_in_columns message_?
# """Split the message by newline (\n) and join it together on '|'
# (pipe), return the obtained output string"""
# r.. '|'.j.. ?.s..('\n'
|
7f571f75e4cde471f37e78d7b6e3f64255c5e9dd | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/topics/String/8/test_rotate.py | 1,794 | 4.46875 | 4 | ____ rotate _______ rotate
___ test_small_rotate
... rotate('hello', 2) __ 'llohe'
... rotate('hello', -2) __ 'lohel'
___ test_bigger_rotation_of_positive_n
s__ 'bob and julian love pybites!'
e.. 'love pybites!bob and julian '
... rotate(s__, 15) __ e..
___ test_bigger_rotation_of_negative_n
s__ 'pybites loves julian and bob!'
e.. 'julian and bob!pybites loves '
... rotate(s__, -15) __ e..
___ test_rotation_of_n_same_as_len_str
s__ e.. 'julian and bob!'
... rotate(s__, l..(s__ __ e..
___ test_rotation_of_n_bigger_than_string
"""
Why are there two expected results for this test?
This Bite can be interpreted in two ways:
1. A slice of size n moved from one end of the string to the other
2. A continual rotation, character by character, n number of times
Both interpretations result in identical output, except in the case
where the rotation size exceeds the length of the string.
Case 1) With a slice method, slicing an entire string and placing
it at either the beginning or end of itself simply results in the
the original string = expected_solution1
Case 2) With a continual rotation, rotating the string len(string)
number of times produces a string idential to the original string.
This means any additional rotations can be considered equivalent to
rotating the string by rotations % len(string) = expected_solution2
"""
s__ 'julian and bob!'
expected_solution1 'julian and bob!'
expected_solution2 ' bob!julian and'
... rotate(s__, 100) __ (expected_solution1,
expected_solution2)
mod 100 % l..(s__) # 10
... rotate(s__, mod) __ (expected_solution1,
expected_solution2) |
937e349234190b8b96f3d110593259c411c01014 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/374_Guess_Number_Higher_or_Lower.py | 567 | 3.59375 | 4 | # The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
c_ Solution o..
___ guessNumber n
"""
:type n: int
:rtype: int
"""
# binary search
begin, end = 1, n
w.. begin <= end:
mid = (begin + end) / 2
res = guess(mid)
__ res __ 0:
r_ mid
____ res > 0:
begin = mid + 1
____
end = mid - 1
|
68fbe016da1345b61f863902bbeadf29b279c3f9 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/The Complete Data Structures and Algorithms Course in Python/Section 18 Cracking Linked List Interview Questions/Q4_SumLists.py | 648 | 4.03125 | 4 | # Created by Elshad Karimov on 18/05/2020.
# Copyright © 2020 AppMillers. All rights reserved.
# Question 4 - Sum Lists
____ LinkedList _____ LinkedList
___ sumList(llA, llB
n1 llA.head
n2 llB.head
carry 0
ll LinkedList()
w__ n1 o. n2:
result carry
__ n1:
result + n1.value
n1 n1.next
__ n2:
result + n2.value
n2 n2.next
ll.add(__.(result % 10))
carry result / 10
r_ ll
llA LinkedList()
llA.add(7)
llA.add(1)
llA.add(6)
llB LinkedList()
llB.add(5)
llB.add(9)
llB.add(2)
print(llA)
print(llB)
print(sumList(llA, llB))
|
bd06af8192fae584aff2a1e7421e9c2f6cf5bd79 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/99_v2/sequence_generator.py | 293 | 3.84375 | 4 | import string
import itertools
def sequence_generator():
numbers = list(range(1,27))
sequence = [numbers[i//2] if i % 2 == 0 else string.ascii_uppercase[i//2] for i in range(52)]
yield from itertools.cycle(sequence)
if __name__ == "__main__":
sequence_generator()
|
c8543619c1c3a6ddccda7adc21b50209c03d8ee2 | syurskyi/Python_Topics | /120_design_patterns/002_builder/_exercises/_templates/001_builder.py | 1,978 | 3.75 | 4 | # #!/usr/bin/python
# # -*- coding : utf-8 -*-
#
# """
# *What is this pattern about?
# It decouples the creation of a complex object and its representation,
# so that the same process can be reused to build objects from the same
# family.
# This is useful when you must separate the specification of an object
# from its actual representation (generally for abstraction).
#
# *What does this example do?
# This particular example uses a director function to abstract the
# construction of a building. The user specifies a Builder (House or
# Flat) and the director specifies the methods in the order necessary,
# creating a different building depending on the specification
# (from the Builder c_).
#
# @author: Diogenes Augusto Fernandes Herminio <diofeher@gmail.com>
# https://gist.github.com/420905#file_builder_python.py
#
# *Where is the pattern used practically?
#
# *References:
# https://sourcemaking.com/design_patterns/builder
#
# *TL;DR80
# Decouples the creation of a complex object and its representation.
# """
#
#
# ___ construct_building builder
# ?.n..
# ?.b_f..
# ?.b_s..
# r_ ?.b..
#
#
# # Abstract Builder
# c_ Builder o..
#
# ___ -
# building _ N..
#
# ___ new_building
# ____.building _ B..
#
# ___ build_floor
# ra.. N...
#
# ___ build_size
# ra.. N..
#
# # Concrete Builder
#
#
# c_ BuilderHouse B..
#
# ___ build_floor
# building.floor _ 'One'
#
# ___ build_size
# building.size _ 'Big'
#
#
# c_ BuilderFlat B..
# ___ build_floor ____
# building.floor _ 'More than One'
#
# ___ build_size
# building.size _ 'Small'
#
#
# # Product
# c_ Building o..
#
# ___ -
# floor _ N..
# size _ N..
#
# ___ -r ____
# r_ 'Floor: 0.f.. | Size: 0.s..'.f.. ____
#
#
# # Client
# __ _____ __ _______
# building _ c... BH..
# print ?
# building _ c.. BF..
# print ?
#
# ### OUTPUT ###
# # Floor: One | Size: Big
# # Floor: More than One | Size: Small
|
c168bbdfaf22f4cd88103d7151e0dc8b3b738b86 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/091 Decode Ways.py | 1,390 | 3.90625 | 4 | """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
"""
__author__ 'Danyang'
c_ Solution(o..
___ numDecodings s
"""
F
Let F[i] be the number of decode ways for s[:i]
- 1 2 2 3 1 2 2 3
1 1 2 ? ?
F[i] = (F[i-1]) + optional(F[i-2]))
notice the special handling for "0
:param s: a string
:return: an integer
"""
__ s.s.. "0"
r.. 0
n l..(s)
__ n.. s:
r.. 0
F [0 ___ _ __ x..(n+1)]
F[0] 1
F[1] 1
___ i __ x..(2, n+1
__ s[i-1] !_ "0":
F[i] F[i-1]
__ 10 <_ i..(s[i-2]+s[i-1]) < 27:
F[i] += F[i-2]
____ # 0 is special
__ s[i-2] __ ("1", "2"
F[i] F[i-2]
____
r.. 0
r.. F[-1]
__ _______ __ _______
... Solution().numDecodings("10") __ 1
... Solution().numDecodings("27") __ 1
... Solution().numDecodings("12") __ 2
... Solution().numDecodings("0") __ 0 |
7aabe12258ce1b1a2d3f8fccf590467bc5663eb1 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/73_SetMatrixZeroes.py | 1,459 | 3.875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
# Frist, make sure whether first row and first col is all 0.
first_row = False
for i in range(n):
if matrix[0][i] == 0:
first_row = True
first_col = False
for j in range(m):
if matrix[j][0] == 0:
first_col = True
# Keep the information about the 0 cell to first row and first col.
for row in range(1, m):
for col in range(1, n):
if matrix[row][col] == 0:
matrix[row][0] = 0
matrix[0][col] = 0
# Set 0s according to the information in first row and first col
for row in range(m):
for col in range(n):
if not matrix[row][0] or not matrix[0][col]:
matrix[row][col] = 0
# Set the first row and first col
if first_row:
for col in range(n):
matrix[0][col] = 0
if first_col:
for row in range(m):
matrix[row][0] = 0
"""
[[0]]
[[1,0],[2,2]]
[[0,0,0,5],[4,3,1,4],[0,1,1,4],[1,2,1,3],[0,0,1,1]]
"""
|
6b853a583be5728336bfbb3368fb53ef4a3af8e1 | syurskyi/Python_Topics | /070_oop/004_inheritance/examples/super/Supercharge Your Classes With Python super()/005_Method Resolution Order.py | 6,828 | 3.921875 | 4 | # The method resolution order (or MRO) tells Python how to search for inherited methods.
# This comes in handy when you're using super() because the MRO tells you exactly where Python will look for
# a method you're calling with super() and in what order.
#
# Every class has an .__mro__ attribute that allows us to inspect the order, so let;s do that:
RightPyramid.__mro__
# (<class '__main__.RightPyramid'>, <class '__main__.Triangle'>,
# <class '__main__.Square'>, <class '__main__.Rectangle'>,
# <class 'object'>)
# This tells us that methods will be searched first in Rightpyramid, then in Triangle, then in Square, then Rectangle,
# and then, if nothing is found, in object, from which all classes originate.
# The problem here is that the interpreter is searching for .area() in Triangle before Square and Rectangle,
# and upon finding .area() in Triangle, Python calls it instead of the one you want. Because Triangle.area()
# expects there to be a .height and a .base attribute, Python throws an AttributeError.
# Luckily, you have some control over how the MRO is constructed. Just by changing the signature
# of the RightPyramid class, you can search in the order you want, and the methods will resolve correctly:
class RightPyramid(Square, Triangle):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
super().__init__(self.base)
def area(self):
base_area = super().area()
perimeter = super().perimeter()
return 0.5 * perimeter * self.slant_height + base_area
# Notice that RightPyramid initializes partially with the .__init__() from the Square class.
# This allows .area() to use the .length on the object, as is designed.
#
# Now, you can build a pyramid, inspect the MRO, and calculate the surface area:
#
pyramid = RightPyramid(2, 4)
RightPyramid.__mro__
# (<class '__main__.RightPyramid'>, <class '__main__.Square'>,
# <class '__main__.Rectangle'>, <class '__main__.Triangle'>,
# <class 'object'>)
pyramid.area()
# 20.0
# You see that the MRO is now what you'd expect, and you can inspect the area of the pyramid as well, thanks
# to .area() and .perimeter().
#
# There's still a problem here, though. For the sake of simplicity, I did a few things wrong in this example:
# the first, and arguably most importantly, was that I had two separate classes with the same method name and signature.
# This causes issues with method resolution, because the first instance of .area() that is encountered
# in the MRO list will be called.
#
# When you're using super() with multiple inheritance, it's imperative to design your classes to cooperate.
# Part of this is ensuring that your methods are unique so that they get resolved in the MRO, by making sure
# method signatures are unique-whether by using method names or method parameters.
#
# In this case, to avoid a complete overhaul of your code, you can rename the Triangle class's .area() method
# to .tri_area(). This way, the area methods can continue using class properties rather than taking external parameters:
class Triangle:
def __init__(self, base, height):
self.base = base
self.height = height
super().__init__()
def tri_area(self):
return 0.5 * self.base * self.height
# Let's also go ahead and use this in the RightPyramid class:
class RightPyramid(Square, Triangle):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
super().__init__(self.base)
def area(self):
base_area = super().area()
perimeter = super().perimeter()
return 0.5 * perimeter * self.slant_height + base_area
def area_2(self):
base_area = super().area()
triangle_area = super().tri_area()
return triangle_area * 4 + base_area
# The next issue here is that the code doesn't have a delegated Triangle object like it does for a Square object,
# so calling .area_2() will give us an AttributeError since .base and .height don't have any values.
#
# You need to do two things to fix this:
#
# All methods that are called with super() need to have a call to their superclass's version of that method.
# This means that you will need to add super().__init__() to the .__init__() methods of Triangle and Rectangle.
#
# Redesign all the .__init__() calls to take a keyword dictionary. See the complete code below.
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
super().__init__(**kwargs)
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
# Here we declare that the Square class inherits from
# the Rectangle class
class Square(Rectangle):
def __init__(self, length, **kwargs):
super().__init__(length=length, width=length, **kwargs)
class Cube(Square):
def surface_area(self):
face_area = super().area()
return face_area * 6
def volume(self):
face_area = super().area()
return face_area * self.length
class Triangle:
def __init__(self, base, height, **kwargs):
self.base = base
self.height = height
super().__init__(**kwargs)
def tri_area(self):
return 0.5 * self.base * self.height
class RightPyramid(Square, Triangle):
def __init__(self, base, slant_height, **kwargs):
self.base = base
self.slant_height = slant_height
kwargs["height"] = slant_height
kwargs["length"] = base
super().__init__(base=base, **kwargs)
def area(self):
base_area = super().area()
perimeter = super().perimeter()
return 0.5 * perimeter * self.slant_height + base_area
def area_2(self):
base_area = super().area()
triangle_area = super().tri_area()
return triangle_area * 4 + base_area
# There are a number of important differences in this code:
# kwargs is modified in some places (such as RightPyramid.__init__()): This will allow users of these objects
# to instantiate them only with the arguments that make sense for that particular object.
# Setting up named arguments before **kwargs: You can see this in RightPyramid.__init__().
# This has the neat effect of popping that key right out of the **kwargs dictionary, so that by the time that
# it ends up at the end of the MRO in the object class, **kwargs is empty.
# Now, when you use these updated classes, you have this:
#
pyramid = RightPyramid(base=2, slant_height=4)
pyramid.area()
# 20.0
pyramid.area_2()
# 20.0
# It works! You've used super() to successfully navigate a complicated class hierarchy while using both inheritance
# and composition to create new classes with minimal reimplementation.
|
08928a50181feb1eb774eee5cedef8be10e5ec2e | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Mock_Helpers.py | 6,507 | 3.625 | 4 | # Python Unittest
# unittest.mock � mock object library
# unittest.mock is a library for testing in Python.
# It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
# unittest.mock provides a core Mock class removing the need to create a host of 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.
#
# Helpers:
# sentinel
# unittest.mock.sentinel
#
# The sentinel object provides a convenient way of providing unique objects for your tests.
#
# Attributes are created on demand when you access them by name.
# Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.
# The sentinel attributes now preserve their identity when they are copied or pickled.
#
# Sometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named
# sentinel objects to test this. sentinel provides a convenient way of creating and testing the identity of objects like this.
#
# In this example we monkey patch method to return sentinel.some_object:
#
real _ ProductionClass()
real.method _ Mock(name_"method")
real.method.return_value _ sentinel.some_object
result _ real.method()
a.. result __ sentinel.some_object
sentinel.some_object
# OUTPUT: 'sentinel.some_object'
#
# DEFAULT:
# unittest.mock.DEFAULT:
# The DEFAULT object is a pre-created sentinel (actually sentinel.DEFAULT). It can be used by side_effect functions to indicate that the normal return value
# should be used.
#
#
# call:
# unittest.mock.call(*args, **kwargs).
# call() is a helper object for making simpler assertions, for comparing with call_args, call_args_list, mock_calls and method_calls.
# call() can also be used with assert_has_calls().
#
m _ MagicMock(return_value_None)
m(1, 2, a_'foo', b_'bar')
m()
m.call_args_list __ [call(1, 2, a_'foo', b_'bar'), call()]
# OUTPUT: 'True'
#
# call.call_list():
# For a call object that represents multiple calls, call_list() returns a list of all the intermediate calls as well as the final call.
# call_list is particularly useful for making assertions on �chained calls�. A chained call is multiple calls on a single line of code.
# This results in multiple entries in mock_calls on a mock. Manually constructing the sequence of calls can be tedious.
# call_list() can construct the sequence of calls from the same chained call:
#
m _ MagicMock()
m(1).method(arg_'foo').other('bar')(2.0)
# OUTPUT: '<MagicMock name='mock().method().other()()' id='...'>'
kall _ call(1).method(arg_'foo').other('bar')(2.0)
kall.call_list()
m.mock_calls __ kall.call_list()
# OUTPUT: 'True'
#
# A call object is either a tuple of (positional args, keyword args) or (name, positional args, keyword args) depending on how it was constructed.
# When you construct them yourself this isn�t particularly interesting, but the call objects that are in the Mock.call_args, Mock.call_args_list and
# Mock.mock_calls attributes can be introspected to get at the individual arguments they contain.
#
# The call objects in Mock.call_args and Mock.call_args_list are two-tuples of (positional args, keyword args) whereas the call objects in Mock.mock_calls,
# along with ones you construct yourself, are three-tuples of (name, positional args, keyword args).
#
# You can use their �tupleness� to pull out the individual arguments for more complex introspection and assertions.
# The positional arguments are a tuple (an empty tuple if there are no positional arguments) and the keyword arguments are a dictionary:
#
m _ MagicMock(return_value_None)
m(1, 2, 3, arg_'one', arg2_'two')
kall _ m.call_args
args, kwargs _ kall
args
# OUTPUT: '(1, 2, 3)'
kwargs
# OUTPUT: '{'arg2': 'two', 'arg': 'one'}'
args __ kall[0]
# OUTPUT: 'True'
kwargs __ kall[1]
# OUTPUT: 'True'
m _ MagicMock()
m.foo(4, 5, 6, arg_'two', arg2_'three')
# OUTPUT: '<MagicMock name='mock.foo()' id='...'>'
kall _ m.mock_calls[0]
name, args, kwargs _ kall
name
# OUTPUT: 'foo'
args
# OUTPUT: '(4, 5, 6)'
kwargs
# OUTPUT: '{'arg2': 'three', 'arg': 'two'}'
name __ m.mock_calls[0][0]
# OUTPUT: 'True'
#
# create_autospec:
# unittest.mock.create_autospec(spec, spec_set=False, instance=False, **kwargs)
# Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the spec object as their spec.
#
#
# Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature.
# If spec_set is True then attempting to set attributes that don�t exist on the spec object will raise an AttributeError.
#
# If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec.
# You can use a class as the spec for an instance object by passing instance=True.
# The returned mock will only be callable if instances of the mock are callable.
# create_autospec() also takes arbitrary keyword arguments that are passed to the constructor of the created mock.
#
#
# ANY
# unittest.mock.ANY
# Sometimes you may need to make assertions about some of the arguments in a call to mock, but either not care about some of the arguments or want to pull
# them individually out of call_args and make more complex assertions on them.
#
# To ignore certain arguments you can pass in objects that compare equal to everything. Calls to assert_called_with() and assert_called_once_with() will
# then succeed no matter what was passed in.
#
mock _ Mock(return_value_None)
mock('foo', bar_object())
mock.a_c_o_w..('foo', bar_ANY)
#
# ANY can also be used in comparisons with call lists like mock_calls:
#
m _ MagicMock(return_value_None)
m(1)
m(1, 2)
m o..())
m.mock_calls __ [call(1), call(1, 2), ANY]
# OUTPUT: 'True'
|
1f7c2a005ecc688598dfc11cf3b382430a32452d | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/advanced/196/js.py | 561 | 3.640625 | 4 | class JsObject(dict):
"""A Python dictionary that provides attribute-style access
just like a JS object:
obj = JsObject()
obj.cool = True
obj.foo = 'bar'
Try this on a regular dict and you get
AttributeError: 'dict' object has no attribute 'foo'
"""
def __init__(self,**kwargs):
super().__init__(kwargs)
def __getattr__(self,key):
return self[key]
def __setattr__(self,name,value):
self[name] = value
def __delattr__(self,name):
del self[name]
|
ad5aba4dbdde1d5f8411a9e973c6e3be08354238 | syurskyi/Python_Topics | /070_oop/_examples/Python-from-Zero-to-Hero/08/06-Additional Dunder Methods.py | 937 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
lst = [1, 2, 3]
# In[ ]:
repr(lst)
# In[ ]:
print(lst)
# In[ ]:
eval(repr(lst)) == lst
# In[ ]:
from datetime import datetime
dt = datetime.now()
# In[ ]:
repr(dt)
# In[ ]:
print(dt)
# In[ ]:
class Character():
def __init__(self, race, damage = 100):
self.race = race
self.damage = damage
def __repr__(self):
return f"Character('{self.race}', {self.damage})"
def __str__(self):
return f"{self.race} with damage = {self.damage}"
def __eq__(self, other):
if isinstance(other, Character):
return self.race == other.race and self.damage == other.damage
return False
# def __ne__(self, other):
# pass
# In[ ]:
c = Character("Elf")
print(c)
# In[ ]:
d = eval(repr(c))
type(d)
# In[ ]:
print(d)
# In[ ]:
c == d
# In[ ]:
# c!=d
|
de990ba8869438b5cf1479fddc2be99591708692 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Practice_Python_by_Solving_100_Python_Problems/50.py | 256 | 3.640625 | 4 | # #A: str and i.. do not support a minus operand. It doesn't make sense to substract a text from a number or the other way around.
# # change age-1 to i..(age)-1
# age = i.. ? What's your age?
# age_last_year = ? - 1
# print("Last year you were __." _ ?
|
ce65f63521103a3b65819c8bdf7daaaf479a51ef | syurskyi/Python_Topics | /012_lists/_exercises/ITVDN Python Starter 2016/03-slicing.py | 822 | 4.4375 | 4 | # -*- coding: utf-8 -*-
# Можно получить группу элементов по их индексам.
# Эта операция называется срезом списка (list slicing).
# Создание списка чисел
my_list = [5, 7, 9, 1, 1, 2]
# Получение среза списка от нулевого (первого) элемента (включая его)
# до третьего (четвёртого) (не включая)
sub_list = my_list[0:3]
# Вывод полученного списка
print(sub_list)
# Вывод элементов списка от второго до предпоследнего
print(my_list[2:-2])
# Вывод элементов списка от четвёртого (пятого) до пятого (шестого)
print(my_list[4:5]) |
9be84fae16d54e85eb80347ea8f192154d068db5 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/299_v4/base_converter.py | 735 | 4.09375 | 4 | # ___ digit_map num
# """maps numbers greater than a single digit to letters (UPPER)"""
# r.. c.. ?+ 55 __ ? > 9 ____ s.. ?
#
# ___ convert number i.. base i.. 2 __ s..
# """Converts an integer into any base between 2 and 36 inclusive
#
# Args:
# number (int): Integer to convert
# base (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
# """
#
# __ ? < 2 o. ? > 36
# r.. V...
#
# d.. # list
# w.... ? > 0
# d...a.. ? % ?
# ? //= ?
#
# d.. l.. m.. d.. d..
#
# r.. ''.j.. r.. d..
|
7104d7c1fad82e692e0ea015c9ba8cf58c45576a | syurskyi/Python_Topics | /070_oop/001_classes/examples/ITVDN_Python_Advanced/006_Типизированный Python/example5.py | 727 | 3.5625 | 4 | from typing import Dict, Tuple, List
def generate_tuple(data) -> list:
result = []
for key, value in data.values():
result.append((key, value))
return result
test_data1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
test_data2 = {'k1': 'v1', 'k2': 'v2', 'k3': 10}
test_data3 = {'k1': 'v1', 'k2': 'v2', 'k3': 10.4}
test_data4 = {'k1': 'v1', 'k2': 'v2', 'k3': []}
test_value1 = generate_tuple(test_data1) # type: Tuple[str, str]
test_value2 = generate_tuple(test_data2) # type: Dict[str, int]
test_value3 = generate_tuple(test_data3) # type: List
test_value4 = generate_tuple(test_data4) # type: dict
another_value = '10' # type: str
# test_value1.???
# test_value2.???
# test_value3.???
# test_value4.???
|
171d8a178003fc0c6367908f3ecc1cdfc9b62152 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/289_GameOfLife.py | 1,461 | 3.765625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
class Solution(object):
def gameOfLife(self, board):
if not board:
return
m_rows = len(board)
n_cols = len(board[0])
count = [[0 for j in range(n_cols)] for i in range(m_rows)]
for i in range(m_rows):
for j in range(n_cols):
# Compute the number of live neighbors and
# Update the count of adjancent next cells meanwhile.
if j+1 < n_cols:
count[i][j] += board[i][j+1]
count[i][j+1] += board[i][j]
if i+1 < m_rows:
count[i][j] += board[i+1][j]
count[i+1][j] += board[i][j]
if j-1 >= 0:
count[i][j] += board[i+1][j-1]
count[i+1][j-1] += board[i][j]
if j+1 < n_cols:
count[i][j] += board[i+1][j+1]
count[i+1][j+1] += board[i][j]
# Current cell interacts with its eight neighbors
# Live cell turn dead
if board[i][j] and (count[i][j] < 2 or count[i][j] > 3):
board[i][j] = 0
# Dead cell turn live
if not board[i][j] and count[i][j] == 3:
board[i][j] = 1
return
"""
[[]]
[[0]]
[[1,1],[0,1]]
[[0,1,0],[1,1,1],[0,1,0]]
"""
|
9584dadc060d867434c2d901d3b37841a1f1995e | syurskyi/Python_Topics | /065_serialization_and_deserialization/002_json/examples/49. Custom JSON Encoding - Coding.py | 19,581 | 4.1875 | 4 | # Custom JSON Serialization
# As we saw in the previous video, certain data types cannot be serialized to JSON using Python's defaults.
# Here's a simple example of this:
from datetime import datetime
current = datetime.utcnow()
print(current)
# datetime.datetime(2018, 12, 29, 22, 26, 35, 671836)
print('#' * 52 + ' As we can see, this is a `datetime` object.')
import json
# json.dumps(current) # TypeError: Object of type 'datetime' is not JSON serializable
# TypeError: Object of type 'datetime' is not JSON serializable
# As we can see Python raises a TypeError exception, stating that datetime objects are not JSON serializable.
# So, we'll need to come up with our own serialization format.
# For datetimes, the most common format is the ISO 8601 format - you can read up more about it here
# (https://en.wikipedia.org/wiki/ISO_8601), but basically the format is:
# YYYY-MM-DD T HH:MM:SS
# There are some variations for encoding timezones, but to keep things simple I am going to use timezone naive
# timestamps, and just use UTC everywhere.
# We could use Python's string representation for datetimes:
print()
print('#' * 52 + ' We could use Pythons string representation for datetimes:')
print(str(current))
# '2018-12-29 22:26:35.671836'
# ######################################################################################################################
print('#' * 52 + ' but this is not quite ISO-8601. We could write a custom formatter ourselves:')
def format_iso(dt):
return dt.strftime('%Y-%m-%dT%H:%M:%S')
# (If you want more info and options on date and time formatting/parsing using strftime and strptime,
# which essentially pass through to their C counterparts, you can see the Python docs here:
# https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
print(format_iso(current))
# '2018-12-29T22:26:35'
# ######################################################################################################################
print('#' * 52 + ' But Python actually provides us a function to do the same:')
print(current.isoformat())
# 2018-12-29T22:26:35.671836'
# ######################################################################################################################
# This is almost identical to our custom representation, but also includes fractional seconds.
# If you don't want fractional seconds in your representation, then you'll have to write some custom code like the one
# above. I'm just going to use Python's ISO-8601 representation. And now let's serialize our datetime object to JSON:
print('#' * 52 + ' This is'
' almost identical to our custom representation, but also includes fractional seconds.')
print('#' * 52 + ' If you dont want fractional seconds in your representation, '
' then you will have to write some custom code like the one above.')
print()
log_record = {'time': datetime.utcnow().isoformat(), 'message': 'testing'}
print(json.dumps(log_record))
# '{"time": "2018-12-29T22:26:42.083020", "message": "testing"}'
# ######################################################################################################################
print('#' * 52 + ' OK, this works, but this is far from ideal.')
print('#' * 52 + ' Normally, our dictionary will contain the `datetime` object, not its string representation.')
log_record = {'time': datetime.utcnow(), 'message': 'testing'}
# The problem is that log_record is now not JSON serializable!
# What we have to do is write custom code to replace non-JSON serializable objects in our dictionary with custom
# representations. This can quickly become tedious and unmanageable if we deal with many dictionaries,
# and arbitrary structures.
# Fortunately, Python's dump and dumps functions have some ways for us to define general serializations for
# non-standard JSON objects.
# The simplest way is to specify a function that dump/dumps will call when it encounters something it cannot serialize
def format_iso(dt):
return dt.isoformat()
print(json.dumps(log_record, default=format_iso))
# '{"time": "2018-12-29T22:26:42.532485", "message": "testing"}'
# ######################################################################################################################
print('#' * 52 + ' This will work even if we have more than one date in our dictionary:')
log_record = {
'time1': datetime.utcnow(),
'time2': datetime.utcnow(),
'message': 'Testing...'
}
print(json.dumps(log_record, default=format_iso))
# '{"time1": "2018-12-29T22:26:43.296170", "time2": "2018-12-29T22:26:43.296171", "message": "Testing..."}'
# ######################################################################################################################
print('#' * 52 + ' So this works, but what happens if we introduce another non-serializable object:')
log_record = {
'time': datetime.utcnow(),
'message': 'Testing...',
'other': {'a', 'b', 'c'}
}
# json.dumps(log_record, default=format_iso) # AttributeError: 'set' object has no attribute 'isoformat'
# AttributeError: 'set' object has no attribute 'isoformat'
# As you can see, Python encountered that set, and therefore called the default callable - but that callable was not
# designed to handle sets, and so we end up with an exception in the format_iso callable instead
# We can remedy this by essentially adding code to our function to make it handle various data types.
# Essentially creating a dispatcher - this should remind you of the single-dispatch generic function decorator
# available in the functools module which we discussed in an earlier part of this series. You can also view more
# info about it here: https://docs.python.org/3/library/functools.html#functools.singledispatch
# Let's first write it without the decorator to make sure we have our code correct:
print('#' * 52 + ' Lets first write it without the decorator to make sure we have our code correct:')
def custom_json_formatter(arg):
if isinstance(arg, datetime):
return arg.isoformat()
elif isinstance(arg, set):
return list(arg)
print(json.dumps(log_record, default=custom_json_formatter))
# '{"time": "2018-12-29T22:26:43.760863", "message": "Testing...", "other": ["c", "a", "b"]}'
# ######################################################################################################################
print('#' * 52 + ' To make things a little more interesting, lets throw in a custom object as well:')
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.create_dt = datetime.utcnow()
def __repr__(self):
return f'Person(name={self.name}, age={self.age})'
def toJSON(self):
return {
'name': self.name,
'age': self.age,
'create_dt': self.create_dt.isoformat()
}
p = Person('John', 82)
print(p)
print(p.toJSON())
# Person(name=John, age=82)
# {'name': 'John', 'age': 82, 'create_dt': '2018-12-29T22:26:45.066252'}
# ######################################################################################################################
print('#' * 52 + ' And we modify our custom JSON formatter as follows:')
def custom_json_formatter(arg):
if isinstance(arg, datetime):
return arg.isoformat()
elif isinstance(arg, set):
return list(arg)
elif isinstance(arg, Person):
return arg.toJSON()
log_record = dict(time=datetime.utcnow(),
message='Created new person record',
person=p)
print(json.dumps(log_record, default=custom_json_formatter))
# '{"time": "2018-12-29T22:26:45.769929", "message": "Created new person record", "person": {"name": "John", "age": 82, "create_dt": "2018-12-29T22:26:45.066252"}}'
# ######################################################################################################################
print(json.dumps(log_record, default=custom_json_formatter, indent=2))
# {
# "time": "2018-12-29T22:26:45.769929",
# "message": "Created new person record",
# "person": {
# "name": "John",
# "age": 82,
# "create_dt": "2018-12-29T22:26:45.066252"
# }
# }
# ######################################################################################################################
print('#' * 52 + ' One thing to note here is that for the `Person` class'
' we returned a formatted string for the `created_dt` attribute.')
print('#' * 52 + ' We dont actually need to do this - we can simply return a `datetime` object and'
' let `custom_json_formatter` handle serializing the `datetime` object:')
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.create_dt = datetime.utcnow()
def __repr__(self):
return f'Person(name={self.name}, age={self.age})'
def toJSON(self):
return {
'name': self.name,
'age': self.age,
'create_dt': self.create_dt
}
p = Person('Monty', 100)
log_record = dict(time=datetime.utcnow(),
message='Created new person record',
person=p)
print(json.dumps(log_record, default=custom_json_formatter, indent=2))
# {
# "time": "2018-12-29T22:26:47.029102",
# "message": "Created new person record",
# "person": {
# "name": "Monty",
# "age": 100,
# "create_dt": "2018-12-29T22:26:46.749022"
# }
# }
# ######################################################################################################################
print('#' * 52 + ' In fact, we could simplify our class further by simply returning a dict of the attributes, '
' since in this case we want to serialize everything as is.')
print('#' * 52 + ' But using the `toJSON` callable means we can customize exactly '
' how we want out objects to be serialized.')
print('#' * 52 + ' So, if we were +not particular about the serialization we could do this:')
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.create_dt = datetime.utcnow()
def __repr__(self):
return f'Person(name={self.name}, age={self.age})'
def toJSON(self):
return vars(self)
p = Person('Python', 27)
print(p.toJSON())
# {'name': 'Python',
# 'age': 27,
# 'create_dt': datetime.datetime(2018, 12, 29, 22, 26, 47, 973930)}
# ######################################################################################################################
print()
print()
print()
print('#' * 52 + ' ')
log_record['person'] = p
print(log_record)
# {'time': datetime.datetime(2018, 12, 29, 22, 26, 47, 29102), 'message': 'Created new person record', 'person': Person(name=Python, age=27)}
# ######################################################################################################################
print(json.dumps(log_record, default=custom_json_formatter, indent=2))
# {
# "time": "2018-12-29T22:26:47.029102",
# "message": "Created new person record",
# "person": {
# "name": "Python",
# "age": 27,
# "create_dt": "2018-12-29T22:26:47.973930"
# }
# }
# ######################################################################################################################
print('#' * 52 + ' In fact, we could use this approach in our custom formatter - '
' if an object does not have a `toJSON` callable,')
print('#' * 52 + ' we will just use a dictionary of the attributes - it it has any, '
' it might not (like a complex number or a set as examples), '
' so we need to watch out for that as well.')
print('toJSON' in vars(Person))
# True
# ######################################################################################################################
def custom_json_formatter(arg):
if isinstance(arg, datetime):
return arg.isoformat()
elif isinstance(arg, set):
return list(arg)
else:
try:
return arg.toJSON()
except AttributeError:
try:
return vars(arg)
except TypeError:
return str(arg)
print('#' * 52 + ' Lets create another custom class that does not have a `toJSON` method:')
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Point(x={self.x}, y={self.y})'
pt1 = Point(10, 10)
print(vars(pt1))
# {'x': 10, 'y': 10}
# ######################################################################################################################
log_record = dict(time=datetime.utcnow(),
message='Created new point',
point=pt1,
created_by=p)
print(log_record)
# {'time': datetime.datetime(2018, 12, 29, 22, 26, 50, 955039),
# 'message': 'Created new point',
# 'point': Point(x=10, y=10),
# 'created_by': Person(name=Python, age=27)}
# ######################################################################################################################
print('#' * 52 + ' And we can now serialize it to JSON:')
print(json.dumps(log_record, default=custom_json_formatter, indent=2))
# {
# "time": "2018-12-29T22:26:50.955039",
# "message": "Created new point",
# "point": {
# "x": 10,
# "y": 10
# },
# "created_by": {
# "name": "Python",
# "age": 27,
# "create_dt": "2018-12-29T22:26:47.973930"
# }
# }
# ######################################################################################################################
print('#' * 52 + ' So now, lets re-write our custom json formatter using the generic single dispatch decorator'
' I mentioned earlier:')
from functools import singledispatch
# Our default approach is going to first try to use toJSON, if not it will try to use vars, and it that still fails
# we'll use the string representation, whatever that happens to be:
@singledispatch
def json_format(arg):
print(arg)
try:
print('\ttrying to use toJSON...')
return arg.toJSON()
except AttributeError:
print('\tfailed - trying to use vars...')
try:
return vars(arg)
except TypeError:
print('\tfailed - using string representation...')
return str(arg)
# And now we 'register' other data types:
@json_format.register(datetime)
def _(arg):
return arg.isoformat()
@json_format.register(set)
def _(arg):
return list(arg)
print(json.dumps(log_record, default=json_format, indent=2))
# Point(x=10, y=10)
# trying to use toJSON...
# failed - trying to use vars...
# Person(name=Python, age=27)
# trying to use toJSON...
# {
# "time": "2018-12-29T22:26:50.955039",
# "message": "Created new point",
# "point": {
# "x": 10,
# "y": 10
# },
# "created_by": {
# "name": "Python",
# "age": 27,
# "create_dt": "2018-12-29T22:26:47.973930"
# }
# }
# ######################################################################################################################
print('#' * 52 + ' Lets change our Person class to emit some custom JSON instead of just using `vars`:')
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.create_dt = datetime.utcnow()
def __repr__(self):
return f'Person(name={self.name}, age={self.age})'
def toJSON(self):
return dict(name=self.name)
p = Person('Python', 27)
log_record['created_by'] = p
print(json.dumps(log_record, default=json_format, indent=2))
# Point(x=10, y=10)
# trying to use toJSON...
# failed - trying to use vars...
# Person(name=Python, age=27)
# trying to use toJSON...
# {
# "time": "2018-12-29T22:26:50.955039",
# "message": "Created new point",
# "point": {
# "x": 10,
# "y": 10
# },
# "created_by": {
# "name": "Python"
# }
# }
# ######################################################################################################################
print('#' * 52 + ' The way we wrote our default formatter,'
' means that we can now also represent other unexpected data types, '
' but using each objects string representation.')
print('#' * 52 + ' If that is not acceptable, we can either not do this and let a `TypeError` exception get generated,'
' or register more custom formatters:')
from decimal import Decimal
from fractions import Fraction
print(json.dumps(dict(a=1 + 1j,
b=Decimal('0.5'),
c=Fraction(1, 3),
p=Person('Python', 27),
pt=Point(0, 0),
time=datetime.utcnow()
),
default=json_format))
# (1+1j)
# trying to use toJSON...
# failed - trying to use vars...
# failed - using string representation...
# 0.5
# trying to use toJSON...
# failed - trying to use vars...
# failed - using string representation...
# 1/3
# trying to use toJSON...
# failed - trying to use vars...
# failed - using string representation...
# Person(name=Python, age=27)
# trying to use toJSON...
# Point(x=0, y=0)
# trying to use toJSON...
# failed - trying to use vars...
# '{"a": "(1+1j)", "b": "0.5", "c": "1/3", "p": {"name": "Python"}, "pt": {"x": 0, "y": 0}, "time": "2018-12-29T22:26:54.860340"}'
# ######################################################################################################################
print('#' * 52 + ' Now, suppose we dont want that default representation for `Decimals` -'
' we want to serialize it in this form: `Decimal(0.5)`.')
print('#' * 52 + ' All we need to do is to register a new function to serialize `Decimal` types:')
@json_format.register(Decimal)
def _(arg):
return f'Decimal({str(arg)})'
print(json.dumps(dict(a=1 + 1j,
b=Decimal(0.5),
c=Fraction(1, 3),
p=Person('Python', 27),
pt=Point(0, 0),
time=datetime.utcnow()
),
default=json_format))
# (1+1j)
# trying to use toJSON...
# failed - trying to use vars...
# failed - using string representation...
# 1/3
# trying to use toJSON...
# failed - trying to use vars...
# failed - using string representation...
# Person(name=Python, age=27)
# trying to use toJSON...
# Point(x=0, y=0)
# trying to use toJSON...
# failed - trying to use vars...
# '{"a": "(1+1j)", "b": "Decimal(0.5)", "c": "1/3", "p": {"name": "Python"}, "pt": {"x": 0, "y": 0}, "time": "2018-12-29T22:26:55.491606"}'
# ######################################################################################################################
print(
'#' * 52 + ' One last example that clearly shows the `json_format` function gets called recursively when needed:')
print(json.dumps(dict(pt = Point(Person('Python', 27), 2+2j)),
default=json_format, indent=2))
# Point(x=Person(name=Python, age=27), y=(2+2j))
# trying to use toJSON...
# failed - trying to use vars...
# Person(name=Python, age=27)
# trying to use toJSON...
# (2+2j)
# trying to use toJSON...
# failed - trying to use vars...
# failed - using string representation...
# {
# "pt": {
# "x": {
# "name": "Python"
# },
# "y": "(2+2j)"
# }
# }
# ######################################################################################################################
|
e67b4827167a7ec9f6e26214dd62b0cda65bd647 | syurskyi/Python_Topics | /100_databases/003_mongodb/examples/w3schools_Python MongoDB/006_Find One.py | 332 | 3.765625 | 4 | # Find One
#
# To select data from a collection in MongoDB, we can use the find_one() method.
#
# The find_one() method returns the first occurrence in the selection.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x) |
a3019df68c1e9b08178180fe9f44dd54cb3cd213 | syurskyi/Python_Topics | /125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 14 Array/array_two_sum_solution.py | 635 | 3.984375 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
"""
Given an array of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 26,
Because nums[0] + nums[1] = 11 + 15 = 26,
return [2, 3].
"""
# Solution 1
# Try all
input_array = [2, 7, 11, 15]
target = 26
result = []
for i, num in enumerate(input_array):
for j in range(i+1, len(input_array)):
print(i,j)
# %%
# Solution 2
|
ade7d89656382c39b72c08bf1c6c2b6e9311c097 | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/Python_Hand-on_Solve_200_Problems/Section 4 Condition and Loop/check_triange_solution.py | 794 | 4.03125 | 4 | # # To add a new cell, type '# %%'
# # To add a new markdown cell, type '# %% [markdown]'
# # %%
# # ---------------------------------------------------------------
# # python best courses https://courses.tanpham.org/
# # ---------------------------------------------------------------
# # Write a Python program to check a triangle is valid or not
#
# ___ triangle_check l1 l2 l3
# __ (l1>l2+l3) o. (l2>l1+l3) o. (l3>l1+l2
# print('No, the lengths wont form a triangle')
# ____ (l1__l2+l3) o. (l2__l1+l3) o. (l3__l1+l2):
# print('yes, it can form a degenerated triangle')
# ____
# print('Yes, a triangle can be formed out of it')
#
# length1 _ in. i.. 'enter side 1\n'
# length2 _ in. i.. 'enter side 2\n'
# length3 _ in. i.. 'enter side 3\n'
#
# ? ? ? ?
#
|
afca8fe2b6189f257f765e893191ba7b41902f18 | syurskyi/Python_Topics | /070_oop/001_classes/examples/Learning Python/026_006_Classes Versus Dictionaries.py | 789 | 3.90625 | 4 | rec = {}
rec['name'] = 'mel' # Dictionary-based record
rec['age'] = 45
rec['job'] = 'trainer/writer'
print(rec['name'])
class rec: pass
rec.name = 'mel' # Class-based record
rec.age = 45
rec.job = 'trainer/writer'
print(rec.age)
class rec: pass
pers1 = rec() # Instance-based records
pers1.name = 'mel'
pers1.job = 'trainer'
pers1.age = 40
pers2 = rec()
pers2.name = 'vls'
pers2.job = 'developer'
print(pers1.name, pers2.name)
class Person:
def __init__(self, name, job): # Class = Data + Logic
self.name = name
self.job = job
def info(self):
return (self.name, self.job)
rec1 = Person('mel', 'trainer')
rec2 = Person('vls', 'developer')
print(rec1.job, rec2.info())
|
c10b1e6b2a1946e418dc762ecf783326ff98c4d3 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/_templates/Python_3_Deep_Dive_Part_4/Section 4 Polymorphism and Special Methods/58. Callables - Coding.py | 12,211 | 4.6875 | 5 | # %%
'''
### Making Objects Callable
'''
# %%
'''
We can make instances of our classes callables by implementing the `__call__` method.
'''
# %%
'''
Let's first see a simple example:
'''
# %%
class Person:
def __call__(self):
print('__call__ called...')
# %%
p = Person()
# %%
'''
And now we can use `p` as a callable too:
'''
# %%
type(p)
# %%
p()
# %%
'''
This is actually quite useful, and is widely used by Python itself.
'''
# %%
'''
For example, the `functools` module has a `partial` function that we can use to create partial functions, like this:
'''
# %%
from functools import partial
# %%
def my_func(a, b, c):
return a, b, c
# %%
'''
We can call this function with three arguments, but we could also create a partial function that essentially pre-sets
some of the positional arguments:
'''
# %%
partial_func = partial(my_func, 10, 20)
# %%
'''
And now we can (indirectly) call `my_func` using `partial_func` using only an argument for `c`, with `a` and `b`
pre-set to `10` and `20` respectively:
'''
# %%
partial_func(30)
# %%
'''
So I referred to `partial` as a function, but in reality it's just a callable (and this is why in Python we generally
refer to things as callables, not just functions, because an object might be callable without being an actual function).
In fact, we've seen this before with properties - these are callables, but they are not functions!
'''
# %%
'''
Back to `partial`, you'll notice that the `type` of `partial` is not a `function` at all!
'''
# %%
type(partial)
# %%
'''
So the type is `type` which means `partial` is actually a class, not a function.
We can easily re-create a simplified approximation of `partial` ourselves using the `__call__` method in a custom class.
'''
# %%
class Partial:
def __init__(self, func, *args):
self._func = func
self._args = args
def __call__(self, *args):
return self._func(*self._args, *args)
# %%
partial_func = Partial(my_func, 10, 20)
# %%
type(partial_func)
# %%
partial_func(30)
# %%
'''
Many such "functions" in Python are actually just general callables. The distinction is often not important.
'''
# %%
'''
There is a built-in function in Python, `callable` that can be used to determine if an object is callable:
'''
# %%
callable(print)
# %%
callable(partial)
# %%
callable(partial_func)
# %%
'''
As you can see our `Partial` class **instance** is callable, but the `Person` class instances will not be (the class
itself is callable of course):
'''
# %%
class Person:
def __init__(self, name):
self.name = name
# %%
callable(Person)
# %%
p = Person('Alex')
# %%
callable(p)
# %%
'''
#### Example: Cache with a cache-miss counter
'''
# %%
'''
Let's take a look at another example. I want to implement a dictionary to act as a cache, but I also want to keep track
of the cache misses so I can later evaluate if my caching strategy is effective or not.
'''
# %%
'''
The `defaultdict` class can be useful as a cache.
Recall that I can specify a default callable to use when requesting a non-existent key from a `defaultdict`:
'''
# %%
from collections import defaultdict
# %%
def default_value():
return 'N/A'
# %%
d = defaultdict(default_value)
# %%
d['a']
# %%
d.items()
# %%
'''
Now, I want to use this `default_value` callable to keep track of the number of times it has been called - this will
tell me how may times a non-existent key was requested from my `defaultdict`.
'''
# %%
'''
I could try to create a global counter, and use that in my `default_value` function:
'''
# %%
miss_counter = 0
# %%
def default_value():
global miss_counter
miss_counter += 1
return 'N/A'
# %%
'''
And now we can use it this way:
'''
# %%
d = defaultdict(default_value)
# %%
d['a'] = 1
d['a']
d['b']
d['c']
# %%
miss_counter
# %%
'''
This works, but is not very good - the `default_value` function **relies** on us having a global `miss_counter`
variable - if we don't have it our function won't work. Additionally we cannot use it to keep track of different
cache instances since they would all use the same instance of `miss_counter`.
'''
# %%
del miss_counter
# %%
d = defaultdict(default_value)
# %%
try:
d['a']
except NameError as ex:
print(ex)
# %%
'''
So nmaybe we can just pass in the counter (defined in our current scope) we want to use to the `default_value` function:
'''
# %%
def default_value(counter):
counter += 1
return 'N/A'
# %%
'''
But this **won't work**, because counter is now local to the function so the local `counter` will be incremented, not
the `counter` from the outside scope.
'''
# %%
'''
Instead, we could use a class to maintain both a counter state, and return the default value for a cache miss:
'''
# %%
class DefaultValue:
def __init__(self):
self.counter = 0
def __iadd__(self, other):
if isinstance(other, int):
self.counter += other
return self
raise ValueError('Can only increment with an integer value.')
# %%
'''
So we can use this class a a counter:
'''
# %%
default_value_1 = DefaultValue()
# %%
default_value_1 += 1
# %%
default_value_1.counter
# %%
'''
So this works as a counter, but `default_value_1` is not callable, which is what we need to the `defaultdict`.
So let's make it callable, and implement the behavior we need:
'''
# %%
class DefaultValue:
def __init__(self):
self.counter = 0
def __iadd__(self, other):
if isinstance(other, int):
self.counter += other
return self
raise ValueError('Can only increment with an integer value.')
def __call__(self):
self.counter += 1
return 'N/A'
# %%
'''
And now we can use this as our default callable for our default dicts:
'''
# %%
def_1 = DefaultValue()
def_2 = DefaultValue()
# %%
cache_1 = defaultdict(def_1)
cache_2 = defaultdict(def_2)
# %%
cache_1['a'], cache_1['b']
# %%
def_1.counter
# %%
cache_2['a']
# %%
def_2.counter
# %%
'''
As one last little enhancement, I'm going to make the returned default value an instance attribute for more flexibility:
'''
# %%
class DefaultValue:
def __init__(self, default_value):
self.default_value = default_value
self.counter = 0
def __iadd__(self, other):
if isinstance(other, int):
self.counter += other
return self
raise ValueError('Can only increment with an integer value.')
def __call__(self):
self.counter += 1
return self.default_value
# %%
'''
And now we could use it this way:
'''
# %%
cache_def_1 = DefaultValue(None)
cache_def_2 = DefaultValue(0)
cache_1 = defaultdict(cache_def_1)
cache_2 = defaultdict(cache_def_2)
# %%
cache_1['a'], cache_1['b'], cache_1['a']
# %%
cache_def_1.counter
# %%
cache_2['a'], cache_2['b'], cache_2['c']
# %%
cache_def_2.counter
# %%
'''
So the `__call__` method can essentially be used to make **instances** of our classes callable.
This is also very useful to create **decorator** classes.
Oftn we just use closures to create decorators, but sometimes it is easier to use a class instead, or if we want our
class to provide functionality beyond just being used as a decorator.
'''
# %%
'''
Let's look at an example.
'''
# %%
'''
#### Example: Profiling Functions
'''
# %%
'''
For simplicity I will assume here that we only want to decorate functions defined at the module level. For creating a
decorator that also works for methods (bound functions) we have to do a bit more work and will need to understand
descriptors - more on descriptors later.
'''
# %%
'''
So we want to easily be able to keep track of how many times our functions are called and how long they take to run on
average.
'''
# %%
'''
Although we could cretainly implement code directly inside our function to do this, it becomes repetitive if we need
to do it for multiple functions - so a decorator is ideal for that.
Let's look at how we can use a decorator class to keep track of how many times our function is called and also keep
track of the time it takes to run on average.
'''
# %%
'''
We could certainly try a closure-based approach, maybe something like this:
'''
# %%
from time import perf_counter
from functools import wraps
def profiler(fn):
counter = 0
total_elapsed = 0
avg_time = 0
@wraps(fn)
def inner(*args, **kwargs):
nonlocal counter
nonlocal total_elapsed
nonlocal avg_time
counter += 1
start = perf_counter()
result = fn(*args, **kwargs)
end = perf_counter()
total_elapsed += (end - start)
avg_time = total_elapsed / counter
return result
# we need to give a way to our users to look at the
# counter and avg_time values - spoiler: this won't work!
inner.counter = counter
inner.avg_time = avg_time
return inner
# %%
'''
So, we added `counter` and `avg_time` as attributes to the `inner` function (the decorated function) - that works but
looks a little weird - also notice that we calculate `avg_time` every time we call our decorated fuinction, even
though the user may never request it - seems wasteful.
'''
# %%
from time import sleep
import random
random.seed(0)
@profiler
def func1():
sleep(random.random())
# %%
func1(), func1()
# %%
func1.counter
# %%
'''
Hmm, that's weird - `counter` still shows zero. This is because we have to understand what we did in the decorator -
we made `inner.counter` the value of `counter` **at the time the decorator function was called** - this is **not**
the counter value that we keep updating!!
'''
# %%
'''
So instead we could try to fix it this way:
'''
# %%
from time import perf_counter
from functools import wraps
def profiler(fn):
_counter = 0
_total_elapsed = 0
_avg_time = 0
@wraps(fn)
def inner(*args, **kwargs):
nonlocal _counter
nonlocal _total_elapsed
nonlocal _avg_time
_counter += 1
start = perf_counter()
result = fn(*args, **kwargs)
end = perf_counter()
_total_elapsed += (end - start)
return result
# we need to give a way to our users to look at the
# counter and avg_time values - but we need to make sure
# it is using a cell reference!
def counter():
# this will now be a closure with a cell pointing to
# _counter
return _counter
def avg_time():
return _total_elapsed / _counter
inner.counter = counter
inner.avg_time = avg_time
return inner
# %%
@profiler
def func1():
sleep(random.random())
# %%
func1(), func1()
# %%
func1.counter()
# %%
func1.avg_time()
# %%
'''
OK, so that works, but it's a little convoluted. In this case a decorator class will be much easier to write and read!
'''
# %%
class Profiler:
def __init__(self, fn):
self.counter = 0
self.total_elapsed = 0
self.fn = fn
def __call__(self, *args, **kwargs):
self.counter += 1
start = perf_counter()
result = self.fn(*args, **kwargs)
end = perf_counter()
self.total_elapsed += (end - start)
return result
@property
def avg_time(self):
return self.total_elapsed / self.counter
# %%
'''
So we can now use `Profiler` as a decorator!
'''
# %%
@Profiler
def func_1(a, b):
sleep(random.random())
return (a, b)
# %%
func_1(1, 2)
# %%
func_1.counter
# %%
func_1(2, 3)
# %%
func_1.counter
# %%
func_1.avg_time
# %%
'''
And of course we can use it for other functions too:
'''
# %%
@Profiler
def func_2():
sleep(random.random())
# %%
func_2(), func_2(), func_2()
# %%
func_2.counter, func_2.avg_time
# %%
'''
As you can see, it was much easier to implement this more complex decorator using a class and the `__call__` method
than using a purely function approach. But of course, if the decorator is simple enough to implement using a functional
approach, that's my preferred way of doing things!
Just because I have a hammer does not mean everything is a nail!!
'''
# %%
|
0c7741c528c1a2723425cc410a7158bee2f3989c | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/83/timezone.py | 720 | 3.71875 | 4 | from pytz import timezone, utc
from datetime import datetime
AUSTRALIA = timezone('Australia/Sydney')
SPAIN = timezone('Europe/Madrid')
def what_time_lives_pybites(naive_utc_dt):
"""Receives a naive UTC datetime object and returns a two element
tuple of Australian and Spanish (timezone aware) datetimes"""
#print(naive_utc_dt)
#print(utc.localize(naive_utc_dt))
#print(utc.localize(naive_utc_dt).astimezone(SPAIN))
#print(utc.localize(naive_utc_dt).astimezone(AUSTRALIA))
return (utc.localize(naive_utc_dt).astimezone(AUSTRALIA),
utc.localize(naive_utc_dt).astimezone(SPAIN))
naive_utc_dt = datetime(2018, 4, 27, 22, 55, 0)
print(what_time_lives_pybites(naive_utc_dt)) |
6001a7741fa8ca503a6a9cc3338b0d350473fc9b | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/152 Maximum Product Subarray.py | 4,720 | 3.6875 | 4 | """
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6
"""
__author__ 'Danyang'
c_ Solution(o..
___ maxProduct_oneline nums
r.. m..(r.. l.... A, n: [m..(A), m..(n, A[1]*n, A[2]*n), m..(n, A[1]*n, A[2]*n)], nums[1:], [nums[0]]*3
___ maxProduct nums
"""
DP
State definitions:
let small[i] be the smallest product result ending with i
let large[i] be the largest product result ending with i
Transition functions:
small[i] = min(A[i], small[i-1]*A[i], large[i-1]*A[i]
large[i] = max(A[i], small[i-1]*A[i], large[i-1]*A[i]
DP space can be optimized
:type nums: List[int]
:rtype: int
"""
small nums[0]
large nums[0]
maxa nums[0]
___ a __ nums 1|
small, large m..(a, small*a, large*a), m..(a, small*a, large*a)
maxa m..(maxa, small, large)
r.. maxa
___ maxProduct_error2 nums
"""
:type nums: List[int]
:rtype: int
"""
__ l..(nums) < 2:
r.. m..(nums)
n l..(nums)
F_pos [0 ___ _ __ x..(n+1)]
F_neg [0 ___ _ __ x..(n+1)]
maxa 1
___ i __ x..(1, n+1
v nums[i-1]
__ v > 0
F_pos[i] F_pos[i-1]*v __ F_pos[i-1] !_ 0 ____ v
F_neg[i] F_neg[i-1]*v
____ v __ 0:
F_pos[i], F_neg[i] 0, 0
____
F_neg[i] m..(0, F_pos[i-1]*v)
F_pos[i] m..(0, F_neg[i-1]*v)
maxa m..(maxa, F_pos[i])
r.. maxa
___ maxProduct_error A
"""
dp, collect number of negative number
notice 0
:param A: a list of int
:return: int
"""
__ n.. A:
r..
length l..(A)
__ length__1:
r.. A[0]
dp [-1 ___ _ __ x..(length+1)]
dp[length] 0 # dummy
___ i __ x..(length-1, -1, -1
__ A[i]<0:
dp[i] dp[i+1]+1
____ A[i]__0:
dp[i] 0
____
dp[i] dp[i+1]
global_max -1<<32
# cur = 1 # starting from 0, encountering problem [-2, 0, -1]
# for ind, val in enumerate(A):
# cur *= val
# if cur<0 and dp[ind+1]<1 or cur==0:
# cur = 1
# global_max = max(global_max, cur)
cur 0 # starting from 0
___ ind, val __ e..(A
__ cur!_0:
cur *= val
____
cur val
__ cur<0 a.. dp[ind+1]<1:
cur 0
global_max m..(global_max, cur)
r.. global_max
___ maxProduct_dp A
"""
dp, collect number of negative number (notice 0).
negative number and 0 will be special in this question
two pointers, sliding window
:param A: a list of int
:return: int
"""
__ n.. A:
r..
length l..(A)
__ length__1:
r.. A[0]
dp [-1 ___ _ __ x..(length+1)]
dp[length] 0 # dummy
___ i __ x..(length-1, -1, -1
__ A[i]<0:
dp[i] dp[i+1]+1
____ A[i]__0:
dp[i] 0
____
dp[i] dp[i+1]
global_max -1<<32
cur 0 # starting from 0
start_ptr 0
end_ptr 0
w.... end_ptr<length: # [start, end), expanding
__ cur!_0:
cur *= A[end_ptr]
____
cur A[end_ptr]
start_ptr end_ptr
end_ptr += 1
__ cur<0 a.. dp[end_ptr]<1:
# from the starting point, get the first negative
w.... start_ptr<_end_ptr a.. A[start_ptr]>0:
cur /= A[start_ptr]
start_ptr += 1
__ A[start_ptr]<0:
cur /= A[start_ptr]
start_ptr += 1
__ start_ptr__end_ptr: # consider A=[-2, 0, -1] when processing [-1]
cur 0 # otherwise 1
global_max m..(global_max, cur)
r.. global_max
__ _____ __ ____
print Solution().maxProduct([2,3,-2,4])
... Solution().maxProduct([2,-5,-2,-4,3])__24
... Solution().maxProduct([-2, 0, -1])__0
... Solution().maxProduct( -2__-2
... Solution().maxProduct([2, 3, -2, 4, -2])__96
... Solution().maxProduct([2, 3, -2, 4, 0, -2])__6
... Solution().maxProduct([2,3,-2,4])__6
|
b7e851d5b33ddd5933ece43eb486bf591e622816 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/template.py | 3,596 | 3.765625 | 4 | ___ checkdupsorting(myarray
myarray.s..()
print(myarray)
___ i __ r..(0, l..(myarray) - 1
#print "in for loop:", myarray
# #print "comparing", myarray[i],"and",myarray[i + 1]
__(myarray[i] __ myarray[i + 1]
print("Duplicates present:", myarray[i])
r..
print("There are No duplicates present in the given array.")
myarray [3,4,5,6,7,8,7]
checkdupsorting(myarray)
# #####################################################################################################################
___ getfirstnonrepeated(myarray
print("Given array:", myarray)
tab # dict # hash
# #print "tab created:", tab
___ ele __ myarray.l..:
__ ele __ tab:
tab[ele] + 1
____ ele ! " ":
tab[ele] 1
____
tab[ele] 0
# print "in loop:",tab,"for","'",ele,"'","in",myarray
___ ele __ myarray.l..:
__ tab[ele] __ 1:
print("the first non repeated character is: %s" % (ele
r.. ele
r..
getfirstnonrepeated("abccdef")
# #####################################################################################################################
____ nose.tools _______ assert_equal
c_ AnagramTest(o..
___ test sol
assert_equal(sol('go go go', 'gggooo'), T..)
assert_equal(sol('abc', 'cba'), T..)
assert_equal(sol('hi man', 'hi man'), T..)
assert_equal(sol('aabbcc', 'aabbc'), F..)
assert_equal(sol('123', '1 2'), F..)
print("ALL TEST CASES PASSED")
# Run Tests
t AnagramTest()
t.test(anagram)
# %%
t.test(anagram2)
# %%
'''
# Good Job!
'''
# #####################################################################################################################
___ balance_check(s
# Check is even number of brackets
__ l..(s) % 2 ! 0:
r.. F..
# Set of opening brackets
opening s..('([{')
# Matching Pairs
matches s..([('(', ')'), (' ', ' '), ('{', '}')])
# Use a list as a "Stack"
stack # list
# Check every parenthesis in string
___ paren __ s:
# If its an opening, append it to list
__ paren __ opening:
stack.a..(paren)
____
# Check that there are parentheses in Stack
__ l..(stack) __ 0:
r.. F..
# Check the last open parenthesis
last_open stack.p.. )
# Check if it has a closing match
__ (last_open, paren) n.. __ matches:
r.. F..
r.. l..(stack) __ 0
balance_check('[]')
# True
balance_check('[](){([[[]]])}')
# True
balance_check('()(){]}')
# False
# Test Your Solution
"""
RUN THIS CELL TO TEST YOUR SOLUTION
"""
____ nose.tools _______ assert_equal
c_ TestBalanceCheck(o..
___ test sol
assert_equal(sol('[](){([[[]]])}('), F..)
assert_equal(sol('[{{{(())}}}]((()))'), T..)
assert_equal(sol('[[[]])]'), F..)
print 'ALL TEST CASES PASSED'
# Run Tests
t TestBalanceCheck()
t.test(balance_check)
# #####################################################################################################################
# tail recursion
___ tail(n
# base case
__ n __ 0:
r..
# do some operation before the recursive call
print(n)
# recursive call
tail(n - 1)
___ head(n
# base case
__ n __ 0:
r..
# recursive call
head(n - 1)
# do some operation after the recursive call
print(n)
__ _______ __ _______
print("Tail recursion:\n")
tail(5)
print("\nHead recursion:\n")
head(5) |
6b580a86576e8fd66da3913d387948f109435da3 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+26 How to get Factorial using for loop.py | 142 | 3.71875 | 4 | x abs(i..(input("Insert any number: ")))
factorial 1
___ i __ r..(2, x+1):
factorial * i
print("The result of factorial = ",factorial) |
81ce3ec1a4145c7283bdd087437cbc247b8113b5 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BinarySearch/35_SearchInsertPosition.py | 623 | 3.984375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
# Pythonic way.
def searchInsert(self, nums, target):
return len([x for x in nums if x < target])
class Solution_2(object):
def searchInsert(self, nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) / 2
if target == nums[mid]:
return mid
elif target > nums[mid]:
left = mid + 1
else:
right = mid - 1
return left
"""
[1,3,5,6]
5
[1,3,5,6]
2
[1,3,5,6]
7
[1,3,5,6]
0
"""
|
a64c2c4481a7f03ccad171656f3430c81f4496db | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-18-find-the-most-common-word.py | 2,185 | 4.25 | 4 | """
Write a function that returns the most common (non stop)word in this Harry Potter text.
Make sure you convert to lowercase, strip out non-alphanumeric characters and stopwords.
Your function should return a tuple of (most_common_word, frequency).
The template code already loads the Harry Potter text and list of stopwords in.
Check the tests for more info - have fun!
KEYWORDS: Counter, data analysis, list comprehensions
"""
_______ __
_______ u__.r..
_______ s__
____ c.. _______ C..
_______ __
# data provided
tmp __.g.. TMP /tmp
stopwords_file __.p...j.. ? 'stopwords')
harry_text __.p...j.. ? 'harry')
u__.r...u..(
'https://bites-data.s3.us-east-2.amazonaws.com/stopwords.txt',
stopwords_file
)
u__.r...u..(
'https://bites-data.s3.us-east-2.amazonaws.com/harry.txt',
harry_text
)
___ my_solution_get_harry_most_common_word
"""
High level concept:
* prepare a list with stopwords
* go over text word by word, stripping all non-alphanumeric characters
* if a word does not exist in stopwords list, add it to another list (let's call it filtered)
* once we have filtered list ready, feed it to the counter object
* retrieve 1st most common object and return it
"""
stopwords # list
filtered # list
f1 o.. stopwords_file, _
___ line __ f1:
stopwords.a..(line.s..
f2 o.. harry_text, _
___ line __ f2:
___ word __ line.s.. :
print(word)
p word.s..(s__.p...l..
__ l..(p) > 0 a.. p n.. __ stopwords:
filtered.a..(word.s..(s__.p...l..
counter C..(filtered)
r.. counter.most_common(1 0
___ pyb_solution_get_harry_most_common_word
___ get_harry_most_common_word
w__ o.. stopwords_file) __ f:
stopwords s..(f.r...s...l...s..('\n'
w__ o.. harry_text) __ f:
words [__.s.. _ \W+', r'', word) # [^a-zA-Z0-9_]
___ word __ f.r...l...s.. ]
words [word ___ word __ words __ word.s..
a.. word n.. __ stopwords]
cnt C..(words)
r.. cnt.most_common(1 0
print(my_solution_get_harry_most_common_word |
36508bf3a8e3ce4e963ed1bd87cd4cc8a3ea544c | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/HashTable/03_LongestSubstringWithoutRepeatingCharacters.py | 978 | 3.796875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_length = 0
start = 0 # Start index of the substring without repeating characters
end = 0 # End index of the substring without repeating characters
char_dict = {}
for index in range(len(s)):
char = s[index]
# Find out a repeating character. So reset start and end.
if char in char_dict and start <= char_dict[char] <= end:
start = char_dict[char] + 1
end = index
# char is not in the substring already, add it to the substring.
else:
end = index
if end - start + 1 > max_length:
max_length = end - start + 1
char_dict[char] = index
return max_length
"""
""
"bbbbb"
"abcabcbb"
"""
|
371efe88e7ca05680323f02cfe926236502cfe7f | syurskyi/Python_Topics | /045_functions/007_lambda/examples/011_Reduce.py | 776 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import functools
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
functools.reduce(lambda acc, pair: acc + pair[0], pairs, 0)
# 6
# Более идиоматический подход, использующий выражение генератора в качестве аргумента для sum() в следующем примере:
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
sum(x[0] for x in pairs)
# 6
# Немного другое и, возможно, более чистое решение устраняет необходимость явного доступа к первому элементу пары и
# вместо этого использует распаковку:
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
sum(x for x, _ in pairs)
# 6 |
00749bb2dd415c70b26415b5422978884a33734b | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 7 - Binary Tree Preorder Traversal.py | 679 | 3.546875 | 4 | # # Return Binary Pre-order Traversal
# # Question: Given a binary tree, return the preorder traversal of its nodes' values.
# # For example:
# # Given binary tree
# # 1
# # \
# # 2
# # /
# # 3
# # return [1,2,3].
# # Solutions:
#
# c_ TreeNode
# ___ - x
# val _ x
# left _ N..
# right _ N..
#
# c_ Solution
# ___ preorderTraversal root
# result _ # list
# stack _ ?
#
# w___ stack
# node _ ?.p..
# __ ?
# ?.ap.. ?.v..
# ?.ap.. ?.r..
# ?.ap.. ?.l..
# r_ ?
#
# __ -n __ ______
# BT, BT.r.. BT.r__.l.. _ ? 1 ? 2 ? 3
# print ?.? B. |
d6457e1f59aa2e7f58e030cdc15209bc2e73432b | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 3 Search Algorithms/LinearSearch.py | 489 | 4.1875 | 4 |
___ linear_search(container, item
# the running time of this algorithms is O(N)
# USE LINEAR SEARCH IF THE DATA STRUCTURE IS UNORDERED !!!
___ index __ ra__(le_(container)):
__ container[index] __ item:
# if we find the item: we return the index of that item
r_ index
# search miss - when the item is not present in the
# underlying data structure (container)
r_ -1
nums [1, 5, -3, 10, 55, 100]
print(linear_search(nums, 10))
|
64ca8b540ac52c773140d97d22196aaf7268d94b | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 8 Descriptors/89. Descriptors - Coding.py | 3,231 | 4.28125 | 4 | # %%
'''
### Descriptors
'''
# %%
'''
Python **descriptors** are simply objects that implement the **descriptor protocol**.
The protocol is comprised of the following special methods - not all are required.
- `__get__`: used to retrieve the property value
- `__set__`: used to store the property value (we'll see where we can do this in a bit)
- `__del__`: delete a property from the instance
- `__set_name__`: new to Python 3.6, we can use this to capture the property name as it is being defined in the owner
class (the class where the property is defined).
There are two types of descriptors we need to distingush as I explain in the video lecture:
- non-data descriptors: these are descriptors that only implement `__get__` (and optionally `__set_name__`)
- data descriptors: these implement the `__set__` method, and normally, also the `__get__` method.
'''
# %%
'''
Let's create a simple non-data descriptor:
'''
# %%
from datetime import datetime
class TimeUTC:
def __get__(self, instance, owner_class):
return datetime.utcnow().isoformat()
# %%
'''
So `TimeUTC` is a class that implements the `__get__` method only, and is therefore considered a non-data descriptor.
'''
# %%
'''
We can now use it to create properties in other classes:
'''
# %%
class Logger:
current_time = TimeUTC()
# %%
'''
Note that `current_time` is a class attribute:
'''
# %%
Logger.__dict__
# %%
'''
We can access that attribute from an instance of the `Logger` class:
'''
# %%
l = Logger()
# %%
l.current_time
# %%
'''
We can also access it from the class itself, and for now it behaves the same (we'll come back to that later):
'''
# %%
Logger.current_time
# %%
'''
Let's consider another example.
'''
# %%
'''
Suppose we want to create class that allows us to select a random suit and random card from that suit from a deck
of cards (with replacement, i.e. the same card can be picked more than once).
'''
# %%
'''
We could approach it this way:
'''
# %%
from random import choice, seed
class Deck:
@property
def suit(self):
return choice(('Spade', 'Heart', 'Diamond', 'Club'))
@property
def card(self):
return choice(tuple('23456789JQKA') + ('10',))
# %%
d = Deck()
# %%
seed(0)
for _ in range(10):
print(d.card, d.suit)
# %%
'''
This was pretty easy, but as you can see both properties essentially did the same thing - they picked a random choice
from some iterable.
Let's rewrite this using a custom descriptor:
'''
# %%
class Choice:
def __init__(self, *choices):
self.choices = choices
def __get__(self, instance, owner_class):
return choice(self.choices)
# %%
'''
And now we can rewrite our `Deck` class this way:
'''
# %%
class Deck:
suit = Choice('Spade', 'Heart', 'Diamond', 'Club')
card = Choice(*'23456789JQKA', '10')
# %%
seed(0)
d = Deck()
for _ in range(10):
print(d.card, d.suit)
# %%
'''
Of course we are not limited to just cards, we could use it in other classes too:
'''
# %%
class Dice:
die_1 = Choice(1,2,3,4,5,6)
die_2 = Choice(1,2,3,4,5,6)
die_3 = Choice(1,2,3,4,5,6)
# %%
seed(0)
dice = Dice()
for _ in range(10):
print(dice.die_1, dice.die_2, dice.die_3)
# %%
|
4702c698e5276bb8733860edc189cfd5a221607f | syurskyi/Python_Topics | /070_oop/008_metaprogramming/examples/abc – Abstract Base Classes/a_005_abc_abc_base.py | 1,052 | 3.875 | 4 | # abc_abc_base.py
import abc
# Forgetting to set the metaclass properly means the concrete implementations do not have their APIs enforced.
# To make it easier to set up the abstract class properly, a base class is provided that sets the metaclass
# automatically.
class PluginBase(abc.ABC):
@abc.abstractmethod
def load(self, input):
"""Retrieve data from the input source
and return an object.
"""
@abc.abstractmethod
def save(self, output, data):
"""Save the data object to the output."""
class SubclassImplementation(PluginBase):
def load(self, input):
return input.read()
def save(self, output, data):
return output.write(data)
if __name__ == '__main__':
print('Subclass:', issubclass(SubclassImplementation,
PluginBase))
print('Instance:', isinstance(SubclassImplementation(),
PluginBase))
# Subclass: True
# Instance: True
# To create a new abstract class, simply inherit from ABC.
|
12d56a34a5952ccbb85cdb40137861ddad6e95b8 | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 40 - BTSTIV.py | 1,642 | 3.859375 | 4 | # Best Time to Buy and Sell Stock IV
# Question: Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions.
# Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
# Solutions:
class Solution:
"""
@param k: an integer
@param prices: a list of integer
@return: an integer which is maximum profit
"""
def maxProfit(self, k, prices):
if prices is None or len(prices) <= 1 or k <= 0:
return 0
n = len(prices)
# k >= prices.length / 2 ==> multiple transactions Stock II
if k >= n / 2:
profit_max = 0
for i in range(1, n):
diff = prices[i] - prices[i - 1]
if diff > 0:
profit_max += diff
return profit_max
f = [[0 for i in range(k + 1)] for j in range(n + 1)]
for j in range(1, k + 1):
for i in range(1, n + 1):
for x in range(0, i + 1):
f[i][j] = max(f[i][j], f[x][j - 1] + self.profit(prices, x + 1, i))
return f[n][k]
# calculate the profit of prices(l, u)
def profit(self, prices, l, u):
if l >= u:
return 0
valley = 2**31 - 1
profit_max = 0
for price in prices[l - 1:u]:
profit_max = max(profit_max, price - valley)
valley = min(valley, price)
return profit_max
Solution().maxProfit(8,[1, 4, 8, 1, 2, 10, 20, 30, 5, 3]) |
b98b1c46993120ba213c3f1d0d80c523fe44c395 | syurskyi/Python_Topics | /125_algorithms/_examples/100_Python_Exercises_Evaluate_and_Improve_Your_Skills/Exercise 88 - Data Filter NUKE.py | 375 | 3.875 | 4 | #Create a script that uses countries_by_area.txt file as data sourcea and prints out the top 5 most densely populated countries
import pandas
data = pandas.read_csv("countries_by_area.txt")
data["density"] = data["population_2013"] / data["area_sqkm"]
data = data.sort_values(by="density", ascending=False)
for index, row in data[:5].iterrows():
print(row["country"])
|
a06fe4550d4ccb21f4ad485acd3b9264c58ba76b | syurskyi/Python_Topics | /045_functions/007_lambda/__for_nuke/01-lambda_expressions.py | 240 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""Пример использования лямбда-выражений"""
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y
}
print(operations['+'](2, 3))
print(operations['-'](2, 3))
|
c858a7abbe63bd79904515fc6f70faf9e0f7eec2 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BitManipulation/78_Subsets.py | 783 | 3.671875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
c.. Solution o..
___ subsets nums
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
subsets # list
n = l..(nums)
nums.s.. )
# We know there are totally 2^n subsets,
# becase every num may in or not in one subsets.
# So we check the jth(0<=j<n) bit for every ith(0=<i<2^n) subset.
# If jth bit is 1, then nums[j] in the subset.
sum_sets = 2 ** n
___ i __ r..(sum_sets
cur_set # list
___ j __ r..(n
power = 2 ** j
__ i & power __ power:
cur_set.a.. nums[j])
subsets.a.. cur_set)
r_ subsets
"""
[0]
[]
[1,2,3,4,7,8]
"""
|
2e672e363875afa8a54d9c5726393acc3cd84ce5 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/LinkedList/21_MergeTwoSortedLists.py | 1,523 | 4 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Recursive way.
c.. Solution o..
___ mergeTwoLists l1, l2
__ n.. l1:
r_ l2
__ n.. l2:
r_ l1
merged_head = None
__(l1.val <= l2.val
merged_head = l1
merged_head.next = self.mergeTwoLists(l1.next, l2)
____
merged_head = l2
merged_head.next = self.mergeTwoLists(l1, l2.next)
r_ merged_head
# Iteratively
c.. Solution_2 o..
___ mergeTwoLists l1, l2
merged_list = ListNode(0)
merged_head = merged_list
# Scan through l1 and l2, get the smaller one to merged list
_____ l1 a.. l2:
__ l1.val <= l2.val:
merged_list.next = l1
l1 = l1.next
____
merged_list.next = l2
l2 = l2.next
merged_list = merged_list.next
# l2 has gone to the tail already and only need to scan l1
_____ l1:
merged_list.next = l1
l1 = l1.next
merged_list = merged_list.next
# l1 has gone to the tail already and only need to scan l2
_____ l2:
merged_list.next = l2
l2 = l2.next
merged_list = merged_list.next
r_ merged_head.next
"""
[]
[]
[1,4,8,12]
[2,3]
[1,3,5,7,9]
[2,4,6,8,10]
"""
|
c1ce4711d2e14d61f0439136c8c3880790dd30f6 | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Return_Value.py | 1,503 | 3.765625 | 4 | # Python Unittest
# unittest.mock � mock object library
# unittest.mock is a library for testing in Python.
# It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
# unittest.mock provides a core Mock class removing the need to create a host of 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.
#
#
# return_value
# Set this to configure the value returned by calling the mock:
#
mock _ Mock()
mock.return_value _ 'fish'
mock()
# OUTPUT: 'fish'
#
# The default return value is a mock object and you can configure it in the normal way:
#
mock _ Mock()
mock.return_value.attribute _ sentinel.Attribute
mock.return_value()
# OUTPUT: '<Mock name='mock()()' id='...'>'
mock.return_value.a_c_w..()
#
# return_value can also be set in the constructor:
#
mock _ Mock(return_value_3)
mock.return_value
# OUTPUT: '3'
mock()
# OUTPUT: '3'
|
1b3f0818e49049b987df39945952e8017642aa19 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/Itertools/99/seq_gen.py | 298 | 3.890625 | 4 | from string import ascii_uppercase
from itertools import cycle
def sequence_generator():
alphabet_list = cycle(ascii_uppercase)
number_list = cycle(range(1,27))
for i in range(100):
yield next(number_list)
yield next(alphabet_list)
print(list(sequence_generator())) |
ab0688242ee45e648ef23c6aea22c389a47fb746 | syurskyi/Python_Topics | /095_os_and_sys/_exercises/exercises/realpython/017_Deleting Files in Python.py | 2,381 | 4.28125 | 4 | # # To delete a single file, use pathlib.Path.unlink(), os.remove(). or os.unlink().
# # os.remove() and os.unlink() are semantically identical. To delete a file using os.remove(), do the following:
#
# ______ __
#
# data_file _ 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt'
# __.r.. ?
#
# # Deleting a file using os.unlink() is similar to how you do it using os.remove():
#
# ______ __
#
# data_file _ 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt'
# __.u.. ?
#
# # Calling .unlink() or .remove() on a file deletes the file from the filesystem. These two functions will throw
# # an OSError if the path passed to them points to a directory instead of a file. To avoid this, you can either check
# # that what you’re trying to delete is actually a file and only delete it if it is, or you can use exception handling
# # to handle the OSError:
#
# ______ __
#
# data_file _ 'home/data.txt'
#
# # If the file exists, delete it
# __ __.p...i_f_ ?
# __.r.. ?
# ____
# print _*Error: |? not a valid filename')
#
# # os.path.isfile() checks whether data_file is actually a file. If it is, it is deleted by the call to os.remove().
# # If data_file points to a folder, an error message is printed to the console.
# # The following example shows how to use exception handling to handle errors when deleting files:
#
# ______ __
#
# data_file _ 'home/data.txt'
#
# # Use exception handling
# ___
# __.r.. ?
# ______ O.. __ e
# print _*Error: |? : |?.s_e..
#
# # The code above attempts to delete the file first before checking its type. If data_file isn’t actually a file,
# # the OSError that is thrown is handled in the ______ clause, and an error message is printed to the console.
# # The error message that gets printed out is formatted using Python f-strings.
# #
# # Finally, you can also use pathlib.Path.unlink() to delete files:
#
# ____ p_l_ ______ P..
#
# data_file _ P..('home/data.txt')
#
# ___
# ?.u..
# ______ Is.. __ e
# print _*Error: |? : |?.s_e..
#
# # This creates a Path object called data_file that points to a file. Calling .remove() on data_file will
# # delete home/data.txt. If data_file points to a directory, an IsADirectoryError is raised. It is worth noting that
# # the Python program above has the same permissions as the user running it. If the user does not have permission
# # to delete the file, a PermissionError is raised. |
b8c6ccb80410275e974422a96b02f43f9351a69f | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Others/220_ContainsDuplicateIII.py | 1,580 | 3.71875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
class Solution(object):
"""
Bucket sort. Refer to:
https://leetcode.com/discuss/48670/o-n-python-using-buckets-with-explanation-10-lines
1. Each bucket i save one number, which satisfy val/(t+1) == i.
2. For each number, the possible candidate can only be
in the same bucket or the two buckets besides.
3. Keep as many as k buckets to ensure that the difference is at most k.
"""
def containsNearbyAlmostDuplicate(self, nums, k, t):
if t < 0 or k < 1:
return False
buckets = {}
for i, val in enumerate(nums):
bucket_num = val / (t+1)
# Find out if there is a satisfied candidate or not.
for b in range(bucket_num-1, bucket_num+2):
if b in buckets and abs(buckets[b] - nums[i]) <= t:
return True
# update the bucket.
buckets[bucket_num] = nums[i]
# Remove the bucket which is too far away.
if len(buckets) > k:
del buckets[nums[i - k] / (t+1)]
return False
# Intuitively, easy to understand, but time limit exceed.
"""
def containsNearbyAlmostDuplicate(self, nums, k, t):
if not nums:
return False
len_nums = len(nums)
for i in range(len_nums-k):
for j in range(i+1, i+k+1):
if abs(nums[i] - nums[j]) <= t:
return True
return False
"""
"""
[]
3
0
[-1,-2,-3,-3]
1
0
[1,3,5,7,1]
3
1
"""
|
b6e934cfc5af74841bd8c4a8f951220163ce6bb0 | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 92 - SortColours.py | 757 | 4.15625 | 4 | # Sort Colours
# Question: Given an array with n objects coloured red, white or blue, sort them so that objects of the same colour are adjacent, with the colours in the order red, white and blue.
# Here, we will use the integers 0, 1, and 2 to represent the colour red, white, and blue respectively.
# Note: You are not supposed to use the library's sort function for this problem
# Solutions:
class Solution:
# @param A a list of integers
# @return sorted A, sort in place
def sortColors(self, A):
color=[0]*3
for i in A:
color[i] += 1
i = 0
for x in range(3):
for j in range(color[x]):
A[i]=x
i+=1
return A
Solution().sortColors([1,2,0,1,2,0]) |
8b3ff422b9e6313a0af0302c628c4179f750d85e | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/227 Basic Calculator II py3.py | 2,303 | 4.21875 | 4 | #!/usr/bin/python3
"""
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators
and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
"""
c_ Solution:
___ calculate s: s..) __ i..
"""
No brackets. Look at previous operand and operator, when finishing
scanning current operand.
"""
operand 0
stk # list
prev_op "+"
___ i, c __ e..(s
__ c.i..
operand operand * 10 + i..(c)
# i == len(s) - 1
delimited c __ ("+", "-", "*", "/") o. i __ l..(s) - 1
__ delimited:
__ prev_op __ "+":
cur operand
____ prev_op __ "-":
cur -operand
____ prev_op __ "*":
cur stk.p.. ) * operand
____
... prev_op __ "/"
# instead of op1 // op2 due to negative handling, -3 // 2 == -2
cur i..(stk.p.. ) / operand)
stk.a..(cur)
prev_op c
operand 0
r.. s..(stk)
___ calculate_error s: s..) __ i..
"""
cannot use dictionary, since it is eager evaluation
"""
operand 0
stk # list
prev_op "+"
___ i, c __ e..(s
__ c.i..
operand operand * 10 + i..(c)
# i == len(s) - 1
delimited c __ ("+", "-", "*", "/") o. i __ l..(s) - 1
__ delimited:
cur {
"+": operand,
"-": -operand,
"*": stk.p.. ) * operand,
"/": i..(stk.p.. ) / operand), # instead of op1 // op2 due to negative handling, -3 // 2 == -2
}[prev_op]
stk.a..(cur)
prev_op c
operand 0
r.. s..(stk)
__ _______ __ _______
... Solution().calculate("3+2*2") __ 7
|
488ebbd9ad22d6996f92b80296358d32ca941bb1 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/96_partition_list.py | 759 | 3.921875 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
c_ Solution:
"""
@param: head: The first node of linked list
@param: x: An integer
@return: A ListNode
"""
___ partition head, x
__ n.. head:
r..
left_dummy left_tail ListNode(-1)
right_dummy right_tail ListNode(-1)
w.... head:
node ListNode(head.val)
__ head.val < x:
left_tail.next node
left_tail node
____
right_tail.next node
right_tail node
head head.next
left_tail.next right_dummy.next
r.. left_dummy.next
|
5f751b07f60be785b4018628e54e9d82da661f04 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/088 Merge Sorted Array.py | 1,051 | 3.71875 | 4 | """
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The
number of elements initialized in A and B are m and n respectively.
"""
__author__ 'Danyang'
c_ Solution(o..
___ merge A, m, B, n
"""
array, ascending order.
basic of merge sort.
CONSTANT SPACE: starting backward. Starting from the end.
:param A: a list of integers
:param m: an integer, length of A
:param B: a list of integers
:param n: an integer, length of B
:return:
"""
i m-1
j n-1
closed m+n
w.... i >_ 0 a.. j >_ 0:
closed -_ 1
__ A[i] > B[j]:
A[closed] A[i]
i -_ 1
____
A[closed] B[j]
j -_ 1
# either-or
# dangling
__ j >_ 0: A[:closed] B[:j+1]
# if i >= 0: A[:closed] = A[:i+1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.