西安交通大学 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]<x:
return binarySearch(arr,mid+1,r,x)
else:
return binarySearch(arr,l,mid-1,x)
else:
return -1
###########End###########
mylist=list(map(int,input().split()))
x=int(input())
print(binarySearch(mylist, 0, len(mylist), x))
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))
更多推荐
已为社区贡献1条内容
所有评论(0)