Design

Sunday, October 5, 2014

Sorting Backbone subviews in Rails

I recently completed my solo project at App Academy, which can be seen here on Heroku. My polling application has two different index views. One index view is if the current user has not answered the poll, sorted with the most recent at the top. The other index is for the polls they have answered, sorted by their most recently answered polls on top. Each index is a Backbone composite view, consisting of subviews. Every line on the table of polls is a subview, so sorting them turned out to be different than what I first tried. I also had infinite scroll, which probably should have given me a clue on the correct way to solve the problem.

The first place I looked was the Backbone documentation. 
If you define a comparator, it will be used to maintain the collection in sorted order. This means that as models are added, they are inserted at the correct index in collection.models
That seemed to be what I wanted, so I defined a comparator. I wanted the most recent at the top, which could have been done with created_at, but more simply could be done by descending id. Comparator does accept a function with a negative value. Unfortunately, I could not get the order to change in my view. The collection was sorted correctly in my browser console, but my JSON API was not in the correct order. So then I realized my API controller was to blame.
def index
    @polls = Poll.all
 end
The most basic index following RESTful conventions youve probably seen in every Rails tutorial. There is a lot me we could do with this however. Mine ended up as:
def index 
    if params[:answered] == "false" 
        @polls = Poll.where.not(id: current_user.answered_polls).order(id: :desc) 
    else 
        @polls = current_user.answered_polls.order("responses.id DESC") 
    end

    @polls = @polls.includes(:responses).page(params[:page]) 
    @page_number = params[:page] 
    @total_pages = @polls.total_pages 
    render :index 
end
Those last three instance variables were for pagination. I explicitly rendered index here for consistency. All my other actions were rendering JSON, butindex is rendering JSON that I customized in Jbuilder. What is cool here is how both indexes used the association answered_polls differently. In the first view, the id in the resulting table is the poll.id, which would be in the same order that a poll was created in the database. The second example was ordering when the user responded to the poll. I only wanted to see the polls they had answered, but I wanted the id of the responses, not the poll. I could not access responses.id as a symbol, the way I did in the first example. ActiveRecord is pretty good at it's job, but sometimes you have to give it some SQL in quotes. In order to figure out the filtering and ordering of these two index views, I had to think about how I'd do it in pure SQL. Lucky for me, I love SQL and this solved my sorting problems.

Saturday, May 31, 2014

App Academy: W-9D-2 - Being Accepted

In 9 weeks and 2 days, I will be starting App Academy in San Francisco. For my Pythonistas out there, yes I am aware I may be made fun of for becoming a Rubyist, but I'm confident this is a good decision for me to have career options as a developer for Rails, Backbone, or Django. For those unfamiliar with App Academy, it is a 12 week hacker bootcamp for Ruby, Rails, SQL, JavaScript, and Backbone.js that includes portfolio building, interview preparation and a final project. What is the most different about App Academy is their payment model. Tuition is collected after you get a job, 18% of your yearly earnings payable over 6 months. As someone with two kids too young for public schools, I'm not going to see much of my first 12 paychecks, but it will still be worth the investment.

I learned more about the program through the application and acceptance process. I submitted my application 2.5 weeks ago, never having done any Ruby, but with Python experience. I got an email back the same day for me to do the coding challenge that included reading assignments from Ruby Monk and Chris Pine's Learn to Program. I spent about 5 days learning Ruby very slowly, because I was visiting family. App Academy does not give a deadline for the coding challenge, so you can take the time you need to prepare. I was prepared to do the coding challenge in Ruby, but the directions said I could do Ruby or Python and it would take about 40 minutes. It took me about 20 minutes to do it in Python while my 9 month old was nursing and my almost 3 year old was "going Bananas" with a cartoon on Netflix (Bruno and the Banana Bunch). The next day, I got an email to schedule an interview with a TA. The Skype interview was audio only and consisted of just one programming question. I did make an error with initializing a variable in the wrong level of my nested loops, but solved it in 9 minutes in Python. I made an effort to talk through my logic process while solving the problem. Less than an hour later, I got an email to schedule a final interview with Kush Patel. There was another live coding problem, which took me 12 minutes to solve in Ruby. I talked through some of the logic, but I realized I was humming at one point (something I do when I'm enjoying a problem). Kush did ask some questions to make sure the program could work for me and that I was aware of some of the requirements. I was accepted the next day, which was quite a surprise because it was a Saturday. So from the time I completed the coding challenge, the interview process took me only 6 days.

One of the requirements of the program is the reason I was being silly with my post title. Every weekday, students post a blog entry with the week number and day number. I have 9 weeks and 2 days until my cohort begins, hence negative numbers. Although tuition is collected afterwards, there is a $3,000 deposit. The deposit holds your spot in the program and goes towards that 18% fee (tuition) when you do get a job, plus or minus any money from fees. Fees are used to keep students focused by penalizing tardiness, absences, getting off task with phones or emails, and failing to write daily blog posts. Fines are redistributed among the graduates at the end so that you only lose money if you were worse than your classmates about following the rules. Another rule of the program is that students may be asked to leave the program. Assessments are taken each week to evaluate if someone is falling behind. It is definitely an intense program, but I'm prepared for a challenge. The gamer inside me expected some fireworks or ominous music when I transferred the first $1250 to hold my place in the program yesterday. And so our hero begins her journey... I've currently worked through 12 chapters of Chris Pine's Learn to Program, 2 chapters of Peter Cooper's Beginning Ruby, and the first half of the Ruby Primer section on Ruby Monk. I am preparing to have a strong foundation for W1D1 !!

Thursday, February 13, 2014

Recursive Turtle Tree

I know the title of this post may sound like random words thrown together, but it's actually a really cool activity to learn about recursion using the turtle module in Python (Linux users need to install tkinter). I've been learning about algorithms and abstract data structures as part of my faking a CS degree personal mission. Problem Solving with Algorithms and Data Structures has been a fantastic resource so far (and free). Although the authors' explanation of recursion is the best I've ever seen, I think I could just add a little to the tree drawing example. Here's the program they provide:

import turtle

def tree(branchLen,t):
    if branchLen > 5:
        t.forward(branchLen)
        t.right(20)
        tree(branchLen-15,t)
        t.left(40)
        tree(branchLen-15,t)
        t.right(20)
        t.backward(branchLen)

def main():
    t = turtle.Turtle()
    myWin = turtle.Screen()
    t.left(90)
    t.up()
    t.backward(100)
    t.down()
    t.color("green")
    tree(75,t)
    myWin.exitonclick()

main()

Now I'm going to focus on the tree function. Notice tree calls itself twice. Now to step through how this function works, I am going to give each line a number and each recursive call a number such that 1.2 is the second time the first recursive call has been made and 2.3 is the third time the second call has been made. 

def tree(branchLen,t):
0    if branchLen > 5:
    1    t.forward(branchLen)
    2    t.right(20)
    3    tree(branchLen-15,t)     first recursive call
    4    t.left(40)
    5    tree(branchLen-15,t)    second recursive call
    6    t.right(20)
    7    t.backward(branchLen)

Let's trace branchLen = 30, following the code and what the turtle does. I've color coded each recursive call:

Code Line    Action                                Recursive Call
0               Passes > 5 test                       none
1               Forward 30                           none
2               Turns right 20 degrees           none
3               Calls tree(15)                        none
0               Passes > 5 test                      1.1
1               Forward 15                           1.1
2               Turns right 20 degrees            1.1
3               Calls tree(0)                           1.1
0               Fails > 5 test                          1.2
4               Turns Left 40 degrees             1.1
5               Calls tree(0)                           1.1
0               Fails > 5 test                          2.1
6               Turns right 20 degrees            1.1
7               Backward 15                         1.1
4               Turns Left 40 degrees             none
5               Calls tree(15)                         none
0               Passes > 5 test                        2.2
1               Forward 15                            2.2
2               Turns right 20 degrees             2.2
3               Calls tree(0)                            2.2
0               Fails > 5 test                           1.3               
4               Turns Left 40 degrees             2.2
5               Calls tree(0)                           2.2
0               Fails > 5 test                           2.3
6               Turns right 20 degrees            2.2
7               Backward 15                         2.2
6               Turns right 20 degrees            none
7               Backward 30                         none

If you choose a color such as red or orange, you can see how the function is executed in its entirety, but with interruptions. The colors that appear nested, such as orange inside the red, appear higher in the stack frame. They are completed first even though they started second, but the program continues to the red after the orange is completed. The next value of branchLen to create more recursive calls is 45. You could also try tracing tree(45), using tree(30) as a shortcut to emphasize the benefit of recursion.
               

Coursera -- Introduction to Interactive Programming in Python

A couple months ago, I took a free course on Coursera.com offered by Rice University and taught by Joe Warren, Scott Rixner, John Greiner, and Stephen Wong. Coursera offers the course a couple times a year, with 2014 offerings including March 24th and October 7th. The course is now part of the Fundamentals of Computing specialization and you earn a certificate after completion with the ability to earn additional "distinction" for scoring an A in the course (I did).

I recommend the course for anyone between "Isn't Python a snake?" to "Why should I use classes?" Students learn Python by developing simple games in CodeSkulptor, which includes a simple GUI like PyGame without using a terminal or setting up a coding environment. Homework includes quizzes over video material, building games in Python, and evaluating peers' code. I enjoyed the peer reviews because you can recognize common mistakes and see how other people solved the same problem you did. The game development approach finally helped me understand the point of object oriented programming. I went from fear of using classes, to empowered by building my own classes in the last three weeks of the course.

I am looking forward to the next course in the Fundamentals of Computing specialization, Principles of Computing. It is exciting to have an option for continuing to learn after a course. Us self-taught learners often waste time trying to decide what is the most appropriate and useful for us to learn next. If you can tolerate some corny Big Bang references and want to take your Python development to the level of using and understanding classes, you can enroll for free on Coursera.com

Tuesday, June 12, 2012

Moving :)

I have been busy with reStructuredText lately because I'm moving to housewifehacker.com. I've also been busy with reading entrepreneur blogs and books because our conference management system has been accepted to StartUp Chile to receive $40,000 in equity free funding. July is going to be busy with hacking on different technologies as well as getting our work visas to live in Chile. My new blog will have categories for Code and StartUp, maybe Personal/Travel too, so you can subscribe to which categories you are interested in. I dont have feed burner or RSS set up on the new domain yet, but you can check out my most recent code tutorial on there now. It's a guess the number script using the new preferred string formatting for python. It also addresses some exception handling, the process of developing a script, and a teensy bit about global variables and scope. Please follow me on twitter @housewifehacker

Tuesday, May 15, 2012

Simple Dictionary Practice: Is Anagram?

I do not use dictionaries very often. Friday, I was without internet all day, so I took the opportunity to play with dir() and help() to discover some dictionary properties. My short-lived obsession with Draw Something on the iPhone has gotten me interested in anagrams (kicked the habit by reading programming books). I believe using dictionaries is the fastest and most accurate way to determine if two words are anagrams of each other.

A dictionary is an unordered set of key: value pairs. Keys must be an immutable type. Values can be anything. Review on mutable versus immutable here. Being unordered causes some interesting properties for working with dictionaries, different from any other python data structure. Instead of being indexed by numbers, dictionaries are indexed by keys. Because they are indexed by keys, each key is unique within it's dictionary. If two dictionaries with the same keys are added to each other, the values of the same data type combine. This is convenient for our anagram activity. But first, some dictionary review.


>>> sample_dict = {}        # creates an empty dictionary
>>> type( sample_dict )
<type 'dict'>
>>> sample_dict['Name'] = 'Jessie'        # creating a key:value pair
>>> sample_dict['Age'] = 23        # another key:value pair
>>> sample_dict
{'Age': 23, 'Name': 'Jessie'}
>>> sample_dict2 = {'Name': 'Jessie', 'Age': 23}        # another way to create dict
>>> type (sample_dict2)
<type 'dict'>
>>> sample_dict2
{'Age': 23, 'Name': 'Jessie'}
>>> sample_dict + sample_dict2        # cannot add dictionaries, only values
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> sample_dict['Age'] + sample_dict2['Age']        # adds values
46
>>> sample_dict.keys()
['Age', 'Name']
>>> sample_dict.values()
[23, 'Jessie']
>>> type( sample_dict.values() )        # keys and values are returned as lists
<type 'list'>
>>> sample_dict.get('Age')        # gets the value at a specific key
23
>>> type( sample_dict.get('Age'))         # value maintains data type in dictionary
<type 'int'>
>>> sample_dict.has_key('Age')        # D.has_key() returns boolean
True
>>> sample_dict3 = {'Children': 'Graham'}
>>> sample_dict3.update(sample_dict)        # update keys and values
>>> sample_dict
{'Age': 23, 'Name': 'Jessie'}
>>> sample_dict3        # Children field is added as a key:value pair
{'Age': 23, 'Children': 'Graham', 'Name': 'Jessie'}
>>> {'Age': 23, 'Name': 'Jessie'} == {'Name': 'Jessie', 'Age': 23}        # different order is equal
True


How do we know if two words are anagrams? Consider the anagrams odor and door. We could say that they are reshuffled strings. Each word uses the same letters, but in a different order: 2 o's, 1 r, and 1 d. My simple program creates empty dictionaries for the two words being compared, stores the letters as keys, and adds to the value for each occurrence of the same letter, then checks that the dictionaries are equivalent. I have not included exception handling and I made the design decision to count white space as part of the anagram such that 'abc def' is not an anagram of 'fdeabc,' but is an anagram of 'abc fed.'


def get_dict(word, count):
     for i in word.lower():
         if count.has_key(i):
             count[i] += 1
         else:
             count[i] = 1
     return count

 def main():
     word1 = raw_input("What is the first word? \n")
     word2 = raw_input("What is the second? \n")
     count1 = {}
     count2 = {}
     count1 = get_dict(word1, count1)                              
     count2 = get_dict(word2, count2)
     if count1 == count2:
         print("Yes, those are anagrams!\n")
     else:
         print("No, you've failed \n")

 if __name__ == "__main__":
     main()


Friday, May 11, 2012

Book Review: The Practice of Programming

Affiliate Link

The Practice of Programming, written by Brian W. Kernighan and Rob Pike, was originally published in 1999. Although most programming books more than a couple years old are obsolete with out of date technology, The Practice of Programming is a pragmatic guide to become a better programmer regardless of your chosen language, framework, or supporting technologies. To quote the epilogue, "The world of computing changes all the time... but there are some constants, some points of stability, where lessons and insight from the past can help with the future." I highly recommend this book to any programmer who wants to establish good habits for writing understandable and consistent code. I also recommend this for programmers who want to or need to be able to work on projects with other developers. Although the exercises and examples were written in languages other than python, I was able to learn a lot. I reflected a lot on my own code, figured out new questions to ask about python, and am more appreciative that python does not suffer from some of the common pitfalls of other languages.

Monday, May 7, 2012

Mutable versus Immutable Objects

Strings, lists, tuples, integers, float, dictionaries, and sets are all types of python objects with different properties and uses. When using an object in a program or in your terminal, your session assigns an Id to access the computer's memory. The Id will be unique each session and on each computer, so the actual number returned by the id() function is irrelevant. What is relevant is when that number changes. If the id changes as the value changes, the computer had to assign a new id to the immutable object. If the id stays the same, then it is a mutable object, because the value associated with the id can be changed without changing the id. Integers are immutable:

>>> x = 5
>>> y = x    # direct the reference of y to be the reference of x
>>> id(x) == id(y)    # x and y point to same reference
True
>>> x = 4    # change the value of x
>>> id(x) == id(y)    # the id of x changed when we changed the value
False
>>> x == y    # the value of y did not change with x
False


I'm the type of learner that skims through vocabulary lessons to get to the action, but understanding this next part will save you some headaches when trying to manipulate mutable objects. Look what happens when I try to do the same thing I just did to the integers, but now to a list:

>>> x = [5]
>>> y = x    # direct the reference of y to be the reference of x
>>> id(x) == id(y)    # x and y point to the same reference
True
>>> x.append(4)    #change x from [5] to [5, 4]
>>> id(x) == id(y)    # x and y still point to the same reference
True
>>> x == y    # y changed with x
True
>>> y
[5, 4]
>>> z = [5, 5]    
>>> id(z)    # will be a different number for everyone
3075316972L
>>> z.append(3)    #z is now [5, 5, 3]
>>> id(z)    # id is constant, the list is mutable
3075316972L


I stumbled upon this while using random.shuffle on a list, while wishing to keep a copy of the list in it's original form. As you can see by assigning x equal to y, the lists changed together. That was an ineffective way to make a copy because all I did was assign the same Id two different names. Try determining if the other object types are mutable or immutable. I don't want to spoil the fun for you.

Sunday, April 22, 2012

Python Style Guide

Did you realize Python has a style guide to clarify consistent and readable code? It covers topics such as white space of indentations in-line, capitalization of variable, function, and class names, and formatting of comments. Read Pep8

Now I look at my code examples and see a whole lot of ugly. Some good news is that some of the proper styles can be integrated into your vim configuration. A tab on your keyboard can type four spaces. A red line can be drawn vertically to show when a line exceeds the recommended 79 characters. The other good news is that you can run the pep8 script to find style errors. I am going to make an effort to follow the style guide, as well as improve my names. By using "is" to preface boolean tests, verbs such as "get" prefacing function names, and complete words or widely accepted abbreviations (such as str for string), my code can be more readable. I am also going to make my names something that I can sound out. As my code becomes more complicated, variable class and method names are easier to remember if you can pronounce them out loud. 

To use pep8, you simply install it using pip or easy install, run it against your python file, then read the corrections pep8 expects. Example corrections may be that two empty lines were expected instead of one, max line length was surpassed, or extra spacing was found. The script prints the lines that each instance is found on, so you can easily make changes if you want to comply with the preferred style. Documentation can be found here.

I am reaching a stage in my learning where I am reading more code than I am writing. Ambiguous names, inconsistent capitalization, incorrect spelling, and weird in-line spacing makes reading code more difficult. I did have the mindset that if Python didn't care, why should I? Well, now I do care. Just like when learning a spoken language, reading is an important part of learning how to communicate with the language properly.

Tuesday, April 17, 2012

Just a reflection

We have moved to Chile. Yes, the country. I really like it ere, except that my husband's laptop warranty does not apply here. So because he spilt Zuko on his computer, he is using mine and I cannot code Python on an iPhone. I have had some recent experiences that I thought I'd share. First, I want to get better with Linux. If you do not know Linux, you are not a nerd and you are powerless to improve your operating system and most of your coding environment. A friend's business uses Linux machines as kiosks, so I was setting up all the applications they use on their newest system. The newest version of Ubuntu is insanely beginner friendly. Instead of just giving an error sound when you've messed up, it attempts to correct your mistake or explain why you couldn't do what you were trying to do. Of course Linux is free and so are the programs for it. Just about anything you would buy for your Windows or iOS computer has a free open source version that runs on Linux. In Linux, you can customize everything to suit your needs and style. I can have a window manager that allows me to never use my touchpad/mouse. With a custom operating system and vim configuration, coding could be more productive.

Another reflection is the cool use of Python for games. Blender is a gaming engine with a GUI, simple enough for artistic people to draw and program 3D games. Blender can also be used for video animations. I like Khan Academy, but think that their videos resemble a lecture. After five minutes, I want to fall asleep or check Facebook. I want to try to make instructional videos in Blender to teach math and physics. Blender has a built in physics engine, so I do not think creating physics animations would be difficult. Check out Pissed Off Penguins on YouTube to see Blender being used to make an Angry Birds similar game. The other cool gaming technology in Python is Pygame. I was not previously interested in Pygame. Tetris, Woohoo. But a friend's application of Pygame in his kiosks is so intriguing to me. I now want to learn other applications of PyGame.

I learned what I could from SICP, but it wasn't applicable to my interests. I like math, physics, and chemistry, but I'm not interested in using Scheme to prove all of Newton's theorems. The first chapter was worth reading, but that's all. So for now I am learning Spanish, playing with my dSLR, and wishing I could build something with Python. Web apps are intimidating, but I'm pretty sure I can do Blender and PyGame. Hopefully I'll get my computer back in the next three weeks, but probably not :(

Thursday, March 15, 2012

ABC and The Birth of Python

As I have mentioned in a previous post, I am very interested in the how and why of programming, which includes the history of different languages. One of the posters at PyCon 2012 held in Santa Clara over the past week was about the programming language ABC. There is a Youtube video that is unfortunately edited poorly and has the microphones off during the most important part of the interview here.

Guido van Rossum is often called "The Father of Python" because of his critical involvement in the development of the language. He wanted programming to be more intuitive, easier to learn, written in true English, and available to everyone. However, he did not start Python until ABC lost its funding. He also did not come up with all the basic principles on his own. Although he did work on the ABC project, he was not one of the original creators, nor is he attributed a large portion of the credit. Leo Geurts, Lambert Meertens, and Steven Pemberton are acknowledged as the leads on the ABC Project sponsored by CWI, Netherlands.

Like Python, ABC uses indentions (white space) to organize loops. ABC is also much easier to read than the programming languages of its time, BASIC, Pascal, and AWK. Tuples, lists, and strings were important in ABC, as they now are in Python. Tuples and indentations were actually utilized by SETL before they were used by ABC.

By looking at examples of SETL developed in the late 1960's, then examples of ABC from the 1980's, and finally modern Python, the progression of the structure and readability is apparent. Python is a beautiful language because of its intuitive design.

Wednesday, March 14, 2012

SICP Square Root Procedure

I haven't progressed much further in SICP. There have been so many interruptions. We traveled to Santa Clara for Pycon, where my husband, sontek, lead a tutorial on gevent, socketio, and realtime web (all things currently above my comprehension). Our son met Steve Holden, the chair of the Python Foundation, and many other developers known in the world of Python. I was hanging out in the lobby of the conference center one day so that I could see some of my husband despite the time involvement of the conference. Oddly enough, my SICP book got just as much attention as having a baby in a stroller and being female. I was more than the elephant in the room. I was a pink elephant wearing roller skates.

Continuing with SICP, I want to discuss the square root procedure example. It is excellent at demonstrating a lot of basic programming principles. Of course, Python has excellent math tools that make defining a procedure for square root unneccesary, but let's just do it for fun. First, we need to understand Newton's Method.

Let's pretend we did not know the square root of 9. We GUESS the answer is 2. But 2 squared is 4. So how do we get closer to the answer? We take the average of our GUESS and X, which is 9, divided by our most recent guess. The average would be 2.75 ( (9/2+2)/2 ). Now 2.75 becomes our new GUESS. We repeat, until guess squared is equal to 9, our x. So what does our code need to do?

make a guess -> square guess to check if good enough -> take the average of guess and x divided by guess if not good enough -> use computed average to improve guess -> square guess to check if good enough -> take the average...
An iterative procedure (repeating) until when?

Some numbers may take a very long time to solve exactly, or the square root may be a decimal with over 10 numbers beyond the decimal, so we also need to allow for some error. When we check if the square of the guess is equal to our x value, we can allow a difference less than .001, between the squared guess and the value of x, ending the iterations. We also need to define what our original guess will be. SICP uses 1.0, so let's try that. In both lisp and python, a number with a decimal allows floating numbers to be computed, while an integer without a decimal does not. Some of our definitions are modular, or reusable, so I'm going to give square, average, and abs their own definitions. I am ignoring the built-in absolute value, just so we can do more coding. I'm calling the absolute value definition abs2. I solve this problem in a different order than SICP, so I'm going to show my logic, in Python.

First, I wrote my code in Vim, so I could fix typos easily and experiment more quickly. In my terminal, I created sqrtsicp.py:

vim sqrtsicp.py

Our modular definitions mentioned previously are easy. Let's get them out of the way.
def square(x):
    return x*x

#naming absolute as abs2 to avoid built-in "abs"
def abs2(x):
    if x<0:
        return -x
   else:
        return x

def average(x,y):
   return (x+y)/2

Now for the hard part. We'll skip the first guess right now. The iterative part involves checking if our guess is good enough, then improving our guess if it is not good enough (good enough is false), only to try to determine if our improved guess is good enough.

def sqrt_iter(guess):
   if good_enough(guess):
       return guess
   else:
       return sqrt_iter(improve(guess))

Next we define how we determine if good_enough is true and how to improve our guess. Both of these need to know the value of x to compute.

def good_enough(guess,x):
   return abs2(square(guess)-x)<.001

def improve(guess,x):
    return average(guess,x/guess)

Now we have two problems. One, the x is being used for good_enough() and improve() without receiving the value of x from sqrt_iter(). Second, we need a starting guess. This is the point where I put good_enough(), improve() and sqrt_iter() all together and give it an initial guess. Our variable x is a constant and can be passed in from the overall procedure sqrt().
def sqrt(x):
    def good_enough(guess):
         return abs2(square(guess)-x)<.001
    def improve(guess):
         return average(guess,x/guess)  
    def sqrt_iter(guess):      
         if good_enough(guess):          
             return guess
         else:
             return sqrt_iter(improve(guess))
     return sqrt_iter(1.0)

It's good structuring to have all your definitions before your actions. The final line is the return function that causes the dominos to fall. sqrt_iter() calls itself on the new guess if our latest guess was not good enough. "Calling itself" is known as recursion. Now just make it a program. Within my file, I define the main procedure (not sure of the programmers vernacular)where my program is going to ask what to take the square root of. I want the input to be any positive number, including decimals. I want to use exception handling to ask for a floating number if the user inputs a string. I'm also going to define the decimal places for the output of the square root procedure to 3 digits past the decimal. If a negative number is entered, I ask for a positive number and attempt the program again. If a string is entered, I say "Oops, that's not a number" before calling the program again.

def main():
    try:
        x=float(raw_input("What number do you want to find the square root of? "))
        answer = sqrt(x)
        print("The answer is \n%.3f") %answer
    except:
        print("Oops, that is not a number")
        main()

if __name__=="__main__":
    main()

Those three pieces combined are a completed program. In my terminal, I can run it by typing:
python sqrtsicp.py

Playing with it, I attempt to find the square root of -9, 874, .04, and L. All my results are what I expect. This may be a good candidate for selenium testing or a unit test in more complicated programs. For another example of exception handling, view my Caesar's Shift. For more information of float from wikipedia, read this article. You can also refresh your math tools knowledge, including absolute value here.

Friday, March 9, 2012

Applicative Order Versus Normal Order Interpreter

How would you solve for c in the following problem? Ignore computer programming languages for just a minute.
b=(a+2)*(a+1) c=a*b a=3
Choice 1:
c=(3)*(3+2)*(3+1)
c=3*5*4
c=60
Choice 2:
c= (3)*((3+2)*(3+1))
c=(3)*(5*4)
c=(3)*(20)
c=60

They look very similar and yield the same result, however they act differently. In choice 1, the numbers are substituted and evaluated at the end. In Choice 2, the intermediate step (solving for b) is completed before evaluating for c. Choice 2 is applicative order, or strict evaluation. Choice 1 is normal order, also known as lazy evaluation because it only calls what is needed. The Lisp interpreter acts like Choice 2.

Knowing that lisp is applicative-order, we can now theorize the results of the somewhat famous Ben Bitdiddle Test, exercise 1.5 in SICP.I attempted to predict the outcome yesterday when I did not have access to my computer. I'm still bitter about it. First is the example written in lisp. Second is the test translated into Python. Do you think lisp and python act the same? What will they do when tested?
(define (p) (p))
(define (test x y)
(if (= x 0)
0
y))

(test 0 (p))
Or in Python
def p():
return p()

def test(x, y):
return 0 if x==0 else y

test(0, p())

I spent about 45 minutes irritated, thinking there was no way lisp would return either 0 or y, because the p would be looping forever, I was able to get on a computer. I WAS RIGHT! Applicative order interpreters cannot evaluate the test, because they are too concerned with the definition of p. "Lazy" or normal order interpreters only apply the needed information, so they are able to return 0. According to this test, Python is also a strict interpreter, using applicative order like lisp. I expect the differences between normal order and applicative order will be relevant again in further reading of SICP.

Saturday, March 3, 2012

Getting Back Into It

It has been awhile since I have posted anything for two reasons. First, I got stuck. Python came easy for me, but programming requires much more than knowing one language. For that reason, I have decided to resume my learning with more elementary programming concepts. Some people learn by doing, but I learn by dissecting. I need to know how and why things work the way they do. Which programming languages came first? How does a program evaluate a complex math problem with variables? What are the strengths and weaknesses of each of the languages? What are interpreters and how do they work? How does code become a website? My second reason for my absence is that I had a baby. Now 8 months old, he is a little less demanding of my attention and energy than he was before he was capable of sitting up on his own.

I am currently reading Structure and Interpretation of Computer Programs. SICP and Little Schemer are used to teach generalized computer programming principles, utilizing the languages of LISP and Scheme for examples. Both books were created at MIT for computer programmers. Lisp is the second oldest programming language still in use. Reddit.com was written in Lisp before it was converted to Python. Unlike how Python is organized by white space, Lisp uses parenthesis. A ridiculous amount of parenthesis. I have not yet attempted to write code in Lisp, but I am anticipating customizing a VIM configuration for using only with Lisp will be beneficial. I am enjoying the conciseness and organization of Lisp, compared to Python. Below is an example of the same mathematical expression in the two languages.

Python
3 * a + 7 + b
Lisp
(+ (* 3 a) 7 b)

I'll be discussing any "Eureka" revelations here on the blog, though it may take me a couple weeks to get through SICP.

Saturday, December 4, 2010

Now on Github

HousewifeHacker is now on Github. To avoid further formatting problems with pasting my code on the blog, I will be using github to embed my code. For those who are unfamiliar with Github, the site allows programmers to follow open source contributions from different authors and contribute to full projects (Repositories) or small code snippets (Gists) by creating your own code or making changes to other user's work (forking). Users can determine whether their repositories and gists are public or private. The objective of Github is to serve as a social coding resource as well as a revision control. Because I want to be able to contribute to open source projects as I become more knowledgeable of Python, Github will become an increasingly valuable resource.

Thursday, December 2, 2010

maketrans Python and Improved Caesar's Shift

Maketrans is used to translate strings, character for character. The characters can be symbols, letters, or numbers. The following short example is a Caesar's Shift moving backwards by two letters.
#first we need to import maketrans
>>> from string import maketrans
#now define the translation
#parameters are strings, not lists
#first parameter defines what will be found in the string
#second parameter defines what each will be changed to
>>> trans = maketrans('cdefg','abcde')
#define our string and translate
>>> s = 'deg'
>>> s.translate(trans)
'bce'

Now using maketrans and a few other suggestions from the comments, I have written a newly improved Caesar's Shift. Encode and decode use the same code, because a shift of 4 in one direction of a 26 character alphabet is equivalent to a shift of 22 in the other direction. I also used ascii_letters to shift my translation, which is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. The letter w may be encoded to be a A by a shift of 4, but the decoding will return the lowercase w. There was an error in my exception handling, which is now corrected.

Saturday, November 13, 2010

Caesar Cipher in Python Using ASCII

ASCII is how American computers store numbers, letters, certain commands, and symbols as numbers. A binary byte is eight digits long, consisting of only 1 and 0. When ASCII was developed, there were 2^8, or 256 possible characters for 8-bit (1 byte) personal computers. Unicode is used more commonly and extensively, but ASCII is sufficient or this exercise. Consult an ASCII Table or play with python's default functions to determine the encoding of a character such as 'a', 'A' or '&'.

In python, we can find the ascii value using ord of a string
>>> ord('a')
97
>>> ord('A')
65
>>> ord('b')
98
>>> ord('1')
49
>>> ord('2')
50
>>> 3-0
3
>>> ord('3')-ord('0')
3

Notice how the lower case and upper case are unique. Also, the ASCII numeric value and the character increase by the same amount. The same trend is true for the continuation of the alphabet, if lower case or upper case characteristic is preserved. The string length must be 1 when using ord, because each index has its own ASCII value.For a multiple digit number or a word, you can use a for loop to go through the string.

The reverse of ord is chr, for character.
>>> chr(97)
'a'
>>> i=97
>>> while i<104:
... print chr(i)
... i+=1
...
a
b
c
d
e
f
g
>>> alpha=[]
>>> i=97
>>> while i<104:
... alpha.append(chr(i))
... i+=1
...
>>> print alpha
['a', 'b', 'c', 'd', 'e', 'f', 'g']


Caesar's shift was how Caesar communicated with his generals, in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, if an 'a' is encoded by a 'c' with a shift of 2, then a 'b' would be encoded by a 'd.' Reversely, an 'a' in the encoded text would be a 'y' in the plaintext. The following program was inspired by thepythonchallenge.com. My husband and I had a lot of fun testing and debugging by sending each other messages over email. The code only changes letters so that spaces, smilies, brackets, and other punctuations and characters will be preserved. string.maketrans would be very useful and less code for a one time application, but the following code is highly reusable.


#string will later allow us to test for ascii letters
import string

def encode(input,shift):
#create an empty string
foo = ''
#a for loop to shift the letters by the shift input
for x in input:
#changes only ascii letters
if x in string.ascii_letters:
#upper case end of alphabet, to loop back to A
if ord(x) > ord("Z") - shift and ord(x) <= ord("Z"):
new_ord = ord(x) + shift - 26
#lower case end of alphabet
elif ord(x) > ord("z") - shift and ord(x) <= ord("z"):
new_ord = ord(x) + shift - 26
else:
new_ord = ord(x) + shift
#other characters will remain unchanged
else:
new_ord = ord(x)

new_chr = chr(new_ord)
foo += new_chr

print "Your encoded message is ", foo

def decode(input,shift):
#create an empty string
foo = ''
#a for loop to shift the leters by the shift input
for x in input:
#changes only ascii letters
if x in string.ascii_letters:
#upper case start of alphabet, to loop back to Z
if ord(x) - shift < ord("A") and ord(x) >= ord("A"):
new_ord = ord(x) - shift + 26
#lower case end of alphabet
elif ord(x) - shift < ord("a") and ord(x) >= ord("a"):
new_ord = ord(x) - shift + 26
else:
new_ord = ord(x) - shift
#other characters will remain unchanged
else:
new_ord = ord(x)
new_chr = chr(new_ord)
foo += new_chr
print "Your decoded message is ", foo


def get_shift():
try:
shift = int(raw_input("How many characters do you want to\
shift?\n"))
except:
print 'Shift must be a number'
shift = get_shift()
if not (shift > 0 and shift <= 25):
print 'Shift must be between 1 and 25'
shift = get_shift()
return shift

def main():
try:
action=raw_input("Welcome to Caeser's Shifter! Would you \
like to encode or decode a message today?\n")
except:
print 'Please type encode or decode'
main()
shift = get_shift()

print "Ok, let's %s your message with a shift of %d." % (action, shift)
input=raw_input("What would you like to be translated?\n")

if action=='encode':
encode(input,shift)
elif action=='decode':
decode(input,shift)

if __name__ == "__main__":
main()


There are probably a few areas where redundancy can be reduced, but I am still learning as a developer. This was my first time trying exception handling, which I learned from my husband.

Tuesday, November 2, 2010

' \ ' Escapes in Python

I have previously mentioned that '\n' codes for a new line. The backslash is known in Python as an escape.
>>> print "\tThis is a tabbed line"
This is a tabbed line
>>> print "This sentence \nis split on \nthree lines"
This sentence
is split on
three lines
>>> print "Type \\ for a backslash"
Type \ for a backslash
>>> print "Verticle \vTab"
Verticle
Tab
>>> print "Shopping List: \vPrenatal vitamins \vCocoa Butter \
... \vOrange juice"
Shopping List:
Prenatal vitamins
Cocoa Butter
Orange juice
>>> print "Shopping List: \n\t*Prenatal vitamins \
...\n\t*Cocoa Butter \n\t*Orange juice"
Shopping List:
*Prenatal vitamins
*Cocoa Butter
*Orange juice
>>> print 'Prevent the single quote 5\'5" from ending the string'
Prevent the single quote 5'5" from ending the string
>>> print "Prevent the double quote 5'5\" from ending the string"
Prevent the double quote 5'5" from ending the string

Notice that I also used a backslash in my string so that I could continue onto the next ine without Python thinking my string was done. There are other escapes in Python you can read about. "Carriage return" is a term from type writers to mean that you move to the beginning of a line. Linefeed and formfeed are also typewriter terms. \n and \t will be the most frequently used, though you may also want to be familiar with other escapes for unique problems.

Monday, October 25, 2010

Guess the Number Game Python

With inspiration from InventWithPython.com, I wrote a game to guess a number between 1 and 20 with six attempts. This simple game is good practice for a beginner. My code is written in Python 2.6. The example from the link is written in Python 3 syntax.

import random

guessesTaken = 0

print 'Hello! What is your name?'
myName = raw_input() #get user name

number = random.randint(1,20) #random number between 1 and 20
print '%s I am thinking of a number between 1 and 20.' % myName

while guessesTaken < 6:
print 'Take a guess.'
guess = int(raw_input())
guessesTaken += 1
if guess < number:
print 'Your guess is too low.'
elif guess > number:
print 'Your guess is too high.'
else:
break #breaks out of loop

if guess == number:
if guessesTaken == 1:
print 'Good Job, %s! You guessed my number in 1 guess!'
else:
print 'Good Job, %s! You guessed my number in %d guesses!' % \
(myName,guessesTaken) #actual format on previous line without '\'


if guess != number:
print 'No. The number I was thinking of was %d' % number

Sunday, October 24, 2010