Python ------- Experiment 5 Homework 1

1. Short answer questions (7 questions in total, 120.0 points)

1 Input the upper bottom, lower bottom and height of the trapezoid, design the function, and output the area of ​​the trapezoid.

my answer:

def S(a,b,h):

    if a>0 and b>0 and h>0:

        return (a+b)*h/2

a =int(input('请输入梯形上底a:'))

b = int(input('请输入梯形下底b:'))

h = int(input('请输入梯形下底h:'))

print('输出梯形的面积:',S(a,b,h))

Operation result:

Please enter the trapezoid upper bottom a: 2

Please enter the bottom of the trapezoid b: 8

Please enter the trapezoidal bottom h: 2

Area of ​​output trapezoid: 10.0

2 Use the function call method to find 1! +2! +… + N!

my answer:

x = int(input("请输入n(不小于1):"))

def f(n):

    a = 0

    Sum = 0

    for i in range (1,n+1):

            a+=i

            Sum+=a

    print('1!+2!+...+ %d!=%d'% (i,Sum))

f(x)

Operation result:

Please enter n (preferably greater than 2): 4

1!+2!+…+ 4!=20

3 Write a function, input three numbers as the three sides of the triangle, and calculate the area of ​​the triangle. Helen formula: p = (x + y + z) / 2 S = sqrt (p * (px) (py) (pz))

my answer:

def S(x,y,z):

    p=(x+y+z)*0.5

    w = (p*(p-x)*(p-y)*(p-z))**0.5

    print("三角形的面积为:",w)

a = int(input("请输入三角形的边长a:"))

b = int(input("请输入三角形的边长b:"))

c = int(input("请输入三角形的边长c:"))

S(a,b,c)

Operation result:

Please enter the triangle length a: 3

Please enter the side length b of the triangle: 4

Please enter the side length c of the triangle: 5

The area of ​​the triangle is: 6

4
定义函数接收年份和月份,返回对应月份有多少天。

(20.0 points)
Correct answer:

def get_days_in_month(year,month):

    if month == 4 or month == 6 or month == 9 or month == 11:

        return 30

    elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:

        return 31

    else:

        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:

            return 29

        else:

            return 28



year = int(input("请输入年份:"))

month = int(input("请输入月份:"))

days = get_days_in_month(year,month)

print(year, "年", month, "月", "有",days,"天")

my answer:

def year_month(year,month):

    a = [0,31,29,31,30,31,30,31,31,30,31,30,31]

    b = [0,31,28,31,30,31,30,31,31,30,31,30,31]

    if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):

        print('该月有%d天' % (a[month]))

    else:

        print('该月有%d天' % (b[month]))

y = int(input("请输入年份:"))

m = int(input("请输入月份:"))

year_month(y,m)

Operation result:

Please enter the year: 1999

Please enter the month: 6

There are 30 days in the month

5 Write a function to receive a time (hours, minutes, and seconds) and return the next second of that time.

(20.0 points)
Correct answer:

def get_next_second(hour,minute,second):

    hour = int(hour)

    minute = int(minute)

    second = int(second)



    second += 1

    second = second % 60

    if second == 0:

        minute += 1

    minute = minute % 60

    if minute == 0:

        hour += 1

    hour = hour % 24

    return [hour,minute,second]

time = input("请输入时间:")

time = time.split(" ")

print("下一秒的时间是:",get_next_second(time[0],time[1],time[2]))

my answer:

import datetime

def time(time):

    time=datetime.datetime.strptime(time,"%H:%M:%S")+datetime.timedelta(seconds=1)

    print("下一秒的时间是:",time.strftime("%H:%M:%S"))

a=input("请以xx:xx:xx格式输入时间:")

time(a)

Operation result:

Please enter the time in xx: xx: xx format: 22:11:10

The next second is: 22:11:11

6
编写函数,实现冒泡排序算法。

(20.0 points)
Correct answer:

from random import randint



def bubbleSort(lst, reverse=False):

    length = len(lst)

    for i in range(0, length):

        flag = False

        for j in range(0, length-i-1):

            #比较相邻两个元素大小,并根据需要进行交换

            #默认升序排序

            exp = 'lst[j] > lst[j+1]'

            #如果reverse=True则降序排序

            if reverse:

                exp = 'lst[j] < lst[j+1]'

            if eval(exp):

                lst[j], lst[j+1] = lst[j+1], lst[j]

                #flag=True表示本次扫描发生过元素交换

                flag = True

        #如果一次扫描结束后,没有发生过元素交换,说明已经按序排列

        if not flag:

            break

lst = [randint(1, 100) for i in range(20)]

print('排序前:\n', lst)

bubbleSort(lst, True)

print('排序后:\n', lst)

my answer:

def sort(a):

    L = list(map(int, a.split()))

    for i in range(len(L)):

        for k in range(len(L)-1):

            if L[k]> L[k+1] :

                t = L[k]

                L[k] = L[k+1]

                L[k+1] = t

    return L

a = input("请输入要排序的数:")

l=sort(a)

print('排序后:', l)

Operation result:

Please enter the number to sort: 9 8 2 4 3 5

After sorting: [2, 3, 4, 5, 8, 9]

7 Optional questions: Write a program to simulate a guessing game. When the program is running, the system generates a random number, and then prompts the user to make a guess, and makes the necessary prompts according to the user input (guessed, too large, too small), if the guess is correct, the program is terminated early, and if the number is used up Still not guessing correctly, it prompts the end of the game and gives the correct answer.

(20.0 points)
Correct answer:

from random import randint

def guessNumber(maxValue=10, maxTimes=3):

# 随机生成一个整数

    value = randint(1,maxValue)

    for i in range(maxTimes):

        prompt = 'Start to GUESS:' if i==0 else 'Guess again:'

# 使用异常处理结构,防止输入不是数字的情况

        try:

            x = int(input(prompt))

        except:

            print('Must input an integer between 1 and ', maxValue)

        else:

            if x == value:

# 猜对了

                print('Congratulations!')

                break

            elif x > value:

                print('Too big')

            else:

                print('Too little')

    else:

# 次数用完还没猜对,游戏结束,提示正确答案

        print('Game over. FAIL.')

        print('The value is ', value)

guessNumber()

my answer:

import  random

def guess(value,num):

    for i in range(num):

        gue = int(input("请输入猜测的数字:"))

        if gue<value:

            print("太小了")

        elif gue>value:

            print("太大了")

        else:

            print("猜对了")

            break

    if i==num-1:

        print("游戏结束,该数字为%d"%(value))



value=random.randint(0,100)

num = int(input("请输入您要猜测的次数:"))

guess(value,num)

Operation result:

Please enter the number of times you want to guess: 10

Please enter the guessed number: 4

too small

Please enter the guessed number: 50

too small

Please enter the guessed number: 80

too big

Please enter the guessed number: 65

too big

Please enter the guessed number: 57

too small

Please enter the guessed number: 61

too big

Please enter the guessed number: 59

Guess right

Published 27 original articles · praised 3 · visits 1419

Guess you like

Origin blog.csdn.net/weixin_41860600/article/details/105484425