简体   繁体   English

在合并和排序中列出超出范围的索引 function

[英]list index out of range in a merge and sort function

I tried writing a simple merge and sort function in python and got stuck after getting the following error-我尝试在 python 中编写一个简单的合并和排序 function 并在收到以下错误后卡住 -

List out of range. 

I would appreciate if you could help me fix it and figure out how to avoid it.如果您能帮我解决它并弄清楚如何避免它,我将不胜感激。 I have added the code below-我在下面添加了代码-

def merge(lst1, lst2):
    # Gets two sorted lists and returns one merged and sorted list
    merge_sorted = []
    i = 0
    j = 0
    len1 = len(lst1) - 1
    len2 = len(lst2) - 1
    while i < len1 or j < len2:
        if lst1[i] < lst2[j]:
            merge_sorted.append(lst1[i])
            i += 1
        elif lst1[i] > lst2[j]:
            merge_sorted.append(lst2[j])
            j += 1
        else:
            merge_sorted.append(lst1[i])
            merge_sorted.append(lst2[j])
            i += 1
            j += 1
    return merge_sorted

lst1 = [2, 4, 5, 6, 8]
lst2 = [1, 3, 7, 9, 0]
merge(lst1, lst2)

What I got:我得到了什么:

IndexError                                Traceback (most recent call last)
<ipython-input-13-572aad47097b> in <module>()
     22 lst1 = [2, 4, 5, 6, 8]
     23 lst2 = [1, 3, 7, 9, 0]
---> 24 merge(lst1, lst2)

<ipython-input-13-572aad47097b> in merge(lst1, lst2)
      7     len2 = len(lst2) - 1
      8     while i < len1 or j < len2:
----> 9         if lst1[i] < lst2[j]:
     10             merge_sorted.append(lst1[i])
     11             i += 1

IndexError: list index out of range

Your problem is the while condition:您的问题是 while 条件:

while i < len1 or j < len2:

it should be and - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done.它应该是and - 如果其中任何一个条件不正确,那么您只需 append 将非空列表的其余部分添加到您的结果中,您就完成了。

Your current code still enters the while-body and checks if lst1[i] < lst2[j]: if one of the i / j is bigger then the list you get the error you have.您当前的代码仍会进入 while-body 并检查if lst1[i] < lst2[j]:如果i / j之一更大,那么您会收到错误的列表。


The full fixed code:完整的固定代码:

def merge(lst1, lst2):
    # Gets two sorted lists and returns one merged and sorted list
    merge_sorted = []
    i = 0
    j = 0
    len1 = len(lst1) - 1
    len2 = len(lst2) - 1
    while i < len1 and j < len2:         # use and
        if lst1[i] < lst2[j]:
            merge_sorted.append(lst1[i])
            i += 1
        elif lst1[i] > lst2[j]:
            merge_sorted.append(lst2[j])
            j += 1
        else:
            merge_sorted.append(lst1[i])
            merge_sorted.append(lst2[j])
            i += 1
            j += 1

    # add remainder lists - the slices evaluate to [] if behind the list lengths
    merge_sorted.extend(lst1[i:])  # if i is aready out of the list this is []
    merge_sorted.extend(lst2[j:]) # if j is aready out of the list this is []
    return merge_sorted

lst1 = [2, 4, 5, 6, 8]
lst2 = [0, 1, 3, 7, 9]  # fixed input, needs to be sorted, yours was not
print(merge(lst1, lst2))

Output: Output:

[0, 1, 2, 3, 4, 5, 6, 8, 7, 9]

As suggested by other techies you can modify and run the program but you are simply increasing the time complexity of your program which you could have done in two lines.正如其他技术人员所建议的那样,您可以修改和运行程序,但您只是增加了程序的时间复杂度,您可以在两行中完成。

  • Just extend the list1 elements like只需扩展 list1 元素,如

    list1.extend(list2)
  • once the elements are into the list1一旦元素进入列表1

     print(set(sorted(list1)))

First of all, Your logic is wrong.首先,你的逻辑是错误的。 You are picking the lower numbers and putting them into the list?您正在选择较低的数字并将它们放入列表中吗? but what about the biggest number of all?但是最大的数字呢? You will be stuck there!你会被困在那里! Because you will never pick the last one!因为你永远不会选择最后一个!

I changed the logic.我改变了逻辑。 Instead of counting up the iterators, I removed the picked ones.我没有计算迭代器,而是删除了选择的迭代器。 and when one list got empty the rest of the other one will join the final list.当一个列表为空时,另一个列表的 rest 将加入最终列表。

and secondly, don't use the "merge" name for your function!其次,不要为您的函数使用“合并”名称! It's occupied!被占用了!

def merger(l1, l2):
    merge_sorted = []
    t1, t2 = sorted(l1), sorted(l2)
    while len(t1) != 0 and len(t2) != 0:
        if t1[0] <= t2[0]:
            merge_sorted.append(t1[0])
            t1 = t1[1:]
        else:
            merge_sorted.append(t2[0])
            t2 = t2[1:]
    return merge_sorted + (t1 if len(t1) != 0 else t2)


lst2 = [2, 4, 5, 6, 8]
lst1 = [1, 3, 7, 9, 0, 10]
print(merger(lst1, lst2))

Here are the values for i, j just before that if condition-以下是 i, j 之前的值if条件-

0 0
0 1
1 1
1 2
2 2
3 2
4 2
4 3
5 3

When any of the lists is traversed till the end, it throws index out of range error .当任何列表被遍历到最后时,它会抛出index out of range error

Solution-解决方案-

Instead of using or condition, use and condition and append the remaining list elements at the end of the sorted list.代替使用or条件,使用and条件和 append 排序列表末尾的剩余列表元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM