分享

Python 1000道练习题(4)

 知识情报院 2022-02-21

Python 1000 道练习题(4)


1.给定一个列表输出星号直方图

def histogram( items ):
    for n in items:
        output = ''
        times = n
        while( times > 0 ):
          output += '*'
          times = times - 1
        print(output)

histogram([2365])

2.给定一个列表输出列表元素组成的字符串

def concatenate_list_data(list):
    result= ''
    for element in list:
        result += str(element)
    return result

print(concatenate_list_data([15122]))

3.给定一个列表输出偶数,如果遇到 237,则停止输出

numbers = [
    38646247418907344236375823566597978328615953345,
    399162758219918237412566826248866950626949687217,
    81567104585122489289476755381379843831445742717,
    958,743527
    ]

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(1217))
print(gcd(46))

7.给定 2 个数,输出最小公倍数

def lcm(x, y):
   if x > y:
       z = x
   else:
       z = y

   while(True):
       if((z % x == 0and (z % y == 0)):
           lcm = z
           break
       z += 1

   return lcm
print(lcm(46))
print(lcm(1517))

8.给定 2 个数字,求解 (x + y) * (x + y)

x, y = 43
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 = [40]
p2 = [66]
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 练习题;大家都学会了吗?

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多