Python打卡Day19
Question 75
Question
Please write a program to randomly print a integer number between 7 and 15 inclusive.
Hints
Use random.randrange() to a random integer in a given range.
Solution:
1import random
2print random.randrange(7,16)
Question 76
Question
Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
Hints
Use zlib.compress() and zlib.decompress() to compress and decompress a string.
Solution:
1import zlib
2s = 'hello world!hello world!hello world!hello world!'
3t = zlib.compress(s)
4print t
5print zlib.decompress(t)
1'''Solution by: anas1434
2'''
3s = 'hello world!hello world!hello world!hello world!'
4# In Python 3 zlib.compress() accepts only DataType <bytes>
5y = bytes(s, 'utf-8')
6x = zlib.compress(y)
7print(x)
8print(zlib.decompress(x))
Question 77
Question
Please write a program to print the running time of execution of "1+1" for 100 times.
Hints
Use timeit() function to measure the running time.
Main author's Solution: Python 2
1
2from timeit import Timer
3t = Timer("for i in range(100):1+1")
4print t.timeit()
My Solution: Python 3
1import datetime
2
3before = datetime.datetime.now()
4for i in range(100):
5 x = 1 + 1
6after = datetime.datetime.now()
7execution_time = after - before
8print(execution_time.microseconds)
OR
1import time
2
3before = time.time()
4for i in range(100):
5 x = 1 + 1
6after = time.time()
7execution_time = after - before
8print(execution_time)
Question 78
Question
Please write a program to shuffle and print the list [3,6,7,8].
Hints
Use shuffle() function to shuffle a list.
Main author's Solution: Python 2
1
2from random import shuffle
3li = [3,6,7,8]
4shuffle(li)
5print li
My Solution: Python 3
1import random
2
3lst = [3,6,7,8]
4random.shuffle(lst)
5print(lst)
OR
1import random
2
3# shuffle with a chosen seed
4lst = [3,6,7,8]
5seed = 7
6random.Random(seed).shuffle(lst)
7print(lst)
Question 79
Question
Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].
Hints
Use list[index] notation to get a element from a list.
Main author's Solution: Python 2
1
2subjects=["I", "You"]
3verbs=["Play", "Love"]
4objects=["Hockey","Football"]
5for i in range(len(subjects)):
6 for j in range(len(verbs)):
7 for k in range(len(objects)):
8 sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
9 print sentence
My Solution: Python 3
1subjects=["I", "You"]
2verbs=["Play", "Love"]
3objects=["Hockey","Football"]
4
5for sub in subjects:
6 for verb in verbs:
7 for obj in objects:
8 print("{} {} {}".format(sub,verb,obj))