text
stringlengths
5
121k
class Salary: def __init__(self, pay): self.pay = pay def getTotal(self): return (self.pay * 12) class Employee: def __init__(self, name, pay, bonus): self.name = name self.bonus = bonus self.salary = Salary(pay) def annualSalary(self): ...
def greet(* names): """this function greets the person in names tuple.""" for name in names: print("Hi... " + name) greet("Ram", "Ali", "Sam", "Jak")
class Emp: org = "InfoSys" def __init__(self): pass def set_no(self, no): self.no = no def set_name(self, name): self.name = name def set_sal(self, sal): self.sal = sal def get_no(self): return self.no def get_name(self): return self.name def get_sal(self): return self.sal @clas...
import time ns_list = list() for i in range(10): time_now_ns = time.time_ns() ns_list.insert(i, time_now_ns) if 0 < i and i < 10: print("Current NS:", ns_list[i], "| Previous NS:", ns_list[i - 1], "| Difference:", ns_list[i] - ns_list[i - 1])
import random item = random.randrange(9) item_list = [item for item in range(9)] item_list_len = len(item_list) item_iter = iter(item_list) for _ in range(item_list_len): print(next(item_iter)) for item in item_list: print(item) item_iter = iter(item_list) for _ in range(item_list_len): prin...
import time """ for i in range(9): sns = time.time_ns() print(time.time_ns() - sns) """ for i in range(9): print(abs(time.time_ns() - time.time_ns()))
def sum(a, b): a = int(a) b = int(b) return a + b a = int(2) b = int(3) print(sum(a, b))
def myfunc(word): result = "" index = 0 for letter in word: if index % 2 == 0: result += letter.lower() else: result += letter.upper() index += 1 return result
bangla = int(input("Enter Your Bangla Exam score :")) english = int(input("Enter Your English exam's score: ")) math=int(input(" Enter your Math exam's score:")) average=(bangla + english + math)/3 print("Avearge is: ", average) if (average <=100) and (average >=80): print("You got A+") elif (average <=79) and (a...
"""-------------------------------------------- ------- Binary Search Tree -------------------- --------------------------------------------""" class Node(): def __init__(self,data): self.data = data self.left_child = None self.right_child = None class BS_tree: def __init__(se...
"""-------------------------------------------------------------------- -->Take a range of 0 - 1000 Numbers and find the Prime numbers in that --range. Store the prime numbers in a 2D Array, the first dimension --represents the range 0-100, 100-200, and so on. While the second --dimension represents the prime numbers ...
import string import re PUNCTUATION_CHARS = list(string.punctuation) used_passwords = set('PassWord@1 PyBit$s9'.split()) def validate_password_1(password): if len(password) < 6 or len(password) > 12: return False if not any(elem in password for elem in string.ascii_lowercase): return False ...
''' ### Class Attributes ''' ''' As we saw, when we create a class Python automatically builds-in properties and behaviors into our class object, like making it callable, and properties like `__name__`. ''' class Person: pass print(Person.__name__) ''' `__name__` is a **class attribute**. We can add our o...
INDENTS = 4 poem = """Remember me when I am gone away, Gone far away into the silent land; When you can no more hold me by the hand, Nor I half turn to go yet turning stay. Remember me when no more day by day You tell me of our future that you planned: Only remember me; you understand""" ''' TO: Remember me when I ...
''' Here is a Bite to practice the continue and break statements in Python. Complete filter_names that takes a list of names and returns a filtered list (or generator) of names using the following conditions: names that start with IGNORE_CHAR are ignored, names that have one or more digits are ignored, if a name star...
try: open('/path/to/does/not/exist', 'rb') except (SystemExit, KeyboardInterrupt): raise except Exception as exception: logger.error('Failed to open file', exc_info=True)
import types from itertools import islice def group(iterable, n): """Splits an iterable set into groups of size n and a group of the remaining elements if needed. Args: iterable (list): The list whose elements are to be split into groups of size n. n (int...
import copy class Memento(object): def __init__(self, data): for attribute in vars(data): setattr(self, attribute, copy.deepcopy(getattr(data, attribute))) class Undo(object): def __init__(self): self.__last = None def save(self):...
class Solution(object): """ Clear explanation is here: https://leetcode.com/discuss/67687/c-o-nlogn-solution-with-explainations-4ms https://leetcode.com/discuss/67643/java-python-binary-search-o-nlogn-time-with-explanation The key to the solution is: build a ladder for numbers: dp. dp[i]: ...
class Squares: def __init__(self, length): self.length = length self.i = 0 def next_(self): if self.i >= self.length: raise StopIteration else: result = self.i ** 2 self.i += 1 return result def __len__(self): retur...
""" Object oriented programming is used to help conceptualise the interactions between objects. I wanted to give you a couple more examples of classes, and try to answer a few frequent questions. """ class Movie: def __init__(self, name, year): self.name = name self.year = year """ Parameter na...
class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 node_list = [root] depth_count = 1 while node_list: nod...
class Memento: def __init__(self, balance): self.balance = balance class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): self.balance += amount return Memento(self.balance) def restore(self, memento): self.balance...
def reverse_string_words(text): for line in text.split('\n'): return(' '.join(line.split()[::-1])) print(reverse_string_words("The quick brown fox jumps over the lazy dog.")) print(reverse_string_words("Python Exercises."))
import sqlite3 db = sqlite3.connect('mydb.db') cursor = db.cursor() newphone = '7113093164' userid = 1 cursor.execute('''UPDATE users SET phone = ? WHERE id = ? ''', (newphone, userid)) delete_userid = 2 cursor.execute('''DELETE FROM users WHERE id = ? ''', (delete_userid,)) db.commit() db.cl...
from typing import List def jagged_list(lst_of_lst: List[List[int]], fillvalue: int = 0) -> List[List[int]]: if not lst_of_lst: return lst_of_lst max_length = max(len(l) for l in lst_of_lst) for l in lst_of_lst: l.extend([fillvalue] * (max_length - len(l))) return lst_of_lst ...
def divide(a, b): try: total = a / b except TypeError: return "Please provide two integers or floats" except ZeroDivisionError: return "Please do not divide by zero" return total
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()) class Mov...
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...
from enum import Enum class AnimalEnum(Enum): HORSE = 1 COW = 2 CHICKEN = 3 DOG = 4 print(AnimalEnum.CHICKEN) print(repr(AnimalEnum.CHICKEN)) AnimalEnum.CHICKEN.name AnimalEnum.CHICKEN.value for animal in AnimalEnum: print('Name: {} Value: {}'.format(animal, animal.value...
from enum import Enum THUMBS_UP = '👍' 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...
def hello_world(): print('Hello, world!') hello_world() hello2 = hello_world hello2() def log_decorator(func): def wrap(): print(f'Calling func {func}') func() print(f'Func {func} finished its work') return wrap def hello(): print('hello, world!') ...
class Person: name = "" age = 0 def __init__(self, person_name, person_age): self.name = person_name self.age = person_age def show_name(self): print(self.name) def show_age(self): print(self.age) class Student(Person): studentId = ""...
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(l...
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 n...
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) l = [1, 2, 3, 4] lists = tee(l, 2) lists[0] lists[1] ...
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) * '*'...
import unittest 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 fixtur...
def calculateTotal(): subtotal = calculateSubtotal() discount = 0 if subtotal > 100: discount = subtotal * 0.1 total = subtotal - discount return total def calculateSubtotal(): pass def calculateTotal(): subtotal = calculateSubtotal() discount = calculateDiscount(sub...
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.wee...
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 total_donations = sum(donation for donation in donations.values()) total_donations = sum(donations.values())
def some_list(x): for i in range(x): for j in range(i): yield (i+1)*(j+1) print(list(some_list(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.x...
str = "abcbb" def longest_non_repeat(str): i=0 max_length = 1 for i,c in enumerate(str): start_at = i sub_str=[] while (start_at < len(str)) and (str[start_at] not in sub_str): sub_str.ap...
""" 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 ... """ input = [] def my_sum_numbers(numbers=None): result = 0 ...
month = input("What's the name of the 12th month of the calendar year?")
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[...
__author__ = 'sergejyurskyj' L1 = [1, ('a', 3)] L2 = [1, ('a', 3)] print(L1 == L2, L1 is L2) 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: ...
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 """ numlis...
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()
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) ...
import abc class parent: def geeks(self): pass class child(parent): def geeks(self): print("child class") print(issubclass(child, parent)) print(isinstance(child(), parent))
import os trash_dir = 'my_documents/bad_dir' try: os.rmdir(trash_dir) except OSError as e: print(f'Error: {trash_dir} : {e.strerror}') 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.str...
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: ...
import re text = 'The quick brown fox jumps over the lazy dog.' print(re.findall(r"\b\w{5}\b", text))
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)
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 self.index = len(iterable_object) def __iter__(self): return self def ...
print('#' * 52 + ' Length: number of items') print(len('abc')) print('#' * 52 + ' Concatenation: a new string') print('abc' + 'def') print('#' * 52 + ' Repetition: like "Ni!" + "Ni!" + ...') print('Ni!' * 4) print('#' * 52 + ' 80 dashes, the hard way') print('------- ...more... ---') print('#' * 52 + ' 80 d...
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""" ...
class SavingsAccount: def __init__(self, owner, acc_number): self.owner = owner self._acc_number = acc_number self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance - amount >= 0: self.bal...
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....
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)
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....
import sqlite3 def writeTofile(data, filename): with open(filename, 'wb') as file: file.write(data) print("Stored blob data into: ", filename, "\n") def readBlobData(empId): try: sqliteConnection = sqlite3.connect('SQLite_Python.db') cursor = sqliteConnection.cursor() ...
class Solution(object): allNQueens = [] def solveNQueens(self, n): self.allNQueens = [] self.cols = [True] * n self.left_right = [True] * (2 * n - 1) self.right_left = [True] * (2 * n - 1) queueMatrix = [["."] * n for row in range(n)] self.solve(0, queueMatri...
import psycopg2 con = psycopg2.connect(database='testdb', user='syurskyi', password='1234') with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS words") cur.execute("CREATE TABLE words(id SERIAL PRIMARY KEY, word VARCHAR(255))") cur.execute("INSERT INTO words(word...
car_brands = ['Mazda', 'McLaren', 'Opel', 'Toyota', 'Honda'] def convert_to_tuple(car_brands): static_cars = tuple(car_brands) return static_cars def print_tuples(car_brands): car_brands = convert_to_tuple() if car_brands: print(car_brands) return
def get_first_name(self): return self.first_name def get_last_name(self): return self.last_name def get_middle_name(self): return self.middle_name def init(self, first_name, last_name, middle_name): self.first_name = first_name self.last_name = last_name self.middle_name = middle_name cl...
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() min_distance = 2 ** 31 - 1 length = len(nums) solution = 0 for i in range(length-2): ...
from collections import namedtuple from bs4 import BeautifulSoup as Soup import requests PACKT = 'https://bites-data.s3.us-east-2.amazonaws.com/packt.html' CONTENT = requests.get(PACKT).text Book = namedtuple('Book', 'title description image link') def get_book(): """make a Soup object, parse the relevant html...
def insertionSort(nlist): for index in range(1,len(nlist)): currentvalue = nlist[index] position = index while position>0 and nlist[position-1]>currentvalue: nlist[position]=nlist[position-1] position = position-1 nlist[position]=currentvalue nlist = [14,46,43,27...
import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def divide(x, y): try: out = x / y except ZeroDivisionError: logger.exception("Division by zero problem") else: return out logger.error("Divide {x} / {y} = {c}".format(x=10, y=0, c=divide(...
import calendar def weekday_of_birth_date(date): """Takes a date object and returns the corresponding weekday string""" return calendar.day_name[date.weekday()]
class Solution(object): def maximalRectangle(self, matrix): """ :type matrix: List[list[str]] :rtype: int """ if not matrix: return 0 m_rows = len(matrix) n_cols = len(matrix[0]) process_matrix = [ [0 for col in ...
class Player: def __init__(self, name, is_dealer=False): self._name = name self._hand = [] self._is_dealer = is_dealer @property def name(self): return self._name @property def is_dealer(self): ...
numberList = [1, 2, 3] strList = ['one', 'two', 'three'] result = zip() print(result) resultList = list(result) print(resultList) result = zip(numberList, strList) print(list(result))
class Solution: def addBinary( a, b): length = max(len(a),len(b)) + 1 sum = ['0' for i in range(length)] if len(a) <= len(b): a = '0' * ( len(b) - len(a) ) + a if len(a) > len(b): b = '0' * ( len(a) - len(b) ) + b Carry = 0 i = len(a) - ...
answer = [val for val in [1, 2, 3, 4] if val in [3, 4, 5, 6]] answer2 = [val[::-1].lower() for val in ["Elie", "Tim", "Matt"]] answer = [] for x in [1,2,3,4]: if x in [3,4,5,6]: answer.append(x) answer2 = [] for name in ["Elie", "Tim", "Matt"]: answer2.append(name[::-1].lower())
l = [1, 2, 3] iter_l = iter(l) type(iter_l) next(iter_l) next(iter_l) next(iter_l) '__iter__' in dir(l) '__getitem__' in dir(l) d = dict(a=1, b=2, c=3) iter_d = iter(d) next(iter_d) iter_vals = iter(d.values()) next(iter_vals) iter_items = iter(d.items()) next(iter_items) class CyclicIterator: de...
def sum(n, func): total = 0 for num in range(1, n+1): total += func(num) return total def square(x): return x*x def cube(x): return x*x*x print(sum(3, cube)) print(sum(3, square))
class InformalParserInterface: def load_data_source(self, path: str, file_name: str) -> str: """Load in the file for extracting text.""" pass def extract_text(self, full_file_name: str) -> dict: """Extract text from the currently loaded file.""" pass class PdfP...
a = [1, 2, 3] zipped = zip(a) list(zipped) integers = [1, 2, 3] letters = ['a', 'b', 'c'] floats = [4.0, 5.0, 6.0] zipped = zip(integers, letters, floats) list(zipped)
from test_sentences import * import re def capitalize_sentences(text: str) -> str: """Return text capitalizing the sentences. Note that sentences can end in dot (.), question mark (?) and exclamation mark (!)""" text_metacharacters = re.findall("[\\!\\.\\?]", text.strip()) text_raw = re.split("[\\!\\.\...
import string import itertools def sequence_generator(): numbers = list(range(1,27)) sequence = [numbers[i//2] if i % 2 == 0 else string.ascii_uppercase[i//2] for i in range(52)] yield from itertools.cycle(sequence) if __name__ == "__main__": sequence_generator()
class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ if not matrix: return [] m = len(matrix) n = len(matrix[0]) first...
RightPyramid.__mro__ class RightPyramid(Square, Triangle): def __init__(self, base, slant_height): self.base = base self.slant_height = slant_height super().__init__(self.base) def area(self): base_area = super().area() perimeter = super().perimeter() ...
class JsObject(dict): """A Python dictionary that provides attribute-style access just like a JS object: obj = JsObject() obj.cool = True obj.foo = 'bar' Try this on a regular dict and you get AttributeError: 'dict' object has no attribute 'foo' """ def __init_...
lst = [1, 2, 3] repr(lst) print(lst) eval(repr(lst)) == lst from datetime import datetime dt = datetime.now() repr(dt) print(dt) class Character(): def __init__(self, race, damage = 100): self.race = race self.damage = damage def __repr__(s...
from typing import Dict, Tuple, List def generate_tuple(data) -> list: result = [] for key, value in data.values(): result.append((key, value)) return result test_data1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} test_data2 = {'k1': 'v1', 'k2': 'v2', 'k3': 10} test_data3 = {'k1': 'v1', 'k2': 'v2', 'k...
class Solution(object): def gameOfLife(self, board): if not board: return m_rows = len(board) n_cols = len(board[0]) count = [[0 for j in range(n_cols)] for i in range(m_rows)] for i in range(m_rows): for j in range(n_cols): ...
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] x = mycol.find_one() print(x)
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 26, Because nums[0] + nums[1] = 11 + 15 = 26...
rec = {} rec['name'] = 'mel' rec['age'] = 45 rec['job'] = 'trainer/writer' print(rec['name']) class rec: pass rec.name = 'mel' rec.age = 45 rec.job = 'trainer/writer' print(rec.age) class rec: pass pers1 = rec() pers1.name = 'mel' pers1.job ...
from pytz import timezone, utc from datetime import datetime AUSTRALIA = timezone('Australia/Sydney') SPAIN = timezone('Europe/Madrid') def what_time_lives_pybites(naive_utc_dt): """Receives a naive UTC datetime object and returns a two element tuple of Australian and Spanish (timezone aware) datetimes"""...
class Solution(object): def searchInsert(self, nums, target): return len([x for x in nums if x < target]) class Solution_2(object): def searchInsert(self, nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) / 2 if tar...
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ max_length = 0 start = 0 end = 0 char_dict = {} for index in range(len(s)): char = s[index] if ch...
''' ### 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 d...
import abc class PluginBase(abc.ABC): @abc.abstractmethod def load(self, input): """Retrieve data from the input source and return an object. """ @abc.abstractmethod def save(self, output, data): """Save the data object to the output.""" class SubclassImplemen...
class Solution: """ @param k: an integer @param prices: a list of integer @return: an integer which is maximum profit """ def maxProfit(self, k, prices): if prices is None or len(prices) <= 1 or k <= 0: return 0 n = len(prices) if k >= n / 2: ...
import pandas data = pandas.read_csv("countries_by_area.txt") data["density"] = data["population_2013"] / data["area_sqkm"] data = data.sort_values(by="density", ascending=False) for index, row in data[:5].iterrows(): print(row["country"])