Please write a program to randomly print a integer number between 7 and 15 inclusive.
Use random.randrange() to a random integer in a given range.
Solution:
import random
print random.randrange(7,16)
Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
Use zlib.compress() and zlib.decompress() to compress and decompress a string.
Solution:
import zlib
s = 'hello world!hello world!hello world!hello world!'
t = zlib.compress(s)
print t
print zlib.decompress(t)
'''Solution by: anas1434
'''
s = 'hello world!hello world!hello world!hello world!'
# In Python 3 zlib.compress() accepts only DataType <bytes>
y = bytes(s, 'utf-8')
x = zlib.compress(y)
print(x)
print(zlib.decompress(x))
Please write a program to print the running time of execution of "1+1" for 100 times.
Use timeit() function to measure the running time.
Main author's Solution: Python 2
from timeit import Timer
t = Timer("for i in range(100):1+1")
print t.timeit()
My Solution: Python 3
import datetime
before = datetime.datetime.now()
for i in range(100):
x = 1 + 1
after = datetime.datetime.now()
execution_time = after - before
print(execution_time.microseconds)
OR
import time
before = time.time()
for i in range(100):
x = 1 + 1
after = time.time()
execution_time = after - before
print(execution_time)
Please write a program to shuffle and print the list [3,6,7,8].
Use shuffle() function to shuffle a list.
Main author's Solution: Python 2
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print li
My Solution: Python 3
import random
lst = [3,6,7,8]
random.shuffle(lst)
print(lst)
OR
import random
# shuffle with a chosen seed
lst = [3,6,7,8]
seed = 7
random.Random(seed).shuffle(lst)
print(lst)
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"].
Use list[index] notation to get a element from a list.
Main author's Solution: Python 2
subjects=["I", "You"]
verbs=["Play", "Love"]
objects=["Hockey","Football"]
for i in range(len(subjects)):
for j in range(len(verbs)):
for k in range(len(objects)):
sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
print sentence
My Solution: Python 3
subjects=["I", "You"]
verbs=["Play", "Love"]
objects=["Hockey","Football"]
for sub in subjects:
for verb in verbs:
for obj in objects:
print("{} {} {}".format(sub,verb,obj))
'''Solution by: popomaticbubble
'''
import itertools
subject = ["I", "You"]
verb = ["Play", "Love"]
objects = ["Hockey","Football"]
sentence = [subject, verb, objects]
n = list(itertools.product(*sentence))
for i in n:
print(i)
'''Solution by: lcastrooliveira
'''
from itertools import product
def question_79():
subject = ["I", "You"]
verb = ["Play", "Love"]
object = ["Hockey", "Football"]
prod = [p for p in product(range(2), repeat=3)]
for combination in prod:
print(f'{subject[combination[0]]} {verb[combination[1]]} {object[combination[2]]}')
question_79()