Home > Enterprise >  check if a string contains determinate sequence from last element to first
check if a string contains determinate sequence from last element to first

Time:10-10

how can i check if a string contains determinate sequence from last element to first?

Example:

I have this sequence:

A, C, C, A, B, C

If sequence contains C [index:5], B[index:4], A[index:3] return true.

In this example the expected out is true

I have this sequence:

P, R, P, R, R

If sequence contains P [index:5], R[index:4], P[index:3] return true.

In this example the expected out is false

CodePudding user response:

Rabinzel's solution is good. If you want a solution using a loop you can do something like this:

Given seqeunce = 'ACCABC' and target = 'CBA'

def checkSeq(sequence, target):
    # This assumes target is the characters to be checked in reverse order from end of seqeuence
    if len(target) > len(sequence):
        return False

    pos = -1
    for ch in target:
        if sequence[pos] != ch:
            return False
        pos -= 1
    
    return True

Or this solution which ignores checking lengths and indexes entirely:

def checkSeq(sequence, target):
    # target is list of elements to check for at the end of sequence in the reverse order
    target = list(reversed(target))
    sequence = list(sequence)
    while sequence and target:
        if target.pop() != sequence.pop():
            return False
    return not (target and not sequence)

CodePudding user response:

If you have your target sequence as list, you could slice your input in reversed order and check if equal:

# 1st
#input list
lst = ['A', 'C', 'C', 'A', 'B', 'C']

#target list
target = ['C', 'B', 'A']
len_target = len(target)

# get the ending index dependent on length of input and target list
idx = len(lst) - len_target - 1 # 5 - 3 - 1 = 2
print(lst[:idx:-1] == target) # lst[:2:-1] slice starting from the back till idx 2 (2 not included)
# ['C', 'B', 'A'] == ['C', 'B', 'A'] --> True

# 2nd
lst = ['P', 'R', 'P', 'R', 'R']
target = ['P', 'R', 'P']
len_target = len(target)
idx = len(lst) - len_target - 1

print(lst[:idx:-1] == target)
False

If you want to read more about how to slice lists, this question has very detailed explanation.

  • Related