CS 115 Lab 6, Part C: Write a number as the sum of powers of 2

[Back to lab instructions]


Overview

Here, you will write the full program described in Part B, which expresses a positive integer as the sum of powers of 2.

Enter a number: 1234
2**10 + 2**7 + 2**6 + 2**4 + 2**1

Read the instructions carefully, and be sure you understand what you are doing at each step. Ask the lab instructors for help if you need it.


Instructions

Create a new Python source file named lab06c.py:

"""
Program: CS 115 Lab 6c
Author: Your name
Description: This program will read a positive integer and
 express it as the sum of powers of 2.
"""


def main():
    # Read user's input and store it in a variable called i_num.

    # Outer loop:
    # while i_num is larger than zero:
        # Initialize n and two_to_n.

        # Do all the stuff you were doing before to find n and two_to_n.
        # Remember that two_to_n is the largest power of 2 less than i_num.

        i_num = i_num - two_to_n

        # print 2**n.

    print()

main()

Before you translate the pseudocode to Python, answer Question 14 in your writeup. This question asks you to trace this algorithm for each iteration of the outer loop, assuming user input i_num = 23.

Once you have understood the algorithm, translate it to Python. If you need help copying code from Part B, ask an instructor.

At this point, test your program on the following sample input:

Enter a number: 1234
2**10
2**7
2**6
2**4
2**1

There are two major changes left to make, which the rest of these steps will walk you through:

First, to have all of these values print on the same line, add end="" to the end of your print statement. For example:

print('example', end="")

Now, your program is probably printing the following:

Enter a number: 1234
2**102**72**62**42**1

Next, you should add spaces and pluses between the terms by inserting this print statement somewhere in your code:

print(' + ', end="")

Now, your program should be printing the following:

Enter a number: 1234
2**10 + 2**7 + 2**6 + 2**4 + 2**1 +

Figure out how to get rid of the final ' + '. This will mean that your new print statement should be inside an if-statement.

When you have gotten rid of the final +, demo your program for an instructor.

Make sure that your docstring is up-to-date, and continue to Part D.