text
stringlengths
5
121k
import turtle import sparse import matrix import random def showMatrix(turtle_object,m,n): screen = turtle.getscreen() screen.tracer(0) value = 1 x = 0 m = matrix.matrix(n,0) while x <= n: x = x + 1 num1 = random.randint(0,n-1) num2 = random.randint(0,n-1) m[num1...
def reverse(string): list = [character for character in string] x = 0 n = -1 while x <= ((len(list))/2)-1: a = list[x] b = list[n] list[x] = b list[n] = a x = x + 1 n = n - 1 stringFinal = "" for letter in list: stringFinal += letter re...
def altSum(values): sum = 0 for i in range(1,(len(values) + 1),2): sum = sum + (int(values[i]) - int(values[(i - 1)])) return sum def main(): values = [] num = "0" while num != "": values.append(num) num = input("Enter a floating point value: ") answer = str(altSum(v...
from common import show @show def find_longest_word(list_): if not list_: raise RuntimeError("List shouldn't be none or empty") max_length = len(list_[0]) for i in xrange(1, len(list_)): if len(list_[i]) > max_length: max_length = len(list_[i]) return max_length assert fi...
from common import show @show def for_loop(list_): res_list_ = [] for i in list_: res_list_.append(len(i)) return res_list_ @show def map_(list_): return map(len, list_) @show def list_comprehension(list_): return [len(i) for i in list_] list_ = ["a", "bb", "ccc"] assert for_loop(lis...
from common import show @show def max(a, b): return a if a >= b else b assert max(1, 3) == 3 assert max(3, 1) == 3 assert max(2, 2) == 2
class Solution: def lookup(self, root: TreeNode, x: int): if (root == None): return -999999 elif (root.val == x): return 0 else: leftheight = self.lookup(root.left, x)+1 rightheight = self.lookup(root.right, x)+1 return max(...
import pandas as pd import hashlib import csv class User: def __init__(self, username, password): self.password = password self.username = username @staticmethod def log_in(): file_path = "account.csv" def_account = pd.read_csv(file_path) lst_username...
import math height = 10 width = 20 rectangle_square = height * width print("Площадь прямоугольника:", rectangle_square) radius = 5 circle_square = math.pi * (radius**2) print("Площадь круга:", round(circle_square, 2)) print(type(circle_square)) catheter1 = 5 catheter2 = 6 hypotenuse = math.sqrt(catheter1**2 ...
class Fruit: count = 0 totalQuantity= 0 def __init__(self,name,quantity): self.name = name self.quantity = quantity Fruit.count += 1 Fruit.totalQuantity += quantity def __del__(self): Fruit.count -= 1 Fruit.totalQuantity -= self.quantity def __str__...
from collections import Counter def verify_anagrams(x, y): return True if Counter(a.lower() for a in x if a.isalpha()) == \ Counter(b.lower() for b in y if b.isalpha()) else False if __name__ == '__main__': assert isinstance(verify_anagrams("a", 'z'), bool), "Boolean!" assert verify_anagrams("Pro...
def seconds_to_hms(seconds): h, mins = divmod(seconds, 3600) m, s = divmod(mins, 60) return '{:0>2}:{:0>2}:{:0>2}'.format(h, m, s) def to_seconds(time, t_value=None): if isinstance(time, str): return sum(int(a) * b for a, b in zip(time.split(':'), (3600, 60, 1))) if t_value.startswith('sec...
def checkio(lst): length = len(lst) lst = sorted(lst) if length % 2 == 0: mid = int(length / 2) return (lst[mid] + lst[mid-1]) / 2 return lst[int(length / 2)] if __name__ == '__main__': assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list" assert checkio([3, 1, 2, 5, 3]) == 3, "No...
from itertools import zip_longest def checkio(text, word): def result(start, line_num, horizontal=True): if horizontal: return [line_num, start + 1, line_num, start + len(word)] return [start + 1, line_num, start + len(word), line_num] horizontal = list() for dex, line in enum...
def find_cycle(connections): d = dict() for a, b in connections: try: d[a].add(b) except KeyError: d[a] = {b} print(d) find_cycle(((1, 2), (2, 3), (3, 4), (4, 5), (5, 7), (7, 6), (8, 5), (8, 4), (8, 1), (1, 5), (2, 4))) ...
class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ return [list(line) for line in zip(*A)] ''' # my Solution class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rty...
import math import random __all__ = ['random_poisson'] def random_poisson(rate, rng=random): """Sample a random value from a Poisson distribution. This implementation is done in pure Python. Using PyTorch would be much slower. References: - https://www.wikiwand.com/en/Poisson_distribution#/Gen...
import requests import parsel def get_http(myurl): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' } response=requests.get(myurl,headers=headers) data=response.text data.encode("UTF-8") ...
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) '''...
import random
def sayHello(name = 'Human Person'): print(f'Hello {name}') sayHello('Bob') sayHello() def getSum(num1, num2): total = num1 + num2 return total getSum(25, 5) getNone = lambda num1, num2 : num1 - num2 none = getNone(10, 3) print(none)
import timeit def benchmark(sort_fun): length_exponents = [1, 2, 3, 4, 5, 6, 7] repetitions = 10 for exponent in length_exponents: length = 10 ** exponent res = benchmark_length(sort_fun, length, repetitions) print(f'Sorting {repetitions} lists of length 10^{exponent} took {res} seconds.') def benc...
a = input("input a number:\n") print(a*a)
def cipher_encrypt(plain_text, key): encrypted = "" for c in plain_text: if c.isupper(): c_index = ord(c) - ord('A') c_shifted = (c_index + key) % 26 + ord('A') c_new = chr(c_shifted) encrypted += c_new ...
from pygrid import PyGrid import math class DrawGrid(PyGrid): def __init__(self, draw_buttons=None, *args, **kwargs): PyGrid.__init__(self, *args, **kwargs) if draw_buttons is None: self._draw_buttons = [1] else: self._draw_buttons = draw_buttons self...
import _thread import threading import time def _thread_handle(thread_name, delay): for num in range(10): time.sleep(delay) print("{}的num:{}".format(thread_name, num)) def threading_handle(delay=1): for num in range(10): time.sleep(delay) print("{}-num-{}".format(threading.cu...
""" Created on Mon Sep 13 16:43:13 2021 @author: pc """ T=int(input()) for i in range(T): id=input() if(id=='B' or id=='b'): print("BattleShip") elif(id=='C' or id=='c'): print("Cruiser") elif(id=='D' or id=='d'): print("Destroyer") else: print("Frigate") ...
""" Created on Mon Sep 13 11:23:00 2021 @author: pc """ T=int(input()) for i in range(T): N=input().split(" ") A=int(N[0]) B=int(N[1]) C=int(N[2]) if((A+B+C)==180): print("YES") else: print("NO")
""" Created on Thu Sep 9 23:29:54 2021 @author: pc """ T=int(input()) for i in range(T): temp=input().split(" ") N=list() N.append(int(temp[0])) N.append(int(temp[1])) N.append(int(temp[2])) N.sort() print(N[1])
""" The neopixel module lets you use Neopixel (WS2812) individually addressable RGB LED strips with the Microbit. Note to use the neopixel module, you need to import it separately with: import neopixel Note From our tests, the Microbit Neopixel module can drive up to around 256 Neopixels. Anything above that and yo...
''' Sam Minix 5/28/2020 https://www.reddit.com/r/dailyprogrammer/comments/98ufvz/20180820_challenge_366_easy_word_funnel_1/ Given two strings of letters, determine whether the second can be made from the first by removing one letter. The remaining letters must stay in the same order. ''' def word_funnel1 (str1, str2): ...
def find_all(string, substr): '''Find all the indexs of substring in string.''' i = -1 result = [] while True: i = string.find(substr, i+1) if i < 0: break result.append(i) return result if __name__ == '__main__': string = input('Please inp...
n = int(input("Enter an integer to create a dictionary: ")) dictionary1 = {} for i in range(1, n+1): dictionary1[i] = i*i i += 1 print(dictionary1)
class HashMap: def __init__(self): self.size = 10 self.map = [None] * self.size def _get_hash(self, key): if type(key) == int: return key % 10 if type(key) == str: return len(key) % 10 if type(key) == tuple: return len(key) % 10 def add(self, key, value): hashed_key = self._get_hash(key) ...
from decimal import Decimal def main(): x = Decimal(".20") y = Decimal(".60") a = x + x + x - y print(f"a is {a}") print(type(a)) if __name__ == "__main__": main()
pwd = "octopus" res = "" user_auth = False attempt = 0 max_attempts = 3 while res != pwd: attempt += 1 if attempt > max_attempts: break res = input("Enter the password:") else: user_auth = True print("Successfully logged in" if user_auth else "try again in one hour..")
import numpy as np import pandas as pd from pandas.core.frame import DataFrame from constants import dataColumn, bacteriaValues def dataLoad(filename: str) -> DataFrame: """Loads data from a space separated values file Keyword arguments: filename: str -- The name of the file to be loaded Returns: ...
def count_a(name): try: f = open(name) text = f.read() except: return 0 f.close() counter = 0 for i in text: if i == 'a': counter += 1 return counter print(count_a('test.txt'))
import pygame from pygame.sprite import Group from settings import Settings from ship import Ship from alien import Alien import game_functions as gf def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) ...
def fib2(n): """Return a list containing the Fibonacci series up to n.""" result = [] a,b = 0,1 while a < n: result.append(a) a,b = b,a+b return result
from abc import ABC, abstractmethod from typing import Tuple import numpy as np class Trajectory(ABC): @abstractmethod def move(self, max_move_dist) -> (Tuple[float, float], float): """Move the point along the trajectory towards its target by the specified distance. If the point woul...
""" Author: Nan <xnone0104@gmail.com> https://projecteuler.net/problem=15 [Lattice paths] Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? """ def count_...
class Hero: def __init__(self, name, armor, health): self.name = name self.__armor = armor self.__health = health @property def info(self): return "name {} : \n\thealth {} \n\tarmor {}".format(self.name, self.__health, self.__armor) @property def armor(self): ...
def bio(name,born,pronoun): age = 2021-born future = born+67 print("----------------------------------------") print(name.capitalize(), "was born in", born) print(pronoun.capitalize(), "will turn", age, "years old this year") print(pronoun.capitalize(), "will be 67 in the year", future) pri...
def even(n): return n % 2 == 0 def fib(n): def fib_iter(a,b,p,q,count): if count == 0: return b elif even(count): return fib_iter(a,b,p*p + q*q,2*p*q + q*q,count / 2) else: return fib_iter(b*q + a*q + a*p,b*p + a*q,p,q,count-1) return fib_iter(1,0...
n=int(input("enter the n'th number:")) def fibonacci(n): if n <= 1: return n else: return(fibonacci(n-1) + fibonacci(n-2)) print("N'th fibonacci number is ",fibonacci(n))
def simple_interest(p,r,t): if p==0 or r==0 or t==0: return 0 else: simple_interest=(p*r*t)/100 return simple_interest p=int(input("enter the value of p: ")) r=int(input("enter the value of r: ")) t=int(input("enter the value of t: ")) print("simple_interest is ",simple_interest(p,r,t))
n=int(input("enter the n'th natural number:")) def squareSum(n): sum=0 for n in range(1,n+1): sum+=(n*n) return sum print("Sum of squares of first n entered natural numbers is",squaresum(n))
""" Implementation of Softmax layer """ import numpy as np class Softmax: def forward(self, inputArray): ''' This function calculates the exponential of all inputs and the sum of the exponentials. Finally, it returns the ratio of the exponential of the inputs a...
class Queue(): def __init__(self): self.queue = [] def isEmpty(self): return self.queue == [] def Enq(self, item): self.queue.append(item) def Deq(self): data = self.queue[0] del self.queue[0] ...
def parse_string(text): output = u'' for char in text: modifiers = u'' if char == u'@': char = u'AT' elif char == u'"': char = u'DOUBLE QUOTE' elif char == u"'": char = u'QUOTE' elif char == u",": char = u'COMMA' elif char == u'.': char = u'NUMPAD .' elif ...
def main(): print("This program illustrates a chaotic function") x = eval(input("Enter a number between 0 and 1: ")) for i in range(10): x = 3.9 * x * (1 - x) print(x) main()
number = int(input("Please enter an Integer number.")) number_sum = 0 print("Entered number by the user is: " + str(number)) while number > 0: number_sum = number_sum + number number = number - 1 print("Sum of the numbers from the entered number and 1 is: " + str(number_sum))
amount = float(input("Please enter the Principal Amount.")) rate = float(input("Please enter the Rate of Interest.")) time = float(input("Please enter the Time Period in Years.")) def simple_interest_cal(para_amo, para_rate, para_time): simple_interest = (para_amo * para_rate * para_time) / 100 print("The Sim...
user_string = input("Please enter a String.") number_of_characters = 0 for letter in user_string: number_of_characters = number_of_characters + 1 print(user_string) print("The number of characters in the input string is: " + str(number_of_characters))
''' Given an undirected graph, determine if a cycle exists in the graph. Can you solve this in linear time, linear space? ''' def find_cycle_helper(graph, reached): if (graph == {}): return False result = False for key in graph.keys(): if (key in reached): return True...
''' You are given an array of integers. Return the largest product that can be made by multiplying any 3 integers in the array. Example: [-4, -4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128. ''' def maximum_product_of_three(lst): lst.sort() cand1 =...
''' Implement a class for a stack that supports all the regular functions (push, pop), and an additional function of max() which returns the maximum element in the stack (return None if the stack is empty). Each method should run in constant time. ''' class MaxStack: def __init__(self): self.stack ...
''' Implement a queue class using two stacks. A queue is a data structure that supports the FIFO protocol (First in = first out). Your class should support the enqueue and dequeue methods like a standard queue. ''' class Queue: def __init__(self): self.head = [] self.stack = [] def ...
import functools def my_decorator(func): @functools.wraps(func) def function_that_runs_func(*args, **kwargs): print("in the decorator") func(*args, **kwargs) print("after the decorator") return function_that_runs_func @my_decorator def my_function(x,y): print(x+y) my_funct...
import random class Board: """A board is defined as a designated playing surface. The responsibility of Board is to keep track of the pieces in play. Stereotype: Information Holder Attributes: """ def __init__(self): self._piles_list = [] self._prepare() ...
""" Created on Sat Dec 7 18:18:24 2019 @author: Ayham """ import sqlite3 from tkinter import * from tkinter import scrolledtext from time import strftime root = Tk() root.title('Project3') conn = sqlite3.connect('OrgDB.db') print("Opened database succuessfully") conn.execute('''CREATE TABLE...
from utils import print_result def bisection(eq, a, b, eps=10e-10): solve = lambda x: eq.s(x) cnt = 1 print('Bisection method: {}'.format(eq.get_name())) if solve(a) * solve(b) > 0: raise RuntimeError('Cannot solve in bisection method') while abs(b - a) >= eps: c = (a + b) / 2 ...
from math import e, sin, cos, log class Equation: def __init__(self): self.term = [] def s(self, x): raise NotImplementedError def sd(self, x): raise NotImplementedError def fp(self, x): raise NotImplementedError def bound(self): raise Not...
""" Created on Sun Mar 31 02:42:19 2019 @author: Kunal Aggarwal """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,:-1].values Y = dataset.iloc[:,-1].values X_train , X_test , Y...
age = input('your age is:') age = int(age) if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid') names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) print(list(range(4))) index = 0 len = len(names) while index < len: if index > 1: ...
email = input("what is your email address? ").strip() user = email[:email.index("@")] domain = email[email.index("@") + 1:] string = '''your username is "{}" and your domain name is "{}"''' output = string.format(user,domain) print(output)
flims ={ "Sanju":[20,5], "Padmabati":[18,7], "Antman":[3,6], "Tarzan":[10,5] } while True: choice= input("which movie u want to watch?").strip().title() if choice in flims: age = int(input("how old are you?:").strip()) if age >=flims[choice][0]: ...
""" Created on Tue Mar 3 16:45:16 2020 @author: nenad """ """ Partition: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see b...
""" Created on Sat Feb 29 19:40:20 2020 @author: nenad """ ''' URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Ja...
""" Group of functions for handling the communication with the database """ import sqlite3 DB = "db/data.db" def conn_db(func): def tmp(*args, **kwargs): conn = sqlite3.connect(DB) cursor = conn.cursor() func(cursor, *args, **kwargs) conn.commit() conn.close() return tm...
number = input() def factorial(n): if n == 0: return 1 fact = 1 for i in range(1,n+1): fact=fact*i return fact print(factorial(int(number)))
string1 = "Hello I hope you are having a nice day!".count(' ') print('count of spaces in string1 is {}'.format(string1.count(' ')))
class Solution: def reverse(self, x): MAX_VAL = 2147483647 form_rev = rev_x = 0 i = abs(x) if i == 0: return 0 while i != 0: rev_x = i % 10 i = i // 10 i...
class ListQueue: def __init__(self): self.items = [] self.size = len(self.items) def enqueue(self, data): self.items.insert(0, data) def dequeue(self): data = self.items.pop() return data def traverse(self): for item in self.items: print(i...
""" My Int class """ class MyInt(int): """ rebel class """ def __init__(self, number): """ initialize """ self.number = number def __eq__(self, other): """ returns not equal """ return self.number != other def __ne__(self, othe...
""" Module 102-square Defines Square class with private attribute, size validation and area accessible with setters and getters comparison with other squares """ class Square: """ class Square definition Args: size: size of side of square, default size is 0 Functions: __init__self, ...
def multiply_by_2(a_dictionary): if a_dictionary is None: return None else: new_dict = {} for key, value in a_dictionary.items(): new_dict[key] = value*2 return new_dict
""" validate utf-8 """ def validUTF8(data): """ returns boolean """ bytes = 0 for num in data: if num < 128: bytes += 1 else: binary = format(num, '08b') if bytes == 0: for bit in binary: if bit == "0": ...
"""Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): def test_success_ints_floats_signed_unsigned(self): self.assertEqual(max_integer([0]), 0) self.assertEqual(max_integer([1, 2, 3, 4]), 4) sel...
""" Module 1-square class Square defined with private attribute size """ class Square: """ class Square Args: size: size of a side in a square """ def __init__(self, size): """ Initialization of square Attributes: size: size of a side of a square ...
class Product: def __init__(self, identification, price, quantity): self.identification = identification self.price = price self.quantity = quantity class Inventory: def __init__(self, products): self.products = products @property def value(self): return sum(pr...
import sys def chk_prime(x): for i in range(2, x): if x % i == 0: return False else: return True j = 'y' for i in range(2, sys.maxsize): if j == "y": if chk_prime(i): print(i) j = input("y: ") else: ...
i1 = int(input("Enter first digit: ")) i2 = int(input("Enter second digit: ")) e = 1 print(i1**i2) while i2 > 2: if i2 % 2 != 0: i2 -= 1 e *= i1 else: i1 = i1**2 i2 = i2/2 print((i1**2)*(e))
n = int(input("enter number: ")) ans = 1 for i in range(1, n + 1): ans *= i print(ans) def fact(n): if n == 1: return 1 else: return n * fact(n - 1) print(fact(n))
n = int(input("enter value: ")) if n >= 10: print('10 rupee: ', n//10) n = n % 10 if n >= 5: print('5 rupee: ', n//5) n = n % 5 if n >= 2: print('2 rupee : ', n//2) n = n % 2 if n >= 1: print('1 rupee: ', n//1) n = n % 1
''' Created on Oct 22, 2018 @author: Jugat Singh Python Period 5 even String Slicing HW ''' string= input("Please enter a String: ") start = int(input("Please enter the index where you would like to start slicing: ")) stop = int(input("Please enter the index where you would like to stop slicing: ")) ...
from graph import * from graph_io import * import os import copy def init_colors(graph): """ This function colors each vertex in "graph" based on the amount of neighbours. The colours are then saved in the first list inside the colors variable. The colors variable is a list of list of which each li...
def searchInsert(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target <= nums[0]: return 0 for i in range(1, len(nums)): if nums[i - 1] <= target <= nums[i]: return i return len(nu...
import collections def simplifyPath(path): """ :type path: str :rtype: str """ pathList = path.split('/') result = collections.deque() for p in pathList: if p == '..': if result: result.pop() if p and p != '.': result.append(p) ret...
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" print(full_name) print(f"Hello, {full_name.title()}!") message = f"Hello, {full_name.title()}!" print(message) full_name2 = "Hello, {} {}!".format(first_name, last_name) print(full_name2.title())
from random import randint class Die: def __init__(self, sides=6): self.sides = sides def describe_die(self): print(f"\nYour die has: {self.sides} sides") def roll_die(self): return randint(1, self.sides) die1 = Die() die2 = Die(10) die3 = Die(20) die1.describe_die() for i in range(10): prin...
print("\nEx 8.14 Cars\n" + "-"*70) def make_car(manufacturer, model, **car_info): car_info['manufacturer'] = manufacturer car_info['model'] = model return car_info car_profile = make_car(model = 'outback', manufacturer = 'subaru', color = 'blue', tow_package = True) print(car_profile)
def format_city_country(city_name, country_name, population=''): if population: format_name = f"{city_name.title()}, {country_name.title()} - {str(population)}" else: format_name = f"{city_name.title()}, {country_name.title()}" return format_name
import json filename = "favorite number.json" def read_number(): try: with open(filename, 'r') as f: number = json.load(f) except FileNotFoundError: return None else: return number def get_new_number(): while True: try: number = input("\nEnter...
print("\nEx 8.9 Messages\n" + "-"*70) def show_messages(text_list): message_list = text_list[:] message_list.reverse() while message_list: current_message = message_list.pop() print(current_message) hello_adele_lyric = ["Hello from the other side", "I must've called a thousand times", "To tell you I'm sorry ...
print("\nEx 7.1") rental_car = input("What kind of rental car would you like?\n") print(f"\nLet me see if I can find you a {rental_car.title()}.")
print("\nSorting") cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.sort() print(cars) print("\nReverse sorting") cars.sort(reverse=True) print(cars) print("\n Sorted()") cars = ['bmw', 'audi', 'toyota', 'subaru'] print("Original list:") print(cars) print("\nSorted list:") print(sorted(cars)) print("\...
print("\nEx 10.6 Addition\n" + "-"*70) print("Give me a number\n") try: num1 = input("First_number = ") num1 = int(num1) except ValueError: print("Value Error!, Enter a number next time.") else: print(f"Your number: {num1}")
Input: root = [3,9,20,null,null,15,7] Output: 3 class Solution(object): def maxDepth(self, root): if not root: return 0 depth = 0 q = [] q.append(root) while q: depth += 1 temp = [] for n...