Home > Enterprise >  Output the index of an item in a set in Python/Sage
Output the index of an item in a set in Python/Sage

Time:06-29

This is what I have so far.

def f(n):
    my_list=[]  
    while n not in my_list: 
        my_list.append(n) 
        if n % 2 == 0: 
            n = n / 2
        else: 
            n =  3 * n   1 
    my_list.append(n) 
    return my_list 

The above code takes any input n and outputs a list e.g. f(2) -> [2, 1, 4, 2]

Now I want to look at any range and output just the highest element in said list.

def f_2(i): 
    for i in range (1,101): 
        set_f = set(f(i)) 
        print(max(set_f)) 

So I converted the list to a set and applied the max command to it. All of this has worked as I had intended it so far.

My problem is with the following issue: I want to output all the indexes of all the highest Elements in all generated lists.

E.g. for i in range (1,101): The highest Element is 9232. I tried doing it in the above way, but a set does not have any indexes. However max() does not seem to work on a list of generated lists.

My try was:

def f_3(i): 
    for i in range (1,101): 
        set_f = set(f(i)) 
        if max(set_f) == 9232:
            print(set_f.index(9232))
        else:
            pass

Here I get the error that set has no index attribute.

def f_3(i): 
    for i in range (1,101): 
        if max(f(i)) == 9232:
            print(f.index(9232))
        else:
            pass

Here I get the error that function has no index attribute.

Only the range of 1 to 100 is of interest to me. So I can use 9232 as a value.

Any help would be greatly appreciated, I feel a bit stuck on this one.

CodePudding user response:

There's several things to unpack here, and I feel like the Code Review community would be a better fit.

  • First of all, why does f_2 have the parameter i? You're just using the i from the loop.

  • Second, why are you converting the list into a set at all? max works just fine on lists too.

  • set doesn't support indexing, and that's why you were getting that mistake.

  • At the other attempt with f_3, you've called index on the function f instead of f(i).

Function f_2 can be rewritten as such.

def f_2(): 
    for i in range (1,101): 
        lst = f(i)
        mx = max(lst)
        print(lst.index(mx))
     

Function f_3 is inefficient, but it too can be fixed like this:

def f_3(): 
    for i in range (1,101): 
        if max(f(i)) == 9232:
            print(f(i).index(9232))
  • Related