Python 1000 道练习题(4)
1.给定一个列表输出星号直方图
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])
2.给定一个列表输出列表元素组成的字符串
def concatenate_list_data(list):
result= ''
for element in list:
result += str(element)
return result
print(concatenate_list_data([1, 5, 12, 2]))
3.给定一个列表输出偶数,如果遇到 237,则停止输出
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
for x in numbers:
if x == 237:
print(x)
break;
elif x % 2 == 0:
print(x)
4.给定 2 个列表,输出列表 1 中且只存在列表 1 中的元素
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print(color_list_1.difference(color_list_2))
5.给定三角形底和高输出面积
b = int(input("请输入底边长 : "))
h = int(input("请输入高 : "))
area = b*h/2
print("三角形面积为 : ", area)
6.给定 2 个数,输出最大公约数
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
for k in range(int(y / 2), 0, -1):
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
print(gcd(12, 17))
print(gcd(4, 6))
7.给定 2 个数,输出最小公倍数
def lcm(x, y):
if x > y:
z = x
else:
z = y
while(True):
if((z % x == 0) and (z % y == 0)):
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
print(lcm(15, 17))
8.给定 2 个数字,求解 (x + y) * (x + y)
x, y = 4, 3
result = x * x + 2 * x * y + y * y
print("({} + {}) ^ 2) = {}".format(x, y, result))
8.给定本金、利率、年限,输出本息和
amt = 10000
int = 3.5
years = 7
future_value = amt*((1+(0.01*int)) ** years)
print(round(future_value,2))
9.给定两个点的坐标,输出两点之间的距离
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)
10.检查本地文件是否存在(注意:如果文件与 Python 脚本不在同一文件夹,需将路径写全)
import os.path
open('abc.txt', 'w')
print(os.path.isfile('abc.txt'))
今天的教程,主要学习了:10 道 Python 练习题;大家都学会了吗?