blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
27a2ee626b34d1662a5d899ddbb760d69379a25f | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/LinkedList/328_OddEvenLinkedList.py | 815 | 3.9375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
if not head or not head.next:
... |
42cb8106d5e3ebea7ac9d1a87cdf1de4a0e93ebd | syurskyi/Python_Topics | /085_regular_expressions/_exercises/templates/Python 3 Most Nessesary/7.5. Snap to start and end of line.py | 9,734 | 3.625 | 4 | # # -*- coding: utf-8 -*-
#
# # Кроме того, можно указать привязку только к началу или только к концу строки
# _______ __ # Подключаем модуль
# p _ __.c.. _ 0-9 1? 2? __.3?) # 1.One or more occurrences | 2.Ends with
# # 3.Makes a period (dot) match a... |
e6729c7cfc3abb4f301d1f09795e975fe7505604 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/DataAnalysis/90/test.py | 207 | 3.53125 | 4 | from collections import defaultdict
from typing import Counter
count = defaultdict(Counter)
count['khoo']['a'] = 1
count['khoo']['b'] = 2
#count['chuan'] += 1
#print(count['chuan'])
print(count['swee']) |
e238bcd4bc432abb27b310e700b6a1bb2c43567a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/773 Sliding Puzzle.py | 3,369 | 4.0625 | 4 | #!/usr/bin/python3
"""
On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and
an empty square represented by 0.
A move consists of choosing 0 and a 4-directionally adjacent number and swapping
it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given a puzzle b... |
58cf2e0e3efb0f44bce7b4ef7c203fc27a443842 | syurskyi/Python_Topics | /095_os_and_sys/examples/realpython/005_Listing All Files in a Directory.py | 2,565 | 4.375 | 4 | # This section will show you how to print out the names of files in a directory using os.listdir(), os.scandir(),
# and pathlib.Path(). To filter out directories and only list files from a directory listing produced by os.listdir(),
# use os.path:
#
import os
# List all files in a directory using os.listdir
basepath =... |
29313678d25756a660eef4638259ee18459be08c | syurskyi/Python_Topics | /125_algorithms/_examples/Practice_Python_by_Solving_100_Python_Problems/77.py | 219 | 4.125 | 4 | #Create a script that gets user's age and returns year of birth
from datetime import datetime
age = int(input("What's your age? "))
year_birth = datetime.now().year - age
print("You were born back in %s" % year_birth)
|
f2e58ef8c9a85492f27cb03127880a01715eff43 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id026-GCD_and_LCM.py | 438 | 3.515625 | 4 | ___ lcm(a,b # Least Common Multiple
r..(a * b / gcd(a, b
___ gcd(a,b # Greatest Common Divisor
w.... b:
a, b b, a % b
r.. a
___ findDivisors(pairs
answer # list
___ pair __ r..(pairs
a,b raw_input().s..
a,b i..(a), i... |
27ad68ad48e6428b183b837ea941b7673cc19675 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/117 Populating Next Right Pointers in Each Node II.py | 1,210 | 3.703125 | 4 | """
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 ... |
cb8edc742b8442363378710ba0e91d7480ce6ca1 | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Auto_Spec.py | 1,771 | 3.53125 | 4 | # Python Unittest
# unittest.mock � mock object library
# unittest.mock is a library for testing in Python.
# It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
# unittest.mock provides a core Mock class removing the need to create a host of stu... |
08eff574578ac91abce96916bc188833ac922619 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-3-word-values.py | 2,365 | 4.3125 | 4 | """
Calculate the dictionary word that would have the most value in Scrabble.
There are 3 tasks to complete for this Bite:
First write a function to read in the dictionary.txt file (= DICTIONARY constant),
returning a list of words (note that the words are separated by new lines).
Second write a function that receiv... |
b7a799605e9f50f6ab9f363daaf7a18ecae80960 | syurskyi/Python_Topics | /060_context_managers/examples/102. Additional Uses - Coding.py | 10,230 | 4.4375 | 4 | print('#' * 52 + ' ### Additional Uses')
# Additional Uses
# Remember what I said in the last lecture about some common patterns we can implement with context managers:
# Open - Close
# Change - Reset
# Start - Stop
# The open file context manager is an example of the Open - Close pattern. But we have othe... |
4ee061f9b2d7ba13ef1d49aa115f9a2e632a2a65 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/1018 Binary Prefix Divisible By 5.py | 1,101 | 4 | 4 | #!/usr/bin/python3
"""
Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i]
interpreted as a binary number (from most-significant-bit to
least-significant-bit.)
Return a list of booleans answer, where answer[i] is true if and only if N_i is
divisible by 5.
Example 1:
Input: [0,1,1]
Output... |
ba236317ae547620e93e529be89885e16c7a39ff | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/Datetimes/73/timezones.py | 734 | 3.671875 | 4 | import pytz
from datetime import datetime
MEETING_HOURS = range(6, 23) # meet from 6 - 22 max
TIMEZONES = set(pytz.all_timezones)
def within_schedule(utc, *timezones):
"""Receive a utc datetime and one or more timezones and check if
they are all within schedule (MEETING_HOURS)"""
utc = pytz.utc.loca... |
ac8855cb9b0969981609182736b8de8d4aee60ee | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id018-Square_Root.py | 435 | 3.609375 | 4 | ___ sqRoot(numbers
answer # list
___ number __ r.. ?
data raw_input().s..
value,runs i..(data 0,i..(data[1])
root 1.00
__ root __ 0:
print(1)
____
___ x __ r..(runs
division value / root
a..(root - division)... |
30ddadd1a69acb89bca5e32d8b221e1a91c09a3a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/504 Base 7.py | 722 | 4.09375 | 4 | #!/usr/bin/python3
"""
Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
"""
c_ Solution:
___ convertToBase7 num
"""
simplfied for negative number
:type num: ... |
70bdb3d9d47e898a1c9258f312214f2bd9a75f31 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/119_PascalTriangleII.py | 1,006 | 3.828125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
rowIndex += 1
row_nums = [0 for i in range(rowIndex)]
row_nums[0] = 1
# Use the post part of pre row to u... |
14cbcea8d1beff63273b32a89811b85c8e5e5a3e | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Python_OOP_Object_Oriented_Programming/Section 15/project/deck.py | 1,350 | 3.9375 | 4 | import random
from card import Card
class Deck:
# The four types of suits for the card.
suits = ["Spades", "Clubs", "Diamonds", "Hearts"]
def __init__(self):
# The deck starts with an empty list of cards.
# It is protected and it doesn't have a getter
# setter because they are... |
d2630a69f253c4a3f1ffee2df7647db7e68b46eb | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Array/164_MaximumGap.py | 945 | 3.5625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
c.. Solution o..
"""
Radix sort, you can see the explanation follow the links.
https://www.cs.usfca.edu/~galles/visualization/RadixSort.html
And here is a java solution in leetcode's discuss:
https://leetcode.com/discuss/53636/radix-sort-solution-in-j... |
f9fb672650bbe3689cdaa4cf085865635f4a54b2 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/480 Sliding Window Median.py | 4,006 | 4.28125 | 4 | #!/usr/bin/python3
"""
Median is the middle value in an ordered integer list. If the size of the list
is even, there is no middle value. So the median is the mean of the two middle
value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Given an array nums, there is a sliding window of size... |
dccee39c84fc8a8b20b0cb56c22b64111a294a7d | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/topics/intro/intro-bite102-infinite-loop-input-continue-break.py | 1,151 | 4.15625 | 4 | VALID_COLORS = ['blue', 'yellow', 'red']
def my_print_colors():
"""Ask for color, lowercase it, check if 'quit' is entered, if so print
'bye' and break, next check if given color is in VALID_COLORS, if not,
continue, finally if that check passes, print the color"""
while True:
inp = inpu... |
9294859713e8ecd586fea0bc599290d57c8bcb64 | syurskyi/Python_Topics | /100_databases/003_mongodb/examples/realpython_Introduction to MongoDB and Python/001_Establishing a Connection.py | 4,459 | 4 | 4 | # To establish a connection we’ll use the MongoClient object.
# The first thing that we need to do in order to establish a connection is import the MongoClient class.
# We’ll use this to communicate with the running database instance. Use the following code to do so:
from pymongo import MongoClient
client = MongoClien... |
f252694f5d82de1e74c5b076691bdb9206f88ab3 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/272/strings.py | 949 | 4.0625 | 4 | from typing import List
def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]:
"""
Input: Two sentences - each is a list of words in case insensitive ways.
Output: those common words appearing in both sentences. Capital and lowercase
words are treated as the same word.
... |
1e8a48df594f0922144abcc2efffca5050573d49 | syurskyi/Python_Topics | /070_oop/007_exceptions/examples/GoCongr/001_Processing division by zero.py | 422 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# Processing division by zero
try: # Перехватываем исключения
x = 1 / 0 # Ошибка: деление на 0
except ZeroDivisionError: # Указываем класс исключения
print("Обработали деление на 0")
x = 0
print(x) ... |
9cc244acec4107266c37331c8ae7c7067055e478 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Math/09_PalindromeNumber.py | 506 | 3.859375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def isPalindrome(self, x):
if x < 0:
return False
reversed_x = 0
original_x = x
while x > 0:
reversed_x = reversed_x * 10 + x % 10
x /= 10
return reversed_x == origina... |
297ab8211294239fd5c2fc1f6a9056d4670c88ff | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/Trie.py | 3,833 | 3.90625 | 4 | """
前缀树又叫字典树,该树会覆盖多个相同的字符以形成空间上的优势。
如:
rat 与 rain
r
a
t i
n
最终会形成这样的树。
字典树有多种实现方式,下面直接用了列表(数组)来实现。
测试用例:
https://leetcode.com/problems/implement-trie-prefix-tree/description/
使用Python 中的字典可以直接形成这种树,所以弃用这种方式,用类的思路实现了一下。
"""
c.. TrieNode o..
# __slots__ 考虑到TrieNode会大量创建,使用 __slot__来减少内存的占用。
# 在测试的15个... |
e39c69fb749b5a25bdc0efa116ca5b1645e0ef7e | syurskyi/Python_Topics | /018_dictionaries/examples/dictionary_003.py | 5,009 | 4.0625 | 4 | # Методы для работы со словарями
# keys () - Одинаковые ключи
d1, d2 = {"a": 1, "b": 2}, {"a": 3, "c": 4, "d": 5}
print(d1.keys() & d2.keys())
# {'a'}
# Методы для работы со словарями
# keys () - Уникальные ключи
d1, d2 = {"a": 1, "b": 2}, {"a": 3, "c": 4, "d": 5}
print(d1.keys() ^ d2.keys())
# {'c', 'b', 'd'}
# Ме... |
b7bad63ce92b0c02cb75adfbd722b04af3be1127 | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 93 - SpiralMatrix.py | 1,543 | 4.15625 | 4 | # Spiral Matrix
# Question: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
# For example:
# Given the following matrix:
# [ [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ] ]
# You should return [1,2,3,6,9,8,7,4,5].
# Solutions:
class Solution:
# @param matrix, a... |
e4504b274522db17826e696e8541a6f7f1d83b05 | syurskyi/Python_Topics | /110_concurrency_parallelism/002_threads/_exercises/exercises/Module Threading overview/008 - threading.main_thread.py | 1,350 | 3.5625 | 4 | import threading, time, logging
def worker():
name = threading.current_thread().name
time.sleep(1)
logging.debug(f'Ending {name}')
logging.basicConfig(
level=logging.DEBUG,
format='[%(levelname)s] %(message)s',
)
# использование 'threading.main_thread()'
# получаем экземпляр основного потока
m... |
3e660c161e74fbbb940d1562747d229af9997926 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/002_list_comprehension/_exercises/exercises/002_list_comprehension_template.py | 2,696 | 3.953125 | 4 | # # List Comprehensions A First Detailed Look
#
# L _ 1 2 3 4 5 # List
#
# ___ i __ r... le. L # how to use range to change a list as we step across it
# L|i += 10
#
# printL
#
# L _ x + 10 ___ ? __ L #list comprehension expression
# print ?
#
#
# # List Comprehension Basics
#
# L _ 1 2 3 4 5
#
# ... |
7bf9169ff6beefc28c02ca3594388262c8b3f138 | syurskyi/Python_Topics | /120_design_patterns/013_chain_of_responsibility/examples/Section_13_Chain of Responsibility/exercise.py | 2,189 | 3.515625 | 4 | import unittest
from abc import ABC
from enum import Enum
# creature removal (unsubscription) ignored in this exercise solution
class Creature(ABC):
def __init__(self, game, attack, defense):
self.initial_defense = defense
self.initial_attack = attack
self.game = game
@property
de... |
ddedc104cb1b08f182806cc3623960d34c8c4224 | syurskyi/Python_Topics | /079_high_performance/exercises/template/Writing High Performance Python/item_16.py | 1,475 | 3.609375 | 4 | import logging
from pprint import pprint
from sys import stdout as STDOUT
# Example 1
def index_words(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ' ':
result.append(index + 1)
return result
# Example 2
address = 'Four sc... |
b9078848e7b70ef142ad2c86cc0be0f1e4c83099 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/LinkedList/148_SortList.py | 2,122 | 3.75 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
# @Last Modified time: 2016-09-06 20:03:53
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Merge Sort
c.. Solution o..
___ sortList head
... |
93b461451168835895e44e1235a700d78eac7972 | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python 3 Most Nessesary/13.4.1.Listing 13.13. Expansion of class functionality by impurity.py | 778 | 3.859375 | 4 | class Mixin: # Определяем сам класс-примесь
attr = 0 # Определяем атрибут примеси
def mixin_method(self): # Определяем метод примеси
print("Метод примеси")
class Class1 (Mixin):
def method1(self):
print("Метод класса Class1")
class Cl... |
05c42d3fc3d3e6041d27797b1e6fc2dd6d6c07c4 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/157_v2/accents.py | 430 | 3.921875 | 4 | import unicodedata
def filter_accents(text):
"""Return a sequence of accented characters found in
the passed in lowercased text string
"""
text = text.lower()
result = []
s = unicodedata.normalize('NFD',text).encode("ascii",'ignore').decode('utf-8')
for character_1,character_2 in zi... |
4879c43d50d6386e3de45553d948c1785d3b8361 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/Practical_Python_Programming_Practices/Practice 52. Longest ordered sequence in ascending order NUKE.py | 433 | 3.875 | 4 | ____ r__ _______ r__
num 20
listitem [0]*num
___ i __ r..(num):
listitem[i] i..(r__()*50)
print(listitem)
maxi 1
mylength 1
mycode 0
___ i __ r..(1,num):
__ listitem[i] > listitem[i-1]:
mylength + 1
____:
__ mylength > maxi:
maxi mylength
mycode i
... |
f5487e3f92d7ad320f07be4fb59581ff4e2c5be0 | syurskyi/Python_Topics | /010_strings/_exercises/ITVDN Python Starter 2016/11-string-operations.py | 837 | 3.578125 | 4 | str1 = 'hel'
str2 = 'lo'
result = str1 + str2 # конкатенация строка
print(result)
# форматирование строк
a = 48
b = 73
message1 = '%d + %d = %d' % (a, b, a + b)
print(message1)
message2 = '{} - {} = {}'.format(a, b, a - b)
print(message2)
# индексация строк
s = 'Hello, World!'
# (вернуться в седьмом уроке)
pr... |
712c693e7db9a2438e596103fb89b966e68521d1 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/1022 Sum of Root To Leaf Binary Numbers.py | 1,355 | 3.96875 | 4 | #!/usr/bin/python3
"""
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path
represents a binary number starting with the most significant bit. For example,
if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary,
which is 13.
For all leaves in the tree, consider the numbers... |
2f0bbaccfffd2a6b9611bd515ce4ad87aa2873c7 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/Search2DMatrix.py | 3,025 | 3.953125 | 4 | """
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 1... |
274b44dada6dcbc7ae5424b9c929e6396365dc10 | syurskyi/Python_Topics | /085_regular_expressions/_exercises/templates/Section 34 Regular Expressions/349.Parsing Bytes Exericse SOLUTION.py | 658 | 3.75 | 4 | # # Parsing Bytes Solution
# #
# # My regex looks like this: '\b[10]{8}\b' It consists of eight 1s or 0s, surrounded by word boundaries on either side.
# # Remember a word boundary is either a space or the start/end of a line.
# # I then used findall rather than search, to return a list of all matches. Here's the f... |
7f8d74217b2cbc3a38cc6e89865437c81073b62f | syurskyi/Python_Topics | /018_dictionaries/_exercises/Python 3 Deep Dive (Part 3)/10. Creating Dictionaries - Coding.py | 4,327 | 4.5625 | 5 | # a = {'k1': 100, 'k2': 200}
# print(a)
#
# print h.. 1, 2, 3
#
# # hash([1, 2, 3]) TypeError: unhashable type: 'list'
#
# print('#' * 52 + ' So we can create dictionaries that look like this: ')
#
# a = {('a', 100): ['a', 'b', 'c'], 'key2': {'a': 100, 'b': 200}}
# print(a)
#
# print('#' * 52 + ' Interestingly, functio... |
98c56b89578656d7339dee729ebca6e2fc87b2d0 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/CodeAbbey_Solutions-master/id009-Triangles.py | 518 | 3.59375 | 4 | ___ triangle(calculations
answer # list
___ calculation __ r..(calculations
[a,b,c] raw_input().s..
[a,b,c] i..(a),i..(b),i..(c)
minNum m..(i..(a),i..(b),i..(c
maxNum m..(i..(a),i..(b),i..(c
___ x __ [a,b,c]:
__ i..(x) ! minNum a.. i..(x) ! maxNum:
... |
9b650a0d9be51d84b4ae0da975ad0d44d515bd88 | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 9 Project 4/110. Solution - Part 2.py | 11,592 | 3.734375 | 4 | # %%
'''
### Solution - Part 2
'''
# %%
'''
Here's where we left off in the last video:
'''
# %%
import numbers
import unittest
# %%
class TestIntegerField(unittest.TestCase):
@staticmethod
def create_test_class(min_, max_):
obj = type('TestClass', (), {'age': IntegerField(min_, max_)})
retur... |
2f93eb2caf06c52f626405f769f6f76e151b919b | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/NumberOfIslands.py | 1,740 | 3.96875 | 4 | """
与今日头条的秋招第一题差不多的题:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
000... |
3070b9084f00b2448b6ac064a90ea2bd3e4146ad | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/advanced/31/matmul.py | 1,178 | 3.734375 | 4 | from copy import deepcopy
class Matrix(object):
def __init__(self, values):
self.values = values
@property
def nrows(self):
return len(self.values)
@property
def ncols(self):
return len(self.values[0])
def __matmul__(self,other):
rows_1,cols_1... |
fadffaf739e2355d3c6b270c6f9f140026a81beb | syurskyi/Python_Topics | /110_concurrency_parallelism/002_threads/examples/Module Threading overview/025 - Examples of installing flow barriers.py | 1,468 | 3.609375 | 4 | import threading, time
def worker(barrier):
th_name = threading.current_thread().name
print(f'{th_name} в ожидании барьера с {barrier.n_waiting} другими')
worker_id = barrier.wait()
print(f'{th_name} прохождение барьера {worker_id}')
# число потоков, при использовании
# барьеров оно должно быть пост... |
eb74ec0a560fd5194d36c90b72ff1321bf60f62a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/topics/Datetimes/186/books.py | 1,255 | 3.640625 | 4 | ____ d__ _______ d__
____ d__.p.. _______ p..
# work with a static date for tests, real use = datetime.now()
NOW d__(2019, 3, 17, 16, 28, 42, 966663)
WEEKS_PER_YEAR 52
___ get_number_books_read books_per_year_goal i..
at_date s.. N.. __ i..
"""Based on books_per_year_goal and at_date, ... |
5335830eee81de3bf01a54a70432f593654252a7 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Learning Python/028_008_Namespace Links.py | 782 | 3.515625 | 4 | # ### File: classtree.py
#
# """
# Climb inheritance trees using namespace links,
# displaying higher superclasses with indentation
# """
#
# ___ classtree ___ indent
# print('.' * i... + ___. -n # Print class name here
# ___ supercls i_ ___. -b # Recur to all superclasses
# c.. s.., i..+3 ... |
dd857cdd956437eba2ac2bd9f395c2e5a8eb6f4f | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Python 3 Most Necessary/13.1.Listing 13.1. Creating a class definition.py | 689 | 3.796875 | 4 | # -*- coding: utf-8 -*-
class MyClass:
def __init__(self): # Конструктор
self.x = 10 # Атрибут экземпляра класса
def print_x(self): # self — это ссылка на экземпляр класса
print(self.x) # Выводим значение атрибута
c = MyClass() # Создание экземпляра класса
... |
c5b6f4d3d3de4708ba6f18ebb5923b17b8e4ed63 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/149 Max Points on a Line.py | 4,502 | 3.5 | 4 | """
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
"""
__author__ 'Danyang'
#Definition for a point
c_ Point:
___ - , a=0, b=0
"""
:param a: int
:param b: int
:return:
"""
x a
y b
c_ Solution:
___ maxP... |
ee61d59b5c973aa7e2a71fe4c9b424658c461a7e | syurskyi/Python_Topics | /115_testing/examples/The_Ultimate_Python_Unit_Testing_Course/Section 4 Coding Challenge #1 - Testing Functions/tests/test_chanllege.py | 1,431 | 3.6875 | 4 | import unittest
from challenge import counter
class EasyTestCase(unittest.TestCase):
def test_easy_input(self):
# Todo: make sure that your program returns 2 given the string 'Mo'
self.assertEqual(counter('Mo'), 2)
def test_easy_input_two(self):
# Todo: make sure that your program r... |
831a963bfc1edcc21568b45528a30db38ddd8eb7 | syurskyi/Python_Topics | /060_context_managers/_exercises/100. Not just a Context Manager.py | 2,710 | 3.703125 | 4 | # # Just because our class implements the context manager protocol does not mean it cannot do other things as well!
# # In fact the open function we use to open files can be used with or without a context manager:
#
# print('#' * 52 + ' ### Not Just a Context Manager')
#
# f _ o.. test.txt '_'
# f.w..l.. 'this is a te... |
1dde8cb11156223aecd6a4a81853f4045270155d | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/299_v4/base_converter.py | 780 | 4.34375 | 4 | def digit_map(num):
"""maps numbers greater than a single digit to letters (UPPER)"""
return chr(num + 55) if num > 9 else str(num)
def convert(number: int, base: int = 2) -> str:
"""Converts an integer into any base between 2 and 36 inclusive
Args:
number (int): Integer to convert
bas... |
84e80040d8810125c7e40338d95c3e292e9f0ec5 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+89 How to Raise Exceptions.py | 131 | 3.953125 | 4 | x ['a','b','c','d','e']
y input("Insert a letter: ")
__ y __ x:
print(1)
____:
r.. ValueError("Letter does not exist!")
|
c26969bd41bbf3ee69cd7b2dbfefe18866603861 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Backtracking/52_NQueensII.py | 2,093 | 3.703125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
countNQueens = 0
def totalNQueens(self, n):
self.countNQueens = 0
cols_used = [-1 for i in range(n)]
self.solveNQueens(0, cols_used, n)
return self.countNQueens
def solveNQueens(self, row, cols_used, n... |
3a3600127741a8b4970e5295538eb6b4db2156b8 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/910 Smallest Range II.py | 1,867 | 3.703125 | 4 | #!/usr/bin/python3
"""
Given an array A of integers, for each integer A[i] we need to choose either
x = -K or x = K, and add x to A[i] (only once).
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B and the
minimum value of B.
Example 1:
Input: A = [1], ... |
ebfd4ced041ba4376999eabe481caec712b356f2 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Array/AddTowNumbersII.py | 3,449 | 3.96875 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Fo... |
38a9936f1417ee98bedafae7b7f8d2a23c328c22 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Stack/32_LongestValidParentheses.py | 1,145 | 3.671875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def longestValidParentheses(self, s):
"""
According to:
https://leetcode.com/discuss/7609/my-o-n-solution-using-a-stack
If current character is '(', push its index to the stack.
If current character is ... |
2320ff2a2f62a49a58ed296a3886563432f3132f | syurskyi/Python_Topics | /070_oop/004_inheritance/_exercises/templates/super/Python Super/002_ Single Inheritance.py | 2,396 | 4.28125 | 4 | # # Inheritance is the concept in object-oriented programming in which a class derives (or inherits) attributes
# # and behaviors from another class without needing to implement them again.
#
# # See the following program.
#
# # app.py
#
# c_ Rectangle
# __ - length width
# ? ?
# ? ?
#
# __ ar... |
961312152de7cdc52600dbbce3f98d379605f5a4 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/159/calculator.py | 724 | 4.125 | 4 | # _______ o..
#
# ___ simple_calculator calculation
# """Receives 'calculation' and returns the calculated result,
#
# Examples - input -> output:
# '2 * 3' -> 6
# '2 + 6' -> 8
#
# Support +, -, * and /, use "true" division (so 2/3 is .66
# rather than 0)
#
# Make sure you convert... |
7cd8898e0e3005975525306f1622e0d54d94136b | syurskyi/Python_Topics | /140_gui/pyqt_pyside/examples/PyQt5/Chapter13_Running Python Scripts on Android and iOS/demoMultipleSelection.py | 573 | 3.578125 | 4 | import android
app = android.Android()
app.dialogCreateAlert("Select your food items")
app.dialogSetMultiChoiceItems(['Pizza', 'Burger', 'Hot Dog'])
app.dialogSetPositiveButtonText('Done')
app.dialogShow()
app.dialogGetResponse()
response = app.dialogGetSelectedItems()
print(response)
selectedResult=response[1]
n=len... |
354ed6c7930439d2e79545bf55140158e4b16571 | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Test_Mock_Same_Patch.py | 2,770 | 3.578125 | 4 | # Python Test Mock
# unittest.mock � mock object library
# unittest.mock is a library for testing in Python.
# It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
# unittest.mock provides a core Mock class removing the need to create a host of st... |
ba9e2387988e23705a9539d684650e4bc759fd9d | syurskyi/Python_Topics | /115_testing/examples/The_Ultimate_Python_Unit_Testing_Course/Section 3 Testing Functions/first_project.py | 258 | 4 | 4 | def avg(*list_numbers: float) -> float:
total = 0
for num in list_numbers:
if isinstance(num, (int, float)):
total += num
else:
raise TypeError("Wrong input data. Please make sure that everything is a number. ")
return total / len(list_numbers)
|
262ad1be65d99d0c1f3a8b681e9667ccade6f919 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/284/pascal_triangle.py | 361 | 3.609375 | 4 | from typing import List
def pascal(N: int) -> List[int]:
current_row = [1]
for _ in range(N - 1):
new_row = [1]
for i in range(0,len(current_row) - 1):
new_row.append(current_row[i] + current_row[i +1])
new_row.append(1)
current_row = new_row
... |
c6621220c758d9a85e9ec856d95a1c91a57aa809 | syurskyi/Python_Topics | /120_design_patterns/020_state/examples/8-python-design-patterns-building-more-m8-exercise-files/State/empty.py | 511 | 3.546875 | 4 | from abs_state import AbsState
class Empty(AbsState):
def add_item(self):
self._cart.items += 1
print('You added the first item')
self._cart.state = self._cart.not_empty
def remove_item(self):
print('Your cart is empty! Nothing to remove!!')
def checkout(self):
pr... |
5f905b04ff0f16e20c86b5ec77de3e99deae2a21 | syurskyi/Python_Topics | /110_concurrency_parallelism/002_threads/_exercises/exercises/Module Threading overview/012 - Thread.join.py | 2,064 | 4.0625 | 4 | import threading, time
def worker(i):
n = i + 1
print(f'Запуск потока №{n}')
time.sleep(2)
print(f'Поток №{n} выполнился.')
for i in range(2):
thread = threading.Thread(target=worker, args=(i,))
thread.start()
# если присоединять 'thread.join()' потоки здесь,
# то они будут запускать... |
dc8846f3e74b784dcee36049f2735d7dd2ae3c4d | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/581 Shortest Unsorted Continuous Subarray.py | 2,052 | 4.3125 | 4 | #!/usr/bin/python3
"""
Given an integer array, you need to find one continuous subarray that if you
only sort this subarray in ascending order, then the whole array will be sorted
in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Outp... |
360c3a434eac8d2d88ad21b5c7d798da56172b02 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/802 Find Eventual Safe States.py | 2,256 | 3.828125 | 4 | #!/usr/bin/python3
"""
In a directed graph, we start at some node and every turn, walk along a directed
edge of the graph. If we reach a node that is terminal (that is, it has no
outgoing directed edges), we stop.
Now, say our starting node is eventually safe if and only if we must eventually
walk to a terminal node.... |
ccb13b4be8add167329e354bf2a16f3cc92f08ab | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/605 Can Place Flowers.py | 1,264 | 3.796875 | 4 | #!/usr/bin/python3
"""
Suppose you have a long flowerbed in which some of the plots are planted and
some are not. However, flowers cannot be planted in adjacent plots - they would
compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means
empty and 1 means not em... |
a84e29f50c480a6d7b1968a3005aa42da6080a3a | syurskyi/Python_Topics | /021_module_collection/chainmap/_exercises/exercises/chainmap_001_template.py | 9,849 | 4 | 4 | # # Remember the chain function i_ the itertools module? That allowed us to chain multiple iterables together to look like
# # a single iterable.
# #
# # The C... i_ the collections module is somewhat similar - it allows us to chain multiple dictionaries
# # (mapping types more generally) so it looks like a single mapp... |
7b5a0849ccdf86762859091fc794e746027acab7 | syurskyi/Python_Topics | /045_functions/008_built_in_functions/zip/examples/005_Passing n Arguments.py | 307 | 3.90625 | 4 | numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
zipped # Holds an iterator object
# <zip object at 0x7fa4831153c8>
type(zipped)
# <class 'zip'>
list(zipped)
# [(1, 'a'), (2, 'b'), (3, 'c')]
s1 = {2, 3, 1}
s2 = {'b', 'a', 'c'}
list(zip(s1, s2))
# [(1, 'a'), (2, 'c'), (3, 'b')] |
81165ad590797c9cff487e643ab10c45e3cda4ad | syurskyi/Python_Topics | /115_testing/examples/ITVDN_Python_Advanced/007_Модульное тестирование/007_Samples/example4_simple.py | 1,158 | 3.96875 | 4 | import unittest
def sum_two_values(a, b):
return a + b
def power(x, n):
return x ** n
def concat_values(*args):
result = ''
for item in args:
result += str(item)
return result
def desc(x, y):
if x == 0:
raise ValueError('`x` should not be equal 0')
return y / x
clas... |
7b08368a570b5d8225073e9729e254c81e71de1b | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/UnitTesting-master/Proj2/shapes.py | 823 | 3.5625 | 4 | ____ math ______ pi, cos, sin
c_ ShapesArea:
___ -
p..
___ value_check r
# Check to make sure user input is of acceptable type and value
__ ty..(r) no. __ [float, __.]:
r_ T..("Please enter a valid number greater than 0.")
__ r < 0:
r_ V..("Length fro... |
c44520ab92e64dccd4856848075e9794ea1ff740 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/925 Long Pressed Name.py | 1,465 | 3.90625 | 4 | #!/usr/bin/python3
"""
Your friend is typing his name into a keyboard. Sometimes, when typing a
character c, the key might get long pressed, and the character will be typed 1
or more times.
You examine the typed characters of the keyboard. Return True if it is possible
that it was your friends name, with some charac... |
f70d21c83d2a3358e063561e80f8b683efd22d7d | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/_properties_templates/Python_OOP_Object_Oriented_Programming/Section 14/Inheritance-Methods-Code/1 - Shape, Triangle, Circle.py | 653 | 3.515625 | 4 | # c_ Shape:
#
# ___ - color is_polygon description
# ____.? ?
# ____.? ?
# ____.? ?
#
# ___ display_data ____
# print(_*\n=== .d__.ca..| ===
# print("Color:", .c..
# print("Is the shape a polygon?", "Yes" if .i.. else "No")
#
# c_ Triangle ?
#
# ___ - colo... |
e5d8d2c92b90ca3ee027e52fa3303be838e4ae6b | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BreadthFirstSearch/103_BinaryTreeZigzagLevelOrderTraversal.py | 815 | 3.90625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
if not root:
retur... |
94f25a94f89bd31421515bc201727e6530947fab | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/417 Pacific Atlantic Water Flow.py | 4,163 | 3.84375 | 4 | #!/usr/bin/python3
"""
Given an m x n matrix of non-negative integers representing the height of each
nit cell in a continent, the "Pacific ocean" touches the left and top edges of
the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) ... |
555ed89f50df9e41ebaf09f27132f620c38cf7fa | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/129_rehashing.py | 879 | 3.765625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
c_ Solution:
"""
@param hash_table: A list of The first node of linked list
@return: A list of The first node of linked list which have twice size
"""
___... |
bd9859f05ef620d248fdfb970ca1b48e96118ec7 | syurskyi/Python_Topics | /045_functions/008_built_in_functions/sort/examples/004_Key also takes user-defined functions as its value for the basis of sorting..py | 278 | 3.890625 | 4 | # Sort a list of integers based on
# their remainder on dividing from 7
def func(x):
return x % 7
L = [15, 3, 11, 7]
print "Normal sort :", sorted(L)
print "Sorted with key:", sorted(L, key = func)
# Output :
# Normal sort : [3, 7, 11, 15]
# Sorted with key: [7, 15, 3, 11] |
eec917248b747e015e7dbc2f30c0340d1e8440b3 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/084_Largest_Rectangle_in_Histogram.py | 992 | 3.515625 | 4 | c_ Solution o..
___ largestRectangleArea heights
"""
:type heights: List[int]
:rtype: int
"""
# https://leetcode.com/discuss/70983/4ms-java-solution-using-o-n-stack-space-o-n-time
largest_rectangle = 0
ls = l.. heights)
# heights[stack[top]] > heights... |
3dd313538384bc7963aa08ed3bda52bffaf47228 | syurskyi/Python_Topics | /125_algorithms/002_linked_lists/_exercises/templates/Linked Lists/Linked Lists Interview Problems/PRACTICE/Singly Linked List Cycle Check.py | 1,451 | 4 | 4 | # # Singly Linked List Cycle Check
# # Problem
# # Given a singly linked list, write a function which takes in the first node in a singly linked list and returns
# # a boolean indicating if the linked list contains a "cycle".
# # A cycle is when a node's next point actually points back to a previous node in the list. T... |
804d661b03b980700a07d8182ab1cf5e95d6d855 | syurskyi/Python_Topics | /012_lists/examples/ITVDN Python Starter 2016/08-string-indexing.py | 214 | 3.625 | 4 | # -*- coding: utf-8 -*-
# Создание строки
string = "a string"
# Вывод отдельных символов строки
print(string[0]) # 'a'
print(string[2]) # 's'
print(string[-1]) # 'g' |
2e80ba9976807b162b6dd922326df973cc8451c9 | syurskyi/Python_Topics | /140_gui/pyqt_pyside/examples/PyQt5/Chapter13_Running Python Scripts on Android and iOS/demoDialog.py | 649 | 3.546875 | 4 | import android
app = android.Android()
title = 'Understanding Dialog Buttons'
message = ('Do you want to Place the Order?')
app.dialogCreateAlert(title, message)
app.dialogSetPositiveButtonText('Yes')
app.dialogSetNegativeButtonText('No')
app.dialogSetNeutralButtonText('Cancel')
app.dialogShow()
response = app.dialogG... |
4cbe452c0972d738a2d511bac2a930e8675f5ce1 | syurskyi/Python_Topics | /050_iterations_comprehension_generations/002_dictionary_comprehension/examples/007.py | 5,442 | 4.15625 | 4 | # List comprehension
# ==================
# new_list = [new_item for item in list_or_range]
numbers = [1, 2, 3, 4, 5]
new_numbers = [n + 1 for n in numbers]
print(new_numbers)
nato_phonetic_alphabet = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet",
... |
281fab13317e229e8b7819c410b29c89d66bf562 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/873 Length of Longest Fibonacci Subsequence.py | 2,842 | 4.0625 | 4 | #!/usr/bin/python3
"""
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence,
find the length of the longest fibonacci-like subsequence of A. If one does not
exist, return 0.
(Recall that a sub... |
150d0efefb3c712edc14a5ff039ef2082c43152b | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/111_Minimum_Depth_of_Binary_Tree.py | 1,281 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
c_ Solution o..
# def minDepth(self, root):
# """
# :type root: TreeNode
# :rtype: int
# """
# # Recursio... |
7a183c9f407ec53a128bb57bfd6e5f0f9e10df7d | syurskyi/Python_Topics | /070_oop/008_metaprogramming/_exercises/templates/Abstract Classes in Python/a_004_Concrete Methods in Abstract Base Classes.py | 848 | 4.21875 | 4 | # # Concrete Methods in Abstract Base Classes :
# # Concrete classes contain only concrete (normal)methods whereas abstract class contains both concrete methods
# # as well as abstract methods. Concrete class provide an implementation of abstract methods, the abstract base class
# # can also provide an implementation b... |
e6cd52ea2f93f9d6b604a86199e13e1062c077c6 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Learning Python/029_002_Indexing and Slicing __getitem__ and __setitem__.py | 1,711 | 3.65625 | 4 | # c_ Indexer:
# ___ -g ____ index
# r_ ? ** 2
#
# X = I.
# print('#' * 23 + ' X[i] calls X.__getitem__(i)')
# print(X[2]) # X[i] calls X.__getitem__(i)
#
#
# # for i in range(5):
# # print(X[i], end=' ') # Runs __getitem__(X, i) each time
#
#
# L = [5, 6, 7, 8, ... |
fc0b28844054dba6e018c3e64422087aa81fb1fe | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/861 Score After Flipping Matrix.py | 1,280 | 3.953125 | 4 | #!/usr/bin/python3
"""
We have a two dimensional matrix A where each value is 0 or 1.
A move consists of choosing any row or column, and toggling each value in that
row or column: changing all 0s to 1s, and all 1s to 0s.
After making any number of moves, every row of this matrix is interpreted as a
binary number, and... |
40d52cb329b0c0128ad81af19b9966cde8a4b9fe | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 32 - 3SumClosest.py | 940 | 3.765625 | 4 | # 3 Sum Closest
# Question: Given an array S of n integers, find three integers in S such that the sum is closest to a given number,
# target. Return the sum of the three integers. You may assume that each input would have exactly one solution
# For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is ... |
7e74db4c09ec16f6fced7843cda365bcf245d0df | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/DynamicProgramming/70_ClimbingStairs.py | 393 | 3.59375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if not n:
return 1
dp = [0 for i in range(n)]
dp[0] = 1
if n > 1:
dp[1] = 2
for i in ra... |
ed94d2c495b0969bd089bc2d0847bde79526a5f2 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-22-write-a-decorator-with-argument-a.py | 609 | 3.703125 | 4 | """
Write a decorator called make_html that wraps text inside one or more html tags.
As shown in the tests decorating get_text with make_html twice should wrap the text in the corresponding html tags, so:
@make_html('p')
@make_html('strong')
def get_text(text='I code with PyBites'):
return text
- would return: <p... |
98357c37192a91a3dc3afbe121908ae36db45019 | syurskyi/Python_Topics | /125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 84 - ReverseInt.py | 382 | 4.15625 | 4 | # Reverse Integer
# Question: Reverse digits of an integer.
# Example1: x = 123, return 321
# Example2: x = -123, return -321.
# Solutions:
class Solution:
# @return an integer
def reverse(self, x):
if x<0:
sign = -1
else:
sign = 1
strx=str(abs(x))
r = s... |
09af2eff3aa3ec127997bcbdb995ace63a092772 | syurskyi/Python_Topics | /070_oop/001_classes/examples/ITVDN_Python_Advanced/006_Типизированный Python/example1.py | 467 | 3.609375 | 4 | # untyped
value = 10
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def create_new_user(first_name, last_name):
# неоднозначность типов и преобразований
# first_name.???
print(first_name)
return User(first_name=first... |
4b9257954ef3f32e2dfcfb4f964f7e0b669b2d7a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/013 Roman to Integer.py | 767 | 3.65625 | 4 | """
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
"""
__author__ 'Danyang'
roman2int {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
c_ Solution:
___ romanToInt s
"""
What happens if cur... |
c9481862292b011e70bf73b3d62078e3a0122ab7 | syurskyi/Python_Topics | /120_design_patterns/025_without_topic/examples/MonoState.py | 2,609 | 4.28125 | 4 | #!/usr/bin/env python
# Written by: DGC
# python imports
#==============================================================================
class MonoState(object):
__data = 5
@property
def data(self):
return self.__class__.__data
@data.setter
def data(self, value):
self.__class... |
4bfbc07c20a755a3e9607e00fe19deb57556f077 | syurskyi/Python_Topics | /125_algorithms/_exercises/exercises/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 78 - RmDupArr.py | 923 | 3.765625 | 4 | # # Remove Duplicates from Sorted Array
# # Question: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
# # Do not allocate extra space for another array, you must do this in place with constant memory.
# # For example: Given input array nums = [1,1,... |
dcd947e7c695994dce361540224d3b63d3bb4d7a | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/336 Palindrome Pairs.py | 2,980 | 4.125 | 4 | #!/usr/bin/python3
"""
Given a list of unique words, find all pairs of distinct indices (i, j) in the
given list, so that the concatenation of the two words, i.e. words[i] + words[j]
is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are... |
d133419e4fcee49cdb10319bc4e000ce04751748 | syurskyi/Python_Topics | /010_strings/_exercises/_templates/Learning Python/019_Advanced Formatting Expression Examples.py | 466 | 3.609375 | 4 | # x = 1234
# res = 'integers: ...@...@-6_...$_6_' % (x, x, x) # | digit
# print(res)
# x = 1.23456789
# print(x) # Shows more digits before 2.7 and 3.1
# print('@ | @ | @' _ x, x, x # |exponential | float | shot of exponential
# print('@' _ x) # |exponential big letter
# print('_-6.2_ | __5... |
947d2727d45716aefa420d81b442014928e09d91 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-111.py | 1,438 | 3.96875 | 4 | """
In this Bite you will use the requests library to make a GET request to the ipinfo service.
Use IPINFO_URL and parse the (2 char) country code from the obtained json response.
Note how we mocked out the requests.get call in the tests, you can see another example of
this in our Parsing Twitter Geo Data and Mocking... |
42ea23542608d894bf2c4c50394464b9d68d0eeb | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/769 Max Chunks To Make Sorted.py | 1,315 | 4.28125 | 4 | #!/usr/bin/python3
"""
Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we
split the array into some number of "chunks" (partitions), and individually sort
each chunk. After concatenating them, the result equals the sorted array.
What is the most number of chunks we could have made?
Example 1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.