Quiz 3b#

Question 1#

When the following code is executed, how many times is timer_handler called?

import simplegui

def timer_handler():
    # …

timer = simplegui.create_timer(10, timer_handler)
timer.start()

The body of timer_handler isn’t given, as it is irrelevant for this question. You may want to finish the code and run it before submitting your answer.

0 — The code hasn’t been written correctly.
1
10
Unlimited — It is called repeatedly until you stop the program. \


Unlimited — It is called repeatedly until you stop the program. \


Question 2#

You want a timer to create exactly 1000 events. Which of the following solutions are possible?

Have a global counter for the number of timer calls. In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer.
Have a global counter for the number of timer calls. Outside the timer handler, increment the counter. Outside the timer handler, check the count and possibly stop the timer.
Specify the number of timer events when creating the timer.
In the timer handler, have a local counter for the number of timer calls. In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer. \


Have a global counter for the number of timer calls. In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer. \


Question 3#

How do you change the frequency of a running timer, either increasing or decreasing the frequency? E.g., in the code below, we want code at the question marks that changes the timer.

#…
timer = simplegui.create_timer(1000, timer_handler)
timer.start()
#…
#???

Create and start the timer again.

  timer = simplegui.create_timer(300, timer_handler)
timer.start()
 


[ Just run create_timer. It will change the timer. ]

  timer = simplegui.create_timer(300, timer_handler)
 


You can’t. But, you can stop this timer, and start a new one with a different frequency and same handler.

  timer.stop()
timer = simplegui.create_timer(300, timer_handler)
timer.start()
 


Just use set_timer_interval.

  timer.set_timer_interval(300)
 

\


You can’t. But, you can stop this timer, and start a new one with a different frequency and same handler.

  timer.stop()
timer = simplegui.create_timer(300, timer_handler)
timer.start()
 

Note that creating a new timer and starting it will leave the first timer in operation.

try:
    import simplegui
except ModuleNotFoundError:
    import simplequi as simplegui

i = 0


def tick():
    global i
    i += 1
    print(i)
    

t = simplegui.create_timer(1000, tick)
t.start()
t = simplegui.create_timer(1000, tick)
t.start()

In the previous code tick() occurs two times per second.


Question 4#

How many timers can you have running at once?

0
1
Unlimited \


Unlimited \


Question 5#

The function time.time() is used in Python to keep track of time. What unit of time is associated with the value returned by time.time()? Hint: Look in the documentation .

Milli-second
Second
Minute
Hour \


Second \


Question 6#

In Python, the time module can be used to determine the current time. This module includes the method time which returns the current system time in seconds since a date referred as the Epoch. The Epoch is fixed common date shared by all Python installations. Using the date of the Epoch and the current system time, an application such as a clock or calendar can compute the current time/date using basic arithmetic.

Write a CodeSkulptor program that experiments with the method time.time() and determines what date and time corresponds to the Epoch. Enter the year of the Epoch as a four digit number. (Remember to import time.)

Enter answer here:\


import datetime  # for getting today's year
todays_year = datetime.date.today().year

import time

secs = time.time()
years = secs / (60 * 60 * 24 * 365)
# this code does not take the leap years into account, but should still help us
# to get the epoch year

print(todays_year - int(years))

1970


Question 7#

The Python code below uses a timer to execute the function update() 10 times, computing a good approximation to a common mathematical function. Examine the code, and run it while varying the input value n.

What is the common name for what this computes?

# Mystery computation in Python
# Takes input n and computes output named result

import simplegui

# global state

result = 1
iteration = 0
max_iterations = 10

# helper functions

def init(start):
    """Initializes n."""
    global n
    n = start
    print "Input is", n

def get_next(current):
    """??? Part of mystery computation."""
    return 0.5 * (current + n / current)

# timer callback

def update():
    """??? Part of mystery computation."""
    global iteration, result
    iteration += 1
    # Stop iterating after max_iterations
    if iteration >= max_iterations:
        timer.stop()
        print "Output is", result
    else:
        result = get_next(result)

# register event handlers

timer = simplegui.create_timer(1, update)

# start program

init(13)
timer.start()

Square: $$n^2$$
Multiplicative inverse: $$1/n$$
Square root of $$n$$
Cosine of $$n$$
Multiplication by 2: $$2n$$
Logarithm base 2
Exponentiation: $$2^n$$\


Square root of $$n$$\


Question 8#

Given any initial natural number, consider the sequence of numbers generated by repeatedly following the rule:

  • divide by two if the number is even or

  • multiply by 3 and add 1 if the number is odd.

The Collatz conjecture states that this sequence always terminates at 1. For example, the sequence generated by 23 is:

23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1

Write a Python program that takes a global variable n and uses a timer callback to repeatedly apply the rule above to n. Use the code from the previous question as a template. I suggest that your code prints out the sequence of numbers generated by this rule. Run this program for n = 217. What is the largest number in the sequence generated by this starting value?

To test your code, starting at n = 23 generates a sequence with a maximum value of 160.

Enter answer here:\


try:
    import simplegui
except ModuleNotFoundError:
    import simplequi as simplegui

# global state

n = 0
iteration = 0
max_iterations = 200
greatest_n = 0

# helper functions

def init(start):
    """Initializes n."""
    global n
    n = start
    print("Input is", n)


def get_next(current):
    """??? Part of mystery computation."""
    if current % 2 == 0:
        current //= 2
    else:
        current *= 3
        current += 1
    return current


# timer callback
def update():
    """??? Part of mystery computation."""
    global iteration, n, greatest_n
    iteration += 1
    # Stop iterating after max_iterations or n == 1
    if iteration >= max_iterations or n == 1:
        timer.stop()
        print("\nOutput is", n)
        print("Greatest n is", greatest_n)
    else:
        print(n, end=' ')
        n = get_next(n)
        if n > greatest_n:
            greatest_n = n

# register event handlers

timer = simplegui.create_timer(1, update)

# start program

init(217)
timer.start()

Output:

Input is 217
217 652 326 163 490 245 736 368 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2
Output is 1
Greatest n is 736

Question 9#

CodeSkulptor runs your Python code by converting it into Javascript when you click the “Run” button and then executing this Javascript in your web browser. Open this example and run the provided code. If the SimpleGUI frame is spawned as a separate window, you should see an animation of an explosion in the canvas for this frame. If the SimpleGUI frame is spawned as a separate tab on top of the existing window containing the code (as happens in some browser configurations), the animation will “freeze” and a single static image is displayed. (If the SimpleGUI frame spawns as a separate window, you can also cause the animation to freeze by opening a new tab on top of the code window.)

As explained in the FAQ (check the Resources tab on the left), what is the explanation for this behavior?

Javascript and Python are incompatible languages. As a result, the Python in one tab can’t run at the same time as the Javascript in the SimpleGUI frame.
To save resources, modern browsers only execute the Javascript associated with the topmost tab of a window. The animation freezes since the code tab and its associated Javascript is no longer the topmost tab.
Modern browser don’t support running Javascript in multiple windows simultaneously. This situation causes the animation to freeze. \


To save resources, modern browsers only execute the Javascript associated with the topmost tab of a window. The animation freezes since the code tab and its associated Javascript is no longer the topmost tab. \