text
stringlengths
37
1.41M
""" An implementation of gaussian processes. Author: Ben Ellis """ from functools import partial from typing import Callable, Dict import numpy as np import pandas as pd class GaussianProcess: def __init__( self, kernel: Callable[[np.array, np.array, Dict[str, float]], np.array], sigma: float = 0.001, ): self.kernel = kernel self.sigma = sigma def draw(self): """ Given the fitted mean and covariance, draw function values at the fit points. """ return np.random.default_rng().multivariate_normal(self.mean, self.cov) def set_kernel_params(self, params: Dict[str, float]): self.kernel = partial(self.kernel, params=params) def fit_and_predict( self, to_predict: pd.DataFrame, data: pd.DataFrame, x: str, y: str ): """ fits a gaussian process to the data, and produces predictions for the time values in to_predict. Arguments --------- to_predict: a Dataframe to predict the data for. This should be a numeric type data: The observed data we can use. x: The X column to use (i.e. the x we want to use to make the prediction) y: The Y column to use (i.e. the column we wish to predict) Returns ------- arr -- A sample of function values at the to_predict points. """ # compute the kernel function on the data self.data_x = np.array(data[x]) self.data_y = np.array(data[y]) self.to_predict_x = np.array(to_predict[x]) # add noise to help with the matrix conditioning k_dd = self.kernel(self.data_x, self.data_x) + 1e-4 * np.eye( self.data_x.shape[0] ) # and on the data and to_predict k_pd = self.kernel(self.to_predict_x, self.data_x) k_pp = self.kernel(self.to_predict_x, self.to_predict_x) data_mat = k_dd + (self.sigma ** 2) * np.eye(k_dd.shape[0]) cholesky = np.linalg.cholesky(data_mat) # using the pseudoinverse is slower, but is better for conditioning inv = np.linalg.pinv(cholesky) inv = np.dot(inv.T, inv) self.mean = np.dot(np.dot(k_pd, inv), self.data_y) self.cov = k_pp - np.dot(np.dot(k_pd, inv), k_pd.T) self.log_marginal_likelihood = ( -0.5 * np.dot(np.dot(self.data_y.T, inv), self.data_y) - np.sum(np.log(np.diag(cholesky))) - (self.data_x.shape[0] / 2) * np.log(2 * np.pi) ) self.predictions = self.draw() return self.predictions
"""Utilities for working with sequence i/o. """ from collections import OrderedDict import re import textwrap import numpy as np __author__ = 'Hayden Metsky <hayden@mit.edu>' def read_fasta(fn, data_type='str', replace_degenerate=False): """Read a FASTA file. Args: fn: path to FASTA file to read data_type: determines whether to store a sequence as a native Python string ('str') or as a numpy array ('np') replace_degenerate: when True, replace the degenerate bases ('Y','R','W','S','M','K') with 'N' Returns: dict mapping the name of each sequence to the sequence itself. The mapping is ordered by the order in which the sequence is encountered in the FASTA file; this helps in particular with replicating past results, where the input order could affect the output. """ degenerate_pattern = re.compile('[YRWSMK]') m = OrderedDict() with open(fn) as f: curr_seq_name = "" for line in f: line = line.rstrip() if len(line) == 0: continue if curr_seq_name == "": # Must encounter a new sequence assert line.startswith('>') if len(line) == 0: # Reset the sequence being read on an empty line curr_seq_name = "" elif line.startswith('>'): curr_seq_name = line[1:] m[curr_seq_name] = '' else: # Append the sequence if replace_degenerate: line = degenerate_pattern.sub('N', line) m[curr_seq_name] += line if data_type == 'str': # Already stored sequence as string m_converted = m elif data_type == 'np': m_converted = OrderedDict() for seq_name, seq in m.items(): m_converted[seq_name] = np.fromstring(seq, dtype='S1') else: raise ValueError("Unknown data_type " + data_type) return m_converted def iterate_fasta(fn, data_type='str', replace_degenerate=False): """Scan through a FASTA file and yield each sequence. This is a generator that scans through a given FASTA file and, upon completing the read of a sequence, yields that sequence. Args: fn: path to FASTA file to read data_type: determines whether to store a sequence as a native Python string ('str') or as a numpy array ('np') replace_degenerate: when True, replace the degenerate bases ('Y','R','W','S','M','K') with 'N' Yields: each sequence in the FASTA file """ degenerate_pattern = re.compile('[YRWSMK]') def format_seq(seq): if data_type == 'str': # Already stored as str return seq elif data_type == 'np': return np.fromstring(seq, dtype='S1') else: raise ValueError("Unknown data_type " + data_tyoe) with open(fn) as f: curr_seq = '' for line in f: line = line.rstrip() if len(line) == 0: continue if line.startswith('>'): # Yield the current sequence (if there is one) and reset the # sequence being read if len(curr_seq) > 0: yield format_seq(curr_seq) curr_seq = '' else: # Append the sequence if replace_degenerate: line = degenerate_pattern.sub('N', line) curr_seq += line if len(curr_seq) > 0: yield format_seq(curr_seq) def write_fasta(seqs, out_fn, chars_per_line=70): """Write sequences to a FASTA file. Args: seqs: dict (or OrderedDict) mapping the name of each sequence to the sequence itself out_fn: path to FASTA file to write chars_per_line: the number of characters to put on each line when writing a sequence """ with open(out_fn, 'w') as f: for seq_name, seq in seqs.items(): if isinstance(seq, np.ndarray): # Convert seq to a string seq = ''.join(seq) f.write('>' + seq_name + '\n') seq_wrapped = textwrap.wrap(seq, chars_per_line) for seq_line in seq_wrapped: f.write(seq_line + '\n') f.write('\n')
# https://math.stackexchange.com/questions/442459/for-the-fibonacci-numbers-show-for-all-n-f-12f-22-dotsf-n2-f-nf-n1 def fibonacci_sum_squares_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current * current return sum % 10 def fibonacci_sum_squares_fast(n): lesser_n = n % 60 lesser_nplus = (n + 1) % 60 if lesser_n <= 1: a = lesser_n else: a = fibo(lesser_n) if lesser_nplus <= 1: b = lesser_nplus else: b = fibo(lesser_nplus) return (a * b) % 10 def fibo(n): a, b, c = 0, 1, 0 for _ in range(2, n + 1): c = a + b c = c % 10 b, a = c, b return c if __name__ == '__main__': n = int(input()) print(fibonacci_sum_squares_naive(n)) print(fibonacci_sum_squares_fast(n))
import random class GeneticAlgorithm: def __init__(self, population_size = 8, mutation_rate = 0.001, number_iterations = 1000): self.population_size = population_size self.number_iterations = number_iterations self.mutation_rate = number_iterations # generates binary initial population def generate_initial_population(self, genes): for i in range(self.population_size): genes.append('{0:07b}'.format(random.randint(1, 127))) # calculates fitness function # in our case we are optimizing 2*(x^2 + 1) function def calculate_fitness_function(self, x): value = int(x, 2) return 2*(value**2 + 1) # calculates the sum of all fitness functions def roulette_fitness_sum(self, genes): sum = 0 for x in genes: sum += self.calculate_fitness_function(x) return sum def roulette_probability_for_gene(self, x, sum): return self.calculate_fitness_function(x) / sum # selects arents to the next generation # based on roulette roulette wheel algorithm def select_parents(self, genes): roulette = [] sum = self.roulette_fitness_sum(genes) roulette.append(self.roulette_probability_for_gene(genes[0], sum)) for i in range(1, len(genes)): roulette.append(self.roulette_probability_for_gene(genes[i], sum)) roulette[i] += roulette[i-1] parent_genes = [] for i in range(0, len(genes)): parent_genes.append(genes[self.get_chosen_gene_index(roulette)]) return parent_genes # helper function which gets the index of # gene which was chosen to the next population def get_chosen_gene_index(self, roulette): val = random.random() index = 0 for i in range(0, len(roulette)): if val < float(roulette[i]): return i return index # makes crossover between genes # choosing the random locus def crosover_genes(self, genes): random.shuffle(genes) crossed_genes=[] for i in range(0,len(genes),2): locus=random.randint(0,len(genes[0])) crossed_genes.append(self.combine_genes(genes[i+1],genes[i],locus)) crossed_genes.append(self.combine_genes(genes[i],genes[i+1],locus)) return crossed_genes # helper function for glueing two genes together def combine_genes(self, parent_first, parent_second, locus): crossed_gene = parent_first[:locus] + parent_second[locus:] return crossed_gene # performs mutation in the whole generation def mutate_genes(self, genes): mutated_genes = [] for x in genes: mutated_genes.append(self.mutate_gen(x)) return mutated_genes # performs mutation of a gene # accordingly to mutation rate def mutate_gen(self, gen): if random.random() < self.mutation_rate: locus = random.randint(0, len(gen) - 1) temp = list(gen) temp[locus] = '0' if temp[locus] == '1' else '1' return ''.join(temp) return gen # prints population inormaiton def print_population_information(self, genes): print('For genes: ' + str(genes)) print('Max value is: ' + str(self.get_max_value_for_population(genes))) # gets the mex fitness value of the fitness function # from the whole population def get_max_value_for_population(self, genes): temp_array = [] for x in genes: temp_array.append(self.calculate_fitness_function(x)) return max(temp_array) # performs the whole agenetic algorithm def perform(self): all_genes=[] for i in range(1,128): all_genes.append(i) genes=[] for i in range(0, self.population_size): genes.append("{:07b}".format(all_genes.pop(random.randint(0, len(all_genes))))) for i in range(self.number_iterations): genes = self.select_parents(genes) genes = self.crosover_genes(genes) genes = self.mutate_genes(genes) self.print_population_information(genes)
""" CMPS 2200 Assignment 1. See assignment-01.pdf for details. """ # no imports needed. def foo(x): if x <= 1: return x else: return foo(x-1) + foo(x-2) def longest_run(mylist, key): #iterative sequential version tempcounter = 0 finalcount = 0 for i in mylist: if i != key: if tempcounter > finalcount: finalcount = tempcounter tempcounter = 0 else: tempcounter += 1 if tempcounter > finalcount: finalcount = tempcounter return finalcount class Result: """ done """ def __init__(self, left_size, right_size, longest_size, is_entire_range): self.left_size = left_size # run on left side of input self.right_size = right_size # run on right side of input self.longest_size = longest_size # longest run in input self.is_entire_range = is_entire_range # True if the entire input matches the key def __repr__(self): return('longest_size=%d left_size=%d right_size=%d is_entire_range=%s' % (self.longest_size, self.left_size, self.right_size, self.is_entire_range)) def longest_run_recursive(mylist, key): if len(mylist) == 1: if key in mylist: return Result(1,1,1,True) else: return Result(0,0,0,False) half= len(mylist)//2 right = longest_run_recursive(mylist[half:],key) left = longest_run_recursive(mylist[:half],key) if right.is_entire_range == True and left.is_entire_range == True: return Result(left.longest_size, right.longest_size, len(mylist), True) elif right.is_entire_range == True: return Result(left.left_size,right.longest_size + left.right_size,right.longest_size + left.right_size,False) elif left.is_entire_range == True: return Result(left.longest_size + right.left_size,right.right_size, left.longest_size + right.left_size,False) elif mylist[half] == key and mylist[half - 1] == key: ans = max(left.longest_size, right.longest_size, right.left_size + left.right_size) return Result(left.right_size,right.left_size,ans, False) else: return Result(left.left_size, right.right_size,max(right.longest_size,left.longest_size),False) ## Feel free to add your own tests here. def test_longest_run(): assert longest_run([2,12,12,8,12,12,12,0,12,1], 12) == 3
# -*- coding:utf-8 -*- """ @author: timkhuang @contact: timkhuang@icloud.com @software: PyCharm @file: View.py.py @time: 06/07/2020 21:24 @description: This is the abstract class for all the rendering/visualisation of the game/board. """ from abc import ABC, abstractmethod class View(ABC): """ An Abstract class for all kinds of GUI. Provide a run() function to draw the GUI and get the user input. """ @abstractmethod def draw(self, board): """ Show the board. Provide a GUI. Args: board (matrix of PointData): The processed board with key info hidden """ pass @abstractmethod def input(self): """ Get the the next step of the player. Returns: input (tuple of int): The coordinate of the user input. """ pass @abstractmethod def get_board_size(self): """ Get the board dimension at start of game Returns: board ({"mine_count": int, "width": int, "height": int}): The dimension of the board """ pass @abstractmethod def fail(self): """ Deal with the situation when game fails. Returns: continue (bool): True is restart. False otherwise. """ pass @abstractmethod def win(self): """ Deal with the situation when game wins. Returns: continue (bool): True is restart. False otherwise. """ pass def run(self, board): """ To run the view, showing the board and get an input from the player. Args: board (matrix of PointData): The processed board with key info hidden Returns: result ({"flag": bool, "x": int, "y": int}): The coordinate of the user input. """ self.draw(board) return self.input()
from numpy import abs as ABS def absolute(xi, xf): ''' Calculates absolute error params: - xi: previous value - xf: current value ''' if xi == None or xf == None: raise AttributeError("values xi and xf cannot be None") return ABS(xi - xf) def relative(xi, xf): ''' Calculates relative error params: - xi: previous value - xf: current value warning: If xf (current value) is zero, a ZeroDivisionError is raised ''' if xf == 0: raise ZeroDivisionError("Current value (xf) cannot be zero") if xi == None or xf == None: raise AttributeError("values xi and xf cannot be None") return ABS( (xi - xf)/ xf )
X=int(input("Enter the value for holder 1:")) Y=int(input("Enter the value for holder 1:")) Z=int(input("Enter the value for jug:")) x=0 y=0 while Z<X<Y: print(x,y) if x==0: for i in range(0,X): if x==X: break x+=1 if not(y==0): print(x, y) for i in range(0,x): if y==Y: print(x, y) y=0 break y+=1 x-=1 if x==Z or y==Z: print("Completed") break
import datetime import calendar from enum import IntEnum class Weekday(IntEnum): MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 def meetup_date(year, month, nth=None, weekday=None): day = 1 if weekday is None: nth = 4 weekday = 3 if nth < 0: nth_mod = nth * -1 day = calendar.monthrange(year, month)[1] calendar_day = datetime.date(year, month, day) while calendar_day.weekday() != weekday: day -= 1 calendar_day = datetime.date(year, month, day) return datetime.date(year, month, day - (nth_mod-1) * 7) else: calendar_day = datetime.date(year, month, day) while calendar_day.weekday() != weekday: day += 1 calendar_day = datetime.date(year, month, day) return datetime.date(year, month, day + (nth-1) * 7)
# -*- coding: utf-8 -*- """Basic tests for the binary search tree""" import unittest from structures.binary_tree import BinaryTree class TestBinaryTree(unittest.TestCase): """Basic test class for binary tree""" def test_empty(self): """Basic test method for binary tree""" self.assertTrue(BinaryTree().empty()) def test_insert(self): """Basic test method for binary tree""" bt = BinaryTree() bt.insert(20) bt.insert(10) bt.insert(30) bt.insert(25) bt.insert(35) self.assertEqual(str(bt), '10,20,25,30,35') def test_remove_left_leaf(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 30, 25, 35]) bt.remove(25) self.assertEqual(str(bt), '10,20,30,35') def test_remove_leaf_right(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 30, 25, 35]) bt.remove(35) self.assertEqual(str(bt), '10,20,25,30') def test_remove_only_left(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 5, 30, 25, 35]) bt.remove(10) self.assertEqual(str(bt), '5,20,25,30,35') def test_remove_only_right(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 15, 30, 25, 35]) bt.remove(10) def test_remove_both(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 15, 30, 25, 35]) bt.remove(30) self.assertEqual(str(bt), '10,15,20,25,35') ''' 20 / \ 10 30 / \ 25 35 / 24 ''' def test_remove_both_again(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 30, 25, 24, 35]) bt.remove(30) self.assertEqual(str(bt), '10,20,24,25,35') ''' 20 / \ 10 30 / \ 25 35 / \ 24 27 ''' def test_double_recursion(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 30, 25, 24, 27, 35]) bt.remove(30) self.assertEqual(str(bt), '10,20,24,25,27,35') def test_remove_root(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 30, 25, 35]) bt.remove(20) self.assertEqual(str(bt), '10,25,30,35') def test_init(self): """Basic test method for binary tree""" bt = BinaryTree([20, 10, 30, 25, 35]) self.assertEqual(str(bt), '10,20,25,30,35')
# -*- coding: utf-8 -*- '''Singly linked list implementation Author: Larsen Close Version: Completed through extra credit level work with implementation and tests for extra methods Outline and initial tests provided in class by Professor Dr. Beaty at MSU Denver Todo: * Make runnable from file * Also also use ``sphinx.ext.todo`` extension ''' class LinkedList(): '''Singly linked list class''' class Node(): '''Node class for the linked list''' def __init__(self, value, next_node): self.value = value self.next_node = next_node def __init__(self, initial=None): self.front = self.back = self.current = None if initial is not None: for x in initial: self.push_front(x) def empty(self): '''empty method for linked list returns empty list''' return self.front == self.back is None def __iter__(self): self.current = self.front return self def __next__(self): if self.current: tmp = self.current.value self.current = self.current.next_node return tmp raise StopIteration() def push_front(self, value): '''push front method for linked list, takes value pushes onto front''' new = self.Node(value, self.front) if self.empty(): self.front = self.back = new else: self.front = new def pop_front(self): '''pop front method for linked list, removes value from list front''' if self.empty(): raise RuntimeError("Empty List") tmp = self.front.value if self.front == self.back is not None: self.front = self.back = None return tmp self.front = self.front.next_node return tmp def push_back(self, value): '''push back method for linked list, takes value pushes onto back''' new = self.Node(value, None) if self.empty(): self.front = self.back = new else: self.back.next_node = new self.back = new def pop_back(self): '''pop back method for linked list, removes value from list back''' if self.empty(): raise RuntimeError("Empty List") tmp = self.back.value previous = None current = self.front if self.front == self.back is not None: self.front = self.back = None return tmp while current.next_node is not None: previous = current current = current.next_node self.back = previous self.back.next_node = None return tmp def __str__(self): tmp = "" while self.front.next_node is not None: tmp = tmp + str(self.pop_back()) + ", " tmp = tmp + str(self.pop_back()) return tmp def __repr__(self): return 'LinkedList((' + str(self) + '))' def delete_value(self, value): '''delete method for linked list, removes value from list''' previous = None current = self.front if (self.front == self.back is not None) and ( self.front.value == value): self.front.next_node = None self.front = self.back = None return while current is not None: if current.value == value: if previous is None: self.front = self.front.next_node return if current == self.back: self.back = previous return previous.next_node = current.next_node return previous = current current = current.next_node raise RuntimeError("Value not present") def find_mid(self): '''find mid method for linked list, returns list middle''' if self.empty(): raise RuntimeError("list empty") fast = self.front slow = self.front while (fast.next_node is not None) and (fast.next_node.next_node): fast = fast.next_node.next_node slow = slow.next_node return slow.value
""" Basic TSP Example file: Individual.py """ import collections import random import math import uuid class Individual: def __init__(self, _size, _data, cgenes): """ Parameters and general variables """ self.fitness = 0 self.genes = [] self.genSize = _size self.data = _data """ Associate an UUID, needed for debug code """ if __debug__: # This has a severe performance penalty, and doubles run time self.uuid = uuid.uuid4() else: self.uuid = None if cgenes: # Child genes from crossover self.genes = cgenes else: # Random initialisation of genes self.genes = list(self.data.keys()) random.shuffle(self.genes) def copy(self): """ Creating a copy of an individual """ ind = Individual(self.genSize, self.data,self.genes[0:self.genSize]) ind.fitness = self.getFitness() """ Copy the UUID, as the sequence is exactly the same """ ind.uuid = self.uuid return ind def euclideanDistance(self, c1, c2): """ Distance between two cities """ d1 = self.data[c1] d2 = self.data[c2] return math.sqrt( (d1[0]-d2[0])**2 + (d1[1]-d2[1])**2 ) # Use this version for performance #return (d1[0]-d2[0])**2 + (d1[1]-d2[1])**2 def getFitness(self): return self.fitness def computeFitness(self): """ Computing the cost or fitness of the individual """ self.fitness = self.euclideanDistance(self.genes[0], self.genes[len(self.genes)-1]) for i in range(0, self.genSize-1): self.fitness += self.euclideanDistance(self.genes[i], self.genes[i+1]) def __eq__(self, other): """ Help check for duplicates, needed for debug code """ assert(None == other or isinstance(other, Individual)) if None == other: return False if None == self.genes and None != other.genes: return False if None != self.data and None == other.genes: return False if len(self.genes) != len(other.genes): return False self_keys = self.genes other_keys = other.genes for i in range(len(self_keys)): if self_keys[i] != other_keys[i]: return False return True def validate(self): """ Validate that it is a proper setting """ allkeys = list(self.data.keys()) for key in allkeys: if key not in self.genes: return False if len(allkeys) != len(self.genes): return False duplicates = [item for item, count in collections.Counter(self.genes).items() if count > 1] #print ("\n", "-" * 80, "\n", allkeys,"\n", self.genes, "\n", duplicates, "\n", "*" * 80) return None == duplicates or 0 == len(duplicates) def __hash__(self): """ Again, needed for debug code to find duplicates """ return self.uuid.int if self.uuid != None else 0 def __repr__(self): return f"Individual: {self.uuid.urn if None != self.uuid else 'GUID_UNAVAILABLE'}"
# coding=utf-8 import time from com.igitras.algorithm.libs import swap_element, random_list __author__ = 'mason' # 直接插入排序 def direct_insertion(list_to_sort): length = len(list_to_sort) index = 1 while index < length: inner_index = index while inner_index >= 1: if list_to_sort[inner_index] < list_to_sort[inner_index - 1]: swap_element(list_to_sort, inner_index, inner_index - 1) else: break inner_index -= 1 index += 1 list_to_sort = random_list(100000, 0, 10000) print time.time() direct_insertion(list_to_sort) print time.time() print list_to_sort
from tkinter import * top=Tk() top.geometry("400x400") def rst(): chkbx1.set(0) chkbx2.set(0) rbvr1.set(0) rbvr2.set(0) def chk(): print("Your Interests are :") if chkbx1.get()==1: print("Data Strcut and Algo") if chkbx2.get()==1: print("Distributed Systems") print("\n") result="Gender is : "+rbvr1.get()+"\n"+"Grade is : "+str(rbvr2.get()) print(result) chkbx1=IntVar() chkbx2=IntVar() # if the variable changes for any reason, the widget it's connected to will be updated to reflect the new value. # These Tkinter control variables are used like regular Python variables to keep certain values. # It's not possible to hand over a regular Python variable to a widget through a variable or textvariable option. # The only kinds of variables for which this works are variables that are subclassed from a class called Variable, defined in the Tkinter module cbx1=Checkbutton(top,text="Data Structures and Algorithms",variable=chkbx1,onvalue=1,offvalue=0,command=chk).grid(row=1,sticky=E) cbx2=Checkbutton(top,text="Distributed Systems",variable=chkbx2,onvalue=1,offvalue=0,command=chk,cursor="dot").grid(row=3,sticky=W) # command - A procedure to be called every time the user changes the state of this checkbutton. # cursor - (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton. # offvalue - control variable will be set to 0 when it is cleared (off). You can supply an alternate value for the off state by setting offvalue to that value. # onvalue - control variable will be set to 1 when it is set (on). You can supply an alternate value for the on state by setting onvalue to that value. # variable - The control variable that tracks the current state of the checkbutton. Normally this variable is an IntVar, and 0 means cleared and 1 means set. qbt=Button(top,text="Quit",command=top.quit).grid(row=5,sticky=W) # Quit Button sbt=Button(top,text="SUBMIT",command=chk).grid(row=7,sticky=W) # Check state of checkboxes rbt=Button(top,text="Reset",command=rst).grid(row=9) # the widgets are centered in their cells. # You can use the STICKY option to change this; this option takes one or more values from the set N, S, E, W. rbvr1=StringVar() rbvr2=IntVar() rb11=Radiobutton(top,text="Male",variable=rbvr1,value="Male").grid(row=13) rb12=Radiobutton(top,text="Female",variable=rbvr1,value="Female").grid(row=14) rb13=Radiobutton(top,text="Other",variable=rbvr1,value="Other").grid(row=15) rb21=Radiobutton(top,text="S",variable=rbvr2,value=10).grid(row=17) rb22=Radiobutton(top,text="A",variable=rbvr2,value=9).grid(row=19) rb23=Radiobutton(top,text="B",variable=rbvr2,value=8).grid(row=21) rb24=Radiobutton(top,text="C",variable=rbvr2,value=7).grid(row=23) # value - When a radiobutton is turned on by the user, its control variable is set to its current value option. #If the control variable is an IntVar, give each radiobutton in the group a different integer value option. #If the control variable is a StringVar, give each radiobutton a different string value option. # variable - The control variable that this radiobutton shares with the other radiobuttons in the group. #This can be either an IntVar or a StringVar. #cbx1.place(x=100,y=150) #cbx2.place(x=200,y=250) #cbx1.pack() #cbx2.pack() top.mainloop()
class EvaluationFunction(object): """Store evaluation functions""" def __init__(self, data, factory): self.data = data self.factory = factory def evaluate(self, timetable): """Return sum of penalties""" penalty = self.countRoomCapacityPenalty(timetable) penalty += self.countMinimumWorkingDaysPenalty(timetable) penalty += self.countCurriculumCompactnessPenalty(timetable) penalty += self.countRoomStabilityPenalty(timetable) penalty += self.countConflictsPenalty(timetable) penalty += self.countLectureConflictsPenalty(timetable) penalty += self.countAvailabilitesPenalty(timetable) return penalty def countRoomCapacityPenalty(self, timetable): """Return sum of penalties for room capacity""" penalty = 0 for day in range(len(timetable.periods)): for period in range(len(timetable.periods[day])): for room in self.data.rooms: course = timetable.periods[day][period][room.id] if course != None: if room.capacity < course.studentsNum: #print day,period,room.id,course.id #print room.capacity, course.studentsNum penalty += course.studentsNum - room.capacity #print "Room capacity: ",penalty return penalty def countMinimumWorkingDaysPenalty(self, timetable): """Return sum of penalties for minimum working days""" penalty = 0 for course in self.data.courses: days = set() for slot in timetable.courses[course.id]: day, _, _ = self.factory.unzip(slot) days.add(day) if len(days) < course.minWorkingDays: #print course.id penalty += (course.minWorkingDays - len(days)) * 5 #print "Min working days: ",penalty return penalty def countCurriculumCompactnessPenalty(self, timetable): """Return sum of penalties for curriculum compactness""" penalty = 0 for curriculum in self.data.curricula: for day in range(len(timetable.periods)): for period in range(len(timetable.periods[day])): for room in self.data.rooms: course = timetable.periods[day][period][room.id] if course != None: if course.id in curriculum.members: ce = course before = False if period == 0: before = False else: for room in self.data.rooms: course = timetable.periods[day][period-1][room.id] if course != None: if course.id in curriculum.members: before = True after = False if period == len(timetable.periods[day]) -1: after = False else: for room in self.data.rooms: course = timetable.periods[day][period+1][room.id] if course != None: if course.id in curriculum.members: after = True if not before and not after: #print day, period, curriculum.id, ce.id penalty += 2 #for curriculum in self.data.curricula: #for day in timetable.periods: #print "Day" #penaltyDay =0 #prev = False #alone = False #per = 0 #for period in day: #print "Day" #for room in period: #course = period[room] #if course != None: #if course.id in curriculum.members: #if prev == False or per -1 != prev: #penaltyDay += 2 #alone = True #print course.id #else: #if alone: #print "Del ", course.id #penaltyDay -= 2 #alone = False #prev = per #per += 1 #if penaltyDay > 0: #penalty += penaltyDay #print "Curiculum compactness: ",penalty return penalty def countRoomStabilityPenalty(self, timetable): """Return sum of penalties for room stability""" penalty = 0 for course in self.data.courses: rooms = set() for slot in timetable.courses[course.id]: _, _, room = self.factory.unzip(slot) rooms.add(room.id) if len(rooms) > 1: #print course.id #print len(rooms) penalty += len(rooms) - 1 #print "Room stability: ",penalty return penalty def countLectureConflictsPenalty(self, timetable): """Return sum of penalties for lecture conflicts""" penalty = 0 for day in range(len(timetable.periods)): for period in range(len(timetable.periods[day])): courses = dict() for room in self.data.rooms: course = timetable.periods[day][period][room.id] if course != None: courses[course.id] = courses.get(course.id, 0) + 1 for c in courses: if courses[c] > 1: #print c penalty += courses[c] - 1 #print "Lecture Conflicts: ", penalty return 1000000 * penalty def countConflictsPenalty(self, timetable): """Return sum of penalties for conflicts""" penalty = 0 for day in range(len(timetable.periods)): for period in range(len(timetable.periods[day])): teachers = dict() courses = set() for room in self.data.rooms: course = timetable.periods[day][period][room.id] if course != None: if not course.id in courses: teachers[course.teacher] = teachers.get(course.teacher, 0) + 1 #if teachers[course.teacher] > 1: #print day, period courses.add(course.id) for t in teachers: if teachers[t] > 1: #print t penalty += (teachers[t] * (teachers[t] -1)) / 2 for day in range(len(timetable.periods)): for period in range(len(timetable.periods[day])): for curriculum in self.data.curricula: count = 0 courses = set() for room in self.data.rooms: course = timetable.periods[day][period][room.id] if course != None: if course.id in curriculum.members: count += 1 courses.add(course.id) if len(courses) > 1: #print day, period #print courses count = len(courses) #print (count * (count -1)) / 2 penalty += (count * (count -1)) / 2 #print penalty #print "Conflicts: ", penalty return penalty * 1000000 def countAvailabilitesPenalty(self, timetable): """return sum of penalties for availabilities""" penalty = 0 #print "Avail" for constraint in self.data.constraints: day = constraint.day period = constraint.dayPeriod for room in self.data.rooms: course = timetable.periods[day][period][room.id] if course != None: if course.id == constraint.id: #print course.id, day, period penalty +=1 #print "Avail: ", penalty return penalty * 1000000
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)-1): for j in range(i+1,len(nums)): if nums[i]+nums[j]==target: return [i,j] def main(): nums=[3,2,4] target=6 t=Solution() l=t.twoSum(nums,target) print(l) if __name__=="__main__": main()
l = float(input('Largura da parede:')) a = float(input('Altura da parede:')) m = (l*a) print('Sua parede tem a dimensao de {}x{} e a sua area e de {}m²'.format(l,a,m)) print('Para pintar essa parede, voce precisara de {}L de tinta'.format(m/2))
'''resposta = contador = media = maior = menor = dividido = 0 while resposta != 'N': contador += 1 numero = int(input('Digite um número: ')) if maior > numero: maior = maior else: maior = numero if contador < 2: menor = maior elif menor < numero: menor = menor else: menor = numero if contador > 1: media += numero else: media += numero resposta = str(input('Quer continuar? [S/N] ')).upper().strip() if resposta == 'N': resposta = 'N' dividido = contador if contador > 1: media = media / dividido print('Você digitou {} números e a média foi {}'.format(contador, media)) print('O maior valor foi {} e o menor foi {}'.format(maior, menor))''' #OU resp = 'S' soma = quant = media = maior = menor = 0 while resp in 'Ss': num = int(input('Digite um número: ')) soma += num quant += 1 if quant == 1: maior = menor = num else: if num > maior: maior = num if num < menor: menor = num resp = str(input('Quer continuar? [S/N] ')).upper().strip()[0] media = soma / quant print('Vocè digitou {} números e a média foi {}'.format(quant, media)) print('O maior valor foi {} e o menor foi {}'.format(maior, menor))
print('Gerador de PA') print('-='*10) primeirotermo = int(input('Primeiro Termo: ')) razao = int(input('Razão: ')) cont = 1 termo = primeirotermo+razao while cont != 10: print('{} '.format(termo), end=' ') termo += razao cont += 1 print('FIM')
soma = 0 for c in range(1, 7): num = int(input('Digite o {} valor: '.format(c))) if num % 2 == 0: soma = soma + num print('A soma dos números pares foi {}'.format(soma))
dinheiro = float(input('Quanto de dinheiro voce tem na carteira? R$')) d = (dinheiro / 5.36) print('Com R${:.2f} voce pode comprar US${:.2f}'.format(dinheiro,d))
medida = float(input('Digite a medida:')) km = (medida / 1000) cm = (medida * 100) mm = (medida * 1000) print('A medida {} corresponde a {}km, {}cm, {}mm'.format(medida,km,cm,mm))
'''p1 = float(input('Peso da 1ª pessoa: ')) p2 = float(input('Peso da 2ª pessoa: ')) p3 = float(input('Peso da 3ª pessoa: ')) p4 = float(input('Peso da 4ª pessoa: ')) p5 = float(input('Peso da 5ª pessoa: ')) if p1 > p2 and p1 > p3 and p1 > p4 and p1 > p5: print('O maior peso lido foi de {}Kg'.format(p1)) elif p2 > p1 and p2 > p3 and p2 > p4 and p2 > p5: print('O maior peso lido foi de {}Kg'.format(p2)) elif p3 > p1 and p3 > p2 and p3 > p4 and p3 > p5: print('O maior peso lido foi de {}Kg'.format(p3)) elif p4 > p1 and p4 > p2 and p4 > p3 and p4 > p5: print('O maior peso lido foi de {}Kg'.format(p4)) elif p5 > p1 and p5 > p2 and p5 > p3 and p5 > p4: print('O maior peso lido foi de {}Kg'.format(p5)) else: print('são todos iguais') if p1 < p2 and p1 < p3 and p1 < p4 and p1 < p5: print('O menor peso lido foi de {}Kg'.format(p1)) elif p2 < p1 and p2 < p3 and p2 < p4 and p2 < p5: print('O menor peso lido foi de {}Kg'.format(p2)) elif p3 < p1 and p3 < p2 and p3 < p4 and p3 < p5: print('O menor peso lido foi de {}Kg'.format(p3)) elif p4 < p1 and p4 < p2 and p4 < p3 and p4 < p5: print('O menor peso lido foi de {}Kg'.format(p4)) elif p5 < p1 and p5 < p2 and p5 < p3 and p5 < p4: print('O menor peso lido foi de {}Kg'.format(p5))''' #OU maior = 0 menor = 0 for p in range(1, 6): peso = float(input('Peso da {}ª pessoa: '.format(p))) if p == 1: maior = peso menor = peso else: if peso > maior: maior = peso if peso < menor: menor = peso print('O maior peso lido foi de {}Kg'.format(maior)) print('O menor peso lido foi de {}Kg'.format(menor))
def leiaint(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('\033[0:31mERRO! Digite um número inteiro válido.\033[m') continue except KeyboardInterrupt: print('\033[31mUsuário preferiu não digitar esse número.\033[m') else: return n def leiafloat(msg2): while msg2 != float: r = input(msg2) try: r = float(r) except ValueError: print('\033[31mERRO! Digite um número Real válido.\033[m') continue except KeyboardInterrupt: print('\033[31mUsuário preferiu não digitar esse número.\033[m') else: return r n = leiaint('Digite um inteiro: ') r = leiafloat('Digite um Real: ') print(f'Você acabou de digitar o número {n} e o real foi {r:.2f}')
p = float(input('Digite o peso da pessoa: (KG)')) a = float(input('Digite a altura da pessoa: (m)')) imc = p / (a * a) if imc < 18.5: print('Abaixo do peso') elif imc >= 18.5 and imc < 25: print('Peso ideal') elif imc >= 25 and imc < 30: print('Sobrepeso') elif imc >= 30 and imc < 40: print('Obesidade') elif imc > 40: print('Obesidade mórbida')
def removeDuplicates(nums): if nums == []: return nums noDupePtr = 1 store = nums[0] for item in nums: if (item != store): nums[noDupePtr] = item noDupePtr+=1 store = item return nums print(removeDuplicates([1,1,2])) #2 print(removeDuplicates([])) #0 print(removeDuplicates([1, 1, 1])) #1 print(removeDuplicates([1, 1,1, 4,4,4])) #2 print(removeDuplicates([1, 2,4])) #3
print('Hello, Django girls!') if 3>2: print ('To działa!') if 5>2: print ('5 jest jednak większe od 2') else: print ('5 nie jest większe od 2') name = 'Sonja' if name == 'Ola': print ('Hej Ola!') elif name == 'Sonja': print ('Hej Sonja!') else: print ('Hej anonimie!') volume = 57 if volume < 20: print("It's kinda quiet.") elif 20 <= volume < 40: print("It's nice for background music") elif 40 <= volume < 60: print("Perfect, I can hear all the details") elif 60 <= volume < 80: print("Nice for parties") elif 80 <= volume < 100: print("A bit loud!") else: print("My ears are hurting! :(") # Change the volume if it's too loud or too quiet if volume < 20 or volume > 80: volume = 50 print("That's better!") def hi(): print('Hej!') print('Jak się masz?') hi() def hi(imie): if imie == 'Ola': print('Hej Ola!') elif imie == 'Sonja': print('Hej Sonja!') else: print('Hej nieznajoma!') imie='Kasia' hi(imie) hi("Ola") def hi(imie): print('Hej ' + imie + '!') hi("Rachel") dziewczyny = ['Rachel', 'Monica', 'Phoebe', 'Ola', 'Ty'] for imie in dziewczyny: hi(imie) print('Kolejna dziewczyna') for i in range(1, 6): print(i)
# 1. Create a Python Program to find Body Mass Index. (Formula. weight/height squared) # 2. Create a Python Program to find the Simple Interest. (Formula. PRT/100). #question 1 weight = float(input("Please Input your weight:")) height = float(input("Please input your height:")) BMI = weight/(height * height) print("You BMI is", BMI) #question 2 P = int(input("Please add the principle amount:")) R = 0.12 T = float(input("Add time")) simple_interest = (P*R*T)/100 print("The simple interest is:", simple_interest)
# if else, elif statements student_name = input("Input your name:") student_average_mark = float(input("Please input your average mark:")) if 0 <= student_average_mark <= 30: print("You scored an E") elif 30 < student_average_mark <= 40: print("You scored a D") elif 40 < student_average_mark <= 50: print("You scored a C") elif 50 < student_average_mark <= 60: print("You scored a B") elif 60 < student_average_mark <= 90: print("You scored a A") elif 90 < student_average_mark <= 100: print("You scored a A+") else: print("Input valid average marks")
import sys from os import system import time def main(): print("Welcome to your Todo list app.\nEnter your name to continue.") cmd = input() todo = ToDoList(cmd) while(1): clear() show_actions() cmd = input() if(cmd=="1"): print("Enter date in dd/mm/yyyy format") d,m,y = input().split('/') date = Date(d,m,y) print("Enter start time in hh:mm format") h,m = input().split(":") stime = Time(h,m) print("Enter duration in hh:mm format") h,m = input().split(":") dtime = Time(h,m) vtask = Task(d,stime,dtime) li = get_names() vtask.add_people(li) todo.add(vtask) elif(cmd=="2"): print("Enter date in dd/mm/yyyy format") d,m,y = input().split('/') date = Date(d,m,y) print("Enter start time in hh:mm format") h,m = input().split(":") stime = Time(h,m) print("Enter location") loc = input() vevent = Event(date,stime,loc) todo.add(vevent) elif(cmd=="3"): tmp = todo.rm() if tmp.type == "Task": print("{} {} {} {}".format(tmp.date,tmp.start_time,tmp.duration,tmp.people)) else: print("{} {} {}".format(tmp.date,tmp.start_time,tmp.location)) time.sleep(3) elif(cmd=="4"): sys.exit() def get_names(): print("Enter names") li =[] name = input() while name != "": li.append(name) name=input() return li def show_actions(): x = "1 to enqueue task" y = "2 to enqueue event" z = "3 to dequeue" a = "4 to exit" print("\n".join([x,y,z,a])) def clear(): system("clear") class MyQueue(object): def __init__(self): self.q = [] def is_empty(self): return self.q == [] def enq(self,item): print("adding to queue") self.q.insert(0,item) def deq(self): ret = self.q.pop() return ret class ToDoList(): def __init__(self,name): self.name = name self.q = MyQueue() def add(self,item): self.q.enq(item) def rm(self): return self.q.deq() class Date(): months = range(1,13) days = range(1,32) def __init__(self,day,month,year): self.day = int(day) self.month = int(month) self.year = int(year) def validate(self): if self.month not in self.months: return 0 if self.day not in self.days: return 0 if len(str(self.year)) != 4: return 0 return 1 def __str__(self): return "{}/{}/{}".format(self.day,self.month,self.year) class Time(): hours = range(0,24) mins = range(0,60) def __init__(self,hour=0,min=0): self.hour = int(hour) self.min = int(min) def validate(self): if self.hour not in self.hours: return 0 if self.min not in self.mins: return 0 return 1 def __str__(self): return "{}:{}".format(self.hour,self.min) class GeneralType(): def __init__(self,date,start_time): self.date = date self.start_time = start_time def __str__(self): return "{}\n{}\n".format(self.date,self.start_time) class Task(GeneralType): def __init__(self,date,start_time,duration): super().__init__(date,start_time) self.duration = duration self.people = [] self.type = "Task" def add_people(self,li): for name in li: self.people.append(name) def __str__(self): x = super().__str__() return "{}\n{}\n{}\n".format(x,self.duration,str(self.people)) class Event(GeneralType): def __init__(self,date,start_time,location): super().__init__(date,start_time) self.location = location self.type = "Event" def __str__(self): x = super().__str__() return "{}\n{}\n".format(x,self.location) if __name__=='__main__': main()
# -*- coding: utf-8 -*- # Projenin Adi : list veri tipi # Tarih : 13-03-2011 # Yazar : pythontr.org ekibi # Kontak : pythontr@pythontr.org # Web : http://pythontr.org # Python Versiyonu : 2.6-2.7 # Amaci : pythontr.org sitesi uzerinde Python kodlarindan # olusan bir kod kutuphanesi olusturmak. Yazilan programlari # en iyilemek ve herzaman erisilebilir bir ortamda tutmak. # Programa eklemek isteginiz kodlar icin kayitli kullanici olunuz... # # http://pythontr.org # mylist=["python", "py", "django", 123] print type (mylist) mylist.append("ekle") print mylist print mylist[2] print len(mylist)
i=["a","1","c","b","f","z","b","5","2",1977,"2"] print i i.sort() print i print type("2") print i.index("c") print i.count("2") print i[3:6] print i[:5] print i[5:] i[2:4]=["sahin","mersin"] print i
class Contact: def __init__(self,first_name, last_name, phone_number, address): self.first_name = first_name.lower() self.last_name = last_name.lower() self.phone_number = str(phone_number) self.address = address.lower() def __repr__(self): return f"first name :{self.first_name}, last name: {self.last_name}, phone number: {self.phone_number}, adress: {self.address}" class Phonebook: def __init__(self): self.phone_list = [] self.checking_instances = [] # Trenger ikke å være der, brukes kun på checking functionen def add(self, new_contact): self.phone_list.append(new_contact) def delete(self, the_contact): print("The delete function:") verify = input("Are you sure you want to delete this contact? (Y/N): ") if verify == "Y": self.phone_list.remove(the_contact) print(self.phone_list) print("The contact " + str(the_contact) + "has been deleted from the phonebook") else: print("Could not find the contact when deletion. Please try again") def checking(self, inf_contact): print("Using checking function:\n") for i in range(len(self.phone_list)): if (inf_contact == self.phone_list[i].first_name or inf_contact == self.phone_list[i].last_name or inf_contact == self.phone_list[i].phone_number or inf_contact == self.phone_list[i].address): self.checking_instances.append(True) else: self.checking_instances.append(False) if True in self.checking_instances: index = self.checking_instances.index(True) print(f"By searching for {inf_contact} we found first name: {self.phone_list[index].first_name}, " f"last name: {self.phone_list[index].last_name}, phonenumber: {self.phone_list[index].phone_number} " f"and address: {self.phone_list[index].address}") else: print("Could not find the contact in checking. Please try again") def update_phone(self, contact, telephone): print("Using update function:") if contact in self.phone_list: index = self.phone_list.index(contact) self.phone_list[index].phone_number = str(telephone) print(self.phone_list[index].phone_number) print("The telephonenumber has been updated") else: print("Could not find the contact. Please try again") def sort(self, option): if option == "first name": #import operator #a = sorted(self.phone_list, key=operator.attrgetter('first_name')) b = sorted(self.phone_list, key=lambda Contact: Contact.first_name) print(f"The phone book has been sorted by {option}: ") for i in range(len(b)): print(b[i]) elif option == "last name": b = sorted(self.phone_list, key=lambda Contact: Contact.last_name) #print(a) print(f"The phone book has been sorted by {option}: ") for i in range(len(b)): print(b[i]) else: print("We could not identify the command.Please check for typing error.") def check_duplicate(self): dup_list = [] print("Check_duplicate:") for i in range(len(self.phone_list)): for j in range(len(self.phone_list)): if self.phone_list[i].phone_number == self.phone_list[j].phone_number and i != j and j not in dup_list: print(f" {self.phone_list[i].first_name} phonenumber match with {self.phone_list[j].first_name}") dup_list.append(i) for i in range(len(dup_list)): print(f"Removing {self.phone_list[dup_list[i]].first_name}") self.phone_list.pop(dup_list[i]) if not dup_list: print("found no duplicate")
import math def comp_midpoint(f, a, b, n): sum = 0 h = (b - a) / n x = h/2 for i in range(n): sum += f(x) * h x += h return sum print comp_midpoint(lambda x:math.sin(x), 0.0, math.pi / 2, 120)
# manipulate the contents of variables. # lower, upper, swapcase are different string functions. message="Hello world" print(message.swapcase()) # change cases. print(message.lower()) # all letter is in lower case. print(message.upper()) # all letter is in upper case. print(message.capitalize()) # capitalize the first letter of the sentence. print(message.title()) # capitalize the first letter of every word in the string. print(message.replace("Hello","hi") )# replace the word after comma to the place of the word before comma. print(message.find("world")) # tells us the position of the word. # the number which comes to the output means the characters before the word is that number. # we can also tell python where to start and where to end. they are going to be the 2nd and 3rd arguement. print(message.find("l",4,-1)) print(message.count("o")) # count the number of the letter. print(" dhaka ".strip()) # ignore the blank space. print(" dhaka ".rstrip()) # ignore the blank space of right side. print(" dhaka ".lstrip()) # ignore the blank space of left side. # we can also use specific character to remove by adding another arguement in those above 3 methods. print("kkkkkkkkkkkkkk foo kkkkkkkkkkkkkk".strip("k")) print(message.startswith("H")) # gives a boolean. if a string starts with the character or not. print(message.endswith("d")) # gives a boolean. if a string ends with the character or not. # Example- name=input("what is your name?") country=input("which country do you live in?") country=country.upper() print(name+" lives in "+country+".") # when we write down a function we can watch a pop up list. that's called intelliSense. # Visual Studio will suggest possible functions we can call automically after we type any word. # we can also press ctrl+space to launch intelliSense. # programmers do not memorize all functions. # so how do programmers find them when they need them?- # 1.intellisense, 2.documentation, 3.internet searches. # asking user to input number # there are functions to convert from one datatype to another. # they are called "casting datatypes" or "datatype conversion"- # int(value) converts to an integreter. # long(value) converts to a long integreter. # float(value) converts to a floating number. (i.e. a number that can hold decimal places) # str(value) converts to a string. # bool(value) converts to boolean. a=input("enter a number") b=input("enter another number") answer=int(a)+int(b) print(answer) # how to find the type of a variable? # we can use type function c="Shawki" print(type(c))
n=eval(input("Enter a number to check if it's even or odd ")) if n%2==0: print("Even") else: print("Odd")
class trie_node(object): def __init__(self, char = '*'): self.char = char self.children = [] self.data = None def add(self,key:str,data): node = self for letter in key: found = False for child in node.children: if letter == child.char: node = child found = True break if not found: node.children.append(trie_node(letter)) node = node.children[-1] node.data = data def get(self,key:str): node = self for letter in key: found = False for child in node.children: if letter == child.char: node = child found = True break if not found: return False return node.data def print(self, prefix=''): for child in self.children: if child.children: child.print(prefix + child.char) else: print(prefix + child.char + ' : ' + str(child.data)) def search(self, prefix): node = self for letter in prefix: found = False for child in node.children: if letter == child.char: node = child found = True break if not found: return [] results = [] if node.data: results.append([prefix, node.data]) for child in node.children: child.scan(prefix,results) return results def scan(self,prefix,results): if self.data: results.append([prefix + self.char, self.data]) else: for child in self.children: child.scan(prefix + self.char,results) if __name__ == '__main__': print('Hewoooooow 0w0') names = trie_node() names.add('batata',22) names.add('baiacu',71) names.add('baiana',38) names.add('cenoura', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH') print(names.get('batata')) print(names.get('baiana')) print(names.get('balada')) print(names.get('baiacu')) print(names.get('cenoura')) names.print()
# Author and Email: # Thomas Lux (tchlux@vt.edu) # # Modifications: # 2018 April -(TL)- Created 'regular_simplex' function. # # Given "d" categories that need to be converted into real space, # generate a regular simplex in (d-1)-dimensional space. (all points # are equally spaced from each other and the origin) This process # guarantees that all points are not placed on a sub-dimensional # manifold (as opposed to "one-hot" encoding). def regular_simplex(num_categories): import numpy as np class InvalidNumberOfCategories(Exception): pass # Special cases for one and two categories if num_categories <= 1: raise(InvalidNumberOfCategories( "Number of categories must be an integer greater than 1.")) elif num_categories == 2: return np.array([[0.],[1.]]) # Standard case for >2 categories d = num_categories # Initialize all points to be zeros. points = np.zeros((d,d-1)) # Set the initial first point as 1 points[0,0] = 1 # Calculate all the intermediate points for i in range(1,d-1): # Set all points to be flipped from previous calculation while # maintaining the angle "arcos(-1/d)" between vectors. points[i:,i-1] = -1/(d-i) * points[i-1,i-1] # Compute the new coordinate using pythagorean theorem points[i,i] = (1 - sum(points[i,:i]**2))**(1/2) # Set the last coordinate of the last point as the negation of the previous points[i+1,i] = -points[i,i] # Return the regular simplex return points
block = """ In our everyday lives we have grown accustomed to computers being a constant. Computers solve problems that require years for a human in just seconds. Yet, there is variance in how long it takes a computer to do the same task multiple times. This variance in performance is a pervasive problem across computer science. In my talk I will share three significant ways that performance variance impacts computer systems in the real world, and introduce you to some modelling methods that we are using to manage and predict variance in the future. """ all_words = {} to_remove = ',\n' # Recursive function for removing all characters in 'to_remove' remove = lambda to_rem, string: ( remove(to_rem[1:], string.replace(to_rem[0],"")) if len(to_rem) > 0 else string) # Correct the entire block with some simple rules block = block.lower() block = block.replace("\n"," ") sentences = [] for sentence in (block.lower()).split("."): s_words = {} for word in sentence.split(" "): word = remove(to_remove, word) if len(word) == 0: continue all_words[word] = all_words.get(word, 0) + 1 s_words[word] = s_words.get(word, 0) + 1 s_words = list(s_words.items()) s_words.sort(key=lambda k: -k[-1]) if len(s_words) == 0: continue print(s_words) print() all_words = list(all_words.items()) all_words.sort(key=lambda k: -k[-1]) for w in all_words: print(w)
''' Author: Devansh Jain (190100044) Lab 11 2 - Defining Permutation Function ''' def perm(arr): ''' List of all Permutations of arr ''' # If empty then only one permutation - phi if len(arr) == 0: return [[]] # Initialize result res = [] for n in range(len(arr)): # Permute the array excluding the nth element # and add the element at the start of it value = arr.pop(n) res += [[value] + perm_elem for perm_elem in perm(arr)] arr.insert(n, value) return res if __name__ == '__main__': l1 = [1, 2, 'hi', True] l2 = [1, 2, 3] p1 = perm(l1) p2 = perm(l2) print('Number of permutation of {} are {}'.format(l1, len(p1))) print(p1) print('Number of permutation of {} are {}'.format(l2, len(p2))) print(p2)
l = [1, 2, 3] l2 = l if l is l2: print("it's the same object") l2.append(10) print(l)
import numpy as np import pandas as pd import nltk import dialogflow from nltk.corpus import stopwords from nltk.stem import SnowballStemmer snowball_stemmer = SnowballStemmer('english') def remove_stopwords(text): words = text.split() meaningful_words = [w for w in words if w not in stopwords.words("english")] return meaningful_words def text_process(text_input): # Remove stopwords print(text_input) text_input = remove_stopwords(text_input) for i, word in enumerate(text_input): print(word) text_input[i] = snowball_stemmer.stem(word) text_input = list(set(text_input)) print(text_input) # Check keywords flag1 = False for w in text_input: if w in ['company', 'packages', 'price']: flag1 = True if flag1: text = respond_packages() print(text) end_signal = False return end_signal def respond_packages(): text = 'We provide 5 different career packages, they are:\n'\ '1. Career Exploration\n'\ '2. Hybrid Training Satisfaction GUARANTEE\n'\ '3. 1-Month Resume Success GUARANTEE\n'\ '4. 3-Month Elite Job Success GUARANTEE\n'\ '5. 1-Month Sprint to Success GUARANTEE\n' return text def respond_three_month(): text = 'The 3-Month Elite Job Success GUARANTEE is priced dynamically\n'\ 'Based on the future offer you would get, ' return text def main(): q1 = input("Hi, how can i help you today?") program_run = True while program_run: # Run input digest process program_run = text_process(q1) if __name__ == '__main__': main()
def read_audio_input(): '''This method takes user voice as input and returns a string as output. Uses Google audio API to convert audio to text NOTE: number of request per day is limited to 100.''' import speech_recognition as sr r = sr.Recognizer() m = sr.Microphone() try: print("Starting up. Please remain quiet.") with m as source: r.adjust_for_ambient_noise(source) print("Hi there! I am jarvis. What do you want me to do?") first_time = True while True: if not first_time: print "Try again please" first_time = False with m as source: audio = r.listen(source) print("Got it. Give me a moment please!") flag = 1 try: # recognize speech using Google Speech Recognition value = r.recognize_google(audio) # we need some special handling here to correctly print unicode characters to standard output if str is bytes: # this version of Python uses bytes for strings (Python 2) command_input = format(value).encode("utf-8") print(u"You said {}".format(value).encode("utf-8")) else: # this version of Python uses unicode for strings (Python 3+) print("You said {}".format(value)) except sr.UnknownValueError: flag = 0 print("Oops! Didn't catch that") except sr.RequestError as e: flag = 0 print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e)) if flag == 1: break except KeyboardInterrupt: pass return command_input def categorize_command( input_string ): '''converts the input command to a more fine grained command to make it easier to understand''' input_string = input_string.lower() possible_list = input_string.split() # news fetch if "news" in possible_list: ind = possible_list.index( "news" ) if( ind + 2 < len( possible_list ) ): if possible_list[ind+1] == "on": category = possible_list[ind+2] return ["news", category] else: return ["news"] # terminal start commands elif "start" in possible_list\ or "run" in possible_list\ or "open" in possible_list: print "cmd command detected." ind = -1 try: ind = possible_list.index("start") except ValueError: a = 1+1 # do nothing try: ind = possible_list.index("open") except ValueError: a = 1+1 # do nothing try: ind = possible_list.index("run") except ValueError: a = 1+1 # do nothing return ["run", possible_list[1].lower() + ".exe"] # fetching emails command elif "email" in possible_list\ or "emails" in possible_list: return ["email"] # PC shutdown related commands elif "shutdown" in possible_list: if "cancel" in possible_list: return ["CANCEL_SHUTDOWN"] elif "minutes" in possible_list: time_to_shut = possible_list[possible_list.index("minutes")-1] return ["SHUTDOWN", time_to_shut] elif "minute" in possible_list: time_to_shut = possible_list[possible_list.index("minute")-1] return ["SHUTDOWN", time_to_shut] else: return ["SHUTDOWN"] def run_on_cmd( process_name ): import os os.system("start " + process_name) def shutdown_pc( power_off_flag, time_dur=120 ): import os if( power_off_flag == "SHUTDOWN"): print "System will shutdown in 2 minutes" os.system("shutdown -s -t " + str(time_dur)) elif ( power_off_flag == "CANCEL_SHUTDOWN"): os.system("shutdown -a") print "Scheduled shutdown was cancelled" class news_item(): def __init__(self): a = 1 + 1 # define news item object here. def get_news(topic): '''Gets the description of news from newsapi.org from some random sources''' from news_preprocessor import get_news_source_list as src_obj from api_getter import get_api_key as gak from random import sample import requests import json api_key = gak('news_org_api') src_list = src_obj() src_len = len(src_list) rand_src = sample( range(src_len), 3) news_item_json = [] for i in rand_src: news_src = src_list[i] print 'Feteching news from '+ news_src.name sorter = "" if news_src.is_popular_poss: sorter = "&sortBy=popular" elif news_src.is_latest_poss: sorter = "&sortBy=latest" elif news_src.is_top_poss: sorter = "&sortBy=top" url = 'https://newsapi.org/v1/articles?source='+news_src.id+sorter+'&apiKey='+api_key print url responses = requests.get(url) sources_json = responses.json() news_item_json.append(sources_json) print news_item_json return news_item_json def print_pretty(json_string): '''Converts json object to human readable text.''' #TODO: implement this function ASAP a = 1 + 1 def process_audio_command(): #TODO: un-comment these lines after testing. input_command = read_audio_input() fine_command = categorize_command(input_command) print fine_command if(fine_command == None): print "Sorry, I didn't understand that!\nTry again." command_len = len( fine_command ) if fine_command[0] == "news": if command_len == 2: # when a category is specified. return get_news(fine_command[1]) else: # when no category is specified. # TODO: finish this part first. # then the other part. return get_news("") elif fine_command[0] == "run": run_on_cmd( fine_command[1]) return None elif fine_command[0] == "email": from email_fetcher import show_emails print "showing emails.." show_emails() elif fine_command[0] == "SHUTDOWN" or fine_command[0] == "CANCEL_SHUTDOWN": print "shutdown flag:" + fine_command[0] if(command_len == 2 ): shutdown_pc(fine_command[0], int(fine_command[1])*60) else: shutdown_pc(fine_command[0],120) process_audio_command()
# Write a method that takes an array of numbers in. Your method should # return the third greatest number in the array. You may assume that # the array has at least three numbers in it. # # Difficulty: medium. def third_greatest(nums): first = None second = None third = None for i in range (0, len(nums)): current = nums[i] if current > first: third = second second = first first = current elif current > second: third = second second = current elif current > third: third = current return third # These are tests to check that your code is working. After writing # your solution, they should all print true. print "Tests for #third_greatest" print 'third_greatest([5, 3, 7]) == 3: ' + str(third_greatest([5, 3, 7]) == 3) print 'third_greatest([5, 3, 7, 4]) == 4: ' + str(third_greatest([5, 3, 7, 4]) == 4) print 'third_greatest([2, 3, 7, 4]) == 3: ' + str(third_greatest([2, 3, 7, 4]) == 3) print 'third_greatest([1, 2, 3,5,6, 7, 4]) == 5: ' + str(third_greatest([1, 2, 3,5,6, 7, 4]) == 5)
# Write a method that takes in a string of lowercase letters and # spaces, producing a new string that capitalizes the first letter of # each word. # # You'll want to use the `split` and `join` methods. Also, the String # method `upcase`, which converts a string to all upper case will be # helpful. # # Difficulty: medium. def capitalize_words(string): words = string.split() capitalized = "" for i in range (0, len(words)): current = words[i] capitalized += current[0].upper() for j in range (1, len(current)): capitalized += current[j] if i < (len(words)-1): capitalized += " " return capitalized # These are tests to check that your code is working. After writing # your solution, they should all print true. print capitalize_words("this is a sentence") print capitalize_words("mike bloomfield") print 'capitalize_words("this is a sentence") == "This Is A Sentence": ' + str(capitalize_words("this is a sentence") == "This Is A Sentence") print 'capitalize_words("mike bloomfield") == "Mike Bloomfield": ' + str(capitalize_words("mike bloomfield") == "Mike Bloomfield")
from bs4 import BeautifulSoup import pandas as pd import codecs html_doc = codecs.open("whatsapptest.htm", 'r', 'utf-8') soup = BeautifulSoup(html_doc, 'html.parser') selector = 'span._3NWy8 > *' found = soup.select(selector) # Extract data from the found elements data = [x.text.split(';')[-1].strip() for x in found] for x in data: print(x)
#!/usr/bin/env python3 """ defines Neuron class that defines a single neuron performing binary classification """ import numpy as np class Neuron: """ class that represents a single neuron performing binary classification class constructor: def __init__(self, nx) private instance attributes: __W: the weights vector for the neuron __b: the bias for the neuron __A: the activated output of the neuron (prediction) """ def __init__(self, nx): """ class constructor parameters: nx [int]: the number of input features to the neuron If nx is not an integer, raise a TypeError. If nx is less than 1, raise a ValueError. sets 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 """ if type(nx) is not int: raise TypeError("nx must be an integer") if nx < 1: raise ValueError("nx must be a positive integer") self.__W = np.random.randn(1, nx) self.__b = 0 self.__A = 0 @property def W(self): """ gets the private instance attribute __W __W is the weights vector for the neuron """ return (self.__W) @property def b(self): """ gets the private instance attribute __b __b is the bias for the neuron """ return (self.__b) @property def A(self): """ gets the private instance attribute __A __A is the activated output of the neuron """ return (self.__A)
#!/usr/bin/env python3 """ Defines class Yolo that uses the Yolo v3 algorithm to perform object detection """ import tensorflow.keras as K class Yolo: """ Class that uses Yolo v3 algorithm to perform object detection class constructor: def __init__(self, model_path, classes_path, class_t, nms_t, anchors) public instance attributes: model: the Darknet Keras model class_names: list of all the class names for the model class_t: the box score threshold for the initial filtering step nms_t: the IOU threshold for non-max suppression anchors: the anchor boxes """ def __init__(self, model_path, classes_path, class_t, nms_t, anchors): """ Yolo class constructor parameters: model_path [str]: the path to where a Darknet Keras model is stored classes_path [str]: the path to where the list of class names used for the Darknet model can be found, list is ordered by order of index class_t [float]: represents the box score threshold for the initial filtering step nms_t [float]: represents the IOU threshold for non-max suppression anchors [numpy.ndarray of shape (outputs, anchor_boxes, 2)]: contains all the anchor boxes: outputs: the number of predictions made by the Darknet model anchor_boxes: number of anchor boxes used for each prediction 2: [anchor_box_width, anchor_box_height] """ self.model = K.models.load_model(model_path) with open(classes_path, 'r') as f: lines = f.readlines() self.class_names = [] for name in lines: self.class_names.append(name[:-1]) self.class_t = class_t self.nms_t = nms_t self.anchors = anchors
#!/usr/bin/env python3 """ Defines a function to create a layer for neural network """ import tensorflow as tf def create_layer(prev, n, activation): """ Creates a layer for neural network parameters: prev [tensor]: tensor output of the previous layer n [int]: the number of nodes in the layer to create activation [function]: the activation function the layer should use use tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG") to implement He et. al initialization for the layer weights each layer is given the name "layer" returns: tensor output of the layer """ weights_initializer = tf.contrib.layers.variance_scaling_initializer( mode="FAN_AVG") layer = tf.layers.Dense( n, activation=activation, name="layer", kernel_initializer=weights_initializer) return (layer(prev))
#!/usr/bin/env python3 """ defines function that performs matrix multiplication """ def mat_mul(mat1, mat2): """ returns new matrix that is the product of two 2D matrices """ mat1_columns = len(mat1[0]) mat2_rows = len(mat2) if mat1_columns != mat2_rows: return None new_matrix = [] for row_count, row in enumerate(mat1): new_matrix.append([]) for column_count in range(len(mat2[0])): dot = 0 for index in range(mat1_columns): dot += (mat1[row_count][index] * mat2[index][column_count]) new_matrix[row_count].append(dot) return new_matrix
#!/usr/bin/env python3 """ Defines function that calculates the symmetric P affinities """ import numpy as np P_init = __import__('2-P_init').P_init HP = __import__('3-entropy').HP def P_affinities(X, tol=1e-5, perplexity=30.0): """ Calculates the symmetric P affinities of a data set parameters: X [numpy.ndarray of shape (n, d)]: containing the dataset to be transformed by t-SNE n: the number of data points d: the number of dimensions in each point tol [float]: maximum tolerance allowed (inclusive) for the difference in Shannon entropy from perplexity for all Gaussian distributions perplexity: perplexity that all Gaussian distributions should have returns: P [numpy.ndarray of shape (n, n)]: contatining the symmetric P affinities """ return None
#!/usr/bin/env python3 """ Defines function that calculates the determinant of a matrix """ def determinant(matrix): """ Calculates the determinant of a matrix parameters: matrix [list of lists]: matrix whose determinant should be calculated returns: the determinant of matrix """ if type(matrix) is not list: raise TypeError("matrix must be a list of lists") height = len(matrix) if height is 0: raise TypeError("matrix must be a list of lists") for row in matrix: if type(row) is not list: raise TypeError("matrix must be a list of lists") if len(row) is 0 and height is 1: return 1 if len(row) != height: raise ValueError("matrix must be a square matrix") if height is 1: return matrix[0][0] if height is 2: a = matrix[0][0] b = matrix[0][1] c = matrix[1][0] d = matrix[1][1] return ((a * d) - (b * c)) multiplier = 1 d = 0 for i in range(height): element = matrix[0][i] sub_matrix = [] for row in range(height): if row == 0: continue new_row = [] for column in range(height): if column == i: continue new_row.append(matrix[row][column]) sub_matrix.append(new_row) d += (element * multiplier * determinant(sub_matrix)) multiplier *= -1 return (d)
#!/usr/bin/env python3 """ Defines a function that calculates the positional encoding for a transformer """ import numpy as np def get_angle(pos, i, dm): """ Calculates the angles for the following formulas for positional encoding: PE(pos, 2i) = sin(pos / 10000^(2i / dm)) PE(pos, 2i + 1) = cos(pos / 10000^(2i / dm)) """ angle_rates = 1 / (10000 ** (i / dm)) return pos * angle_rates def positional_encoding(max_seq_len, dm): """ Calculates the positional encoding for a transformer parameters: max_seq_len [int]: represents the maximum sequence length dm: model depth returns: [numpy.ndarray of shape (max_seq_len, dm)]: contains the positional encoding vectors """ positional_encoding = np.zeros([max_seq_len, dm]) for pos in range(max_seq_len): for i in range(0, dm, 2): # sin for even indices of positional_encoding positional_encoding[pos, i] = np.sin(get_angle(pos, i, dm)) # cos for odd indices of positional_encoding positional_encoding[pos, i + 1] = np.cos(get_angle(pos, i, dm)) return positional_encoding
#!/usr/bin/env python3 """ Updates function that trains a model using mini-batch gradient descent to train using early stopping with Keras library """ 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 mini-batch gradient descent, including analyzing validation data and using early stopping parameters: network [keras model]: model to train data [numpy.ndarray of shape (m, nx)]: contains the input data labels [one-hot numpy.ndarray of shape (m, classes)]: contains labels of data batch_size [int]: size of batch used for mini-batch gradient descent epochs [int]: number of passes through data for mini-batch gradient descent validation_data: data to be analyzed during model training early_stopping [boolean]: indicated whether early stopping should be used early stopping should only be performed if validation_data exists early stopping should be based on validation loss patience: patience used for early stopping verbose [boolean]: determines if output should be printed during training shuffle [boolean]: determines whether to shuffle the batches every epoch returns: the History object generated after training the model """ if early_stopping and validation_data: callback = [] callback.append( K.callbacks.EarlyStopping(monitor='loss', patience=patience)) else: callback = None history = network.fit(x=data, y=labels, batch_size=batch_size, epochs=epochs, validation_data=validation_data, callbacks=callback, verbose=verbose, shuffle=shuffle) return history
#!/usr/bin/env python3 """ defines function that concatenates two arrays """ def cat_arrays(arr1, arr2): """ returns new list that is the concatenation of two arrays """ cat_array = [] for i in arr1: cat_array.append(i) for i in arr2: cat_array.append(i) return cat_array
#!/usr/bin/env python3 """ Defines a function that performs forward propagation over a convolutional neural network """ import numpy as np def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)): """ Performs forward propagation over a convolutional neural network parameters: A_prev [numpy.ndarray of shape (m, h_prev, w_prev, c_prev)]: contains 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 W [numpy.ndarray of shape(kh, kw, c_prev, c_new)]: contains the kernels for the convolution kh: filter height kw: filter width c_prev: number of channels in the previous layer c_new: number of channels in the output b [numpy.ndarray of shape (1, 1, 1, c_new)]: contains the biases applied to the convolution activation [function]: activation function applied to the convolution padding [string: 'same' or 'valid']: indicates the type of padding used for the convolution stride [tuple of shape (sh, sw)]: contains the strides for the convolution sh: stride for the height sw: stride for the width returns: output of the convolutional layer """ m, h_prev, w_prev, c_prev = A_prev.shape kh, kw, c_prev, c_new = W.shape sh, sw = stride if padding is 'valid': ph = 0 pw = 0 elif padding is 'same': ph = ((((h_prev - 1) * sh) + kh - h_prev) // 2) pw = ((((w_prev - 1) * sw) + kw - w_prev) // 2) else: return images = np.pad(A_prev, ((0, 0), (ph, ph), (pw, pw), (0, 0)), 'constant', constant_values=0) ch = ((h_prev + (2 * ph) - kh) // sh) + 1 cw = ((w_prev + (2 * pw) - kw) // sw) + 1 convoluted = np.zeros((m, ch, cw, c_new)) for index in range(c_new): kernel_index = W[:, :, :, index] i = 0 for h in range(0, (h_prev + (2 * ph) - kh + 1), sh): j = 0 for w in range(0, (w_prev + (2 * pw) - kw + 1), sw): output = np.sum( images[:, h:h + kh, w:w + kw, :] * kernel_index, axis=1).sum(axis=1).sum(axis=1) output += b[0, 0, 0, index] convoluted[:, i, j, index] = activation(output) j += 1 i += 1 return convoluted
#!/usr/bin/env python3 """ Defines the class GRUCell that represents a gated recurrent unit """ import numpy as np class GRUCell: """ Represents a gated recurrent unit class constructor: def __init__(self, i, h, o) public instance attributes: Wz: update gate weights bz: update gate biases Wr: reset gate weights br: reset gate biases Wh: intermediate hidden state and input data weights bh: intermediate hidden state and input data biases Wy: output weights by: output biases public instance methods: def forward(self, h_prev, x_t): performs forward propagation for one time step """ def __init__(self, i, h, o): """ Class constructor parameters: i: dimensionality of the data h: dimensionality of the hidden state o: dimensionality of the outputs creates public instance attributes: Wz: update gate weights bz: update gate biases Wr: reset gate weights br: reset gate biases Wh: intermediate hidden state and input data weights bh: intermediate hidden state and input data biases Wy: output weights by: output biases weights should be initialized using random normal distribution weights will be used on the right side for matrix multiplication biases should be initiliazed as zeros """ self.bz = np.zeros((1, h)) self.br = np.zeros((1, h)) self.Wz = np.random.normal(size=(h + i, h)) self.Wr = np.random.normal(size=(h + i, h)) self.bh = np.zeros((1, h)) self.by = np.zeros((1, o)) self.Wh = np.random.normal(size=(h + i, h)) self.Wy = np.random.normal(size=(h, o)) def softmax(self, x): """ Performs the softmax function parameters: x: the value to perform softmax on to generate output of cell return: softmax of x """ e_x = np.exp(x - np.max(x, axis=1, keepdims=True)) softmax = e_x / e_x.sum(axis=1, keepdims=True) return softmax def sigmoid(self, x): """ Performs the sigmoid function parameters: x: the value to perform sigmoid on return: sigmoid of x """ sigmoid = 1 / (1 + np.exp(-x)) return sigmoid def forward(self, h_prev, x_t): """ Performs forward propagation for one time step parameters: h_prev [numpy.ndarray of shape (m, h)]: contains previous hidden state m: the batch size for the data h: dimensionality of hidden state x_t [numpy.ndarray of shape (m, i)]: contains data input for the cell m: the batch size for the data i: dimensionality of the data output of the cell should use softmax activation function returns: h_next, y: h_next: the next hidden state y: the output of the cell """ concatenation1 = np.concatenate((h_prev, x_t), axis=1) z_gate = self.sigmoid(np.matmul(concatenation1, self.Wz) + self.bz) r_gate = self.sigmoid(np.matmul(concatenation1, self.Wr) + self.br) concatenation2 = np.concatenate((r_gate * h_prev, x_t), axis=1) h_next = np.tanh(np.matmul(concatenation2, self.Wh) + self.bh) h_next *= z_gate h_next += (1 - z_gate) * h_prev y = self.softmax(np.matmul(h_next, self.Wy) + self.by) return h_next, y
#!/usr/bin/env python3 """ Defines function that changes the hue of an image """ import tensorflow as tf def change_hue(image, delta): """ Changes the hue of an image parameters: image [3D td.Tensor]: contains the image to change delta [float]: the amount the hue should change returns: the altered image """ return (tf.image.adjust_hue(image, delta))
#!/usr/bin/env python3 """ Defines a function that builds a dense block using Keras """ import tensorflow.keras as K def dense_block(X, nb_filters, growth_rate, layers): """ Builds a dense block using Keras parameters: X: output from the previous layer nb_filters [int]: represents the number of filters in X growth_rate: growth rate for the dense block layers: number of layers in dense block Use the bottleneck layers used for DenseNet-B All convolutions inside the dense block should be followed by batch normalization along the channels axis and then ReLU activation, respectively All weights should be initialized using he normal returns: the concatenated output of each layer within the dense block and the number of filter within the concatenated outputs """ init = K.initializers.he_normal() activation = K.activations.relu for layer in range(layers): Batch_Norm1 = K.layers.BatchNormalization(axis=3)(X) ReLU1 = K.layers.Activation(activation)(Batch_Norm1) C1 = K.layers.Conv2D(filters=(4 * growth_rate), kernel_size=(1, 1), padding='same', kernel_initializer=init)(ReLU1) Batch_Norm3 = K.layers.BatchNormalization(axis=3)(C1) ReLU3 = K.layers.Activation(activation)(Batch_Norm3) C3 = K.layers.Conv2D(filters=growth_rate, kernel_size=(3, 3), padding='same', kernel_initializer=init)(ReLU3) X = K.layers.concatenate([X, C3]) nb_filters += growth_rate return X, nb_filters
#!/usr/bin/env python3 """ Defines a function that makes a prediction using neural network using Keras library """ import tensorflow.keras as K def predict(network, data, verbose=False): """ Makes a prediction using a neural network parameters: network [keras model]: model to make prediction with data: input data to make prediction with verbose [boolean]: determines if output should be printed during prediction process returns: the prediction for the data """ prediction = network.predict(x=data, verbose=verbose) return prediction
#!/usr/bin/env python3 """ Defines a function that tests a neural network using Keras library """ import tensorflow.keras as K def test_model(network, data, labels, verbose=True): """ Tests a neural network parameters: network [keras model]: model to test data: input data to test the model with labels: correct one-hot labels of data verbose [boolean]: determines if output should be printed during testing process returns: the loss and accuracy of the model with the testing data """ loss, accuracy = network.evaluate(x=data, y=labels, verbose=verbose) return loss, accuracy
#!/usr/bin/env python3 """ Defines function that updates the learning rate using inverse time decay in numpy """ 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 parameters: alpha [float]: original learning rate decay_rate: wight used to determine the rate at which alpha will decay global_step [int]: number of passes of gradient descent that have elapsed decay_step [int]: number of passes of gradient descent that should occur before alpha is decayed furtherXS the learning rate decay should occur in a stepwise fashion returns: the updated value for alpha """
#!/usr/bin/env python3 """ Defines a function that saves a model's configuration in JSON format and defines a function that loads a model with specific configuration using Keras library """ import tensorflow.keras as K def save_config(network, filename): """ Saves a model's configuration in JSON format parameters: network [keras model]: model to save configuration of filename [str]: file name where the configuration should be saved in JSON format returns: None """ json = network.to_json() with open(filename, 'w+') as f: f.write(json) return None def load_config(filename): """ Loads model's weights parameters: filename [str]: path of file containing model's configuration in JSON format returns: the loaded model """ with open(filename, 'r') as f: json_string = f.read() model = K.models.model_from_json(json_string) return model
#!/usr/bin/env python3 """ defines a function that calculates a summation """ def summation_i_squared(n): """ calculates summation of i^2 from i=1 to n utilizes Faulhaber's formula for power of 2: sum of i^2 from i=1 to n = (n * (n + 1) * (2n + 1)) / 6 or ((n^3) / 3) + ((n^2) / 2) + (n / 6) """ if type(n) is not int or n < 1: return None sigma_sum = (n * (n + 1) * ((2 * n) + 1)) / 6 return int(sigma_sum)
#!/usr/bin/env python3 """ defines DeepNeuralNetwork class that defines a deep neural network performing binary classification """ import numpy as np class DeepNeuralNetwork: """ class that represents a deep neural network performing binary classification class constructor: def __init__(self, nx, layers) private instance attributes: L: the number of layers in the neural network cache: a dictionary holding all intermediary values of the network weights: a dictionary holding all weights and biases of the network public methods: def forward_prop(self, X): calculates the forward propagation of the neural network def cost(self, Y, A): calculates the cost of the model using logistic regression def evaluate(self, X, Y): evaluates the neural network's predictions def gradient_descent(self, Y, cache, alpha=0.05): calculates one pass of gradient descent on the neural network def train(self, X, Y, iterations=5000, alpha=0.05, verbose=True, graph=True, step=100): trains the neural network and updates __weights and __cache """ def __init__(self, nx, layers): """ class constructor parameters: nx [int]: the number of input features If nx is not an integer, raise a TypeError. If nx is less than 1, raise a ValueError. layers [list]: representing the number of nodes in each layer If layers is not a list, raise TypeError. If elements in layers are not all positive ints, raise a TypeError. sets private instance attributes: __L: the number of layers in the neural network, initialized based on layers __cache: a dictionary holding all intermediary values for network,, initialized as an empty dictionary __weights: a dictionary holding all weights/biases of the network, weights initialized using the He et al. method using the key W{l} where {l} is the hidden layer biases initialized to 0s using the key b{l} where {1} is the hidden layer """ if type(nx) is not int: raise TypeError("nx must be an integer") if nx < 1: raise ValueError("nx must be a positive integer") if type(layers) is not list or len(layers) < 1: raise TypeError("layers must be a list of positive integers") weights = {} previous = nx for index, layer in enumerate(layers, 1): if type(layer) is not int or layer < 0: raise TypeError("layers must be a list of positive integers") weights["b{}".format(index)] = np.zeros((layer, 1)) weights["W{}".format(index)] = ( np.random.randn(layer, previous) * np.sqrt(2 / previous)) previous = layer self.__L = len(layers) self.__cache = {} self.__weights = weights @property def L(self): """ gets the private instance attribute __L __L is the number of layers in the neural network """ return (self.__L) @property def cache(self): """ gets the private instance attribute __cache __cache holds all the intermediary values of the network """ return (self.__cache) @property def weights(self): """ gets the private instance attribute __weights __weights holds all the wrights and biases of the network """ return (self.__weights) def forward_prop(self, X): """ calculates the forward propagation of the neuron parameters: X [numpy.ndarray with shape (nx, m)]: contains the input data nx is the number of input features to the neuron m is the number of examples updates the private attribute __cache using sigmoid activation function sigmoid function: activated output = 1 / (1 + e^(-z)) z = sum of ((__Wi * __Xi) + __b) from i = 0 to nx activated outputs of each layer are saved in __cache as A{l} where {l} is the hidden layer X is saved to __cache under key A0 return: the output of the neural network and the cache, respectively """ self.__cache["A0"] = X for index in range(self.L): W = self.weights["W{}".format(index + 1)] b = self.weights["b{}".format(index + 1)] z = np.matmul(W, self.cache["A{}".format(index)]) + b A = 1 / (1 + (np.exp(-z))) self.__cache["A{}".format(index + 1)] = A return (A, self.cache) def cost(self, Y, A): """ calculates the cost of the model using logistic regression parameters: Y [numpy.ndarray with shape (1, m)]: contains correct labels for the input data A [numpy.ndarray with shape (1, m)]: contains the activated output of the neuron for each example logistic regression loss function: loss = -((Y * log(A)) + ((1 - Y) * log(1 - A))) To avoid log(0) errors, uses (1.0000001 - A) instead of (1 - A) logistic regression cost function: cost = (1 / m) * sum of loss function for all m example return: the calculated cost """ m = Y.shape[1] m_loss = np.sum((Y * np.log(A)) + ((1 - Y) * np.log(1.0000001 - A))) cost = (1 / m) * (-(m_loss)) return (cost) def evaluate(self, X, Y): """ evaluates the neural network's predictions parameters: X [numpy.ndarray with shape (nx, m)]: contains the input data nx is the number of input features to the neuron m is the number of examples Y [numpy.ndarray with shape (1, m)]: contains correct labels for the input data returns: the neuron's prediction and the cost of the network, respectively prediction is numpy.ndarray with shape (1, m), containing predicted labels for each example label values should be 1 if the output of the network is >= 0.5, 0 if the output of the network is < 0.5 """ A, cache = self.forward_prop(X) cost = self.cost(Y, A) prediction = np.where(A >= 0.5, 1, 0) return (prediction, cost) def gradient_descent(self, Y, cache, alpha=0.05): """ calculates one pass of gradient descent on the neural network parameters: Y [numpy.ndarray with shape (1, m)]: contains correct labels for the input data cache [dictionary]: contains intermediary values of the network, including X as cache[A0] alpha [float]: learning rate updates the private instance attribute __weights using back propagation derivative of loss function with respect to A: dA = (-Y / A) + ((1 - Y) / (1 - A)) derivative of A with respect to z: dz = A * (1 - A) combining two above with chain rule, derivative of loss function with respect to z: dz = A - Y using chain rule with above derivative, derivative of loss function with respect to __W: d__Wi = Xidz or vectorized as d__W = (1 / m) * (dz dot X transpose) derivative of loss function with respect to __b: d__bi = dz of vectorized as d__b = (1 / m) * (sum of dz elements) for neural network, using the derivatives above: derivative of loss function with respect to z2: dz2 = A2 - Y derivative of loss function with respect to __W2: d__W2 = (1 / m) * (dz1 dot A1 transpose) derivative of loss function with respect to __b2: d__b2 = (1 / m) * (sum of dz2 over axis 1) derivative of loss function with respect to z1: dz1 = (__W2 transpose dot dz2) * A1(1 - A1) derivative of loss function with respect to __W1: d__W1 = (1 / m) * (dz dot X transpose) one-step of gradient descent updates the attributes with the following: __W = __W - (alpha * d__W) __b = __b - (alpha * d__b) """ m = Y.shape[1] back = {} for index in range(self.L, 0, -1): A = cache["A{}".format(index - 1)] if index == self.L: back["dz{}".format(index)] = (cache["A{}".format(index)] - Y) else: dz_prev = back["dz{}".format(index + 1)] A_current = cache["A{}".format(index)] back["dz{}".format(index)] = ( np.matmul(W_prev.transpose(), dz_prev) * (A_current * (1 - A_current))) dz = back["dz{}".format(index)] dW = (1 / m) * (np.matmul(dz, A.transpose())) db = (1 / m) * np.sum(dz, axis=1, keepdims=True) W_prev = self.weights["W{}".format(index)] self.__weights["W{}".format(index)] = ( self.weights["W{}".format(index)] - (alpha * dW)) self.__weights["b{}".format(index)] = ( self.weights["b{}".format(index)] - (alpha * db)) def train(self, X, Y, iterations=5000, alpha=0.05, verbose=True, graph=True, step=100): """ trains the neuron and updates __weights and __cache parameters: X [numpy.ndarray with shape (nx, m)]: contains the input data nx is the number of input features to the neuron m is the number of examples Y [numpy.ndarray with shape (1, m)]: contains correct labels for the input data iterations [int]: the number of iterations to train over If iterations is not an int, raise TypeError. If iterations is not positive, raise ValueError. alpha [float]: learning rate If alpha is not an int, raise TypeError. If alpha is not positive, raise ValueError. verbose [boolean]: defines whether or not to print information about training If True, prints "Cost after {iteration} iterations: {cost} after every step iterations, includes data from 0th and last iteration graph [boolean]: defines whether or not to graph information about training If True, plots the training data every step iterations: Training data is shown as a blue line, X-axis is labeled as "iteration", Y-axis is labeled as "cost", Title of the plot is "Training Cost", Includes data from the 0th and last iteration. step [int]: the number of iterations between printing verbose info of plotting graph data point If verbose or graph is True: If step is not int, raise TypeError. If step is not positive or is greater than iterations, raise ValueError. returns: the evaluation of the training data after iterations of training """ if type(iterations) is not int: raise TypeError("iterations must be an integer") if iterations <= 0: raise ValueError("iterations must be a positive integer") if type(alpha) is not float: raise TypeError("alpha must be a float") if alpha <= 0: raise ValueError("alpha must be positive") if verbose or graph: if type(step) is not int: raise TypeError("step must be an integer") if step <= 0 or step > iterations: raise ValueError("step must be positive and <= iterations") if graph: import matplotlib.pyplot as plt x_points = np.arange(0, iterations + 1, step) points = [] for itr in range(iterations): A, cache = self.forward_prop(X) if verbose and (itr % step) == 0: cost = self.cost(Y, A) print("Cost after " + str(itr) + " iterations: " + str(cost)) if graph and (itr % step) == 0: cost = self.cost(Y, A) points.append(cost) self.gradient_descent(Y, cache, alpha) itr += 1 if verbose: cost = self.cost(Y, A) print("Cost after " + str(itr) + " iterations: " + str(cost)) if graph: cost = self.cost(Y, A) points.append(cost) y_points = np.asarray(points) plt.plot(x_points, y_points, 'b') plt.xlabel("iteration") plt.ylabel("cost") plt.title("Training Cost") plt.show() return (self.evaluate(X, Y))
#!/usr/bin/env python3 """ Defines function that randomly changes the brightness of an image """ import tensorflow as tf def change_brightness(image, max_delta): """ Randomly changes the brightness of an image parameters: image [3D td.Tensor]: contains the image to change max_delta [float]: maximum amount the image should be brightened (or darkened) returns: the altered image """ return (tf.image.random_brightness(image, max_delta))
#!/usr/bin/env python3 """ defines function that adds two matrices """ def matrix_shape(matrix): """ returns list of integers representing dimensions of given matrix """ matrix_shape = [] while type(matrix) is list: matrix_shape.append(len(matrix)) matrix = matrix[0] return matrix_shape def add_matrices(mat1, mat2): """ returns new matrix that is sum of two matrices added element-wise """ if matrix_shape(mat1) != matrix_shape(mat2): return None if len(matrix_shape(mat1)) is 1: return [mat1[i] + mat2[i] for i in range(len(mat1))] return [add_matrices(mat1[i], mat2[i]) for i in range(len(mat1))]
def get_fibonacci_last_digit_sq_sum(n): if n <= 1: return n previous = 0 current = 1 z = [] for _ in range(n + 1): z.append(previous**2) previous, current = current, (previous + current)%10 if previous == 0 and current == 1: break return ((n//len(z))*(sum(z))+sum(z[0:(n%(len(z)))+1]))%10 if __name__ == '__main__': n = int(input()) print(get_fibonacci_last_digit_sq_sum(n))
import random n = [0,1,2,3,4,5] e = int(input('digite um número entre 0 e 5: ')) r = random.choice(n) print('O numero era {}'.format(r)) if e == r: print('Você acertou!') else: print('Tente novamente.')
nome = str(input('Digite seu nome completo: ')).strip() maiusculo = nome.upper() print('Seu nome em maiúsculo é: {}'.format(maiusculo)) minusculo = nome.lower() print('Seu nome minúsculo é: {}'.format(minusculo)) print('Seu nome tem {} letras'.format(len(nome) - nome.count(' '))) #p = int(nome.find(' ')) #print('Seu primeiro nome tem {} letras'.format(nome.find(' '))) separa = nome.split() print('Seu primeiro nome é {} e ele tem {} letras'.format(separa[0], len(separa[0])))
import sys users = [ (0,"Bob", "password"), (1,"Rolf", "bob123"), (2,"Jose", "longp4ssword"), (3,"username", "1234"), ] user_map = {user[1] : user for user in users} print(user_map) print(user_map["Jose"]) user_input = sys.argv[1] passwd_input = sys.argv[2] #destructuring Tuple _,username,password=user_map[user_input] if password == passwd_input: print("Correct Password") else: print("Incorrect Password")
import sys import timeit # 실행 속도에 중점을 두고 만들었다. # start_time = timeit.default_timer() sys.stdin = open('sort_input.txt') def merge_sort(li): half = len(li)//2 if half: lft = merge_sort(li[:half]) rgt = merge_sort(li[half:]) li=[] while lft and rgt: if lft[0] < rgt[0]: li.append(lft.pop(0)) else : li.append(rgt.pop(0)) if lft: li += lft else : li += rgt return li def merge_sort2(li): half = len(li)//2 if half: lft = merge_sort2(li[:half])[::-1] rgt = merge_sort2(li[half:])[::-1] li=[] while lft and rgt: if lft[-1] < rgt[-1]: li.append(lft.pop()) else : li.append(rgt.pop()) if lft: li += lft[::-1] else : li += rgt[::-1] return li def bubble_sort(boxes_height): for i in range(len(boxes_height)-1, 0, -1): for j in range(0, i): if boxes_height[j] > boxes_height[j+1] : boxes_height[j], boxes_height[j+1] = boxes_height[j+1], boxes_height[j] return boxes_height def flatten(dump_n, dumps): start_time = timeit.default_timer() srt = sorted(dumps) terminate_time = timeit.default_timer() print("sorted는 %f초 걸렸습니다." % (terminate_time - start_time)) start_time = timeit.default_timer() bub = bubble_sort(dumps) terminate_time = timeit.default_timer() print("bub는 %f초 걸렸습니다." % (terminate_time - start_time)) start_time = timeit.default_timer() mrg = merge_sort(dumps) terminate_time = timeit.default_timer() print("mrg는 %f초 걸렸습니다." % (terminate_time - start_time)) start_time = timeit.default_timer() mrg2 = merge_sort2(dumps) terminate_time = timeit.default_timer() print("mrg2는 %f초 걸렸습니다." % (terminate_time - start_time)) print(srt == mrg, srt == mrg2) print() for tc in range(1, 11): Dump_n = int(input()) Dumps = list(map(int, input().split())) print(tc) flatten(Dump_n, Dumps) # terminate_time = timeit.default_timer() # 종료 시간 체크 # print("%f초 걸렸습니다." % (terminate_time - start_time))
# -*- coding: utf-8 -*- def findMatch (itemsList, userInput): isValid = False counter = 0 possibilities = [] while (isValid == False and counter < len(itemsList)): item = itemsList[counter] if userInput == item : isValid = True return counter shorterWordsLength = min(len(userInput), len(item)) letterMatch = 0 for i in range(shorterWordsLength) : if userInput[i] == item[i] or (i < len(item)-1 and userInput == item[i+1]) or (i != 0 and userInput[i] == item[i-1]) : letterMatch += 1 if letterMatch >= 3 : possibilities.append(item) counter+=1 return possibilities
def remove_digit(string): st_res = "" for ch in string: if not ch.isdigit(): st_res +=ch return st_res def remove_let(string): st_res = "" for ch in string: if not ch.isalpha(): st_res +=ch return st_res def parse_matrix(file): matrix_free_terms = [] matrix_coef =[] matrix_unknown_terms = [] matrix_helper = [] with open(file, 'r') as fl: line = fl.readline() while line: current_coef = [] current_helper= [] free_term = line.split('=')[-1].strip() matrix_free_terms.append([int(free_term)]) equation = line.split('=')[0].strip() sign, coefficient, unknown_term = 1, None, None for element in equation.split(): #print(element) if element == '-': sign = -1 elif element == '+': continue else: coefficient = remove_let(element) if coefficient == '': coefficient = 1 * sign else: coefficient = int(coefficient) * sign unknown_term = remove_digit(element) current_helper.append(unknown_term) if unknown_term not in matrix_unknown_terms: matrix_unknown_terms.append(unknown_term) current_coef.append(coefficient) sign, coefficient, unknown_term = 1, None, None matrix_coef.append(current_coef) matrix_helper.append(current_helper) line = fl.readline() return matrix_coef, matrix_free_terms, matrix_unknown_terms, matrix_helper # a b c # d e f # g h i def matrix_determinant(matrix): a, b, c = matrix[0] efhi = [x[1:] for x in matrix[1:]] dfgi = [x[::2] for x in matrix[1:]] degh = [x[0:2] for x in matrix[1:]] determinant = ( a * det2x2(efhi) - b * det2x2(dfgi) + c * det2x2(degh) ) return determinant # determinant of 2x2 matrix def det2x2(matrix): return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] def calc_transpose(matrix): tr_matrix = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(matrix)): for j in range(len(matrix[i])): tr_matrix[j][i] = matrix[i][j] return tr_matrix #Find the determinant of each of the 2x2 minor matrices. def calc_adj(matrix): adj_matrix = [] current_minor = [] minor_efhi = det2x2([x[1:] for x in matrix[1:]]) current_minor.append(minor_efhi) minor_dfgi = (-1) * det2x2([x[::2] for x in matrix[1:]]) current_minor.append(minor_dfgi) minor_degh = det2x2([x[0:2] for x in matrix[1:]]) current_minor.append(minor_degh) adj_matrix.append(current_minor) current_minor = [] minor_bchi = (-1) * det2x2([x[1:] for x in matrix[::2]]) current_minor.append(minor_bchi) minor_acgi = det2x2([x[::2] for x in matrix[::2]]) current_minor.append(minor_acgi) minor_abgh = (-1) * det2x2([x[:2] for x in matrix[::2]]) current_minor.append(minor_abgh) adj_matrix.append(current_minor) current_minor = [] minor_bcef = det2x2([x[1:] for x in matrix[:2]]) current_minor.append(minor_bcef) minor_acdf =(-1) * det2x2([x[::2] for x in matrix[:2]]) current_minor.append(minor_acdf) minor_abde = det2x2([x[:2] for x in matrix[:2]]) current_minor.append(minor_abde) adj_matrix.append(current_minor) return adj_matrix def calc_inverse(matrix, det): inverse_matrix = [[0,0,0], [0,0,0], [0,0,0]] for row in range(0, len(matrix)): for column in range(0, len(matrix[row])): inverse_matrix[row][column] = (matrix[row][column] / det) return inverse_matrix def matrix_product(matrix_a, matrix_b): matrix_result = [[0], [0], [0]] for i in range(0, len(matrix_a)): for j in range(0, len(matrix_b[0])): for k in range(0, len(matrix_b)): matrix_result[i][j] += matrix_a[i][k] * matrix_b[k][j] return matrix_result def start(file_name): matrix_coef, matrix_free_terms, matrix_unknown_terms, matrix_helper = parse_matrix(file_name) # add 0 for i in range(0, 3): for j in matrix_unknown_terms: if j not in matrix_helper[i]: index = matrix_unknown_terms.index(j) matrix_coef[i].insert(index, 0) determinant = matrix_determinant(matrix_coef) if determinant == 0: print("Determinant is null") return transpose = calc_transpose(matrix_coef) adjoint = calc_adj(transpose) inverse = calc_inverse(adjoint, determinant) product = matrix_product(inverse, matrix_free_terms) print("Solution:") for i in range(0, len(matrix_unknown_terms)): print("{} = {}".format(matrix_unknown_terms[i], product[i][0])) start("matrice.txt")
largura = int(input("Digite a largura:")) altura = int(input("Digite a altura:")) guardaLargura = largura guardaAltura = altura while altura > 0: larguraLimite = largura while larguraLimite > 0: if larguraLimite == 1 or larguraLimite == guardaLargura: print("#", end="") elif altura == 1 or altura == guardaAltura: print("#", end="") else: print(" ", end="") larguraLimite = larguraLimite - 1 print() altura = altura - 1
n = int(input("Digite um numero positivo inteiro e descubra se é primo:")) def primo(numero): i, cont = 1, 0 while i <= numero: if (numero % i == 0): cont += 1 i += 1 if cont == 2: print('primo') else: print('não primo') while n >= 0: primo(n) n = int(input("Digite um numero positivo inteiro e descubra se é primo:"))
def fatorial(num): fat = 1 while num > 1: fat *= num num -= 1 return fat def numBionominal(n, k): return fatorial(n) // (fatorial(k) * fatorial(n-k)) def testaBinomial(): if numBionominal(5,2) == 10: print("Ta funcionando para 5,2") else: print("Não funciona em 5,2") if numBionominal(7,4) == 35: print("Ta funcionando em 7,4") else: print("Não funciona em 7,4") if numBionominal(6,1) == 6: print("Funciona em 6,1") else: print("Não funciona 6,1") testaBinomial()
""" @author:YJM @Date:20160408 """ def FindingLeapYear(): print "DO you want Leapyear, Please input year" year=raw_input("Input the year:") year=int(year) if(year%4 == 0) and (year % 100 !=0 or year % 400==0): res="LeapYear" else: res="NormalYear" print res def SumOfMultiplesOf3_5(): print "sumOfMultiplesOf3_5" Start=raw_input("Start your value") Finish=raw_input("Finish your value") Start=int(start) Finish=int(Finish) sum=0 for i in range(Start,Finish): if i%3==0: sum+=i elif i%5==0: sum+=i elif i%15==0: sum-=i print sum def Updown(): print "Game start value up and down" while True: val = raw_input("check your value:") value = int(val) num = 80 if(num<value): print "down" elif(num>value): print "up" else: print "bingo" break; def lab6(): FindingLeapYear() SumOfMultiplesOf3_5() Updown() def main(): lab6() if __name__=="__main__": main()
""" Vizcaino Lopez Fernando 13/03/2020 15/03/2020 reference https://www.geeksforgeeks.org/python-program-for-dynamic-programming-set-10-0-1-knapsack-problem/ """ def knapSack(W , wt , val , n): if n == 0 or W == 0 : return 0 if (wt[n-1] > W): return knapSack(W,wt,val,n-1) else: return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1), knapSack(W , wt , val , n-1)) def CC(coin,n): if n==-1: return 0 if coin[n]==1: return 1 else: return CC(coin,n-1)+coin[n] """coin=[0,1,2,5,10,20,50] n = len(coin)-1 print(CC(coin,n)) val = [5,18,26,35] wt = [1,3,4,5] W = 13 n = len(val) print (knapSack(W , wt , val , n))"""
import numpy as np import pandas as pd df = pd.read_csv("foo.csv") print df df2 = pd.read_csv("foo.csv", index_col=0) print df2 print df2.ix['tom'] print df2['age'] print df2['age'].values print df2['age']['tom']
import re #正则表达式操作库 #match与serch 匹配 # mach()从字符串起始位置开始匹配,匹配成功返回匹配对象,失败则返回None # search()不要求从起始位置开始匹配 print(re.match('book','books')) print(re.search('book','sbooks')) #findall 在爬虫中使用最频繁,用于查找字符串中所有符合正则表达式的字符串,返回一个列表 python = 'python2 python3 are all python' print(re.findall('python',python)) #split 按某个字符将字符串分解为若干子字符串 python = 'python2 python3 are all python' print(re.split(' ',python)) #sub 将字符串中某些字符替换为特定字符串 python = 'python2 python3 are all python' print(re.sub('python','java',python))
import random class Encryptor(object): def __init__(self): self.substitution = {} self.reverse_substitution = {} self.generate_substitution() def generate_substitution(self): russian_alpha_lower = [chr(x) for x in range(ord('а'), ord('а') + 32)] + ['ё', ] russian_alpha_upper = [x.upper() for x in russian_alpha_lower] for alpha in [russian_alpha_lower, russian_alpha_upper]: for letter in alpha: available = set(alpha) - set(self.substitution.values()) available = list(available) self.substitution[letter] = random.choice(available) def generate_reverse_substitution(self): self.reverse_substitution = {v: k for k, v in self.substitution} def check(self): if len(self.substitution) < 1: raise ValueError("Substitution table not generated") def encrypt(self, text): self.check() cypher = [self.substitution[x] if x in self.substitution.keys() else x for x in text] return ''.join(cypher) def decrypt(self, cypher): cypher = [self.reverse_substitution[x] if x in self.reverse_substitution.keys() else x for x in cypher] return ''.join(cypher) e = Encryptor() text = open("text.txt").read() text = text.lower() encrypted = e.encrypt(text) decrypted = e.decrypt(encrypted) assert encrypted == decrypted print(encrypted)
""" Simple functions, Chapter 2 """ def square(x): """ :param x: :return: square of imput number """ return x**2 ##### def evalQuadratic(a, b, c, x): ''' a, b, c: numerical values for the coefficients of a quadratic equation x: numerical value at which to evaluate the quadratic. ''' for check in [a,b,c,x]: if type(check) is str: print("Wrong values! ") exit(1) return a*x**2 + b*x + c
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ given_num = x num = 0 while (x > 0): rem = x % 10 x = x/10 num = num*10 +rem if (given_num == num): return True else: return False
n = int(input("Введите первое число: ")) m = int(input("Введите второе число: ")) s = n + m print("Сумма чисел: " + str(s)) n = int(input("Введите количество секунд: ")) h = n // 3600 a = n % 3600 m = a // 60 s = a % 60 print(f"{h} часов, {m} минут, {s} секунд") n = input("Введите произвольное число: ") m = n * 2 k = n * 3 n = int(n) m = int(m) k = int(k) s = n + m + k print(s) n = int(input("Введите произвольное число подлиннее: ")) s = 0 while n > 0: m = n % 10 if m > s: s = m n = (n - m) / 10 s = int(s) print("Самая большая цифра в числе: ", s) n = int(input("Какова выручка: ")) m = int(input("Каковы издержки: ")) if n < m: print("К сожалению компания принесла убытки") if n == m: print("Вы вышли в ноль") if n > m: s = n - m print("Отлично! Вы получили прибыль в размере: ", s) r = s / n print("Рентабельность составляет: ", r) p = int(input("Сколько в компании сотрудников: ")) pc = s / p print("Прибыль на каждого сотрудника: ", pc)
''' Given six real numbers – a, b, c, d, e, f. Solve the following system of linear equations: a*x + b*y = e c*x + d*y = f Output format If the system has no solution, then the program should print a single number 0. If the system has infinitely many solutions, each of which looks like y=kx+b, then the program should print the number 1, and then the values k and b. If the system has a single solution (x0, y0), then the program should print the number 2, and then the values x0 and y0. If the system has infinitely many solutions that look like x=x0 with any y, then the program should output the number 3, and then the value x0. If the system has infinitely many solutions that look like y=y0 with any x, then the program should output the number 4, and then the value y0. If any pair of numbers (x,y) is a solution, the program should output the number 5. ''' a, b, c, d, e, f = list(map(lambda x: float(input()), range(6))) arr = ['5' if (a,b,c,d,e,f) == (0,0,0,0,0,0) else None, '4 '+str(e/b) if (a,c,d,f) == (0,0,0,0) and b!=0 else None, '4 '+str(f/d) if (a,b,c,e) == (0,0,0,0) and d!=0 else None, '3 '+str(e/a) if (b,c,d,f) == (0,0,0,0) and a!=0 else None, '3 '+str(f/c) if (a,b,d,e) == (0,0,0,0) and c!=0 else None, '1 '+str(-a/b)+' '+str(e/b) if (c,d,f) == (0,0,0) and a!=0 and b!=0 else None, '1 '+str(-c/d)+' '+str(f/d) if (a,b,e) == (0,0,0) and c!=0 and d!=0 else None, '4 '+str(e/b) if (a,c) == (0,0) and b!=0 and d!=0 and e/b == f/d else None, '3 '+str(e/a) if (b,d) == (0,0) and a!=0 and c!=0 and e/a == f/c else None, '2 '+str(e/a) + ' '+str(f/d) if (b,c) == (0,0) and a!=0 and d!=0 else None, '2 '+str(f/c) + ' '+str(e/b) if (a,d) == (0,0) and c!=0 and b!=0 else None, '2 '+str((f - d*e/b)/c)+' '+str(e/b) if a == 0 and b!=0 and c!=0 and d!=0 else None, '2 '+str(e/a)+' '+str((f-c*e/a)/d) if b==0 and a!=0 and c!=0 and d!=0 else None, '2 '+str((e - b*f/d)/a)+' '+str(f/d) if c == 0 and a!=0 and b!=0 and d!=0 else None, '2 '+str(f/c)+' '+str((e-a*f/c)/b) if d==0 and a!=0 and b!=0 and c!=0 else None, '1 '+str(-a/b)+' '+str(e/b) if a!=0 and b!=0 and c!=0 and d!=0 and a*d-b*c == 0 and a*f-c*e == 0 else None, '2 '+str((e-b*(a*f-c*e)/(a*d-b*c))/a)+' '+str((a*f-c*e)/(a*d-b*c)) if a!=0 and b!=0 and c!=0 and d!=0 and a*d-b*c != 0 else None] result = list(filter(lambda x: x, arr)) print(result[0]) if result else print(0)
#!/usr/bin/python from audio_file import AudioFile import argparse import os import shutil parser = argparse.ArgumentParser(description='Audio file information printer.') parser.add_argument('filepath', metavar='filepath', type=str, help='prints audio information from file') parser.add_argument('--overwrite', action="store_true", default=False, help='Overwrite existing files?') parser.add_argument('--copy-to-directory', action="store", dest='copy_to_directory', default=None, help='If supplied, copies the files into an Artist>Album>Track name folder structure') args = parser.parse_args() def get_new_file_path(root_directory, artist, album, track): return os.path.join(root_directory, artist or "Unknown", album or "Unknown", track or "Untitled") def ensure_directory_exists(directory): if not os.path.exists(directory): os.makedirs(directory) file_paths = [] if os.path.isfile(args.filepath): file_paths.append(args.filepath) elif os.path.isdir(args.filepath): for root, dirs, files in os.walk(args.filepath): for file_name in files: file_paths.append(os.path.join(root, file_name)) else: raise IOError("No file or directory at %s" % args.filepath) for file_path in file_paths: audio_file = AudioFile(file_path) print "File path: %s" % audio_file.file_path print "Artist: %s" % (audio_file.artist or "Unknown") print "Album: %s" % (audio_file.album or "Unknown") print "Track name: %s" % (audio_file.track_name or "Unknown") if args.copy_to_directory is not None: extension = "." + file_path.split(".")[-1] new_file_path = get_new_file_path(args.copy_to_directory, audio_file.artist, audio_file.album, audio_file.track_name or "Untitled" + extension) if args.overwrite is False and os.path.exists(new_file_path): print "%s already exists, will not overwrite" % (new_file_path) else: ensure_directory_exists(os.path.join(args.copy_to_directory, audio_file.artist or "Unknown", audio_file.album or "Unknown")) print "copying from %s to %s" % (file_path, new_file_path) shutil.copyfile(file_path, new_file_path) print ""
"""Useful miscellaneous functions.""" from typing import Callable def get_linear_anneal_func( start_value: float, end_value: float, start_step: int, end_step: int ) -> Callable: """Create a linear annealing function. Parameters ---------- start_value : float Initial value for linear annealing. end_value : float Terminal value for linear annealing. start_step : int Step to start linear annealing. end_step : int Step to end linear annealing. Returns ------- linear_anneal_func : Callable A function that returns annealed value given a step index. """ def linear_anneal_func(step): if step <= start_step: return start_value if step >= end_step: return end_value # Formula for line when two points are known: # y1 - y0 # y - y0 = --------- (x - x0) # x1 - x0 return (end_value - start_value) / (end_step - start_step) * ( step - start_step ) + start_value return linear_anneal_func
palavra = 'paralelepipedo' for letra in palavra: print(letra, end='\n') print('Fim') # ------------------------------------------------------------------------------------------------- aprovados = ['Jefferson', 'Derico', 'Dirlayne', 'Denise', 'Sergio', 'Leiri', 'Lilian', 'Pedro', 'Giuliano', 'Felipe'] for nome in aprovados: print(nome) for posicao, nome in enumerate(aprovados): print(f'{posicao + 1})', nome) # ------------------------------------------------------------------------------------------------ dias_semana = ('Domingo', 'Segunda', 'Terça' 'Quarta', 'Quinta', 'Sexta', 'Sábado') for dia in dias_semana: print(f'Hoje é {dia}') for letra in set('jeffersonluisrasini'): print(letra) for numero in {1, 2, 3, 4, 5, 6, 7, 8, 9}: print(numero)
# a = 10 # b = 5.2 # print(a + b) # ------------------------------- # a = 'Agora sou uma string' print(a)
nota = 10 if nota == 10: print('Excelente, você foi aprovado com a nota máxima!!! ') elif nota >= 7: print('Parabéns, você foi aprovado!!! ') elif nota >= 6: print('Faltou muito pouco para sua aprovação. Você ficou de recuperação!!! ') else: print('Você está reprovado!!')
#!/usr/bin/env python # coding: utf-8 # # Chapter 3: Sequence objects # * Sequences are essentially strings of letters like AGTACACTGGT, which seems very natural since this is the most common way that sequences are seen in biological le formats # * The most important di erence between Seq objects and standard Python strings is they have di erent methods. Although the Seq object supports many of the same methods as a plain string, its translate() method di ers by doing biological translation, and there are also additional biologically relevant methods like reverse_complement(). # ## 3.1 Sequences act like strings # In[1]: from Bio.Seq import Seq my_seq = Seq("GATCG") for index, letter in enumerate(my_seq): print("%i %s" % (index, letter)) print( "First element: " + my_seq[0] ) print( "Total elements: " + str( len( my_seq ) ) ) # ### Count elements # In[2]: from Bio.Seq import Seq my_seq = Seq("GATCGATGGGCCTATATAGGATCGAAAATCGC") # In[3]: len(my_seq) # In[4]: my_seq.count("G") # In[5]: my_seq.count("GA") # #### GC% # In[6]: 100 * float(my_seq.count("G") + my_seq.count("C")) / len(my_seq) # In[7]: from Bio.SeqUtils import GC GC( my_seq ) # ## 3.2 Slicing a sequence # In[8]: my_seq[4:12] # In[9]: my_seq[0::2] # In[10]: # Reverse print( my_seq ) print( my_seq[::-1] ) # In[11]: # Back to string: str(my_seq) # # 3.4 Concatenating or adding sequences # In[12]: from Bio.Seq import Seq seq_1 = Seq("ATATAGG") seq_2 = Seq("ACGT") seq_1 + seq_2 # ## Loop-based concat # In[13]: from Bio.Seq import Seq list_of_seqs = [Seq("ACGT"), Seq("AACC"), Seq("GGTT")] concatenated = Seq("") for s in list_of_seqs: concatenated += s concatenated # ## Join-based concat # ## TODO: Not working but code shows this example? # In[14]: from Bio.Seq import Seq concatenated = Seq('NNNNN').join([Seq("AAA")]) concatenated # In[15]: from Bio.Seq import Seq contigs = [Seq("ATG"), Seq("ATCCCG"), Seq("TTGCA")] spacer = Seq("N"*10) spacer.join(contigs) # ## 3.6 Nucleotide sequences and (reverse) complements # * DNA: A=T, G≡C # * RNA: A=U, G≡C # # * Nucleic acid sequence of bases that can form a double- stranded structure by matching base pairs. For example, the **complementary sequence** to C-A-T-G (where each letter stands for one of the bases in DNA) is G-T-A-C # * The **reverse complement** of a DNA sequence is formed by reversing the letters, interchanging A and T and interchanging C and G. Thus the reverse complement of ACCTGAG is CTCAGGT. # In[16]: from Bio.Seq import Seq my_seq = Seq("GATCGATGGGCCTATATAGGATCGAAAATCGC") print( my_seq ) print( my_seq.complement() ) print( my_seq.reverse_complement() ) # # 3.7 Transcription # In[17]: from Bio.Seq import Seq coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG") template_dna = coding_dna.reverse_complement() print("5' - " + coding_dna + " - 3'") print("3' - " + template_dna[::-1] + " - 5'") # ## Transcribe # ### DNA Coding Strand transcription # "As you can see, all this does is to replace T by U." # In[18]: coding_dna.transcribe() # In[19]: coding_dna # ### Template Strand transcription # In[20]: template_dna.reverse_complement().transcribe() # ### mRNA to DNA # # "Again, this is a simple U -> T substitution:" # In[21]: from Bio.Seq import Seq messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG") print( messenger_rna ) print( messenger_rna.back_transcribe() ) # # 3.8 Translation # Translation is done from NCBI coding schemes. # # * [NCBI Coding Scheme](https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi) # ## Translate from mRNA # In[22]: from Bio.Seq import Seq messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG") print( messenger_rna ) print( messenger_rna.translate() ) # ## Translate from coding DNA # In[23]: from Bio.Seq import Seq coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG") print( coding_dna ) print( coding_dna.translate() ) # ### Take into account the DNA type # In[24]: print( coding_dna.translate(table="Vertebrate Mitochondrial") ) # ### NCBI table number (instead of using Vertebrate Mitochondrial) # In[25]: print( coding_dna.translate(table=2) ) # ### To Stop Codon # In[26]: print( coding_dna.translate(to_stop=True) ) # In[27]: print( coding_dna.translate(to_stop=True, table="Vertebrate Mitochondrial") ) # ## Complete coding sequence CDS # Telling BioPython to use a CDS means the coding becomes **Methionine** instead of **Valine**. # In[28]: from Bio.Seq import Seq gene = Seq( "GTGAAAAAGATGCAATCTATCGTACTCGCACTTTCCCTGGTTCTGGTCGCTCCCATGGCA" "GCACAGGCTGCGGAAATTACGTTAGTCCCGTCAGTAAAATTACAGATAGGCGATCGTGAT" "AATCGTGGCTATTACTGGGATGGAGGTCACTGGCGCGACCACGGCTGGTGGAAACAACAT" "TATGAATGGCGAGGCAATCGCTGGCACCTACACGGACCGCCGCCACCGCCGCGCCACCAT" "AAGAAAGCTCCTCATGATCATCACGGCGGTCATGGTCCAGGCAAACATCACCGCTAA") # In[29]: gene.translate(table="Bacterial") # In[30]: gene.translate(table="Bacterial", cds = True) # ### And it will throw an exception if wrong. # # "Sequence length 296 is not a multiple of three" # In[31]: gene = Seq( "GTGAAAAAGATGCAATCTATCGTACTCGCACTTTCCCTGGTTCTGGTCGCTCCCATGGCA" "GCACAGGCTGCGGAAATTACGTTAGTCCCGTCACTAAAATTACAGATAGGCGATCGTGAT" "AATCGTGGCTATTACTGGGATGGAGGTCACTGGCGCGACCACGGCTGGTGGAAACAACAT" "TATGAATGGCGAGGCAGTCGCTGGCACCTACACGGACCGCCGCCACCGCCCGCCACCAT" "AAGAAAGCTCCTCATGATCATCACGGCGGTCATGGTCCAGGCAAACATCACCGCTAA") gene.translate(table="Bacterial", cds = True) # # 3.9 Translation Tables # * Internally these use codon table objects derived from the NCBI information at [gc.prt](ftp://ftp.ncbi.nlm.nih.gov/entrez/misc/data/) # * Also shown on https: [wprintgc.cgi](//www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi ) # In[32]: from Bio.Data import CodonTable standard_table = CodonTable.unambiguous_dna_by_name["Standard"] mito_table = CodonTable.unambiguous_dna_by_name["Vertebrate Mitochondrial"] # In[33]: print(standard_table) # In[34]: print(mito_table) # ## Example: Find Codons # In[35]: standard_table.stop_codons # In[36]: standard_table.start_codons # In[37]: print( mito_table.forward_table["ACG"] ) print( mito_table.forward_table["CCG"] ) # # 3.10 Comparing Seq objects # As of Biopython 1.65, sequence comparison only looks at the sequence and compares like the Python string. # # 3.11 MutableSeq objects # In[38]: from Bio.Seq import Seq my_seq = Seq("GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA") my_seq[5] = "G" # Throws exception # In[39]: mutable_seq = my_seq.tomutable() mutable_seq # In[40]: mutable_seq[0] = "C" mutable_seq # In[41]: mutable_seq.remove("T") mutable_seq # ## Back to immutable # In[42]: immutable_again_seq = mutable_seq.toseq() immutable_again_seq # In[43]: immutable_again_seq[5] = "G" # # 3.12 UnknownSeq objects # # A (more) memory efficient way of holding a sequence of unknown letters. # In[44]: from Bio.Seq import UnknownSeq unk = UnknownSeq(20) print(unk) # * DNA is commonly labeled with N # * Protein is commonly labeled with X # In[45]: unk_dna = UnknownSeq(20,character="N") unk_dna # In[46]: unk_protein = UnknownSeq(20,character="X") unk_protein # In[ ]:
import numpy as np ### Functions for you to fill in ### def polynomial_kernel(X, Y, c, p): """ Compute the polynomial kernel between two matrices X and Y:: K(x, y) = (<x, y> + c)^p for each pair of rows x in X and y in Y. Args: X - (n, d) NumPy array (n datapoints each with d features) Y - (m, d) NumPy array (m datapoints each with d features) c - a coefficient to trade off high-order and low-order terms (scalar) p - the degree of the polynomial kernel Returns: kernel_matrix - (n, m) Numpy array containing the kernel matrix """ # YOUR CODE HERE kernel_matrix = (X @ Y.T + c) ** p return kernel_matrix raise NotImplementedError def rbf_kernel(X, Y, gamma): """ Compute the Gaussian RBF kernel between two matrices X and Y:: K(x, y) = exp(-gamma ||x-y||^2) for each pair of rows x in X and y in Y. Args: X - (n, d) NumPy array (n datapoints each with d features) Y - (m, d) NumPy array (m datapoints each with d features) gamma - the gamma parameter of gaussian function (scalar) Returns: kernel_matrix - (n, m) Numpy array containing the kernel matrix """ # YOUR CODE HERE n, m = X.shape[0], Y.shape[0] # kernel_matrix = np.zeros((n,m)) # for i in range(n): # for j in range(m): # kernel_matrix[i,j] = np.exp(-gamma * sum((X[i]-Y[j])**2)) # print("X=",X) # print("Y=",Y) # matrix1 = np.tile((X @ X.T).sum(axis=1),m).reshape(m,n).T # n,m # matrix2 = np.tile((Y @ Y.T).sum(axis=1),n).reshape(n,m) matrix1 = np.tile((X**2).sum(axis=1), m).reshape(m, n).T matrix2 = np.tile((Y**2).sum(axis=1), n).reshape(n, m) # print("matrix1=", matrix1) # print("matrix2=", matrix2) matrix3 = -2* X @ Y.T kernel_matrix = np.exp(-gamma * (matrix1 + matrix2 + matrix3)) return kernel_matrix raise NotImplementedError
#!/usr/bin/python import sys import csv csv_reader = csv.reader(sys.stdin) for s in csv_reader: if s[16] == 'NY': print("NY\t1") else: print("Other\t1")
number = int(input("Please enter a number: ")) sum_of_odd_nums = 0 sum_of_even_nums = 0 even_num_counter = 0 for i in range(1, number+1): if i % 2 != 0: sum_of_odd_nums += i else: sum_of_even_nums += i even_num_counter += 1 print("sum of odd numbers: ", sum_of_odd_nums) print("average of even numbers: ", sum_of_even_nums / even_num_counter)
# asdfasdfasdfasdfasdfasdfasdf # input de usuário nome = input("Digite seu nome: ") # input de usuário idade = int(input(f"Qual a sua idade {nome}?")) nascimento = 2020 - idade print(f"{nome} você nasceu em {nascimento}") num1 = int(input("Digite um numero: ")) num2 = int(input("Digite outro numero: ")) resultado = num1 + num2 print(f"O resultado é: {resultado}")
from __future__ import print_function ''' Introduction ''' # A line of text is called a string because it is similar to a string of characters # connected together. ''' ''' ''' ''' ''' ''' ''' Procedure ''' #5 The data type long can be used to represent 6 million because it is an integer # with a very large value. slogan = 'My school is the best' type(slogan) # str slogan # 'My school is the best' #6 The second line of code will produce an error because a string and an integer # cannot be concatenated. type('tr' + "y this") # type('tr' + 5) #7 The index of a string returns the character at that index, starting from 0. If # the index is greater than the amount of characters in the string, the code # will produce an error. If the index is a negative number, the code will # count that index from the end of the string. In the case of slogan[-7], it # returns the 7th to last character in the string. #8 # slogan[5:21] = 'hool is the best' # slogan[:5] = 'My sc' # Slicing for 'best': slogan[17:] #9 slogan[:12] + 'in Dublin.' #10 #10a The variable activity is set to the value of a string, 'theater,' and # using the len() function on activity will return the length of the # string it holds, not the name of the variable. #10b The output of the code is 'theate' because the string is sliced so that # it returns all characters except the last one, because the second number # in slicing is excluded. #11 The code returns True because the string 'test goo' is found in part of # 'Greatest good for the greatest number!' between 'Greatest' and 'good'. #12 def how_eligible(essay): counter = 0 if '?' in essay: counter += 1 if '"' in essay: counter += 1 if ',' in essay: counter += 1 if '!' in essay: counter += 1 return counter #1.3.5 Function Test print(how_eligible('This? "Yes." No, not really!')) print(how_eligible('Really, not a compound sentence.')) # I believe I have successfully completed the assignment because the output of # assignment check matches that of the instructions.
while True: nums = input().split(' ') if (nums.count('0') == 2): break nums_sorted = sorted(nums) print(' '.join(nums_sorted))
"""The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated. Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.""" n = int(input()) a = list(map(int, input().split())) unsolved_crimes = 0 police_officers = 0 crimes = 0 m = len(a) for i in range(m): if crimes == 0 and a[i] == -1 and police_officers == 0: unsolved_crimes += 1 elif a[i] == -1: police_officers -= 1 if a[i] > 0: police_officers += a[i] print(unsolved_crimes)
"""«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every k-th dragon got punched in the face with a frying pan. Every l-th dragon got his tail shut into the balcony door. Every m-th dragon got his paws trampled with sharp heels. Finally, she threatened every n-th dragon to call her mom, and he withdrew in panic. How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of d dragons?""" k = int(input()) l = int(input()) m = int(input()) n = int(input()) D = int(input()) count = 0 for i in range(1, D + 1): if i % k == 0 and k <= D: count += 1 elif i % l == 0 and l <= D: count += 1 elif i % m == 0 and m <= D: count += 1 elif i % n == 0 and n <= D: count += 1 print(count)