In this lesson I will do some examples of using the for loop with the list element in Python.
For list Python – Print a list in reverse order using the for loop
This problem can have several solutions, we will analyze some of them.
The first solution makes use of the reversed() function, to invert a list, the second one uses the length of the list, the len() function.
Let’s start by analyzing the first solution in detail.
First we create a list of elements: numbers = [1, 2, 3, 4, 5], then we use the existing function reversed() to reverse the elements of a list. So we print the inverted elements using the for loop in Python on the list.
Here is a possible solution:
numbers = [1, 2, 3, 4, 5]
numbers_reversed = reversed(numbers)
for number in numbers_reversed:
print(number)
Let’s now work out a second solution, calculating the length of the list from which we will subtract one. In this way we find the index of the last element of the list. Then we will use the appropriate for loop.
Here is the complete code of the second solution to our algorithm that uses the for on lists in Python:
numbers = [1, 2, 3, 4, 5]
n_numbers = len(numbers) - 1
for i in range (n_numbers, -1, -1):
print(numbers[i])
For list Python – Compute the cube of all elements of a list
Let’s create a list of integers. With the for loop we calculate the cube of each element and print the list. We use the len function to determine the length of the list. Finally we cycle through the modified list to print the elements.
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
numbers[i] = numbers[i] * numbers[i] * numbers[i]
for number in numbers:
print(number)
A second solution involves simply using the function in Python to calculate the powers of a number, the pow() function.
In our case we will need to raise to the cube. Then we cycle through the list with the for loop in Python.
Here is the complete sample code:
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
numbers[i] = pow(numbers[i],3)
for number in numbers:
print(number)
These are just some simple examples of using the for loop with lists in Python, in the next lessons we will develop many other examples.
Integrate a Python Compiler Online to test the code directly.
Below you will find the basic version, scrolling the page you will find the compiler with the integration of some fundamental libraries for automatic calculation.
Basic version of the Python Compiler Online:
Write Python code using one of the most popular built-in compilers.
Python Compiler Online with Libreries
We can also use libraries like NumPy, Pandas, Matplotlib, Seaborn. Here is an advanced version of the Python Compiler with an example on the logarithmic scale:
About Python
Python is a very popular programming language created by Guido van Rossum. It was released in 1991 and has been increasingly adopted in a variety of fields since then.
Python, in fact, is a generic and high-level programming language widely used both for Web development and for the field of data science and machine learning. So it allows you to create mobile apps using cutting-edge frameworks such as Flask and Diango, and on the other hand it allows you to use libraries such as NumPy, Pandas, Matplot, Seaborn, etc …So we can say that sit is suitable both in the field of web development and in the analysis of data and automatic access.
Simple examples – Python Compiler Online:
Try some simple examples in the Python Compiler to test the programs.
First example:
Write a Python program using Pandas to create and display a one-dimensional array-like object containing an array of data.
In questa lezione farò alcuni esempi di utilizzo del ciclo for … in sulle liste in Python.
For in con le liste in Python
In questo primo esempio dobbiamo stampare una lista in ordine inverso utilizzando il ciclo for in.
Questo problema può avere diverse soluzioni, ne analizzeremo alcune.
Prima soluzione – For in con le liste in Python
La prima soluzione fa uso della funzione reversed(), per invertire una lista, la seconda che fa uso della lunghezza della lista, la funzione len().
Cominciamo analizzando in dettaglio la prima soluzione.
Innanzitutto creiamo una lista di elementi: numbers = [1, 2, 3, 4, 5], dopo utilizziamo la funzione esistente reversed() per invertire gli elementi di una lista. Dunque stampiamo gli elementi invertiti utilizzando il ciclo for in Python sulla lista.
numbers = [1, 2, 3, 4, 5]
numbers_reversed = reversed(numbers)
for number in numbers_reversed:
print(number)
Seconda soluzione – For in con le liste in Python
Realizziamo adesso una seconda soluzione, calcolando la lunghezza della lista a cui sottrarremo uno. In questo modo troviamo l’indice dell’ultimo elemento della lista. Poi utilizzeremo il ciclo for opportuno.
Ecco il codice completo della seconda soluzione al nostro algoritmo che utilizza il for sulle liste in Python:
numbers = [1, 2, 3, 4, 5]
n_numbers = len(numbers) - 1
for i in range (n_numbers, -1, -1):
print(numbers[i])
For in con le liste in Python
Propongo un secondo esempio dove dobbiamo calcolare il cubo di tutti gli elementi di una lista.
Creiamo dunque una lista di numeri interi. Con il ciclo for calcoliamo il cubo di ciascun elemento e stampiamo la lista. Utilizziamo la funzione len per determinare la lunghezza della lista. Infine cicliamo la lista modificata per stampare gli elementi.
Ecco il codice completo
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
numbers[i] = numbers[i] * numbers[i] * numbers[i]
for number in numbers:
print(number)
Una seconda soluzione prevede semplicemente l’uso della funzione in Python per calcolare le potenze di un numero, la funzione pow().
Nel nostro caso ci servirà elevare al cubo. Poi cicliamo sulla lista con il ciclo for in Python.
Migliora le tue capacità di programmazione Python seguendo i nostri corsi in diretta!
Ecco il codice di esempio completo:
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
numbers[i] = pow(numbers[i],3)
for number in numbers:
print(number)
Conclusioni
Da questa lezione possiamo trarre alcune conclusioni utili:
Flessibilità di utilizzo: Il ciclo for in Python offre un modo flessibile per iterare attraverso gli elementi di una lista ed eseguire operazioni su di essi.
Diverse soluzioni per gli stessi problemi: Come dimostrato nei vari esempi, ci sono spesso diverse soluzioni per risolvere lo stesso problema. È importante conoscere le varie opzioni disponibili e scegliere quella più adatta alle proprie esigenze.
Utilizzo delle funzioni built-in: Python fornisce diverse funzioni built-in, come reversed() e len(), che semplificano la manipolazione delle liste. Saperle utilizzare efficacemente può semplificare il codice e renderlo più leggibile.
Sperimentazione e pratica: La pratica è fondamentale per padroneggiare l’utilizzo del ciclo for con le liste. Sperimentare con diversi esempi e esercizi aiuta a comprendere appieno le potenzialità di questo costrutto e a diventare più abili nel suo utilizzo.
In conclusione, l’utilizzo del ciclo for con le liste in Python è un’abilità fondamentale per qualsiasi programmatore Python. Con una comprensione approfondita di come utilizzare il ciclo for in modo efficace e creativo, è possibile affrontare una vasta gamma di problemi di programmazione con sicurezza e precisione. Continuare a esplorare e praticare queste tecniche è essenziale per migliorare le proprie capacità di programmazione in Python.
Questi sono solo alcuni semplici esempi di utilizzo del ciclo for in sulle liste in Python, nelle prossime lezioni sviluppermo tanti altri esempi.
Install Python is very simple and we will see it in detail on all systems. But before installation let’s make a brief introduction to this amazing programming language
Python is a language that adapts to multiple fields, such as websites, computer science, and artificial intelligence. During this tutorial we will therefore explore the various areas of expertise.
In this lesson we will see how to install Python. First let’s make a brief introduction of this fantastic programming language.
It is a language that supports object-oriented programming and is being addressed more and more, even in universities.
There are numerous frameworks developed for Python and often represent optimal solutions for quickly building applications. Among these we will deal with Flask and Django, two important open-source web frameworks, useful for creating simple internet and e-commerce sites.
I will also mention Plone, a CMS (Content Management System) used to manage a website with ease.
This last part will therefore be useful for those who want to work with these tools.
How to install Python?
To install, go to the official website: https://www.python.org/downloads/ and download the version suitable for your operating system.
Windows
First we show the installation of Python in a Windows environment.
As soon as the installation starts, you will be asked for some options, make sure you select the Add Python 3.X to PATH item.
But, if you forget to do so, don’t worry, you can still change this option by going to: control panel -> system-> advanced system settings -> environment variable.
As well as from the pictures shown below.
Then click on the edit button and add the path specifying the appropriate path.
Alternatively, you can launch the executable again, click on modify and add the check mark on Add Python to environment variables.
The Python installation is complete
Working in interactive mode
After installing Python on your PC, you can start working in interactive mode or creating scripts that can then be executed.
The interactive mode allows you to interact directly with the interpreter, this is only convenient at the beginning to learn how to do some small tests.
To work in this mode, you need to start the IDLE. IDLE is software that allows both to work interactively and to create scripts.
Starting it, the interactive interpreter will be presented with the cursor positioned after the symbol: >>> (triple major sign), the Python shell.
You can consult information about the language specifications by entering the help() command.
After entering the help, you can request, for example, information on the individual instructions of the language.
Then try to request the if statement, you will see information on the use of this statement.
To exit the help you need to type quit.
You can also avoid entering the help by typing, after the >>> symbol, the word help followed by the required term inserted in quotes inside the round brackets.
For example help (‘if’).
Well in this guide we have seen the installation of Python, in the next tutorial we will start creating our first Python program.
L’algoritmo bubble sort in Python è l’argomento di questa lezione. Il bubble sort è un algoritmo di ordinamento molto semplice da implementare, ma dobbiamo dire che è anche poco efficiente.
Infatti il bubble sort è utilizzato principalmente in ambito didattico per far apprendere le logiche e le basi della programmazione.
Il funzionamento del bubble sort è questo:
Si confrontano gli elementi vicini tra di loro, portando l’elemento maggiore in ultima posizione durante la prima “passata” (eseguendo n-1 confronti), poi il secondo massimo in penultima posizione e così via finché l’array non è ordinato.
Quindi ad ogni passaggio si inserisce nell’elenco il valore successivo più grande al posto giusto.
La complessità dell’algoritmo è O(n2), sia nel caso peggiore, sia nel caso migliore.
Implementazione dell’algoritmo bubble sort in Python
Implementiamo la soluzione all’algortimo bubble sort in Python in maniera diversa rispetto agli altri linguaggi di programmazione. Questo perchè per lo scambio delle variabili in Python non è necessaria una variabile di appoggio temporanea.
Questa procedura, detta assegnazione simultanea, mi consente di snellire l’algoritmo bubble sort in Python.
def bubbleSort(array):
for j in range(0, len(array)-1):
for i in range(0, len(array)-1):
if array[i]>array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
array_numbers = [54,26,93,17,77,31,44,55,20]
bubbleSort(array_numbers)
print(array_numbers)
L’algoritmo è molto semplice, basandosi sul confronto di elementi adiacenti.
Ma se l’algoritmo fosse ordinato? In ogni caso dovrei ripetere il ciclo esterno sempre n-1 volte. Possiamo pensare allora a fare delle ottimizzazioni all’algoritmo proposto.
Ottimizzazione dell’algoritmo bubble sort in Python – ordinamento per scambio con sentinella
Possiamo pensare di interrompere il ciclo for esterno, con un break, se al termine del primo ciclo interno non si è fatto alcuno scambio. Per questo scopo utilizziamo una variabile di appoggio chiamata flag, che inizializziamo a 0. Dopo, cambiamo il valore di questa variabile se nel ciclo interno si effettua almeno uno scambio. In alternativa a 0 ed 1 posso usare una variabile booleana.
Ecco il codice di esempio:
def bubbleSort(array):
for j in range(0, len(array)-1):
flag = False
for i in range(0, len(array)-1):
if array[i]>array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
flag = True
if not(flag):
break
array_numbers = [54,26,93,17,77,31,44,55,20]
bubbleSort(array_numbers)
print(array_numbers)
Seconda ottimizzazione dell’algoritmo bubble sort in Python
Possiamo ottimizzare l’algoritmo bubble sort riflettendo sul fatto che ad ogni incremento di j, almeno gli ultimi j+1 elementi sono già stati ordinati. Questo in considerazione del fatto che ad ogni iterazione, l’elemento più grande è stato spostato verso destra.
Quindi ad ogni iterazione accorciamo il ciclo dei confronti. Infatti all’n-esima iterazione si può fare a meno di toccare gli ultimi n-1 elementi che ormai sono nella loro posizione definitiva. Dunque decrementiamo n di uno ad ogni iterazione (- -n), in modo da diminuire di 1, di volta in volta, il numero dei confronti effettuati.
Ecco dunque il codice completo dell’algoritmo ottimizzato:
def bubbleSort(array):
len_array = len(array)
for j in range(0, len_array-1):
flag = False
for i in range(0, len_array-1):
if array[i]>array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
flag = True
len_array = len_array - 1
if not(flag):
break
array_numbers = [54,26,93,17,77,31,44,55,20]
bubbleSort(array_numbers)
Terza ottimizzazione dell’algoritmo bubble sort in Python
Un’ulteriore ottimizzazione all’algoritmo bubble sort in Python può essere sviluppata in considerazione del fatto che il ciclo interno si interrompe proprio dove è avvenuto lo scambio. Quindi, dopo ogni iterazione più elementi si trovano nella posizione definitiva e si può evitare di ordinarli nuovamente.
Occorre memorizzare la posizione ( i+1) dell’ultimo scambio effettuato in una variabile che chiameremo ad esempio pos. Dopo assegniamo alla lunghezza dell’array il valore di pos.
Ecco una possibile implementazione dell’algoritmo ottimizzato:
def bubbleSort(array):
len_array = len(array)
for j in range(0, len_array-1):
flag = False
for i in range(0, len_array-1):
if array[i]>array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
flag = True
pos = i + 1
if not(flag):
break
else:
len_array = pos
print(i,j)
array_numbers = [54,26,93,17,77,31,44,55,20]
bubbleSort(array_numbers)
print(array_numbers)
Conclusioni
In questa lezione ho realizzato alcune implementazioni dell’algoritmo bubble sort in Python, cercando di ottimizzare un algoritmo semplice da implementare, ma lento. Nelle prossime lezioni spiegherò altri algoritmi di ordinamento.
Commenti recenti