【问题标题】:Having problem in compiling this Greedy Algorithm's python question [duplicate]在编译这个贪婪算法的python问题时遇到问题[重复]
【发布时间】:2020-07-17 19:24:09
【问题描述】:

我正在尝试这个问题,这是一个贪心算法问题。庆功宴问题。 当我运行它时,如下所示,它说列表索引必须是整数.. 你能帮我吗,我是算法编码的新手。 我也愿意接受更好、更有效的解决方案。

问题:

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

【问题讨论】:

  • 你能贴出你正在运行的代码吗?
  • 我的意思是你的问题,而不是 cmets。
  • 由于某种原因没有添加图片。
  • 我正在尝试,但我做不到,因为我是新手,所以我无法发布有问题的图片,截至目前,我必须等待 90 分钟才能添加另一个问题。
  • 不添加图片,通过编辑问题添加代码。提出新问题不会有帮助。

标签: python list algorithm greedy


【解决方案1】:

问题在于在将 q 分配给 a 中的值之后使用 q

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

当您检查if (a[q]+1.0)&gt;=a[i] 时,它会获取列表a 并使用值q 检查索引。由于该值可以是浮点数,因此您可能会遇到错误,因为 index 必须是 int。

您可以更改循环以跟踪索引:

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

哪个会输出

{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]}

【讨论】:

  • 非常感谢。你帮了我很大的忙。
  • @RohitRajsuryaPrasad 太好了,如果您单击复选标记为已接受,其他人就会知道他们不需要也回答。
【解决方案2】:

else 块的开头,你说q=a[i]。由于a 中有浮点数,因此在循环中的某个时刻,q 被设置为浮点数。即使该浮点数类似于 2.0,当您尝试将其用作列表的索引时,python 仍会引发错误。要解决这个问题,您需要从列表 a 中删除所有浮点数。

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多