简体   繁体   English

切换索引,使用显示的相同精确的9位数字创建下一个最高数字

[英]Switch indexes, create the next highest number using the same exact 9 digits presented

So I received a challenge that states the following: "Design a program that takes as input a 9 digit number where no digit appears twice and produces as output an arrangement of the same 9 digits corresponding to the next highest number. If no such number exists, the algorithm should indicate this. So for example, if the input is 781623954 the output would be 781624359." 因此,我收到了一个挑战,陈述如下:“设计一个程序,输入一个9位数字,其中没有数字出现两次,并输出对应于下一个最高数字的相同9位数字作为输出。如果不存在这样的数字, ,算法应该指出这一点。因此,例如,如果输入为781623954,则输出将为781624359。”

So I came up with this idea to flip the indexes, so check the last index with the one right before to see which is bigger and compare then flip if necessary but for some reason my code isn't working. 因此,我想到了翻转索引的想法,因此请在检查前一个索引之前检查一下哪个索引更大,然后进行比较,然后在必要时翻转,但由于某些原因我的代码无法正常工作。 I only did the work for checking the last two digits not all the digits, so if you can help me out and check it for me and if you have any better ideas on how to tackle this problem, please share. 我只是检查最后两位数字而不是全部数字,因此,如果您可以帮助我并为我检查一下,并且您对解决此问题有更好的想法,请分享。

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

Here's a more efficient approach, using the algorithm of the 14th century Indian mathematician Narayana Pandita, which can be found in the Wikipedia article on Permutation . 这是使用14世纪印度数学家Narayana Pandita的算法的一种更有效的方法,该算法可以在Wikipedia上有关置换的文章中找到。 This ancient algorithm is still one of the fastest known ways to generate permutations in order, and it is quite robust, in that it properly handles permutations that contain repeated elements. 这种古老的算法仍然是已知的按顺序生成置换的最快方法之一,并且它非常健壮,因为它可以正确处理包含重复元素的置换。

The code below includes a simple test() function that generates all permutations of an ordered numeric string. 下面的代码包括一个简单的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()

I am not convinced that your approach of flipping digits is guaranteed to find the next highest number (at least not without further checks) 我不相信您会用数字翻转的方法来保证找到下一个最高的数字(至少在没有进一步检查的情况下)

Here a simple solution: Simply increment the input number and check if the conditions are met or if no number can be found. 这是一个简单的解决方案:只需增加输入数字并检查是否满足条件或找不到数字。

set() can be used to get the set of unique digits in the number. set()可用于获取数字中唯一的一组数字。

input_num = '781623954'
next_num = int(input_num) + 1
input_digits = set(input_num)
found = False
while not found:
    next_num += 1
    next_digits = set(str(next_num))
    found = len(next_digits) == 9 and input_digits == next_digits
    if next_num > 987654321:
        break

if found:
    print(next_num)
else:
    print("No number was found.")
input[8] == input[7]
input[7] == temp

you probably meant: 你可能的意思是:

input[8] = input[7]
input[7] = temp

didn't you? 是不是

Which, as stated in the comments, wouldn't work directly on the string, as it is immutable in Python. 如注释中所述,它不能直接在字符串上工作,因为它在Python中是不可变的。 So, as a first step, you could make a list of characters from that string: 因此,作为第一步,您可以列出该字符串中的字符:

input = list(input)

and as a last step, get a string back from the modified list: 最后,从修改后的列表中返回一个字符串:

input = ''.join(input)

BTW, you might want to benefit from Python tuple unpacking which allows you to swap two variables without having to introduce a third one: 顺便说一句,您可能想从Python元组解压缩中受益,它允许您交换两个变量而不必引入第三个变量:

input[7], input[8] = input[8], input[7]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM