我正在写一个程序,它接受一个9位数字作为输入,每个数字从1到9(即459876231),该程序获取该数字,然后找到具有相同数字的下一个最高数字。我拥有的代码可以工作,但只有当我将print语句放入for循环中时才能工作。
n = int(input("Please input a 9 digit number"))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
print(n)如果我将print语句放在不缩进的位置,程序将无法工作。将print语句放在这里还会显示程序在获得正确数字的过程中尝试的每个数字,而我只想显示最终的答案。为什么会发生这种情况?我尝试将n存储在一个全新的变量中,然后尝试在循环外打印,但得到的结果是一样的。
发布于 2021-09-27 16:07:07
这是因为如果执行n += 1,n将是1,然后是2,3..,所以每次都需要打印n。如果在for之外打印n,它将只打印它的最后一个值。
发布于 2021-09-27 16:20:56
您的代码已修复为:
n = int(input("Please input a 9 digit number: "))
n_str = str(n)
n_str1 = str(n+1)
while n < 1000000000:
found = True
for char in n_str:
if not char in n_str1:
n += 1
n_str1 = str(n)
found = False
break
if found:
print(n)
break你的情况中有个bug
for char in n_str:
if not char in n_str1:如果输入数字为333222323,n_str1为333222324,则数字校验char in n_str1将全部为true,结果为333222323。
我发现LeetCode problem 31. Next Permutation和你的问题非常相似,而且已经有很多推荐的解决方案,大多数都比你的更有效。
此示例代码基于我的LeetCode答案:
nstr = input("Please input a 9 digit number: ")
nums = [int(c) for c in nstr]
l = len(nums) # length should be 9
for i in range(l-2, -1, -1):
swap_idx, swap_n = None, None
for j in range(i+1, l):
if (nums[i] < nums[j]) and (not swap_n or (nums[j] < swap_n)):
swap_idx, swap_n = j, nums[j]
if swap_idx:
tmp = nums[i]
nums[i] = nums[swap_idx]
nums[swap_idx] = tmp
break
nums = nums[:i+1] + sorted(nums[i+1:])
print(''.join([str(i) for i in nums]))通过测试:
Please input a 9 digit number: 459876231
459876312
Please input a 9 digit number: 333222323
333222332https://stackoverflow.com/questions/69349783
复制相似问题