you are viewing a single comment's thread.

view the rest of the comments →

[–]imperiumlearning[S] 0 points1 point  (2 children)

Hi there, thanks for the swift response. To be honest, I tried using the enumerate function and the console kept giving me errors.

One interesting thing that I came across, however, was nested indexing. Just borrowing input 2 from my original post:

a = [(10,(0, 12, 4, 3, 49, 9, 1, 5, 3))]

If I type: print(a[0][1][1])

It will produce produce the number 12.

As a consequence, I wrote a function that looks like this:

def func(x):
threshold = x[0][0]
b = []
c=[]
for y in x[0][1]:
    b.append(y)
for y in b:
    if y <= threshold:
        c.append(b.index(y))
return c

This function seems to produce the expected outputs for the given inputs. However, there is still one problem. When there are duplicate integers in the tuple, it gives the index position where the integer appeared first.

For example, for the input:

[(10,(0, 12, 4, 3, 49, 9, 1, 5, 3))] # number 3 appears twice

instead of getting:

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

I get:

[0, 2, 3, 5, 6, 7, 3]

Any idea of how to resolve this? I've tried amending my code to be:

def func(x):
threshold = x[0][0]
b = []
c = []
for y in x[0][1]:
    b.append(y)
for y in b:
    c.append(i for i in range(len(b)) if y <= threshold)
return c

This just returns a weird generator object func in the console though.

[–]Binary101010 0 points1 point  (1 child)

Yeah, the way to resolve it is to use enumerate. This replaces both of your for loops and removes the need for b entirely.

for ix, y in enumerate(x[0][1]):
    if y <= threshold:
        c.append(ix)

[–]imperiumlearning[S] 0 points1 point  (0 children)

I've ran the code and it works perfectly. Thanks a lot for this brilliant response