栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python语言程序设计教程上海交通大学答案_交大Python编程基础课后答案?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python语言程序设计教程上海交通大学答案_交大Python编程基础课后答案?

本文仅供交流学习,部分代码根据练习题需求未采用函数进行直接转换。有错误或更好的方法欢迎提出。


1.列表输入输出

分别编写输入列表元素和输出列表元素的函数。设列表元素为整数。

输入:
1 2 3 4
输出:
1 2 3 4

# 输入
def input_list():
    ###########Begin###########
    n=list(map(int,input().split()))
    return n
    ###########End###########

# 输出
def output_list(mylist):
    ###########Begin###########
    for i in range(len(mylist)):
        print(mylist[i],end=" ")
    ###########End###########

mylist=input_list()
output_list(mylist)

2.统计列表元素

编写函数,计算列表的最大、最小和平均值。编写主程序,输入列表,调用函数计算最大、最小和平均值,并在主程序中显示结果。注,不能使用Python及第三方库的函数直接求。

输入:
3 5 7 1 8 2
输出:
4.3
8.0
1.0

# 输入
def input_list():
    ###########Begin###########
    n=list(map(float,input().split()))
    return n
    ###########End###########

# 输出
def output_list(mylist):
    ###########Begin###########
    import numpy as np
    print("%.1f" %np.mean(mylist))
    print("%.1f" %max(mylist))
    print("%.1f" %min(mylist))
    ###########End###########

mylist=input_list()
output_list(mylist)

3.对列表选择排序

编写函数,用选择法对列表元素排序。编写主程序,输入列表元素,调用函数排序,并在主程序中显示排序后的列表元素。注,不能使用Python及第三方库的排序函数。

输入:
1 2 8 3 5 4 7
输出:
1 2 3 4 5 7 8

# 排序
def list_sort(nums):
    ###########Begin###########
    #采用冒泡排序
    n=len(nums)
    for i in range(n):
        for j in range(0, n-i-1):
            if nums[j] > nums[j+1] :
                nums[j], nums[j+1] = nums[j+1], nums[j]
    ###########End###########

nums=list(map(int,input().split()))
list_sort(nums)
for i in range(len(nums)):
    print(nums[i],end=" ")

4.二分法查找

编写函数,用二分法在有序列表中查找元素,找到则返回下标,找不到则返回-1。编写主程序,输入列表元素,调用第3关的函数排序,输入一个数,调用本题的函数查找。

输入:
2 4 1 3
2
输出:
1

# 排序
def list_sort(nums):
    ###########Begin###########
    n=len(nums)
    for i in range(n):
        for j in range(0, n-i-1):
            if nums[j] > nums[j+1] :
                nums[j], nums[j+1] = nums[j+1], nums[j]
    ###########End###########

# 二分查找
def binarySearch(arr, l, r, x):
    ###########Begin###########
    list_sort(arr)
    
    if r>=l:
        mid=int((l+r)/2)
        if arr[mid]==x:
            return mid
        elif arr[mid] 

5.计算最大公因数

编写函数,求两个数的最大公因数。编写主程序,输入两个整数,调用函数求最大公因数,在主程序中输出最大公因数。

输入:
3 6
输出:
3

# 求最大公因数
def common_factor(a, b):
    ###########Begin###########
    if b!=0:
        return common_factor(b,a%b)
    else:
        return a
    ###########End###########

a,b=map(int,input().split())
print(common_factor(a,b))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783296.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号