交换最小值和最大值

一、输入数据

n=int(input())

nums = list(map(int,input().split()))#输入一组整数数组

二、分别取最小值和最大值索引,交换最小值和最大值位置

nums.index()取索引函数

python数组中交换数的位置无需借助其他变量,直接交换即可。

d = nums.index(min(nums))

nums[0], nums[d] = nums[d], nums[0]

#交换完最小值位置之后再取最大值索引位置,不可同时获取

c = nums.index(max(nums))

nums[-1], nums[c] = nums[c], nums[-1]

三、输出结果

for num in nums:

print(num, end=' ')

print()

提交结果:

完整代码:

n=int(input())

nums = list(map(int,input().split()))#输入一组整数数组

d = nums.index(min(nums))

nums[0],nums[d] = nums[d],nums[0]

#交换完最小值位置之后再取最大值索引位置,不可同时获取

c = nums.index(max(nums))

nums[-1],nums[c] = nums[c],nums[-1]

for num in nums:

print(num, end=' ')

print()

相关推荐
deephub9 分钟前
向量搜索系统的三个核心优化维度:速度、精度与规模
人工智能·python·rag·检索
勇往直前plus43 分钟前
python格式化字符串
开发语言·前端·python
咋吃都不胖lyh1 小时前
导出可复用的包版本信息(核心命令)
python
jiang_changsheng1 小时前
ms-swift 训练、微调、推理、评估、量化与部署的统一框架。配合comfyui使用
人工智能·python
撩妹小狗2 小时前
科赫雪花--Python--数学原理--turtle绘图
python·线性代数·几何学
宝贝儿好2 小时前
【强化学习】第十章:连续动作空间强化学习:随机高斯策略、DPG算法
人工智能·python·深度学习·算法·机器人
scott1985123 小时前
Improving Classifier-Free Guidance of Flow Matching via Manifold Projection
人工智能·python·机器学习
iOS开发上架3 小时前
系统架构-信息系统
python·腾讯云
Lupino3 小时前
从逻辑“脑裂”到 AI 重构:不到 2 美金解决物联网电位反转难题
python·物联网
青春不败 177-3266-05203 小时前
最新AI赋能Python长时序植被遥感动态分析、物候提取、时空变异归因及RSEI生态评估
人工智能·python·生态学·植被遥感·遥感·物候提取