【问题标题】:Writing a program in Python to check whether a number is a palindrome用 Python 编写一个程序来检查一个数字是否是回文
【发布时间】:2020-10-10 19:11:09
【问题描述】:

我是 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、b、c、d、e、f 吗?
  • @DS abcdef 在函数 digits() 中定义。所以它们在palindrome() 内部是不可访问的,因为它不知道它们
  • @D_S 我看到 Maxijazz 发布了一个答案,digits 返回了一个列表,尽管我建议您调整该答案以考虑到 Thierry Lathuille 在其下方的评论。

标签: python palindrome


【解决方案1】:

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

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

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

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

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

它所做的是将数字视为一个字符串,然后将其视为一个字符串并进行比较。

它适用于任何数字。

【讨论】:

    【解决方案2】:

    变量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)
    

    【讨论】:

    • 全局变量通常是要避免的。这里a, b, c, d, e, f = digits(n)应该是palindrome函数的一部分,它只需要一个参数n,其他的都可以推导出来。
    【解决方案3】:

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

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

    在这里,我进行了更正和其他一些小事,并用 cmets 说明我为什么要做这一切。

    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)
    
    

    【讨论】:

    • 您应该只调用一次digits(n) 并将输出存储在一个变量中。
    • @ThierryLathuille 啊我明白你的意思了,这很有道理!
    【解决方案4】:

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

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

    数值处理:

    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
    

    但是,如果你想用数字模式来测试它,是的,你需要划分和检查。

    【讨论】:

      【解决方案5】:

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

      还有两点我想说明:

      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")
      

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-06-25
          • 1970-01-01
          • 2015-02-12
          • 2022-07-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多