Repetition

--Originally published at Python

In this post I will be talking about repetition in Python 3 and when you should use which type of repetition. As we already know (or should) the 2 types of repetition we have are “while” and “for”. They are different but follow the same idea, a process is repeated depending on what you want to achieve.

While is better used when you don’t know the number of times a process will be repeated. That’s why you just state a condition and expect it to be false at some point in time, that’s when it will stop and you will get your result from it.

For is used when you have a List or a Tuple. We know how many times a process will be repeated because we know the number of variables inside of the list or tuple used. So the final answer here will depend on the number of variables you have stored, not on a condition given to the program.

In conclusion, use While when you want a loop to repeat infinitely until a certain condition is false, use For when you have a list or a Tuple and you want a process to be repeated according to the number of variables you have in them and their value. If you want another explanation and easy to follow examples, click here.


Tuples

--Originally published at Hector Martinez Alcantara

The tuples are almost the same as the lists, with the diference that tuples are immutable, is means that you can’t enlarge or shorten a tuple, but you can update it.

Also the syntax of the tuples is different,if you want to create a tuple you have to use parentheses unlike lists.

The syntax is:

Tuple=("elem",2,3,"elem 4")

If you want to access it you can do the same as you do with the lists, you also have to use brackets to access a value of the tuple.

print( Tuple[2] )

The Tuples operators and indexing are also the same, if you want to know more about them, visit my last post called Lists or Tutorialspoint, there is a lot of information about these topics.

Thanks for reading, and again thanks to  Tutorialspoint where you can find a lot of information.


Lists

--Originally published at Hector Martinez Alcantara

In this posst we’re going to explain some things about the lists in python.

Firstly, a list is like an array of diferent or equal type of elements which can be updated, enlarged and shortened.

The syntax of a list is the next:

List= ["element 1", 2,"element3",...,n]

To access a list you have to type brackets after the list name, and between them the number of the position you want to acess.

print(List[0]); #This shows'element 1' which is the first element of List
print(List[1:3]) #This prints the elements in position 1 to position 3

To update an element of  the list you only have to assign the new value to the List’s position.

List[0]="New element"

To delete an element you have to use the function del with the position of the list that you want to delete.

del(List[4])

Then there are some operations with operators that are basic in a list like: +, *, len, in, for.

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

 

Python Expression Results Description
L[2] ‘SPAM!’ Offsets start at zero
L[-2] ‘Spam’ Negative: count from the right
L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections

Some Basic  methods

cmp(list1, list2)
Compares elements of both lists.

len(list)
Gives the total length of the list.

max(list)
Returns item from the list with max value.

min(list)
Returns item from the list with min value.

list(seq)
Converts a tuple into list.
Python also includes following list methods

list.append(obj)
Appends object obj to list

list.count(obj)
Returns count of how many

Continue reading "Lists"

This blog is FOR you

--Originally published at LunaSports

En esta ocasión veremos el ciclo for, el cual es una estructura de control en programación en la que, antes de ejecutar el programa elaborado, se indica el número de repeticiones que la instrucción realizará.

Las veces que se repiten las instrucciones se le llama iteraciones.

Ejemplo:

for

Se le pide ingresar un número, posteriormente el programa dará su respectiva tabla de multiplicación, para eso e utiliza el ciclo  for.

“i” sirve como contador, seguido de “i” se escribe un rango para saber donde será el inicio de las operaciones y hasta que número parar de realizarlas. (En este caso empieza del 0 y termina en el 12).

Para dar los resultados finales, se deben colocar en orden las cosas para poder entenderlos. (Línea 5).

for

Si quieres saber más del mundo de Python 3, no olvides revisar esta página.

fin


Reto: Yo soy 196

--Originally published at Migue´s Blog

Este reto consiste en identificar los posibles numeros Lycharel, los cuales son numeros que no se convierten en palyndromos después de sumar sus inversos, para este programa considere un posible candidato aquel numero que no se volvía palindromo después de sumar 30 veces su inverso

captura-de-pantalla-de-2016-10-27-01-03-46

captura-de-pantalla-de-2016-10-27-01-04-11

captura-de-pantalla-de-2016-10-27-01-03-29

captura-de-pantalla-de-2016-10-27-01-07-11

En esta parte se declaran las variables, a continuación se introduce el inicio y el final de la serie y por ultime se añade toda la sería una variable llamada “secuencia”

captura-de-pantalla-de-2016-10-27-01-07-34

Este ciclo for es el que se va a repetir por cada numero dentro de la secuencia para ver si es número Lycharel.

Primero se invierte el número y se guarda en la variable “y” para posteriormente sumarselo

captura-de-pantalla-de-2016-10-27-01-07-52

En esta sección se analiza si es un palindromo natural, es decir sin necesidad de sumar su inverso, el if y los elif sirven para descartar los numeros del 0 al 9, debido a que ellos podrian ser tomados como palindromos pero yo no los tome debido a que solo son de 1 cifra, si aun asi es palindromo natural y tiene más de una cifra se añade uno al contador de palindromos naturales y de numeros no Lycharel y s termina el ciclo para ese numero.

captura-de-pantalla-de-2016-10-27-01-08-13

Si no es palindromo entonces se comienza a analizar sumando su inverso.

El contador se utiliza para entrar al ciclo mientras sea menor que 31, si alcanza a 31 quiere decir que ya se sumo 30 veces su inverso y no se volvio palindromo, por lo que lo consideraremos como un posible candidato.

si en una de esas sumas se vuelve palindromo se acaba el ciclo para ese numero y se añade uno al contador de numeros no Lycharel

 

 


Reto: Revisar Palindromos

--Originally published at Migue´s Blog

Este reto fue de los más complicados, consistía en revisar un texto y mostrar cuantos palindromos contiene, hubiera sido más sencillo si solo se analizaban palabras como:

Bob=boB

Pero también se tiene que analizar toda la frase para ver en donde inicia y en donde termina cada palindromo por ejemplo en:

Anita lava la tina=anita lava la tinA

captura-de-pantalla-de-2016-10-27-00-40-32

captura-de-pantalla-de-2016-10-27-00-40-50

captura-de-pantalla-de-2016-10-27-00-41-38

captura-de-pantalla-de-2016-10-27-00-47-56

Aquí se declaran todas las variables a utilizar a lo largo del programa, son muchas para no revolverlas entre ellas, se irán explicando conforme se utilicen

captura-de-pantalla-de-2016-10-27-00-48-17

Con esta parte se preparan las letras a analizar:

  • linea 16: se introduce la frase
  • 17: se cambian a minusculas las letras
  • 18: se eliminan los elementos de la lista “eliminar”
  • 20: se añade cada elemento a la lista “letras_espacios” incluyendo los espacios
  • 22: Se separan las palabras por espacios, lo que elimina a los espacios de la lista
  • 23: Añade cada palabra separada a una lista
  • 25: separa las palabras en letras y las añade a otra lista
  • 29: Voltea las letras

captura-de-pantalla-de-2016-10-27-00-48-48

En esta sección se analizan las letras para identificar los palindromos,

Se analiza cada letra de la lista de letras que tiene el orden correcto, con la lista de letras con el orden invertido, si las letras son iguales se añade esa letra a una lista de “palindromos”, si no se agrega un espacio para separar los palindromos ya identificados y se continuan analizando las siguientes letras.

captura-de-pantalla-de-2016-10-27-00-49-02

En esta parte ya se tienen todos los palindromos identificados, pero sin espacios, por ejemplo se imprimiria “anitalavalatina”

por lo que se comparan las letras de la lista “palindromos” con la de la lista “letras_espacios”, si son iguales los elementos se añade a la lista”palindromo_final”, si no es igual y en las lista “letras_espacios” no corresponde a un espacio se le

Continue reading "Reto: Revisar Palindromos"

Reto: Cuenta Palabras

--Originally published at Migue´s Blog

Este reto es muy simple y sencillo, lo que hace es pedirle al usuario una frase, para que posteriormente el programa cuente cuantos carácteres tiene esta frase

captura-de-pantalla-de-2016-10-26-23-38-43

captura-de-pantalla-de-2016-10-26-23-38-19

captura-de-pantalla-de-2016-10-26-23-41-37

En la linea 3 se muestra en pantalla que es lo que hace este programa

Y en la linea 4 se le pide al usuario que ingrese la frase la cual se guardara en la variable “y” como una cadena

captura-de-pantalla-de-2016-10-26-23-41-53la variable “letras” es el contador, el cual va a almacenar el número de caracteres de la frase

captura-de-pantalla-de-2016-10-26-23-42-04

Este ciclo se repite 1 vez por cada caracter almaccenado en “y”, y en cada repetición se le suma 1 al contador.

Por el último se muestra en pantalla el contador

 


Recursion

--Originally published at Hector Martinez Alcantara

Let’s talk about recursion. Personally, recursion is the  most dificult thing in programming, but I’ll try to explain it by the most common recursive function, the factorial.

Let’s see the example code:

def factorial(var):
    if var>1:
       var=var*factorial(var-1)
       return var
    else:
       return 1
 
x=int(input("Type a number to calculate the factorial:\n"))
print("The factorial of "+str(x)+" is:")
print(factorial(x))

The result of this is:

Type a number to calculate the factorial:
5
The factorial of 5 is:
120

But why?

Let’s see step by step, what happens.

First of all, we call the function with one parameter.

factorial(5) #factorial of 5

The number 5 enters to the function then if the number is 1 it returns 1, and then, the interesting part, if there’s some number higher than 1 the next function will be realized

var=var* factorial(var-1)

What happen here? Let’s see step by step.

First the value is 5, it’s greater than 1, so the function will be

var= 5 * factorial(var-1)

Now we can see that the value of factorial var-1 will be the same function, so we can see that the value of var in the function will be 4 that part will be like this:

var= 5 * (4*factorial((var-1)-1)

As you can see the value of the function factorial is the same function nested in the other sentence, so I’m goin to show you how the function looks doing the same procedure.

var=5 * ( 4 * ( 3 * ( 2 * (factorial ((((var-1)-1)-1)-1) ) ) ) )
#Remember the var==5
#((((var-1)-1)-1)-1) is like ((((5-1)-1)-1)-1) == 1

So…

var=5 * ( 4 * ( 3 * ( 2 * (factorial(1) ) ) )

What happens with factorial of 1? Remember that we typed that if the variable of the function is 1 or less, then the function will return

Continue reading "Recursion"

While loop

--Originally published at Hector Martinez Alcantara

This post is about the other loop, the while loop, it’s often used to do an action until a variable changes it’s value.

Here’s the sintaxis of the while loop

while condition:
      statements

And here’s an example of this:

#Introducing 5 lines of text
list=[]
x=1
while x<6:
      list.append(input("type some words"))
      x=x+1
print(list)

An example of while used as a returning menu:

op=""
while op!= "c":
      print("a)Print Hello")
      print("b)Print something")
      print("c)Exit")
      op=input("Select an option\n")
      op=op.lower()
      if(op=="a"):
           print("Hello")
      elif(op=="b"):
           print("Something")
      elif(op=="c"):
           print("Goodbye")
      else:
           print("Thats not a letter of the menu")

The result is

a)Print Hello
b)Print something
c)Exit
Select an option
>>a
Hello
a)Print Hello
b)Print something
c)Exit
Select an option
>>b
Something
a)Print Hello
b)Print something
c)Exit
Select an option
>>z
Thats not a letter of the menu
a)Print Hello
b)Print something
c)Exit
Select an option
>>c
Goodbye

Thanks for reading, ask me in comments.

Special thanks to Python while loop from Tutorialspoint


For loop

--Originally published at Hector Martinez Alcantara

Hi, I’m writing this post about the control flow tool called for loop. It’s used to repeat an action many times, but not only that, you can make a loop with specific conditions, and use it as a ‘foreach’ in C.

Another tool that we’re going to use is the range funtion that returns a list of a range of numbers.

I’m going to explain how the different uses of this for loop works.

First the sintaxis of the range tool:

range('initial number','last number range','conditional number')

Examples of use of range function:

#It can be used only as a quantity of numbers
range(5)
#The result is a list of numbers between 0 and 5 = [0,1,2,3,4]

#Used as a range of numbers
range(4,14)
#The result is a list of the range of numbers between 4 and 14 = [4,5,6,7,8,9,10,11,12,13]

#Used as a range of numbers with a jump condition
range(0,100,10)
#The result is a list of the range between 0 and 100 every 10 numbers = [0,10,20,30,40,50,60,70,80,90]

Now the sintaxis of the for tool:

for 'variable' in 'list' :
     #conditions

Examples of for loop function:

#Doing a quantity of actions
for number in range(8):
    print("Hello")
#The result is a print of the word 'Hello' 8 times

#Using a range of numbers
for number in range(10,20):
    print(number)
#The result is a print of numbers from 10 to 19

#Using a range of numbers with a special jump condition
for number in range(0,10,2):
    print(number)
#The result is the pair numbers from 0 to 8

#Using a variable
word="Hello"
for letter in word:
    print(letter)
#The result is a print of every letter in the word 'Hello' = ['H','e','l','l','o']

The explanation is that the for function takes every component in a list of components and use the component as the variable, for each component, the actions

Continue reading "For loop"