Exercises
-
Assign 27 to the variable
a, 1027 to the variableb, and the product to the variablec. Have python output the values of all three variables. -
For
a = 27,b = 1027, use the remainder command%to determine if16is a factor ofab+1. -
Split the string "I am Sam, Sam I am" in to a list.
-
Given the variables
planet = 'Earth'anddiameter = 12742, use.format()to print the following string:The diameter of Earth is 12742 kilometers.
-
Create a function that grabs the email website domain from a string in the form:
user@domain.comFor example, passinguser@domain.comwould return:domain.com. -
Create and print a list of integers from 50 to 100 (inclusive).
-
From the list in Exercise 3, create a sublist consisting of (a) even integers, (b) odd integers, and (c) numbers divisible by 13.
-
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. -
Define a function
sum1ToNthat returns1+2+3+...+nusing the formula \(1+2+3+\cdots+n=\frac{n(n+1)}{2}\). -
The function below prints string
objn times:
Test it with various inputs fordef printNtimes(n,obj): count=0 result='' # empty string while count < n: result += str(obj) # same as result = result + str(obj) count += 1 print(result)objand n.
Notice there is noreturnline in the function. Since we don't ask the function to return anything we could either write the last line asreturn, or just leave it out as we have done above. Type inprint(printNtimes(3,'hello'))and describe what happens. -
Write a function
pow4(x)that returns \(x^4\) and performs only two multiplications (and no exponentiations). -
Create a basic function that returns
Trueif the word 'dog' is contained in the input string. -
Write a function
divBy(n,m)which returnsTrueif integer n is divisible by m, otherwise it returnsFalse. -
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'] -
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 thexgcd()function.