CMU 15-112: Fundamentals of Programming and Computer Science
- These exercises will help you prepare for writing-session2,
which is on Thu 23-Jan, and which will contain a randomly-chosen
subset of exercises from among these.
- Unlike the hw, you may work collaboratively on these practice exercises.
- That said, during the actual writing session on Thursday you
must work alone, and without any notes or access to the web or other
- To start:
- Create a folder named 'writing_session2_practice'
- Download all three of these files into that folder:
- Edit writing_session2_practice.py
- Do not use strings, lists, or recursion in this unit.
- Do not hardcode the test cases in your solutions.
Write the function digitCount(n) that takes a possibly-negative int and returns the number of digits in it. So, digitCount(12323) returns 5, digitCount(0) returns 1, and digitCount(-111) returns 3. One way you could do this would be to return len(str(abs(n))), but you cannot do that, since you may not use strings here! This can be solved with logarithms, but seeing as this is the "loops unit", you should instead simply repeatedly remove the ones digit until you cannot.
- gcd(m, n)
[Note: to receive any credit, you must solve this problem
using Euclid's algorithm, and by no other means.
In particular, do not just loop through all integers
less than min(m,n) and find the common factors that way --
it is much too slow! Also, do not use math.gcd!]
According to Euclid, the greatest
common divisor, or gcd, can be found like so:
gcd(x,y) == gcd(y, x%y)
We can use that to quickly find gcd's. For example:
gcd(270,250) == gcd(250, 20) # 270 % 250 == 20
== gcd(20, 10) # 250 % 20 == 10
== gcd(10, 0) # 20 % 10 == 0
When we get to gcd(x,0), the answer is x. So gcd(270, 250)
is 10. With this in mind, write the function gcd(x,y) that
takes two positive integers x and y and returns their gcd
using Euclid's gcd algorithm.
Write the function hasConsecutiveDigits(n) that takes a possibly- negative int value n and returns True if that number contains two consecutive digits that are the same, and False otherwise.
- nthPrime(n) with fasterIsPrime(n)
Write the function nthPrime(n) using fasterIsPrime(n). This
is straight from the course notes!
Write the function nthAdditivePrime(n) that takes a non-negative
int n and returns the nth Additive Prime, which is a prime number
such that the sum of its digits is also prime. For example,
113 is prime and 1+1+3==5 and 5 is also prime, so 113 is an Additive
- drawDashedLine(canvas, width, height, dashLength)
Write the function drawDashedLine(canvas, width, height, dashLength) that
takes a canvas, width, height,
and a positive dashLength,
and draws a horizontal dashed line across the
middle of the canvas, starting on the left edge, made up of a bunch of small
lines of length dashLength followed by gaps also of length dashLength.