首页 > 解决方案 > 从给定的输入中打印最大的数字

问题描述

我创建了一个代码来打印给定输入(字符串)中的最大数字,但它仅对包含不同数字的输入有效,并在输入包含重复数字时给出错误“字符串索引超出范围”。为什么这样?注意:“不能使用列表的概念”我的代码如下:

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)

输出:

上述代码的输出

标签: pythonpython-3.x

解决方案


利用输入是字符串这一事实更直接,并且可以轻松地对字符串进行排序。请尝试下一个代码:

    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 

推荐阅读