Giorgio Marauder
Giorgio Marauder

Reputation: 11

Alternatives to index() in Python

So for my assignment I must find a way in which I can work around this problem of printing 'YES' if a list contains the elements 1,2,3 in the consecutive order. It does not work if the list contains the elements [3,1,2,3] due to the index method. How can I work around this?

n=int(input("Enter the number of elements: "))

A=[]
for i in range(0,n):
    print("Entering element", i)
    LstEl=int(input("Please enter the element: "))
    A.append(LstEl)


print(A)
for i in range(0,len(A)):
    if(1 in A and 2 in A and 3 in A):
        post1 = A.index(1)
        post2 = A.index(2)
        post3 = A.index(3)
        if(post1 < post2 and post2 < post3):
            print("YES")        
            break
        else:
            print('NO')
            break
    else:
        print("NO")
        break

Thanks!

Upvotes: 1

Views: 7297

Answers (4)

Deep Patel
Deep Patel

Reputation: 739

I would suggest using enumerate with the for loop.

lst = ['a', 'b', 'c', 'd']   
for i, value in enumerate(lst):
    print(i, value) # 0,a.....3,d

Upvotes: 0

John Anderson
John Anderson

Reputation: 38857

Once you find a valid post1 value, you can check for the sequence using

if A[post1:post1+3] == [1, 2, 3]:
    print('Yes')
    break

Use the other parameters of the index() method to find successive occurrences of the element '1'.

Upvotes: 1

jedwards
jedwards

Reputation: 30210

The following code uses a generator function to extract sublists from a larger list. It's probably not appropriate for a homework assignment if you don't understand the mechanics behind generator functions, but it might be something to look into if you're interested.

# A generator function that returns the n-length sublists of list lst
def slider(lst, n):
    start = 0
    while start + n <= len(lst):
        yield lst[start:start+n]
        start += 1


# A function that will return True if sequence needle exists in
#   haystack, False otherwise
def list_contains(haystack, needle):
    for sub in slider(haystack, 3): # Loop through the sublists...
        if sub == needle:           # ... test for equality ...
            return True
    return False

# Code
big = [2,4,6,8,0,1,2,3,1,5,7]       # Hardcoded here, could be created
                                    #   in a loop like you show

seq = [1,2,3]                       # The sequence you're looking for

print(list_contains(big, seq))

You can see the output of the generator function with something like:

big = [2,4,6,8,0,1,2,3,1,5,7]
for sub in slider(big, 3):
    print(sub)

Output:

[2, 4, 6]
[4, 6, 8]
[6, 8, 0]
[8, 0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 1]
[3, 1, 5]
[1, 5, 7]

Or maybe more clearly:

#  [2, 4, 6, 8, 0, 1, 2, 3, 1, 5, 7]
   [2, 4, 6]
      [4, 6, 8]
         [6, 8, 0]
            [8, 0, 1]
               [0, 1, 2]
                  [1, 2, 3]
                     [2, 3, 1]
                        [3, 1, 5]
                           [1, 5, 7]

Upvotes: 0

acushner
acushner

Reputation: 9946

one option is just:

# find the indices of all `1`s
one_idxs = (i for (i, v) in enumerate(values) if v == 1)
for idx in one_idxs:
    if values[i : i + 3] == [1, 2, 3]:
        print('YES')
        break
else:
    print('NO')

a more concise way is

if any(values[i : i + 3] == [1, 2, 3] for (i, v) in enumerate(values) if v == 1):
    print('YES')
else:
    print('NO')

Upvotes: 1

Related Questions