检查回文的功能中的错误在哪里? [英] Where's the bug in this function to check for palindrome?

查看:95
本文介绍了检查回文的功能中的错误在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面给出的代码用于检查列表是否为回文.它给出了983的正确输出.我在哪里出问题了?

Given below is the code to check if a list is a palindrome or not. It is giving correct output for 983. Where am I going wrong?

def palindrome(num):
    flag=0
    r=num[::-1]
    for i in range (0, len(num)-1):
        if(r[i]==num[i]):
            flag=1
        else:
            flag=0
    return flag

推荐答案

一旦不匹配,您应立即返回.另外,您只需要迭代到一半的长度即可:

You should return as soon as there is a mismatch. Also, you just need to iterate till half the length:

def function(...):
    ...
    for i in range (0, (len(num) + 1) / 2):
        if r[i] != num[i]:
            return False
    return True


顺便说一句,您不需要该循环.您可以简单地做到:


BTW, you don't need that loop. You can simply do:

def palindrome(num):
    return num == num[::-1]

这篇关于检查回文的功能中的错误在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆