WSQ 9

--Originally published at Python

“So for this assignment I would like to see you create a function that receives as parameter the name of a file (this would be a string value like data.txt) and your function counts the number of lines and the number of characters in the file which it returns as a single value (but with two values). You will want to look at how to use and return a tuple from a function and how to open and read text files line by line.”

En este programa, estableci 2 funciones: una para leer los caracteres en un texto (readi) y otra para leer lineas (readline1). Y para cada una asigne una funicon de python llamada “open()” la cual, aparentemente, busca en toda la computadora, puesto que no le asignas una carpeta especifica,  y abre el archivo, va seguida de funciones “r” para leer “e”para editar, etc. por ejemplo: open(“texto”, “r”). lo que hara es leer el archivo “texto” y lo leerá. Despues simplemente le asigne una variable contadora para los caracteres y otro para las lineas, despues solo imprimir las respectivas funciones y listo.


QuizWeek#11

Practice Exam

Download and attempt to solve the problems in the attached exam file.

The real exam next week will be shorter but drawn from these questions.

I would expect everyone to be able to do all except #8 and #9 now but I know there are some of you that could do those now.

Featured Image Credit

<a title="2016/366/26 Pair Programming" href="https://flickr.com/photos/ken_bauer/24271690249">2016/366/26 Pair Programming</a> flickr photo by <a href="https://flickr.com/people/ken_bauer">kenbauer</a> shared under a <a href="https://creativecommons.org/licenses/by-sa/2.0/">Creative Commons (BY-SA) license</a> </small>
2016/366/26 Pair Programming flickr photo by kenbauer shared under a Creative Commons (BY-SA) license

 

Lists – WQS07

--Originally published at Programming

The instructions of this excersise are: “Create a program that asks the user for 10 numbers  (floating point). Store those numbers in a list. Show to the user the total, average and standard deviation of those numbers.”

Well, first of all, I learn about the standard deviation here: Standar Deviation. That was the way I could generate the function you will see in my code.

Maybe the most difficult part of this was just the standard deviation, but is not to much after you understand how it works.

Here is the code:

Captura de pantalla 2017-03-20 a la(s) 09.23.05

Ok, let’s explain. We import math because we need square root in the last step of the standard deviation. Then we made a function to perform standard deviation too. I will not stop to much in this step, because all is just the steps you can look for  in the link I gave you up here.

The main part of this excersise if to know lists. So, as you see we ask the user for ten numbers, that is what we save in the thing that we will call list.

If you want to know and understand more about it, clic here.

Well, after saving in a list we can work all the values like a package. So, then we just perfom the math operations and finally we print them.

That’s it, and this is how it runs:

Captura de pantalla 2017-03-20 a la(s) 09.23.45

Hope it helps 🙂


Factorial Calculator – WSQ06

--Originally published at Programming

Hello! Today we are doing a factorial calculator. This is about calculate the factorial of a number, asking the user for a non-negative integer. If you don’t know is the factorial or you want to refresh, you can know about it in Wikipedia-Factorial.

Well, as usual, here is the code: (and then I will explain)

Captura de pantalla 2017-03-20 a la(s) 08.26.41

First we print an introduction phrase for the user. The objetive of this exercise is to use loops. To start the loop our coindition needs to be true, thats why we declared repeat as “yes” and the we start the loop.

Inside this loop, we ask for the number like an int. Then we inicialize the counter like one and the fact too, fact is the number that will be multipliying and incrementing. For that happens we made another loop. The condition as we see is that the counter is different than the number (that the user give us) plus one. This way then we see that fact will be multiplicating the counter and after that it will increase one.

After this math operations we print the result with a sentence to advise, and finally we ask the user if he want to repeat the cycle.

If yes, all start again. If no, we just print Thanks.

And that’s it. This is how it runs:

Captura de pantalla 2017-03-20 a la(s) 08.27.14

Hope it helps 🙂


Dictionaries and 46 exercises: 20-22

--Originally published at Python learning

In Python we can create dictionaries that store values, like what we do with lists, except that instead of using an index to refer to something in it, we use other values called keys.

An example of a dictionary looks like this:

translate = {“hello”:”hola”,”my”:”mi”,”name”:”nombre”,”is”:”es”}

In this case, hello, my, name, and is are called keys, and each key has a corresponding value: hola, mi, nombre, and es.

I read about this topic in the book How to Think Like a Computer Scientist: Learning with Python by Allen Downey, Jeffrey Elkner, and Chris Meyers, which I had mentioned before in this post. You can check it out here.

I used dictionaries to solve the exercises 20-22 of the 46 showed in the past posts.

In number 20 I had to create a program that would take a list of English words and return a list of those words in Swedish, like this:

20

The get() method I used in the loop has two parameters: the first one is the key of the dictionary, the second one is the value to return if said key is not found.

20run

Number 21 was about determining the frequency in which each character of a string is used:

2121run

And 22 was to create an encoder & decoder of ROT-13 that would be able to decipher the following message:

Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!

2222run


46 exercises: 16-19

--Originally published at Python learning

Here’s another blog of four more of the 46 exercises I have been working with 💻

In number sixteen the task was to write a program that would take an integer and a list of words, and return a list of the words that their length is longer than the integer:

1616run

The next one was similar to problem eight, in which the program recognized palindromes, only this time it had to work with sentences as well, like “Go hang a salami I’m a lasagna hog.”, “Was it a rat I saw?”, “Step on no pets”, “Sit on a potato pan, Otis”, “Lisa Bonet ate no basil”, “Satan, oscillate my metallic sonatas”, “I roamed under it as a tired nude Maori”, “Rise to vote sir”, or the exclamation “Dammit, I’m mad!”.

17

As you can see, I used the function string.punctuation in the string module to eliminate all punctuation from the sentence, as suggested from a friend of mine in the class. For this, I also used the replace() method to change it for an empty space (“”), as well as to eliminate spaces between words.

17run

Number nineteen was about creating a program that would tell whether a phrase was a panagram or not:

18

In match = set(alphabet) & set(letters) the program is comparing the two lists and finding elements in common, which it then puts into a list. I read about that in this page:

http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches

And this is how it runs:

18run

And the following exercise asked to write a program that generated all the verses in the popular song “99 bottles of beer” :

1919run119run2

I’ll continue showing more of these exercises in future posts 🙂


WSQ05

--Originally published at Site Title

ON TO FUNCTIONS

What to Do:

You will go back and do WSQ01 – Fun with Numbers again.

But this time, write a function for each calculation. Each function should define two parameters (in this example of type int) and return the correct value as an integer as well.

You main program needs to ask the user for the input and then call each function to calculate the answer for each of the parts.

 

Qué hacer:

Volverá a hacer WSQ01 – Diversión con números de nuevo.

Pero esta vez, escriba una función para cada cálculo. Cada función debe definir dos parámetros (en este ejemplo de tipo int) y devolver el valor correcto como un entero también.

El programa principal debe preguntar al usuario por la entrada y luego llamar a cada función para calcular la respuesta para cada una de las partes.

 

Code/Código:

 

5code

 

 

Python:

 

5py