Problem 2: Python 3
Implement a function called gee_whiz that does the following: given argument n, a positive integer, it returns a list of n tuples corresponding to the numbers 1 through n (both inclusive): the tuple for the number k consists of k as the first component, and exactly one of the following strings as the second:
• the string 'two!' if k is divisible by 2
• the string 'three!' if k is divisible by 3
• the string 'five!' if k is divisible by 5
• the string 'two!three!' if k is divisible by 2 and 3
• the string 'three!five!' if k is divisible by 3 and 5
• the string 'two!five!' if k is divisible by 2 and 5
• the string 'two!three!five' if k is divisible by 2, 3 and 5 • the
empty string otherwise
The most specific condition applies, e.g. if k is 12, the corresponding string is “two!three!”. For example, the function call
gee_whiz(30) returns the list of 30 tuples (not all shown) below:
Hint: You should be able to do this with fewer than 8 conditions inside the loop. Do not modify the doctests.
def gee_whiz(n):
"""Returns list of n tuples of the form (k, <string_k>)
Args:
n (int >=0)
>>> gee_whiz(6)
[(1, ''), (2, 'two!'), (3, 'three!'), (4, 'two!'), (5, 'five!'),
(6, 'two!three!')]
>>> a = gee_whiz(20)
>>> a[14]
(15, 'three!five!')
"""
#code here
Python code:
#initializing gee_whiz function
def gee_whiz(n):
#initializing list to store tuples
lis=[]
#looping from 1 to n(inclusive)
for i in range(1,n+1):
#checking if number is
divisible by 2,3,5
if(i%2==0 and i%3==0 and
i%5==0):
#adding to lis, tuple for divisible by 2,3,5
lis.append((i,'two!three!five'))
#checking if number is
divisible by 2,5
elif(i%2==0 and
i%5==0):
#adding to lis, tuple for divisible by 2,5
lis.append((i,'two!five!'))
#checking if number is
divisible by 3,5
elif(i%3==0 and
i%5==0):
#adding to lis, tuple for divisible by 3,5
lis.append((i,'three!five!'))
#checking if number is
divisible by 2,3
elif(i%2==0 and
i%3==0):
#adding to lis, tuple for divisible by 2,3
lis.append((i,'two!three!'))
#checking if number is
divisible by 2
elif(i%2==0):
#adding to lis, tuple for divisible by 2
lis.append((i,'two!'))
#checking if number is
divisible by 3
elif(i%3==0):
#adding to lis, tuple for divisible by 3
lis.append((i,'three!'))
#checking if number is
divisible by 5
elif(i%5==0):
#adding to lis, tuple for divisible by 5
lis.append((i,'five!'))
else:
#adding to lis, tuple for divisible by none
lis.append((i,''))
#retuning the list
return lis
#calling gee_whiz function printing the list for a sample value
6
print(gee_whiz(6))
Screenshot:
Output:
Get Answers For Free
Most questions answered within 1 hours.