I have a tuple ("apple",pear","banana","watermelon") and want to find whether "pear","banana" are next to each other in this tuple.
May I know how to do it in python?
CodePudding user response:
A very analytical way of thinking about this:
#! /usr/bin/env python3
tup = ("apple", "pear", "banana", "watermelon")
index = 0
pearIndex = 0
bananaIndex = 0
for item in tup:
# print(item)
if(item == 'pear'):
pearIndex = index
elif(item == 'banana'):
bananaIndex = index
index = 1
if(bananaIndex-pearIndex == 1 or pearIndex-bananaIndex == 1):
print('they are next to each other')
Also your tuple is not right, it's missing some quotes before pear.
CodePudding user response:
You can use a small generator comprehension:
t = ("apple", "pear", "banana", "watermelon")
match = set(('pear', 'banana'))
any(match == set((t[i],t[i 1])) for i in range(len(t)-1))
output: True
How it works: the generator expression makes couples of consecutive values and compares them to the match set (sets are used as they are unordered). Then any
will return True
for the first True
value. The advantage of using a generator is that the process will stop at the first match.
CodePudding user response:
A simple way to do this would be to check if their absolute index difference is equal to 1.
Here's the code
tup = ("apple", "pear", "banana", "watermelon")
print(abs(tup.index("pear")-tup.index("banana")) == 1)
CodePudding user response:
Let's say this is the tuple:
tup = ("apple", "pear", "banana", "watermelon", "mango", "grapes")
Try zipping the tuple to check consecutive elements:
print(
any(lhs == "pear" and rhs == "banana" for lhs, rhs in zip(tup, tup[1:]))
)
print(
any(lhs == "pear" and rhs == "watermelon" for lhs, rhs in zip(tup, tup[1:]))
)
print(
any(lhs == "watermelon" and rhs == "mango" for lhs, rhs in zip(tup, tup[1:]))
)
Or try using functools.reduce
from functools import reduce
print(
reduce(
lambda lhs, rhs: True if lhs is True or lhs == "pear" and rhs == "banana" else rhs,
tup (False,),
)
)
print(
reduce(
lambda lhs, rhs: True if lhs is True or lhs == "pear" and rhs == "watermelon" else rhs,
tup (False,),
)
)
print(
reduce(
lambda lhs, rhs: True if lhs is True or lhs == "watermelon" and rhs == "mango" else rhs,
tup (False,),
)
)
Output
True
False
True