繁体   English   中英

用Python编写一个程序来检查一个数字是否是回文

[英]Writing a program in Python to check whether a number is a palindrome

我是 Python 编程的新手,正在编写一个程序来检查最多六位数字的整数是否是回文。 这是我的代码:

def digits(n):
    a = (n%10)/1
    b = ((n-a)%100)/10
    c = ((n-a-10*b)%1000)/100
    d = ((n-a-10*b-100*c)%10000)/1000
    e = ((n-a-10*b-100*c-1000*d)%100000)/10000
    f = ((n-a-10*b-100*c-1000*d-10000*e)%1000000)/100000
    
n = 123321
digits(n)

def palindrome(n):
    if a==f and b==e and c==d:
        return True
        print("is a palindrome")
    else:
        return False
        print("is not a palindrome")

palindrome(n)

函数digits() 给出我输入的数字的前六位数字。回文函数检查第一位数字是否等于第六位,第二位到第五位,依此类推。 当我尝试运行代码时收到以下错误消息:

Traceback (most recent call last):
  File "<string>", line 20, in <module>
  File "<string>", line 13, in palindrome
NameError: name 'a' is not defined
> 

它说变量“a”未定义。 我以为在运行digits() 函数时定义了'a'。 这里出了什么问题?

引发异常是因为 'a' 是在digits范围内定义的,而不是传递给palindrome

您可以返回数字并像seth提供的那样传递它们,但在 python 中使用每种类型的最佳质量是一门艺术。

在您的情况下,使用索引访问字符串或列表比整数更好,因此raphael的答案以这种方式更好。

但是,通过利用字符串的切片功能,甚至可以实现更好的解决方案,这使我想到了我能想到的最 Pythonic 的解决方案:

is_palindrom = lambda number: str(number) == str(number)[::-1]

它所做的是将数字视为字符串,向后视为字符串并比较它们。

它适用于任何数字。

变量abcdef是局部变量。 像这样使它们成为全局变量:

def digits(n):
    a = (n%10)/1
    b = ((n-a)%100)/10
    c = ((n-a-10*b)%1000)/100
    d = ((n-a-10*b-100*c)%10000)/1000
    e = ((n-a-10*b-100*c-1000*d)%100000)/10000
    f = ((n-a-10*b-100*c-1000*d-10000*e)%1000000)/100000
    return a, b, c, d, e, f
    
n = 123321
a, b, c, d, e, f = digits(n)

def palindrome(n, a, b, c, d, e, f):
    if a==f and b==e and c==d:
        return True
        print("is a palindrome")
    else:
        return False
        print("is not a palindrome")

palindrome(n, a, b, c, d, e, f)

就像 Seth 和 Alani 指出的那样,您面临的问题是 af 仅在函数内可用。

还有两点我想说明:

  1. 您不需要模计算来获得第 n 位数字。 您可以简单地将您的数字转换为字符串并通过索引访问数字。

  2. 您的打印件将无法使用,因为它们是在返回后出现的,因此无法访问。


def palindrome(number):
    number_str = str(number)
    if number_str[0] == number_str[5] and number_str[1] == number_str[4] and number_str[2] == number_str[3]:
        return True
    else:
        return False


n = 123321
if palindrome(n):
    print(f"{n} is a palindrome")
else:
    print(f"{n} is not a palindrome")

未定义a的原因是您只是将其作为变量键入,而a仅在函数digits内部定义。 此外,函数digits不返回任何内容。 因此,即使您要调用该函数来获取隐藏在其中的a变量,该函数也会返回null

因此,要解决这些问题,您必须将palindrome函数中的a替换为digits(n)[a] ,并且必须让digits函数返回一些内容,最好是af的简单列表。

在这里,我提出了我的更正和其他一些小问题,并附有评论以说明我为什么要这样做。

def digits(n):
    a = (n % 10) / 1
    b = ((n - a) % 100) / 10
    c = ((n - a - 10 * b) % 1000) / 100
    d = ((n - a - 10 * b - 100 * c) % 10000) / 1000
    e = ((n - a - 10 * b - 100 * c - 1000 * d) % 100000) / 10000
    f = ((n - a - 10 * b - 100 * c - 1000 * d - 10000 * e) % 1000000) / 100000

    # returns a list of all the variables you created, so you can access them from outside.
    return [a, b, c, d, e, f]


# if you call this variable "n" then it can get confusing because all the functions also use "n". the functions will 
# therefore "shadow 'n' from outer scope", which is something we want to avoid.
number = 123321


def palindrome(n):
    # here we are calling the digits function on "n", and collecting the values from that list we made.
    if digits(n)[0] == digits(n)[5] and digits(n)[1] == digits(n)[4] and digits(n)[2] == digits(n)[3]:
        # you can't return True before you print, because when you return something the function instantly quits, and 
        # the print() statement will never be reached.
        print("is a palindrome")
        return True
    else:
        print("is not a palindrome")
        return False


palindrome(number)

您可以将数字转换为字符串并检查字符串的反向是否与原始字符串匹配。 这将是最简单的方法。 我知道您可能需要使用数字来检查它们。

下面,我为您提供了数值处理和字符串处理的解决方案。 此外,此解决方案不限制您使用六位数。

数值处理:

def check_numeric_pal(numval):
    temp = numval
    ln = len(str(temp))
    x = int(ln/2)
    for i in range (x):
        ln -= 1
        a = int(temp/(10**ln))
        b = int(temp%10)
        if a != b:
            print (numval, 'is NOT a Palindrome')
            break
        temp = int((temp - (a* (10**ln) + b))/10)
        ln -= 1
    else:
        print (numval, 'is a Palindrome')

字符串处理

def check_palindrome(numval):
    if str(numval) == str(numval)[::-1]:
        print (numval,'is a Palindrome')
    else:
        print (numval,'is NOT a Palindrome')

调用数字函数:

print ('Processing as numerics values')   
check_numeric_pal(12345654321)
check_numeric_pal(12345678901)
check_numeric_pal(123321)
check_numeric_pal(123456)
check_numeric_pal(12321)
check_numeric_pal(12345)

调用字符串函数

print ()   
print ('Processing as a string')   
check_palindrome(12345654321)
check_palindrome(12345678901)
check_palindrome(123321)
check_palindrome(123456)
check_palindrome(12321)
check_palindrome(12345)

这些的输出是:

Processing as numerics values
12345654321 is a Palindrome
12345678901 is NOT a Palindrome
123321 is a Palindrome
123456 is NOT a Palindrome
12321 is a Palindrome
12345 is NOT a Palindrome

Processing as a string
12345654321 is a Palindrome
12345678901 is NOT a Palindrome
123321 is a Palindrome
123456 is NOT a Palindrome
12321 is a Palindrome
12345 is NOT a Palindrome

但是,如果要使用数字模式进行测试,是的,您需要进行划分和检查。

重新排列“回文”函数,将“数字”函数的操作放入其中。 另外,我建议您将 a,b,c,d,e,f 初始化为 int 变量。

暂无
暂无

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

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