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

如何解决用Python编写程序来检查数字是否是回文

我是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'。我以为“ a”是在运行digits()函数时定义的。怎么了?

解决方法

引发异常是因为'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,f = digits(n)

def palindrome(n,a,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,f)
,

像塞思(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")
,

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

因此,要解决这些问题,您必须将a函数中的palindrome替换为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,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变量。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-