Inception

inception

Use of recursion for repetitive algorithms.

Sometimes we will be in the need to repeat a cerain procedure several times but if we write the same line of code multiple times it will make pur code hard to read and it can get confusing. But for that we have a solution: Recursion

lmzz52m_700wa_0

Recursion is a method in which we call the same function inside a function. Yes it is possible. We can see some common examples like when we are looking for the max common divisor with the Euclides method. It will be something like this:

rw9zy9m_700wa_0

def obtener_mcd(a, b):
if(b==0):
return a
else:
return obtener_mcd(b, a % b)

wwlnamr_700wa_0

Or when we want to obtain a factorial:

def factorial(n):

if n==1:

return 1

else:

return n*factorial(n-1)

In both we can see the function inside the function. We just change the values in the parameters with the ones we obtain with the first iteration.

1d43qdr_700wa_0

It is very important to know how to use recursion to have better looking codes and efficient ones.

This is an excelent video to help you understand if you don’t get quite well how can a method call itself and what does it actually happens when it does.

Keep up with the code!

Follow me on twitter: @danigguemez

Check out more info in this sites:

http://www.aprenderaprogramar.com/foros/index.php?topic=1161.0

Use of Recursion for Repetitive Algorithms

 

Introducing C#

Hola amigos, esto es algo nuevo en este blog. En primer lugar lo estoy haciendo en español y en segundo lugar, no es acerca de python sino de otro lenguaje de programación increible: C#

ymkparr_700wa_0

Empecé a aprender C# porque estoy interesada en la creación de videojuegos y un programa de desarollo de videojuegos (Unity) esta basado en este lenguaje de programación, tambien loqueze aprender porque nunca esta de mas saber usar diferentes lenguajes de programación.

No sabía donde empezar así que hice lo de siempre: busqué en youtube, y encontré algo increible.

brk4gd2_700wa_0

Hay una serie de videos tutoriales hechos por un español que empieza desde lompas básico y explica muy bien todo lo que necesitas saber de C# básico, también tien videos de programación orientada a objetos pero no me he metido a profundidad en ese tema.

 

Ademas de tener los videos de youtube, también tine un foro donde deja ejercicios de práctica y si tienes problemas para resolver alguno puedes buscar en un foro donde la gente publica sus preguntas o soluciones a las tareas.

4wbvz4w_700wa_0

Creo que el curso está muy completo y se los recomiendo mucho si quieren aprender otro lenguaje de pregramación.

Link del foro: https://foroinsider.com/

Si estas en windows descarga visual studio aquí: https://www.visualstudio.com/es/downloads/

Si no estas usando windows… no tengo idea de que software puedes usar para programar C#, buscalo en google.

#TC101 #C#

Babylonian method

mdgvx7r_700wa_0

This is another task from Ken’s previos courses that I had trouble with because I didn´t understand quite well the babilonian method so in order to fully understand what the program is doing watch this video first:

 

So here is what the task was asking for:

WSQ13 – Babylonian Method

In this assignment you will write a function to calculate the square root of a number using the Babylonian method. You can search for that method, it will be easy to find.

What to Do

The function should receive a number and return floating point number. Obviously you should test your function, so create a main program that asks the user a value, calculates the square root and displays that.

omj2y5m_700wa_0

So here is a short solution:

babylonian1

We ask for the integer from the user, the first guess we make is just half the number because it doesn’t really matter how of our first guess is because the cobe will continue until th diference between the two guesses are lower than the error. The second guess is done with the method’s formula. If the error is higher than the value error the guess2 is reasigned and a new guess2 is made.

This is the output:

babylonian2

And with that error it is pretty accurate:

babylonian3

Cool right? Now you don’t need a calculator to get the square root fo a number, do it like the babylonians did it.

9d6xzjm_700wa_0

Follow me on twitter @danigguemez

Code avaliable on github: https://github.com/Guemez/TC1014/blob/master/babylonian.py

Sources: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots

#TC101 #python #BabylonianMethod #KenCoursesChallenge

Yo soy 196

Long time ago I tweeted that I was going to do all the proyects from a previous Ken’s course but it’s been a long time and I haven’t  posted a single solution.

0mabexr_700wa_0+

It’s not that I haven’t done them, is just that I didn’t know which one to post, so I chose the lychrell number challenge because I thought it was really interesting, I didn´t even knew that kind of numbers had a name!

So here is what the challenge said:

WSQ11 – Yo Soy 196

Lychrel numbers are natural numbers that do not form a palindrome after successive additions to their inverse. See details on Wikipedia:http://en.wikipedia.org/wiki/Lychrel_number

What to Do

Your jobs is to create a program that asks the user for two pieces of data:

  • The lower bound of the sequence
  • The upper bound of the sequence
Then you check the values from the lower bound (inclusive) to the upper bound (inclusive) and make a report of them. During the analysis of each number, if a Lychrel number is found it should be reported immediately with something like “Found a Lychrel number: 196”

Details

The report must show:
  • The range of numbers analysed (lower to upper bound)
  • The number of natural palindromes (no addition to inverse needed)
  • The number of non-Lycherels encountered (become palindromes)
  • The number of Lycherel number candidates (that did not converge to palindrome)

Since you will not be able to prove that a number is Lycherel (since you cannot computer forever to check), our definition for a Lycherel candidate will be if a number does not converge after 30 iterations of applying the addition to the inverse.

Here is my solution:

yosoy1

yosoy2

We begin validating the user’s input as always with try and except inside a loop.

We create a function that reverses the number in order for us to compare it to the original number.

The for willdo one of three:

Indicate that it is a natural palindrome if without any cycle repetition it is a palindrome.

If the number after 30 or less loops becomes a palindrome, and

If the number, after 30+ loops is still not a palindrome.

The output is the amount of natural palindromes, the number of non-lychrell numbers and print the lichrel numbers, like this:

yosoy3

It was pretty fun to make. If you have trouble understanding what the program is supposed to do (like me) check out Ken’s video:

Thanks guys!

Follow me on twitter @danigguemez

Code on Github: https://github.com/Guemez/TC1014/blob/master/yo_soy_196.py

Sources: http://kenscourses.com/tc101winter2015/course-home-page-for-tc1014/wsqs-tc1014/wsq11-yo-soy-196/

#TC101 #python #KenCoursesChallenge #yosoy196

Files in Python

In the blog about counting words, I used the funtion open() to coun the words in that file but I haven’t made a post explaining how to do that, so here it is:

In Python, you don’t need to import any library to read and write files.

The first step is to get a file object.

The way to do this is to use the open function.

A file is usually categorized as either text or binary.

vmveq3w_700wa_0

A text file is often structured as a sequence of lines and a line is a sequence

of characters.

The line is terminated by a EOL (End Of Line) character.

The backslash character indicates that the next character will be treated as a

newline.

A binary file is basically any file that is not a text file. Binary files can

only be processed by application that know about the file’s structure.

To open a file for writing use the built-i open() function. open() returns a

file object, and is most commonly used with two arguments.

 

The syntax is:

file_object = open(filename, mode) where file_object is the variable to put the

file object.

 

The second argument describes the way in which the file will be used

The mode argument is optional; ‘r’ will be assumed if it’s omitted.

lmzjvmm_700w_0

The modes can be:

‘r’ when the file will only be read

‘w’ for only writing (an existing file with the same name will be erased)

‘a’ opens the file for appending; any data written to the file is automatically

added to the end.

‘r+’ opens the file for both reading and writing.

ymkd7rq_700wa_0

Create a text file

Let’s first create a new text file. You can name it anything you like,

in this example we will name it “newfile.txt”.

file = open(“newfile.txt”, “w”)

file.write(“hello world in the new file

“)

file.write(“and another line

“)

file.close()

How to read a text file

To read a file, we can use different methods.

file.read( )

If you want to return a string containing all characters in the file, you can

use file.read().

file = open(‘newfile.txt’, ‘r’)

print file.read()

Output:

hello world in the new file

and another line

A video that explains it:

Thanks for reading.

Follow me on twitter: @danigguemez

#TC101 #python #files

Sources:http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

https://www.sololearn.com/User/Login/?ReturnUrl=%2fPlay%2fPython

 

Bubble sort

Just like the previous challenge, this time we had to put a list in order but instead of using random we use the bubble sort method (thanks God!).

rw9ykew_700wa_0

It is so much better and efficient, in contrast with random, also it is less code so if you want to do it the better way….. don’t use any of this, there is a built in function in python that does it for you hehe

krqrjmd_700wa_0

Don’t go! it’s still usefull to know this way of sorting. Here it is:

bubble1

The same as the random code except that instead of sorting asigning random index we use the function bubble(). This function, while the list is not sorted, compares each pair of numbers that are side by side in the list and if the first one is greater than the second one it swiches the position of those numbers.

xw7v9db_700w_0

The rest is just printing the list an the amount of times the while repeated. Hava a look to the results to compare the difference between this and random sorting:

bubble2

And with 10 numbers:

bubble3

Big difference.

Here is a video to help you out:

Follow me on twitter @danigguemez

Code avaliable in Github: https://github.com/Guemez/TC1014/blob/master/bubblesort.py

#TC101 #python #bubblesort #DailyChallenge

The ultimate efficience

RAMDOM, the worst way to sort a list of numbers.

pdwbyrk_700w_0

Well, I had to sort a list of n numbers for the challenge, thanks Ken!

And, what is the problem?

nwrlojr_700wa_0

Yes, there is a huge problem: it’s really inefficient.

krp0arl_700wa_0

But well, the point of the challenge was for us to realice this. So this is what I did:

sorted1

First things first. We import the main character here: random. After that we have the function that checks if the list is sorted and returns the boolean value True if the list is in order or False if the list is not in order, we are sorting the list high to low.

odgoegd_700wa_0

The user is asked how many numbers does he/she wants to sort and then proceeds to ask the user for those numbers which are stored in a list using the for.

3dbolpw_700wa_0

We rearrange the list giving random indexes to the numbers and creating a new list. Then we run the function is_sorted() again and again until it returns the value True (when the list is in order).

We print the list in order and the amount of times it took random to get it right. Here is an example:

sort2

sort3

As you can see it took 138 tries to sort only 5 numbers!

What you learn with this is to not use random to get things in order…

Here you have the worst of the worst… sort 10 numbers:

1rxbzwp_700wa_0

Keep up with the code:

Follow me on twitter @danigguemez

Get the code in github: https://github.com/Guemez/TC1014/blob/master/sortednumbers.py

#TC101 #Python #DailyChallenge #Random #3milliontries

Why the word palindrome is not a palindrome?

Shouldn’t the word that defines a text that is read the same way backwars or normally be a word with this properties?

pm0aarl_700wa_0

Hello world! Here we come with another daily challenge for TC101.

The challenge was to check if the users input was a palindrome or if there was a palindrome contained in the sentence.

omjmg5w_700wa_0

palindromo1

We have the same function filtrar as in the count words program (now that I think about it I should have just imported the function…)

Inside the code we have something siimilar to whats inside the function filtrar but we use a different list of not acceptable characters that include the ” ” for us to check if the whole sentence is a palindrome, not just single letters.

1d4bjdm_700wa_0

Here are some outputs having the whole sentence be a palindrome or just a word:

palindromes2

palindromes3

Thanks, remember to follow me on twitter @danigguemez

The code is avaliable on github: https://github.com/Guemez/TC1014/blob/master/palindromes.py

If you need help here is a video:

#Tc101 #python #DailyChallenge #palindromes

Evolution of counting letters

Hello guys, yesterday I posted a program that counted the letters that appeared in a text. Today we will make something similar but instead of counting letters we will be counting words.

3m28eld_700wa_0

I will show you diferent ways of doing this, first using a build in function and then creating our own function.

word1

Here is the simplest way of doing it. We have a string stored in a variable (with split() we make the string into a list) and with the function counter() that does exactly what we want, we print the result. It looks like this:

word2

Ok now a little more complicated (we should not do complicated stuff, this is just for learning purposes)

word3

In this one we check if the word in the list (that is formed with spit()) is in a list, if it is not, the word is added and in thesame position in other list it is added a value 1 to the amount of times it repeats. If the word is already on the list we recover the index of that word and on the same position we add +1 to the list with numbers. Finally we print the word followed by it’s frecuency:

word4

pm0zodl_700wa_0

Now  we build our own function

The first funtion filtrar erases all the invalid characters so the only thing left are lower case words.word5The function count_words() does the same as what we previously explained with the lists but instead of using 2 lists, it adds the word to a dictionary with the value of the amount of times it repeats itself, pretty easy right?

We proceed to ask the user for an input or to open a text file, when opening the text file we type ‘r’ for it to be in read mode (not modified), we change the file to lower case (without modifying the original file), we filter it and then use our count_words function. This is the output:

word6

ymkparr_700wa_0

That’s all for this post. Take care and enjoy this video:

Follow me on twitter @danigguemez

The code is avaliable in github: https://github.com/Guemez/TC1014/blob/master/countwords.py

#TC101 #python #DailyChallenge #files

Count letters

This was a challenge by Ken from long ago (sorry for posting too late) but it’s bettter later than never.

1d4bjdm_700wa_0

This was a simple program: we asked the user for an imput and the program counted the times that each letter appeared in the text.

The solution is quite simple as you can see

count letters.PNG

3m2apw2_700wa_0

First we create a list with all the letters (or only with the eltters that you want to count). Then we create a function that creates a dictionary to store the key values of each letter (P.D. the number of times that the letter appears on the text). the function then makes the users input lowercase so we avoid counting for example “A” and “a” as different letters.

mrpzwwl_700wa_0

For each letter in the list (it can be other things, not only letters) the program counts the times the letter appears with the built in function count (text.count(the character that you want to count)) and proceeds to add the key and value to the dictionary only if the letter actually appears in the text written (to avoid printing all the letters).

We finally just print the dictionary that the function created and… TA-DA!

lmzj0bm_700wa_0

And in case you were felling down check out this cute video :3

You can check out the full code on github: https://github.com/Guemez/TC1014/blob/master/countletters.py

Follow me on twitter @danigguemez

#TC101 #Python #DailyChallenge #dictionaries