Computer Science 15-112
Class Notes:  Quiz2 Practice


Read these instructions first!
  1. onesDigit(n)
    Write a function that takes a possibly-negative integer and returns its ones digit (as a non-negative value between 0 and 9 inclusive).
     
  2. tensDigit(n)
    Write a function that takes a possibly-negative integer and returns its tens digit (as a non-negative value between 0 and 9 inclusive).  You must deal with leading 0's properly for numbers less than 10.
     
  3. eggCartons(eggs)
    Write a program that reads in a non-negative number of eggs, and prints the number of egg cartons required to hold that many eggs (given that each egg carton holds one dozen eggs, and you cannot buy fractional egg cartons). Be sure your program works for multiples of 12, including 0.
     
  4. militaryTimeToStandardTime(hour)
    Write a program that reads in an integer between 0 and 23, representing the hour in military time, and prints the same hour in standard time. For example, 17 is 5 o'clock.
     
  5. triangleArea(base, height)
    Write a program that reads in 2 non-negative integers, the width and height of a triangle, and prints the area of that triangle (using integer division).  You may assume the input values are non-negative.  Thought question:  Why won't this work:
        int area = 1/2*width*height;
     
  6. fabricYards(inches)
    Fabric must be purchased in whole yards.  Write a function that takes the number of inches of fabric desired, and returns the smallest number of whole yards of fabric that must be purchased.  So, for example, to purchase 72 inches you need 2 yards, but to purchase 73 inches you need 3 yards.
     
  7. fabricExcess(inches)
    Write a function that takes the number of inches of fabric desired and returns the number of inches of excess fabric that must be purchased (as purchases must be in whole yards).  Hint: you may want to use fabricYards, which you just wrote!
     
  8. nearestBusStop(street)
    Write a function that takes a non-negative street number, and returns the nearest bus stop to the given street, where buses stop every 8th street, including street 0, and ties go to the lower street, so the nearest bus stop to 12th street is 8th street, and the nearest bus stop to 13 street is 16th street.
     
  9. dayOfWeek(month, day, year)
    Write a function that takes a date represented by three integers, the month (1-12), the day (1-31), and the year, and returns an integer representing the day-of-week for that date, where Sunday is 1, Monday is 2, and so on, and Saturday is 7.

    While there are several ways to do this, you must use this formula (from the most-excellent web site mathforum.org):
          N = d + 2m + [3(m+1)/5] + y + [y/4] - [y/100] + [y/400] + 2
    Then the remainder when you divide N by 7 is the day-of-week, where Saturday is 0 and Friday is 6.  Note that these values for the days are not quite the same as those returned by this method.

    Here is mathforum's description of the formula: "d is the number or the day of the month, m is the number of the month, and y is the year. The brackets around the divisions mean to drop the remainder and just use the integer part that you get.  Also, a VERY IMPORTANT RULE is the number to use for the months for January and February. The numbers of these months are 13 and 14 of the PREVIOUS YEAR. This means that to find the day of the week of New Year's Day [of 1998], 1/1/98, you must use the date 13/1/97."

    Note: you must make the adjustment to the month and year when appropriate.  So, for example, the date of New Year's Day for 1998 would be obtained in the natural way:  dayOfWeek(1, 1, 1998).  You may ignore the cases where the month, day, or year are out of bounds.

    def testDayOfWeek():
        print "Testing dayOfWeek... ",
        # On 2/5/2006, the Steelers won Super Bowl XL on a Sunday!
        assert(dayOfWeek(2, 5, 2006) == 1)
        # On 6/15/1215, the Magna Carta was signed on a Monday!
        assert(dayOfWeek(6, 15, 1215) == 2)
        # On 3/11/1952, the author Douglas Adams was born on a Tuesday!
        assert(dayOfWeek(3, 11, 1952) == 3)
        # on 4/12/1961, Yuri Gagarin became the first man in space, on a Wednesday!
        assert(dayOfWeek(4, 12, 1961) == 4)
        # On 7/4/1776, the Declaration of Independence was signed on a Thursday!
        assert(dayOfWeek(7, 4, 1776) == 5)
        # on 1/2/1920, Isaac Asimov was born on a Friday!
        assert(dayOfWeek(1, 2, 1920) == 6)
        # on 10/11/1975, Saturday Night Live debuted on a Saturday (of course)!
        assert(dayOfWeek(10, 11, 1975) == 7)
        print "Passed all tests!"
     
  10. integerSquareRoot(x)
    Write a function that takes a possibly-floating-point non-negative number and returns the integer value that is nearest to its actual square root.
     
  11. celsiusToFahrenheight(degrees)
    Write a function that takes some number of degrees Fahrenheit and returns that same temperature in Celsius, and rounded to the nearest tenth.
     
  12. numberOfPoolBalls(rows)
    Write a function that takes a non-negative integer, the number of rows in a rack of pool balls (where the first row has one ball, the second row has two balls, and so on), and returns the total number of pool balls in the rack.
     
  13. numberOfPoolBallRows(balls)
    Write a function that takes a non-negative integer, the number of balls to place in a pool ball rack (as just described), and returns the fewest number of rows required to hold that many balls.  For example, you need 2 rows to hold 2 pool balls (with extra room for one more ball).
     
  14. almostEqual(d1, d2)
    Write a function that takes two floating-point numbers and returns True if they are almost equal (within some small epsilon, say 0.0000001) and False otherwise.  Be sure to handle the cases where d1>d2 and also where d1<d2.
     
  15. xIntercept(m, b)
    Write a function that takes two numbers, m and b, describing the line y = mx+b, and returns the x intercept of that line (that is, the value for x such that f(x) is 0).
     
  16. yValueOfLineIntersection(m1, b1, m2, b2)
    Write a function that takes 4 numbers, m1, b1, m2, and b2, describing two lines y = m1x + b1 and y = m2x + b2, and returns the y value of the point of intersection of the two lines.  If the lines do not intersect in a single point, return None.  You may want to call almostEqual to help you determine if the lines do not intersect in a single point, because the slopes are not guaranteed to be integers, and floating point numbers are approximate.
     
  17. hypotenuse(a, b)
    Write a function that takes two non-negative numbers, a and b, representing the sides of a right triangle, and returns the length of the hypotenuse.
     
  18. distance(x1, y1, x2, y2)
    Write a function that takes four numbers representing the two points (x1, y1) and (x2, y2) and returns the distance between those points.
     
  19. standardDeviation(a, b, c)
    Write a function that takes three numbers and returns their standard deviation.
     
  20. isRightTriangle(a, b, c)
    Write a function that takes three numbers and returns True if they can form the sides of a right triangle, and False otherwise.
     
  21. isPerfectIntSquare(n)
    Write a function that takes a possibly-negative integer and returns True if it is a perfect square (the square of another integer) and False otherwise.
     
  22. areCollinear(x1, y1, x2, y2, x3, y3)
    Write a function that takes six integer values representing three points (x1,y1), (x2,y2), and (x3,y3), and returns True if those points all lie on a single line, and False otherwise.
     
  23. isTriangular(n)
    Write a function that takes a possibly-negative integer and returns True if is triangular, and False otherwise.  A triangular number is the sum of the first K positive integers for some K.  So these numbers are 1, 3, 6, 10, 15, 21, ...
     
  24. kthDigit(x, k)
    Write a function that takes a possibly-negative integer x and a non-negative integer k and returns the kth digit (counting from the right) of x.  For example, kthDigit(9876, 0) returns 6, and kthDigit(9876, 2) returns 8, and kthDigit(9876, 4) returns 0.
     
  25. getKthLowestNybble(n, k)
    Write a function that takes a possibly-negative integer n and a non-negative integer k, and returns the value of the kth lowest nybble of the value n as represented in two's complement.  Note that a nybble is 4 bits, and nybble 0 would be the rightmost or least-significant 4 bits of n.
     
  26. setKthLowestNybble(n, k, value)
    Write a function that takes three values -- a possibly-negative integer n, a non-negative integer k, and an integer value between 0 and 15 -- and returns the value obtained by replacing the kth lowest nybble of n with 4 bits from the given value.
     
  27. nthFibonacciNumber(n)
    Write the function nthFibonacciNumber that takes a positive integer n and (without using loops) returns the nth Fibonacci number, so:
       nthFibonacciNumber(1) returns 1
       nthFibonacciNumber(2) returns 1
       nthFibonacciNumber(3) returns 2
       nthFibonacciNumber(4) returns 3
       nthFibonacciNumber(5) returns 5
       nthFibonacciNumber(6) returns 8
    Hint: look at formula (8) here, where phi (in the numerator) is the Golden Ratio. Cool!
     
  28. isGreen(rgba)
    Write the function isGreen that takes a single 32-bit rgba value (which you may assume is an int value) and returns True if it represents some pure shade of green, and False otherwise. That is, return True if the green value is positive, both red and blue are zero, and the alpha is positive.
     
  29. getColorFamily(rgba)
    Write the function getColorFamily that takes a single 32-bit rgba value (which you may assume is an int value) and returns 1 if that value is "mostly red" (that is, if the red value is greater than both the blue value and the green value), 2 if it is "mostly green", 3 if it is "mostly blue", and 4 otherwise (for example, if there is just as much red as green).
      
  30. challenge:  findIntRootsOfCubic(a, b, c, d)
    Write the function findIntRootsOfCubic that takes the real (float) coefficients a, b, c, d of a cubic equation of this form:
         y = ax3 + bx2 + cx + d
    You are guaranteed the function has 3 real roots, and in fact that the roots are all integers.  Your function should return these 3 roots in increasing order.  How does a function return multiple values?  Like so:
        return root1, root2, root3
    To get started, you'll want to read about Cardano's cubic formula here (great stuff!).  Then, from that page, use this formula:
     
    x   =   {q + [q2 + (r-p2)3]1/2}1/3   +   {q - [q2 + (r-p2)3]1/2}1/3   +   p

    where:

    p = -b/(3a),   q = p3 + (bc-3ad)/(6a2),   r = c/(3a)

    This isn't quite as simple as it seems, because your solution for x will not only be approximate (and not exactly an int, so you'll have to do something about that), but it may not even be real!  Though the solution is real, the intermediate steps may include some complex values, and in these cases the solution will include a (possibly-negligibly-small) imaginary value.  So you'll have to convert from complex to real (see hint above), and then convert from real to int.

    Great, now you have one root.  What about the others?  Well, we can divide the one root out and that will leave us with a quadratic equation, which of course is easily solved.  A brief, clear explanation of this step is provided here.  Don't forget to convert these to int values, too!

    So now you have all three int roots.  Great job!  All that's left is to sort them.  Now, if this were later in the course, you could put them in a list and call a built-in function that will sort for you.  But it's not, so you can't.  Instead, figure out how to sort these values using the limited built-in functions and arithmetic available this week.  Then just return these 3 values and you're done.

    Good luck!!!


carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem