python - 从给定的输入中打印最大的数字
问题描述
我创建了一个代码来打印给定输入(字符串)中的最大数字,但它仅对包含不同数字的输入有效,并在输入包含重复数字时给出错误“字符串索引超出范围”。为什么这样?注意:“不能使用列表的概念”我的代码如下:
def largest_num(num):
nums = ""
length = len(num)
while length:
max_num = num[0]
for i in num:
if i > max_num:
max_num = i
num = num.replace(max_num,"")
nums = nums + max_num
length-=1
return nums
x = input("Entered number: ")
a = largest_num(x)
print(a)
输出:
解决方案
利用输入是字符串这一事实更直接,并且可以轻松地对字符串进行排序。请尝试下一个代码:
from functools import cmp_to_key
def largestNum(num):
num = [str(n) for n in num]
num.sort(key=cmp_to_key(lambda b, a: ((a+b)>(b+a))-((a+b)<(b+a)) ))
return ''.join(num).lstrip('0') or '0'
x = input("Entered number: ")
#a = largest_num(x)
print(largestNum(x))
Demo:
>>>Entered number: 321895
985321
>>>Entered number: 10957
97510
>>>Entered number: 4576889
9887654
>>>
Or simply do the sorting directly (you can convert this to function):
1. num = list(num). # num is string input of number
2. num = num.sort(reverse=True)
3. largest = int(‘’.join(num)) # answer
推荐阅读
- python - PYTHON:如何每分钟自动从 RTSP 捕获图像,直到 24 小时
- assembly - 如何在 64 位 Linux 系统上执行 32 位 shellcode?
- android - Android Studio 中的密钥存储路径是什么?
- api - Spotify API:无效的重定向 URI
- javascript - 如何将ajax json响应保存到全局变量以供重用
- android - android 房间 livedata 一次
- mysql - 如何使用 MySQL `SELECT FROM` 作为查询本身的一部分的表?
- tkinter - 根据查询结果在 tkinter 中更改 Treeview 小部件的背景颜色
- ios - touchBegan,检查是否触摸了 CAShapeLayer
- python - 为什么循环 Python TCP 接收器部分接收消息?