肯定有更简单的解决方案。例如,这是我想出的一个(只是尝试一下,我确信还有更优化的解决方案):
def flip(i):
return int(''.join(str(i)[::-1]))
def strict_inc(xs, single_flip_allowed=True):
for n, (a, b) in enumerate(zip(xs, xs[1:])):
if a >= b:
break
else:
return True
# here, n will be the index at which the first problem occurs
return single_flip_allowed and (
(
(n == 0 or xs[n-1] < flip(xs[n]))
and (n == len(xs) or flip(xs[n]) < xs[n+1])
and strict_inc(xs[n+1:], False)
)
or
(
(xs[n] < flip(xs[n+1]))
and (n+1 == len(xs) or flip(xs[n+1]) < xs[n+2])
and strict_inc(xs[n+2:], False)
)
)
(请注意,这实现了您的解决方案,并添加了翻转,但不是正确的解决方案,请继续阅读)
尽管该函数会递归调用自身,但它不会多次调用自身,因此不会出现任何问题。
它基本上工作的前提是原始正整数序列中只能有一个缺陷。因此,它找到第一个缺陷,查看是否可以通过“翻转”缺陷中的第一个或第二个整数来修复它,并检查在这种情况下序列的其余部分是否仍然严格增加(不允许进一步翻转)。
您要求对您的代码进行审查,但鉴于它显然远非最佳,因此全面完成这将是一项艰巨的任务。
如果您确实想要评论,我建议您尝试https://codereview.stackexchange.com/因为StackOverflow确实更适合寻求具体技术问题的解决方案。
事实证明(感谢@barmar 指出我的错误,并感谢@kellybundy 指出OP 的错误),一个有效的解决方案也不是那么复杂(同样有改进的空间):
def check(xs):
x = str(xs[1])
return any(xs[0] < int(f'{x[0:i]}{x[j]}{x[i+1:j]}{x[i]}{x[j+1:]}') < xs[2]
for i in range(len(x)) for j in range(i+1, len(x)))
def strict_inc(xs, single_flip_allowed=True):
for n, (a, b) in enumerate(zip(xs, xs[1:])):
if a >= b:
break
else:
return True
# here, n will be the index at which the first problem occurs
return single_flip_allowed and (
(
check(xs[n-1:n+2] if n > 0 else [-1] + xs[n:n+2])
and strict_inc(xs[n+1:], False)
)
or
(
check(xs[n:n+3] if n < len(xs)-2 else xs[n:n+2] + [int('9'*len(str(xs[n+1])))])
and strict_inc(xs[n+2:], False)
)
)
(另一个编辑:这个解决方案实际上根据需要尝试所有可能的配对)