COGS 501 Quiz
-
Define a function that takes a positive integer and returns the sum of its digits. Two mathematical operations that might be useful here are modulo and division. You get 2pts bonus credit if you solve the problem using
proc_seq.Save the definition of
proc_seqfrom here in a file namedrepo.pyin the same directory as the code you write for solving the problem. Now, you can haveproc_seqavailable for use by importing it fromrepo, byfrom repo import proc_seq. Here is the solution withproc_seq:from repo import proc_seq def sum_digits(n): """Return the sum of the digits of n in decimal representation. >>> sum_digits(0) 0 >>> sum_digits(123) 6 >>> sum_digits(4096) 19 """ def sequencer(n): return n // 10 def alive(n): return n > 0 def update(state, n): return state + (n % 10) return proc_seq(n, sequencer, alive, update, 0) -
[3pts] You are asked to define a function to compute the sum of all the even numbers in the Collatz sequence seeded by $n$. You are asked to use
proc_seq. Assume you have thecollatzfunction defined. Write the update function you would pass toproc_seqas parameter.Add the collatz function to your
repo.py.from repo import proc_seq, collatz def sum_even_collatz(n): """Return the sum of the even numbers in the Collatz sequence seeded by n. >>> sum_even_collatz(8) 14 >>> sum_even_collatz(3) 40 """ def sequencer(n): return collatz(n) def alive(n): return n != 1 def update(state, n): if n % 2 == 0: return state + n else: return state return proc_seq(n, sequencer, alive, update, 0)