Assignment 2: Problem Solving Example

Unit 1 > Assignment 1 > problem solving


Let's start with the outer while loop that reads an integer from the user each time:

 

A1.1 Exercise: Write up the above in my_demo_problem1.py and test out the while loop.
 

Next, we want to successively divide by 2 (using integer division):

 

A1.2 Exercise: Does this work? Write up the above in my_demo_problem2.py and find out. Then explain what went wrong in your assignment2.pdf.
 

A1.3 Exercise: In my_demo_problem3.py fix the problem by rewriting the inner while-loop so that the output is correct (as shown in the problem description).
 

That solves the problem. However, we'll now explore a few alternative ways of writing the code:

 

A1.4 Exercise: Write up the above in my_demo_problem4.py and explain in assignment2.pdf why we were able to use the same variable n in the function.
 

Finally, noticing that we get input once outside and then again inside the loop, we could ask: can we rewrite the outer loop so that we get input only inside the loop?

 

A1.5 Exercise: In my_demo_problem5.py show that this can indeed be done, using a break statement. Use the function num_divides() as given to you above.


© 2020, Rahul Simha