0
0

More than 1 year has passed since last update.

【Python】サブシーケンスの検証

Posted at

作るもの

 与えられた array が与えられた sequence の有効なサブシーケンス(subsequence)であるかを判定する関数 isValidSubsequence を作る。関数はブール値を返す。True を返す場合、array は sequence の有効なサブシーケンスであることを示す。False を返す場合、array は sequence の有効なサブシーケンスではないことを示す。

実装

validate_subsequence.py
def isValidSubsequence(array, sequence):
    # インデックス変数を初期化する
    arrIdx = 0  # arrayのインデックスを表す変数
    seqIdx = 0  # sequenceのインデックスを表す変数

    # arrayとsequenceの要素を比較しながらサブシーケンスを検証する
    while arrIdx < len(array) and seqIdx < len(sequence):
        # array[arrIdx]とsequence[seqIdx]が等しい場合、次のsequence要素を検索する
        if array[arrIdx] == sequence[seqIdx]:
            seqIdx += 1  # sequenceのインデックスを次に進める
        arrIdx += 1  # arrayのインデックスを次に進める

    # サブシーケンスの検証結果を返す
    return seqIdx == len(sequence)

# テスト
if __name__ == "__main__":
    array = [5, 1, 22, 25, 6, -1, 8, 10]
    sequence = [22, 25, 6]
    print(isValidSubsequence(array, sequence))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0