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

编程入门 行业动态 更新时间:2024-10-11 09:26:42
本文介绍了切换索引,使用显示的完全相同的 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 位数字创建下一个最高数字

本文发布于:2023-11-30 09:44:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649543.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   完全相同   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!