1

The list comprehension [j-x[i]==0 for i,j in enumerate(x[1:])] will produce a list of boolean elements. The return value must be a boolean scalar rather than a list. It is obtained by OR-ing all elements. How to do so?

def has_same_adjecent(x):
    if len(x)<2:
        return False
    return [j-x[i]==0 for i,j in enumerate(x[1:])]

has_same_adjecent([3,1,3,3])# must return True
cs95
  • 379,657
  • 97
  • 704
  • 746
Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165

2 Answers2

1

You can do that with any (which short circuits). As an additional optimization, you can zip your list with itself shifted by 1, then compare.

def has_same_adjecent(data):
     return any(x == y for x, y in zip(data, data[1:]))

has_same_adjecent([3, 1, 3, 3])
# True
cs95
  • 379,657
  • 97
  • 704
  • 746
1

You can also use numpy's any as well:

np.any(~np.diff(a).astype(bool))

In code:

import numpy as np

a = [3,1,3,3]
print(np.any(~np.diff(a).astype(bool)))

# True
Austin
  • 25,759
  • 4
  • 25
  • 48