当前位置:网站首页>实例039:有序列表插入元素
实例039:有序列表插入元素
2022-08-04 01:35:00 【懒笑翻】
题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
程序分析:首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。
代码:
方法一:
lis = [1, 10, 100, 1000, 10000, 100000]
n = int(input('insert a number: '))
lis.append(n)
for i in range(len(lis) - 1):
if lis[i] >= n:
for j in range(i, len(lis)):
lis[j], lis[-1] = lis[-1], lis[j]
break
print(lis)
方法二:
lis = [1, 10, 100, 1000, 10000, 100000]
n = int(input('insert a number: '))
lis.append(n)
print(sorted(lis))
结果:
"""
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群,扫码下方官方推荐的群即可进入哦
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!↓↓↓↓↓↓
"""
边栏推荐
- 持续投入商品研发,叮咚买菜赢在了供应链投入上
- 【虚拟化生态平台】虚拟化平台esxi挂载USB硬盘
- Slipper - virtual point, shortest path
- Is there any jdbc link to Youxuan database documentation and examples?
- C 学生管理系统_添加学生
- Tanabata festival coming, VR panoramic look god assists for you
- FeatureNotFound( bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested:
- jmeter distributed stress test
- [store mall project 01] environment preparation and testing
- Variable string
猜你喜欢
随机推荐
nodejs installation and environment configuration
nodejs 安装多版本 版本切换
nodejs+express实现数据库mysql的访问,并展示数据到页面上
boot issue
Sky map coordinate system to Gaode coordinate system WGS84 to GCJ02
2022年上半年各大厂Android面试题整理及答案解析(持续更新中......)
Quickly build a website with static files
【正则表达式】笔记
Linux安装mysql最简单教程(一次成功)
Is there any jdbc link to Youxuan database documentation and examples?
2022 China Computing Power Conference released the excellent results of "Innovation Pioneer"
贴纸拼词 —— 记忆化搜索 / 状压DP
工程制图平面投影练习
一个项目的整体测试流程有哪几个阶段?测试方法有哪些?
GNSS文章汇总
splice随机添加和删除的写法
redis中常见的问题(缓存穿透,缓存雪崩,缓存击穿,redis淘汰策略)
typescript58 - generic classes
特征值与特征向量
阿里云技术专家邓青琳:云上跨可用区容灾和异地多活最佳实践