Skip to main content
 首页 » 编程设计

python之切换索引,使用显示的完全相同的 9 位数字创建下一个最高数字

2025年05月04日13cmt

所以我收到了一个挑战,内容如下: “设计一个程序,将一个 9 位数字作为输入,其中没有数字出现两次,并产生与下一个最高数字相对应的相同 9 位数字的排列作为输出。如果不存在这样的数字,算法应该指出这一点。例如,如果输入为 781623954,则输出为 781624359。”

所以我想出了翻转索引的想法,所以检查最后一个索引和之前的索引,看看哪个更大,然后比较然后在必要时翻转,但由于某种原因我的代码无法正常工作。我只检查了最后两位数字而不是所有数字,所以如果你能帮我检查一下,如果你对如何解决这个问题有更好的想法,请分享。

input = raw_input("Enter 9 Digits: ") 
x = 9 
while x>0: 
    x-=1 
    if input[8] > input[7]: 
        temp = input[8] 
        input[8] == input[7]  
        input[7] == temp 
        print input 
        break 

请您参考如下方法:

这里有一个更有效的方法,使用 14 世纪印度数学家 Narayana Pandita 的算法,可以在关于 Permutation 的维基百科文章中找到。 .这种古老的算法仍然是已知最快的按顺序生成排列的方法之一,而且它非常稳健,因为它可以正确处理包含重复元素的排列。

下面的代码包含一个简单的 test() 函数,它生成有序数字字符串的所有排列。

#! /usr/bin/env python 
 
''' Find the next permutation in lexicographic order after a given permutation 
 
    This algorithm, due to Narayana Pandita, is from 
    https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order 
 
    1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists,  
    the permutation is the last permutation. 
    2. Find the largest index k greater than j such that a[j] < a[k]. 
    3. Swap the value of a[j] with that of a[k]. 
    4. Reverse the sequence from a[j + 1] up to and including the final element a[n]. 
 
    Implemented in Python by PM 2Ring 2015.07.28 
''' 
 
import sys 
 
def next_perm(a): 
    ''' Advance permutation a to the next one in lexicographic order ''' 
    n = len(a) - 1 
    #1. Find the largest index j such that a[j] < a[j + 1] 
    for j in range(n-1, -1, -1): 
        if a[j] < a[j + 1]: 
            break 
    else: 
        #This must be the last permutation 
        return False 
 
    #2. Find the largest index k greater than j such that a[j] < a[k] 
    v = a[j] 
    for k in range(n, j, -1): 
        if v < a[k]: 
            break 
 
    #3. Swap the value of a[j] with that of a[k]. 
    a[j], a[k] = a[k], a[j] 
 
    #4. Reverse the tail of the sequence 
    a[j+1:] = a[j+1:][::-1] 
 
    return True 
 
 
def test(n): 
    ''' Print all permutations of an ordered numeric string (1-based) ''' 
    a = [str(i) for i in range(1, n+1)] 
    i = 0 
    while True: 
        print('%2d: %s' % (i, ''.join(a))) 
        i += 1 
        if not next_perm(a): 
            break 
 
 
def main(): 
    s = sys.argv[1] if len(sys.argv) > 1 else '781623954' 
    a = list(s) 
    next_perm(a) 
    print('%s -> %s' % (s, ''.join(a))) 
 
 
if __name__ == '__main__': 
    #test(4) 
    main()