Indexing the largest element in the tuple - python

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

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] )

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)

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:

Related

How do you output the highest index in the list on Python?

How do you output the highest index in the list on Python?
Situation.
I'm solving an algorithm problem.
We are unable to solve the problem because of one condition.
So I googled, but I couldn't solve it.
my code
arr = [1,0,0,0,1,1]
try code
arr = [1,0,0,0,1,1]
res = []
temp = 0
for i in arr :
temp = max(i)
max_index = temp.inedx(temp)
i want result output
so, I want to output the index 5th value within the list above.
Case
a = [1,1,1,0,0,0] -------> 2
a = [0,1,1,1,0,0] -------> 3
a = [0,0,0,1,1,1] -------> 5
a = [1,0,1,1,0,0] -------> 3
a = [1,1,2,1,0,0] -------> 2
It has the same value in the list.
Outputting the highest index among themselves.
len(arr) - 1 - arr[::-1].index(max(arr))
arr[::-1] produces a reversed list; .index finds the first index of an element; max finds the highest element. First index of an element in a reversed list is the last index of an element. We then need a bit of arithmetic to unreverse the index.
Alternately:
max_v = None
max_i = None
for i, v in enumerate(arr):
if max_v is None or v >= max_v:
max_v = v
max_i = i
print(max_i)
You can simply use numpy.where:
import numpy as np
max(numpy.where([0, 0, 1])[0]) # outputs 2
numpy.where returns a tuple where the first element is an array of indexes where truth-y values are found.
Simply enumerate the list and once exhausted you get the index:
last = 0
for idx, item in enumerate(your_list):
if item != 0:
last = idx # or with +1, depending on your use-case
print(last)
You can be a bit creative with the solution which might cause it being more efficient such as reversing the list (reversed() / list[::-1]), halving it (check for odd/even number of elements) and using a look-ahead or use sum() and other:
for idx, item in enumerate(data):
if item != 0 and sum(data[idx + 1:]) == 0:
last = idx
For fetching the index of the highest element in a list, add a check not for != 0 but for == max(your_list), preferably store the max(your_list) into a variable before your loop so it's calculated only once instead of in all of the iterations.

Index out of Range despite check

t = [1, 2, 3]
def cumsum(t):
t2 = []
total = 0
i = 0
while i < len(t):
total += t[i]
t2[i].append(total)
i += 1
return t2
cumsum(t)
This code takes the sum of the first two list integers and appends it to another list.
I feel like this should logically work and I don't understand why it is producing an index error if i < len(t) when len(t)= 3. So ideally t2 =[1, 3, 6]
while the iterator is less than len(t) (which is 3) add the list item to the total variable then append the total to the new list then iterate.
Because you are using index i to access t2 list that is empty. To append an element to a list you should use <list>.append(<element>), that is t2.append(total) in your case.

Python - List index out of range, "for" loop

I don't get how a "for" loop that iterates through the elements of a list can be out of range.
First part seems to be okay as I can print it.
import random
def random_list(n):
l = []
for i in range(0,n):
l.append(random.randint(0,n))
return l
def maximum(n):
x = 0
b = random_list(n)
for i in b:
if b[i] > x:
x = b[i]
print (maximum(10))
This:
for i in b:
if b[i] > x:
x = b[i]
Iterates over the elements of b, not the indices. Change it to
for i in b:
if i > x:
x = i
You also need to return something from your function, probably x.
Considering that you know how to iterate over a list in python, the error could be due to randint, which generates an integer in the interval [low, high]. This means high is a possible output, while the highest index in your program is high - 1.
For example,
random.randint(0, 0)
gives 0.
Similarly, random.randint(10) can return 10.
If you don't understand how to iterate over a list in Python, consider a simple example:
Take the list below:
myList = [1, 3, 5, 7, 9]
Now, there are two ways to iterate over the list:
Directly accessing elements:
for element in myList:
print(element, end=" ")
This gives the output:
1 3 5 7 9
Accessing elements using indices
for idx in range(len(myList)):
print(idx, ":", myList[idx], end=" ")
This gives the output:
0:1 1:3 2:5 3:7 4:9

How to find the index of an element in a list which is minimum in a sublist of that list in Python?

Assume I have a Python list:
x = [3,6,4,8,1,9]
and I want to find the index of the element in the list which is the minimum inside a sublist (say from index 2 to 4).
So I want to take a sublist x[2:5] and get the index of the minimum element (in this case x[4]).
How to return index 4 in such a case? If I use np.argmin() on the sublist, it will return the index according to the sublist (in this case, np.argmin(x[2:5]) will return 2 which is correct according to the sublist).
I don't want to use multiple if-else conditions. How to go about getting this index in a short way?
Just add the index where the sublist starts, and you'll have your original index:
x = [3,6,4,8,1,9]
subl_start = 2
subl_end = 5
ind_min = np.argmin(x[subl_start: subl_end]) + subl_start
You can also find the minimum of numbers between a threshold:
>>> x = [3,6,4,8,1,9]
>>> start, end = 2, 5
>>> min((e, i) for i, e in enumerate(x) if start <= i < end)[1]
4
Or incrementing the final result index:
>>> min((e, i) for i, e in enumerate(x[start:end]))[1] + start
4
I think this one liner will do fine for your case.
x.index(min(x[2:5]))
you can replace 2 & 5 with some variables also. (for index n to m -> (arr[n:m+1]))

Get the pairs of values from a list according to a condition without elements repeating

I have a list of integers like:
1 3 4 4 9 7 10 (the number of elements is between 1 and 200000)
and an integer variable D, it lies between 0 and 10^9.
Let it be 5 for example.
I need to count how many pairs in the list have a difference between each other not bigger than a variable D but the tricky part is that if I took the zero element with value 1 and the first element with the value 3(the difference between them meets the condition) I can't use these elements of a list again.
For example for the sequence above the answer is 3 pairs: (1,3) (4,4) (7,9)
I wrote a code which seems to be correct but I need a hint how to change the input sequence and the variable d the way it will output wrong answer
list_of_colors = [1, 3, 4, 4, 9, 7, 10]
d = 5
number_of_pairs = 0
list_of_colors.sort() # the values in the list are not always sorted
i = 0
while True:
if i >= len(list_of_colors):
break
if i != len(list_of_colors) - 1:
# if the number i in list and i+1 is the same or difference between them not greater than a variable d...
if (int(list_of_colors[i]) == int(list_of_colors[i + 1])) or abs(int(list_of_colors[i]) - int(list_of_colors[i + 1])) <= d:
#print list_of_colors[i]," ",list_of_colors[i + 1]
number_of_pairs += 1 # increasing the number of the acceptable pairs
i += 2 # jump over two elements, we already counted them
continue
i += 1
print number_of_pairs
I need another algorithm to compare it with the results of my algorithm on the various range of the input sequence and the variable d
Suggest your ideas please
I have a greedy solution for this problem:
Sort the input sequence.
Parse the sorted sequence as follows:
For ith element in the sequence,
if |a[i+1]-a[i]| <= D,
then pair up the elements. Proceed to process i+2th element.
else
proceed to process i+1th element.
My solution here is to first "clean" the list what means I made the number of elements even. Then I've converted the list into a list of tuples (pairs).
My result for this example is 3 pairs in order to your condition.
list_of_colors = [1, 3, 4, 4, 9, 7, 10]
d = 5
number_of_pairs = 0
list_of_colors.sort() # the values in the list are not always sorted
# remove the last element if the number of elements is odd
if len(list_of_colors) % 2 != 0:
list_of_colors = list_of_colors[:-1]
# create a list of tuples
list_of_colors = [tuple(list_of_colors[i:i+2]) for i in range(0, len(list_of_colors), 2)]
for i in list_of_colors:
if (int(i[0]) == int(i[1])) or abs(int(i[0])) - int(i[1]) <= d:
number_of_pairs += 1
print number_of_pairs

Categories

Resources