# 100题练习记录（八）

Question 71:

Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.

Hints:
Use if/elif to deal with conditions.

``````import math
def bin_search(li, element):
bottom = 0
top = len(li)-1
index = -1
while top>=bottom and index==-1:
mid = int(math.floor((top+bottom)/2.0))
#如果查找元素在中间位置
if li[mid]==element:
index = mid
#如果查找元素小于列表中部数值，则设置顶部top为mid-1
elif li[mid]>element:
top = mid-1
#如果查找元素大于列表中部数值，则设置底部bottom为mid-1
else:
bottom = mid+1
#返回对应下标值，如不存在，则输出-1
return index
#输入数组为sort排序后数组
li=[2,5,7,9,11,17,222]
print(bin_search(li,11))
print(bin_search(li,12))
``````

Question 72:

Please generate a random float where the value is between 10 and 100 using Python math module.

Hints:
Use random.random() to generate a random float in [0,1].

``````import random
f = random.random()
print(f*100)
``````

Question 73:

Please generate a random float where the value is between 5 and 95 using Python math module.

Hints:
Use random.random() to generate a random float in [0,1].

``````import random
print(random.randint(5,95)+random.random())
``````

Question 74:

Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.

Hints:
Use random.choice() to a random element from a list.

``````import random
print(random.choice([i for i in range(11) if i % 2 == 0]))
``````

Question 75:

Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 200 inclusive using random module and list comprehension.

Hints:
Use random.choice() to a random element from a list.

``````import random
print(random.choice([x for x in range(201) if x%5==0 and x%7==0]))
``````

Question 76:

Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.

Hints:
Use random.sample() to generate a list of random values.

``````import random
print(random.sample(range(100,201),5))
``````

Question 77:

Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.

Hints:
Use random.sample() to generate a list of random values.

``````import random
print(random.sample([i for i in range(100,201) if i%2 ==0],5))
``````

Question 78:

Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.

Hints:
Use random.sample() to generate a list of random values.

``````import random
print(random.sample([i for i in range(1,1001) if (i % 5 == 0) and (i % 7 == 0)],5))
``````

Question 79:

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.

``````import random
print(random.randrange(7,16))
``````

Question 80:

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.

``````import zlib
s = "hello world!hello world!hello world!hello world!"
s1 = s.encode()
print(s1)
t = zlib.compress(s1)
print(t)
s2 = zlib.decompress(t)
print(s2)
``````

Question 81:

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.

``````from timeit import Timer
t = Timer("for i in range(101):1+1")
print(t.timeit())
``````

Question 82:

Please write a program to shuffle and print the list [3,6,7,8].

Hints:
Use shuffle() function to shuffle a list.

``````from random import shuffle
li = [3,6,7,8]
shuffle(li)
#生成随机排列数组
print(li)
``````

Question 84:

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.

``````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)
``````

Question 85:
Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].

Hints:
Use list comprehension to delete a bunch of element from a list.

``````li = [5,6,77,45,22,12,24]
li = [x for x in li if x%2!=0]
print(li)
``````

Question 86:

By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].

Hints:
Use list comprehension to delete a bunch of element from a list.

``````l1 = [12,24,35,70,88,120,155]
l2 = [x for x in l1 if not (x%5==0 and x%7==0)]
print(l2)
#官方给出的方法中将能被5整除的数也进行了移除。
li = [12,24,35,70,88,120,155]
li = [x for x in li if x%5!=0 and x%7!=0]
print(li)
``````

Question 87:

By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].

Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.

``````l1 = [12,24,35,70,88,120,155]
l2 = l1[1:len(l1)-1:2]
print(l2)
#使用enumerate函数
li = [12,24,35,70,88,120,155]
li = [x for (i,x) in enumerate(li) if i%2!=0]
print(li)
``````

Question 88:

By using list comprehension, please write a program generate a 358 3D array whose each element is 0.

Hints:
Use list comprehension to make an array.

``````l1 = [[ * 8 for x in range(5)] for y in range(3)]
print(l1)
#方法二
array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
print(array)
``````

Question 89:

By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155].

Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.

``````l = [12,24,35,70,88,120,155]
l1 = [x for (i,x) in enumerate(l) if i not in (0,4,5)]
print(l1)
``````

Question 90:

By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].

Hints:
Use list’s remove method to delete a value.

``````l = [12,24,35,70,88,120,155]
l.remove(24)
print(l)
#方法二
li = [12,24,35,24,88,120,155]
li = [x for x in li if x!=24]
print(li)
``````

Question 91:

With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.

Hints:
Use set() and “&=” to do set intersection operation.

``````l1 = [1,3,6,78,35,55]
l2 = [12,24,35,24,88,120,155]
print(l1+l2)
s = set(l1+l2)
print(s)
``````

Question 92:
With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.

Hints:
Use set() to store a number of values without duplicate.

``````def remove_duplicate(l1=[]):
set1 = set()
l2 = []
for i in l1:
if i not in set1:
l2.append(i)
print(l2)
l1 = [12,24,35,24,88,120,155,88,120,155]
remove_duplicate(l1)
``````

Question 93:

Define a class Person and its two child classes: Male and Female. All classes have a method “getGender” which can print “Male” for Male class and “Female” for Female class.

Hints:
Use Subclass(Parentclass) to define a child class.

``````class Person(object):
def __init__(self):
self.gender = ""
def getGender(self):
return self.gender
class Male(Person):
def __init__(self):
self.gender = "Male"
class Female(Person):
def __init__(self):
self.gender = "Female"
m = Male()
print(m.getGender())
f = Female()
print(f.getGender())
``````

Question 94:

Please write a program which count and print the numbers of each character in a string input by console.

Example:
If the following string is given as input to the program:

abcdefgabc

Then, the output of the program should be:

a,2
c,2
b,2
e,1
d,1
g,1
f,1

Hints:
Use dict to store key/value pairs.
Use dict.get() method to lookup a key with default value.

``````s = input("请输入：")
dic = {
}
for i in s:
if i not in dic.keys():
dic[i] = 1
else:
dic[i] = dic[i] + 1
for k,v in dic.items():
print(str(k)+","+str(v))
``````

Question 95:

Please write a program which accepts a string from console and print it in reverse order.

Example:
If the following string is given as input to the program:

rise to vote sir

Then, the output of the program should be:

ris etov ot esir

Hints:
Use list[::-1] to iterate a list in a reverse order.

``````def rever(s):
s1 = s[::-1]
return s1
s = input("请输入：")
print(rever(s))
#直接使用
s = input("请输入：")
print(s[::-1])
``````

Question 96:

Please write a program which accepts a string from console and print the characters that have even indexes.

Example:
If the following string is given as input to the program:

H1e2l3l4o5w6o7r8l9d

Then, the output of the program should be:

Helloworld

Hints:
Use list[::2] to iterate a list by step 2.

``````s = input("请输入：")
s1 = s[::2]
print(s1)
``````

Question 97:

Please write a program which prints all permutations of [1,2,3]

Hints:
Use itertools.permutations() to get permutations of list.

``````import itertools
print(list(itertools.permutations([1,2,3])))
``````

Question 98:

Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?

Hint:
Use for loop to iterate all possible solutions.

``````def solve(numheads,numlegs):
ns='No solutions!'