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

编程入门 行业动态 更新时间:2024-10-11 15:22:00
本文介绍了切换索引,使用显示的相同精确的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

推荐答案

我不确信您的数字翻转方法可以保证找到 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.")

更多推荐

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

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

发布评论

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

>www.elefans.com

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