2017-03-08

posted Mar 8, 2017, 7:03 AM by Samuel Konstantinovich
Goal: String to integer conversion.

Membership: 
"ab" in "abcd"  -> True
"c" in "abcd"  -> True
"C" in "abcd"  -> False

This is another feature that is nice to have. 

Instead of writing:
if s.find(x) >= 0:
  #stuff

You can write:
if x in s :
   #stuff


Python does not like when you apply an operator on numbers and strings at the same time. Because of this, we need to convert one way or another.
Python allows us to say:
str(123)   ->  '123'

Python also allows the opposite:
int('492') -> 492

READ ALL DIRECTIONS:
Your goal is to duplicate the int(s) function. 

Without using the int() function, write a function myInt(s) that takes a string that contains only the digits 0-9. It should return the numerical value of that string. 

e.g.
myInt('123') -> 123
myInt('5023') -> 5023
myInt("23")+myInt("32") + 1  -> 56

BEFORE WRITING ANY CODE:
In your notebooks:
 - Outline a few expressions that will help you solve the problem
 - Come up with a step by step process, using English language, to describe how you will solve it in python.
 - Trace through an algorithm that you design using a three-digit number, to show you know what you are trying to do.
 - FINALLY: Show your algorithm to a neighbor, and see if they agree with the steps you want to take.

Now code the solution in python using idle.
Comments