En esta entrada estaré compartiendo como validar si un número es primo o no en Python, primeramente estaré definiendo que es un número primo. ¿Qué es un número primo? Los números primos son aquellos que solo son divisibles entre ellos mismos y el 1, es decir, que si intentamos dividirlos por cualquier otro número, el resultado no es entero. Dicho de otra forma, si haces la división por cualquier número que no sea 1 o él mismo, se obtiene un resto distinto de cero. Solución Luego de ver la definición de un número primo, veremos como programar una función que retorne verdadero si un número es primo o no. Será mostrado de dos formas, con recursividad y con iteración. Iteración Para esta solución haremos una función que recibirá un número y creará una variable llamada contador que inicia en 0. Luego de eso va entrar a un ciclo for que irá de 1 al número + 1, donde aumentará el contador en uno cuando el número sea divisible entre la variable de iteración (...
In this blog, I will be showing you how to get the lowest number from a list. In Python, you can easily do this with just min, for example:
list=[1,10,20,4,0,2]
min(list)
#this will return 0
But I want to show you a way to get the lowest number yourself.
Code
In the next code, you will see a function that receives a list of numbers and does the next steps:
- Views if the list is not empty, if it is empty, you will print in the console a message.
- Sets in the length variable, the length of the list of numbers
- Sets in result the first element of the list
- In a for loop, it goes through each number of list except the first one.
- it compares the number selected in the loop with the number in the variable result
- If the number in the variable i is lower, then that number is the new value of result and goes to the next loop
- when the whole list was already checked, it returns the variable result.
def get_min_number(number_list):
if(number_list):
length=len(number_list)
result=number_list[0]
for i in range(0,length):
if(result>number_list[i]):
result=number_list[i]
return result
else:
print('List is empty')
How to run this program
Save this code in a Python file (code1.py for example) and run it the Python shell. View the next image to see how to call the function and what it return.
| How to run the program |
Comentarios
Publicar un comentario