简体   繁体   English

如何在python中正确递归?

[英]How to recurse properly in python?

so, we have two lists of int, and all i am trying to do is to check if first int of list 2 exists in list 1. If so, then negate the first int of list 1. I tried to use recursion, however, i get an error saying "TypeError: 'int' object is unsubscriptable". 因此,我们有两个int列表,而我要做的就是检查列表1中是否存在列表2的第一个int。如果是这样,则取反列表1的第一个int。我尝试使用递归,我收到一条错误消息,提示“ TypeError:'int'对象无法下标”。 Help? 救命?

def search(l1,l2):
    if l1 == [] and l2 == []:
        return []
    elif l1[0] == l2[0]:
        return [-(l1[0]),search(l1[1:],l2[1:])]
    else:
        return search(l1[1:],l2[0])

print search([1,2,1],[1,3,4])

A recursive function has to terminate. 递归函数必须终止。 Your function will only terminate if both lists are empty, which can only happen if you get a hit on your first elif all times, if the last elif kicks in then you will have lists of unequal lengths (also if you make sure you pass a list as an argument and not an integer). 仅当两个列表都为空时,函数才会终止,这仅在您始终击中第一个elif的情况下才会发生,如果最后一个elif插入,则您将具有不等长的列表(也请确保您通过了列出作为参数而不是整数)。

So your first elif suggest you want to check if the first element of l1 is equal to the first of l2, the second of l1 equal to the second of l2, the nth of l1 equal to l2, and so on. 因此,您的第一个elif建议您要检查l1的第一个元素是否等于l2的第一个元素,l1的第二个元素是否等于l2的第二个元素,l1的第n个元素等于l2,依此类推。 The second, however suggests that you want check if any elements in l1 is equal to the first element of the original l2. 但是第二个建议您要检查l1中的任何元素是否等于原始l2中的第一个元素。 If you are just looking for list membership of l2[0] in l1, you can do it a lot easier. 如果您只是在查找l1中l2 [0]的列表成员身份,则可以轻松得多。

So it seems that you need to be more explicit about what you want to return here. 因此,似乎您需要更明确地说明要返回的内容。 The function as it stands cannot work as you try to pass an integer (in the last elif) to the function search that expects a list. 当您尝试将整数(在最后一个省略号中)传递给需要列表的函数搜索时,该函数无法正常工作。

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

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