使用python中的递归检查列表中是否存在元素

时间:2018-03-10 18:07:07

标签: python arrays list recursion

这是我用Python中的递归检查列表中是否存在元素的代码。根据程序的流程,它应该返回True,而是返回None。请帮忙解释我哪里出错了。提前谢谢。

def numCheck(list,num):
    if len(list) == 0:
        return
    if list[0] == num:
        return True
    else:
        numCheck(list[1:],num)
print(numCheck([1,2,3],2))

1 个答案:

答案 0 :(得分:1)

您需要返回函数调用的结果:

       // [START initialize]
    FileInputStream serviceAccount = new FileInputStream(FILE_NAME);

    GoogleCredentials credentials = GoogleCredentials
        .fromStream(serviceAccount)
        .createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.database"));

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(credentials)
            .setDatabaseUrl(DATABASE_URL)
            .build();
    FirebaseApp.initializeApp(options);
    // [END initialize]

输出:

def numCheck(list,num):
  if len(list) == 0:
    return False
  if list[0] == num:
    return True
  return numCheck(list[1:],num)

print(numCheck([1,2,3],2))