Reputation: 427
a = (3,4,11,12,5,2,7,8,6,9,10)
for i in range(len(a)):
b = a[i]
for x in range(2,15):
if b > x:
c = i
print(c)
Result
>>>
10
>>>
In the above example, i'm trying to extract the largest element from tuple a by comparing each element against a specific range (2-14).
The result of above example should be 3(the index of 12), but i'm getting 10.
Can someone tell me what's wrong with the codes
Upvotes: 0
Views: 119
Reputation: 61
Why use for loops at all?
a = (3,4,11,12,5,2,7,8,6,9,10)
print(a.index(max(a)))
If you are looking for a local maximum in a specific range between 2 indexes.
startindex, endindex = 2, 14
b = a[startindex : endindex]
print(b.index(max(b)) + startindex)
If by range 2 to 14 you mean the values in tuple a instead of index range then this works for me. It will print index of first occurrence.
a = (3,4,11,12,5,2,7,8,6,9,10)
subsetTuple = tuple(item for item in a if item in range(2,14))
print(a.index(max(subsetTuple)))
Or you can do it in one line
a = (3,4,11,12,5,2,7,8,6,9,10)
print( max( enumerate(a), key = lambda pair: pair[1] if pair[1] in range( 2, 14) else False )[0] )
Upvotes: 2
Reputation: 43334
You get 10 as result because your tuple has 11 elements and the index of the last is 10.
You set this index equal to c
in the 2nd loop:
for x in range(2,15):
if b > x:
c = i
Because 10 is the last value of the tuple that is looped over, and b > x
is True at least once for b = 10
, c
gets assigned the index of 10 (which is 10) and that the is what is printed at the end.
How would you correct the problem?
I would do something like this:
a = (3,4,11,12,5,2,7,8,6,9,10)
c = 0
for i in range(len(a)):
if a[i] in range(2, 15) and a[i] > a[c]:
c = i
print(c)
This prints 3
It just loops over the tuple, checks if the current value is in the range 2-15 AND if the value is greater than the previous highest value, if both are True it sets the current index as the new c
Output:
Upvotes: 0
Reputation: 1
Your code just delivers the index of the last element, which is laying in your defined range (which is in fact at index 10).
You you need to store the local maximum and compare each new element against it (instead of using range(2,15).
I'm not that familar with python, but to get the index of the largest element this could be a solution:
a = (3,4,11,12,5,2,7,8,6,9,10)
localMaximum = 0
for i in range(len(a)):
b = a[i]
if b>localMaximum:
localMaximum = b
c = i
print(c)
Upvotes: 0