python练习2

本文介绍了如何编写Python程序,实现测试用户输入的列表是否排序以及合并两个有序列表的功能,通过实例展示了代码执行过程和结果。
摘要由CSDN通过智能技术生成

1.编写一个测试程序,提示用户输入一个列表,然后显示这个列表是否排好序。下面是一个示例运行。

Enter list:1 1 3 4 4 5 7 9 10 30 11
The list is not sorted
Enter list:1 1 3 44 5 7 9 10 30
The list is already sorted

l = eval(input('Enter list:'))
l1 = list(l)
l2=[]
for i in l1:
    l2.append(i)
l2.sort()
if l1==l2:
    print('The list is already sorted')
else:
    print('The list is not sorted')

测试结果

Enter list:1,3,1
The list is not sorted

Enter list:1,2,3
The list is already sorted

2.(合并两个有序列表)编写程序合并两个有序列表构成一个新的有序列表。
下面是一个实例运行。

Enter list1:1,5,16,61,111
Enter list2:2,4,5,6
The merged list is [1, 2, 4, 5, 6, 111, 16, 61]

l1=eval(input('Enter list1:'))
l2=eval(input('Enter list2:'))
list1=list(l1)
list2=list(l2)
list_1=set(list1)
list_2=set(list2)
list_3=list_1.union(list_2)
m_list=list(list_3)
print('The merged list is',m_list)

测试

Enter list1:1,3,57,3,2
Enter list2:2,5,2
The merged list is [1, 2, 3, 5, 57]
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值