簡體   English   中英

如何確定列表中的數字最初是增加(或保持不變)然后減少(或保持不變)與Python?

[英]How can I determine if the numbers in a list initially increase (or stay the same) and then decrease (or stay the same) with Python?

例如, 1234314577852的數字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")

找到最大元素。 在該位置將列表分成兩部分。 檢查第一件是否增加,第二件減少。

  • 對於第二個示例4577852 ,您找到最大的元素, 8
  • 將列表分為兩部分: 4577852 (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

然后我們將各個部分放在一起以解決檢測“增加然后減少數量”的更廣泛問題:

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

用法是這樣的:

>>> stream = digits(123431)
>>> is_inc_dec(stream)
True

此解決方案將正確短路,例如:

121111111111111111111111111111111111111111111111111 ... 2

我只解決了“嚴格增加,然后嚴格減少”的案例。 因為這聽起來像是你的家庭作業,所以我將把它作為練習讓你調整代碼以適應問題標題中提到的“不減少然后不增加”的情況。

將列表拆分為最大值,然后取每邊差異的最小值/最大值:

import numpy as np

test1 = [1, 2, 3, 4, 5, 8, 7, 3, 1, 0]
test2 = [1, 2, 3, 4, 5, 8, 7, 3, 1, 0, 2, 5]
test3 = [7, 1, 2, 3, 4, 5, 8, 7, 3, 1, 0]
test4 = [1, 2, 3, 4, 5, 8, 8, 7, 3, 1, 0]

def incdec_test(x):
    i = np.array(x).argmax()
    return (np.diff(x[0:i]).min() >= 0) and (np.diff(x[i:-1]).max() <= 0)

for test in [test1, test2, test3, test4]:
    print 'increase then decrease = {}'.format(incdec_test(test))

結果:

increase then decrease = True
increase then decrease = False
increase then decrease = False
increase then decrease = False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM