## Quiz 11

• Question1:

• Question2:

Check for a string in a file

## ECOS

This is a screenshot of my finished ECOS, yes it seems that they bugged.

## Quiz 10

I have uploaded the source files for my to programs of my Quiz 10:

For this program I used something that isn’t very usual, the % operator. This is used to return the modulus of a division, this means the number at the left of the operator is divided by the number at the right, and the result is the residue of the first division of them. This way you can know if a number is evenly divisible by another. Whenever a number is evenly divisible it module returns 0.

So I check the module and if it is cero we add the number to the total that is afterward printed in the console.

The next program first verifies that the lengths of the lists provided are equal, if they are not there’s no calculation to compute so we only print out the error message and return a -1. If they are we take the element of the same index of both lists, calculate the product of them and then add it to the total, which is later on returned by the function.

This is 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.

The correct usage of rescursion is very important when programming. The usage of functions is other way to simplify some very complex programs. Many times when you see that your main is a giant block of code you should try and see that much of it can be redefined using functions, where much of those lines can become just some function calls.

This is for my  of my

## Reading and writing files in Python

Reading and writting files is very important so that we can manipulate data and keep it even after our program has ceased to live. In order to understand both task I made a Python3 program that reads a .txt file and copies its content to other one.

Mi program is available in Github. You can also find the text files that I used to test the program.

The program is the following:

`C = open("Original.txt","r")`

`V = open("Test.txt","w")`

`for line in C:`

`    print(line,end="")`

`    V.write(line)`

`C.close()`

`V.close()`

What the program does is very simple, first we open/create our files. This is done usign the function open(), where our first argument should be the name of the file, and the second one is the mode in which we are going to open it. In this case “r” stands for reading, and “w” for writing.

I found in the Python3 Documentation that the best way to read a files lines is by usign the for loop of the lines in the file. This helps us to do it in a very efficient and clean way.

In this case every line is printed in the console that you may compare what has been writen in the new file and what has been read.

Then we write each line that we read in the new file.

And as for any file writting and reading operation we close our files.

For the file reading and writing the official documentation has the other functions that you can perform, like usign f.seek() to perform searches , or how to acces a certain part of the file.

This is my of my

## Creating and Using Dictionaries in Python

Another one of the Python types are dictionaries. They are bascially an unordered list of key-value related elements, this means that you have an element in the key group and you assign an arbitrary object as its definition.

They work much like language dictionaries, where for each word, or key, you have a definition for that word, or the value; so whenever you ask for a certain key, you get its corresponding value in return.

Dictionaries can be modified by adding values or by redefining the value for a given key. Lets see this whith examples.

`>>>dict={}`

Dictionaries are created using {}, and you have to define key : value pairs, separated by a coma.

`>>>dict{"Name":"Manuel","Career":"IMT"}`

`>>>dict`

{‘Name’: ‘Manuel’, ‘Career’: ‘IMT’}

To add a new pair to the dictionary you just declare it, using the key as the index and the value

`>>>dict["UNI"]="ITESM"`

`>>>dict`

{‘UNI’: ‘ITESM’, ‘Name’: ‘Manuel’, ‘Career’: ‘IMT’}

When you type a value that has the same key, the old value is overwritten so you can only have one value for any key.

`>>>dict["Name"]="Ken"`

{‘UNI’: ‘ITESM’, ‘Name’: ‘Ken’, ‘Career’: ‘IMT’}

If you want to implement Dictionaries in a boolean context, whenever a dicotionary has at least one element, it will return True, if it doesn’t have any element it returns False.

Python Variables Types

Native Datatypes

This is my of my

## Creating and Using Strings in Python

String in Python3 can be created using both pairs of singles and double quotes. They are concatenations or secuences of characters, they can be numbers, letters or special characters as long as they are inside the quotes.

String can be sliced, this means that you can get substrings from a string using the two slice operators:

• String[i] This returns the character that is in the position given by i. Remember that strings start at 0.
• String[i:j] This returns the section of characters between the given range from i to j, whitout including the upper limit.

Strings can also be used to perform two opperations:

• + : this operator is the String concatenation, this means it is used to “attach” the begining of the string at the end of another string. You can make the analogy to the algebraic sum, where the result will be the adition of both components.
• *: this is the repetition operator; this allow us to repeat the String many times as desired, just like the algebraic multiplicaction, that adds, or in our case concatenates, a certain number of the original String copies.

For example:

`>>>str = "Hello World!"  `

`>>>print (str)`

Hello World!

`>>>print (str[0])`

H

`>>> print (str[2:5])`

llo

`>>>print (str[-1])`

!

`>>>Print (str[::-1])`

!dlroW olleH

`>>> Print(str+"!!")`

Hello World!!!

`>>>Print(str*2)`

Hello World!Hello World!

As you can see String can be seen as lists in some ways. For example the [-1] index points to the last element of the array.

As you can see the [::-1] gives you the reversed string, but why? Well as I had said if you check lists in Python you will see that its called slicing, and what we are typing is that you will slice the string with a -1 step, this means from the last to the start.

This is my of my

## Creating and using Ranges in Python

One of the Built-in Functions of Python3 is the range() function. This is a very usefull function that allow us to create in a very easy way lists of numbers. As you may recall we had used it in for loops. There are two ways to use this function:

• range( number ): This way what you are telling Python to do is to give you a list that begins in 0 and has “number” elements. So if you type in your Python editor:

`>>>for i in range(4):`

`...    print(i)`

0

1

2

3

The list begins at cero and has four elements.

• range(start, stop, step ): This way we can be a little more especific about the list that will be created. The first argument is the number at which the list will start, the second is the number where the list should stop not including, and the thrid one is the step that will be between each element of the list.

`>>>for i in range(1,7,1):`

`...     print(i)`

1

2

3

4

5

6

`>>> for i in range (0,-10,-2):`

`...    print(i)`

0

-2

-4

-6

-8

As you can see the second way is very helpfull when we have very specific lists. I found this page that explained the range function and I think it’s worth your while.

This is my of my

## Quiz09

I have made a new repository in Github, where you can find my Quiz09 program files.

This is my of my .

## Creating and Using Python Modules

This post is very useful. As we can see many times we face different problems that need a solution of the ones before, or to use it as a step to solve a bigger problem. The point is that defining functions is not the only way to reuse code.

Python has the advantage of saving our previous files and use them as a module, like the one we import to use some math functions. So in order to use some previously defined functions we create a Python file and import it in another to make use of its content!

I will use two of our previous programs to help me prove this. In order to calculate the standard deviation we had to use the factorial of a number. So instead of going to our old factorial code we could have just imported it and made use of it!