Lecture 4 - Exercises

4A - print’s keyword arguments

  1. Which of the following is printed by: print("B", "C", "D", "BR", sep="A")

    1. BACADABR
    2. ABACADABRA
    3. ABACADABR
    4. BACADABRA
  2. What is printed by the following code?

  3. What does the following program print?

  4. Last time I asked you to prompt the user for three numbers and print their sum. The last problem asked you to print the sum without spaces between the numbers and operators. Solve this problem again using what you learned about the print function’s keyword arguments.

    Enter the first number: 4
    Enter the second number: 2.4
    Enter the third number: 8.6
    4.0+2.4+8.6=15.0

4B - Binary Representation

For your convience, here is a table of the first 8 powers of two:

2^0:   1
2^1:   2
2^2:   4
2^3:   8
2^4:  16
2^5:  32
2^6:  64
2^7: 128
  1. Convert each of the following binary numbers to decimal:
    1. 1
    2. 10
    3. 1010
    4. 1111
  2. Convert each of the following decimal numbers to binary:
    1. 32
    2. 15
    3. 28
    4. 68

Problems

  1. Write a program that prints the table of powers of two that I provided above. Use one print call per line and use the sep keyword argument.

  2. Write a program to extract the 10^ks digit from a number n, given k and n. Assume k and n are both positive integers, and n has at least k+1 digits. Hint: try using modulus and integer divison together - for example, notice that the 100’s digit of 3624 can be calculated as 3624 // 100 % 10. A couple example runs are given below:

    Enter k: 2
    Enter n: 1531
    The 100s digit of 1531 is 5
    Enter k: 0
    Enter n: 13
    The 1s digit of 13 is 3
  3. Suppose a variable p contains a positive integer. Write a Python expression that evaluates to a string containing the binary representation of 2^p - 1 with no leading zeros. For example: if p = 3, you’d give the binary for 2^3 - 1 = 7, which comes out to 111. Hint: work out a couple more examples with different values of p and see if you can find a pattern.

  4. Typically, integers are stored on computers by default using 64 bits. What’s the largest integer that can be represented using 64 bits? I recommend using a calculator (or Python!) for this one.

  5. Integers can be negative, but computer memory can’t store “+” and “-” signs, only 0s and 1s. For this reason, the decimal-to-binary integer conversion approach I presented doesn’t have any way to represent negative integers. Can you come up with an approach to represent both negative and positive integers using binary?