DUE Monday Jan 30 at 9AM. Upload to Desire 2 Learn dropbox.
Please refer to Lab 2
# solution.py
import random
"""
R-1.1
Write a short Python function, is multiple(n, m), that takes two integer values and returns True if n is a multiple of m, that is, n = mi for some integer i, and False otherwise.
"""
def is_multi(n, m):
for i in range(n):
if n == m*i:
return True
return False
"""
R-1.3
Write a short Python function, minmax(data), that takes a sequence of one or more numbers, and returns the smallest and largest numbers, in the form of a tuple of length two. Do not use the built-in functions min or max in implementing your solution.
"""
def minimaxi(data):
try:
mn = data[0]
except:
print "data is empty!"
return (None, None)
mx = mn
for i in range(1, len(data)):
if data[i] < mn:
mn = data[i]
if data[i] > mx:
mx = data[i]
return (mn, mx)
"""
R-1.11
Demonstrate how to use Python's list comprehension syntax to produce the list [1, 2, 4, 8, 16, 32, 64, 128, 256].
"""
def listcomp1():
return [2**i for i in range(0, 9)]
"""
C-1.15
Write a Python function that takes a sequence of numbers and determines if all the numbers are different from each other (that is, they are distinct).
"""
def unique_data(data):
if len(data) == len(set(data)):
return "data items are unique"
return "data items are NOT unique"
"""
C-1.18
Demonstrate how to use Python's list comprehension syntax to produce the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].
"""
def listcomp2():
return [i**2+i for i in range(0, 10)]
"""
C-1.19
Demonstrate how to use Python's list comprehension syntax to produce the list[ a , b , c ,..., z ],but without having to type all 26 such characters literally.
"""
def alphalower():
return [chr(i) for i in range(97, 97+26)]
"""
C-1.20
Python's random module includes a function shuffle(data) that accepts a list of elements and randomly reorders the elements so that each possible order occurs with equal probability. The random module includes a more basic function randint(a, b) that returns a uniformly random integer from a to b (including both endpoints). Using only the randint function, implement your own version of the shuffle function.
"""
def shuffler(data):
datalen = len(data)
for i in range(datalen):
rint = random.randint(0, datalen-1)
temp = data[i]
data[i] = data[rint]
data[rint] = temp
return data
"""Test calls"""
list_data = [4, 15, 10, 0, 5, 12, 12, 18, 5, 3]
ordered_nums = [i for i in range(10)]
print is_multi(24, 3)
print minimaxi(list_data)
print listcomp1()
print unique_data(list_data)
print listcomp2()
print alphalower()
print shuffler(ordered_nums)