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 |
|---|---|---|---|---|---|---|
dbc0858c29b42a577ffc2a2a939cc2a293d07368 | syurskyi/Python_Topics | /070_oop/007_exceptions/_exercises/templates/The_Complete_Python_Course_l_Learn_Python_by_Doing/side_projects/handling_errors_in_user_input/errors.py | 608 | 4.03125 | 4 | def power_of_two():
user_input = input('Please enter a number: ')
try:
n = float(user_input)
n_square = n ** 2
return n_square
except ValueError:
print('Your input was invalid. Using default value 0')
return 0
print(power_of_two())
print(power_of_two())
# Define a Movie class that has two properties: name and director
class Movie:
def __init__(self, new_name, new_director):
self.name = new_name
self.director = new_director
# You should be able to create Movie objects like this one:
my_movie = Movie('The Matrix', 'Wachowski') |
427f25eeaec738cf00e6b14a733d6f981bd4a63d | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-135-sort-a-list-of-book-objects.py | 1,643 | 4.03125 | 4 | """
In this Bite you are going to look at a list of Book namedtuples and sort them by various criteria.
Complete the 4 functions below. Consider using lambda and/or one or more helper functions and/or
attrgetter (operator module). Good luck and have fun!
"""
____ c.. _______ n..
____ d__ _______ d__
____ o.. _______ a__
Book n.. '?', 'title authors pages published'
books [
Book t.._"Python Interviews",
authors="Michael Driscoll",
pages=366,
published="2018-02-28"),
Book t.._"Python Cookbook",
authors="David Beazley, Brian K. Jones",
pages=706,
published="2013-05-10"),
Book t.._"The Quick Python Book",
authors="Naomi Ceder",
pages=362,
published="2010-01-15"),
Book t.._"Fluent Python",
authors="Luciano Ramalho",
pages=792,
published="2015-07-30"),
Book t.._"Automate the Boring Stuff with Python",
authors="Al Sweigart",
pages=504,
published="2015-04-14"),
]
# all functions return books sorted in ascending order.
___ sort_books_by_len_of_title books_?
"""
Expected last book in list:
Automate the Boring Stuff with Python
"""
x s.. ? k.._l.... x l.. ?.t..
print(x)
___ sort_books_by_first_authors_last_name books_?
"""
Expected last book in list:
Automate the Boring Stuff with Python
"""
p..
___ sort_books_by_number_of_page books_?
"""
Expected last book in list:
Fluent Python
"""
p..
___ sort_books_by_published_date books_?
"""
Expected last book in list:
Python Interviews
"""
p..
sort_books_by_len_of_title books_?)
|
553b58eaecdc8fedb8c451c1e9d35940b7d5cd72 | syurskyi/Python_Topics | /018_dictionaries/examples/Python 3 Most Nessesary/9.1.Listing 9.3. Creating a complete copy of the dictionary.py | 582 | 3.796875 | 4 | d1 = {"a": 1, "b": [20, 30, 40]}
# d2 = dict(d1) # Создаем поверхностную копию
# d2["b"][0] = "test"
# d1, d2 # Изменились значения в двух переменных!!!
# # ({'a': 1, 'b': ['test', 30, 40]}, {'a': 1, 'b': ['test', 30, 40]})
# import copy
# d3 = copy.deepcopy(d1) # Создаем полную копию
# d3["b"][1] = 800
# d1, d3 # Изменилось значение только в переменной d3
# # ({'a': 1, 'b': ['test', 30, 40]}, {'a': 1, 'b': ['test', 800, 40]}) |
76751388da7addf8780880881fbcccc9dc38b93c | syurskyi/Python_Topics | /025_print/examples/025_print.py | 4,546 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# Строка-разделитель выводиться не будет
x = 'spam'
y = 99
z = ['eggs']
print(x, y, z, sep='')
# Нестандартная строка-разделитель
x = 'spam'
y = 99
z = ['eggs']
print(x, y, z, sep=', ')
# Подавление вывода символа конца строки
x = 'spam'
y = 99
z = ['eggs']
print(x, y, z, end='')
# Вывод двух строк в одной строке
x = 'spam'
y = 99 z = ['eggs']
print(x, y, z, end='')
print(x, y, z)
# Нестандартный разделитель строк
x = 'spam'
y = 99
z = ['eggs']
print(x, y, z, end='...\n')
# Несколько именованных аргументов
x = 'spam'
y = 99
z = ['eggs']
print(x, y, z, sep='...', end='!\n')
# Порядок не имеет значения
x = 'spam'
y = 99
z = ['eggs']
print(x, y, z, end='!\n', sep='...')
# Вывод в файл
x = 'spam'
y = 99
z = ['eggs']
print(x, y, z, sep='...', file=open('data.txt', 'w'))
# Вывод содержимого текстового файла
x = 'spam'
y = 99
z = ['eggs']
print(open('data.txt').read())
# Сохранить для последующего восстановления Перенаправить вывод в файл Выведет в файл, а не на экран Вытолкнуть буферы
# на диск Восстановить первоначальный поток Результаты более ранних обращений
import sys
x = 'spam'
y = 99
z = ['eggs']
temp = sys.stdout
sys.stdout = open('log.txt', 'a')
print('spam')
print(1, 2, 3)
sys.stdout.close()
sys.stdout = temp
print('back here')
print(open('log.txt').read())
# В версии 3.0 именованный аргумент file позволяет перенаправить в файл вывод единственного вызова функции print,
# не прибегая к переустановке значения sys.stdout.
import sys
x = 'spam'
y = 99
z = ['eggs']
log = open(‘log.txt’, ‘a’)
# 3.0 print(x, y, z, file=log) # Вывести в объект, напоминающий файл print(a, b, c) Вывести в оригинальный поток вывода
# Эти способы перенаправления удобно использовать, когда в одной и той же программе необходимо организовать вывод
# и в файл, и в стандартный поток вывода. Однако если вы собираетесь использовать эти формы вывода, вам потребуется
# создать объект-файл (или объект, который имеет метод write, как и объект файла) и передавать инструкции этот объект,
# а не строку с именем файла:
import sys
x = 'spam'
y = 99
z = ['eggs']
log = open('log.txt', 'w')
print(1, 2, 3, file=log)
# В 2.6: print >> log, 1, 2, 3 print(4, 5, 6, file=log) log.close() print(7, 8, 9) # В 2.6: print 7, 8, 9 print(open('log.txt').read())
# Эти расширенные формы инструкции print нередко используются для вывода сообщений об ошибках в стандартный поток ошибок,
# sys.stderr. Вы можете либо использовать его метод write и форматировать выводимые строки вручную, либо использовать
# синтаксис перенаправления:
import sys
sys.stderr.write(('Bad!' * 8) + '\n')
# Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad! print('Bad!' * 8, file=sys.stderr) # В 2.6: print >> sys.stderr, ‘Bad’ * 8 # Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
# я вывод текста обоими способами в версии 3.0, перенаправление вывода во внешний файл и выполняется проверка содержимого
# екстовых файлов:
X = 1; Y = 2 print(X, Y)
# Вывод: простой способ # 1 2 import sys # Вывод: сложный способ sys.stdout.write(str(X) + ' ' + str(Y) + '\n') print(X, Y, file=open('temp1', 'w')) # Перенаправление в файл open('temp2', 'w').write(str(X) + ' ' + str(Y) + '\n') # Запись в файл print(open('temp1', 'rb').read()) # Двоичный режим print(open('temp2', 'rb').read())
|
56992da99dfce4fc45484256df0a63cb6f2d082a | syurskyi/Python_Topics | /045_functions/007_lambda/examples/004_Closures.py | 613 | 4.40625 | 4 | # -*- coding: utf-8 -*-
def outer_func(x):
y = 4
def inner_func(z):
print(f"x = {x}, y = {y}, z = {z}")
return x + y + z
return inner_func
for i in range(3):
closure = outer_func(i)
print(f"closure({i+5}) = {closure(i+5)}")
# Точно так же лямбда также может быть замыканием. Вот тот же пример с лямбда-функцией Python:
print('#' * 52 + ' ')
def outer_func(x):
y = 4
return lambda z: x + y + z
for i in range(3):
closure = outer_func(i)
print(f"closure({i+5}) = {closure(i+5)}")
|
ea7311d342a87982b177bc9d256f87684fd45410 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/409 Longest Palindrome.py | 874 | 3.96875 | 4 | """
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be
built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
"""
____ c.. _______ d..
__author__ 'Daniel'
c_ Solution(o..
___ longestPalindrome s
"""
:type s: str
:rtype: int
"""
c d.. i..
___ elt __ s:
c[elt] += 1
ret 0
___ v __ c.v..
ret += (v/2) * 2
__ a__ m..(l.... x: x % 2 __ 1, c.v..:
ret += 1
r.. ret
__ _______ __ _______
... Solution().longestPalindrome("abccccdd") __ 7
|
d3e9bd61135b603f1f8b149781f49b88e49eb11f | syurskyi/Python_Topics | /030_control_flow/001_if/examples/Python 3 Most Nessesary/4.2. Listing 4.2. Check several conditions.py | 790 | 4.21875 | 4 | # -*- coding: utf-8 -*-
print("""Какой операционной системой вы пользуетесь?
1 — Windows 8
2 — Windows 7
3 — Windows Vista
4 — Windows XP
5 — Другая""")
os = input("Введите число, соответствующее ответу: ")
if os == "1":
print("Вы выбрали: Windows 8")
elif os == "2":
print("Вы выбрали: Windows 7")
elif os == "3":
print("Вы выбрали: Windows Vista")
elif os == "4":
print("Вы выбрали: Windows XP")
elif os == "5":
print("Вы выбрали: другая")
elif not os:
print("Вы не ввели число")
else:
print("Мы не смогли определить вашу операционную систему")
input() |
e58907b658aa64f39602711e90e8954b3d9ec228 | syurskyi/Python_Topics | /120_design_patterns/001_SOLID_design_principles/_exercises/_templates/dip/dependency_inversion_principle.py | 2,727 | 3.765625 | 4 | # """
# High level modules should not depend on low-level modules, both should depend on abstractions and Abstractions should
# not depend on details. Details should depend on abstractions.
# """
#
# # BAD PRACTICE
# print('>' * 10)
# print('BAD PRACTICE')
# print('>' * 10)
# from abc import ABCMeta, abstractmethod
#
#
# class Worker(object):
#
# def work(self):
# print("I'm working!!")
#
#
# class Manager(object):
#
# def __init__(self):
# self.worker = None
#
# def set_worker(self, worker):
# assert isinstance(worker, Worker), '`worker` must be of type {}'.format(Worker)
#
# self.worker = worker
#
# def manage(self):
# if self.worker is not None:
# self.worker.work()
#
#
# class SuperWorker(object):
#
# def work(self):
# print("I work very hard!!!")
#
#
# # Now you can see what happens if we want the `Manager` to support `SuperWorker`.
# # 1. The `set_worker` must be modified or it will not pass the type-checking.
# # 2. The `manage` method should be re-test, which means you may or may not have to
# # rewrite the testing code.
#
# def main():
# worker = Worker()
# manager = Manager()
# manager.set_worker(worker)
# manager.manage()
#
# # The following will not work...
# super_worker = SuperWorker()
# try:
# manager.set_worker(super_worker)
# except AssertionError:
# print("manager fails to support super_worker....")
#
#
# main()
#
# # GOOD PRACTICE
# # Here we solve the issues in the design in `BAD PRACTICE` with an interface (implemented with abstract class).
#
# print('>' * 10)
# print('GOOD PRACTICE')
# print('>' * 10)
#
#
# c_ IWorker o..
# m..
#
# ??
# ___ work
# p..
#
#
# # `IWorker` defines a interface which requires `work` method.
#
# c_ Worker I..
#
# ___ work
# print("I'm working!!")
#
#
# c_ Manager o..
#
# ___ -
# ?worker = N..
#
# ___ set_worker worker
# as.. isi.. ? I.. '`worker` must be of type @'.f.. W..
#
# ?w.. w..
#
# ___ manage
# __ ?w.. __ no. N...
# ?w__.w..
# # And some complex codes go here....
#
#
# c_ SuperWorker I..
#
# ___ work
# print("I work very hard!!!")
#
#
# # Now, the manager support `SuperWorker`...
# # In addition, it will support any worker which obeys the interface defined by `IWorker`!
#
# ___ main
# worker = W..
# manager = M..
# ?.s_w.. w..
# ?.m..
#
# # The following will not work...
# super_worker = S...
# ___
# m__.s_w.. ?
# m__.m..
# ________ As...
# print("manager fails to support super_worker....")
#
#
# __ _______ __ _____
# ?
|
e9e455eacdb596a36f52fee4dd8175aa37686023 | syurskyi/Python_Topics | /030_control_flow/example/Python-from-Zero-to-Hero/03-Коллеции, циклы, логика/11_ДЗ-1-2_solution.py | 259 | 4.125 | 4 | # 1
rows = int(input('Enter the number of rows'))
for x in range(rows):
print('*' * (x+1))
# 2
limit = int(input('Enter the limit'))
for x in range(limit):
if x % 2 == 0:
print(f'{x} is EVEN')
else
print(f'{x} is ODD')
|
7c1e3d910e4171a54ebbb58ee6de5f9d2bcd5227 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/DynamicProgramming/121_BestTimeToBuyAndSellStock.py | 1,230 | 3.90625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
c.. Solution o..
""" Same as "max subarray problem" using Kadane's Algorithm.
Just need one scan through the array values,
computing at each position the max profit ending at that position.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
"""
___ maxProfit prices
__ n.. prices:
r_ 0
max_profit = 0
min_buy = prices[0]
___ price __ prices:
min_buy = m.. price, min_buy)
max_profit = m..(price - min_buy, max_profit)
r_ max_profit
c.. Solution_2 o..
"""
sell_1: The maximum if we've just sold 1nd stock so far.
buy_1: The maximum if we've just buy 1st stock so far.
Then we can update sell_1 if p + buy_1(sell now) get more than pre-sell_1.
And update buy_1 if remain more money when we buy now than pre-buy_1.
Here update sell_1 before buy_1 because we need to use pre_buy_1 to get sell_1.
"""
___ maxProfit prices
sell_1, buy_1 = 0, -2**31
___ p __ prices:
sell_1 = m..(sell_1, p + buy_1)
buy_1 = m..(buy_1, -p)
r_ sell_1
"""
[]
[3,4,5,6,2,4]
[6,5,4,3,2,1]
[1,2,3,4,3,2,1,9,11,2,20]
"""
|
fa766880da60df8ad60e49550779bac2707a9cf1 | syurskyi/Python_Topics | /018_dictionaries/examples/Python 3 Deep Dive (Part 3)/16. Updating, Merging, and Copying - Coding.py | 5,226 | 4.4375 | 4 | # print('#' * 52 + ' Updating an existing keys value in a dictionary is straightforward: ')
#
# d = {'a': 1, 'b': 2, 'c': 3}
# d['b'] = 200
# print(d)
#
# print('#' * 52 + ' ')
# d1 = {'a': 1, 'b': 2}
# d2 = {'c': 3, 'd': 4}
# d1.update(d2)
# print(d1)
#
# print('#' * 52 + ' Note how the key order is maintained and based on the order in which the dictionaries were'
# ' create/updated. ')
#
# d1 = {'a': 1, 'b': 2}
# d1.update(b=20, c=30)
# print(d1)
#
# print('#' * 52 + ' Again notice how the key order reflects the order in which the parameters were'
# ' specified when calling the `update` method. ')
#
# d1 = {'a': 1, 'b': 2}
# d1.update([('c', 2), ('d', 3)])
# print(d1)
#
# print('#' * 52 + ' Of course we can use more complex iterables. For example we could use a generator expression: ')
# d = {'a': 1, 'b': 2}
# d.update((k, ord(k)) for k in 'python')
# print(d)
#
# print('#' * 52 + ' ')
# d1 = {'a': 1, 'b': 2, 'c': 3}
# d2 = {'b': 200, 'd': 4}
# d1.update(d2)
# print(d1)
#
# print('#' * 52 + ' #### Unpacking dictionaries ')
#
# l1 = [1, 2, 3]
# l2 = 'abc'
# l = (*l1, *l2)
# print(l)
#
# print('#' * 52 + ' We can do something similar with dictionaries: ')
#
# d1 = {'a': 1, 'b': 2}
# d2 = {'c': 3, 'd': 4}
# d = {**d1, **d2}
# print(d)
#
# print('#' * 52 + ' Again note how order is preserved. What happens when there are conflicting keys in the unpacking? ')
# d1 = {'a': 1, 'b': 2}
# d2 = {'b': 200, 'c': 3}
# d = {**d1, **d2}
# print(d)
#
# print('#' * 52 + ' ')
# conf_defaults = dict.fromkeys(('host', 'port', 'user', 'pwd', 'database'), None)
# print(conf_defaults)
#
# print('#' * 52 + ' ')
#
# conf_global = {
# 'port': 5432,
# 'database': 'deepdive'}
#
# conf_dev = {
# 'host': 'localhost',
# 'user': 'test',
# 'pwd': 'test'
# }
#
# conf_prod = {
# 'host': 'prodpg.deepdive.com',
# 'user': '$prod_user',
# 'pwd': '$prod_pwd',
# 'database': 'deepdive_prod'
# }
#
# config_dev = {**conf_defaults, **conf_global, **conf_dev}
# print(config_dev)
# config_prod = {**conf_defaults, **conf_global, **conf_prod}
# print(config_prod)
#
# print('#' * 52 + ' Another way dictionary unpacking can be really useful,'
# ' is for passing keyword arguments to a function: ')
#
# def my_func(*, kw1, kw2, kw3):
# print(kw1, kw2, kw3)
#
# d = {'kw2': 20, 'kw3': 30, 'kw1': 10}
#
# print('#' * 52 + ' In this case, we dont really care about the order of the elements, since we will be'
# ' unpacking keyword arguments: ')
#
# print(my_func(**d))
#
# print('#' * 52 + ' Of course we can even use it this way, but here the dictionary order does matter,'
# ' as it will be reflected in the order in which those arguments are passed to the function: ')
#
# def my_func(**kwargs):
# for k, v in kwargs.items():
# print(k, v)
#
# print(my_func(**d))
# print('#' * 52 + ' #### Copying Dictionaries ')
# d = {'a': [1, 2], 'b': [3, 4]}
# d1 = d.copy()
# print(d)
# print(d1)
#
# print(id(d), id(d1), d is d1)
#
# print('#' * 52 + ' ')
# del d['a']
# print(d)
# print(d1)
# d['b'] = 100
# print(d)
# print(d1)
#
# print('#' * 52 + ' But lets see what happens if we mutate the value of one dictionary: ')
#
# d = {'a': [1, 2], 'b': [3, 4]}
# d1 = d.copy()
# print(d)
# print(d1)
#
# d['a'].append(100)
# print(d)
# print(d1)
# print(d['a'] is d1['a'])
print('#' * 52 + ' So if we have nested dictionaries for example, as is often the case with JSON documents,'
' we have to be careful when creating shallow copies. ')
d = {'id': 123445,
'person': {
'name': 'John',
'age': 78},
'posts': [100, 105, 200]
}
d1 = d.copy()
d1['person']['name'] = 'John Cleese'
d1['posts'].append(300)
print(d1)
print(d)
print('#' * 52 + ' If we want to avoid this issue, we have to create a **deep** copy. '
' We can easily do this ourselves using recursion, but the `copy` module implements such'
' a function for us: ')
from copy import deepcopy
d = {'id': 123445,
'person': {
'name': 'John',
'age': 78},
'posts': [100, 105, 200]
}
d1 = deepcopy(d)
d1['person']['name'] = 'John Cleese'
d1['posts'].append(300)
print(d1)
print(d)
print('#' * 52 + ' We saw earlier that we can also copy a dictionary by essentially unpacking the keys of one,'
' or more dictionaries, into another.This also creates a **shallow** copy: ')
d1 = {'a': [1, 2], 'b':[3, 4]}
d = {**d1}
print(d)
d1['a'].append(100)
print(d1)
print(d)
print('#' * 52 + ' ')
# from random import randint
#
# big_d = {k: randint(1, 100) for k in range(1_000_000)}
#
#
# def copy_unpacking(d):
# d1 = {**d}
#
#
# def copy_copy(d):
# d1 = d.copy()
#
#
# def copy_create(d):
# d1 = dict(d)
#
#
# def copy_comprehension(d):
# d1 = {k: v for k, v in d.items()}
#
# print('#' * 52 + ' ')
# from timeit import timeit
#
# print(timeit('copy_unpacking(big_d)', globals=globals(), number=100))
# print(timeit('copy_copy(big_d)', globals=globals(), number=100))
# print(timeit('copy_create(big_d)', globals=globals(), number=100))
# print(timeit('copy_comprehension(big_d)', globals=globals(), number=100)) |
02326748ee457155d6e8f5d5a1499a63d7157f24 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/SearchInRotatedSortedArray.py | 3,044 | 3.96875 | 4 | """
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
一个排过序的数组被旋转了一下,但不知道在哪个位置旋转的。
给定这样一个数组,并且给定一个目标,找到此数组中是否存在目标。
时间复杂度必须是 O(log n)。
排序过的找某数第一个想法就是 二分法。
这个二分法的关键点在于应该分成两个部分:
1. 递增的部分。
2. 第二个递增的部分。
---
1. 要找的旋转点可以利用 已排序 这个关键词:
由于是已经排过序的所以若是有旋转的 nums[0] 一定是大于所有旋转的元素的。
所以首先的二分是根据以 nums[0] 为 target 找到收个比它小的位置。
代码在 find_rotate 函数。
因为target是 nums[0] lo 就不管 0 了,直接从1开始。
lo hi
4 5 6 7 0 1 2
若 mid 大于 nums[0] 因为是排过序的,而且旋转的情况的话上面也分析过了,不可能有大于 nums[0] 的存在,所以mid左边的不可能存在旋转点。
nums[0] < nums[mid]
lo = mid + 1
否则
hi = mid
这样一轮过后,要么找到旋转点,lo确定后 hi 一直缩小。
要么无旋转点,lo一直增大。
2. 对于两个递增的部分,分别进行一次普通二分即可。
beat 100%
20ms
测试地址:
https://leetcode.com/problems/search-in-rotated-sorted-array/description/
"""
class Solution(object):
def find_rotate(self, nums):
target = nums[0]
lo = 1
hi = len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > target:
lo = mid + 1
else:
hi = mid
return lo
def bi_search(self, nums, target, lo, hi):
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] > target:
hi = mid
else:
lo = mid + 1
return -1
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
rotate_index = self.find_rotate(nums)
lo = 0
hi = rotate_index
# print(hi)
one = self.bi_search(nums, target, lo, hi)
if one != -1:
return one
two = self.bi_search(nums, target, hi, len(nums))
if two != -1:
return two
return -1
|
628cf9043b8d901c2123abb494aca0441c59a8e8 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Learning Python/031_004_Implications for type testing.py | 922 | 3.5 | 4 | # c_ C:
# p___
#
# c_ D:
# p___
#
# c = C()
# d = D()
# print('#' * 23 + ' 3.0: compares the instances classes')
# print(ty.. c __ ty.. d # 3.0: compares the instances' classes
#
#
# print(ty.. c ty.. d
#
# c. -c, d. -c
#
#
# c1, c2 = C(), C()
# print(ty.. c1 __ ty.. c2
#
#
# c_ C
# p___
#
#
# c_ D
# p___
#
# c = C()
# d = D()
# print('#' * 23 + ' 2.6: all instances are same type')
# print(ty..(c) __ ty..(d # 2.6: all instances are same type
#
# print('#' * 23 + ' Must compare classes explicitly')
# print(c. -c __ d. -c # Must compare classes explicitly
#
# print(ty..(c ty.. d
#
# print(c. -c, d. -c)
#
#
# c_ C o..
# p___
#
#
# c_ D o..
# p___
#
# c = C()
# d = D()
# print('#' * 23 + ' But classes are not the same as types')
# print(ty.. c __ ty.. d # 2.6 new-style: same as all in 3.0
#
# print(ty.. c ty.. d
# print(c. -c, d. -c)
|
6c918e87b863ab1e3291fb39e9e7c78f79d82028 | syurskyi/Python_Topics | /125_algorithms/005_searching_and_sorting/_exercises/exersises/03_Buble Sort/4 - Bubble Sort - timeit.py | 1,963 | 3.75 | 4 | # ______ ti..
#
# NUM_REPETITIONS _ 500
#
# SETUP_CODE _ "from random import shuffle"
#
# # Bubble Sort Algorithm Implementations
#
# ___ bubble_sort lst
#
# n _ le. ?
#
# ___ i __ ra.. ?
# ___ j __ ra.. 0 ?-1
# __ ?|? > ?|?+1
# ?|? ?|?+1 _ ?|?+1 ?|?
#
# ___ bubble_sort_optimized lst
# n = le. ?
#
# ___ i __ ra.. ?
# swapped _ F..
#
# ___ j __ ra.. 0 n-i-1
# __ ?|? > ?|?+1
# ?|? ?|?+1 _ ?|?+1 ?|?
# s.. _ T...
#
# __ no. s..
# b..
#
# # First test case - Small list (50 elements)
#
# test_code_1 = '''
#
# a = [i for i __ ra..(50)]
#
# shuffle(a)
#
# bubble_sort(a)
#
# '''
#
# print("\n==> First test of Bubble Sort: Small List")
#
# time = ti__.ti.. _1, s.. n.. g..
#
# print("Total time to sort the list:" ti..
# print("Average time per repetition:" ti../N..
#
#
# # Second test case - Small list (50 elements) OPTIMIZED VERSION
#
# test_code_2 = '''
#
# a = [i for i __ ra..(50)]
#
# shuffle(a)
#
# bubble_sort_optimized(a)
#
# '''
#
# print("\n==> Second test of Bubble Sort: Small List (OPTIMIZED)")
#
# time _ t___.t.. _2, s.. n.. g..
#
# print("Total time to sort the list:" ?
# print("Average time per repetition:" t../N..
#
#
# # Third test case - Large list (250 elements)
#
# test_code_3 = '''
#
# a = [i for i __ ra..(250)]
#
# shuffle(a)
#
# bubble_sort(a)
#
# '''
#
# print("\n==> Third test of Bubble Sort: Large List")
#
# time = t__.t.. _3 s.. n.. g..
#
# print("Total time to sort the list:" ?
# print("Average time per repetition:", t../N..
#
#
# # Fourth test case - Large list (250 elements) OPTIMIZED
#
# test_code_4 = '''
#
# a = [i for i __ ra..(250)]
#
# shuffle(a)
#
# bubble_sort_optimized(a)
#
# '''
#
# print("\n==> Fourth test of Bubble Sort: Large List (OPTIMIZED)")
#
# time _ t__.t__ _4 s.. n.. g..
#
# print("Total time to sort the list:" ?
# print("Average time per repetition:", t../N..
#
#
|
f1cd67923e90294c3a5c457d1925664b58b06270 | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/Python_Hand-on_Solve_200_Problems/Section 7 Dictionary/check_key_exist_solution.py | 753 | 3.6875 | 4 | # # To add a new cell, type '# %%'
# # To add a new markdown cell, type '# %% [markdown]'
# # %%
# # ---------------------------------------------------------------
# # python best courses https://courses.tanpham.org/
# # ---------------------------------------------------------------
# # Check if a given key already exists in a dictionary
# # input
# # d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
# # is_key_present(5)
# # is_key_present(9)
# # output
# # Key is present in the dictionary
# # Key is not present in the dictionary
#
# d _ {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
# ___ is_key_present x
# __ ? __ ?
# print('Key is present in the dictionary')
# ____
# print('Key is not present in the dictionary')
# ? 5
# ? 9
#
#
|
a04d43d47db4b5358097188df07a0c25393bb3f4 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/100_Python_Exercises_Evaluate_and_Improve_Your_Skills/Exercise 91 - CSV to Database NUKE.py | 475 | 3.90625 | 4 | #Please download the database file database.db and and the ten_more_countries.txt file. Then, add the rows of the text file to the database file.
_______ sqlite3
_______ pandas
data pandas.read_csv("ten_more_countries.txt")
conn sqlite3.connect("database.db")
cur conn.cursor()
___ index, row __ data.iterrows
print(row["Country"], row["Area"])
cur.execute("INSERT INTO countries VALUES (NULL,?,?,NULL)",(row["Country"], row["Area"]))
conn.commit()
conn.close()
|
d83552fae236deecb6b23fb25234bdf7ff6f26b9 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/771 Jewels and Stones.py | 763 | 4.1875 | 4 | #!/usr/bin/python3
"""
You're given strings J representing the types of stones that are jewels, and S
representing the stones you have. Each character in S is a type of stone you
have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are
letters. Letters are case sensitive, so "a" is considered a different type of
stone from "A".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
"""
c_ Solution:
___ numJewelsInStones J: s.., S: s..) __ i..
"""
hash map
"""
targets s..(J)
ret 0
___ c __ S:
__ c __ targets:
ret += 1
r.. ret
|
afad1ed9a71a346d6cadfff3f7ca922426047b88 | syurskyi/Python_Topics | /070_oop/006_enumerations/examples/Python 3 An Intro to Enumerations.py | 4,889 | 4.46875 | 4 | # Python added the enum module to the standard library in version 3.4. The Python documentation describes an enum like
# this: An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration,
# the members can be compared by identity, and the enumeration itself can be iterated over.
#
# Let's look at how you might create an Enum object:
#
from enum import Enum
class AnimalEnum(Enum):
HORSE = 1
COW = 2
CHICKEN = 3
DOG = 4
print(AnimalEnum.CHICKEN)
# AnimalEnum.CHICKEN
print(repr(AnimalEnum.CHICKEN))
# <AnimalEnum.CHICKEN: 3>
# Here we create an Enumeration class called AnimalEnum. Inside the class, we create class attributes called enumeration
# members, which are constants. When you try to print out an enum member, you will just get back the same string.
# But if you print out the repr of the enum member, you will get the enum member and its value.
# If you try to modify an enum member, Python will raise an AttributeError:
#
# >>> AnimalEnum.CHICKEN = 5
# Traceback (most recent call last):
# Python Shell, prompt 5, line 1
# File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 361, in __setattr__
# raise AttributeError('Cannot reassign members.')
# builtins.AttributeError: Cannot reassign members.
# Enum members have some properties you can use to get their name and value:
#
AnimalEnum.CHICKEN.name
# 'CHICKEN'
AnimalEnum.CHICKEN.value
# 3
# Enumerations also support iteration. So you can do something fun like this:
#
for animal in AnimalEnum:
print('Name: {} Value: {}'.format(animal, animal.value))
# Name: AnimalEnum.HORSE Value: 1
# Name: AnimalEnum.COW Value: 2
# Name: AnimalEnum.CHICKEN Value: 3
# Name: AnimalEnum.DOG Value: 4
# Python's enumerations do not allow you to create enum members with the same name:
#
class Shapes(Enum):
CIRCLE = 1
SQUARE = 2
SQUARE = 3
# Traceback (most recent call last):
# Python Shell, prompt 13, line 1
# Python Shell, prompt 13, line 4
# File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 92, in __setitem__
# raise TypeError('Attempted to reuse key: %r' % key)
# builtins.TypeError: Attempted to reuse key: 'SQUARE'
# As you can see, when you try to reuse an enum member name, it will raise a TypeError.
# You can also create an Enum like this:
#
AnimalEnum = Enum('Animal', 'HORSE COW CHICKEN DOG')
print(AnimalEnum)
# <enum 'Animal'>
AnimalEnum.CHICKEN
# <Animal.CHICKEN: 3>
# Personally, I think that is really neat!
#
# Enum Member Access
# Interestingly enough, there are multiple ways to access enum members. For example, if you don't know which enum
# is which, you can just call the enum directly and pass it a value:
#
AnimalEnum(2)
# <AnimalEnum.COW: 2>
#
# If you happen to pass in an invalid value, then Python raises a ValueError
#
# >>> AnimalEnum(8)
# Traceback (most recent call last):
# Python Shell, prompt 11, line 1
# File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 291, in __call__
# return cls.__new__(cls, value)
# File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 533, in __new__
# return cls._missing_(value)
# File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 546, in _missing_
# raise ValueError("%r is not a valid %s" % (value, cls.__name__))
# builtins.ValueError: 8 is not a valid AnimalEnum
# You may also access an enumeration by name:
#
AnimalEnum['CHICKEN']
# <AnimalEnum.CHICKEN: 3>
# Enum Niceties
# The enum module also has a couple of other fun things you can import. For example, you can create automatic values
# for your enumerations:
#
from enum import auto, Enum
class Shapes(Enum):
CIRCLE = auto()
SQUARE = auto()
OVAL = auto()
Shapes.CIRCLE
# <Shapes.CIRCLE: 1>
# You can also import a handy enum decorator to make sure that your enumeration members are unique:
#
@unique
class Shapes(Enum):
CIRCLE = 1
SQUARE = 2
TRIANGLE = 1
# Traceback (most recent call last):
# Python Shell, prompt 18, line 2
# File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 830, in unique
# (enumeration, alias_details))
# builtins.ValueError: duplicate values found in <enum 'Shapes'>: TRIANGLE -> CIRCLE
# Here we create an enumeration that has two members trying to map to the same value. Because we added the @unique
# decorator, a ValueError is raised if there are any duplicate values in the enum members. If you do not have
# the @unique decorator applied, then you can have enum members with the same value.
#
# Wrapping Up
# While I don't think the enum module is really necessary for Python, it is a neat tool to have available.
# The documentation has a lot more examples and demonstrates other types of enums, so it is definitely worth a read.
|
4ceaf0265f4600274ff1d1002480e41d0441450a | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/82_v4/score.py | 365 | 3.625 | 4 | from enum import Enum
THUMBS_UP = '👍' # in case you go f-string ...
class Score(Enum):
BEGINNER = 2
INTERMEDIATE = 3
ADVANCED = 4
CHEATED = 1
def __str__(self):
return f'{self.name} => {THUMBS_UP * self.value}'
def average():
vals = [s.value for s in Score.__members__.values()]
return sum(vals) / len(vals)
|
e9b7e415a19e4aae056651b649a4744fe88aba1b | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/693 Binary Number with Alternating Bits.py | 729 | 4.34375 | 4 | #!/usr/bin/python3
"""
Given a positive integer, check whether it has alternating bits: namely, if two
adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
"""
c_ Solution:
___ hasAlternatingBits n: i.. __ b..
last N..
w.... n:
cur n & 1
# `if last` is error
__ last __ n.. N.. a.. last ^ cur __ 0:
r.. F..
last cur
n >>= 1
r.. T..
__ _______ __ _______
... Solution().hasAlternatingBits(5) __ T..
... Solution().hasAlternatingBits(7) __ F..
|
5d2df31c20546ffa5cded20386f6e03c6a1af097 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/459 Repeated Substring Pattern.py | 1,661 | 3.75 | 4 | #!/usr/bin/python3
"""
Given a non-empty string check if it can be constructed by taking a substring
of it and appending multiple copies of the substring together. You may assume
the given string consists of lowercase English letters only and its length will
not exceed 10000.
"""
c_ Solution:
___ repeatedSubstringPattern s
"""
The start of the substring is always 0, then incr the ending index e
until n/2 where n = len(s)
Brute force: O(n/2) * O(n)
test substring using KMP is O(|target|)
if s is composed of n substrings p, then s2 = s + s should contain
2n * p.
Destroying the first and the last character leads to at
least (2n - 2) * p left.
n >= 2
2n - 2 >= n
S1[1:-1] should still contain S
:type s: str
:rtype: bool
"""
r.. s __ (s + s)[1:-1]
___ repeatedSubstringPattern_error s
"""
Two pointers algorithm. The start of the substring is always 0
:type s: str
:rtype: bool
"""
__ n.. s:
r.. F..
p1 0
e 1 # ending s[0:e] is the substring
p2 1
w.... p2 < l..(s
__ s[p1] __ s[p2]:
p1 += 1
__ p1 __ e:
p1 0
____
p1 0
e p2 + 1
p2 += 1
r.. p2 __ l..(s) a.. p1 __ 0 a.. e !_ l..(s)
__ _______ __ _______
... Solution().repeatedSubstringPattern("abab") __ T..
... Solution().repeatedSubstringPattern("abcd") __ F..
... Solution().repeatedSubstringPattern("abacababacab") __ T..
|
6c27ed30f7c0259092479eae4b54a924d55e3251 | syurskyi/Python_Topics | /045_functions/_examples/Python-from-Zero-to-Hero/04-Функции и модули/06-Decorators.py | 1,179 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
def hello_world():
print('Hello, world!')
hello_world()
# In[ ]:
hello2 = hello_world
hello2()
# In[ ]:
#return func from func
#pass in a func as an arg
# In[ ]:
def log_decorator(func):
def wrap():
print(f'Calling func {func}')
func()
print(f'Func {func} finished its work')
return wrap
# In[ ]:
def hello():
print('hello, world!')
# In[ ]:
wrapped_by_logger = log_decorator(hello)
wrapped_by_logger()
# In[ ]:
@log_decorator
def hello():
print('hello, world!')
# In[ ]:
hello()
# In[ ]:
#decorators are used by frameworks extensively, that's why it's important to understand what they are in essence
# In[ ]:
from timeit import default_timer as timer
import math
import time
def measure_exectime(func):
def inner(*args, **kwargs):
start = timer()
func(*args, **kwargs)
end = timer()
print(f'Function {func.__name__} took {end-start} for execution')
return inner
@measure_exectime
def factorial(num):
time.sleep(3)
print(math.factorial(num))
# In[ ]:
factorial(100)
|
a2694917932bacba638fec6327d5993272b652cc | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/LinkedList/83_RemoveDuplicatesFromSortedList.py | 892 | 3.8125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
# @Last Modified time: 2016-04-29 16:18:37
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Recursively
c.. Solution_2 o..
___ deleteDuplicates head
__ n.. head or n.. head.next:
r_ head
head.next = self.deleteDuplicates(head.next)
r_ head.next __ head.val __ head.next.val else head
# Iteratively
c.. Solution o..
___ deleteDuplicates head
cur = head
_____ cur:
# Skip all the duplicated nodes of cur.
_____ cur.next a.. cur.val __ cur.next.val:
cur.next = cur.next.next
# No duplicated nodes, move cur to next node
cur = cur.next
r_ head
"""
[]
[1]
[3,3,3,3,3]
[1,1,1,2,3,4,4,4,4,5]
"""
|
550e085e7618bbc1b7046419f23a47587965a162 | syurskyi/Python_Topics | /070_oop/004_inheritance/examples/super/Python 3 super()/001_super function example.py | 1,476 | 4.78125 | 5 | # At first, just look at the following code we used in our Python Inheritance tutorial. In that example code,
# the superclass was Person and the subclass was Student. So the code is shown below.
class Person:
# initializing the variables
name = ""
age = 0
# defining constructor
def __init__(self, person_name, person_age):
self.name = person_name
self.age = person_age
# defining class methods
def show_name(self):
print(self.name)
def show_age(self):
print(self.age)
# # definition of subclass starts here
class Student(Person):
studentId = ""
def __init__(self, student_name, student_age, student_id):
Person.__init__(self, student_name, student_age)
self.studentId = student_id
def get_id(self):
return self.studentId # returns the value of student id
# # end of subclass definition
#
#
# # Create an object of the superclass
person1 = Person("Richard", 23)
# # call member methods of the objects
person1.show_age()
# # Create an object of the subclass
student1 = Student("Max", 22, "102")
print(student1.get_id())
student1.show_name()
# In the above example, we have called parent class function as:
# Person.__init__(self, student_name, student_age)
# We can replace this with python super function call as below.
#
#
# super().__init__(student_name, student_age)
# The output will remain the same in both the cases, as shown in the below image.
|
b6aaf21d66855444a6f681923a383ca687e40f4b | syurskyi/Python_Topics | /070_oop/001_classes/examples/ITDN Python RUS/001_Vvedenie v OOP/02-class-attributes.py | 1,718 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# Все члены класса в терминологии Python называются атрибутами
# Объявление класса MyClass с двумя атрибутами int_field
# и str_field. Атрибуты класса, являющиеся переменными,
# примерно соответствуют статическим полям класса в других
# языках программирования
class MyClass:
int_field = 8
str_field = 'a string'
# Обращение к атрибутам класса
print(MyClass.int_field)
print(MyClass.str_field)
# Создание двух экземпляров класса
object1 = MyClass()
object2 = MyClass()
# Обращение к атрибутам класса через его экземпляры
print(object1.int_field)
print(object2.str_field)
# Все вышеперечисленные обращения к атрибутам на самом деле относятся
# ко двум одним и тем же переменным
# Изменение значения атрибута класса
MyClass.int_field = 10
print(MyClass.int_field)
print(object1.int_field)
print(object2.int_field)
# Однако, аналогично глобальным и локальным переменным,
# присвоение значение атрибуту объекта не изменяет значение
# атрибута класса, а ведёт к созданию атрибута данных
# (нестатического поля)
object1.str_field = 'another string'
print(MyClass.str_field)
print(object1.str_field)
print(object2.str_field) |
6ee5d8d89559db11d88b34e9d985c35fb554695a | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/advanced/31_v3/matmul.py | 684 | 3.84375 | 4 | class Matrix(object):
def __init__(self, values):
self.values = values
def __repr__(self):
return f'<Matrix values="{self.values}">'
def __matmul__(self, other):
A = self.values
B = list(zip(*other.values))
print(A)
print(B)
Y = [[0 for _ in range(len(B))] for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B)):
Y[i][j] = sum(a * b for a, b in zip(A[i], B[j]))
return Matrix(Y)
def __imatmul__(self, other):
Y = self @ other
self.values = Y.values
return self
def __rmatmul__(self, other):
return self @ other
|
67592f055428cf2fd1aefd14a535c9d855a5a881 | syurskyi/Python_Topics | /010_strings/_exercises/_templates/Python 3 Most Nessesary/6.3. Row operations.py | 2,523 | 4.15625 | 4 | # # -*- coding: utf-8 -*-
# f__ -f _______ p.... # for Python 2.7
#
# s = "Python"
# print(s[0], s[1], s[2], s[3], s[4], s[5])
# # ('P', 'y', 't', 'h', 'o', 'n')
#
#
# s = "Python"
# # s[10]
# """
# Traceback (most recent call last):
# File "<pyshell#90>", line 1, in <module>
# s[10]
# IndexError: string index out of range
# """
#
#
# s = "Python"
# print ? -1 ? le. ?-1
# # ('n', 'n')
#
#
# s = "Python"
# # s[0] = "J" # Изменить строку нельзя
# """
# Traceback (most recent call last):
# File "<pyshell#94>", line 1, in <module>
# s[0] = "J" # Изменить строку нельзя
# TypeError: 'str' object does not support item assignment
# """
#
# s = "Python"
#
#
# print ? # Возвращается фрагмент от позиции 0 до конца строки
# # 'Python'
#
#
# print ? ? # Указываем отрицательное значение в параметре <Шаг>
# # 'nohtyP'
#
#
# print "J" + ? ? # Извлекаем фрагмент от символа 1 до конца строки
# # 'Jython'
#
#
# print ? ? # Возвращается фрагмент от 0 до len(s)-1
# # 'Pytho'
#
#
# print ? ? ? # Символ с индексом 1 не входит в диапазон
# # 'P'
#
# print ? ?; # Получаем фрагмент от len(s)-1 до конца строки
# # 'n'
#
#
# print ? ? ? # Возвращаются символы с индексами 2, 3 и 4
# # 'tho'
#
#
# print(le. "Python"), le. "\r\n\t"), le. _"\r\n\t"
# # (6, 3, 6)
#
#
# s = "Python"
# ___ i __ ra.. le. ? print ?? e.._" ")
#
#
# s = "Python"
# ___ i __ ? print ? e.._" ")
#
#
# print("Строка1" + "Строка2")
# # Строка1Строка2
#
#
# print("Строка1" "Строка2")
# # Строка1Строка2
#
#
# s = "Строка1", "Строка2"
# print(type(s)) # Получаем кортеж, а не строку
# # <class 'tuple'>
#
#
# s = "Строка1"
# print(s + "Строка2") # Нормально
# # Строка1Строка2
# # print(s "Строка2") # Ошибка
# # SyntaxError: invalid syntax
#
#
# print("string" + str(10))
# # 'string10'
#
#
# print("-" * 20)
# '--------------------'
# print("yt" __ "Python") # Найдено
# # True
# print("yt" __ "Perl") # Не найдено
# # False
# print("PHP" ___ __ "Python") # Не найдено
# # True
|
808cd586104300ae94577177ef184aa7f5c5e010 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/IntersectionOfTwoArraysII.py | 2,297 | 3.828125 | 4 | """
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
与 1 差不多,不过这次有重复。
进阶条件里问:
1. 如果是已排序的可以怎么优化?
2. 如果 数组1 比 数组2 要小,哪个算法好些?
3. 如果 数组2 在硬盘里排过序,但内存不足以一次性全部读取该怎么做?
我的思路是:
1. 先排序。
2. 之后设置两个指针。
若 1与2相同,则将结果添加到最终结果的列表中,1和2各+1。
若 1比2要大,那么表示2向后走还有可能遇到和1相同的数字,所以2 +1。
否则 1 +1。直到有一个到了末尾。
这个思路的话,进阶的1和3直接可以包含进去。
2的话,Discuss 里的其他方法基本上是用 哈希表。 1和2哈希,然后取个数较小的交集,这种方法在数组较小的时候要比上面提到的思路快。
排序后的思路:
beat 100% 24ms.
测试地址:
https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
"""
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
nums1.sort()
nums2.sort()
_n1 = 0
_n2 = 0
_n1_length = len(nums1)
_n2_length = len(nums2)
while _n1 < _n1_length and _n2 < _n2_length:
if nums1[_n1] == nums2[_n2]:
result.append(nums1[_n1])
_n1 += 1
_n2 += 1
elif nums1[_n1] < nums2[_n2]:
_n1 += 1
else:
_n2 += 1
return result |
8496596aefa39873f8321a61d361bf209e54dcbd | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/108_Convert_Sorted_Array_to_Binary_Search_Tree.py | 977 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
c_ Solution o..
# def sortedArrayToBST(self, nums):
# """
# :type nums: List[int]
# :rtype: TreeNode
# """
# # Recursion with slicing
# if not nums:
# return None
# mid = len(nums) / 2
# root = TreeNode(nums[mid])
# root.left = self.sortedArrayToBST(nums[:mid])
# root.right = self.sortedArrayToBST(nums[mid + 1:])
# return root
___ sortedArrayToBST nums
# Recursion with index
r_ getHelper(nums, 0, l.. nums) - 1)
___ getHelper nums, start, end
__ start > end:
r_ N..
mid = (start + end) / 2
node = TreeNode(nums[mid])
node.left = getHelper(nums, start, mid - 1)
node.right = getHelper(nums, mid + 1, end)
r_ node |
580c6f1c7c387f91b9ff8782a595ed7f0ed4c183 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/_templates/Python_3_Deep_Dive_Part_4/Section 02 - Classes/06-Function_Attributes.py | 5,496 | 3.796875 | 4 | # # %%
# '''
# ### Function Attributes
# '''
#
# # %%
# '''
# So far, we have been dealing with non-callable attributes. When attributes are actually functions,
# things behave differently.
# '''
#
# # %%
# c_ Person
# ___ say_hello
# print('Hello!')
#
# # %%
# print ?.s..
#
# # %%
# print(ty..(?.s...
#
# # %%
# '''
# As we can see it is just a plain function, and be called as usual:
# '''
#
# # %%
# print ?.s..
#
# # %%
# '''
# Now let's create an instance of that class:
# '''
#
# # %%
# p = ?
#
# # %%
# print h. i. ?
#
# # %%
# '''
# We know we can access class attributes via the instance, so we should also be able to access the function attribute
# in the same way:
# '''
#
# # %%
# ?.s..
#
# # %%
# print ty.. ?.s.
#
# # %%
# '''
# Hmm, the type has changed from `function` to `method`, and the function representation states that it is a
# **bound method** of the **specific object** `p` we created (notice the memory address).
# '''
#
# # %%
# '''
# And if we try to call the function from the instance, here's what happens:
# '''
#
# # %%
# t__
# ?.s..
# e__ E.. a_ ex
# print ty.. e. .-n e.
#
# # %%
# '''
# `method` is an actual type in Python, and, like functions, they are callables, but they have one distinguishing feature.
# They need to be bound to an object, and that object reference is passed to the underlying function.
# Often when we define functions in a class and call them from the instance we need to know which **specific** instance
# was used to call the function. This allows us to interact with the instance variables.
# To do this, Python will automatically transform an ordinary function defined in a class into a method when it is
# called from an instance of the class.
# Further, it will "bind" the method to the instance - meaning that the instance will be passed as the **first**
# argument to the function being called.
# It does this using **descriptors** which we'll come back to in detail later.
# For now let's just explore this a bit more:
# '''
#
# # %%
# c_ Person
# ___ say_hello 0a..
# print 'say_hello args:' a..
#
# # %%
# ?.s..
#
# # %%
# '''
# As we can see, calling `say_hello` from the **class**, just calls the function (it is just a function).
# But when we call it from an instance:
# '''
#
# # %%
# p = ?()
# he. i. ?
#
# # %%
# ?.s..
#
# # %%
# '''
# You can see that the object `p` was passed as an argument to the class function `say_hello`.
# The obvious advantage is that we can now interact with instance attributes easily:
# '''
#
# # %%
# c_ Person
# ___ set_name instance_obj new_name
# i__.n__ = n._n. # or setattr(instance_obj, 'name', new_name)
#
#
# # %%
# p = ?
#
# # %%
# ?.s.. Alex
#
# # %%
#
# print ?.-d
#
# # %%
# '''
# This has essentially the same effect as doing this:
# '''
#
# # %%
# ?.s.. ? John
#
# # %%
# print ?.-d
# # %%
# '''
# By convention, the first argument is usually named `self`, but asd you just saw we can name it whatever we want -
# it just will be in the instance when the method variant of the function is called - and it is called an
# **instance method**.
# '''
#
# # %%
# '''
# But **methods** are objects created by Python when calling class functions from an instance.
# They have their own unique attributes too:
# '''
#
# # %%
# c_ Person
# ___ say_hello ____
# print _ |self says hello
#
# # %%
# p = ?
#
# # %%
# print ?.s..
#
# # %%
# m_hello = ?.s..
#
# # %%
# print ty.. ?
#
# # %%
# '''
# For example it has a `__func__` attribute:
# '''
#
# # %%
# print ?.-f
#
# # %%
# '''
# which happens to be the class function used to create the method (the underlying function).
# '''
#
# # %%
# '''
# But remember that a method is bound to an instance. In this case we got the method from the `p` object:
# '''
#
# # %%
# print he. i. ?
#
# # %%
# print m_..-s
#
# # %%
# '''
# As you can see, the method also has a reference to the object it is **bound** to.
# '''
#
# # %%
# '''
# So think of methods as functions that have been bound to a specific object, and that object is passed in as the first
# argument of the function call. The remaining arguments are then passed after that.
# '''
#
# # %%
# '''
# Instance methods are created automatically for us, when we define functions inside our class definitions.
# This even holds true if we monkey-patch our classes at run-time:
# '''
#
# # %%
# c_ Person
# ___ say_hello _____
# print _ instance method called from |self
#
# # %%
# p = ?
# print he. i. ?
#
# # %%
# ?.s..
#
# # %%
# ?.do_work _ l_____ self: _ do_work called from |self
#
# # %%
# print ?.-d
#
# # %%
# '''
# OK, so both functions are in the class `__dict__`.
# let's create an instance and see what happens:
# '''
#
# # %%
# print ?.s..
#
# # %%
# ?.d._
#
# # %%
# ?.d._
#
# # %%
# '''
# But be careful, if we add a function to the **instance** directly, this does not work the same - we have create
# a function in the instance, so it is not considered a method (since it was not defined in the class):
# '''
#
# # %%
# ?.other_func _ l____ 0a.. print _ other_func called with a. |
#
# # %%
# print ?.o.
#
# # %%
# print 'other_func' i_ ?.-d
#
# # %%
# ?.o..
#
# # %%
# '''
# As you can see, `other_func` is, and behaves, like an ordinary function.
# '''
#
# # %%
# '''
# Long story short, functions defined in a class are transformed into methods when called from instances of the class.
# So of course, we have to account for that extra argument that is passed to the method.
# '''
#
# # %%
|
401a88672799653d6ec7622503562ca9ade096c5 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/539 Minimum Time Difference.py | 1,007 | 3.84375 | 4 | #!/usr/bin/python3
"""
Given a list of 24-hour clock time points in "Hour:Minutes" format, find the
minimum minutes difference between any two time points in the list.
Example 1:
Input: ["23:59","00:00"]
Output: 1
Note:
The number of time points in the given list is at least 2 and won't exceed 20000.
The input time is legal and ranges from 00:00 to 23:59.
"""
____ t___ _______ L..
c_ Solution:
___ findMinDifference timePoints: L..s.. __ i..
"""
sort and minus
"""
ret f__("inf")
A l..(s.. m..(minutes, timePoints)))
n l..(A)
___ i __ r..(n - 1
ret m..(ret, diff(A[i+1], A[i]
ret m..(ret, diff(A[n-1], A[0]
r.. ret
___ diff b, a
ret b - a
__ ret > 12 * 60:
ret 24 * 60 - ret
r.. ret
___ minutes a
h, m a.s..(":")
minutes 60 * i..(h) + i..(m)
r.. minutes
__ _______ __ _______
... Solution().findMinDifference(["23:59","00:00"]) __ 1
|
4a5bffa178e6da609717a681b19c51537a278a60 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+1 How to detect Positive and Negative Numbers.py | 175 | 4.0625 | 4 | x float(input("Insert any number: "))
__ x>0:
print("This is a POSITIVE number")
____ x < 0:
print("This is a NEGATIVE number")
____:
print("The number is ZERO") |
819f625f8be17ccc19566382dbd6b8eb68b39580 | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python 3 Most Nessesary/13.3.Listing 13.7. Inheritance.py | 671 | 3.78125 | 4 | class Class1: # Базовый класс
def func1(self):
print("Метод func1() класса Class1")
def func2(self):
print("Метод func2() класса Class1")
class Class2(Class1): # Класс Class2 наследует класс Class1
def func3(self):
print("Метод func3() класса Class2")
c = Class2() # Создаем экземпляр класса Class2
c.func1() # Выведет: Метод func1() класса Class1
c.func2() # Выведет: Метод func2() класса Class1
c.func3() # Выведет: Метод func3() класса Class2 |
eb10863faaab3eabc8f28a687d4d698567c8cea0 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/149/solution.py | 560 | 4.125 | 4 | words = ("It's almost Holidays and PyBites wishes You a "
"Merry Christmas and a Happy 2019").split()
def sort_words_case_insensitively(words):
"""Sort the provided word list ignoring case, and numbers last
(1995, 19ab = numbers / Happy, happy4you = strings, hence for
numbers you only need to check the first char of the word)
"""
# this works because: >>> sorted([True, False])
# [False, True]
return sorted(words, key=lambda x: (str(x).lower(), x[0].isdigit() ))
print(sort_words_case_insensitively(words)) |
4b608473f7af8c94e1e98dae58a5cdfac59943d2 | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 6 Single Inheritance/75. Delegating to Parent - Coding.py | 9,481 | 4.09375 | 4 | # %%
'''
### Delegating to Parent
'''
# %%
'''
You'll most likely encounter `super()` in the `__init__` method of custom classes, but delegation is not restricted to
__init__`. You can use `super()` anywhere you need to explicitly instruct Python to use a callable definition that is
higher up in the inheritance chain. In these cases you only need to use `super()` if there is some ambiguity - i.e.
your current class overrides an ancestor's callable and you need to specifically tell Python to use the callable
in the ancestry chain.
'''
# %%
class Person:
def work(self):
return 'Person works...'
class Student(Person):
def work(self):
result = super().work()
return f'Student works... and {result}'
# %%
s = Student()
# %%
s.work()
# %%
'''
Now the `super().work()` call in the `Student` class looks up the hierarchy chain until it finds the first definition
for that callable.
We can easily see this:
'''
# %%
class Person:
def work(self):
return 'Person works...'
class Student(Person):
pass
class PythonStudent(Student):
def work(self):
result = super().work()
return f'PythonStudent codes... and {result}'
# %%
ps = PythonStudent()
# %%
ps.work()
# %%
'''
Of course every class can delegate up the chain in turn:
'''
# %%
class Person:
def work(self):
return 'Person works...'
class Student(Person):
def work(self):
result = super().work()
return f'Student studies... and {result}'
class PythonStudent(Student):
def work(self):
result = super().work()
return f'PythonStudent codes... and {result}'
# %%
ps = PythonStudent()
ps.work()
# %%
'''
Do note that when there is **no ambiguity** there is no need to use `super()`:
'''
# %%
class Person:
def work(self):
return 'Person works...'
class Student(Person):
def study(self):
return 'Student studies...'
class PythonStudent(Student):
def code(self):
result_1 = self.work()
result_2 = self.study()
return f'{result_1} and {result_2} and PythonStudent codes...'
# %%
ps = PythonStudent()
# %%
ps.code()
# %%
'''
The really important thing to understand is which object (instance) is bound when a delegated method is called.
It is **always** the calling object:
'''
# %%
class Person:
def work(self):
return f'{self} works...'
class Student(Person):
def work(self):
result = super().work()
return f'{self} studies... and {result}'
class PythonStudent(Student):
def work(self):
result = super().work()
return f'{self} codes... and {result}'
# %%
ps = PythonStudent()
# %%
hex(id(ps))
# %%
ps.work()
# %%
'''
As you can see each of the methods in the parent classes were called bound to the original `PythonStudent` instance
`ps`.
'''
# %%
'''
What this means is that when a class sets an instance attribute, it will be set in the namespace of the original object.
Here's a simple example that illustrates this:
'''
# %%
class Person:
def set_name(self, value):
print('Setting name using Person set_name method...')
self.name = value
class Student(Person):
def set_name(self, value):
print('Student class delegating back to parent...')
super().set_name(value)
# %%
s = Student()
# %%
'''
As you can see, the dictionary for `s` is currently empty:
'''
# %%
s.__dict__
# %%
'''
But if we call set_name:
'''
# %%
s.set_name('Eric')
# %%
'''
As you can see the `Person` class `set_name` method did the actual work, but the `name` attribute is created in
the `Student` instance `s`:
'''
# %%
s.__dict__
# %%
'''
So just to re-emphasize, whenever you use `super()`, any `self` in the called methods actually refers to the object
used to make the initial call.
'''
# %%
'''
One place where this is really handy is in class initialization - we use it to leverage the parent class initializer
so we don't have to re-write a lot of initialization code in our child class.
'''
# %%
'''
Let's use a simple example first:
'''
# %%
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, student_number):
super().__init__(name)
self.student_number = student_number
# %%
s = Student('Python', 30)
# %%
s.__dict__
# %%
'''
I do want to point out that if your parent class has initializer and your child class does not, then Python will attempt
to call the parent `__init__` automatically - because the `__init__` is **inherited** from the parent class!
'''
# %%
class Person:
def __init__(self):
print('Person __init__')
class Student(Person):
pass
# %%
s = Student()
# %%
'''
But watch what happens if the parent class requires an argument:
'''
# %%
class Person:
def __init__(self, name):
print('Person __init__ called...')
self.name = name
class Student(Person):
pass
# %%
try:
s = Student()
except TypeError as ex:
print(ex)
# %%
'''
In fact, we can pass this argument to the `Student` class and Python will automatically pass it along to the (inherited)
`Person` class `__init__`:
'''
# %%
s = Student('Alex')
# %%
s.__dict__
# %%
'''
However, if we provide a custom `__init__` in our child class, then Python will not automatically call the parent init:
'''
# %%
class Person:
def __init__(self):
print('Person __init__ called...')
class Student(Person):
def __init__(self):
print('Student __init__ called...')
# %%
s = Student()
# %%
'''
To do so, we need to call `super().__init__`:
'''
# %%
class Person:
def __init__(self):
print('Person __init__ called...')
class Student(Person):
def __init__(self):
super().__init__()
print('Student __init__ called...')
# %%
s = Student()
# %%
'''
Let's take a look at a more practical example:
'''
# %%
'''
Let's first create a `Circle` class:
'''
# %%
from math import pi
from numbers import Real
class Circle:
def __init__(self, r):
self._r = r
self._area = None
self._perimeter = None
@property
def radius(self):
return self._r
@radius.setter
def radius(self, r):
if isinstance(r, Real) and r > 0:
self._r = r
self._area = None
self._perimeter = None
else:
raise ValueError('Radius must a positive real number.')
@property
def area(self):
if self._area is None:
self._area = pi * self.radius ** 2
return self._area
@property
def perimeter(self):
if self._perimeter is None:
self._perimeter = 2 * pi * self.radius
return self._perimeter
# %%
'''
Now let's make a specialized circle class, a `UnitCircle` which is simply a circle with a radius of `1`:
'''
# %%
class UnitCircle(Circle):
def __init__(self):
super().__init__(1)
# %%
'''
And now we can use it this way:
'''
# %%
u = UnitCircle()
# %%
u.radius, u.area, u.perimeter
# %%
'''
Now one thing that's off here is that we can actually set the radius on the `UnitCircle` - which we probably don't want
to allow.
My approach here is to redefine the `radius` property in the unit circle class and disallow setting the radius
altogether:
'''
# %%
class UnitCircle(Circle):
def __init__(self):
super().__init__(1)
@property
def radius(self):
return super().radius
# %%
u = UnitCircle()
# %%
u.radius
# %%
u.radius = 10
# %%
'''
Note how my overriding property uses `super().radius` - I cannot use `self.radius` as that would be trying to call
the radius getter defined in the `UnitCircle` class (the one I am currently defining) - instead I specifically want
to access the property from the parent class.
'''
# %%
'''
Finally I want to come back to another example that also helps underscore the fact that methods called via `super()`
are still bound to the original (child) object, and hence will use methods defined in the child class if they override
any in the parent class - this is a little tricky, but fundamental to understand:
'''
# %%
class Person:
def method_1(self):
print('Person.method_1')
self.method_2()
def method_2(self):
print('Person.method_2')
class Student(Person):
def method_1(self):
print('Student.method_1')
super().method_1()
# %%
s = Student()
s.method_1()
# %%
'''
So `Student.method_1` called `Person.method_1` via `super`, which in turn called `Person.method_2` - all of these
methods were bound to the `Student` instance `s`.
'''
# %%
'''
Now watch what happens when we also override `method_2` in the `Student` class:
'''
# %%
class Person:
def method_1(self):
print('Person.method_1')
self.method_2()
def method_2(self):
print('Person.method_2')
class Student(Person):
def method_1(self):
print('Student.method_1')
super().method_1()
def method_2(self):
print('Student.method_2')
# %%
s = Student()
s.method_1()
# %%
'''
Since `self.method_2()` in the Person class was called from `s`, that `self` is the instance `s`, and hence `method_2`
from the `Student` class was called, not the one defined in the `Person` class!
'''
# %%
|
167776832ada38867f57a79bd37cf80b5ef2ff70 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/001_iterations_and_iteration_tool/examples/013_Copying an Iterator.py | 1,344 | 4.90625 | 5 | # "Copying" an Iterator
# Sometimes we may have an iterator that we want to use multiple times for some reason.
# As we saw, iterators get exhausted, so
# simply making multiple references to the same iterator will not work -
# they will just point to the same iterator object.
#
# What we would really like is a way to "copy" an iterator and use these copies independently of each other.
#
# As you can see iters is a tuple contains 3 iterators - let's put them into some variables and see what each one is:
from itertools import tee
def squares(n):
for i in range(n):
yield i**2
gen = squares(10)
gen
iters = tee(squares(10), 3)
iters
iter1, iter2, iter3 = iters
next(iter1), next(iter1), next(iter1)
next(iter2), next(iter2)
next(iter3)
# "Copying" an Iterator
# As you can see, iter1, iter2, and iter3 are essentially three independent "copies" of our original
# iterator (squares(10))
# Note that this works for any iterable, so even sequence types such as lists:
# But you'll notice that the elements of lists are not lists themselves!
#
# As you can see, the elements returned by tee are actually iterators -
# even if we used an iterable such as a list to start off with!
l = [1, 2, 3, 4]
lists = tee(l, 2)
lists[0]
lists[1]
list(lists[0])
list(lists[0])
lists[1] is lists[1].__iter__()
'__next__' in dir(lists[1])
|
0c0ac5a38c38b07dbcb2bca1dbcf4a7500700ef1 | syurskyi/Python_Topics | /085_regular_expressions/examples/Python 3 Most Nessesary/7.20. Finding the first pattern match.py | 1,533 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import re
p = re.compile(r"[0-9]+")
print("Найдено" if p.match("str123") else "Нет")
# Нет
print("Найдено" if p.match("str123", 3) else "Нет")
# Найдено
print("Найдено" if p.match("123str") else "Нет")
# Найдено
p = r"[0-9]+"
print("Найдено" if re.match(p, "str123") else "Нет")
# Нет
print("Найдено" if re.match(p, "123str") else "Нет")
# Найдено
p = re.compile(r"[0-9]+")
print("Найдено" if re.match(p, "123str") else "Нет")
# Найдено
p = re.compile(r"[0-9]+")
print("Найдено" if p.search("str123") else "Нет")
# Найдено
print("Найдено" if p.search("123str") else "Нет")
# Найдено
print("Найдено" if p.search("123str", 3) else "Нет")
# Нет
p = r"[0-9]+"
print("Найдено" if re.search(p, "str123") else "Нет")
# Найдено
p = re.compile(r"[0-9]+")
print("Найдено" if re.search(p, "str123") else "Нет")
# Найдено
p = re.compile("[Pp]ython")
print("Найдено" if p.fullmatch("Python") else "Нет")
# Найдено
print("Найдено" if p.fullmatch("py") else "Нет")
# Нет
print("Найдено" if p.fullmatch("PythonWare") else "Нет")
# Нет
print("Найдено" if p.fullmatch("PythonWare", 0, 6) else "Нет")
# Найдено
p = "[Pp]ython"
print("Найдено" if re.fullmatch(p, "Python") else "Нет")
# Найдено
print("Найдено" if re.fullmatch(p, "py") else "Нет")
# Нет |
c1d5564b0ac514129054bc175764a865aa6e6e07 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/119_xmas_tree_generator/save1_passed.py | 487 | 3.796875 | 4 | def generate_xmas_tree(rows=10):
"""Generate a xmas tree of stars (*) for given rows (default 10).
Each row has row_number*2-1 stars, simple example: for rows=3 the
output would be like this (ignore docstring's indentation):
*
***
*****"""
tree_stars = [(line * 2 - 1) * '*'
for line in range(rows + 1)]
tree = [line.center(len(tree_stars[-1]), ' ')
for line in tree_stars[1:]]
return '\n'.join(tree)
|
a2ef98f9c2960ed70c81aeaf7add720023be160f | syurskyi/Python_Topics | /115_testing/examples/Github/_Level_1/unittest_example-master/test/test_example.py | 2,756 | 3.59375 | 4 | import unittest
# from typing import ...
# Example code to organize the unit testing of a class following xUnit philosophy with 'unittest'
# Designed following chapters 3 and 6 of "Python Unit Test Automation" - Ashwin Pajankar
# It has been written in a typed manner (PEP 484) (hence, only fully work as of Python 3.6)
# https://medium.com/@ageitgey/learn-how-to-use-static-type-checking-in-python-3-6-in-10-minutes-12c86d72677b
# 'Fixture' (ENG) -> 'Accessori' (CAT)
# Test fixtures : set of sterps performed before and after the tests
# There are module-level, class-level and function-level fixtures
# module-level: executed once at the beginning/end of the module testing.
# class-level: executed once at the beginning/end of the class testing.
# function-level: executed before/after every test method in the test class
# Notice that function fixtures does not follow PEP8 python naming style !!
# Module-level fixtures
# -----------------------------------------------------------
def setUpModule() -> None:
"""called once, before anything else in this module"""
print("In SetUpModule()...(module-level fixture)")
def tearDownModule() -> None:
"""called once, after everything else in this module"""
print("In tearDownModule()...(module-level fixture)")
# Test class
# ------------------------------------------------------------
class TestClassExample(unittest.TestCase):
# Class-level fixtures. Require the classmethod decorator
# -----------------------------------------------------------
@classmethod
def setUpClass(cls) -> None:
"""called once, at the beginning of the class testing"""
print("In setUpClass()...(class-level fixture)")
@classmethod
def tearDownClass(cls) -> None:
"""called once, once all tests have been done, if setUpClass succesfull"""
print("In tearDownClass")
# Method-level fixtures
# -----------------------------------------------------------
def setUp(self) -> None:
"""called before every test method"""
print("In setUp()...")
def tearDown(self) -> None:
"""called after every test method"""
# Test case related functions
# -----------------------------------------------------------
# assert methods available
# https://docs.python.org/3/library/unittest.html#assert-methods
# Test cases
def test_case01(self):
print(self.id()) # Print module, class and method name, to ease test output analysis
self.assertEqual(True, False)
def test_case02(self):
print(self.id())
self.assertEqual(True, True)
def test_case03(self):
print(self.id())
self.assertNotEqual(True, False)
if __name__ == '__main__':
unittest.main()
|
b515b48cbe2000b9d0ef4145af2b0ccb1e197bb1 | syurskyi/Python_Topics | /121_refactoring/Code_Smells/Bloaters/Long_Method/Replace_Temp_with_Query/006.py | 1,081 | 3.734375 | 4 | # Problem
def calculateTotal():
subtotal = calculateSubtotal()
discount = 0
if subtotal > 100:
discount = subtotal * 0.1
total = subtotal - discount
return total
def calculateSubtotal():
pass
# calculation logic for subtotal
# Solution
def calculateTotal():
subtotal = calculateSubtotal()
discount = calculateDiscount(subtotal)
total = subtotal - discount
return total
def calculateSubtotal():
pass
# calculation logic for subtotal
def calculateDiscount(subtotal):
if subtotal > 100:
return subtotal * 0.1
else:
return 0
# In this example, we extract the calculation of the discount into a separate function calculateDiscount().
# This function takes the subtotal as a parameter and returns the discount amount. By doing so, we eliminate
# the temporary variable discount in the main function and improve code clarity.
#
# By applying the "Replace Temp with Query" refactoring technique, we can simplify complex calculations,
# improve code maintainability, and enhance code readability. |
1f3cdd17aad7658f6e1eb39cf1e234514707db76 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 4 Selection Algorithms/QuickSelect.py | 1,433 | 3.5 | 4 | _____ r__
c_ QuickSelect:
___ - nums
nums nums
first_index 0
last_index le_(nums) - 1
___ run k
r_ select(first_index, last_index, k-1)
# PARTITION PHASE
___ partition first_index, last_index
# generate a random value within the range [first, last]
pivot_index r__.randint(first_index, last_index)
swap(pivot_index, last_index)
___ i __ ra__(first_index, last_index
__ nums[i] > nums[last_index]:
swap(i, first_index)
first_index + 1
swap(first_index, last_index)
# it is the index of the pivot
r_ first_index
___ swap i, j
nums[i], nums[j] nums[j], nums[i]
# THIS IS THE SELECTION PHASE
___ select first_index, last_index, k
pivot_index partition(first_index, last_index)
# selection phase when we compare the pivot_index with k
__ pivot_index < k:
# we have to discard the left sub-array and keep
# considering the items on the right
r_ select(pivot_index + 1, last_index, k)
____ pivot_index > k:
# we have to discard the right sub-array
r_ select(first_index, pivot_index - 1, k)
# we have found the item we are looking for
r_ nums[pivot_index]
x [1, 2, -5, 10, 100, -7, 3, 4]
select QuickSelect(x)
print(select.run(2))
|
4fd8358ac28cd3b5366ed7f9cb94833e72d8559a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/DFS/WordSearchII.py | 3,633 | 3.953125 | 4 | """
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must 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 in a word.
Example:
Input:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Output: ["eat","oath"]
Note:
You may assume that all inputs are consist of lowercase letters a-z.
I 的升级版。
I 中只需要找一个单词是否存在。
II 中升级为找很多单词。
直接扩展 I 的话对重复比较多的单词会TLE,
比如 aaaa,aaaab,aaaac,aaaae ...
这样的都有共同的前缀,aaaa,基于这个条件,可以用前缀树来将它们整合在一起,省去重复搜索 aaaa 的步骤。
前缀树可以用字典(哈希表)来模拟。
```
trie = {}
for w in words:
# 从根字典开始。
t = trie
# leetcode
for l in w:
# 若当前前缀不在这个前缀树字典中,则创建为一个新的前缀树字典。
# 'l' not in t
# t -> {'l': {}
# }
if l not in t:
t[l] = {}
# 下一次循环的为 'l' 下的 'e'
# 所以替换为 t['l']
t = t[l]
# 这里添加一个标记,表示当前前缀树可以是末尾。
# 如 leet 和 leetcode 可以在 leet 处结束。
t['mark'] = 'mark'
```
之后的操作基本一样,只是把字符串换成了字典。
这里有个有趣的点,下面的写法会有重复的数据进去,
如果结果一开始用 set,添加时可以直接去重,效率是比不过先用 list 再用 set 去重的。
beat:
46%
测试地址:
https://leetcode.com/problems/word-search-ii/description/
前面的思路都是同一种思路,也就是可以优化。
"""
c.. Solution o..
___ findWords board, words
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
result # list
words = s..(words)
trie _ # dict
___ i __ words:
t = trie
___ x __ i:
__ x n.. __ t:
t[x] _ # dict
t = t[x]
t['!'] = '!'
___ find(board, x, y, word, pre
# print(word)
__ '!' __ word:
result.a.. pre)
___ w __ word:
raw = board[y][x]
board[y][x] = 0
# up
__ y-1 >= 0 a.. board[y-1][x] __ w:
find(board, x, y-1, word[w], pre+w)
# down
__ y+1 < l..(board) a.. board[y+1][x] __ w:
find(board, x, y+1, word[w], pre+w)
# left
__ x-1 >= 0 a.. board[y][x-1] __ w:
find(board, x-1, y, word[w], pre+w)
# right
__ x+1 < l..(board[0]) a.. board[y][x+1] __ w:
find(board, x+1, y, word[w], pre+w)
board[y][x] = raw
maps _ # dict
___ i __ r..(l..(board)):
___ j __ r..(l..(board[0])):
try:
maps[board[i][j]].append((i,j))
except:
maps[board[i][j]] = [(i,j)]
___ i __ trie:
__ maps.get(i
xy = maps.get(i)
___ j __ xy:
find(board, j[1], j[0], trie[i], i)
r_ list(s..(result))
|
82432656d06b812015a3cb455c5c05085c762933 | syurskyi/Python_Topics | /125_algorithms/005_searching_and_sorting/_exercises/templates/02_Binary Search/4 Binary Search/Binary-Search-Recursive-Implementation-with-Print-Statements.py | 1,170 | 4.25 | 4 | # ___ binary_search data low high item
#
# print("\n===> Calling Binary Search")
# print("Lower bound:" ?
# print("Upper bound:" ?
#
# __ ? <_ ?
# middle _ ? + ?//2
# print("Middle index:" ?
# print("Item at middle index:" ?|?
# print("We are looking for:" ?
# print("Is this the item?", "Yes" __ ?|? __ i.. ____ "No"
# __ ?|? __ ?
# print("The item was found at index:" ?
# r_ ?
# ____ ?|? > ?
# print("The current item is greater than the target item:" ?|? ">" ?
# print("We need to discard the upper half of the list"
# print("The lower bound remains at:" ?
# print("The upper bound is now:" ? - 1
# r_ ? d.. ? m.. - 1 i..
# ____
# print("The current item is smaller than the target item:" ?|? "<" ?
# print("We need to discard the lower half of the list")
# print("The lower bound is now:" ? + 1
# print("The upper bound remains at:" ?
# r_ ? d.. m.. + 1 ? i..
# ____
# print("The item was not found in the list")
# r_ -1
|
ff244299c6831f01e62b6e1ec05c777c9840c057 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/197/mday.py | 618 | 4.28125 | 4 | from datetime import date
def get_mothers_day_date(year):
"""Given the passed in year int, return the date Mother's Day
is celebrated assuming it's the 2nd Sunday of May."""
day_counter = 1
mothers_day = date(year, 5, day_counter)
sunday_count = 0
while sunday_count < 2:
if mothers_day.weekday() == 6:
sunday_count += 1
day_counter += 1
else:
day_counter += 1
if sunday_count == 2:
break
mothers_day = mothers_day.replace(day=day_counter)
return mothers_day
# if __name__ == "__main__":
# print(get_mothers_day_date(2014)) |
0c8fc8a50961f4cd18c3b1bfe27baf3beb6e8cdc | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/SortArrayByParity.py | 889 | 4.125 | 4 | """
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
开胃菜,偶数放一堆,奇数放一堆。
O(n).
测试链接:
https://leetcode.com/contest/weekly-contest-102/problems/sort-array-by-parity/
contest.
"""
c.. Solution o..
___ sortArrayByParity A
"""
:type A: List[int]
:rtype: List[int]
"""
even # list
odd # list
___ i __ A:
__ i % 2 __ 0:
even.a.. i)
____
odd.a.. i)
r_ even + odd
|
08e9f80faf31bc8002939a3833f17f6c784e2b48 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/_templates/Python 3 Most Necessary/13.6.Listing 13.14. An example of overloading mathematical operators.py | 907 | 4.03125 | 4 | # -*- coding: utf-8 -*-
class MyClass:
def __init__(self, y):
self.x = y
def __add__(self, y): # Перегрузка оператора +
print("Экземпляр слева")
return self.x + y
def __radd__(self, y): # Перегрузка оператора +
print("Экземпляр справа")
return self.x + y
def __iadd__(self, y): # Перегрузка оператора +=
print("Сложение с присваиванием")
self.x += y
return self
c = MyClass(50)
print(c + 10) # Выведет: Экземпляр слева 60
print(20 + c) # Выведет: Экземпляр справа 70
c += 30 # Выведет: Сложение с присваиванием
print(c.x) # Выведет: 80 |
5b20636dd84b1d2d0e6ddee5cfe760bcebae38aa | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Practical_Python_Programming_Practices/Practice 3. How to check for Greatest of 3 Numbers.py | 259 | 3.640625 | 4 | # x _ in. i.. "Insert first number: "
# y _ in. i.. "Insert second number: "
# z _ in. i.. "Insert third number: "
#
# print("The maximum number is : ", e.._"")
# __ y<_ x >_z:
# print(x)
# ____ x <_ y >_z:
# print(y)
# ____ x<_ z >_ y:
# print(z) |
fa5ce2dd1e40237d09d030ef93cc02a501f28d69 | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/Python_Hand-on_Solve_200_Problems/Section 10 Math/standard_deviation_solution.py | 823 | 3.546875 | 4 | # # To add a new cell, type '# %%'
# # To add a new markdown cell, type '# %% [markdown]'
# # %%
# # Write a Python program to calculate the standard deviation of the following data.
# # Input
# # Sample Data: [4, 2, 5, 8, 6]
# # Output
# # Standard Deviation : 2.23606797749979
#
# ______ ma__
# ______ ___
#
# ___ sd_calc data
# n _ le. ?
#
# __ n <_ 1
# r_ 0.0
#
# mean sd _ a.. ? 0.0
#
# # calculate stan. dev.
# ___ el __ ?
# ? +_ (fl.. ? - ?**2
# sd _ ma__.sq.. ? / fl.. ? - 1
#
# r_ ?
#
#
# ___ avg_calc ls
# n, mean _ le. ? 0.0
#
# __ ? <_ 1
# r_ ? 0
#
# # calculate average
# ___ el __ ?
# m.. _ ? + fl.. ?
# m.. _ ? / fl.. ?
#
# r_ ?
#
# data _ [4, 2, 5, 8, 6]
# print("Sample Data: " ?
# print("Standard Deviation : " ? ?
#
#
|
56babf76fe75de9231d6b9079eeb56190fa70312 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Practice_Python_by_Solving_100_Python_Problems/52.py | 278 | 4 | 4 | # #Please fix the script so that it returns the user submited first name for the first %s
# #and the second name for the second %s
#
# firstname = ? ("Enter first name: ")
# secondname = ? ("Enter second name: ")
# print("Your first name is __ and your second name is __" _ ? ?
|
b93d47200a6b3d85b091efd78c2d3ca1bac9f217 | syurskyi/Python_Topics | /018_dictionaries/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 28 Totaling Donations Exercise.py | 741 | 3.828125 | 4 | # Version 1
#
# Loop over donations, add all the VALUES together and store in a variable called total_donations
donations = dict(sam=25.0, lena=88.99, chuck=13.0, linus=99.5, stan=150.0, lisa=50.25, harrison=10.0)
total_donations = 0
for donation in donations.values():
total_donations += donation
# Advanced Version 1 -
#
# This solution uses a built-in function called sum() which I cover in the "Lambdas and Built-In Functions" section.
# We haven't talked about how it works, but if you're curious...
total_donations = sum(donation for donation in donations.values())
# Advanced Version 2
#
# An even better solution using the same sum built-in function is just this nice little line:
total_donations = sum(donations.values()) |
c91dfb6cd0b30ca592645fcf0a1fa05ee0c13ad0 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/216 Combination Sum III.py | 1,182 | 3.671875 | 4 | """
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used
and each combination should be a unique set of numbers.
Ensure that numbers within the set are sorted in ascending order.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
"""
__author__ 'Daniel'
c_ Solution:
___ combinationSum3 k, n
"""
Backtracking
:type k: int
:type n: int
:rtype: list[list[int]]
"""
ret # list
dfs(k, n, # list, ret)
r.. ret
___ dfs remain_k, remain_n, cur, ret
__ remain_k __ 0 a.. remain_n __ 0:
ret.a..(l..(cur
r..
# check max and min reach
__ remain_k * 9 < remain_n o. remain_k * 1 > remain_n:
r..
start 1
__ cur:
start cur[-1] + 1 # unique
___ i __ x..(start, 10
cur.a..(i)
dfs(remain_k - 1, remain_n - i, cur, ret)
cur.p.. )
__ _______ __ _______
... Solution().combinationSum3(3, 9) __ [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
|
49a39ee32f845817124fe2e1cd2112ba6c790282 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/Itertools/65/test_yield.py | 125 | 3.703125 | 4 |
def some_list(x):
for i in range(x):
for j in range(i):
yield (i+1)*(j+1)
print(list(some_list(5))) |
9823abdc5913bf193054f16ca7a44b5d55f69d99 | syurskyi/Python_Topics | /070_oop/008_metaprogramming/examples/Expert Python Programming/properties_decorator.py | 1,167 | 4.53125 | 5 | """
"Properties" section example of writing properties using
`property` decorator
"""
class Rectangle:
def __init__(self, x1, y1, x2, y2):
self.x1, self.y1 = x1, y1
self.x2, self.y2 = x2, y2
@property
def width(self):
"""rectangle height measured from top"""
return self.x2 - self.x1
@width.setter
def width(self, value):
self.x2 = self.x1 + value
@property
def height(self):
"""rectangle height measured from top"""
return self.y2 - self.y1
@height.setter
def height(self, value):
self.y2 = self.y1 + value
def __repr__(self):
return "{}({}, {}, {}, {})".format(
self.__class__.__name__,
self.x1, self.y1, self.x2, self.y2
)
if __name__ == "__main__":
rectangle = Rectangle(0, 0, 10, 10)
print(
"At start we have {} with size of {} x {}"
"".format(rectangle, rectangle.width, rectangle.height)
)
rectangle.width = 2
rectangle.height = 8
print(
"After resizing we have {} with size of {} x {}"
"".format(rectangle, rectangle.width, rectangle.height)
)
|
349f3736e7f0501b25121416277c49c97428fee4 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/142_v2/scores.py | 1,604 | 4 | 4 | # ____ c.. _______ n..
#
# MIN_SCORE 4
# DICE_VALUES r.. 1, 7
#
# Player n..('Player', 'name scores')
#
#
# ___ calculate_score scores
# """Based on a list of score ints (dice roll), calculate the
# total score only taking into account >= MIN_SCORE
# (= eyes of the dice roll).
#
# If one of the scores is not a valid dice roll (1-6)
# raise a ValueError.
#
# Returns int of the sum of the scores.
# """
# s 0
# ___ score __ ?
# __ ? n.. __ D..
# r.. V...("Invalid dice value")
# __ ? >_ M..
# s += ?
#
# r.. s
#
# ___ get_winner players
# """Given a list of Player namedtuples return the player
# with the highest score using calculate_score.
#
# If the length of the scores lists of the players passed in
# don't match up raise a ValueError.
#
# Returns a Player namedtuple of the winner.
# You can assume there is only one winner.
#
# For example - input:
# Player(name='player 1', scores=[1, 3, 2, 5])
# Player(name='player 2', scores=[1, 1, 1, 1])
# Player(name='player 3', scores=[4, 5, 1, 2])
#
# output:
# Player(name='player 3', scores=[4, 5, 1, 2])
# """
#
# score_list max_player = N..
# max_score f__ '-inf'
# ___ player __ ?
# __ score_list __ N..
# s.. l.. ?.s..
# ____
# __ l.. ?.s.. !_ ?
# r.. V... "All lengths don't match!"
# score c.. ?.s..
# __ ? > m..
# m.. ?
# m.. ?
#
#
# r.. ?
|
fc8d7266535b1af6ba76aac70e15c867ee09d069 | syurskyi/Python_Topics | /125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 14 Array/array_longest_non_repeat_solution.py | 2,461 | 4.25 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
# ---------------------------------------------------------------
# python best courses https://courses.tanpham.org/
# ---------------------------------------------------------------
# Challenge
# Given a string, find the length of the longest substring
# without repeating characters.
# Examples:
# Given "abcabcbb", the answer is "abc", which the length is 3.
# Given "bbbbb", the answer is "b", with the length of 1.
# Given "pwwkew", the answer is "wke", with the length of 3.
# ---------------------------------------------------------------
# Algorithm
# In summary : Form all posible sub_strings from original string, then return length of longest sub_string
# - start from 1st character, form as long as posible sub string
# - Add first character to sub string
# - Add second character to sub string if second character not exist in sub string
# ...
# - Repeate until got a character which already exist inside sub string or
# - start from 2nd character, form as long as posible sub string
# - Add first character to sub string
# - Add second character to sub string if second character not exist in sub string
# ...
# - Repeate until got a character which already exist inside sub string
# ....
# - start from final character, form as long as posible sub string
# - Add first character to sub string
# - Add second character to sub string if second character not exist in sub string
# ...
# - Repeate until got a character which already exist inside sub string
# ---------------------------------------------------------------
str = "abcbb"
def longest_non_repeat(str):
# init start position and max length
i=0
max_length = 1
for i,c in enumerate(str):
# init counter and sub string value
start_at = i
sub_str=[]
# continue increase sub string if did not repeat character
while (start_at < len(str)) and (str[start_at] not in sub_str):
sub_str.append(str[start_at])
start_at = start_at + 1
# update the max length
if len(sub_str) > max_length:
max_length = len(sub_str)
print(sub_str)
return max_length
longest_non_repeat(str)
|
8aa25e67573a2f055e7a9846d5c1c26d7e08605c | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BreadthFirstSearch/127_WordLadder.py | 2,448 | 3.875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
c.. Solution o..
___ ladderLength beginWord, endWord, wordList
"""
Breadth First Search
When build the adjacency tree, skip the visited word
"""
__ beginWord __ endWord:
r_ 1
cur_level = [beginWord]
next_level # list
visited_word _ # dict
visited_word[beginWord] = 1
length = 0
_____ cur_level:
length += 1
___ cur_word __ cur_level:
cur_len = l..(cur_word)
# Get the next level
# When I put "abc...xyz" in the out loop, it just exceeded.
___ i __ r..(cur_len
pre_word = cur_word[:i]
post_word = cur_word[i+1:]
___ j __ "abcdefghijklmnopqrstuvwxyz":
next_word = pre_word + j + post_word
# Find the endWord
__ next_word __ endWord:
r_ length + 1
____ (next_word n.. __ visited_word a..
next_word __ wordList
visited_word[next_word] = 1
next_level.a.. next_word)
____
pass
# Scan the next level then
cur_level = next_level
next_level # list
r_ 0
""" disapproved, when wordList growth bigger, it may be called too many times
def is_one_distance(self, word_1, word_2):
# alert(len(word_1) == len(word_2))
word_l = len(word_1)
one_distance = False
for i in range(word_l):
if word_1[i] != word_2[i]:
if not one_distance:
one_distance = True
else:
return False
return one_distance
"""
"""
if __name__ == '__main__':
sol = Solution()
print sol.ladderLength("hit", "cog", ["hot", "dot", "dog", "lot", "log"])
print sol.ladderLength("hit", "cog", ["hot", "dot", "doh", "lot", "loh"])
print sol.ladderLength(
"hit", "cog",
["hot", "dot", "dog", "lot", "log", "hig", "hog"])
print sol.ladderLength(
"cet", "ism",
['cot', 'con', 'ion', 'inn', 'ins', 'its', 'ito', 'ibo', 'ibm', 'get',
'gee', 'gte', 'ate', 'ats', 'its', 'ito', 'ibo', 'ibm'])
"""
|
588bf0bbec704e41a0cd2915531d901029ae21c0 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/beginner-bite-1-sum-n-numbers.py | 2,579 | 3.890625 | 4 |
"""
TASK DESCRIPTION:
Write a function that can sum up numbers:
It should receive a list of n numbers.
If no argument is provided, return sum of numbers 1..100.
Look closely to the type of the function's default argument ...
"""
# ??? Co powinno sie wydarzyc, jesli przekazemy pusta liste ???
input = []
############################### KEY TAKEAWAYS #################################
### 1. Sum of empty list is 0.
### 2. None is a type of NoneType
### 3. "is" keyword is used to test if two variables refer to the same object.
### It returns True if the two variable are referring to same object otherwise it returns False.
### https://stackoverflow.com/questions/60975441/behaviour-of-is-keyword-in-python
### 4. Some objects in Python are cached for efficieny reasons
### https://medium.com/@bdov_/https-medium-com-bdov-python-objects-part-ii-demystifying-cpython-shared-objects-fce1ec86dd63
### 5. Every object has value, type and memory location (id)
### https://realpython.com/null-in-python/
################################################################################
### ----------- My solution ---------------------------
def my_sum_numbers(numbers=None):
result = 0
# Dlaczego samo "if numbers:" nie dziala? Tzn. wtedy jak podamy pusta liste to nie spelnia warunku?
# albo inaczej, przy przekazywaniu argumentu "if arg" dla pelnej tablicy dziala, dla pustej nie
# "false" values include False, None, 0 and [] (an empty list), also empty sets, strings, dicts.
# Bo if testuje wartosc boolowska danej zmiennej. Dlatego jak podamy pusta liste,
# to bedzie traktowane jako bool false i
# zostanie policzona suma 1-100.
# None ma wartosc boolowska false, czyli albo moge sprawdzic wartosc albo moge sprawdzic typ obiektu
# is None
# == False
#
if numbers != None:
for item in numbers:
result += item
return result
for i in range(101):
result += i
return result
### ---------- PyBites original solution ---------------
def pyb_sum_numbers(numbers=None):
if numbers is None:
numbers = range(1, 101)
return sum(numbers)
### Tutaj nie wiem, co chcialem osiagnac. Chyba chcialem sprawdzic alternatywny sposob, jak moznaby
### cos takiego napisac. Zamiast sprawdzac, co zostalo przekazane jako argument, mozna
### probowac obsluzyc wyjatek 'NoneType' object is not iterable
def sum_numbers_1(numbers=None):
try:
return sum(numbers)
except TypeError:
return sum(range(1,101))
print(pyb_sum_numbers("hello"))
|
8d70800936635d3784421da646d1c8eebf91ae17 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/advanced/268_newbie_bite/save1_nopass.py | 106 | 3.6875 | 4 | # Enter your code below this line
month = input("What's the name of the 12th month of the calendar year?") |
7fbb8d1a8f6ba5adb4f40772214e605c8c901a24 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/387 First Unique Character in a String.py | 739 | 3.984375 | 4 | """
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
"""
__author__ 'Daniel'
c_ Solution(o..
___ firstUniqChar s
"""
:type s: str
:rtype: int
"""
__ n.. s:
r.. -1
first # dict
___ i, v __ e..(l..(s:
__ v n.. __ first:
first[v] i
____
first[v] -1
lst f.. l.... x: x !_ -1, first.values
r.. m..(lst) __ lst ____ -1
__ _______ __ _______
... Solution().firstUniqChar("leetcode") __ 0 |
848f72a5bccaaf413b9fcc51b5751a42a969a604 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Backtracking/79_WordSearch.py | 2,328 | 3.953125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def exist(self, board, word):
if not board and word:
return False
if not word:
return True
m_rows = len(board)
n_cols = len(board[0])
for row in range(m_rows):
for col in range(n_cols):
if board[row][col] == word[0]:
board[row][col] = "*"
if (self.exist_adjacent(
[row, col],
word[1:],
board)):
return True
# Backtracking here
board[row][col] = word[0]
return False
def exist_adjacent(self, cur_pos, next_str, board):
# Find all the characters in word.
if not next_str:
return True
adj_pos = self.adj_pos_lists(cur_pos, board)
# No adjancent position can be used.
if not adj_pos:
return False
# For every adjacent position, find out whether it contains
# the first character in the word or not.
# If matches, then resursively check the other characters in word.
for pos in adj_pos:
row = pos[0]
col = pos[1]
if board[row][col] == next_str[0]:
board[row][col] = "*"
if (self.exist_adjacent(
[row, col],
next_str[1:],
board)):
return True
# Backtracking here
board[row][col] = next_str[0]
return False
# Find the adjacent position around cur_pos
def adj_pos_lists(self, cur_pos, board):
m_rows = len(board)
n_cols = len(board[0])
row = cur_pos[0]
col = cur_pos[1]
adj_list = []
if row - 1 >= 0:
adj_list.append([row - 1, col])
if row + 1 < m_rows:
adj_list.append([row + 1, col])
if col - 1 >= 0:
adj_list.append([row, col - 1])
if col + 1 < n_cols:
adj_list.append([row, col + 1])
return adj_list
"""
[]
""
[]
"as"
["abce","sfcs", "adee"]
"abcced"
["abce","sfcs", "adee"]
"abcb"
["ABCE","SFES","ADEE"]
"ABCESEEEFSAD"
"""
|
6b5576d476a5b235e2152e5753db888d5b912fba | syurskyi/Python_Topics | /012_lists/_exercises/_templates/Learning Python/009_003_Python 2.X and 3.X mixed-type comparisons and sorts.py | 824 | 3.71875 | 4 | __author__ = 'sergejyurskyj'
L1 = [1, ('a', 3)] # Same value, unique objects
L2 = [1, ('a', 3)]
print(L1 == L2, L1 is L2) # Equivalent? Same object?
S1 = 'spam'
S2 = 'spam'
print(S1 == S2, S1 is S2)
S1 = 'a longer string'
S2 = 'a longer string'
print(S1 == S2, S1 is S2)
L1 = [1, ('a', 3)]
L2 = [1, ('a', 2)]
print('#' * 52 + ' Less, equal, greater: tuple of results')
print(L1 < L2, L1 == L2, L1 > L2) # Less, equal, greater: tuple of results
D1 = {'a':1, 'b':2}
D2 = {'a':1, 'b':3}
print(D1 == D2)
# print(D1 < D2)
D1 = {'a':1, 'b':2}
D2 = {'a':1, 'b':3}
print(D1 == D2)
# D1 < D2 # TypeError: unorderable types: dict() < dict()
list(D1.items())
sorted(D1.items())
print(sorted(D1.items()) < sorted(D2.items()))
print(sorted(D1.items()) > sorted(D2.items()))
L = [None] * 100
print(L)
|
a59eb87232f3f07450acc97b0ecccca53c611d09 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/254/scoping.py | 504 | 3.78125 | 4 | num_hundreds = -1
def sum_numbers(numbers: list) -> int:
"""Sums passed in numbers returning the total, also
update the global variable num_hundreds with the amount
of times 100 fits in total"""
sumlist = sum(numbers)
globals()['num_hundreds'] += sumlist //100
return sumlist
""" numlists = [[],[1, 2, 3],[40, 50, 60],[140, 50, 60],[140, 150, 160],[1140, 150, 160]]
for numlist in numlists:
print(numlist)
print(sum_numbers(numlist))
print(num_hundreds) """ |
0048c207702b1fac7f6c1d42162732567d0749e6 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Python_3_Deep_Dive_Part_4/Section 8 Descriptors/89. Descriptors - Coding.py | 3,307 | 4.21875 | 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 ____ 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:
# '''
#
# # %%
# ____ d_t_ _____ d_t_
#
# c_ TimeUTC
# ___ -g ____ instance owner_class
# r_ d_t_.u_n_.i_f_
#
# # %%
# '''
# 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:
# '''
#
# # %%
# c_ Logger
# current_time _ ?
#
# # %%
# '''
# Note that `current_time` is a class attribute:
# '''
#
# # %%
# ?. -d
#
# # %%
# '''
# We can access that attribute ____ an instance of the `Logger` class:
# '''
#
# # %%
# l = L..
#
# # %%
# print(?.c..
#
# # %%
# '''
# We can also access it ____ the class itself, and for now it behaves the same (we'll come back to that later):
# '''
#
# # %%
# L__.c..
#
# # %%
# '''
# Let's consider another example.
# '''
#
# # %%
# '''
# Suppose we want to create class that allows us to select a random suit and random card ____ that suit ____ a deck
# of cards (with replacement, i.e. the same card can be picked more than once).
# '''
#
# # %%
# '''
# We could approach it this way:
# '''
#
# # %%
# ____ ra.. _____ ch.. se..
#
# c_ Deck
# ?p..
# ___ suit ____
# r_ ch.. 'Spade', 'Heart', 'Diamond', 'Club'
#
# ?p..
# ___ card ____
# r_ ch.. tu.. '23456789JQKA'| + '10';|
#
# # %%
# d = ?
#
# # %%
# seed(0)
#
# ___ _ __ ra.. 10 # _ the original
# print(?.c.. ?.s..
#
# # %%
# '''
# This was pretty easy, but as you can see both properties essentially did the same thing - they picked a random choice
# ____ some iterable.
# Let's rewrite this using a custom descriptor:
# '''
#
# # %%
# c_ Choice
# ___ - ____ $choices
# ____.? ?
#
# ___ -g ____ instance, owner_class
# r_ c..|____.c..
#
# # %%
# '''
# And now we can rewrite our `Deck` c_ this way:
# '''
#
# # %%
# c_ Deck
# suit = C.. 'Spade', 'Heart', 'Diamond', 'Club'
# card = C.. @'23456789JQKA', '10'
#
# # %%
# seed(0)
#
# d = D..
#
# ___ _ __ ra.. 10
# print ?.c.. ?.s..
#
# # %%
# '''
# Of course we are not limited to just cards, we could use it in other classes too:
# '''
#
# # %%
# c_ 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)
#
# # %%
|
2bfd3d1c05de676850cd447ca2f9adab34335e98 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/String/SortCharactersByFrequency.py | 1,384 | 4.15625 | 4 | """
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input:
"cccaaa"
Output:
"cccaaa"
Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input:
"Aabb"
Output:
"bbAa"
Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
给定一个字符串,以字符出现的频率进行排序。
思路:
1. 用一个字典记录每个字符出现的频率。
2. 根据出现的频率排序。
3. 因为直接堆在一起即可,直接构建一个列表。
4. 在组合起来。
beat 95% 36ms.
测试地址:
https://leetcode.com/problems/sort-characters-by-frequency/description/
"""
c.. Solution o..
___ frequencySort s
"""
:type s: str
:rtype: str
"""
x _ # dict
___ i __ s:
try:
x[i] += 1
except:
x[i] = 1
b = s..(x, k.._l... t: x[t], reverse=True)
r_ ''.join([i*x[i] ___ i __ b])
|
a7d7ec6ef2a98fd3407265cd5af6c7f8f35d9e37 | syurskyi/Python_Topics | /070_oop/004_inheritance/examples/super/Understanding Python super()/001.py | 250 | 3.515625 | 4 | class Base(object):
def __init__(self):
print("Base created")
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
ChildA()
ChildB()
|
f6266f2a13c31a765420db79fdb8235f06487c5e | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/_algorithms_challenges/pybites/beginner/beginner-bite-208-find-the-number-pairs-summing-up-n.py | 1,075 | 4.34375 | 4 | '''
In this Bite you complete find_number_pairs which receives a list of numbers and returns all the pairs
that sum up N (default=10). Return this list of tuples from the function.
So in the most basic example if we pass in [2, 3, 5, 4, 6] it returns [(4, 6)] and if
we give it [9, 1, 3, 8, 7] it returns [(9, 1), (3, 7)]. The tests check more scenarios
(floats, other values of N, negative numbers).
Have fun and keep calm and code in Python
'''
___ find_number_pairs(numbers, N=10
result_possible_duplicates # list
___ i __ numbers:
number_to_find N - i
__ number_to_find __ l..(s..(numbers) - s..([i]:
result_possible_duplicates.a..((i, number_to_find
result # list
# Reverse tuples so we can eliminate duplicates using set
___ p __ result_possible_duplicates:
a,b p
temp (a,b) __ a < b ____ (b,a)
result.a..(temp)
r.. l..(s..(result
print(find_number_pairs([0.24, 0.36, 0.04, 0.06, 0.33, 0.08, 0.20, 0.27, 0.3, 0.31,
0.76, 0.05, 0.08, 0.08, 0.67, 0.09, 0.66, 0.79, 0.95], 1
|
b3a301679651342e857b909786567e3792548d25 | syurskyi/Python_Topics | /095_os_and_sys/examples/realpython/031_Working With Compressed Archives.py | 950 | 3.578125 | 4 | # tarfile can also read and write TAR archives compressed using gzip, bzip2, and lzma compression.
# To read or write to a compressed archive, use tarfile.open(), passing in the appropriate mode for
# the compression type.
#
# For example, to read or write data to a TAR archive compressed using gzip, use the 'r:gz' or 'w:gz'
# modes respectively:
import tarfile
files = ['app.py', 'config.py', 'tests.py']
with tarfile.open('packages.tar.gz', mode='w:gz') as tar:
tar.add('app.py')
tar.add('config.py')
tar.add('tests.py')
with tarfile.open('packages.tar.gz', mode='r:gz') as t:
for member in t.getmembers():
print(member.name)
# app.py
# config.py
# tests.py
#
# The 'w:gz' mode opens the archive for gzip compressed writing and 'r:gz' opens the archive
# for gzip compressed reading. Opening compressed archives in append mode is not possible.
# To add files to a compressed archive, you have to create a new archive.
|
79f63e8ffd91b098a1bc5431b1c56a83ae08e113 | syurskyi/Python_Topics | /045_functions/007_lambda/_exercises/templates/003_Decorator can be applied to lambda_!cool!.py | 769 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# ___ some_decorator f
# ___ wraps $
# print _*Calling function * | ?. -n |**|
# r_ ? a___
#
# r_ ?
#
# ??
# ___ decorated_function x
# print _*With argument *|x|**|
#
# ? 2
#
# print('#' * 52 + ' ')
# print('#' * 52 + ' ')
# print('#' * 52 + ' ')
#
# # Defining a decorator
# ___ trace f
# ___ wrap $ $$
# print _*[TRACE] func: ?. -n| args: a..| kwargs: k..|*|
# r_ _|$ $$
#
# r_ ?
#
# # Applying decorator to a function
# ??
# ___ add_two x
# r_ ? + 2
#
# # Calling the decorated function
# ? 3
#
# # Applying decorator to a lambda
# print t00|l_____ x x ** 2 | 3
#
# print('#' * 52 + ' ')
# print('#' * 52 + ' ')
# print('#' * 52 + ' ')
#
#
# li.. ma. t..|l_____ x ? * 2 |ra.. 3
|
76d2c1b04fbd323151d922175310497a5cb8eb07 | syurskyi/Python_Topics | /070_oop/008_metaprogramming/examples/Abstract Classes in Python/a_003_Implementation Through Subclassing.py | 333 | 4.03125 | 4 | # Python program showing
# implementation of abstract
# class through subclassing
import abc
class parent:
def geeks(self):
pass
class child(parent):
def geeks(self):
print("child class")
# Driver code
print(issubclass(child, parent))
print(isinstance(child(), parent))
# Output:
# True
# True
|
69ad335243346001307df683f73d09e66a0e72d3 | syurskyi/Python_Topics | /095_os_and_sys/examples/realpython/018_Deleting Directories.py | 1,222 | 4.3125 | 4 | # The standard library offers the following functions for deleting directories:
#
# os.rmdir()
# pathlib.Path.rmdir()
# shutil.rmtree()
#
# To delete a single directory or folder, use os.rmdir() or pathlib.rmdir(). These two functions only work if the d
# irectory you’re trying to delete is empty. If the directory isn’t empty, an OSError is raised. Here is how to delete
# a folder:
import os
trash_dir = 'my_documents/bad_dir'
try:
os.rmdir(trash_dir)
except OSError as e:
print(f'Error: {trash_dir} : {e.strerror}')
# Here, the trash_dir directory is deleted by passing its path to os.rmdir(). If the directory isn’t empty,
# an error message is printed to the screen:
#
# Traceback (most recent call last):
# File '<stdin>', line 1, in <module>
# OSError: [Errno 39] Directory not empty: 'my_documents/bad_dir'
#
# Alternatively, you can use pathlib to delete directories:
from pathlib import Path
trash_dir = Path('my_documents/bad_dir')
try:
trash_dir.rmdir()
except OSError as e:
print(f'Error: {trash_dir} : {e.strerror}')
# Here, you create a Path object that points to the directory to be deleted. Calling .rmdir() on the Path object
# will delete it if it is empty. |
3ea4a2eeebbb4784a57accf7184350ed53c503ff | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/SortArrayByParityII.py | 968 | 4.21875 | 4 | """
Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies this condition.
Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
根据单双排列,一个双一个单。
"""
c.. Solution o..
___ sortArrayByParityII A
"""
:type A: List[int]
:rtype: List[int]
"""
odd # list
even # list
___ i __ A:
__ i%2 __ 0:
even.a.. i)
____
odd.a.. i)
result # list
___ j, k __ zip(even, odd
result.a.. j)
result.a.. k)
r_ result
|
834d18a6ecbdf21fa47341260b9a1fb240e5d200 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/324 Wiggle Sort II.py | 2,802 | 3.6875 | 4 | """
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], 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?
"""
__author__ 'Daniel'
c_ Solution(o..
___ wiggleSort A
"""
1. Quick selection for finding median (Average O(n))
2. Three-way partitioning to split the data
3. Re-mapping the index to do in-place partitioning
Average time O(n)
Space O(1)
:type A: List[int]
:rtype: in-place
"""
n l..(A)
median_idx find_kth(A, 0, n, n/2)
v A[median_idx]
idx l.... i: (2*i+1) % (n|1)
lt -1
hi n
i 0
w.... i < hi:
__ A[idx(i)] > v:
lt += 1
A[idx(lt)], A[idx(i)] A[idx(i)], A[idx(lt)]
i += 1
____ A[idx(i)] __ v:
i += 1
____
hi -_ 1
A[idx(hi)], A[idx(i)] A[idx(i)], A[idx(hi)]
___ pivot A, lo, hi, pidx_ N..
lt lo-1
gt hi
__ n.. pidx: pidx lo
v A[pidx]
i lo
w.... i < gt:
__ A[i] < v:
lt += 1
A[lt], A[i] A[i], A[lt]
i += 1
____ A[i] __ v:
i += 1
____
gt -_ 1
A[gt], A[i] A[i], A[gt]
r.. lt, gt
___ find_kth A, lo, hi, k
__ lo >_ hi: r..
lt, gt pivot(A, lo, hi)
__ lt < k < gt:
r.. k
__ k <_ lt:
r.. find_kth(A, lo, lt+1, k)
____
r.. find_kth(A, gt, hi, k)
c_ SolutionSort(o..
___ wiggleSort nums
"""
Sort-based: interleave the small half and large half
Could they be "equal to"? That would require some number M to appear both in the smaller and the larger half.
It shall be the largest in the smaller half and the smallest in the larger half.
To deal with duplicate median element cases (e.g. [4 5 5 6]), interleave in a reverse order
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n l..(nums)
A s..(nums)
j, k (n-1) / 2, n-1
___ i __ x..(l..(nums:
__ i % 2 __ 0:
nums[i] A[j]
j -_ 1
____
nums[i] A[k]
k -_ 1
__ _______ __ _______
# A = [1, 5, 1, 1, 6, 4]
A [3, 2, 1, 1, 3, 2]
Solution().wiggleSort(A)
print A
|
e078c1706b2bf4fc5458e0377519db5d6243c4d4 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/leetcode/684_redundant_connection.py | 1,647 | 3.625 | 4 | """
given input is an undirected graph
1. iterate edges
2. if u and v are connected before we add edge in nodes (graph)
=> that is the edge should be removed
"""
c_ Solution:
"""
UnionFind
"""
___ findRedundantConnection edges
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
__ n.. edges:
r.. # list
nodes # dict
___ u, v __ edges:
__ n.. union(nodes, u, v
r.. [u, v]
r.. # list
___ union nodes, u, v
a f.. nodes, u)
b f.. nodes, v)
__ a __ b:
r.. F..
nodes[a] b
r.. T..
___ find nodes, u
__ u n.. __ nodes:
nodes[u] u
r.. u
__ nodes[u] __ u:
r.. u
nodes[u] f.. nodes, nodes[u])
r.. nodes[u]
_______ c..
c_ Solution:
"""
DFS
"""
___ findRedundantConnection edges
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
__ n.. edges:
r.. # list
nodes c...d..(s..)
___ u, v __ edges:
# dfs to check u and v are connected already => cycle
__ u __ nodes a.. v __ nodes a.. dfs(nodes, u, v, s..
r.. [u, v]
nodes[u].add(v)
nodes[v].add(u)
r.. # list
___ dfs nodes, u, v, visited
__ u __ v:
r.. T..
__ u __ visited:
r.. F..
visited.add(u)
___ x __ nodes[u]:
__ dfs(nodes, x, v, visited
r.. T..
r.. F..
|
a4246818f77617532d4e5049fe334f4a598c35bd | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/325/arithmetic.py | 949 | 3.5 | 4 | # ____ t___ _______ G..
#
# VALUES "[0.1, 0.2, 0.3, 0.005, 0.005, 2.67]"
#
#
# ___ calc_sums values s.. ? __ G.. s.. N.. N..
# """
# Process the above JSON-encoded string of values and calculate the sum of each adjacent pair.
#
# The output should be a generator that produces a string that recites the calculation for each pair, for example:
#
# 'The sum of 0.1 and 0.2, rounded to two decimal places, is 0.3.'
# """
# values_list ?.s.. "[]" .s.. ", "
# ___ i __ r.. 1 l.. ?
#
# previous, current f__ ? ? -1 f__ ? ?
# __ p.. < 0.1 a.. c.. < 0.1
# total ? + ?
# ____
# total r.. ? 2 + r.. ? 2
#
# y.. _*The sum of ? ? -1 and ? ?, rounded to two decimal places, is ?|.2f
#
#
# # if __name__ == "__main__":
# # test = calc_sums()
# # print(next(test))
# # print(next(test))
# # print(next(test))
# # print(next(test))
# # print(next(test)) |
f788a24381a9a53b3d2c1e1006cf7314749a80ec | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/042_Trapping_Rain_Water.py | 2,264 | 3.546875 | 4 | c_ Solution o..
___ trap height
"""
:type height: List[int]
:rtype: int
"""
ls = l.. height)
__ ls __ 0:
r_ 0
res, left = 0, 0
w.. left < ls a.. height[left] __ 0:
left += 1
pos = left + 1
w.. pos < ls:
__ height[pos] >= height[left]:
# there is a right bar which is no less than left bar
res += rain_water(height, left, pos)
left = pos
pos += 1
____ pos __ ls - 1:
# left bar is higher than all right bar
max_value, max_index = 0, pos
___ index __ r.. left + 1, ls
__ height[index] > max_value:
max_value = height[index]
max_index = index
res += rain_water(height, left, max_index)
left = max_index
pos = left + 1
____
pos += 1
r_ res
___ rain_water height, start, end
# computer rain water
__ end - start <= 1:
r_ 0
min_m = m.. height[start], height[end])
res = min_m * (end - start - 1)
step = 0
___ index __ r.. start + 1, end
__ height[index] > 0:
step += height[index]
r_ res - step
# def trap(self, height):
# ls = len(height)
# if ls == 0:
# return 0
# height.append(0)
# height.insert(0, 0)
# left = [0] * ls
# right = [0] * ls
# cur_left, cur_right = 0, 0
# for i in range(1, ls + 1):
# cur_left = max(cur_left, height[i - 1])
# # left[i] store max bar from left
# left[i - 1] = cur_left
# for i in reversed(range(ls)):
# cur_right = max(cur_right, height[i + 1])
# # right[i] store max bar from right
# right[i] = cur_right
# res = 0
# for i in range(ls):
# curr = min(left[i], right[i])
# if curr > height[i]:
# res += curr - height[i]
# return res
__ ____ __ ____
# begin
s ?
print s.trap([2,6,3,8,2,7,2,5,0])
|
2eea360e8642372c4134745ba2fb376c0202b200 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/70/eggs.py | 438 | 3.625 | 4 | from random import choice
COLORS = 'red blue green yellow brown purple'.split()
class EggCreator:
def __init__(self, max) -> None:
self.max = max
self.count = 0
def __iter__(self):
return self
def __next__(self):
self.count += 1
if self.count <= self.max:
return f"{choice(COLORS)} egg"
else:
raise StopIteration
ec = EggCreator(5)
print(next(ec)) |
00b1d1d09e4f4f30bdd78dd2ed68cc3cc03c5a79 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/ConvertSortedArrayToBinarySearchTree.py | 1,918 | 3.96875 | 4 | """
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
给定一个已排序过的数组,将它转换为一颗高度平衡的二叉搜索树。
也就是两颗子树的高度差不超过1。
因为是排序的数组,相对来说也异常简单,可以将它看做是一颗二叉搜索树中序遍历后的结果。
按照此结果转换回去就是了。
每次都二分:
[-10,-3,0,5,9]
mid
5//2 = 2 mid = 2
0
[-10, -3] [5, 9] 2 // 2 = 1 mid = 1
↓ ↓
-3 9
[-10] [] [5] []
为空则不进行下面的操作。
beat 98%
测试地址:
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
c.. Solution o..
___ sortedArrayToBST nums
"""
:type nums: List[int]
:rtype: TreeNode
"""
__ n.. nums:
r_ None
___ makeBinarySearchTree(nums
mid = l..(nums) // 2
root = TreeNode(nums[mid])
left = nums[:mid]
right = nums[mid+1:]
__ left:
root.left = makeBinarySearchTree(left)
__ right:
root.right = makeBinarySearchTree(right)
r_ root
root = makeBinarySearchTree(nums)
r_ root
|
a5ae2046a401cae347fe7a33ccf0c96ec51dcef5 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/Palindrome.py | 474 | 4.25 | 4 | #The word or whole phrase which has the same sequence of letters in both directions is called a palindrome.
___ i __ r..(i..(i.. ))):
rev_str ''
s__ ''.j..(e ___ e __ i.. ).l.. __ e.islower
#here iam storing the string in the reverse form
___ j __ r..(l..(s__)-1,-1,-1
rev_str += s__[j]
#once the reverse string is stored then i'm comparing it with the original string
__ rev_str __ s__:
print('Y',' ')
____
print('N',' ') |
cce1bccf64a44bd76dba1e146f9de2de03f49171 | syurskyi/Python_Topics | /125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 12 Regex/all_word_contain_5_chracters_solution.py | 368 | 3.6875 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
# Write a Python program to find all five characters long word in a string.
# Input
# 'The quick brown fox jumps over the lazy dog.'
# Output
# ['quick', 'brown', 'jumps']
import re
text = 'The quick brown fox jumps over the lazy dog.'
print(re.findall(r"\b\w{5}\b", text))
|
cb921dc911e9303043b1928211b8573584a79a73 | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/unittest_examples-master/proj/sample_module.py | 244 | 3.90625 | 4 | ___ add2num(a,b
"""This function return sum of 2 numbers
>>> add2num(5,6)
11
>>> add2num(-10.5,3)
-7.5
>>> add2num(8, 'hello')
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
r_ a+b |
c2ed4a564cc754afbee699556ef3b5483dca28ed | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/9_v2/palindrome.py | 1,427 | 4.15625 | 4 | # """A palindrome is a word, phrase, number, or other sequence of characters
# which reads the same backward as forward"""
# _______ __
# _______ u__.r..
# _______ __
#
# TMP __.g.. TMP /tmp
# DICTIONARY __.p...j..? dictionary_m_words.txt
# u__.r...u..
# 'https://bites-data.s3.us-east-2.amazonaws.com/dictionary_m_words.txt',
# ?
#
#
#
# ___ load_dictionary
# """Load dictionary (sample) and return as generator (done)"""
# w__ o.. ? __ f
# r.. word.l...s.. ___ ? __ ?.r..
#
#
# ___ is_palindrome word
# """Return if word is palindrome, 'madam' would be one.
# Case insensitive, so Madam is valid too.
# It should work for phrases too so strip all but alphanumeric chars.
# So "No 'x' in 'Nixon'" should pass (see tests for more)"""
#
#
#
# word __.s.. _ \W '' w.. .l..
#
# low,high 0,l.. ? - 1
#
#
# w.... ? < ?
# __ ? l.. !_ ? h..
# r.. F..
#
# l.. +_ 1
# h.. -_ 1
#
# r.. T..
#
#
#
# ___ get_longest_palindrome words_ N..
# """Given a list of words return the longest palindrome
# If called without argument use the load_dictionary helper
# to populate the words list"""
#
# __ n.. ?
# words ?
#
# longest_length f__ "-inf"
# longest N..
# ___ word __ ?
# __ i.. ?
# __ l.. ? > ?
# l.. l. ?
# l.. w..
#
# r.. ?
#
|
51d6368c8a9162ae4c13b7f6d07ee40bbe120e9b | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/MergeSortedArray.py | 4,069 | 4.15625 | 4 | """
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
合并两个排序过的整数数组。
要求在nums1中做修改。
测试用例:
https://leetcode.com/problems/merge-sorted-array/description/
第一版:
思路与merge two sorted list 一致...
passed 但是效率较低。
第二版:
直接以倒序的方式,从尾到头判断,这样不需要额外的空间,列表,效率也自然要高。
passed,但还不是最高的。
第三版:
通过的解法中有一种非常聪明的:
由于本身是在nums1中操作,基于 merge two sorted list 的思想中的:
如果有一方结束了那么就把另一方直接合并过去。
但我们是在nums1中做修改,所以可以修改下判断规则:
不再以整个m+n作为while的依据而是m和n都不为0。
若m为0,那么合并剩余的n到nums1中,
若n为0,则无需做任何动作,因为本来就是nums1.。
"""
c.. Solution o..
# 第一版:
# def merge(self, nums1, m, nums2, n):
# """
# :type nums1: List[int]
# :type m: int
# :type nums2: List[int]
# :type n: int
# :rtype: void Do not return anything, modify nums1 in-place instead.
# """
# nums3 = nums1[:m]
# nums1_index = 0
# nums2_index = 0
# nums3_index = 0
# mn = m+n
# length_nums3 = len(nums3)
# length_nums2 = len(nums2)
# while nums1_index < mn:
# if nums3_index == length_nums3:
# for i in nums2[nums2_index:]:
# nums1[nums1_index] = i
# nums1_index += 1
# break
# if nums2_index == length_nums2:
# for i in nums3[nums3_index:]:
# nums1[nums1_index] = i
# nums1_index += 1
# break
# if nums3[nums3_index] < nums2[nums2_index]:
# nums1[nums1_index] = nums3[nums3_index]
# nums3_index += 1
# else:
# nums1[nums1_index] = nums2[nums2_index]
# nums2_index += 1
# nums1_index += 1
# 第二版:
# def merge(self, nums1, m, nums2, n):
# """
# :type nums1: List[int]
# :type m: int
# :type nums2: List[int]
# :type n: int
# :rtype: void Do not return anything, modify nums1 in-place instead.
# """
# mn = m + n - 1
# while mn >= 0:
# if m == 0:
# for i in nums2[:n][::-1]:
# nums1[mn] = i
# mn -= 1
# break
# if n == 0:
# for i in nums1[:m][::-1]:
# nums1[mn] = i
# mn -= 1
# break
# if nums1[m-1] > nums2[n-1]:
# nums1[mn] = nums1[m-1]
# m -= 1
# else:
# nums1[mn] = nums2[n-1]
# n -= 1
# mn -= 1
# 第三版
___ merge nums1, m, nums2, n
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
mn = m + n - 1
_____ m > 0 a.. n > 0:
__ nums1[m-1] > nums2[n-1]:
nums1[mn] = nums1[m-1]
m -= 1
____
nums1[mn] = nums2[n-1]
n -= 1
mn -= 1
__ n > 0:
nums1[:n] = nums2[:n]
|
6caab5b5e7ff9b156330d7302bf1567b16c8ea59 | syurskyi/Python_Topics | /125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 7 Dictionary/check_key_exist_solution.py | 816 | 4 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
# ---------------------------------------------------------------
# python best courses https://courses.tanpham.org/
# ---------------------------------------------------------------
# Check if a given key already exists in a dictionary
# input
# d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
# is_key_present(5)
# is_key_present(9)
# output
# Key is present in the dictionary
# Key is not present in the dictionary
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)
|
0586551822d2c81be6473a3604a06b80f558c254 | syurskyi/Python_Topics | /120_design_patterns/016_iterator/examples/Iterator_003.py | 1,326 | 4.375 | 4 | #!/usr/bin/env python
# Written by: DGC
#==============================================================================
class ReverseIterator(object):
"""
Iterates the object given to it in reverse so it shows the difference.
"""
def __init__(self, iterable_object):
self.list = iterable_object
# start at the end of the iterable_object
self.index = len(iterable_object)
def __iter__(self):
# return an iterator
return self
def next(self):
""" Return the list backwards so it's noticeably different."""
if (self.index == 0):
# the list is over, raise a stop index exception
raise StopIteration
self.index = self.index - 1
return self.list[self.index]
#==============================================================================
class Days(object):
def __init__(self):
self.days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
]
def reverse_iter(self):
return ReverseIterator(self.days)
#==============================================================================
if (__name__ == "__main__"):
days = Days()
for day in days.reverse_iter():
print(day)
|
c2821b1b84aa545178d219f8c8f21b7ab1aefd9d | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/030_movie_data_analysis/save4_nopass.py | 1,812 | 3.6875 | 4 | import csv
from collections import defaultdict, namedtuple
import os
from u__.r.. import u..
BASE_URL = 'https://bites-data.s3.us-east-2.amazonaws.com/'
TMP = '/tmp'
fname = 'movie_metadata.csv'
remote = os.path.join(BASE_URL, fname)
local = os.path.join(TMP, fname)
u..(remote, local)
MOVIE_DATA = local
MIN_MOVIES = 4
MIN_YEAR = 1960
Movie = namedtuple('Movie', 'title year score')
def get_movies_by_director():
"""Extracts all movies from csv and stores them in a dict,
where keys are directors, and values are a list of movies,
use the defined Movie namedtuple"""
d = defaultdict(list)
full_list = []
with open(MOVIE_DATA, newline='') as file:
reader = csv.DictReader(file)
for row in reader:
year = row['title_year']
if year != '' and int(year) > 1960:
full_list.append([row['director_name'],
row['movie_title'].strip(),
int(row['title_year']),
float(row['imdb_score'])])
for name, movie, year, score in full_list:
d[name].append(Movie(title=movie, year=year, score=score))
return d
def calc_mean_score(movies):
"""Helper method to calculate mean of list of Movie namedtuples,
round the mean to 1 decimal place"""
scores = [movie.score for movie in movies]
return round(sum(scores) / len(scores), 1)
def get_average_scores(directors):
"""Iterate through the directors dict (returned by get_movies_by_director),
return a list of tuples (director, average_score) ordered by highest
score in descending order. Only take directors into account
with >= MIN_MOVIES"""
return [(k, calc_mean_score(v)) for k, v in directors.items() if len(v) >= MIN_MOVIES] |
8135e47c83f7b497b5b96684ea6dbf1328eddc6f | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/100_Python_Exercises_Evaluate_and_Improve_Your_Skills/Exercise 98 - Desktop GUI.py | 806 | 4.03125 | 4 | # #Create a program that asks the user to submit text through a GUI
#
# ____ tkinter ______ *
#
# window _ Tk()
#
# file _ o..("user_gui.txt", "a+")
#
# ___ add
# file.w..(user_value.g..() + "\n")
# entry.delete(0, END)
#
# ___ save
# global file
# file.c..
# file _ o..("user_gui.txt", "a+")
#
# ___ close
# file.close
# window.destroy()
#
# user_value _ StringVar()
# entry _ Entry(window, textvariable_user_value)
# entry.grid(row_0, column_0)
#
# button_add _ Button(window, text_"Add line", command_add)
# button_add.grid(row_0, column_1)
#
# button_save _ Button(window, text_"Save changes", command_save)
# button_save.grid(row_0, column_2)
#
# button_close _ Button(window, text_"Save and Close", command_close)
# button_close.grid(row_0,column_3)
#
# window.mainloop()
|
d30db8111d0afde19ad5f64be9cfeb27beb7393e | syurskyi/Python_Topics | /010_strings/examples/Learning Python/005_Basic Operations.py | 929 | 4.09375 | 4 | print('#' * 52 + ' Length: number of items')
print(len('abc')) # Length: number of items
print('#' * 52 + ' Concatenation: a new string')
print('abc' + 'def') # Concatenation: a new string
print('#' * 52 + ' Repetition: like "Ni!" + "Ni!" + ...')
print('Ni!' * 4) # Repetition: like "Ni!" + "Ni!" + ...
print('#' * 52 + ' 80 dashes, the hard way')
print('------- ...more... ---') # 80 dashes, the hard way
print('#' * 52 + ' 80 dashes, the easy way')
print('-' * 80) # 80 dashes, the easy way
print('#' * 52 + ' Step through items, print each (3.X form)')
myjob = "hacker"
for c in myjob:
print(c, end=' ') # Step through items, print each (3.X form)
print()
print('#' * 52 + ' Found')
print("k" in myjob) # Found
print('#' * 52 + ' Not found')
print("z" in myjob) # Not found
print('#' * 52 + ' Substring search, no position returned')
print('spam' in 'abcspamdef') # Substring search, no position returned
|
c290512c87d484d91c2e31f4bf02a5a0578629c3 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+18 How to convert from base 2 to 9.py | 223 | 3.890625 | 4 | num1 i..(input("Insert number to convert: "))
base_num i..(input("Choose the base(2-9): "))
__ n..(2< base_num <9):
quit()
num2 ''
w___ num1>0:
num2 s..(num1%base_num) + num2
num1 // base_num
print(num2) |
b0492ca55a573aa06a266384bafc66cc425fc948 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/advanced/63/traffic.py | 782 | 3.828125 | 4 | from collections import namedtuple
from itertools import cycle, islice
from time import sleep
State = namedtuple('State', 'color command timeout')
def traffic_light():
"""Returns an itertools.cycle iterator that
when iterated over returns State namedtuples
as shown in the Bite's description"""
colors = ('red','green','amber')
commands = ('Stop','Go','Caution')
timeouts = (2,2,0.5)
states = [State(color,command,timeout) for color,command,timeout in zip(colors,commands,timeouts)]
return cycle(states)
if __name__ == '__main__':
# print a sample of 10 states if run as standalone program
for state in islice(traffic_light(), 10):
print(f'{state.command}! The light is {state.color}')
sleep(state.timeout)
|
9c9a0bf6f5564a308d1ef43be06858a3bd0380b9 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/346_Moving_Average_from_Data_Stream.py | 788 | 3.703125 | 4 | c_ MovingAverage o..
___ - size
"""
Initialize your data structure here.
:type size: int
"""
size = size
curr_range = # list
___ next val
"""
:type val: int
:rtype: float
"""
__ l.. curr_range) __ size:
curr_range.pop(0)
curr_range.a.. val)
r_ s..(curr_range) * 1.0 / l.. curr_range)
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)
# def __init__(self, size):
# """
# Initialize your data structure here.
# :type size: int
# """
# self.next = lambda v, q=collections.deque((), size): q.append(v) or 1.*sum(q) / len(q) |
9859f5948489eebbab89c8db62e707fd77f0d5fb | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/_templates/Python_OOP_Object_Oriented_Programming/Section 17/Special-Methods-Code/9 - __bool__().py | 418 | 3.53125 | 4 | class SavingsAccount:
def __init__(self, owner, acc_number):
self.owner = owner
self._acc_number = acc_number
# The balance starts at 0
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance - amount >= 0:
self.balance -= amount
def __bool__(self):
return self.balance > 0
|
7acf2a5f96bd85fb45d1fb6ed4dc0f683f79eeaf | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/911 Online Election.py | 2,019 | 3.609375 | 4 | #!/usr/bin/python3
"""
In an election, the i-th vote was cast for persons[i] at time times[i].
Now, we would like to implement the following query function:
TopVotedCandidate.q(int t) will return the number of the person that was leading
the election at time t.
Votes cast at time t will count towards our query. In the case of a tie, the
most recent vote (among tied candidates) wins.
Example 1:
Input: ["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1,0,0,1,0],
[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]]
Output: [null,0,1,1,0,0,1]
Explanation:
At time 3, the votes are [0], and 0 is leading.
At time 12, the votes are [0,1,1], and 1 is leading.
At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the
most recent vote.)
This continues for 3 more queries at time 15, 24, and 8.
Note:
1 <= persons.length = times.length <= 5000
0 <= persons[i] <= persons.length
times is a strictly increasing array with all elements in [0, 10^9].
TopVotedCandidate.q is called at most 10000 times per test case.
TopVotedCandidate.q(int t) is always called with t >= times[0].
"""
____ t___ _______ L..
____ c.. _______ d..
_______ b__
c_ TopVotedCandidate:
___ - , persons: L..[i..], times: L..[i..]
"""
Running top vote
Need to maintain list
but time is too large to enumerate. Cannot have direct access, then
query is binary search
"""
maxes # list # [(t, i)] at time t
counter d.. i..
tp s..(z..(times, persons
___ t, p __ tp:
counter[p] += 1
__ n.. maxes o. counter[maxes[-1][1]] <_ counter[p]:
maxes.a..((t, p
___ q t: i.. __ i..
i b__.b__(maxes, (t, 0
# equal
__ i < l..(maxes) a.. maxes[i][0] __ t:
r.. maxes[i][1]
# smaller
i -_ 1
r.. maxes[i][1]
# Your TopVotedCandidate object will be instantiated and called as such:
# obj = TopVotedCandidate(persons, times)
# param_1 = obj.q(t)
|
baa6b0b8905dfc9e832125196f3503f271557273 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/SlidingWindowMaximum.py | 2,656 | 4.03125 | 4 | """
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
这个我的思路是:
1. 先把前 k 个数取出来,然后排序一组,不排序一组。
2. 排序的一组作为查找使用。 不排序的一组作为删除增加会用。
3. 这里也可以使用堆代替排序,红黑树应该最好不过了。
4. 这里使用排序过的列表是为了能够使用二分法,从而达到 log n 级别的查找和后续添加。
但同时因为即使在 log n级别查找到要添加删除的位置,进行列表的添加和删除仍然是一个 O(n) 级别的事情...
所以使用堆或者红黑树是最好的,添加和删除都是 log n 级别的。
5. sorted list 主要是进行获取最大与删除冗余,这里使用二分法来删除冗余。
6. unsorted list 用于知道要删除和添加的都是哪一个。
beat 31% 176ms.
测试地址:
https://leetcode.com/problems/sliding-window-maximum/description/
"""
from collections import deque
import bisect
c.. Solution o..
___ find_bi nums, target
lo = 0
hi = l..(nums)
_____ lo < hi:
mid = (lo + hi) // 2
__ nums[mid] __ target:
r_ mid
__ nums[mid] < target:
lo = mid + 1
____
hi = mid
___ maxSlidingWindow nums, k
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
__ n.. nums:
r_ []
x = nums[:k]
y = s..(x)
x = deque(x)
maxes = m..(x)
result = [maxes]
___ i __ nums[k:]:
pop = x.popleft()
x.a.. i)
index = self.find_bi(y, pop)
y.pop(index)
bisect.insort_left(y, i)
result.a.. y[-1])
r_ result
|
42623f87735e09a8941af14ec047671e235218ec | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/721 Accounts Merge.py | 3,528 | 4.59375 | 5 | #!/usr/bin/python3
"""
Given a list accounts, each element accounts[i] is a list of strings, where the
first element accounts[i][0] is a name, and the rest of the elements are emails
representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to
the same person if there is some email that is common to both accounts. Note
that even if two accounts have the same name, they may belong to different
people as people could have the same name. A person can have any number of
accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the
first element of each account is the name, and the rest of the elements are
emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input:
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John",
"johnnybravo@mail.com"], ["John", "johnsmith@mail.com",
"john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [["John", 'john00@mail.com', 'john_newyork@mail.com',
'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary",
"mary@mail.com"]]
Explanation:
The first and third John's are the same person as they have the common email
"johnsmith@mail.com".
The second John and Mary are different people as none of their email addresses
are used by other accounts.
We could return these lists in any order, for example the answer [['Mary',
'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']]
would still be accepted.
Note:
The length of accounts will be in the range [1, 1000].
The length of accounts[i] will be in the range [1, 10].
The length of accounts[i][j] will be in the range [1, 30].
"""
____ c.. _______ d..
c_ Solution:
___ accountsMerge accounts: L..[L..[s..]]) __ L..[L..[s..]]:
"""
merge has to be dfs
account id
"""
email_to_ids d..(s..)
___ i, v __ e..(accounts
___ email __ v 1|
email_to_ids[email].add(i)
# graph nodes by ids, edges by email
visited [F.. ___ _ __ accounts]
ret # list
___ i, v __ e..(accounts
__ n.. visited[i]:
emails s..()
dfs(i, accounts, email_to_ids, emails, visited)
ret.a..([v[0]] + s..(emails
r.. ret
___ dfs i, accounts, email_to_ids, emails, visited
visited[i] T..
___ email __ accounts[i] 1|
emails.add(email)
___ nbr __ email_to_ids[email]:
__ n.. visited[nbr]:
dfs(nbr, accounts, email_to_ids, emails, visited)
___ accountsMerge_error accounts: L..[L..[s..]]) __ L..[L..[s..]]:
"""
data structure
map: email -> id, if exist mapping, then merge
map: id -> [email]
mistake: not dfs, search on the first level
"""
email_id # dict
id_emails d.. l..
___ i __ r..(l..(accounts:
person N..
___ email __ accounts[i] 1|
__ email __ email_id:
person email_id[email]
_____
___ email __ accounts[i] 1|
__ person __ N..
person i
email_id[email] person
id_emails[person].a..(email)
____ email n.. __ email_id:
email_id[email] person
id_emails[person].a..(email)
ret # list
___ k, v __ id_emails.i..
ret.a..([accounts[k][0]] + s..(v
r.. ret
|
d42ee9dfb7fbeb18b1efa91d44196ed24445d9dd | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/Triangle Area.py | 529 | 3.734375 | 4 | _______ m__
___ i __ r..(i..(i.. ))):
x1,y1,x2,y2,x3,y3 l.. m..(i..,i.. ).s..()))
#distance formula
a m__.sqrt((x2-x1)**2 + (y2-y1)**2)
b m__.sqrt((x3-x1)**2 + (y3-y1)**2)
c m__.sqrt((x3-x2)**2 + (y3-y2)**2)
#Heron's formula s = 1/2(a+b+c)
s 0.5 * (a + b + c)
s1= a..(s-a)
s2 a..(s-b)
s3 =a..(s-c)
area s * s1 * s2 * s3
__ (area - i..(area > 0.5:
area += 0.5
area i..(area)
____
area i..(area)
area m__.sqrt(area)
print(area,end=' ') |
a4491e5f9eec461e4263797ff2b83265f9a1e530 | syurskyi/Python_Topics | /070_oop/008_metaprogramming/examples/Interface/Implementing an Interface in Python/a_007_Using Abstract Method Declaration.py | 3,682 | 4.25 | 4 | # Using Abstract Method Declaration
# An abstract method is a method that's declared by the Python interface, but it may not have a useful implementation.
# The abstract method must be overridden by the concrete class that implements the interface in question.
#
# To create abstract methods in Python, you add the @abc.abstractmethod decorator to the interface's methods.
# In the next example, you update the FormalParserInterface to include the abstract methods .load_data_source()
# and .extract_text():
class FormalParserInterface(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
return (hasattr(subclass, 'load_data_source') and
callable(subclass.load_data_source) and
hasattr(subclass, 'extract_text') and
callable(subclass.extract_text) or
NotImplemented)
@abc.abstractmethod
def load_data_source(self, path: str, file_name: str):
"""Load in the data set"""
raise NotImplementedError
@abc.abstractmethod
def extract_text(self, full_file_path: str):
"""Extract text from the data set"""
raise NotImplementedError
class PdfParserNew(FormalParserInterface):
"""Extract text from a PDF."""
def load_data_source(self, path: str, file_name: str) -> str:
"""Overrides FormalParserInterface.load_data_source()"""
pass
def extract_text(self, full_file_path: str) -> dict:
"""Overrides FormalParserInterface.extract_text()"""
pass
class EmlParserNew(FormalParserInterface):
"""Extract text from an email."""
def load_data_source(self, path: str, file_name: str) -> str:
"""Overrides FormalParserInterface.load_data_source()"""
pass
def extract_text_from_email(self, full_file_path: str) -> dict:
"""A method defined only in EmlParser.
Does not override FormalParserInterface.extract_text()
"""
pass
# In the above example, you've finally created a formal interface that will raise errors when the abstract
# methods aren't overridden. The PdfParserNew instance, pdf_parser, won't raise any errors, as PdfParserNew
# is correctly overriding the FormalParserInterface abstract methods. However, EmlParserNew will raise an error:
pdf_parser = PdfParserNew()
eml_parser = EmlParserNew()
# Traceback (most recent call last):
# File "real_python_interfaces.py", line 53, in <module>
# eml_interface = EmlParserNew()
# TypeError: Can't instantiate abstract class EmlParserNew with abstract methods extract_text
# As you can see, the traceback message tells you that you haven't overridden all the abstract methods.
# This is the behavior you expect when building a formal Python interface.
# Conclusion
# Python offers great flexibility when you're creating interfaces. An informal Python interface is useful
# for small projects where you're less likely to get confused as to what the return types of the methods are.
# As a project grows, the need for a formal Python interface becomes more important as it becomes more difficult
# to infer return types. This ensures that the concrete class, which implements the interface, overwrites
# the abstract methods.
#
# Now you can:
#
# Understand how interfaces work and the caveats of creating a Python interface
# Understand the usefulness of interfaces in a dynamic language like Python
# Implement formal and informal interfaces in Python
# Compare Python interfaces to those in languages like Java, C++, and Go
# Now that you've become familiar with how to create a Python interface, add a Python interface to
# your next project to see its usefulness in action!
|
39c485baf4869ac0756987e22ea9013dbfe661f3 | syurskyi/Python_Topics | /110_concurrency_parallelism/_examples/Gitlab/_qt/PYQT_QThread/Thread_Sync.py | 160 | 4 | 4 | def square_numbers(nums):
result = []
for i in nums:
result.append(i*i)
my_nums = square_numbers(1,2,3,4,5)
for num in my_nums:
print(num) |
14e23ea3e3de89813068797bce4742c01e62044d | syurskyi/Python_Topics | /045_functions/008_built_in_functions/reduce/_exercises/templates/002_Using Operator Functions.py | 829 | 4.28125 | 4 | # # python code to demonstrate working of reduce()
# # using operator functions
#
# # importing functools for reduce()
# ____ f..
#
# # importing operator for operator functions
# ____ o..
#
# # initializing list
# lis _ 1 3 5 6 2
#
# # using reduce to compute sum of list
# # using operator functions
# print ("The sum of the list elements is : " e.._""
# print f____.r____ o____.a.. ?
#
# # using reduce to compute product
# # using operator functions
# print "The product of list elements is : "; e.._""
# print f___.r___ o____.m__ ?
#
# # using reduce to concatenate string
# print "The concatenated product is : "; e.._""
# print f____.r_____ o____.a.. |"geeks" "for" "geeks"
#
# # Output
# #
# # The sum of the list elements is : 17
# # The product of list elements is : 180
# # The concatenated product is : geeksforgeeks |
61fa0a364f6a3dea96e0d5b9747203877d72f4f1 | syurskyi/Python_Topics | /115_testing/examples/The_Ultimate_Python_Unit_Testing_Course/Section 6 Coding Challenge #2 - Testing Classes/tests/test_chanllege.py | 1,981 | 3.5625 | 4 | import unittest
from challenge import Car
class EasyTestCase(unittest.TestCase):
def setUp(self):
self.car = Car()
self.car.start_car()
def test_easy_input(self):
self.car.add_speed()
self.car.add_speed()
self.car.add_speed()
self.car.add_speed()
self.assertEqual(self.car.current_speed(), 20)
def test_easy_input_two(self):
self.car.add_speed()
self.car.add_speed()
self.car.stop()
self.assertEqual(self.car.current_speed(), 0)
def tearDown(self):
self.car.stop()
self.car.turn_off_car()
self.car = None
class MediumTestCase(unittest.TestCase):
def setUp(self):
self.car = Car()
self.car.start_car()
def test_medium_input(self):
with self.assertRaises(Exception):
self.car.start_car()
def test_medium_input_two(self):
self.car.remove_speed()
self.car.remove_speed()
self.car.remove_speed()
self.car.remove_speed()
self.assertEqual(self.car.current_speed(), 0)
def tearDown(self):
self.car.stop()
self.car.turn_off_car()
self.car = None
class HardTestCase(unittest.TestCase):
def setUp(self):
self.car = Car()
self.car.start_car()
def test_hard_input(self):
with self.assertRaises(Exception):
self.car.add_speed()
self.car.add_speed()
self.car.add_speed()
self.car.add_speed()
self.car.turn_off_car()
def test_hard_input_two(self):
self.car.add_speed()
self.car.add_speed()
self.car.stop()
self.assertEqual(self.car.current_speed(), 0)
self.car.stop()
self.car.stop()
self.assertEqual(self.car.current_speed(), 0)
def tearDown(self):
self.car.stop()
self.car.turn_off_car()
self.car = None
if __name__ == '__main__':
unittest.main() |
680e9aad720a7ad02ffe15251087b91ddf3889cd | syurskyi/Python_Topics | /125_algorithms/012_backtracking/_exercises/templates/Cracking Coding Interviews - Mastering Algorithms/permutations.py | 539 | 3.5625 | 4 | # ______ co..
# # Given a collection of distinct integers, return all possible permutations.
#
# # Example:
#
# # Input: [1,2,3]
# # Output:
# # [
# # [1,2,3],
# # [1,3,2],
# # [2,1,3],
# # [2,3,1],
# # [3,1,2],
# # [3,2,1]
# # ]
#
# ___ permutation_recursive nums path
# __ le. ? __ 0
# r_ |?
#
# output _ # list
#
# ___ i __ ra.. le. ?
# copy_path _ co__.d_c.. ?
# ?.ap.. n..|?
# permutations _ ? n..|:? + n..|? + 1: ?
#
# o.. +_ ?
#
# r_ ?
#
# ___ permute nums
# r_ ? ? ||
#
# print(?([1, 2, 3, 4, 5, 6]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.