I start feeling that the amount of info taken in is too much to comfortably remember. I am getting a bit concerned of not being able to fully assimilate everything :S! At the same time I am happy I started this blog because I know that at any point I am lost I can go back look what I did before.
One thing today is that I learned that with triple quotes you can do specifications. Those help the user understand what a function does. “”” specification “””
Also I start feeling the pain and effort that is going to take to go forward! 😛 It’s not going to be easy. And MIT course, the assignments really are tough!
Also already touched Recursion in class. Recursion is pretty scare. Let’s see if I am able to assimilate it.
First recursive function:
I am quite happy because teacher talked about “Palindromes” and he wanted to use a recursive function to find if any string is indeed a palindrome. I paused the video before he showed how to do it and came up with the answer myself. I am happy cause it took me just 15 min or so to get it right.
def palindrome (string): if string[0] != string[-1]: print "Sorry not palindrome" return else: if len(string) <= 1: print "this is a palindrome" else: string = string[1:-1] palindrome(string)
However, after seeing the teacher equation, I feel a bit bad. Because my code above is really not following the right order and its unnecessarily complex. the teacher function is much more ordered and fundamental.
def ispalindrome(s): if len(s)<= 1: return True else: return s[0] == s[-1] and ispalindrome(s[1:-1])
His formula is so good. Basically it says, if string length is less or equal to 1, then we have reached the end and thus is palindrome. If not then return the result to a logic comparison X with Y.
X is answering the question “Is the first and last letter the same?” if yes it will be “True” otherwise “False”. And remember that we are doing X and Y, so this means that if the condition X is not meant, the formula will return False, it’s not palindrome.
And Y is basically asking… is the word in between the first and last character a palindrome? (If yes, it will mean it returns True).
Still there is a big gap of truly understanding recursive functions for me. Basically there must be a base case, and we test stuff on smaller and smaller chunks until we reach the base case, once base case is reached, the function “unwraps” and goes back again one by one till the beginning point.
Another explanation: https://www.youtube.com/watch?v=Mv9NEXX1VHc
Way too advanced, but this is a great video to go back in the future where it explains a real life scenario where recursion is needed: https://www.youtube.com/watch?v=k7-N8R0-KY4