Comprensione delle liste

    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())


    l1 = [i for i in range(x+1)]
    l2 = [i for i in range(y+1)]
    l3 = [i for i in range(z+1)]

    cubi = [[x,y,z] for x in l1 for y in l2 for z in l3]
    sol = [a for a in cubi if a[0]+a[1]+a[2]!=n]

    print(sol)

In questo esercizio mostro le list comprehensions.

Risolviamo un problema utilizzando solo le liste e senza loop.

Viene fornito un cubo di dimensioni x,y,z ed un intero n

si tratta di trovare tra tutti i cubi contenuti in x,y,z, tutti quelli la cui somma dei lati sia diversa da n.

Media dei voti degli studenti di una classe

    n = int(input())
    student_marks = {}
    for _ in range(n):
        line = input().split()
        name, scores = line[0], line[1:]
        scores = map(float, scores)
        student_marks[name] = scores
    query_name = input()

    votes = student_marks[query_name]
    
    n=0.0
    for v in votes:
        n=n+v;
    
    n=n/len(votes)

    print("{:.2f}".format(n))

L’input è come segue :

3
andrea 27 21 30
marco 30 28 26
matteo  30 29 28
marco

La prima riga (3) è i numero di studenti;

segue una riga per ciascun studente contenente nome e lista dei voti;

infine il nome dello studente di cui si vuole conoscere la media dei voti.

Rete Neuronale

import numpy as np

class NeuralNetwork():
    
    def __init__(self):
        # seeding for random number generation
        np.random.seed(1)
        
        #converting weights to a 3 by 1 matrix with values from -1 to 1 and mean of 0
        self.synaptic_weights = 2 * np.random.random((3, 1)) - 1

    def sigmoid(self, x):
        #applying the sigmoid function
        return 1 / (1 + np.exp(-x))

    def sigmoid_derivative(self, x):
        #computing derivative to the Sigmoid function
        return x * (1 - x)

    def train(self, training_inputs, training_outputs, training_iterations):
        
        #training the model to make accurate predictions while adjusting weights continually
        for iteration in range(training_iterations):
            #siphon the training data via  the neuron
            output = self.think(training_inputs)

            #computing error rate for back-propagation
            error = training_outputs - output
            
            #performing weight adjustments
            adjustments = np.dot(training_inputs.T, error * self.sigmoid_derivative(output))

            self.synaptic_weights += adjustments

    def think(self, inputs):
        #passing the inputs via the neuron to get output   
        #converting values to floats
        
        inputs = inputs.astype(float)
        output = self.sigmoid(np.dot(inputs, self.synaptic_weights))
        return output


if __name__ == "__main__":

    #initializing the neuron class
    neural_network = NeuralNetwork()

    print("Beginning Randomly Generated Weights: ")
    print(neural_network.synaptic_weights)

    #training data consisting of 4 examples--3 input values and 1 output
    training_inputs = np.array([[0,0,1],
                                [1,1,1],
                                [1,0,1],
                                [0,1,1]])

    training_outputs = np.array([[0,1,1,0]]).T

    #training taking place
    neural_network.train(training_inputs, training_outputs, 15000)

    print("Ending Weights After Training: ")
    print(neural_network.synaptic_weights)

    user_input_one = str(input("User Input One: "))
    user_input_two = str(input("User Input Two: "))
    user_input_three = str(input("User Input Three: "))
    
    print("Considering New Situation: ", user_input_one, user_input_two, user_input_three)
    print("New Output data: ")
    print(neural_network.think(np.array([user_input_one, user_input_two, user_input_three])))
    print("Wow, we did it!")

by  Dr. Michael J. Garbade

https://www.kdnuggets.com/2018/10/simple-neural-network-python.html

Funzioni

def is_leap(year):
    leap = False
    
    if (year%4==0 and year%100!=0) or year%400==0:
        leap = True
  
    return leap

anno = 1964
anno = int(input("Scrivi un anno nel formato <aaaa> e premi invio"))
res = is_leap(anno)
if res:
    print("L'anno è bisestile")
else:
    print("L'anno non è bisestile")

Esempio di come scrivere una funzione (is_leap) in Python.

In questo caso la funzione calcola se l’anno passato come argomento sia bisestile o no.