text
stringlengths
37
1.41M
def is_integer(num): if int(num) != num: return False else: return True def prime(x): for factor in range(1, int(x/2), 2): div = x / factor if is_integer(div) and factor != 1: print('It is composite; can be divided by %d'%factor) return print('I...
import torch class MyReLu(torch.autograd.Function): """ We can implement our own custom autograd Functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors. """ @staticmethod def forward(ctx, input): """ In th...
# Ejemplo de fechas #Es necesario importar las depencendias necesarias from datetime import date from datetime import datetime #Día actual today = date.today() #Fecha actual now = datetime.now() print(today) print(now) #Date print("El día actual es {}".format(today.day)) print("El mes actual es {}".format(today.mo...
#!/usr/bin/env python3 """Convolution module """ import numpy as np def convolve_grayscale_padding(images, kernel, padding): """ performs a convolution on grayscale images with custom padding: - images: numpy.ndarray with shape (m, h, w) containing multiple grayscale images - m: number of im...
#!/usr/bin/env python3 """ module to add matrices """ def add_matrices2D(mat1, mat2): """ Adds two matrices element-wise """ if len(mat1) != len(mat2): return None elif len(mat1[0]) != len(mat2[0]): return None add = [] total = [] for i in range(len(mat1)): for...
#!/usr/bin/env python3 """train module """ import tensorflow.keras as K def train_model(network, data, labels, batch_size, epochs, validation_data=None, early_stopping=False, patience=0, verbose=True, shuffle=False): """ trains a model using mb gradient descent...
#!/usr/bin/env python3 """module that defines a single neuron """ import numpy as np class Neuron: """define a single neuron performing binary classification """ def __init__(self, nx): """ - nx: number of input features to the neuron Private instance attributes: -__W: The...
#!/usr/bin/env python3 """foward prpagation over pooling """ import numpy as np def pool_forward(A_prev, kernel_shape, stride=(1, 1), mode='max'): """ Performs forward propagation over a pooling layer of a neural network: - A_prev_numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing the outp...
#!/usr/bin/env python3 """ """ import numpy as np kmeans = __import__('1-kmeans').kmeans variance = __import__('2-variance').variance def optimum_k(X, kmin=1, kmax=None, iterations=1000): """ tests for the optimum number of clusters by variance: - X: numpy.ndarray of shape (n, d) containing the data set ...
#!/usr/bin/env python3 """ Module to slice matrix on an axis """ def np_slice(matrix, axes={}): """ Slices a matrix along a specific axes """ slices = [] for axis in range(len(matrix.shape)): slices.append(slice(*axes.get(axis, (None, None, None)))) return matrix[tuple(slices)]
#!/usr/bin/env python3 """ module to integrate """ def poly_integral(poly, C=0): """ calculate the integral of a polynomial """ if not isinstance(poly, list) or not isinstance(C, int) or len(poly) == 0: return None if C % 1 == 0: integral = [int(C)] else: integral = [C...
#!/usr/bin/env python3 """module learning rate dacay """ import numpy as np def learning_rate_decay(alpha, decay_rate, global_step, decay_step): """ updates the learning rate using inverse time decay in numpy - alpha: original learning rate - decay_rate: weight used to determine the rate at which alp...
#!/usr/bin/env python3 """ module of Normal distribution """ class Normal: """ class that represents a normal distribution """ e = 2.7182818285 pi = 3.1415926536 def __init__(self, data=None, mean=0., stddev=1.): """initialize class """ self.mean = float(mean) ...
#!/usr/bin/env python3 """module learning decay ugraded """ import tensorflow as tf def learning_rate_decay(alpha, decay_rate, global_step, decay_step): """ creates a learning rate decay operation in tf using inverse time decay - alpha: original learning rate - decay_rate: weight used to determine th...
year=int(input('year:\n')) month=int(input('mouth:\n')) day=int(input('day:\n')) months = (0,31,59,90,120,151,181,212,243,273,304,334) if 0 < month <=12: sum=months[month -1] else: print('date error') i = sum + day print('it is the',str(i)+'th day')
class Heap: def __init__(self, array, N): self._heap = array self._max = N self._descending_sorted = [] def get_heap(self): return self._heap def get_child_index(self,parent_index): return (parent_index * 2 + 1), (parent_index * 2 + 2) def get_parent_index(s...
import random import time pierre = 1 papier = 2 ciseaux = 3 names = { pierre: "Pierre", papier: "Papier", ciseaux: "Ciseaux" } rules = { pierre: ciseaux, papier: pierre, ciseaux: papier } player_score = 0 computer_score = 0 def start(): print("Faisons une partie de Pierre, Papier, Ciseaux!") ...
""" Creating and populating the database This file is used to : - Create the MySQL tables "Categories", "Products" and "Favorites" - Populate the "Categories" table - Retrieve the API data - Use the API Data to populate the "Products" table """ # Importing the Database objects provided by the ORM...
from Crop_Class import * class Carrot(Crop): '''This is a child class of crop''' #constructor def __init__(self): super().__init__(1, 6, 7) self._type = "Carrot" def Grow(self, light, water): #Overwrites the grow function if light >= self._light_need and wate...
# -*- coding: utf-8 -*- """ Created on Wed Feb 3 17:53:11 2021 @author: dylan """ #connect 4: #need to be able to input values #matrix as the board #1. input - range 0-6 col #2. valid col? if T #3 if T what is the next open row? #4 place piece in that next open row, of selected col #need to end game ...
from threading import Thread import time def timer(name, delay, repeat): print "Timer: " + "name" + "Started" while repeat > 0: time.sleep(delay) print name + ":" + str(time.ctime(time.time())) repeat -= 1 print "Timer: " + name + "Completed" def main(): t1 = Thread(target=timer, args=("Timer",1,5)) t2...
for x in range(1,100): if((x%3==0) and (x%5)!=0): print x,"-fuzzy" elif((x%5==0) and (x%3)!=0): print x,"-buzzy" elif((x%3==0) and (x%5)==0): print x,"-fuzzybuzzy" else: print(x)
# work with condicional if True: print('Condicional was True') #language ='Python' language ='Java' if language =='Python': print('Linguage is Phiton') elif language =='Java': print('Linguage is Java') elif language =='JavaScript': print('Linguage is JavaScript') else: print ('No match') #and = ...
#work with loop nums = [1,2,3,4,5] for num in nums: print(num) for num in nums: if num ==3: print('Found!') break print(num) for num in nums: if num ==3: print('Found!') continue print(num) for num in nums: for latter in 'abc' : print(num,latter) for i...
# Implements unigram language model # primary uses are 1) train with a file (passed as a path) to train probabilities of words # and 2) evaluate against another file -- to evaluate perplexity scores (fitness of model) from config import UNK_, STOP_, pad_sentence, UNK_THRESHOLD, MAX_UNKS class Unigrams: def __init...
import numpy as np from random import random # save activations and derivatives # implement backpropagation # implement gradient descent # implement a train method that uses both # train our network with some dummy dataset class MLP: """A class of a MLP for an ANN""" def __init__(self, num_inputs=3, hidden_...
# May Trinh # CMPS 4553 - Computational Methods # This program searches through mycoplasma dna sequence and its reverse complement in genbank format and finds all open reading frames (ORFs) with start # codon ATG and stop codon TAA, TAG , TGA. It only print genes that has more than 1000 nucleotides. Additionally, it ...
from question2 import CoPrimePairs from collections import defaultdict class Old: # to understandold solution! def coPrimes(n): """ returns lists of all coprimes for 1 to n """ choices = defaultdict(list) for pair in CoPrimePairs[n]: choices[pair[0]].append(pair[1]) ...
""" href: https://www.testdome.com/questions/25970 Write a function that provides change directory (cd) function for an abstract file system. Notes: Root path is '/'. Path separator is '/'. Parent directory is addressable as '..'. Directory names consist only of English alphabet letters (A-Z and a-z)...
""" Smallest multiple Problem 5 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ #### Brute force method def isDivisable(xNum, yList): for y in yList: ...
import re import numpy as np from pprint import pprint """ Permutations Functions for finding rotational permtuations. This scipt supports countcycles.py by finding all rotational permutations of a given move sequence to help eliminate duplicates. """ def main(): captains, seq2captains = algorithm_m_clean(2) ...
first=1000 second=200 third=300 fourth=400 # to find the biggest number out of four(they are not equal) first > second, first > third, first>fourth, 'first is biggest' second > third, second > fourth, 'second is biggest' third > fourth, 'third is biggest' 'fourth is biggest' if (first > second) and (first >...
# Qual o total de voos internacionais quue partiram do aeroporto de Logan no ano de 2014 calendario = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'] with open("economic-indicators.csv", "r") as boston: total = 0 for linha in boston.readlines()[1:-1]: if 2014 == int...
from tkinter import * # ---------------------------- PASSWORD GENERATOR ------------------------------- # # ---------------------------- SAVE PASSWORD ------------------------------- # # ---------------------------- UI SETUP ------------------------------- # window = Tk() window.title("Password Manager") window.conf...
from datetime import date from datetime import time from datetime import datetime def main(): today = datetime.today() print("Today's date is", today) print("Today's date by date, month, year", today.day, today.month, today.year) days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "...
# Let's check the first if and else condition x = 10 y = 20 z = 30 if x > y: print(x + " is greater than " +y) # this line is not executing that why it is not giving error. # Otherwise it gives this error TypeError: unsupported operand type(s) for +: 'int' and 'str' else: pass # this will pass without a...
# If he walks from A to B and then from B to A whit the same tempo, he has to walk 10 miles ... timeAB=2*495+3*432 >>> timeAB 2286 >>> timeBA=timeAB >>> timeBA 2286 >>> totaltimesec=timeAB+timeBA >>> totaltimesec 4572 >>> totaltimemin=totaltimesec/60 >>> totaltimemin 76 # He will be at home after 76min (8:08) #If he...
def gcd(a, b): if b == 0: return a else: r = a % b return gcd(b, r) gcd(6, 8)
def divisores(num): try: if num < 0: raise ValueError("Ingrese un número positivo") divisor =[i for i in range(1,num+1) if num % i == 0] return divisor except ValueError as e: print(e) return False def run(): num = input("Ingrese un número: ") assert ...
x=int(input("enter anumber")) y=int(input("enter another number")) z=int(input("enter third number")) print(x,y,z)
def serialize(words): return "".join(chr(len(word)) + word for word in words) def deserialize(words): if not words: return [] idx = ord(words[0])+1 return [words[1:idx]] + deserialize(words[idx:]) serialized = serialize(["test", "word", "three", "hello", "world"]) print(serialized) deserialized = deserialize(se...
import math def isComposite(n): """Straight loop.""" for x in range(2, int(math.sqrt(n)) + 1): if n % x == 0: return x return False _PrimeList = [2] def isCompPL(n): """Recursive version.""" for x in _PrimeList: if n % x == 0: if n == x: ret...
def find_missing(numbers): minimum = 1 length = len(numbers) i = 0 while i < length: idx = numbers[i] - minimum if idx < length: if numbers[i] - minimum == i: i += 1 else: numbers[idx], numbers[i] = numbers[i], numbers[idx] ...
size = 16 def printMatrix(matrix): for row in matrix: print(row) """ matrix = [] for i in range(size): matrix.append([(i, x) for x in range(size)]) printMatrix(matrix) print("========================") """ def shiftMatrixHoriz(matrix): newMatrix = [] for i in range(len(matrix)//2): #newMatrix.append([val fo...
import numpy as np def winnow_fit(xs, ys): # Implements the winnow algorithm as given in the coursework. n = xs.shape[1] w = np.ones(n, dtype=np.float64) for i in range(ys.size): x = xs[i] y = ys[i] y_hat = 0 if x @ w < n else 1 # Update weights if prediction is wrong. ...
def Selectionsort(vetor): for i in range(0, len(vetor)): menor = i for direita in range(i + 1, len(vetor)): if vetor[direita] < vetor[i]: menor = direita vetor[i], vetor[menor] = vetor[menor], vetor[i]
#!/usr/bin/env python """ Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues. This module contains one function diagnose_car(). It is an expert system to interactive diagnose car issues. """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__...
num1=int(input("Introduce un numero: ")) num2=int(input("Introduce un número mayor que: " + str(num1) + ": ")) while num2 > num1: num1 = num2 num2 = int(input("introduce un numero mayor que: " + str(num1) + ": ")) print() print (num2, "no es mayor que", str (num1))
year_of_birth=int(input("Date of birth: ")) current_year=int(input("Actual Date: ")) if year_of_birth==current_year: print("You were born this very year!") elif year_of_birth==current_year-1: print("You are "+ str((year_of_birth-current_year)*-1) + " year old!") elif year_of_birth<=current_year: ...
#Write a function called write_movie_info. write_movie_info #will take as input two parameters: a string and a #dictionary. # #The string will represent the filename to which to write. # #The keys in the dictionary will be strings representing #movie titles. The values in the dictionary will be lists #of string...
#APA citation style cites author names like this: # # Last, F., Joyner, D., & Burdell, G. # #Note the following: # # - Each individual name is listed as the last name, then a # comma, then the first initial, then a period. # - The names are separated by commas, including the last # two. # - There is also...
#Imagine you're playing a game in which every action you #take grants you some number of experience points. There is #an item called a Lucky Egg that, when used, doubles the #number of experience points you earn. The company behind #the game also runs occasional events where they increase #how many experience poin...
x = 2 for i in range(2, 12, 2): print(x) x += 2 print('Goodbye!')
#Write a function called num_factors. num_factors should #have one parameter, an integer. num_factors should count #how many factors the number has and return that count as #an integer # #A number is a factor of another number if it divides #evenly into that number. For example, 3 is a factor of 6, #but 4 is not...
class School(): def __init__(self,schoolName,stdCount,tchCount,employee,schoolType,classCount): self.schoolName=schoolName self.stdCount=stdCount self.tchCount=tchCount self.employee=employee self.schoolType=schoolType self.classCount=classCount school1 = School("Afyo...
database = [ {"name":"Sakshi", "acc":123456, "ph":9008001001, "pin":6749, "balance":7800} , {"name":"Sarah", "acc":234567, "ph":9008001002, "pin":5903, "balance":6500} , {"name":"John", "acc":345678, "ph":9008001003, "pin":7832, "balance":9000} , {"name":"Nikki", "acc":456789, "ph":9008001004, "pin":4880, "balance":550...
n = int(input('enter rows:')) for i in range(n+1, 1, -1): for j in range(1, i): print(f'{j}', end=" ") print("* "*(n+1-i) + "* "*(n-i))
cislo = int(input("Zadej číslo")) if cislo == 0: print("Je to moc jednoduché") print(cislo, "+ 3", cislo + 3)
from turtle import forward, left, right, shape, exitonclick shape = 'turtle' delka = 50 uhel = 60 for y in range(6): for i in range(6): forward(delka) left(uhel) forward(delka) right(uhel) exitonclick()
from typing import Dict def gc_content(sequence: str) -> float: if any(nucleotide not in "atgc" for nucleotide in sequence): raise AttributeError nucleotides: Dict[str, int] = {nucleotide: sequence.count(nucleotide) for nucleotide in "atgc"} gc_percentage: float = (nucleotides["g"] + nucleotides...
def st(): stscore = 0 #3rd quest for the user print("\n1: Timer\n2: Ton\n3: Time\n4: Toh") Quest3 = input("\nWhich of the above statements do i need, to create a timer for my program?\n") stscore = 0 while Quest3 != '2': print("\nYou disappoint me, Thanks for the points!\n") Quest3 =...
def gcd(a,b): if (b==0): return a return gcd(b, a%b) # Example Test Run # a=8 # b=4 # print(gcd(a,b)) # output: 4
import random print('\n\t\t\tЦе гра "Відгадай число:)" !!! ') number = random.randint(1,100) guest = int(input('\nЯ загадав число від 1 до 100, давай спробуй вгадай:')) popitka = 1 while guest != number: if guest>number: print("Моє число менше :(") else: print("Моє число більше :)") guest ...
''' This file defines the Assertion class. Assertions represent conceptual knowledge. ''' from SimpleRealizer import realize_brain_assertion import json class Assertion(object): def __init__(self, attributes = {}): for k, v in attributes.items(): setattr(self,k,v) def __eq__(self, other): if type(other) is...
def pyTriples(a): return([(m**2-n**2,2*m*n,m**2+n**2) for m in range(1,a) for n in range(1,a) if 2*m*n > 0 if m**2-n**2 > 0 if m**2+n**2 > 0]) def quickSort(arr): if arr == []: return [] pivot = arr[0] lower = quickSort([x for x in arr[1:] if x < pivot]) upper = quickSort([x for x in arr[1:]...
#! /usr/bin/env python3 # -*- encoding: utf-8; py-indent-offset: 2 -*- import sys print("Polyalphabetic substitution cypher") # asking for a key key=input(" Specify (string, private) key: ") # controlling key validity if len(key)<1: sys.stderr.write(" ERROR key should not be empty\n") sys.exit(1) # generating ...
number = int(input()) count, current_number = 1, 1 for i in range(number): if count > 0: print(current_number, end=' ') count -= 1 else: count = current_number current_number += 1 print(current_number, end=' ')
import numpy as np def gradient_decent(x,y): m_curr=0 b_curr=0 iteration=100 n = len(x) learning_rate=0.001 for i in range(iteration): y_predict=m_curr*x+b_curr md=-(2/n)*sum(x*(y-y_predict)) bd=-(2/n)*sum(y-y_predict) m_curr=m_curr - learning_rate*...
#!/usr/bin/env python3 class Duck: count = 0 def quack(self): print('Quaaack!') def walk(self): print('Walks like a duck.') def main(): donald = Duck() donald.quack() donald.walk() donald.count = 9 print(f'donald count {donald.count}') drill = Duck() # so Duck() ...
#!/usr/bin/env python3 hungry = True default = 23**3 tunary = 'this is default' if default else 'use special case' x = 'Feed the bear now!' if hungry else 'Do not feed the bear.' print(default)
# Use Python3 n = input() a, b = map(int, n.split()) def GCD(a, b): if b == 0: return a else: r = a % b return GCD(b, r) print(GCD(a, b))
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.e ** (-x)) def create_bias(x): bias = np.zeros(len(x)) bias = np.random.normal(bias) return bias def create_weight(x): weight = np.zeros_like(x) weight = np.random.normal(weight) return weight def h...
# Laços de repetiçãos minha_condicao = True while minha_condicao: print("Esse para...") print("1") print("2") minha_condicao -= True
import numpy as np import pandas as pd import random def generate_data(rn): """ Takes a roll number as input and generates random dataset according to the required specifications. :param rn: roll number of the student to ensure randomness and uniqueness of data """ n = 93 + (r...
# -*- coding:utf-8 -*- class Solution: def hasPath(self, matrix, rows, cols, path): # write code here visit = [0] * (rows * cols) def helper(i, j, k): idx = i * cols + j if i < 0 or i >= rows or j < 0 or j >= cols or visit[idx] or matrix[idx] != path[k]: ...
def parse_input(): """ Parses the input and passes the parsed input correctly into the calculator function. Returns ------- float The calculated float from passing in the parameters of the operands and the operation symbol to calculator. """ inputString = input("Enter equation: ") ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Calculates the average number of coins you would need to generate amounts up to `up_to_amount`, using representative baskets from `ons_data/baskets2.txt`. Also generates the average weight of these coins (actual weight, like in kilograms!) if you provide the `weight...
def feladat6(lista): print("6. feladat:") datum = "2004-11-21" for i in range(1, len(lista)): if lista[i][5] == datum: print("\t"+lista[i][0] + " - " + lista[i][1] + " (" + lista[i][2] + ":" + lista[i][3] + ")")
class Car: def __init__(self, p=0, i=0, e=0, t=0): self.paint = p self.interior = i self.engine = e self.tires = t def setCustom(self, pnt, ntrr, engn, trs): self.paint = pnt self.interior = ntrr self.engine = engn self.tires = trs def getPai...
def receipt(food, price): print("{:.<15}{:.>15.2f}".format(food,price)) food1=input("Please enter item 1:") price1=float(input("Please enter the price of item 1:")) food2=input("Please enter item 2:") price2=float(input("Please enter the price of item 2:")) food3=input("Please enter item 3:") price3=float(inpu...
def printf(word, number): print("{:<10},{:<10.2f}".format(word, number)) word="blah!" word="blah!" number=3456.8934 printf(word, number) word="oh boy!" number=454.67848304 printf(word, number)
def interest(amount): amount="${:<10.2f}".format(amount/(years*12)) return(amount) principle=float(input("Please enter your intial monetary value to be invested:")) rate=float(input("Please enter the interest rate, as a decimal to be multiplied by 100%:")) number=float(input("Please enter the number of time...
def idcard(item1,item2): print("*{:>15}{:>15} *".format(item1,item2)) item1=input("What organization are you affiliated with?") item2=input("What years were you affiliated with said organization?") item3=input("Enter your title:") item4=input("Enter subject taught/duty:") item5=input("Enter first name:") item6=i...
num1=float(input("Enter value 1:")) num2=float(input("Enter value 2:")) num3=float(input("Enter value 3:")) def average(): global avg avg=float("{:.5f}".format((num1+num2+num3)/3)) def prnt(): print("The average of",num1,num2,"and",num3,"is",avg) average() prnt()
"https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html" word = str(input("Put word:")) a = [] b = [] for i in word: a.append(i) count = len(word)-1 for j in word: b.append(word[count]) count -= 1 if a == b: print("The word is palindrome:") else: print("The word is no...
"https://www.practicepython.org/exercise/2015/11/01/25-guessing-game-two.html" from random import randint x= "" a=0 b=100 z=1 while x != "correct": y=randint(a,b) print(y) x = input("Answer: ") if x == "Too high": b = y+1 elif x == "Too low": a = y-1 elif x == "...
"https://www.practicepython.org/exercise/2015/11/26/27-tic-tac-toe-draw.html" a=[[0,0,0], [0,0,0], [0,0,0]] def decided(a): sx = 0 for i in range(0,3): ste="" for j in range(0,3): if a[i][j] == 0: sx+=1 ste=ste+" "+str(a[i][j...
with open("input.txt") as f: lines = f.readlines() valid_pass_count = 0 for line in lines: splitted = line.split() how_much = splitted[0].split("-") letter = splitted[1][:1] first_letter_check = splitted[2][int(how_much[0]) - 1] second_letter_check = splitted[2][int(how_much[1]) - 1] if...
# -*- coding: utf-8 -*- """ Created on Thu Mar 1 20:20:37 2018 @author: user """ import pandas as pd df = pd.read_csv('Ntu_Orders.csv') data = df.groupby(by='DateId')['Quantity'].sum() data = pd.DataFrame(data).sort_values(by='Quantity',ascending=False) data.to_csv('example.csv')
from urllib import error from weather import Weather weather = Weather() while True: city = input('Enter city: ') days = input('Enter days: ') try: weather_data = weather.get_weather(city) except error.HTTPError: print('Please, enter valid city') continue print(weather_data...
f_name=input("Enter the first name:") l_name=input("enter the last name:") print(f_name[::-2],l_name[::-2])
""" Utilities * General stable functions * Transforming coordinates * Computing rotations * Performing spherical integrals """ import numpy from scipy.integrate import dblquad def cartesian_from_polar(phi, theta): """ Embedded 3D unit vector from spherical polar coordinates. Parameters ---------- p...
from multiprocessing import Pool import time def fun(n): time.sleep(1) print("执行pool map事件") return n*n def main(): pool =Pool(4) l = [1,2,4,5,6,7,8] j = pool.map(fun,l) print(j) pool.close() pool.join() if __name__ == '__main__': main()
import threading def value(a,b,l): while True: l.acquire() if a != b: print(('a = %d,b = %d')%(a,b)) l.release() def main(): lock = threading.Lock() a = b = 0 t = threading.Thread(target=value,args=(a,b,lock)) t.start() while True: with lock: ...
"""############################################# # All tasks should be solved using recursion ############################################# Task 3 from typing import Optional def mult(a: int, n: int) -> int: This function works only with positive integers mult(2, 4) == 8 True mult(2, 0) == 0 Tru...
"""Task 2 Implement a stack using a singly linked list.""" from node import Node class Stack: def __init__(self): self.head = None def isempty(self): if self.head == None: return True else: return False def push(self, data): if self.head == None:...
"""############################################# # All tasks should be solved using recursion ############################################# Task 1 from typing import Optional def to_power(x: Optional[int, float], exp: int) -> Optional[int, float]: Returns x ^ exp to_power(2, 3) == 8 True to_power(3....
"""List comprehension exercise Use a list comprehension to make a list containing tuples (i, j) where `i` goes from 1 to 10 and `j` is corresponding to `i` squared.""" result = list(tuple(i for i in range(1, 11)), tuple(j for (j ** 2) in range(1, 11)))
"""Task 3 Fraction Create a Fraction class, which will represent all basic arithmetic logic for fractions (+, -, /, *) with appropriate checking and error handling ``` class Fraction: pass x = Fraction(1/2) y = Fraction(1/4) x + y == Fraction(3/4) ```""" class Fraction: def __init__(self, numerator: int...
"""Task 5 def sum_of_digits(digit_string: str) -> int: um_of_digits('26') == 8 True sum_of_digits('test') ValueError("input string must be digit string") """ def sum_of_digits(digit_string: str) -> int: if digit_string == "": return 0 else: return int(digit_string...