Author Archives: Manuel Lepe

When to use what kind of repetition in a program

We have seen many way to make a loop, and one may wonder how con you know which one should be implemented?

This question is not that hard to answer:

  • While:

The while loop is implemented when we don’t know how many times a loop will be excecucted. For example when we want to do a cycle until we find something or we espect to find a certain value. For example:

>>> while(n>=0):

               n-1

In this case we don’t know what value will be given to n, so we use a while, so that whatever value it may take the cycle runs until it gets to cero. (Assuming n is not negative)

  • For:

The for loop is used in cases where we now exactly how many times we want the cycle to repeat itself, everytome in a cycle for we tell it how many times we want it to execute itself.

For example: when we want to print every value inside a list we use a for loop, wich we use as the index, another application of the for loop; when we want a variable that is increasing or decresing each time a cycle runs a for loop might solve our problem. To print the list we code something like this:

>>>for i in list:

      print(list[i])

Which means that i will take the values that cover the number of elements inside the list, and when we print we acces the element of the index i, wich will eventually sweep the hole list printing every element in order. 

This is my of my

Python Basic Types

I found this page very usefull and complete about the types that are most used in Python, so feel free to check it if you still have doubts about the types in Python 3.

Boolean

The first of the types are the boolean. This types are used to evaluate simple true or false statements for control loops. They can take two different values True or False, and almost all the times are result of a logic operation like a comparison between two values.

Numbers

Numbers are divided in two basic types:

  • Integers: They are the set of the Integer numbers (Z). They can be of any size, thus long type doesn’t exist any more. They are used for cycles, for example in a for cycle we don’t use floating point numbers, we can’t execute half a cycle or a cycle and a third. 
  • Float: They complete the set of the Real numbers, so we have floating point numbers, with up to 15 decimals of precision.

There are ways to convert an int into a float, most of the time is just by adding a cast. For example:

>>>int(2.5)

2

Another important operator is the floor division //, wich gives us the integer result of a division , instead of giving the floating point.

Strings

Strings are the way Python manages text, they are sequences of Unicode text, and they are asigned by using “”; they are much like arrays of characters, so they share some functions.

Lists

Lists are very usefull ways of saving sets of different types. Lists can contain any number of elements and they can be texts or numbers. They can be modified by many means. And normally they are used to store data and then use it againg. 

For loops are used to go trough the elements inside a list. And there are many ways to add elements or to rearange them. The way to create them is to use the name of the list and then typing all the elements in it inside brackets […].

Tupples

Tupples are much like lists, but they are created by encasing the elements in parenthesis instead of brackets (…). And have the peculiarity that they cannot be modified once created, they are much like read-only lists.

What are they goof for then? Well since they are write protected, you can use a set of data that must never be modified even by mistake. They also tend to be faster when they are processed by the computer. And they are able to be used as dictionary keys, wich we don’t want to get modified. 

Dictionary

A Dictionary in Python can be imagined as a bidimensional array, in wich every value in a column has a value in the next column. Much like actual language dictionary, in a dictionary you have a key word and you have a meaning for that, so it is in Python’s Dictionary, you have keys and you have a meaning assosiated to it.

In order to create them we use keys and we use colon to stablish the key-meaning realtionship:

{ key : meaning, other key : next meaning}

This is for my of my .

Square Root (Babylonian Method)

In this case we can see an example of recursiveness in a program. As always the source code is in GitHub.

The square root Babylonian method consists in doing a series of sums and divisions in order to calculate the value of the square root of a number. It is approximated by solving an equation that you can check in the page link pasted before.

This program is written so that it asks the user for the number, the number that he wants to use as a first guess and the number of runs or iterations it want to use to calculate the value. Any way the program should stop if the value of the next iteration is the same as the one before. 

After each iteration the number of the run and the estimated value ar displayed to show the user the different values calculated. 

This is my of my

Greatest Common Divisor

Source code of the program in GitHub.

This program basically asks the user for two numbers, and after that it calls for the function gcd to calculate the greatest common divisor of both numbers. 

The Greatest Common Divisor can be obtained very easly by contemplating three different escenarios, two of those are almost the same and are when one of the values is greater than the other, and the other is when the two are the same.

The goal of the function is to achieve that both numbers are the same so that the gcd is the same number. So we achieve this by using a simple if control form. Whenever a number is greater than the other we substract the smaller number from it and repeat the process until we have the same number.

This program is quite simple and you can try it so you better understand it.

This is my of my .

YoSoy196

The source code is in GitHub.

This program asks the user for the two boundaries of a range and then the program starts calculating for each value if it’s a palyndrome. 

For this the function check_palyndrome( ) is created. The function first saves the orignial number in form of a string. Once we have an String it’s very easy to reverse it. 

If you have a String you can treat it as a list, so if you want to reorder it you can use the [::-1], notation after it. What it does is position itself in the last index, and start decrementing it, thus writting the string backwards. This is also saved in a different variable. 

If the String and it’s reverse are the same, the function returns the value 0; wich in the main program is interpretated as adding 1 to the natural palyndromes count.

If they are not the same, then we take the reversed String and parse it into an int, and then add it to the original number. And update the palyndrome that we whant to check as the result of this sum. Then the process is repeated. If the String and it’s reverse are the same before the 30th try, the function returns a 1; which is the indicator for adding one to the non-Lychrels numbers.

If after the 30th try the String and its reverse are not the same, then we categorize it as a Lychrel’s number. So the function prints the message: “Found a Lychrel number: “with the number before returning a 2 that increments the Lychrels numbers count. 

The [::-1] notation is better explained here, as extended slice notation.

This is my of my .

Lists in Python 3

One of the most useful types in Python are the Lists. They consists in arrays of different types of information ordered, they can be manipulated and accesed in many ways. 

The source code of the program is in GitHub.

The program is about a list of 10 floating point numbers, called list1 , which will be typed in by the user. Once the user has typed the values then we will start some calculations that are defined in the functions in the Function Declaration section of the code. 

The first one takes the value of the total, originally 0.0, and then adds every single element of the list. Thus giving us the total of the numbers inside the list1. 

The second function is to calculate the average of the elements inside the list1. For this we simply use the total that we have already calculated, and divide it by the total of elements in the list1. For this we use the function len(), which applied to a list returns the number of elements contained in that list. 

The third function is the standard deviation of the list. This one is a little bit trickier. In order to calculate this another list is created, listd, which is the difference between each of the values inside list1 and the average that we have previously calculated. Once we have calculated this we need to calculate the square of the differences, and start adding them to a total variable. Once we have the total we can calculate the average of the square differences, so we divide it by the number of elements in the list.

After all those calculations we just use the math module to calculate the square root of the total.

The main topic of this post is to see how you can use a list with a for loop to read every value. Instead of using a range(), you can use a list so the for loop goes thru every single one of its values.

If the standard deviation calculation process wasn’t very clear,  here you can find a usefull page to understand it.

This is for my of my

Use of Recursion for Repetitive Algorithms

In some cases we may see that in order to compute a given problem we need to do the same procedure several times, which may turn our source code into a nightmare, making it very very long and very easy to get lost into. So for this cases the use of recursion is very important. 

Recursion is a way of programming in wich you use the same function in a function. Yeah, that’s right you can actually make a function call inside itself. The most common example of recursion is the factorial fuction. The factorial function has a definition that is recursive itself. When you want to compute the factorial of a number you can actually define it as the number times the factorial of the number before it. 

Let’s make the example a little easier to understand:

def factorial(n):

      if n == 1: 

            return 1

      else:

           return n * factorial(n-1)

In this case we can see that the factorial function has a factorial function inside it. This helps us recalculate the factorial many many times, until the n takes the value of 1 which is the smallest factorial. So if we want the factorial of 4, we will calculate the factorial of 3, 2 and 1 to help us calculate it.

Recursion is very important to help us simplify problems and give a more cleaner estructurated solution, instead of having chunks and chunks of code for solving the same problem for different scenarios.

This is for my

Factorial of a number (for loops)

In this case I have uploaded the code to Github here.

What this program does is ask the user for an integer, and then we do what we call sanitizing the entry, or handling exceptions.

The factorial of a number is the result of multiplying the integer numbers before it until we reach 1. This algorithm can’t be done to a negative number, and the factorial of 0 is 1. 

The way that we handled the exception is to be prepared to recieve an input that would make the program fail, so that when it happens our program knows what to do and not only crashes. In this case an if is implemented so that it verifies the given input. If the number is negative, then the program ignores it value and it takes the negative part from it and calculates the factorial of the given number.

After we have prepared for the human error, we now calculate the factorial of the number. For this we implemented a for loop. This loops are used when we know that we must apply a task a certain number of times, or when we want a variable that keeps track of the numberof times a section of code has executed. 

Basically the for loops needs a varaible that we use as counter, and we help ourselves with the range() function. This function returns the value of a series of succesive numbers between the given values, without including the upper limit.

range(0,10) gives us a list of numbers like this:

0 1 2 3 4 5 6 7 8 9

This is used to specify the values that our control variable will take inside the for loop.

This is for my of my

First Satuts Update

First Satuts Update