CMU 15-112 Spring 2018: Fundamentals of Programming and Computer Science
Colab 1 (Due Thursday 18-Jan, at 10pm)




  1. isPerfectSquare(n) [15pts]
    Write the function isPerfectSquare(n) that takes a possibly-non-int value, and returns True if it is an int that is a perfect square (that is, if there exists an integer m such that m**2 == n), and False otherwise. Do not crash on non-ints nor on negative ints.

  2. perfectSquareHandler() [15pts]
    Write the function perfectSquareHandler() that does not take any parameters and does not return any values. Instead, it asks the user to input a number, then prints whether or not that number is a perfect square. You must use the specific prompts shown in the examples below to pass the test cases (where the bolded numbers are user input), so you should copy the prompts directly into your code to avoid typos. Of course, your program should be able to handle any integer, not just 4 and 7.

    Enter a number:4 The number 4 is a perfect square
    Enter a number:7 The number 7 is not a perfect square

  3. nearestOdd(n) [25pts]
    Write the function nearestOdd(n) that takes an int or float n, and returns as an int value the nearest odd number to n. In the case of a tie, return the smaller odd value.

  4. rectanglesOverlap(x1, y1, w1, h1, x2, y2, w2, h2) [25pts]
    A rectangle can be described by its left, top, width, and height. This function takes two rectangles described this way, and returns True if the rectangles overlap at all (even if just at a point), and False otherwise.

    Note: here we will represent coordinates the way they are usually represented in computer graphics, where (0,0) is at the left-top corner of the screen, and while the x-coordinate increases while you head right, the y-coordinate increases while you head down. Yes, up is down! This is quite common in computer graphics, and is how Tkinter and Brython in particular both work.

  5. getKthDigit(n, k) [10pts]
    Write the function getKthDigit(n, k) that takes a possibly-negative int n and a non-negative int k, and returns the kth digit of n, starting from 0, counting from the right. So:
       getKthDigit(789, 0) returns 9
       getKthDigit(789, 2) returns 7
       getKthDigit(789, 3) returns 0
       getKthDigit(-789, 0) returns 9

  6. setKthDigit(n, k, d=0) [10pts]
    Write the function setKthDigit(n, k, d=0) that takes three integers -- n, k, and d -- where n is a possibly-negative int, k is a non-negative int, and d is a non-negative single digit (between 0 and 9 inclusive) with a default value of 0. This function returns the number n but with the kth digit replaced with d. Counting starts at 0 and goes right-to-left, so the 0th digit is the rightmost digit. For example:
       setKthDigit(468, 0, 1) returns 461
       setKthDigit(468, 1, 1) returns 418
       setKthDigit(468, 2, 1) returns 168
       setKthDigit(468, 3, 1) returns 1468
       setKthDigit(468, 1) returns 408