例如,数字123431和4577852增加然后减少.我写了一个代码,将数字分成一个列表,并能够判断所有数字是否增加或所有数字是否减少,但我不知道如何检查数字增加然后减少.我该如何延长?
x = int(input("Please enter a number: "))
y = [int(d) for d in str(x)]
def isDecreasing(y):
for i in range(len(y) - 1):
if y[i] < y[i + 1]:
return False
return True
if isDecreasing(y) == True or sorted(y) == y:
print("Yes")
Run Code Online (Sandbox Code Playgroud)
找到最大元素.在该位置将列表分成两部分.检查第一件是否增加,第二件减少.
4577852你找到了最大的元素8.4577和852(8可以列在两个列表中,两者都可以,或者两者都没有).4577正在增加(好)并且852正在减少(也没关系).这足以让你找到解决方案吗?
似乎是学习使用itertools和生成器管道的好机会。首先我们制作一些简单的、解耦的、可重用的组件:
from itertools import tee, groupby
def digits(n):
"""420 -> 4, 2, 0"""
for char in str(n):
yield int(char)
def pairwise(iterable):
"""s -> (s0,s1), (s1,s2), (s2, s3), ..."""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def deltas(pairs):
"""2 5 3 4 -> 3, -2, 1"""
for left, right in pairs:
yield right - left
def directions(deltas):
"""3 2 2 5 6 -> -1, 0, 1, 1"""
for delta in deltas:
yield -1 if delta < 0 else +1 if delta > 0 else 0
def deduper(directions):
"""3 2 2 5 6 2 2 2 -> 3, 2, 5, 6, 2"""
for key, group in groupby(directions):
yield key
Run Code Online (Sandbox Code Playgroud)
然后我们将这些部分放在一起来解决检测“先增加后减少的数字”的更广泛的问题:
from itertools import zip_longest
def is_inc_dec(stream, expected=(+1, -1)):
stream = pairwise(stream)
stream = deltas(stream)
stream = directions(stream)
stream = deduper(stream)
for actual, expected in zip_longest(stream, expected):
if actual != expected or actual is None or expected is None:
return False
else:
return True
Run Code Online (Sandbox Code Playgroud)
用法是这样的:
>>> stream = digits(123431)
>>> is_inc_dec(stream)
True
Run Code Online (Sandbox Code Playgroud)
该解决方案将正确短路以下数字:
121111111111111111111111111111111111111111111111111...2
我只讨论了“严格增加,然后严格减少”的数字情况。由于这听起来可能是您的作业,因此我将其作为练习留给您,以适应问题标题中提到的“非递减然后非递增”情况的代码。