As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.
$ cd ~/cs120/labs $ mkdir lab19 $ cd lab19
We have been using the input
command for a few weeks
now. And what you should have noticed is that it always returns a string.
However, there are times where you want an actual integer instead of
a string. We have been using the built in int
to
perform this conversion. You now possess the tools to write this
function on your own. Let's practice string manipulation by writing
your own function to parse integers.
Create a function parse_int(integer_string)
in a file
called parse_int.py. This function takes
as a parameter a string of numeric characters. It should
return an integer, the decimal integer representation of the number in the
string. Your function should assume that every character in the
string is numeric.
DO NOT USE THE BUILT IN int
FUNCTION.
Make sure your program handles all necessary cases gracefully. What additional test cases should you check?
Function Parameters | Expected Output |
---|---|
"0" | 0 |
"1" | 1 |
"13" | 13 |
for i in range...
loop, or a for
character in integer_string
loop.
You can use the ord
function to get the ASCII
value of the numeric character. Because of the way the
ASCII table is setup, we can simply subtract the ASCII value
for '0' to get the actual digit this character represents
Your code above likely assumed, rightfully so, that the parameter
string was positive. However, negative base-10 integers are still
valid integers. Re-work your parse_int
function so
that it can handle a leading minus sign (-), and return the
correct numeric value for the input.
As we discussed in the lecture today, binary numbers are very
important to the functionality of our computers today. Even in
programs, it is very common to actually inspect or input a number in
binary for use later in the program. Again, the int
function can accomplish this already. However, we will practice
again by doing the conversions manually.
Create a function parse_binary(binary_string)
in a file
called parse_binary.py. This function takes as a parameter
a string of '1' and '0' characters. It should return an integer,
the decimal integer representation of the binary number in the
string.
DO NOT USE THE BUILT IN int
FUNCTION.
Make sure your program handles all necessary cases gracefully. What additional test cases should you check?
Function Parameters | Expected Output |
---|---|
"0" | 0 |
"1" | 1 |
"11" | 3 |
parse_int
The function assumes that all input strings represent a positive integer. Unlike decimal numbers, binary numbers typically do not use the minus sign, instead they use 0 and 1 and two's compliment. Modify the function to also convert strings that represent a negative number using two's complement.