Search code examples
pythonlistalgorithmgreedy

Having problem in compiling this Greedy Algorithm's python question


I was trying this question which is a greedy algorithm question. The celebration party problem. When i run it , as you can see below, it says list indices must be integer.. Can you help me with this, I am new to algorithm coding. I am also open to better and effective solutions.

Problem:

a=[1,5.4,2.1,3.4,3.1,2.0,1.8,8.9,10,23,4,5,5,2,1.6,1.9]
a.sort()
q=0
z={}
for i in range(len(a)):
    if (a[q]+1.0)>=a[i]:
        if q not in z.keys():
            z[q]=[]
        z[q].append(a[i])
    else:
        q=a[i]
        if q not in z.keys():
            z[q]=[]
        z[q].append(a[i])

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-60bee6e37157> in <module>
      4 z={}
      5 for i in range(len(a)):
----> 6     if (a[q]+1.0)>=a[i]:
      7         if q not in z.keys():
      8             z[q]=[]

TypeError: list indices must be integers or slices, not float


Solution

  • The problem is with using q after you have assigned it to the values in a

    a=[1,5.4,2.1,3.4,3.1,2.0,1.8,8.9,10,23,4,5,5,2,1.6,1.9]
    a.sort()
    q=0
    z={}
    for i in range(len(a)):
        if (a[q]+1.0)>=a[i]: # this is the problem that you have an error
            if q not in z.keys():
                z[q]=[]
            z[q].append(a[i])
        else:
            q=a[i] #here you are assigned the value to q, which can be a float
            if q not in z.keys():
                z[q]=[]
            z[q].append(a[i])
    

    When you check if (a[q]+1.0)>=a[i], it is taking the list a and checking the index using the value q. Since that value can be a float, you can have the error, since index must be an int.

    You can change the loop to track the index instead:

    a=[1,5.4,2.1,3.4,3.1,2.0,1.8,8.9,10,23,4,5,5,2,1.6,1.9]
    a.sort()
    q=0
    qidx=0
    z={}
    for i in range(len(a)):
        if (a[qidx]+1.0)>=a[i]:
            if q not in z.keys():
                z[q]=[]
            z[q].append(a[i])
        else:
            q=a[i]
            qidx = i
            if q not in z.keys():
                z[q]=[]
            z[q].append(a[i])
    

    Which will output

    {0: [1, 1.6, 1.8, 1.9, 2.0, 2], 2.1: [2.1, 3.1], 3.4: [3.4, 4], 5: [5, 5, 5.4], 8.9: [8.9], 10: [10], 23: [23]}