Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将整数表示为根和幂_Python - Fatal编程技术网

Python 将整数表示为根和幂

Python 将整数表示为根和幂,python,Python,我目前正在学习python,这是我编写的以根及其幂的形式表示整数的代码。当网站上的其他答案使用While循环时,我希望使用for循环来改进并使我的代码更加优雅。我还为输入的正数加上了负根(如果有的话)。我能做些什么来改进这一点?我在OCW课程中使用了约翰·古塔格(John Guttag)的书,对这些东西只有一个基本的概念。总是会有根和电源对,所以根找不到线对我来说是无用的 alpha=int(input("Enter an integer to find all its roots:&

我目前正在学习python,这是我编写的以根及其幂的形式表示整数的代码。当网站上的其他答案使用While循环时,我希望使用for循环来改进并使我的代码更加优雅。我还为输入的正数加上了负根(如果有的话)。我能做些什么来改进这一点?我在OCW课程中使用了约翰·古塔格(John Guttag)的书,对这些东西只有一个基本的概念。总是会有根和电源对,所以根找不到线对我来说是无用的

alpha=int(input("Enter an integer to find all its roots:"))
root=0
found=False
if alpha >=0:
    for power in range (1,6):
        for root in range(alpha+1):
            if root**power==alpha:
                print("Root:",root,"power:",power)
                found=True
                if power in range(2,6,2) and root!=0:
                    print("Root:",-root,"Power",power)       
elif alpha<0:
    for power in range (1,6):
        for root in range(0,alpha-1,-1):
            if root**power==alpha:
                print("Root :",root,"power: ",power)
                found= True
if not found:
    print("No such root and power pair is possible for",alpha)
    
alpha=int(输入(“输入一个整数以查找其所有根:”)
根=0
发现=错误
如果α>=0:
对于范围(1,6)内的功率:
对于范围内的根(alpha+1):
如果根**幂==α:
打印(“Root:,Root,“power:,power”)
找到=真
如果幂在范围(2,6,2)和根中=0:
打印(“根:”,-Root,“电源”,电源)

elif alphaNote:只有当问题与python3版本特定的问题相关时,才使用python3标记。这不仅仅是因为您正在运行python3。这种类型的“如何改进我的代码”问题更适合该网站。花点时间阅读关于如何提出好问题的文章,欢迎来到StackOverflow!“6”的意义是什么?为什么您认为
for
循环可以改进您的代码并使其“更加优雅”。通常,当您预先知道要迭代的一组特定值时,您会使用
for
循环;当您只知道在什么条件下希望循环停止时,您会使用
while
循环。一个通常并不比另一个更好或更优雅。考虑到
6
在这里似乎是一个任意数,我可能认为
while
更适合在一些不太随意的条件下停止循环。您应该中断一次内部循环
root**power>alpha
,因为一旦这是真的,它将适用于所有未来的迭代(您应该在不计算候选值两次的情况下执行此操作)。对于一些非常小的值,此代码将给出错误的结果。我相信它将忽略因子的第一个值是
64
2^6
)。