Skip to content

Exercises

  1. Assign 27 to the variable a, 1027 to the variable b, and the product to the variable c. Have python output the values of all three variables.

  2. For a = 27, b = 1027, use the remainder command % to determine if 16 is a factor of ab+1.

  3. Split the string "I am Sam, Sam I am" in to a list.

  4. Given the variables planet = 'Earth' and diameter = 12742, use .format() to print the following string:

    The diameter of Earth is 12742 kilometers.

  5. Create a function that grabs the email website domain from a string in the form: user@domain.com For example, passing user@domain.com would return: domain.com.

  6. Create and print a list of integers from 50 to 100 (inclusive).

  7. From the list in Exercise 3, create a sublist consisting of (a) even integers, (b) odd integers, and (c) numbers divisible by 13.

  8. Create the two sets A=\{1,2,3,4,5,6\}, B=\{2,4,6,8,10\} and find (a) their intersection, (b) their union, and (c) their symmetric difference.

  9. Define a function sum1ToN that returns 1+2+3+...+n using the formula \(1+2+3+\cdots+n=\frac{n(n+1)}{2}\).

  10. The function below prints string obj n times:

    def printNtimes(n,obj):
        count=0
        result=''     # empty string
        while count < n:
            result += str(obj) # same as result = result + str(obj)
            count += 1
        print(result)
    
    Test it with various inputs for obj and n.
    Notice there is no return line in the function. Since we don't ask the function to return anything we could either write the last line as return, or just leave it out as we have done above. Type in print(printNtimes(3,'hello')) and describe what happens.

  11. Write a function pow4(x) that returns \(x^4\) and performs only two multiplications (and no exponentiations).

  12. Create a basic function that returns True if the word 'dog' is contained in the input string.

  13. Write a function divBy(n,m) which returns True if integer n is divisible by m, otherwise it returns False.

  14. Use lambda expressions and the filter() function to filter out words from a list that don't start with the letter 's'. For example:
    seq = ['soup','dog','salad','cat','great']
    should be filtered down to:
    ['soup','salad']

  15. Create a function getModInverse(a,m) which returns the multiplicative inverse of a modulo m, when a is relative prime to m. You may find it useful to use the xgcd() function.