Python Homework #2
Instructions:
You will be creating several functions (all in the same file).
Be sure to include, after each function, the appropriate test cases that you've
devised. There must be at least 2 test cases for each function, in the
following format:
print("fred(18) should be 34, and is: ", fred(18))
After using the test lines, you may comment them out.
- Create the function sum_squares(low,high) which will be given
two integers, with the requirement that low <= high. The function
will add up all of the squares of the numbers between (and including) low
and high and return tthat value. Be sure to include test cases to
validate your function.
- Create the function sum_powers(low,high,power) which will be
given two integers and a power (which is a number that is not necessarily an
integer or even a positive number), with the requirement that low <=
high. The function will add up all of the powers of the numbers
between (and including) low and high and return that value. For
instance, of power is 2, then it's the sum of squares. If it's 3 then
the sum of cubes, etc.
- Create the function SUM_POWERS(a,b,power) which will be given
two integers and a power, like the one above, except that we're not
guaranteeing that a <= b. You may use a previously
battle-tested function as a helper function.
- Create the function
fizzbuzz(n), which will be given a number n >= 1.
It will print out all the numbers from 1 to n, except: if a number is
divisible by 3, it will print out "fizz" instead, if it's divisble by 5 then
"buzz" instead and if divisible by both, then "fizzbuzz" instead. All
other numbers are printed out in numerical form. The function will not
return anything (no return statement).
- Create the function num_digits(n) which will be given a
positive integer n, and will return the number of digits in the decimal
representation of n. For instance, num_digits(105) returns 3,
num_digits(8) returns 1. Remember that the % operator gives you the
remainder (e.g. 17 % 4 gives you 1) and that the // operator is quotient
(e.g. 21 // 4 gives you 5) -- you'll need these.
Challenge problem (optional):
Create the function bin_to_dec(n), which will be given a number in
binary (only 1's and 0's), and will return the decimal equivalent of it.
Examples:
bin_to_dec(10) -> 2
bin_to_dec(101) -> 5