下面是一个练习,因为它是写的:

手指练习:编写一个程序,要求用户输入一个整数,并打印两个整数,root和numr,使得1 numr 6和root ** numr等于用户输入的整数.<<如果不存在这样的整数对,它应该打印一条消息来表示该效果.

这就是我的 idea :

    num_value = int(input("Enter a number value:"))
    result_state = "unknown"
    for root in range (-abs(num_value),abs(num_value)):
        for pwr in range(2,6):
            test_value = root**pwr
            if test_value == num_value:
                print(f'{num_value} is equivalent to {root} to the power of {pwr}')
                result_state = "Printed"
    if result_state != "Printed":
        print('I was not able to find a root/power integer pair for this number.')

我写的代码工作,但我觉得可能有更有效的方法来达到同样的结果.我也明确地觉得我可能有一点模糊它添加了根范围的绝对函数. 我正在try 使用OpenCourse自己学习Python,但我想确保我不会在理解上出现盲点.所以,提前感谢你的帮助!

推荐答案

以下是对代码的一些改进:

  1. result_statestring更改为boolean.布尔的比较比字符串的比较快.
  2. root的范围从range(-abs(num_value),abs(num_value))更改为range(-sqrt_num, sqrt_num + 1).因为最小的pwr是2,如果root大于abs(num_value)的平方根,test_value不可能等于num_value.
  3. breakif-statement,如果是rootpwr的一对,当root增长时,test_value不可能仍然等于num_value.

以下是更新的代码:

num_value = int(input("Enter a number value: "))
result_state = False
sqrt_num = int(abs(num_value) ** 0.5)

for root in range(-sqrt_num, sqrt_num + 1):
    for pwr in range(2, 6):
        test_value = root ** pwr
        if test_value == num_value:
            print(f'{num_value} is equivalent to {root} to the power of {pwr}')
            result_state = True
            break  # Exit inner loop if pair found

if result_state != True:
    print('I was not able to find a root/power integer pair for this number.')

Python相关问答推荐

Select 用a和i标签包裹的复选框?

pandas DataFrame GroupBy.diff函数的意外输出

如何使用Python将工作表从一个Excel工作簿复制粘贴到另一个工作簿?

我们可以为Flask模型中的id字段主键设置默认uuid吗

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

Odoo 16使用NTFS使字段只读

字符串合并语法在哪里记录

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

使用BeautifulSoup抓取所有链接

基于形状而非距离的两个numpy数组相似性

Python—转换日期:价目表到新行

根据Pandas中带条件的两个列的值创建新列

将CSS链接到HTML文件的问题

使用python playwright从 Select 子菜单中 Select 值

有没有办法在不先将文件写入内存的情况下做到这一点?

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

我怎样才能让深度测试在OpenGL中使用Python和PyGame呢?

如何在表单中添加管理员风格的输入(PDF)

我如何为测试函数的参数化提供fixture 生成的数据?如果我可以的话,还有其他 Select 吗?

搜索结果未显示.我的URL选项卡显示:http://127.0.0.1:8000/search?";,而不是这个:";http://127.0.0.1:8000/search?q=name";