所以我收到了一个挑战,陈述以下内容: 设计一个程序,该程序以一个9位数字作为输入,其中没有数字出现两次,并产生与下一个最高数字相对应的相同9位数字的排列.如果不存在该数字,则算法应指出这一点.例如,如果输入为781623954,则输出为781624359."
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."
因此,我想到了翻转索引的想法,因此请检查一下最后一个索引是否正确,然后比较,然后在必要时翻转,但由于某种原因我的代码无法正常工作.我只是检查最后两位数字而不是全部数字,所以,如果您可以帮助我并为我检查一下,并且您对解决此问题有更好的想法,请与我们分享.
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推荐答案
我不确信您的数字翻转方法可以保证找到 next 最高数字(至少在没有进一步检查的情况下)
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()可用于获取数字中的唯一数字集.
set() can be used to get the set of unique digits in the number.
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.")