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('It is prime') #Input source print('Enter a number') i = input() fi = int(i) prime(fi)
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 the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method. """ ctx.save_for_backward(input) return input.clamp(min=0) @staticmethod def backward(ctx, grad_output): """ In the backward pass we receive a Tensor containing the gradient of the loss with respect to the output, and we need to compute the gradient of the loss with respect to the input. """ input, = ctx.saved_tensors # we only have one tensor saved grad_input = grad_output.clone() # why clone? grad_input[input < 0] = 0 return grad_input dtype = torch.float device = torch.device('cpu') N, D_in, H, D_out = 64, 1000, 100, 10 x = torch.randn(N, D_in, device=device, dtype=dtype) y = torch.randn(N, D_out, device=device, dtype=dtype) W1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True) W2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True) learning_rate = 1e-6 for t in range(500): relu = MyReLu.apply yHat = relu(x.mm(W1)).mm(W2) J = (y - yHat).pow(2).sum() print(t, J.item()) # Use autograd to compute the backward pass. This call will compute the # gradient of loss with respect to all Tensors with requires_grad=True. # After this call w1.grad and w2.grad will be Tensors holding the gradient # of the loss with respect to w1 and w2 respectively. J.backward() # Manually update weights using gradient descent. Wrap in torch.no_grad() # because weights have requires_grad=True, but we don't need to track this # in autograd. # An alternative way is to operate on weight.data and weight.grad.data. # Recall that tensor.data gives a tensor that shares the storage with # tensor, but doesn't track history. # You can also use torch.optim.SGD to achieve this. with torch.no_grad(): W1 -= learning_rate * W1.grad W2 -= learning_rate * W2.grad # Manually zero the gradients after updating weights W1.grad.zero_() W2.grad.zero_()
# 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.month)) print("El año actual es {}".format(today.year)) #Datetime print("El día actual es {}".format(now.day)) print("El mes actual es {}".format(now.month)) print("El año actual es {}".format(now.year))
#!/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 images - h: height in pixels of the images - w: width in pixels of the images - kernel: numpy.ndarray with shape (kh, kw) containing the kernel for the convolution - kh: height of the kernel - kw: width of the kernel - padding: tuple of (ph, pw) - ph: padding for the height of the image - pw: padding for the width of the image - the image should be padded with 0’s Returns: a numpy.ndarray containing the convolved images """ m, h, w = images.shape kh, kw = kernel.shape ph, pw = padding images_pad = np.pad(images, ((0, 0), (ph, ph), (pw, pw)), 'constant') out_w = w + 2*pw - kw + 1 out_h = h + 2*ph - kh + 1 convolve_out = np.ndarray((m, out_h, out_w)) for i in range(out_h): for j in range(out_w): convolve_out[:, i, j] = np.sum( images_pad[:, i:kh+i, j:kw+j] * kernel, axis=(1, 2)) return convolve_out
#!/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 j in range(len(mat1[0])): result = mat1[i][j] + mat2[i][j] add.append(result) total.append(add) add = [] return(total)
#!/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 with early stopping: - network: model to train - data: numpy.ndarray of shape (m, nx) containing the input data - labels: one-hot numpy.ndarray of shape (m, classes) with the labels - batch_size: size of the batch used for mini-batch gradient descent - epochs: number of passes through data for mini-batch gradient descent - validation_data: data to validate the model with - early_stopping: boolean that indicates whether early stopping should be used: - early stopping should only be performed if validation_data exists - early stopping should be based on validation loss - verbose: determines if output should be printed during training - shuffle: determines whether to shuffle the batches every epoch. """ callback = None if validation_data: callback = [K.callbacks.EarlyStopping(patience=patience)] history = network.fit(data, labels, batch_size=batch_size, epochs=epochs, validation_data=validation_data, callbacks=callback, verbose=verbose, shuffle=shuffle) return history
#!/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 weights vector for the neuron. Initialized using a random normal distribution. - __b: The bias for the neuron. Initialized to 0. - __A: The activated output of the neuron (prediction). Initialized to 0. Each private attribute have its getter function (no setter function). """ if not isinstance(nx, int): raise TypeError('nx must be an integer') if nx < 1: raise ValueError('nx must be a positive integer') self.__W = np.random.normal(size=(1, nx)) self.__b = 0 self.__A = 0 @property def W(self): """setter method of the weights """ return self.__W @property def b(self): """setter method of the bias """ return self.__b @property def A(self): """setter method of the activated output """ return self.__A def forward_prop(self, X): """ Calculates the forward propagation of the neuron - X: numpy.ndarray with shape (nx, m) that contains the input data - nx: number of input features to the neuron - m: number of examples Updates the private attribute __A The neuron use a sigmoid activation function - sig(z) = 1 / (1 + exp(-z)) Returns the private attribute __A """ x = np.matmul(self.__W, X) + self.__b self.__A = 1 / (1 + np.exp(-x)) return self.__A def cost(self, Y, A): """ Calculates the cost of the model using logistic regression Loss Function: L(A, Y) = -(Y * log(A) + (1 - Y) * log(1 - A))) Cost function: J(w, b) = (1 / m) * ∑(i=1; i<=m) L(A, Y) - Y: numpy.ndarray with shape (1, m) that contains the correct labels for the input data. - A: numpy.ndarray with shape (1, m) containing the activated output of the neuron for each example Returns the cost """ loss1 = np.matmul(Y, np.log(A).T) # 1.0000001 - A instead of 1 - A to avoid division by zero errors loss2 = np.matmul(1 - Y, np.log(1.0000001 - A).T) m = Y.shape[1] cost = np.sum(-(loss1 + loss2)) / m return cost
#!/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 output of the previous layer - m: number of examples - h_prev: height of the previous layer - w_prev: width of the previous layer - c_prev: number of channels in the previous layer - kernel_shape: tuple of (kh, kw) containing the size of the kernel for the pooling - kh: kernel height - kw: kernel width - stride: tuple of (sh, sw) containing the strides for the pooling - sh is the stride for the height - sw is the stride for the width - mode: string containing either max or avg, indicating whether to perform maximum or average pooling, respectively Returns: the output of the pooling layer """ m, h_prev, w_prev, c_prev = A_prev.shape kh, kw = kernel_shape sh, sw = stride ph = int(1 + (h_prev - kh) / sh) pw = int(1 + (w_prev - kw) / sw) output = np.zeros((m, ph, pw, c_prev)) m_prev = np.arange(0, m) for h in range(ph): for w in range(pw): for c in range(c_prev): pool = A_prev[m_prev, h * sh:h * sh + kh, w * sw:w * sw + kw, c] if mode == 'max': output[m_prev, h, w, c] = np.max(pool, axis=(1, 2)) elif mode == "avg": output[m_prev, h, w, c] = np.mean(pool, axis=(1, 2)) return output
#!/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 - kmin: positive integer containing the minimum number of clusters to check for (inclusive) - kmax: positive integer containing the maximum number of clusters to check for (inclusive) - iterations: positive integer containing the maximum number of iterations for K-means This function should analyze at least 2 different cluster sizes Returns: results, d_vars, or None, None on failure - results: list containing the outputs of K-means for each cluster size - d_vars: list containing the difference in variance from the smallest cluster size for each cluster size """ if not isinstance(X, np.ndarray) or len(X.shape) != 2: return None, None if not isinstance(iterations, int) or iterations <= 0: return None, None if not isinstance(kmin, int) or kmin < 1: return None, None if kmax and not isinstance(kmax, int) or kmax < 1: return None, None if kmax and kmin >= kmax: return None, None results = [] d_vars = [] for cluster in range(kmin, kmax + 1): centroid, clss = kmeans(X, cluster, iterations=1000) results.append((centroid, clss)) if cluster == kmin: cluster_var = variance(X, centroid) var = variance(X, centroid) d_vars.append(cluster_var - var) return results, d_vars
#!/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] if len(poly) == 0 or poly == [0]: return integral for coef in enumerate(poly): if not isinstance(coef[1], int) and not isinstance(coef[1], float): return None c = coef[1] / (coef[0] + 1) if c % 1 == 0: integral.append(int(c)) else: integral.append(c) return integral
#!/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 alpha will decay - global_step: number of passes of gradient descent that have elapsed - decay_step: number of passes of gradient descent that should occur before alpha is decayed further learning rate decay occur in a stepwise fashion Returns: the updated value for alpha """ global_step = int(global_step / decay_step) alpha = alpha / (1 + decay_rate * global_step) return alpha
#!/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) self.stddev = float(stddev) if data is None: self.mean = mean self.stddev = stddev if stddev <= 0: raise ValueError('stddev must be a positive value') else: if not isinstance(data, list): raise TypeError('data must be a list') if len(data) < 2: raise ValueError('data must contain multiple values') self.mean = (float(sum(data) / len(data))) sumdif = sum([(d - self.mean) ** 2 for d in data]) self.stddev = (sumdif / len(data)) ** (1 / 2) def z_score(self, x): """z score calculation """ return (x - self.mean) / self.stddev def x_value(self, z): """x value given z score """ return (z * self.stddev) + self.mean def pdf(self, x): """probability density function """ variance = self.stddev ** 2 exp = -((x - self.mean) ** 2) / (2 * variance) den = (2 * self.pi * variance) ** (1 / 2) return (self.e ** exp) / den def cdf(self, x): """cumulative distribution function """ error = self.erf((x - self.mean) / (self.stddev * (2 ** (1 / 2)))) return ((1 + error) / 2) def erf(self, x): """error function """ serie = 0 for i in range(5): j = 2 * i + 1 den = self.factorial(i) * j if j in [3, 7]: serie += -(x ** (j)) / den elif j in [1, 5, 9]: serie += (x ** (j)) / den return serie * 2 / (self.pi ** (1 / 2)) def factorial(self, n): """returns factorial of a number """ if not isinstance(n, int): n = int(n) factorial = 1 for i in range(n): factorial *= i + 1 return factorial
#!/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 the rate at which alpha will decay - global_step: number of passes of gradient descent that have elapsed - decay_step: number of passes of gradient descent that occurs before alpha is decayed further the learning rate decay occurs in a stepwise fashion Returns: the learning rate decay operation """ lr_decay = tf.train.inverse_time_decay( alpha, global_step, decay_step, decay_rate, staircase=True) return lr_decay
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(self,child_index): return (child_index - 1 )/2 def add(self,child): if self._max == len(self._heap): self.delete() self._heap.append(child) child_index = len(self._heap) - 1 while child_index > 0: parent_index = self.get_parent_index(child_index) if self._heap[parent_index] > self._heap[child_index]: self._heap[parent_index], self._heap[child_index] = self._heap[child_index], self._heap[parent_index] child_index = parent_index def delete(self): minimum_value = self._heap[0] self._heap[0] = self._heap[-1] del self._heap[-1] if len(self._heap) > 1: self.balance() return minimum_value def balance(self): parent_index = 0 while True: l_child_index, r_child_index = self.get_child_index(parent_index) # Both left and right child present if (l_child_index < len(self._heap)) and (r_child_index < len(self._heap)): if self._heap[l_child_index] < self._heap[r_child_index]: smaller = l_child_index else: smaller = r_child_index # Only left child present elif l_child_index < len(self._heap): smaller = l_child_index if self._heap[smaller] < self._heap[parent_index]: self.get_heap() self._heap[parent_index], self._heap[smaller] = self._heap[smaller], self._heap[parent_index] parent_index = smaller else: break def sort(self): for i in range(0,len(self._heap)): self._descending_sorted.append(self.delete()) return self._descending_sorted if __name__ == '__main__': f = 'test.txt' N = 12 h = Heap([],N) for line in open(f, 'r').readlines(): h.add(float(line)) print h.get_heap() for number in reversed(h.sort()): print number
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!") while game(): pass scores() def game(): player = move() computer = random.randint(1, 3) result(player, computer) return play_again() def move(): while True: print player = input("Pierre = 1\nPaper = 2\nCiseaux = 3\nFaites un mouvement: ") try: player = int(player) if player in (1,2,3): return player except ValueError: pass print("HEY HO! Il faut rentrer 1, 2 ou 3 !!!") def result(player, computer): print("1...") time.sleep(2) print("2...") time.sleep(2) print("2.3/4...") time.sleep(2) print("ça devient long non?") time.sleep(1.5) print("Bon ok 3!") time.sleep(1) print("Computer a fait {0}!".format(names[computer])) global player_score, computer_score if player == computer: print("Egalité") else: if rules[player] == computer: print("VICTOIRE!! Bravo vous avez terrassé l'ennemi") player_score += 1 else: print("Computer se rit de vous, vous avez PERDU LOOSER AH AH AH!!!") computer_score += 1 def play_again(): answer = input("Voulez-vous faire une autre partie? y/n: ") if answer in ("y", "Y", "yes", "Yes", "o", "O", "oui", "Oui"): return answer else: print("Merci d'avoir joué à mon jeu. A bientôt pour de nouvelles aventures ! ") def scores(): global player_score, computer_score print("Meilleurs scores") print("Player: ", player_score) print("Computer: ", computer_score) if __name__ == '__main__': start()
""" 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 and the module to that has a requester object (named 'Collector') from food_requests import Collector from modeles.category import Categories from modeles.favorite import Favorites from modeles.product import Product from modeles.users import Users from modules.database_service import DatabaseService # Creation of the tables Product.create_table() Categories.create_table() Favorites.create_table() Users.create_table() # Instantiation of a Collector collector = Collector() # I defined there a tuple of categories list_of_categories = ('soup', 'pizza', 'salad', 'cake', 'cheese') # I populate the table of the categories for category in list_of_categories: category_entry = {"Name": category} DatabaseService.fill_categories_table(category_entry) # I retrieve only the products that correspond to my categories in my tuple and I populate the products table for category in list_of_categories: food_returned = collector.get_products_by_category(category) DatabaseService.fill_products_table(food_returned)
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 water >= self._water_need: if self._status == "Seed" and water > self._water_need: self._growth = self._growth + self._growth_rate * 2 elif self._status == "Seedling" and water > self._water_need: self._growth = self._growth + self._growth_rate * 1.75 elif self._status == "Young" and water > self._water_need: self._growth = self._growth + self._growth_rate * 1.5 else: self._growth = self._growth + self._growth_rate else: pass self._days_grow = self._days_grow + 1 self._Update()
# -*- 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 when connected 4 #loop only way that game_over = T if 4 in a row import numpy as np ROW_COUNT = 6 COL_COUNT = 7 def create_board(): board = np.zeros((ROW_COUNT,COL_COUNT)) return board def drop_piece(board, row, col, piece): board[row][col] = piece #chack if top row for that column hasnt been filled-top row (5th) still 0 def is_valid(board, col): return board[ROW_COUNT-1][col] == 0 #next open row within that column loop if that row =0 # is available so return the first position avaiable in that col def open_row(board, col): for r in range(ROW_COUNT): if board[r][col] == 0: return r #numpy has the 0 index at the top of the matrix as default - so must flip it # - logical sense for players #(0 at the bottom) def print_board(board): print(np.flip(board, 0)) #winning - letting you know it's over # to do this - can manually check all the possible winning positions and see # if that matches - check every turn - to know which player won - (over all #the possible starting positions of a winning move) # im sure this isnt the best way - but didnt want to sink too much time into # this - any suggestions would be very welcome #[though about cheching around each piece, so may look at that if i try to # refine this :)] def winning_move(board, piece): #1. check all horizontals for winning move - all starting position #of winning move horizontal win e.g. cant start 4 in as only have 3 #horizontal spaces not the required 4, the last = 3rd col (starting at 0) #loop that iterates over the columns for c in range (COL_COUNT-3): for r in range (ROW_COUNT): if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece: return True #vertical locations #opposite of horizontal - any 4 up for c in range(COL_COUNT): for r in range(ROW_COUNT-3): if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece: return True #positively sloped diaganols for c in range(COL_COUNT-3): for r in range(ROW_COUNT-3): if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece: return True #negative slope- requires different - # rows 0-6 ascending - can only have 4 starting from 3rd row for c in range(COL_COUNT-3): for r in range(3, ROW_COUNT): if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece: return True board = create_board() print(board) game_over = False turn = 0 while not game_over: #ask for the first player input column if turn == 0: col = int(input("Player 1 Make your Move (0-6):")) if is_valid(board, col): row = open_row(board, col) drop_piece(board, row, col, 1) if winning_move(board, 1): print("PLAYER 1 WINS!") game_over = True #first player's assigned as 1 #second player's input else: col = int(input("Player 2 Make your Move (0-6):")) if is_valid(board, col): row = open_row(board, col) drop_piece(board, row, col, 2) if winning_move(board, 2): print("PLAYER 2 WINS!") game_over = True break #second player is assigned as 2 print_board(board) #once turn is played need to update the board - print the new board #increase the turn by 1 every play #(%2) alternating between players turns turn +=1 turn = turn % 2
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 = Thread(target=timer, args=("Timer",2,5)) t1.start() t1.start() print "main Completed" if __name__ == '__main__': main()
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 = && #or = || #not = != user = 'Admin' logged_in = True if user =='Admin' and logged_in: print('Admin Page') else: print('Bad crad') #logged_in = False if not logged_in: print('Please Log In') else: print('Welcome') #is compara id(possiçao da memoria) a = [1,2,3] b = [1,2,3] print(id(a)) print(id(b)) print(a is b) b = a print(a is b) condition = 0# or '' or [] or {} contendo estruturas nulas if condition: print('Evalueted to true') else: print('Evaluated to False') condition = 'Test'# extruturas nao nulas if condition: print('Evalueted to True') else: print('Evaluated to False')
#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 in range(1,11): print(i) x = 0 while x < 10: print(x) x+=1
# 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__(self, trainingDataPath: str, report_mode) -> None: self.unigram_counter: dict = None # set up when ready self.probabilities: dict self.vocab_size: int = 0 # assume empty vocab size to start self.extract_vocab(trainingDataPath) if report_mode: self.report_training() # main worker for unigram model training def extract_vocab(self, training_data_path): # set up our model structure self.unigram_counter = {} # use a dictionary for convenience training_data_file = open(training_data_path, "r") # open a handle to our training corpus (read mode) sentence = training_data_file.readline() # get the first sentence while sentence: sentence = pad_sentence(sentence) self.consume_sentence(sentence) # update our model with this sentence sentence = training_data_file.readline() # go to the next line training_data_file.close() ''' Train structures on a sentence -- takes a tokenized sentence (white space indicates a new token) and process into our unigram model ''' def consume_sentence(self, sentence): for token in sentence.split(): # get a token and if we are first meeting it, default to 0 self.unigram_counter[token] = self.unigram_counter.get(token, 0) + 1 self.vocab_size += 1 def report_training(self): print("Number of unigrams: {}".format(len(self.unigram_counter.keys()))) print("Vocabulary Size: {}", self.vocab_size) print("Number of occurrences of 'the': {}".format(self.unigram_counter["the"])) print("Number of occurrences of '.': {}".format(self.unigram_counter["."])) print("Number of occurrences of special stop: {}".format(self.unigram_counter[("%s" % STOP_)])) def get_unigrams(self): return self.unigram_counter def get_vocab_size(self): return self.vocab_size class UnigramModel: def __init__(self, trainingDataPath: str, report_mode=False) -> None: self.probabilities: dict = None # set up later self.unigrams = Unigrams(trainingDataPath, report_mode) self.learn() if report_mode: self.report_learning() def learn(self): # probability is the number of encounters / total tokens # Get our Unigrams and Vocab unigrams = self.unigrams.get_unigrams() vocab_size = self.unigrams.get_vocab_size() # add the UNK place holder -- start at 0 occurrences unigrams[UNK_] = 0 self.probabilities = {} # Calc probs and add in some unkness for unigram in unigrams.keys(): if unigrams[unigram] <= UNK_THRESHOLD and unigrams[UNK_] < MAX_UNKS: # [unk] the single occurrence unigrams unigrams[UNK_] = unigrams.get(UNK_, 0) + unigrams[unigram] else: self.probabilities[unigram] = unigrams[unigram] / vocab_size self.probabilities[UNK_] = unigrams[UNK_] / vocab_size def report_learning(self): print("Probability of 'the': {}".format(self.probabilities["the"])) print("Probability of [unk]: {}".format(self.probabilities[UNK_]))
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_layers=[3, 5], num_outputs=2): """ Constructor for the MLP class :param num_inputs: int number of inputs :param hidden_layers: list number of hidden layers stored in list, length is number of hidden layers :param num_outputs: int number of outputs """ self.num_inputs = num_inputs self.hidden_layers = hidden_layers self.num_outputs = num_outputs # layer is a list where each input is number of nuerons in a layer layers = [num_inputs] + hidden_layers + [num_outputs] # initiate random weights weights = [] for i in range(len(layers) - 1): # creates random arrays that can have a matrix with rand(rows, columns) # rows is #nuerons in i-th layer, column is #nuerons in i-th+1 layer # ex. 2->3 would be (2,3) b/c we need |w11 w12 w13| # (w23 is weight from nueron 2 -> 3 |w21 w22 w23| w = np.random.rand(layers[i], layers[i + 1]) weights.append(w) self.weights = weights activations = [] for i in range(len(layers)): a = np.zeros(layers[i]) activations.append(a) # instance variable self.activations = activations derivatives = [] for i in range(len(layers) - 1): # same logic as weights above d = np.zeros((layers[i], layers[i + 1])) derivatives.append(d) # instance variable self.derivatives = derivatives def forward_propagate(self, inputs): """Forward propogation step of ANN Loops through weights of weight array and calculates weight. Then performs activation function (sigmoid) on each nueron. :param inputs: array array of inputs (net sum) :return activations: array activation layer """ activations = inputs self.activations[0] = inputs for i, w in enumerate(self.weights): # calculate net inputs net_inputs = np.dot(activations, w) # calculate the activations activations = self._sigmoid(net_inputs) # save activations for backprop self.activations[i + 1] = activations return activations def back_propagate(self, error, verbose=False): for i in reversed(range(len(self.derivatives))): # get activations for the previous layer activations = self.activations[i + 1] # apply the sigmoid derivative function and reshape delta = error * self._sigmoid_derivative(activations) delta_reshaped = delta.reshape(delta.shape[0], -1).T # get activations for the current layer and reshape current_activations = self.activations[i] current_activations_reshaped = current_activations.reshape(current_activations.shape[0], -1) # save derivative after applying matrix mult. self.derivatives[i] = np.dot(current_activations_reshaped, delta_reshaped) # back prop the next error error = np.dot(delta, self.weights[i].T) if verbose: print("Derivatives for W{}: {}".format(i, self.derivatives[i])) return error def gradient_descent(self, learning_rate): for i in range(len(self.weights)): weights = self.weights[i] derivatives = self.derivatives[i] weights += derivatives * learning_rate def train(self, inputs, targets, epochs, learning_rate): """ Train the model and run forward and backward pro :param inputs: ndarray X :param targets: ndarray Y :param epochs: int Number of epochs we want to train network with :param learning_rate: int Step to apply gradient descent """ for i in range(epochs): sum_error = 0 # iterate through all the training data for j, input in enumerate(inputs): target = targets[j] # forward propagation output = self.forward_propagate(input) # calculate the error error = target - output # back propagation self.back_propagate(error) # apply gradient descent self.gradient_descent(learning_rate) sum_error += self._mse(target, output) # report error for each error - are we improving? print("Error: {} at epoch {}".format((sum_error / len(inputs)), i)) def _mse(self, target, output): return np.average((target - output)**2) def _sigmoid_derivative(self, x): return x * (1.0 - x) def _sigmoid(self, x): """ :param x: int input for sigmoid function :return: result result of performing sigmoid on input """ return 1.0 / (1 + np.exp(-x)) if __name__ == "__main__": # create a dataset to train a network for the sum operation items = np.array([[random() / 2 for _ in range(2)] for _ in range(1000)]) targets = np.array([[i[0] + i[1]] for i in items]) # create a Multilayer Perceptron with one hidden layer mlp = MLP(2, [5], 1) # train network mlp.train(items, targets, 50, 0.1) # create dummy data input = np.array([0.3, 0.1]) target = np.array([0.4]) # get a prediction output = mlp.forward_propagate(input) print() print("Our network believes that {} + {} is equal to {}".format(input[0], input[1], output[0])) print("Nice!")
# 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 translates the ORFs # to its corresponding amino acid sequence. from Bio import SeqIO from Bio.Seq import translate import re # Find ORF in Sequence def find_orf(sequence): # Find all ATG indexs start_indexs = [] index = [] stops =["TAA", "TAG", "TGA"] mark = 0 # find start codon index for i in range(1, len(sequence)): # ORF 1, 2, 3 if sequence[i:i+3] == "ATG": #group of 3 nucleotides start_indexs.append(i) for i in range(0, len(start_indexs)): if start_indexs[i] > mark: #start from the end of the previous ORF found for j in range (start_indexs[i], len(sequence),3): if sequence[j:j+3] in stops: #found stop codons index.append((start_indexs[i], j+3)) #save the start and stop index of ORF found mark = j + 3 #mark the end of the ORF just found. If another ATG is within the ORF, we ignore it break #break out of for loop once ORF is found for a start index return index with open("orfs.txt","w") as outf: outf.write(""" May Trinh CMPS 4553 - Computational Methods This program searches through mycoplasma dna sequence and its reverse complement 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 translates the ORFs to its corresponding amino acid sequence. \n\n""") outf.write("ORFs of original strand \n\n") outf.write("Length \t\tStart \t Stop \t Sequence \n") # find ORFs in the sequence for seq_record in SeqIO.parse("mycoplasma.gb", "genbank"): record = seq_record.seq orfs = find_orf(record) # the normal way for s in orfs: length = s[1] - s[0] if length >= 1000: #only get gene with more than 1000 nucleotide in it orf = record[s[0]:s[1]] aa = orf.translate(cds=True, table = "Bacterial") #translate ORF to amino acid outf.write(str(length) + "\t\t " + str(s[0]) + "\t " + str(s[1]) + "\t " + str(orf)+ "\n") outf.write("Amino Acid: \t \t\t \t " + str(aa) + "\n") outf.write("\nORFs of reverse complement strand \n\n") outf.write("Length \t\tStart \t Stop \t Sequence \n") # find orfs of reverse complement strand reverse = record.reverse_complement() orfReverse = find_orf(reverse) for s in orfReverse: length = s[1] - s[0] start = len(record) - s[1] stop = len(record) - s[0] if length >= 1000: orfR = reverse[s[0]:s[1]] orf = record[start:stop] # origin = orfR.reverse_complement() # this translation also works as well # aa = orfR.translate(to_stop=True, table = 4) aa = orfR.translate(cds=True, table = "Bacterial") outf.write(str(length) + "\t\t " + str(start) + "\t " + str(stop) + "\t " + str(orfR)+ "\n") outf.write("Orginal strand: \t \t\t " + str(orf)+"\n") outf.write("Amino Acid: \t \t\t \t " + str(aa) + "\n")
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]) if pair[0] != pair[1]: choices[pair[1]].append(pair[0]) return choices def ways(num, length, coprimes): ways = [0] + [1] * num for _ in range(length): total = sum(ways) nextways = [0] * (num + 1) nextways[1] = total for i in range(2, num + 1): nextways[i] = sum(ways[coprime] for coprime in coprimes[i]) ways = nextways return total % (10**9 + 7) print (ways(3, 4, coPrimes(3)))
""" 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). The function should support both relative and absolute paths. The function will not be passed any invalid paths. Do not use built-in path-related functions. For example: path = Path('/a/b/c/d') path.cd('../x') print(path.current_path) should display '/a/b/c/x' """ class Path: def __init__(self, path): self.current_path = path def cd(self, new_path): if not new_path.strip(): self.current_path = "/" return elif new_path.startswith("/"): current_path = [''] new_path = new_path[1:] else: current_path = self.current_path.split('/') index = len(current_path) for dirname in new_path.split("/"): if dirname == "." or dirname == "": continue elif dirname == "..": if index > 0: index -= 1 elif dirname.isalpha(): if index < len(current_path): current_path[index] = dirname else: current_path.append(dirname) index += 1 else: raise ValueError("abstract: cd: {}: No such file or directory" .format(new_path)) self.current_path = "/".join(current_path[:index]) if not self.current_path.startswith("/"): # FIXME remove this fix and write better code self.current_path = '/' + self.current_path if __name__ == '__main__': path = Path('/a/b/c/d') print(path.current_path) path.cd('../x') # /a/b/c/x print(path.current_path) path.cd('/../x') # x print(path.current_path) path = Path('/a/b/c/d') path.cd('..') print(path.current_path)
""" 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: if xNum%y != 0: return False return True def smallest_multiple(top_range): """ takes top range to make a list from 1 to n will return the smallest number which is multiple by all numbers in the list No need to check 1 as everything will be divisable. So 2 onwards """ list = [x for x in range(2,top_range)] base = 0 while True: base += 1 if isDivisable(base, list) == True: return base else: print "Current iteration of {0}".format(base) print smallest_multiple(10) #print smallest_multiple(20) #Takes too long for 1-20. #nicer method #http://codereview.stackexchange.com/questions/67938/project-euler-5-lowest-multiple-of-1-through-20 def lowest_common_multiple(nfrom, nto): lcm = nfrom for i in range(nfrom, nto+1): sum = lcm print "sum is {0}, iteration is {1}".format(sum, i), while (sum % i != 0): print " adding {0}".format(lcm), sum += lcm print "" lcm = sum return lcm print lowest_common_multiple(1,20)
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) print("List of all length-2 permutations generated:") pprint(list(seq2captains.keys())) print("Total: %d"%(len(seq2captains.keys()))) print("") print("List of rotationally unique length-2 permutations:") pprint(list(captains)) print("Total: %d"%(len(captains))) def algorithm_m_clean(n): """ Knuth's Algorithm M for permutation generation, cleaned up to remove duplicate rotations. This generates the rotations: constructs a map of each sequence to its captain. """ sequence_to_captain = {} captains = set() for perm in algorithm_m(n): # get all possible rotations of this # move sequence (permutation) rotations = get_rotations(perm) # important: # sort rotations in reverse lexicographic order, # extract captains after they are returned captain = rotations[0] # for each rotation, # set its captain. for rot in rotations: if rot not in sequence_to_captain: sequence_to_captain[rot] = captain captains.add(captain) captains = list(captains) return captains, sequence_to_captain def algorithm_m(n): """ Knuth's Algorithm M for permutation generation, via AOCP Volume 4 Fascile 2. This is a generator that returns permtuations generated using the variable-radix method. This generates ALL permutations. Many of these are rotations of one another, so use the get_rotations() function below to get all rotations of a given permutation. A better way to do this is to clean up algorithm M so it only generates the original, plus the 24 rotations each in turn... ...but that makes my brain hurt. """ moves = ['U', 'D', 'B', 'F', 'L', 'R', 'Uw','Dw','Bw','Fw','Lw','Rw', '2U','2D','2B','2F','2L','2R', ] # M1 - Initialize a = np.zeros(n,) m = np.ones(n,)*len(moves) j = n-1 nvisits = 0 while True: # M2 - visit move_sequence = " ".join([ moves[int(aj)] for aj in a]) yield move_sequence nvisits += 1 # M3 - prepare to +1 j = n-1 # M4 - carry while( a[j] == m[j]-1): a[j] = 0 j = j-1 # M5 - increase unless done if(j<0): break else: a[j] = a[j] + 1 def get_rotations(sequence): """ Given a cube sequence, find all 24 rotations of it. Need to fix this so it doesn't necessarily expect the U-first case. """ cubes = ["UBFLRD", "UFBRLD", "ULRFBD", "URLBFD", "DFBLRU", "DBFRLU", "DLRBFU", "DRLFBU", "LUDBFR", "LDUFBR", "LFBUDR", "LBFDUR", "RUDFBL", "RDUBFL", "RBFUDL", "RFBDUL", "FUDLRB", "FDURLB", "FRLUDB", "FLRDUB", "BUDRLF", "BDULRF", "BLRUDF", "BRLDUF"] results = set() results.add(sequence) cubestart = {'U': 0, 'D': 4, 'L': 8, 'R':12, 'F':16, 'B':20} # Split the sequence into its moves, # and use the first cube configuration to map # moves to numbers. moves = sequence.split(" ") move0 = moves[0] first_move = move0[0] if(move0[0]=='2'): first_move = move0[1] first_move_index = cubestart[first_move] # Now run through all other cube configurations, # and map the numbers back to moves. move_numbers = [] for move in moves: if(move[0]=='2'): move_numbers.append(cubes[first_move_index].index(move[1])) else: move_numbers.append(cubes[first_move_index].index(move[0])) for i in range(len(cubes)): cube = cubes[i] xmoves = [] for j, move_number in enumerate(move_numbers): old_face = cubes[first_move_index][move_number] new_face = cube[move_number] old_move = moves[j] new_move = re.sub(old_face,new_face,old_move) xmoves.append(new_move) # Assemble the moves to a string xmove = " ".join(xmoves) results.add(xmove) # reversed is slightly more convenient, # starts with U instead of B return list(reversed(sorted(list(results)))) def test_rotations(): # Focusing on sequences of length 3 and up # Focusing on right hand sequences only # # 12 possible right hand moves, # 3^12 total possibilities, # 24 rotational equivalents, # 22,000 total unique 3-move sequences moves = ['U', 'D', 'B', 'F', 'L', 'R', 'Uw','Dw','Bw','Fw','Lw','Rw', '2U','2D','2B','2F','2L','2R', ] sequences = [] move1 = 'L' for move2 in ['D']:#moves: for move3 in moves: seq = " ".join([move1,move2,move3]) sequences.append(seq) print("Length of sequence: %d"%(len(sequences))) for sequence in sequences: print(get_rotations(sequence)) if __name__=="__main__": main()
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 > third) and (first > fourth): print("first is biggest") elif(second > third) and (second > fourth): print("second is biggest") elif(third > fourth): print ("third is biggest") else: print(" fourth biggest")
# 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(linha.split(',')[0]): total = total + float(linha.split(',')[3]) # separa pela vigula na posição 3 print("O total de voos é: ", total) with open("economic-indicators.csv", "r") as boston: maiorPassageiros = 0 for linha in boston.readlines()[1:-1]: numPassageiros = float(linha.split(',')[2]) if numPassageiros > maiorPassageiros: maiorPassageiros = numPassageiros mes = int(linha.split(',')[1]), int(linha.split(',')[0]) print("O mês e ano ", mes[0], '/', mes[1], "houveram ", maiorPassageiros, 'passageiros') with open("economic-indicators.csv", "r") as boston: quantidadeDePassageirosQuePassaramPeloAeroporto = 0 quantidadeDeVezesQueApareceaData = 0 usuario = float(input('Digite o ano para saber o total de pessoas que passaram pelo aeroporto: ')) for linha in boston.readlines()[1:-1]: if usuario == int(linha.split(',')[0]): quantidadeDeVezesQueApareceaData += 1 quantidadeDePassageirosQuePassaramPeloAeroporto += int(linha.split(',')[2]) print(quantidadeDeVezesQueApareceaData) print(quantidadeDePassageirosQuePassaramPeloAeroporto, " pessoas.") with open("economic-indicators.csv", "r") as boston: maiorMediadeDiaria = 0 mes = 0 usuario = int(input('Digite o ano para saber a maior diária de um hotel: ')) for linha in boston.readlines()[1:-1]: if usuario == int(linha.split(',')[0]) and maiorMediadeDiaria < float(linha.split(',')[5]): maiorMediadeDiaria = float(linha.split(',')[5]) mes = int(linha.split(',')[1]) for m in range(0, len(calendario) + 1, 1): if mes == m: print('O mês de', calendario[mes-1], 'teve a maior média de preços')
from tkinter import * # ---------------------------- PASSWORD GENERATOR ------------------------------- # # ---------------------------- SAVE PASSWORD ------------------------------- # # ---------------------------- UI SETUP ------------------------------- # window = Tk() window.title("Password Manager") window.config(padx=50,pady=50) canvas = Canvas(height=200, width=200) logo_img = PhotoImage(file="logo.png") canvas.create_image(100,100,image=logo_img) canvas.pack() canvas.grid(column=1, row=0) lb_website = Label(text="Website:").grid(column=0,row=1) en_website = Entry(width=35).grid(column=1, row=1, columnspan=2) lb_account = Label(text="Email/Username:").grid(column=0, row=2) en_account = Entry(width=35) en_account.insert(0, "[email protected]") en_account.grid(column=1, row=2, columnspan=2) lb_pwd = Label(text="Password").grid(column=0, row=3) en_pwd = Entry(width=21).grid(column=1, row=3) btn_pwd = Button(text="Generate Password").grid(column=2, row=3) btn_add = Button(text="Add", width=36).grid(column=1, row=4, columnspan=2) window.mainloop()
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", "Saturday", "Sunday"] print("Today is", days[today.weekday()]) now = datetime.now() print("Current time is ", now) if __name__ == '__main__': main()
# 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 any thing print # another example if x > y: print(str(x)+ " is greater than " + str(y)) # Here we need to type cast int to string. else: print(str(y) + " is greater than " + str(x)) # another example if x > y & x > z: print(str(x) + " is the greatest number") elif y > x & y > z: print(str(y) + " is the greatest number") else: print(str(z) + " is the greatest number") # Let's check the loop condition print("********While loop test**********") x = 1 while x < 5: print(x) x += 1 print("********For loop test**********") list = [1, 2, 3, 4, 5] for x in list: print(x) print("********For loop range test**********") for x in range(1,5): print(x)
# 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 walks in a circle(from A to A), he has to walk only 5 miles ... timesec=2*495+3*432 >>> timesec 2286 >>> timemin=timesec/60 >>> timemin 38 >>> #He will be at home after 38 min ( at 7:30)
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 num.isnumeric(), "Ingrese un número" print(divisores(int(num))) print("El programa termino") if __name__ == '__main__': run()
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(serialized) print(deserialized)
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: return False return x for x in range(_PrimeList[-1], int(math.sqrt(n)) + 1): if not isCompPL(x): if x > _PrimeList[-1]: _PrimeList.append(x) if n % x == 0: return x return False def isCompSR(n): """Serialized recursive version.""" l = [n] while (math.sqrt(l[0]) > _PrimeList[-1]): l.insert(0, int(math.sqrt(l[0]))) l.insert(0, _PrimeList[-1] + 1) while (len(l) > 2): q = l.pop(0) for x in range(q, l[0]): for y in _PrimeList: if x % y == 0: break else: _PrimeList.append(x) return isCompPL(n) #for i in range(20000, 50000): for i in [1299827]*10000: #print("{}: {}".format(i, isComp(i))) #isComposite(i) isCompSR(i)
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] else: numbers[i] = None i += 1 for i, val in enumerate(numbers): if val is None: return i + minimum return minimum + length def find_missing2(numbers): minimum = 1 length = len(numbers) for i in range(length): numbers[i] -= minimum for i, val in enumerate(numbers): while val != i: if val >= length: numbers[i] = None break numbers[val], numbers[i] = val, numbers[val] val = numbers[i] for i, val in enumerate(numbers): if val is None: return i + minimum return minimum + length def find_missing3(numbers): for i in range(len(numbers)): if numbers[i] >= len(numbers): numbers[i] = None for i in range(len(numbers)): while numbers[i] not in (i, None): numbers[numbers[i]], numbers[i] = numbers[i], numbers[numbers[i]] for i, val in enumerate(numbers[1:], 1): if val is None: return i return len(numbers) def main(): numbers = [3, 2, 1, 7] numbers = [4, 2, 7, 6, 1, 3] missing = 1#find_missing(list(numbers)) missing2 = 1#find_missing2(list(numbers)) missing3 = find_missing3(list(numbers)) print(missing, missing2, missing3) if __name__ == "__main__": main()
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 for pair in zip(matrix[i],matrix[i+1]) for val in pair]) newMatrix.append([val for pair in zip(matrix[i],matrix[i+len(matrix)//2]) for val in pair]) return newMatrix def shiftMatrixVert(matrix): newM2 = [] for i in range(len(matrix)): newM2.append(matrix[i][:len(matrix)*2]) newM2.append(matrix[i][len(matrix)*2:]) return newM2 def newShift(matrix, n): m = [] for i in range(len(matrix)//n): #m.append([val for tup in zip(*matrix[i:i+n]) for val in tup]) m.append([val for tup in zip(*matrix[i::len(matrix)//n]) for val in tup]) matrix = m printMatrix(matrix) m2 = [] for i in range(len(matrix)): for j in range(n): m2.append(matrix[i][len(matrix)*j*n:n*len(matrix)*(j+1)]) return m2 #matrix = shiftMatrixHoriz(matrix) #matrix = shiftMatrixVert(matrix) #matrix = shiftMatrixHoriz(matrix) #matrix = shiftMatrixVert(matrix) #matrix = newShift(matrix, 4) #printMatrix(matrix) sqrt9 = 3 sz = 9 M = [] for i in range(sz): M.append([0]*sz) for i in range(sz): for j in range(sz): #val = j // sqrt9 + sqrt9 * ((i + sz * j) % (sz * sqrt9)) #val = j // sqrt9 + sqrt9 * (i % (sz * sqrt9)) + sqrt9 * sz * (j % sqrt9) val = j // sqrt9 + sqrt9 * (i + sz * (j % sqrt9)) #print(i + j * sz, val) vi = (j // sqrt9 + sqrt9 * i) % sz vj = (j // sqrt9 + sqrt9 * i) // sz + sqrt9 * (j % sqrt9) #print((i,j), (val % sz, val // sz)) #print((i,j), (vi, vj)) M[i][j] = (val % sz, val // sz) printMatrix(M)
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. if y_hat != y: w *= np.power(2, (y - y_hat) * x, dtype=np.float64) return w def winnow_evaluate(w, xs, ys): n = xs.shape[1] predictions = np.where(xs @ w >= n, 1.0, 0.0) return (predictions != ys).sum() / ys.size * 100.0
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__ = "[email protected]" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Expected Outputs: Errors: """ print("The battery cables may be damaged. Replace cables and try again.") diagnose_car()
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: print("You are "+ str((year_of_birth-current_year)*-1) + " years old!") elif year_of_birth>=current_year: print("You will be born in " + str(year_of_birth-current_year) + " Years. ")
#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 strings representing performers in the corresponding #movie. # #write_movie_info should write the list of movies to the file #given by the filename using the following format: # # Title: Actor 1, Actor 2, Actor 3, etc. # #The movies and the actor names should be sorted #alphabetically. # #So, for this dictionary: # # {"Chocolat": ["Juliette Binoche", "Judi Dench", "Johnny Depp", "Alfred Molina"], # "Skyfall": ["Judi Dench", "Daniel Craig", "Javier Bardem", "Naomie Harris"]} # #The file printed would look like this: # # Chocolat: Alfred Molina, Johnny Depp, Judi Dench, Juliette Binoche # Skyfall: Daniel Craig, Javier Bardem, Judi Dench, Naomie Harris # # HINT: the keys() method of a Dictionary will return a list # of the dictionary's keys. So, to get a sorted list of a_dict's # keys, you could call key_list = a_dict.keys(), then call # key_list.sort(). # import os # os.getcwd() # Write your function here! def write_movie_info( filename , movies ): movie_names = movies.keys() actors = movies.values() outputFile = open( filename , "w") for actor in actors: actor.sort() sorted_movie_names = dict() sorted_movie_names = sorted(movie_names) for movie_names, actor in movies.items(): sorted_movie_names(movie_names) = actor for movie_names, actors in movies.items(): outputFile.write(str(movie_names) + ": ") counter = 0 for actor in actors: outputFile.write(str(actors)) counter += 1 if counter == len(actors): outputFile.write("\n") break else: outputFile.write(", ") print(str(movie_names) + ": " + str(actors)) outputFile.close() # new = dict(zip( key_sort , items_sort )) # for i in movie_names: # x = i + ": " # outputFile.write(x) # # outputFile.write(", ".join(actor)) # outputFile.write("\n") # counter = 0 # while len(items) > counter: # print(items[counter], end = "") # counter += 1 # if counter == len(items): # print("") # break # else: # print(", ", end = "") # outputFile.close() #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print nothing -- however, it should write the same contents #as Sample.txt to Test.txt. movies = {"Skyfall": ["Judi Dench", "Daniel Craig", "Javier Bardem", "Naomie Harris"], "Chocolat": ["Juliette Binoche", "Judi Dench", "Johnny Depp", "Alfred Molina"], } write_movie_info("Test.txt", movies)
#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 an ampersand and additional space before # the final name. # - There is no space or comma following the last period. # #Write a function called names_to_apa. names_to_apa should #take as input one string, and return a reformatted string #according to the style given above. You can assume that #the input string will be of the following format: # # First Last, David Joyner, and George Burdell # #You may assume the following: # # - There will be at least three names, with "and" before # the last name. # - Each name will have exactly two words. # - There will be commas between each pair of names. # - The word 'and' will precede the last name # - The names will only be letters (no punctuation, special # characters, etc.), and first and last name will both be # capitalized. #Write your function below! def names_to_apa( names ): # remove unnecessary characters (separating wheat from the chaff) names = names.replace(" and","") names = names.split(", ") # storing number of names pop = len(names) # isolates last name final_name = names.pop() # Iteratively isolates the list items for name in names: fname, lname = name.split(" ") # Prints output in requested format (with modified print statement allowing single-line output) piece1 = lname + ", " + fname[0] + "., ", sep="",end="",flush=True # Preps final output piece2 = "and ", sep="",end="",flush=True # Splits last name ffname, flname = final_name.split(" ") # Declares variable to return at the end final_final_i_promise_this_time_no_really_final_v2 = flname + ", " + ffname[0] return final_final_i_promise_this_time_no_really_final_v2 #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: Last, F., Joyner, D., & Burdell, G. print(names_to_apa("First Last, David Joyner, and George Burdell"))
#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 points you earn for each action by 50%, #100%, or even 200%. # #Write a function called find_total_exp. find_total_exp #should have one positional parameter, a base number of #experience points. It should also have two keyword #parameters: lucky_egg, whose default value is False, and #event_multiplier, whose default value is 1. # #The function should return the number of experience #points earned based on these two variables. The base number #of experience points should always be multiplied by the #event multiplier, and then doubled if lucky_egg is True. # #You should convert the final result from a float to an #integer before returning it. This will automatically round #down. #Add your code here! def find_total_exp( exp , lucky_egg = False , multiplier = 1): exp *= multiplier if lucky_egg == True: exp *= 2 return int(exp) #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #100 #200 #150 #300 print(find_total_exp(100)) print(find_total_exp(100, lucky_egg = True)) print(find_total_exp(100, multiplier = 1.5)) print(find_total_exp(100, lucky_egg = True, multiplier = 1.5))
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. As such, all factors will be less than the #number itself. # #Do not count 1 or the number itself in your factor count. #For example, 6 should have 2 factors: 2 and 3. Do not #count 1 and 6. You may assume the number will be less than #1000. #Add your code here! def num_factors( num ): count = 0 for i in range(2,num): if num % i == 0: count += 1 return count #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: 0, 2, 0, 6, 6, each on their own line. print(num_factors(5)) print(num_factors(6)) print(num_factors(97)) print(num_factors(105)) print(num_factors(999))
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("Afyon Fen Lisesi",500,30,25,"Science High School",25) school2 = School("Afyon Anadolu Lisesi",400,25,25,"Anatolian High School",25) school3 = School("Afyon Meslek Lisesi",450,35,25,"Vocational High School",25) print("------------",school1.schoolName,"-------------") print("\n Number of Students: ",school1.stdCount,"\n Number of Teacher: ",school1.tchCount ,"\n Number of Employee: ",school1.employee,"\n School Type: ",school1.schoolType,"\n Number of Class: ",school1.classCount) print("------------",school2.schoolName,"-------------") print("\n Number of Students: ",school2.stdCount,"\n Number of Teacher: ",school2.tchCount ,"\n Number of Employee: ",school2.employee,"\n School Type: ",school2.schoolType,"\n Number of Class: ",school2.classCount) print("------------",school3.schoolName,"-------------") print("\n Number of Students: ",school3.stdCount,"\n Number of Teacher: ",school3.tchCount ,"\n Number of Employee: ",school3.employee,"\n School Type: ",school3.schoolType,"\n Number of Class: ",school3.classCount) school1.employee=35 school2.stdCount=515 school3.schoolName="Afyon Mesleki ve Teknik Anadolu Lisesi" print("\n*** UPDATES ***") print(school1.schoolName,"updated number of employees:",school1.employee,"\n",school2.schoolName,"updated number of students: ",school2.stdCount,"\n",school3.schoolName,"updated school names:",school3.schoolName)
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":5500} , {"name":"Jimmy", "acc":567890, "ph":9008001005, "pin":2198, "balance":7400} , ] class Account: def __init__(self, name, acc_no, phone_no, balance): self.name = name self.acc_no = acc_no self.phone_no = phone_no self.balance = balance def account_info(self): print('\nAccount Details: ') print(f'\nName: {self.name}\nAccount no: {self.acc_no}\nContact no: {self.phone_no}\n') def enquiry(self): print(f'\nYour Account balance is: Rs.{self.balance}') def pin_change(self,newpin): self.pin = newpin print(f"\nYour PIN is now {self.pin}") def deposit(self,dep_amt): self.balance += dep_amt print(f'\nDeposit Accepted! Your Current balance is Rs. {self.balance}') def withdraw(self,wd_amt): if self.balance >= wd_amt: self.balance -= wd_amt print(f'\nWithdrawl Accepted! Your Current balance is Rs. {self.balance}') else: print('\nSorry! You have insuficient Balance.') user_acc = int(input('Enter Account no: ')) attempt = 3 while attempt!=0: user_pin = int(input('Enter PIN: ')) for user in database: if user.get('acc') == user_acc and user.get('pin') == user_pin: print (f"\nHello {user['name']}!") attempt=0 userobj = Account(user['name'], user['acc'], user['ph'], user['balance']) print("\nPlease select the operation:\nAccount details (press 1)\nBalance Enquiry (press 2)\nChange PIN (press 3)\nMoney Deposit (press 4)\nMoney Withdrawl (press 5)") response = int(input("\nEnter your response: ")) if response == 1: userobj.account_info() elif response == 2: userobj.enquiry() elif response == 3: newpin = int(input("\nEnter a new 4-digit PIN: ")) userobj.pin_change(newpin) user['pin'] = newpin elif response == 4: dep_amt = int(input("\nEnter the amount to be deposited: ")) userobj.deposit(dep_amt) elif response == 5: wd_amt = int(input("\nEnter the amount to be withdrawn: ")) userobj.withdraw(wd_amt) elif user.get('acc') == user_acc and user.get('pin') != user_pin: print (f"{user['name']}, you have entered incorrect password. Try again!") attempt = attempt-1 if attempt==0: print("You've entered inncorrect password 3 times. Your account is now blocked!") break
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["c"]) / sum(nucleotides.values()) return gc_percentage * 100 if __name__ == "__main__": sequence: str = input("\nDigite uma sequência de dna: ").strip().lower() try: print(f"\n{sequence} -> {gc_content(sequence)}%", end="\n\n") except AttributeError: print("\nSequencia de dna inválida. Tente novamente.", end="\n\n")
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 = input("\nYou may try again, i want more of these points of yours\n") stscore -= 1 else: stscore += 1 print("\nYou came this far, now lets move forward\n") #4th quest for the user print("\nI need to make a function for this program.\n") print("\n\n1: Function_block <name>\n2: FC <name>\n3: Function <name>\n4: <name> Function\n") Quest4 = input("\nWhich of the above statements is the right one, to create a function?\n") while Quest4 != '3': print("\nYou have to shape up, if you want to continue this journey!") Quest4 = input("\nTry again, but do it right this time...\n") stscore -= 1 else: stscore += 1 print("\nYou are getting better... i guess\n") return stscore
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 = int(input('Спробуй ще раз :')) popitka+=1 print('Ура! Ти вгадав, так, це число :', number, '\n Ти вгадав його за ', popitka, ' спроби\n') input('\t\t\tНатисни ентер для виходу :) ')
''' 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 type(self): return self.__dict__ == other.__dict__ # Returns a dictionary with the attributes of this assertion. def to_dict(self): d = {} for attr, value in self.__dict__.iteritems(): d[attr] = value return d # Same as to_dict(), except returns a dict with the non-default values. def to_pruned_dict(self): d = {} for attr, value in self.__dict__.iteritems(): if value != "": d[attr] = value return d # Same as to_dict(), except with pretty indentation. def prettyprint(self): print json.dumps(self.to_dict(), indent=2) # Realize the assertion given a brain and a Boolean which represents # whether the realization is a sentence fragment or not. def realize(self, brain, isFragment): return realize_brain_assertion(brain,self,isFragment)
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:] if x >= pivot]) return lower + [pivot] + upper print(pyTriples(10)) print(quickSort([1,5,3,7,8,2,3,7,1,4,7,2,20]))
#! /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 a salt based on the given key salt=[] for i in key: ascii=ord(i) if ascii >= 97 and ascii <= 122: delta=97 elif ascii >=65 and ascii <= 90: delta=65 salt.append(str(ord(i)-delta+1)) # asking for the message to encrypt, using our key (salt) given=input(" Enter the text to encrypt: ") if len(given)<1: sys.stderr.write(" ERROR nothing given\n") sys.exit(2) # encoding each text character j=0 for i in given: ascii=ord(i) if ascii >= 97 and ascii <= 122: delta = 97 elif ascii >=65 and ascii <= 90: delta = 65 else: sys.stdout.write(i) continue sys.stdout.write(chr((ascii-delta+1+int(salt[j]))%26+delta)) j+=1 if j==len(salt): j=0
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*md b_curr=b_curr - learning_rate*bd print("m {}, b {} , iteration {}".format(m_curr,b_curr,i)) x=np.array([1,2,3,4,5]) y=np.array([5,7,11,25,13]) gradient_decent(x,y)
#!/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() is equal to new a class print(f'drill count {drill.count}') drill.count = 3 print(f'drill count {drill.count}') if __name__ == '__main__': main()
#!/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 hidden_layer(x, weight, bias): hypothesis = weight * x + bias return hypothesis def cost_function(hypothesis, y): cost_v = np.sum((y - hypothesis) ** 2) / len(y) return cost_v np.random.seed(3) data = np.array([[100, 20], [150, 24], [300, 36], [400, 47], [130, 22], [240, 32], [350, 47], [200, 42], [100, 21], [110, 21], [190, 30], [120, 25], [130, 18], [270, 38], [255, 28]]) data = data.astype('float32') x_data = data[:, 0] y_data = data[:, 1] w1 = create_weight(x_data) b1 = create_bias(y_data) h1 = hidden_layer(x_data, w1, b1) # hypothesis = weight * x + bias cost = cost_function(hidden_layer(x_data, w1, b1), y_data) # cost 의 값 이제 미분해서 w와 b값 갱신 print() def numerical_gradient_w(x): h = 1e-4 grad = np.zeros_like(x) for idx in range(x.size): tmp_val = x[idx] x[idx] = tmp_val + h hf = hidden_layer(x_data, x, b1) fxh1 = cost_function(hf, y_data) x[idx] = tmp_val - h hf = hidden_layer(x_data, x, b1) fxh2 = cost_function(hf, y_data) grad[idx] = (fxh1 - fxh2) / (2 * h) x[idx] = tmp_val return grad def numerical_gradient_b(x): h = 1e-4 grad = np.zeros_like(x) for idx in range(x.size): tmp_val = x[idx] x[idx] = tmp_val + h hf = hidden_layer(x_data, w1, x) fxh1 = cost_function(hf, y_data) x[idx] = tmp_val - h hf = hidden_layer(x_data, w1, x) fxh2 = cost_function(hf, y_data) grad[idx] = (fxh1 - fxh2) / (2 * h) x[idx] = tmp_val return grad def back_propagation(x, y, w, b, epochs, learning_rate): for i in range(epochs): h1 = hidden_layer(x, w, b) cost_function(h1, y) if i % 100 == 0: print(cost_function(h1, y)) print('\n\n') grad_w = numerical_gradient_w(w) grad_b = numerical_gradient_b(b) w -= learning_rate * grad_w b -= learning_rate * grad_b return w, b total_w, total_b = back_propagation(x_data, y_data, w1, b1, 500, 0.00001) print(total_w, total_b) W = total_w.mean() B = total_b.mean() y_predict = W * x_data + B plt.scatter(x_data, y_data) plt.plot([min(x_data), max(x_data)], [min(y_predict), max(y_predict)]) plt.show()
# 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 + (rn%11) m = 70 + (rn%11) print("generate_data(): STARTING WITH " + str(n) + " ALTERNATIVES AND " + str(m) + " ATTRIBUTES.") data = { "alternatives": np.arange(1,n+1) } for i in range(1,m+1): data["Attribute " + str(i)] = list(np.random.randint(rn-(rn%11), rn+(rn%11), n)) pd.DataFrame(data).to_csv("data.csv", index=False) print("generate_data(): DATA GENERATION COMPLETED; CHECK data.csv IN CWD.") if __name__=="__main__": generate_data(72)
# -*- 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]: return False if k == len(path) - 1: return True visit[idx] = True if helper(i - 1, j, k + 1): return True if helper(i + 1, j, k + 1): return True if helper(i, j - 1, k + 1): return True if helper(i, j + 1, k + 1): return True visit[idx] = False return False for i in range(rows): for j in range(cols): if helper(i, j, 0): return True return False
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: ") inputList = inputString.split(" ") return calculator(inputList[0], inputList[2], inputList[1]) #order is 0, 2, 1 since the middle is the operator, which corresponds with index 1 def calculator(number1, number2, operator): """ Calculates the correct value from the equation that was taken from the user. If the operator or numbers are invalid, the function exits and returns the boolean value false. Valid operators are +, -, *, /, //, and ** which are addition, subtraction, multiplication, division, integer division, and power respectively. Parameters ---------- number1: float First operand. number2: float Second operand. operator: string Operator to do an operation of number1 operator number2. Returns ------- float The operation of ``number1`` and ``number2``. Examples -------- Enter equation: 10 + 11 21.0 Enter equation: 10 ** 2 100.0 """ try: #use a try and except block to test whether or not we can convert the 2 numbers into floats for valid input #https://www.tutorialspoint.com/python/python_exceptions.htm for try except handling help number1 = float(number1) number2 = float(number2) except ValueError: return False if operator == "+": return number1 + number2 elif operator == "-": return number1 - number2 elif operator == "*": return number1 * number2 elif operator == "/": if (number2 == 0): return False return number1 / number2 elif operator == "//": if (number2 == 0): return False return number1 // number2 elif operator == "**": return number1 ** number2 else: return False
#!/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 `weights` as well. """ from __future__ import division def get_min_coins(coins, target_amount, weights=0): # Returns an array X = [0,1,1,...] of length target_amount, # where X_i tells you the number of coins you need to make i money if weights == 0: weights = [1 for i in range(len(coins))] min_coins = [0] + [10000] * target_amount min_coins_desc = [0] + [10000] * target_amount min_coins_weight = [0] + [10000] * target_amount n = len(coins) for c in range(n): for target in range(coins[c], target_amount + 1): if min_coins[target - coins[c]] + 1 < min_coins[target]: min_coins_desc[target] = min_coins_desc[target - coins[c]] + 10**(n - c - 1) min_coins[target] = min(min_coins[target - coins[c]] + 1, min_coins[target]) min_coins_weight[target] = min(min_coins_weight[target - coins[c]] + weights[c], min_coins_weight[target]) for target in range(target_amount + 1): min_coins_desc[target] = str(min_coins_desc[target]).zfill(n) return min_coins, min_coins_desc, min_coins_weight # BASKETS ------------------------------------------------ basket_sizes = [] basket_prices = [] with open("ons_data/baskets2.txt", "r") as f: for line in f: line_split = line.split(',') basket_sizes.append(int(line_split[0])) basket_prices.append(int(line_split[1])) prices_less_than = 2000 basket_prices_we_want = [basket_prices[i] for i in xrange(len(basket_prices)) if basket_prices[i] < prices_less_than] lowest_banknote = 500 lowest_coin = 1 ends_in = range(0, lowest_banknote, lowest_coin) prices_mod_lowest_banknote = [i % lowest_banknote for i in basket_prices_we_want] prices_end_in_count = [sum(1 for i in prices_mod_lowest_banknote if i == j) for j in ends_in] prices_end_in_count_as_percent = [i / sum(prices_end_in_count) * 100 for i in prices_end_in_count] # END BASKETS --------------------------------------------- ''' name = "UK" up_to_amount = 499 coins = [1,2,5,10,20,50,100,200] weights = [3.56,7.12,3.25,6.5,5,8,9.5,12] weightings_for_each_amount = prices_end_in_count_as_percent name = "UK self-service" up_to_amount = 499 coins = [1,2,5,20,100,200] weights = [3.56,7.12,3.25,5,9.5,12] weightings_for_each_amount = prices_end_in_count_as_percent ''' name = "UK no 1p or 2p" up_to_amount = 499 // 5 coins = [5 // 5, 10 // 5, 20 // 5, 50 // 5, 100 // 5, 200 // 5] weights = [3.25, 6.5, 5, 8, 9.5, 12] weightings_for_each_amount = prices_end_in_count_as_percent weightings_for_each_amount = [0 for i in range(100)] weightings_for_each_amount[0] = (sum(prices_end_in_count_as_percent[0:3]) + sum(prices_end_in_count_as_percent[498:500])) / 5 for i in range(1, 100): # Swedish rounding (i.e. prices of baskets would be rounded to the nearest 5p) weightings_for_each_amount[i] = sum(prices_end_in_count_as_percent[5 * i - 2:5 * i + 3]) / 5 ''' name = "UK 1960" up_to_amount = 479 # in farthings coins = [1,2,1*4,3*4,6*4,12*4,24*4,30*4] weights = [2.83,5.67,9.4,6.8,2.83,5.66,11.31,14.14] name = "US" up_to_amount = 99 coins = [1,5,10,25] weights = [2.5,5,2.268,5.67] name = "Canada" up_to_amount = 495/5 coins = [5/5,10/5,25/5,100/5,200/5] weights = [3.95,1.75,4.4,6.27,6.92] name = "Euro" up_to_amount = 499 coins = [1,2,5,10,20,50,100,200] weights = [2.3,3.06,3.92,4.1,5.74,7.8,7.5,8.5] name = "Japan" up_to_amount = 999 coins = [1,5,10,50,100,500] weights = [1,3.75,4.5,4,4.8,7] name = "Switzerland" up_to_amount = 995/5 coins = [5/5,10/5,20/5,50/5,100/5,200/5,500/5] weights = [1.8,3,4,2.2,4.4,8.8,13.2] name = "Australia" up_to_amount = 495/5 coins = [5/5,10/5,20/5,50/5,100/5,200/5] weights = [2.83,5.65,11.3,15.55,9,6.6] name = "NZ" up_to_amount = 490/10 coins = [10/10,20/10,50/10,100/10,200/10] weights = [3.3,4,5,8,10] name = "Harry Potter" up_to_amount = 492 coins = [1,29] weights = [1,29] name = "Mexico" up_to_amount = 1950/50 coins = [50/50,100/50,200/50,500/50,1000/50] weights = [3.103,3.95,5.19,7.07,10.329] name = "China" up_to_amount = 100/10 coins = [10/10,50/50] weights = [3.22,3.8] name = "Sweden" up_to_amount = 19 coins = [1,2,5,10] weights = [3.6,4.8,6.1,6.6] name = "Euro no 1 or 2 cent" up_to_amount = 495/5 coins = [5/5,10/5,20/5,50/5,100/5,200/5] weights = [3.92,4.1,5.74,7.8,7.5,8.5] name = "UK new £1 coin" up_to_amount = 499 coins = [1,2,5,10,20,50,100,200] weights = [3.56,7.12,3.25,6.5,5,8,8.75,12] name = "Singapore" up_to_amount = 195/5 coins = [5/5,10/5,20/5,50/5,100/5] weights = [1.24,2.83,5.66,9.33,16.85] name = "HK" up_to_amount = 990/10 coins = [10/10,20/10,50/10,100/10,200/10,500/10] weights = [1.85,2.59,4.92,7.1,8.41,13.5] name = "Norway" up_to_amount = 49 coins = [1,5,10,20] weights = [4.35,7.85,6.8,9.9] name = "S Korea" up_to_amount = 990/10 coins = [10/10,50/10,100/10,500/10] weights = [1.22,4.16,5.42,7.7] name = "Turkey" up_to_amount = 495/5 coins = [5/5,10/5,25/5,50/5,100/5] weights = [2.9,3.15,4,6.8,8.2] name = "India" up_to_amount = 9 coins = [1,2,5] weights = [3.79,4.85,6] name = "Russia" up_to_amount = 4990/10 coins = [10/10,50/10,100/10,200/10,500/10,1000/10] weights = [1.95,2.9,3.25,5.1,6.45,5.63] name = "Brazil" up_to_amount = 195/5 coins = [5/5,10/5,25/5,50/5,100/5] weights = [4.1,4.8,7.55,7.81,7] name = "South Africa" up_to_amount = 990/10 coins = [10/10,20/10,50/10,100/10,200/10,500/10] weights = [2,3.5,5,4,5.5,9.5] name = "UK with £1.33" up_to_amount = 499 coins = [1,2,5,10,20,50,100,133,200] weights = [3.56,7.12,3.25,6.5,5,8,9.5,30,12] name = "Best 3" up_to_amount = 499 coins = [1, 7, 57, 80] weights = 0 name = "Stamps" up_to_amount = 499 coins = [1, 55, 64, 75, 96, 105, 133, 152, 225] weights = 0 name = "UK with £1.23 instead of £1" up_to_amount = 499 coins = [1,2,5,10,20,50,123,200] weights = [3.56,7.12,3.25,6.5,5,8,8.75,12] name = "UK with no 1p or 2p" up_to_amount = 495/5 coins = [5/5,10/5,20/5,50/5,100/5,200/5] weights = [3.25,6.5,5,8,9.5,12] #coins = [1,2,1*4,3*4,6*4,12*4,24*4,30*4] name = "UK with 25p instead of 20p" up_to_amount = 499 coins = [1,2,5,10,25,50,100,200] weights = [3.56,7.12,3.25,6.5,5,8,9.5,12] ''' print name print "Lowest note: ", up_to_amount + 1 print "Coins: ", coins print "Average number of coins required: ", round(sum(get_min_coins(coins, up_to_amount)[0]) / float(up_to_amount), 2) print "Average weight of coins required: ", round(sum(get_min_coins(coins, up_to_amount, weights)[2]) / float(up_to_amount), 1), "g" print "On average expect to receive X of each coin: ", each_coin = get_min_coins(coins, up_to_amount)[1] print [round(sum([float(each_coin[amount][c]) for amount in range(len(each_coin))]) / float(len(each_coin)), 3) for c in range(len(coins))] print "" print "WEIGHTED by how common they are:" weightings_symmetric = [weightings_for_each_amount[0]] + [(weightings_for_each_amount[i] + weightings_for_each_amount[len(weightings_for_each_amount) - i]) / 2 for i in range(1, len(weightings_for_each_amount))] gmc = get_min_coins(coins, up_to_amount)[0] mean_weighting = (sum(weightings_symmetric) / len(weightings_symmetric)) print "Average number of coins required: ", round(sum([gmc[i] * weightings_symmetric[i] for i in range(up_to_amount)]) / float(up_to_amount) / mean_weighting, 2)
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 getPaint(self): return self.paint def getInterior(self): return self.interior def getEngine(self): return self.engine def getTires(self): return self.tires def main(): paint = input("Enter paint color(red/black/silver): ") interior = input("Enter interior material(black leather/brown leather): ") engine = input("Enter engine specs(5/6/7 liter, v6/v8, 500-800hp): ") tires = input("enter tire type(road/sport): ") car1 = Car(paint, interior, engine, tires) print("Your Vehicle: ") print("Paint: ",car1.getPaint()) print("Interior: ",car1.getInterior()) print("Engine: ",car1.getEngine()) print("Tires: ",car1.getTires()) main()
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(input("Please enter the price of item 3:")) food4="Subtotal:" price4=price1+price2+price3 food5="Tax:" price5=float((price1+price2+price3)/12.5) food6="Total:" price6=price1+price2+price3+price5 print("<<<<<<<<<<<<<<<<Receipt>>>>>>>>>>>>>>>") receipt(food1, price1) receipt(food2, price2) receipt(food3, price3) receipt(food4, price4) receipt(food5, price5) receipt(food6, price6) print("____________________________________") print("*Thank you for your support*")
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 times your loan is compounded per year:")) years=float(input("Please enter the life of the loan(in years):")) amount=principle*((1+(rate/number))**(number*years)) print("The total payment amount on your loan is:",interest(amount))
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=input("Enter last name:") print("*********************************") idcard(item1,item2) idcard(item5,item6) idcard(item3,item4) print("*********************************")
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 not palindrome:")
"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 == "correct": print("Number of attempt: "+ str(z)) elif x == "close": print("Number of attempt: "+ str(z)) break else: print("wrong input") z=z-1 z=z+1
"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]) print(ste) print(str(sx)+" square left") if sx == 0: return 0 else: return 3 s=3 while s == 3: p = 3 while p == 3: x =str(input("Enter the coordinate for x:")) x = x.split(",") if a[int(x[0])-1][int(x[1])-1] == 0: a[int(x[0])-1][int(x[1])-1] = "x" p = 0 else: print("Already place") s = decided(a) if s == 3: q = 3 while q == 3: x =str(input("Enter the coordinate for o:")) x = x.split(",") if a[int(x[0])-1][int(x[1])-1] == 0: a[int(x[0])-1][int(x[1])-1] = "o" q = 0 else: print("Already place") s = decided(a)
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 ( first_letter_check == letter and second_letter_check != letter or first_letter_check != letter and second_letter_check == letter ): valid_pass_count = valid_pass_count + 1 print(valid_pass_count)
# -*- 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) weather_data = weather.get_weather_on_days(city, days) for item in weather_data: print(item) if input('If you want to see another city enter (y)') != 'y': break
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 ---------- phi, theta : float or numpy.array azimuthal and polar angle in radians. Returns ------- nhat : numpy.array unit vector(s) in direction (phi, theta). """ x = numpy.sin(theta) * numpy.cos(phi) y = numpy.sin(theta) * numpy.sin(phi) z = numpy.cos(theta) return numpy.array([x, y, z]) def polar_from_cartesian(x): """ Embedded 3D unit vector from spherical polar coordinates. Parameters ---------- x : array_like cartesian coordinates Returns ------- phi, theta : float or numpy.array azimuthal and polar angle in radians. """ x = numpy.array(x) r = (x*x).sum(axis=0)**0.5 x, y, z = x theta = numpy.arccos(z / r) phi = numpy.mod(numpy.arctan2(y, x), numpy.pi*2) return phi, theta def polar_from_decra(ra, dec): """ Convert from spherical polar coordinates to ra and dec. Parameters ---------- ra, dec : float or numpy.array Right ascension and declination in degrees. Returns ------- phi, theta : float or numpy.array Spherical polar coordinates in radians """ phi = numpy.mod(ra/180.*numpy.pi, 2*numpy.pi) theta = numpy.pi/2-dec/180.*numpy.pi return phi, theta def decra_from_polar(phi, theta): """ Convert from ra and dec to spherical polar coordinates. Parameters ---------- phi, theta : float or numpy.array azimuthal and polar angle in radians Returns ------- ra, dec : float or numpy.array Right ascension and declination in degrees. """ ra = phi * (phi < numpy.pi) + (phi-2*numpy.pi)*(phi > numpy.pi) dec = numpy.pi/2-theta return ra/numpy.pi*180, dec/numpy.pi*180 def logsinh(x): """ Compute log(sinh(x)), stably for large x. Parameters ---------- x : float or numpy.array argument to evaluate at, must be positive Returns ------- float or numpy.array log(sinh(x)) """ if numpy.any(x < 0): raise ValueError("logsinh only valid for positive arguments") return x + numpy.log(1-numpy.exp(-2*x)) - numpy.log(2) def rotation_matrix(a, b): """ The rotation matrix that takes a onto b. Parameters ---------- a, b : numpy.array Three dimensional vectors defining the rotation matrix Returns ------- M : numpy.array Three by three rotation matrix Notes ----- StackExchange post: https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d """ v = numpy.cross(a, b) s = v.dot(v)**0.5 if s == 0: return numpy.identity(3) c = numpy.dot(a, b) Id = numpy.identity(3) v1, v2, v3 = v vx = numpy.array([[0, -v3, v2], [v3, 0, -v1], [-v2, v1, 0]]) vx2 = numpy.matmul(vx, vx) R = Id + vx + vx2 * (1-c)/s**2 return R def spherical_integrate(f, log=False): r""" Integrate an area density function over the sphere. Parameters ---------- f : callable function to integrate (phi, theta) -> float log : bool Should the function be exponentiated? Returns ------- float Spherical area integral .. math:: \int_0^{2\pi}d\phi\int_0^\pi d\theta f(\phi, \theta) \sin(\theta) """ if log: def g(phi, theta): return numpy.exp(f(phi, theta)) else: g = f ans, _ = dblquad(lambda phi, theta: g(phi, theta)*numpy.sin(theta), 0, numpy.pi, lambda x: 0, lambda x: 2*numpy.pi) return ans def spherical_kullback_liebler(logp, logq): r""" Compute the spherical Kullback-Liebler divergence. Parameters ---------- logp, logq : callable log-probability distributions (phi, theta) -> float Returns ------- float Kullback-Liebler divergence .. math:: \int P(x)\log \frac{P(x)}{Q(x)} dx Notes ----- Wikipedia post: https://en.wikipedia.org/wiki/Kullback-Leibler_divergence """ def KL(phi, theta): return (logp(phi, theta)-logq(phi, theta))*numpy.exp(logp(phi, theta)) return spherical_integrate(KL)
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: a += 1 b += 1 t.join() if __name__ == '__main__': main()
"""############################################# # 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 True mult(2, -4) ValueError("This function works only with postive integers") """ def mult(a: int, n: int) -> int: if a == 0: return 0 elif a == 1: return n elif n == 1: return a elif n < 0: raise ValueError(Exception, "This function works only with postive integers") else: return n + mult(a - 1, n) if __name__ == '__main__': print(mult(2, 4)) print(mult(2, 0)) print(mult(2, -4))
"""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: self.head = Node(data) else: newnode = Node(data) newnode.next = self.head self.head = newnode def pop(self): if self.isempty(): return None else: poppednode = self.head self.head = self.head.next poppednode.next = None return poppednode.data def peek(self): if self.isempty(): return None else: return self.head.data def display(self): iternode = self.head if self.isempty(): print("Stack Empty") else: while (iternode != None): print(iternode.data) iternode = iternode.next return MyStack = Stack() MyStack.push(18) MyStack.push(11) MyStack.push(20) MyStack.display() print("Fifo element is ", MyStack.peek()) MyStack.pop() MyStack.pop() MyStack.display() print("Fifo element is ", MyStack.peek())
"""############################################# # 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.5, 2) == 12.25 True to_power(2, -1) ValueError: This function works only with exp > 0. pass""" from typing import Optional def to_power(x, exp): if exp == 1: return x * exp else: if exp <= 0: raise Exception(ValueError, "This function works only with exp > 0") else: return x * to_power(x, exp-1) if __name__ == '__main__': print(to_power(2, 3) == 8) print(to_power(3.5, 2) == 12.25) print(to_power(2, -1))
"""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, denominator: int): self.den = denominator self.num = numerator def __add__(self, other): return Fraction(self.num * other.den + self.den * other.num, self.den * other.den) def __sub__(self, other): return Fraction(self.num * other.den - other.num * self.den, self.den * other.den) pass def __truediv__(self, other): return self.__mul__(Fraction(other.den, other.num)) def __mul__(self, other): return Fraction(self.num * other.num, self.den * other.den) def __str__(self): return f"{self.num}\n——\n{self.den}\n" if __name__ == '__main__': f1 = Fraction(3, 7) f2 = Fraction(5, 6) print(f1 + f2) print(f1 - f2) print(f1 * f2) print(f1 / f2)
"""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[0]) + sum_of_digits(digit_string[1:]) if __name__ == '__main__': print(sum_of_digits("26")) print(sum_of_digits("test"))