我找到的一本书中的一个问题。
Write a program that asks the user to input an integer and prints two integers, root and pwr, such that 0 < pwr < 6 and root**pwr is equal to the integer user entered. If no such pair exists, print that it is impossible to find such a pair.
integer = 3 #there will be raw_input but I use it as an example
root = 0
for pwr in range(1,6):
if root**pwr != integer:
pwr += 1
print pwr
else:
print root, pwr
if pwr > 5:
pwr = 1
root += 1
我还没有完成程序,因为我无法正确循环。问题是我收到输出 2、3、4、5、6,然后循环终止。但是,我确实在您看到的最后一个 if 语句代码块中对 pwr 变量使用了 restart。但是,它无论如何都会停止执行。这里有什么问题?
请您参考如下方法:
正如其他人所指出的,这是 John Guttag 编写的 Introduction to Computation and Programming Using Python 第 3.1 节(关于详尽枚举)的手指练习,这是大规模开放在线类(class)的教科书MITx: 6.00.1x Introduction to Computer Science and Programming Using Python .教科书和类(class)使用 Python 2.7。
我还没有足够高的声誉来评论其他答案,所以请允许我在我的回答前说,在我发布这篇文章时,之前发布的所有答案都不正确或不完整,据我所知。其他答案中的一个常见错误是他们没有考虑所有整数。一个正确的程序应该解决所有整数的问题,包括正整数、负整数和零(zero is also an integer)。
在 Guttag 书中的这个练习之前,我们已经介绍过 while 循环,但没有介绍过 for 循环和 range 函数,两者都是在下一节中介绍。这是我的答案,仅使用本练习之前书中介绍的概念:
num = int(raw_input("Enter an integer: "))
pwr = 1
root = 0
found = False
if num < 0:
neg = True
else:
neg = False
while pwr < 6:
while abs(root**pwr) <= abs(num):
if root**pwr == num:
print(str(root) + "**" + str(pwr) + " = " + str(num))
found = True
if abs(root) > abs(num):
root = 0
elif neg:
root -= 1
else:
root +=1
pwr += 1
root = 0
if not found:
print("No pair of integers, 'root' and 'pwr', exists such that 0 < pwr < 6 and root**pwr = " + str(num))
我用整数 0、1、-1、2、-2、8、-8 和其他一些整数测试了这段代码,它似乎可以工作。
