blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
165700180b7a2790f488c0103dbf1b8ff57e37ca
KhlopotovAI/codewars-py
/scramblies/kata.py
291
3.546875
4
# https://www.codewars.com/kata/scramblies/train/python from collections import Counter def scramble(s1, s2): s1_counter = Counter(s2) s2_counter = Counter(s1) for k in s1_counter: if s2_counter.get(k, 0) < s1_counter.get(k): return False return True
5f55f5379825069175456d8c53c25836e960d816
KhlopotovAI/codewars-py
/deadfish/kata.py
695
3.71875
4
# https://www.codewars.com/kata/make-the-deadfish-swim/train/python class Parser: def __init__(self, data): self.value = 0 self.arr = [] self.data = data def plus(self): self.value += 1 def minus(self): self.value -= 1 def square(self): self.value **= 2...
4eacf7e0a9bf10918579aec5097ea124bd79c070
cmattey/leetcode_problems
/Python/lc_167_two_sum_ii_sorted_array.py
528
3.5
4
# Time: O(len(numbers)) # Space: O(1) class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ start = 0 end = len(numbers)-1 while start<end: cur_num = numbers[sta...
3dfd3af3b7e78905181c1892550b56071a0a2e90
cmattey/leetcode_problems
/Python/lc_1000_min_cost_merge_stones.py
3,903
3.515625
4
# Oct 28th '19 # Time: O(n^3) # Space: O(n^2) for dict class Solution: def mergeStones(self, stones: List[int], K: int) -> int: """ Using dp dp[i][j] = state, min_cost to combine stones from index i to j(inclusive) dp[i][j] = min(dp[i][temp]+dp[temp+1][j] for temp in range(i,j, K-...
0633de2ca1924258662f385f41e0f29f4262a3df
cmattey/leetcode_problems
/Python/lc_489_robot_room_cleaner.py
2,103
3.796875
4
# Time: O(4^m*n), m= numrows, n = numcols # Space: O(m*n),for visited set # """ # This is the robot's control interface. # You should not implement it, or speculate about its implementation # """ #class Robot: # def move(self): # """ # Returns true if the cell in front is open and robot moves into the...
2f824767e06661454e41a92c12e621dd7f3addd5
cmattey/leetcode_problems
/Python/lc_24.py
767
3.78125
4
# 24. Swap Nodes in Pairs # Time: O(len(list)) # Space: O(1) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head: return None ...
bba5c6fed7e339300b4a6d9bfc382cf6aa58cd77
cmattey/leetcode_problems
/Python/lc_36_valid_sudoku.py
1,427
3.78125
4
# 36. Valid Sudoku # Time: O(len(board)^2) # Space: O(len(board)) class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: for row in board: if not self.validateRow(row): return False for col in range(len(board[0])): if not self.validateCol(c...
3c6f9a32ede001698b46f8040d67f30725b9e559
cmattey/leetcode_problems
/Python/lc_211_add_search_word_ds_design.py
1,682
3.9375
4
class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word: str) -> None: """ Adds a word into the data structure. """ cur_node = self.root for ch in word: ...
d7fa361262063dc070334c8b9c8d0085dfaed8ca
cmattey/leetcode_problems
/Python/lc_129_sum_root_leaf_numbers.py
1,529
3.828125
4
# 129. Sum Root to Leaf Numbers # Time: O(size(tree)) # Space: O(1) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.result = 0 def sumNumbers(sel...
17b0094095b703e82b75e099bec5f6e4125f0a91
cmattey/leetcode_problems
/Python/lc_19.py
610
3.78125
4
# 19. Remove Nth Node From End of List # Time: O(n) # Space: O(1) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: slow = head fast ...
f8acb8c28bcf7427653833bca9c560f2e2b68a8e
cmattey/leetcode_problems
/Python/lc_958_check_completeness_binary_tree.py
1,038
3.90625
4
# Time: O(n) # Space: O(1) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isCompleteTree(self, root: TreeNode) -> bool: """ if left-child is None, then no more chi...
6acf591c28e1c471463511db3dd0409d7cac1487
cmattey/leetcode_problems
/Python/lc_130_surrounded_regions.py
1,049
3.609375
4
# Time: O(size(board)) # Space: O(1) class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ for row in range(len(board)): for col in range(len(board[0])): if row==0 or row==len(boar...
1e6a7a4ebf23d67bdb57705829b59b59fe7c569f
cmattey/leetcode_problems
/Python/lc_101_symmetric_tree.py
636
4.03125
4
# Time: O(size(tree)) # Space: O(size(tree)), for recursion stack # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.uti...
c444bab20129686ed29a92c5e74d8059c2e303f2
cmattey/leetcode_problems
/Python/lc_238_product_array_except_self.py
2,369
3.578125
4
# Nov 15th '19 # Time: O(n) # Space: O(n) class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: """ Cleaner, Linear time, linear space solution """ left_prod = [None]*len(nums) left_prod[0] = 1 for index in range(1, len(nums)): left_pr...
3ab67dc193632d834087a0364bcc6690ebab3360
Maxpersik/multilang
/python/resist.py
181
3.546875
4
#!/usr/bin/python3 import sys rA = sys.argv[1:] S = 0 for r in rA: S += 1/int(r) R = 1/S print("Общее сопротивление равно:", round(R, 2), "Ом")
3fe8ff6ea8a307276a311b01f494c3e92175868d
corridda/Studies
/Articles/Python/pythonetc/year_2018/september/operator_and_slices.py
2,069
4.5
4
"""Оператор [] и срезы""" """В Python можно переопределить оператор [], определив магический метод __getitem__. Так, например, можно создать объект, который виртуально содержит бесконечное количество повторяющихся элементов:""" class Cycle: def __init__(self, lst): self._lst = lst def __getitem__(se...
accd652b489ce6fa17681df757df723b0c87ef4e
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 15. Floating Point Arithmetic_Issues and Limitations/test_floating_point_arithmetic.py
415
3.546875
4
import math print(.1 + .1 + .1 == .3) # False print(round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)) # False print(round(.1 + .1 + .1, 1) == 0.3) # True print() # The math.fsum() function helps mitigate loss-of-precision during summ...
b779876874fbc28d28cdf052cd11ff1e6f8c314c
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/e-g/float__test.py
618
4.15625
4
"""class float([x])""" # https://www.programiz.com/python-programming/methods/built-in/float """Return a floating point number constructed from a number or string x.""" print(f"float(): {float()}") print(f"float(10.5): {float(10.5)}") s = ' -2.5\n' print(f"float(' -2.5'): {float(s)}") print(f"float('NaN'): {flo...
22806e83c0bf42cbab9b17e32580e80e3d0ad87a
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/c-d/dict__test.py
673
4.1875
4
"""class dict""" # https://www.programiz.com/python-programming/methods/built-in/dict """ class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class. ...
6e3253b0394a6da0e35700a60c420cf946ebb0f6
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/o-r/property_test.py
4,013
4.1875
4
"""class property(fget=None, fset=None, fdel=None, doc=None)""" # https://www.programiz.com/python-programming/methods/built-in/property """Return a property attribute. 'fget' is a function for getting an attribute value. 'fset' is a function for setting an attribute value. 'fdel' is a function for deleting an attribu...
8953847f9c86d3aa1287e4b505f11b710b607374
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Constants/Built-in Constants.py
1,444
3.515625
4
"""Built-in Constants""" """False, True, None""" # Assignments to False, True, None are illegal and raise a SyntaxError. print(False, True, None) print(type(False), type(True), type(None), '\n') """NotImplemented""" """Special value which should be returned by the binary special methods (e.g. __eq__(), __lt__(), ...
8f5f9f99bd7741d9c7bc286e2bc5f93293c92a39
corridda/Studies
/Courses/Cybersecurity/Cryptography_I/week_1/q7.py
610
3.640625
4
"""Suppose you are told that the one time pad encryption of the message "attack at dawn" is 09e1c5f70a65ac519458e7e53f36 (the plaintext letters are encoded as 8-bit ASCII and the given ciphertext is written in hex). What would be the one time pad encryption of the message "attack at dusk" under the same OTP key?""" m1...
bf07a352d67d378ae73f9336d9c74761e47222b2
corridda/Studies
/Books/Mathematics/Algebra/Linear Algebra/Introduction to Linear Algebra/Chapter 2/_2_2_The_Idea_of_Elimination/problem_28.py
184
3.671875
4
import numpy as np if __name__ == '__main__': A = np.array([[2,2],[6,4]]) print(f"A:\n{A}\n") for i in range(len(A[1])): A[1][i] -= A[0][i]*3 print(f"A:\n{A}")
96cf593665d56c5e66c18577f3558e2edf22a62a
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 4. More Control Flow Tools/4.7. More on Defining Functions/4.7.3. Arbitrary Argument Lists/test.py
568
3.875
4
import tempfile # Before the variable number of arguments, zero or more normal arguments may occur. def write_multiple_items(separator, *args): with tempfile.TemporaryFile() as f: f.write(separator.join(args)) f.seek(0) print(f.read()) write_multiple_items(b" ", b'A', b'string', b'to', b'w...
a642a315921776c3d5920bd3e9f649a888462773
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/list_test.py
2,003
4.46875
4
"""class list([iterable])""" # https://www.programiz.com/python-programming/methods/built-in/list """Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range. The list() constructor creates a list in Python. Python list() constructor takes ...
3ec93bc3e2bbb8ec2f59a612ac2ad112aa1f4930
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.8. Generator expressions/example.py
230
4.25
4
# A generator expression is a compact generator notation in parentheses. # A generator expression yields a new generator object. a = (x**2 for x in range(6)) print(f"a: {a}") print(f"type(a): {type(a)}") for i in a: print(i)
c46fa1c8b803ed58abbfeb86d53d0b47f76c0c7d
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/h-i/hasattr_test.py
597
4.21875
4
"""hasattr(object, name)""" # https://www.programiz.com/python-programming/methods/built-in/hasattr print(f"'int' has 'real': {hasattr(int, 'real')}\n") class A: def __init__(self, a, b): self.a = a self.b = b obj_1 = A(1, 2) obj_2 = 15 print(f"hasattr(obj_1, 'a'): {hasattr(obj_1, 'a')}") prin...
d866a29053b2e57c7dacf0d44ebaa0078138305a
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/a-b/all__test.py
1,808
4.25
4
"""all(iterable)""" # https://www.programiz.com/python-programming/methods/built-in/all """Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:""" def all_func(iterable): for element in iterable: if not element: return False return True def m...
5315e68a06067a3ab9a99178ab86ce613dc163fb
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/c-d/divmod__test.py
816
4.21875
4
"""divmod(a, b)""" # https://www.programiz.com/python-programming/methods/built-in/divmod """Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For in...
f312b493d986a88f5f05e4ef2c0db055aa8a8c8d
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/min_test.py
2,432
4.25
4
"""min(iterable, *[, key, default]) min(arg1, arg2, *args[, key])""" # https://www.programiz.com/python-programming/methods/built-in/min """Return the smallest item in an iterable or the smallest of two or more arguments. If one positional argument is provided, it should be an iterable. The smallest item in the it...
3cb0ca44cd1e78c0461902e7a4dd6b2c4480e76d
corridda/Studies
/Articles/Python/Cython_более_чем_30_кратное_ускорение_Python_кода/main.py
4,303
4.09375
4
"""Ускорение кода с использованием Cython Начнём с создания Python-бенчмарка. Это будет цикл for, в котором выполняется вычисление факториала числа. Соответствующий код на чистом Python будет выглядеть так: """ # def test(x): # y = 1 # for i in range(1, x+1): # y *= i # return y """Cython-эквивал...
bf573e2b7eafe79adde1e52d40e21d5d393b043e
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.4. Displays for lists, sets and dictionaries/example.py
218
4.125
4
# The comprehension consists of a single expression followed by at least one for clause # and zero or more for or if clauses. a = [x**2 for x in range(11) if x % 2 == 0] print(f"a: {a}") print(f"type(a): {type(a)}")
e5de070bfe40a82008d8d9e6ed6986c618dc7043
corridda/Studies
/Articles/Python/pythonetc/year_2018/october/python_etc_oct_23.py
1,278
4.1875
4
"""https://t.me/pythonetc/230""" """You can modify the code behavior during unit tests not only by using mocks and other advanced techniques but also with straightforward object modification:""" import random import unittest from unittest import TestCase # class Foo: # def is_positive(self): # return sel...
beb99591beb990888eb58b3d949b3b44a21bcb2f
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/s-z/tuple_test.py
724
4.40625
4
""" tuple([iterable]) class type(object) class type(name, bases, dict)""" # https://www.programiz.com/python-programming/methods/built-in/tuple """Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range. If an iterable is pass...
8341587ff2d172282ab6b00a82ea56380f062e4f
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 5. Data Structures/5.6. Looping Techniques/Looping Techniques.py
1,713
4.15625
4
import math # looping through dictionaries -> items() knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k,v in knights.items(): print(k, ':', v) # looping through a sequence -> # the position index and corresponding value can be retrieved at the same time using the enumerate() function. for i, v in enu...
b099a789095e0219156d5cc73d690a738c42ed79
corridda/Studies
/Articles/Python/pythonetc/year_2018/september/autovivification.py
1,204
4.15625
4
from collections import defaultdict """collections.defaultdict позволяет создать словарь, который возвращает значение по умолчанию, если запрошенный ключ отсутствует (вместо выбрасывания KeyError). Для создания defaultdictвам нужно предоставить не просто дефолтное значение, а фабрику таких значений. Так вы можете созд...
bb7912441f3be3546706bd7c232a5f43979c8b07
aaraskumar-git/python_scripts
/fbtest.py
306
3.515625
4
class Car: def __init__(self, color): print('we are in init') self.color = color @staticmethod def mycolor(color): return color def display(self): return self.color colorcode = Car('red') Car.mycolor('green') print(colorcode.display())
cef6f73dfd6d7f8a41220465d3968cf67340eaa8
aaraskumar-git/python_scripts
/ascii.py
244
3.9375
4
# Given string, change all the characters into caps str = "aRaS" upd_str = "" for index, ech in enumerate(str): if ord(ech) >= 97: upd_str = upd_str + chr(ord(ech)-32) else: upd_str = upd_str + ech print(upd_str)
e57b3e452ffc52808876426c484d2d5e0adafd44
pisomnia/Research
/DL_Seismic_Response_Prediction_Model/Spectragram_Based_SRPM/plot_utils.py
786
3.6875
4
import numpy as np from math import sqrt import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error, r2_score def score(model_name, y_val, y_val_pred): print("The calculated RMSE is:%0.8f" % (sqrt(mean_squared_error(y_val, y_val_pred)))) ARD = np.absolute(y_val_pred-y_val)/y_val MARD=n...
7a3c236aeb8cca90cfeec1f2c9a5fe5f713b7a35
agga1/compilation_theory
/src/type_check/SymbolTable.py
1,296
3.515625
4
from enum import Enum, auto from typing import Optional class Type(Enum): INTNUM = auto() FLOAT = auto() STRING = auto() VECTOR = auto() MATRIX = auto() BOOLEAN = auto() RANGE = auto() NULL = auto() UNKNOWN = auto() @staticmethod def is_number(mtype): return mtype i...
d0129d8983441636b7a83f26f82b0af862372526
Dknyboy20/AlexaSkillKits
/get_quote.py
1,114
3.59375
4
from __future__ import print_function import requests from bs4 import BeautifulSoup import sys def get_quote(company_name): ''' perform google search on a given company name ans stock quote if the stock price info box appears in the search results page then get the stock price and return that number ''' html ...
7226763ef30f787382dd511cb3f66a18f1bf87ba
jvslinger/Year9Design01PythonJVS
/Sample Project 1/GUI1JVS.py
1,455
3.96875
4
#This opens the tkinter "tool box" containing all support material to make GUI Elements #By including as tk we are giving a short name to use. import tkinter as tk #Main Window root = tk.Tk() #creates the window #Three stages to build elements #1. Construct the Object: Building and Configuring it #2. Configure the ...
f4242f4fd543eb9d763cd3834cfb8e0c550b1f39
sylviachan127/Natural-Language-Processing
/2017-materials/psets/ps1/gtnlplib/preproc.py
1,593
3.6875
4
import nltk import pandas as pd from collections import Counter from nltk.tokenize import sent_tokenize, word_tokenize def tokenize_and_downcase(string,vocab=None): """for a given string, corresponding to a document: - tokenize first by sentences and then by word - downcase each token - return a Counte...
419189ba840f3baffd14eebd053d85a1aff8e3fb
Yoshihama0901/burger_war_19sm
/circle/model-sin-theta.py
422
3.734375
4
#!/usr/bin/env python import sys import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression df = pd.read_csv(sys.argv[1]) lr = LinearRegression() X = df[['circle_x']] Y = df['sin_theta'] lr.fit(X, Y) print('coef=', lr.coef_) print('intercept=', lr.intercept_) plt.scatter(X,...
3d7822f603028b3aec26d7951b148ba414dd4816
swyatik/Python-core-07-Vovk
/Task 12/1.py
813
3.59375
4
class Door: colour = 'white' def __init__(self, number, status, locked): self.number = number self.status = status self.locked = locked def open(self): self.status = 'open' def close(self): self.status = 'close' def is_open(self): return sel...
433f91cdfc47f8b60fb99085a60f7104708cbe48
swyatik/Python-core-07-Vovk
/Task 13/task2.py
521
3.625
4
import sqlite3 conn = sqlite3.connect('my.db') c = conn.cursor() def add_user(username, userpass): c.execute("INSERT INTO users (name,password) VALUES ('%s', '%s')" % (username, userpass)) conn.commit() name = input("enter login\n") passwd = input('enter code\n') print("Users' list:\n") add_user(name, passwd) ...
538539363bd307306d3225b157d1505465468d7c
swyatik/Python-core-07-Vovk
/Task 6/Home Work 1/6.7.py
502
3.96875
4
"""У списку знайти елементи, які в ньому зустрічаються тільки один раз, і вивести їх на екран. """ from random import randint randList = [] print('Our list:') for i in range(20): randList.append(randint(0, 10)) print('%2d' %randList[i], end=' ') print() once = [i for i in randList if randList.co...
846c4d29e4c35d7bcfef67418034cd9647ef2e2c
swyatik/Python-core-07-Vovk
/Task 6/Home Work 2/6.2.7.py
1,227
4.28125
4
"""Змінити послідовність стовпців матриці так, щоб елементи її першого рядка були відсортовані за зростанням. """ from random import randint # function of prints a matrix def printMatrix(matrix): for item in matrix: for jtem in item: print("%4d " % j, end="") print() colum...
6b3f8316bc32ae76e7975953ae2839bc47a0d317
swyatik/Python-core-07-Vovk
/Task 4/2_number_string.py
293
4.15625
4
number = 1234 strNumber = str(number) product = int(strNumber[0]) * int(strNumber[1]) * int(strNumber[2]) * int(strNumber[3]) reversNumber = int(strNumber[::-1]) print('Product of number %d is %15d' % (number, product)) print('Inverse number to number %d is %8d' % (number, reversNumber))
31a2fa5b2febc2ef80b57e45c2ebb662b886c4b7
swyatik/Python-core-07-Vovk
/Task 3/4_hall_scene.py
547
3.921875
4
'''Чи можна в квадратному залі площею S помістити круглу сцену радіусом R так, щоб від стіни до сцени був прохід не менше K?''' from math import sqrt s = int(input('Input your area of square (S): ')) r = int(input('Input your radius of scene (R): ')) k = int(input('Input your width of passage (K): ')) k2 = sqrt...
56403e728de4d373716f254eeda78713f902edf3
swyatik/Python-core-07-Vovk
/Task 8/8.2.5.py
1,683
4.125
4
"""Задано два символьних рядка із малих і великих латинських літер та цифр. Розробити програму, яка будує і друкує в алфавітному порядку множину літер, які є в обох масивах, і множини літер окремо першого і другого масивів. """ def printSetSort(userSet): usrSetSort = sorted(userSet) for i in range...
fe02d0c885670f821eae1389a3b1f62f3921801a
swyatik/Python-core-07-Vovk
/Task 1/11_total_points.py
1,650
4.15625
4
# Функція, що перевіряє чи рядок число int or float. # Повертає tuple (true or false, тип даних в рядку) def check_int_float(string): if string == '': return (True, 'int') if string[0] == '-': return (False, '') if string.isdigit(): return (True, 'int') else: ...
8e288fb388d5b9aa1f19104535a2c2dcec52422b
Aryan-Dubey02/single-player-TIC-TAC-TOE
/Tic_Tac_Toe_GUI.py
12,199
3.703125
4
from tkinter import * from tkinter import messagebox #Creating main window here root = Tk() root.title("Tic Tac Toe") count = 0 winner = False #Function for taking location of player click for backend process def which_button(m): if m=="b1": board[1] = "X" elif m== "b2": board[2] = "X" eli...
03b85a070f12b43fe9206f7b8001135cb3fb1c83
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_197.py
644
3.796875
4
from typing import Union # a def print_prev_els(nums:list, n:Union[int, float]) -> None: dummy = nums[:] while dummy: d = dummy.pop(0) if d == n: break else: print(d, end=',') # b def ends_with(x:int, ld:int=7) -> bool: return(not x...
0dc8597aa58ee6647df657f8f902c72fde421f58
bakunobu/exercise
/1400_basic_tasks/chap_9/ex_9_23.py
334
3.515625
4
def num_div(n:int) -> int: n_divs = 0 for x in range(1, n+1): if not n % x: n_divs += 1 return(n_divs) def count_k_divs(a, b, k) -> dict: div_counter = {} for i in range(a, b+1): n_divs = num_div(i) if n_divs == k: div_counter[i] = n_divs return(...
2f970c7049fdcf0704bee24f1e46b0dc0d8eb1af
bakunobu/exercise
/1400_basic_tasks/chap_7/7_24.py
400
3.703125
4
def bigger_prod(n:int, s:float) -> bool: my_prod = 1 for i in range(n): while True: try: x = float(input('Введите число: ')) my_prod *= x break except ValueError: print('Используйте только числа (разделитель - \'.\')...
e4f868c12aec7eb4028611d46bf578e5e7619556
bakunobu/exercise
/python_programming /Chapter_1.3/stats.py
1,067
4.5625
5
""" Обобщая упражнение о равномерных случайных числах, составьте программу stats.ру, получающую в аргумен­те командной строки целое число n и использующую функцию random.random ( ) для вывода n равномерно случайных чисел от О до 1, а затем вы­водящую их среднее, минимальное и максимальное значения """ import random ...
e2c7c02447cb46af800e74dd161409ecc4a47d15
bakunobu/exercise
/1400_basic_tasks/chap_6/6_35.py
884
3.65625
4
# a def count_three(n:int) -> int: counter = 0 while n: num = n % 10 if num == 3: counter += 1 n //= 10 return(counter) # b def count_last_digit(n:int) -> int: ld = n % 10 counter = 0 while n: num = n % 10 if num == ld: counter +=...
e4c976a7140ee9846573480824d6c41d1fbbf1c7
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_174.py
448
3.59375
4
from typing import Union def is_five_init(x:int) -> bool: while x: if not x % 5 and x % 10: return(True) x //= 10 return(False) def cont_five_ind(nums:list, a:Union[int, float]) -> list: ind_five = [i for i in range(len(nums)) if is_five_init(nums[i])] i = 1 for j in ...
826fe7271db8a9626df56801a6d68dbfad1c4eb2
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_214.py
350
3.796875
4
from typing import Union def is_descending(nums:list) -> Union(None, int): i = None for j in range(len(nums) - 1): if nums[j] < nums[j+1]: i = j break return(i) def print_result(points:list) -> bool: i = is_descending(points) if i is None: return(True) ...
b38f85208cfea9330c70889640fb6236d9850fbc
bakunobu/exercise
/1400_basic_tasks/chap_4/4_111.py
134
3.640625
4
def how_many_even(a: int, b:int, c: int, d: int) -> int: res = [1 if x % 2 == 0 else 0 for x in (a, b, c, d)] return(sum(res))
fba2b4923789ab569aeebe84aeb07bf035a5c2bc
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_111.py
212
3.71875
4
def length_even_nums(nums:list) -> int: i = 0 longest = 0 for x in nums: if x % 2: i += 1 else: longest = max(i, longest) i = 0 return(longest)
1523cbef47a7a574dd2fc3d634a246838933a590
bakunobu/exercise
/1400_basic_tasks/chap_8/ex_8_17.py
357
3.78125
4
import fractions from fractions import Fraction def calc_seq(eps:float=0.001) -> fractions.Fraction: prev_num = 1 prev_den = 1 num = 2 den = 1 while abs((num / den) - (prev_num / prev_den)) > eps: prev_num, num = num, prev_num + num prev_den, den = den, prev_den + den return(F...
fdc692b70c2d2eaae88992fa6f008935d3c2228f
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_153.py
256
3.796875
4
def shift_three_els(nums:list) -> list: nums[0], nums[1], nums[2],\ nums[-3], nums[-2], nums[-1] = nums[-3],\ nums[-2], nums[-1], nums[0], nums[1], nums[2] return(nums) # num_list = [1, 2, 3, 4, 5, 6, 7] # print(shift_three_els(num_list))
03b684e80451215ec5a507b100db38088ec81c19
bakunobu/exercise
/1400_basic_tasks/chap_3/3.45.py
1,405
4.46875
4
""" Меня вынесла формулировка. На самом деле задание сводится к тому, что имеется последовательность длиной 180 символов, в которой индекс есть у каждой пары чисел, например номер элемента|->|индекс 1 -> 0 2 -> 0 3 -> 1 4 -> 1 5 -> 2 6 -> 2 и т.д. """ import doctest # k = int(input()) # a def find_index(k: int) -> i...
61f13e75727c217854b0fee244d61327dcca9420
bakunobu/exercise
/1400_basic_tasks/chap_4/4_85.py
829
3.734375
4
def month_to_years(n:int) -> int: years = n // 12 month = n % 12 if 11 <= years <= 19: y_ending = 'лет' elif years % 10 == 0: y_ending = 'лет' elif years % 10 == 1: y_ending = 'год' elif years % 10 in (2, 3, 4): y_ending = 'года' else: y_ending = ...
d41d4cc1ff02995cf4a9830bb00296ef6cbd8466
bakunobu/exercise
/1400_basic_tasks/chap_4/4_107.py
112
3.578125
4
def print_even(a:int, b:int, c:int) -> None: for x in (a, b, c): if x % 2 == 0: print(x)
56e4e6fc1ca292a57ecb1bc40d3bb1675e3c6c02
bakunobu/exercise
/1400_basic_tasks/chap_6/6_18.py
274
3.8125
4
import math # a def print_sqrt(a:int, b:int) -> None: while a > b: print(math.sqrt(a)) a -= 1 # b def print_sqrt_alt(a:int, b:int) -> None: while True: print(math.sqrt(a)) a -= 1 if a == b: break
c8cf8bc7b91eae2858b4c2c3f54be401fdbbee96
bakunobu/exercise
/1400_basic_tasks/chap_5/5_3.py
460
3.828125
4
# a for x in range(20, 36): print(x) # b def print_squares(a:int, b:int=51) -> None: for i in range(a, b): print(i ** 2) if __name__ == '__main__': a = int(input('Введите число: ')) print_squares(a) # c def print_cubes(b:int, a:int=10) -> None: for x in range(a, b+1): p...
09c1f6ffdeb99495656086931b56710f37538ddb
bakunobu/exercise
/1400_basic_tasks/chap_4/4_123.py
142
3.640625
4
def points_to_res(x:int) -> str: if x == 3: return('Win') elif x == 0: return('Lose') else: return('Draw')
01479006da67767f219e8d241f421c50d12df092
bakunobu/exercise
/python_programming /Chapter_1.1_and_1.2/dragon_curve.py
1,795
4.5
4
""" Составьте программу, выводящую инструкции по рисованию кривых дракона в по­рядке от О до 5. """ def inverse_replacer(my_str:str, a:str, b:str) -> str: """ Replaces a wit b and b with a in my_str Args: ===== my_str: str the sequence of symbols a: str if my_str[i] == a: my_...
b1c5d14493db1c29e23f5b0b154b03a5354a1648
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_195.py
306
3.5625
4
def find_same(nums:list) -> list: is_same = [int(x == nums[0]) for x in nums] return(is_same) def get_index(indices:list, ind:int=0) -> int: return(indices.index(ind)) def print_other_els(nums:list) -> None: indices = find_same(nums) i = get_index(indices) + 1 print(* nums[i:])
aa32fd5b3400fca26d8e41105b7e1b26d0cfe942
bakunobu/exercise
/1400_basic_tasks/chap_6/6_66.py
214
3.578125
4
def eucl_gcd(a:int, b:int) -> int: while a > 0 and b > 0: a, b = min(a, b), max(a, b) % min(a, b) return(a) def gcd_three_el(a:int, b:int, c:int) -> int: return(eucl_gcd(eucl_gcd(a, b), c))
e5ac3cabe485c1b6b7ced5c4bbb77415d9a67b7a
bakunobu/exercise
/python_programming /Chapter_1.1_and_1.2/box_muler.py
1,211
4.28125
4
""" Один способ создания случайного числа в со­ответствии с распределением Гаусса подразумевает использование фор­мулы Бокса-Мюллера. Составьте программу, выводящую значение согласно стандарт­ному Гауссову распределению. """ import math import random import random def box_muller_trans(v:float, u: float) -> float:...
e21a48f5de55348a2f914db0b61a38fe74f57f05
bakunobu/exercise
/1400_basic_tasks/chap_7/7_106.py
260
3.546875
4
from main_funcs import get_input def calc_mean(n:int) -> float: i = 0 my_sum = 0 for _ in range(n): c = get_input('Введите число: ') if c > 20: i += 1 my_sum += c return(my_sum / i)
9855d40038b650f05024cdcca39f6a2e764530d6
bakunobu/exercise
/1400_basic_tasks/chap_7/7_153.py
678
4.03125
4
from main_funcs import get_input from typing import Union # a def max_even(n:int=14) -> Union[int, bool]: max_even_num = False for _ in range(n): a = get_input('Введите число: ', False) if not a % 2: if not max_even_num: max_even_num = a else: ...
19ab17ebb5dc4a6f13acc5a75c77f3ec55dedaec
bakunobu/exercise
/1400_basic_tasks/chap_7/7_37.py
1,054
3.921875
4
def return_dense(pop:float, area:float) -> float: return(pop / area) def get_input(message:str, is_float:bool=True) -> Union[int, float]: if is_float: while True: try: a = float(input(message)) return(a) except ValueError: print('...
96982e3fe352c185b4385ea69fe1d205fe1a1ad2
bakunobu/exercise
/1400_basic_tasks/chap_5/5_14.py
54
3.5625
4
for x in range(1, 10): print(f'{x} * 9 = {x * 9}')
a159a8b40d9118b1a188167ef8db5b96ec485ffb
bakunobu/exercise
/1400_basic_tasks/chap_3/3.17.py
262
3.828125
4
import doctest def num_sum(x:int) -> int: """ >>> num_sum(20) 2 >>> num_sum(19) 10 >>> num_sum(23) 5 """ return(x // 10 + x % 10) num = int(input()) print(num_sum(num)) if __name__ == "__main__": doctest.testmod()
8ea707bcfce57596b468ef550107e257fe75fc83
bakunobu/exercise
/1400_basic_tasks/chap_4/4_120.py
551
3.53125
4
from typing import Union # a def calc_func_one(x:Union[float, int]) -> Union[float, int]: if x < -1: return(0) elif x > 0: return(1) else: return(x) # b def calc_func_one(x:Union[float, int]) -> Union[float, int]: if x < -1: return(1) elif x > 1: return...
ea91ece9810222f636a7fd4f1d884b9fb91eac68
bakunobu/exercise
/1400_basic_tasks/chap_4/4_35.py
587
3.734375
4
def num_to_digit(a:int) -> list: nums = [] nums.append(a % 10) a -= nums[-1] while a > 0: a /= 10 nums.append(int(a % 10)) a -= nums[-1] return(nums[::-1]) # a def a_eq_b(a:int) -> bool: nums = num_to_digit(a) return(sum(nums[:2]) == sum(nums[2:])) # b def div_thr...
7f36d82e43879f874c4fd72145613cf5f4a5efe3
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_219.py
225
3.640625
4
def num_to_list(n:int) -> list: units = [] while n: u = n % 10 n //= 10 units.append(u) return(units) def unique_units(n:int) -> int: nums = num_to_list(n) return(len(set(nums)))
cc445797cacbe7a1c7662ced9a026689677f52b9
bakunobu/exercise
/1400_basic_tasks/chap_6/6_28.py
134
3.640625
4
nums = [] i = 500 while len(nums) < 20: i += 1 if i % 13 == 0 or i % 17 == 0: nums.append(i) print(* nums, sep =', ')
a4aa37ead46a353c3b90acf5c21095ccb54e0aaa
bakunobu/exercise
/1400_basic_tasks/chap_7/7_57.py
988
3.96875
4
from typing import Union def get_input(message:str, is_float:bool=True) -> Union[int, float]: if is_float: while True: try: a = float(input(message)) return(a) except ValueError: print('Используйте только числа (разделитель - \'.\')')...
02f7e2e0219c68ac533520456c040d0a5422ff1e
bakunobu/exercise
/1400_basic_tasks/chap_2/2.8.py
373
4.09375
4
import math def calc_circumference(r:float) -> float: P = 2 * math.pi * r return(P) def calc_area(r:float) -> float: S = math.pi * r ** 2 return(S) def show_res(r:float) -> None: print('Circunference of the circle: %0.2f' % calc_circumference(r)) print('Area of the circle: %0.2f' ...
c746a914a79186ea92efe3e05a4746c868ee98f2
bakunobu/exercise
/1400_basic_tasks/chap_4/4_132.py
212
3.578125
4
def find_quarter(x:float, y:float) -> str: if x > 0 and y > 0: return('I') elif x > 0 and y < 0: return('IV') elif x < 0 and y > 0: return('II') else: return('III')
d433bdf74283b1962b43b0d8f1a52316ff430c0a
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_187.py
477
3.59375
4
from typing import Union # a def add_hundr(nums:list) -> list: new_list = list(100,) new_list += nums return(new_list) # b def add_any(nums:list, n:Union[int, float]) -> list: new_list = list(n) new_list += nums return(new_list) # c def add_any_to_any_place(nums:list, ...
071d060124d5d70d8740855f9ad37a4b72be62d3
bakunobu/exercise
/1400_basic_tasks/chap_4/4_99.py
215
3.609375
4
# a def which_bigger(a:float, b:float) -> float: if a > b: return(a) if b > a: return(b) # b def which_bigger(a:float, b:float) -> float: if a > b: return(a) return(b)
a7681c1f46b63a681c59f7d052e11850177112a1
bakunobu/exercise
/python_programming /Chapter_1.1_and_1.2/day_of_a_week.py
1,311
4.34375
4
""" Составьте программу, получающую дату и выводящую день недели, выпадающий на эту дату. Программа должна получать три аргу­мента командной строки: m (месяц), d (день) и у (год). Значение 1 перемен­ной m соответствует январю, 2 -февралю и т.д. В вы воде О соответствует воскресенью, 1 -понедельнику, 2 -вторнику и т.д....
b3a6a36c34325640f6e9173608743e12f4a3d1a9
bakunobu/exercise
/1400_basic_tasks/chap_4/4.10.py
271
3.734375
4
def foot_to_m(f:float) -> float: return(f * 0.3048) def foot_to_km(f:float) -> float: m = foot_to_m(f) return(m / 1000) def which_bigger(km:float, f:float) -> float: km_2 = foot_to_km(f) if km > km_2: return(km) else: return(f)
66f2a6842848ebb67eec5a996812fb4b06eef830
bakunobu/exercise
/1400_basic_tasks/chap_5/5_22.py
702
3.984375
4
def get_input() -> float: while True: a = input('Введите стоимость 1 кг конфет: ') try: a = float(a) return(a) except ValueError: print('Пожалуйста, используйте числа') def calc_cost(x: float) -> tuple: r = int(x) kop = x - r r...
475157af7b73019dc2a8c6faeb1c41ed898fe49a
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_179.py
286
3.703125
4
def manual_sort(results:list) -> list: i = 0 result = results.pop(0) while i < len(results) - 1: if result > results[i]: i += 1 else: results.insert(i, result) return(results) results.append(result) return(results)
83f3db501f343ef0dc98ec2056d4b9a4c71d9af5
bakunobu/exercise
/1400_basic_tasks/chap_9/ex_9_53.py
332
3.53125
4
def first_cubes_sum(): cubes = [i ** 3 for i in range(1, 100)] for a in cubes: for b in cubes: for c in cubes: for d in cubes: if a + b == c + d: if len(set((a, b, c, d))) == 4: return(a+b) print(first_...
4f2c56826edd5d63096b1fedf4afdc3744011613
bakunobu/exercise
/1400_basic_tasks/chap_8/ex_8_10.py
1,024
4.0625
4
""" Упражнение сломанное, так как получим бесконечно убывающую последовательность c lim=1. Можно предположить, что есть некоторое n, обозначающее нижнюю границу (знеменатель дроби). Тогда задание имеет смысл. """ from fractions import Fraction def calc_part(n:int=100) -> None: while True: try: ...
440d13f2f8d92d32f3fe7bd186f6933d5f1d20ab
bakunobu/exercise
/1400_basic_tasks/chap_6/6_34.py
148
3.546875
4
def mut_prime(m:int, n:int) -> None: i = min(m, n) while i < m * n: i += 1 if i % m == 0 or i % n == 0: print(i)
953e56d721a811313a3e6c6c76457680f0930ccd
bakunobu/exercise
/1400_basic_tasks/chap_4/4_110.py
240
3.59375
4
def how_many_pos(a:float, b:float, c:float, d:float) -> int: counter = 0 if a >= 0: counter += 1 if b >= 0: counter += 1 if c >= 0: counter += 1 if d >= 0: counter += 1 return(counter)
09bf60fd6a939199a86cb4db26fe413f2d10d2eb
bakunobu/exercise
/1400_basic_tasks/chap_7/7_68.py
351
3.53125
4
from main_funcs import get_input def equal_seq(n: int) -> int: a = get_input('Введите число: ', False) b = get_input('Введите число: ', False) i = 0 counter = 0 while a == b and i < n: i += 1 b = get_input('Введите число: ', False) counter += 1 return(counter)
df919dc2506b7ea04eeb10a5e1fa522a29067d10
bakunobu/exercise
/1400_basic_tasks/chap_9/ex_9_44.py
1,040
3.546875
4
def count_value(a:int, b:int, c:int, d:int, e:int, f:int, g:int, h:int, i:int, j:int) -> int: return(a+2*b+3*c+5*d+10*e+12*f+14*g+15*h+20*i+30*j) def count_vars(v:int) -> int: v = v // 100 counter = 0 for a in range(0, v // 1 + 1): for b in range(...
ec47791d31f5e1fe4967f2eca4b23d30a93c3b15
bakunobu/exercise
/1400_basic_tasks/chap_7/7_168.py
694
3.6875
4
from main_funcs import get_input def which_earlier(n:int) -> str: max_ind = 0 min_ind = 0 max_num = False min_num = False for i in range(n): x = get_input('Введите возраст: ', False) if not max_num: max_num = x max_ind = i if not min_nu...
4b3f25c2be116a1d780e7966b24510011edc46db
bakunobu/exercise
/1400_basic_tasks/chap_11/ex_11_134.py
150
3.703125
4
def which_earlier(nums:list) -> str: if nums.index(max(nums)) > nums.index(min(nums)): return('Oldes') else: return('Yongest')