切换索引,使用显示的完全相同的 9 位数字创建下一个最高数字 [英] Switch indexes, create the next highest number using the same exact 9 digits presented

查看:15
本文介绍了切换索引,使用显示的完全相同的 9 位数字创建下一个最高数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我收到了一个挑战,内容如下:设计一个程序,输入一个 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

推荐答案

我不相信你的翻转数字方法一定能找到下一个最高数字(至少在没有进一步检查的情况下不会)

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.")

这篇关于切换索引,使用显示的完全相同的 9 位数字创建下一个最高数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆