Thursday, January 21, 2016

Week 2, Day 4 - Search and sort and more recursion

Today's exercises involved writing some basic search and sort functions using a binary search and bubble sort.  My solutions worked well and were done quickly. I'm not sure what else to say aside from "I know reasonably sized data sets would use other algorithms that use fewer operations (on average)"

Another exercise: given a string such as "2+3-4", perform the indicated calculation.  My solution based on a for loop through the string:
    1. put a digit in a 'temp' holding place
    2. store the operator in a second temp variable
    3. identify a second variable as 'y'
    4. look up the correct lambda function in a dictionary (e.g. {'+': lambda x,y: x+y}
    5. set the first temp variable to  = lambda(x,y)
    6. proceed
    7. return total

My small discovery for the day, though: give a set of 'infix' notation, perform the calculation with correct order of operations.  The hardest part (converting a string to proper notation) was given. So 4 x 6 + 7 would be shown as (7, 4, 6, x, +) .  The idea is that the two right-most numbers would be operated on by the 'x' and 7 + the product would be the answer.  Solving the small example would be simple.  For a list of unknown length however, I used a very small recursive function (again using a lookup table for the right lambda function.

def process_infix(array):
 
   if len(array) == 1:
      return array[0]
 
   total = lambda_lookup[array[-1]](array[0], process_infix(array[1:-1])
 
   return total

no for loop, no iterating through the string....and it used the recursive logic that I was struggling with yesterday.  I still have  a lot of learning to do on recursion, but I'll take my victories where I can.

No comments:

Post a Comment