3

我找到的一本书中的一个问题。

编写一个程序,要求用户输入一个整数并打印两个整数,root 和 pwr,使得 0 < pwr < 6 并且 root**pwr 等于用户输入的整数。如果不存在这样的对,则打印不可能找到这样的对。

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 。但是,它无论如何都会停止执行。这里有什么问题?

4

25 回答 25

5

正如其他人所指出的,这是John Guttag 的《使用 Python 进行计算和编程导论》第 3.1 节(详尽枚举)的手指练习,这是大规模开放在线课程MITx:6.00.1x 计算机科学导论和使用 Python 编程。教科书和课程使用Python 2.7

我还没有足够高的声誉来评论其他答案,所以请允许我在我的答案前言,在我发布此内容时,据我所知,以前发布的所有答案都是不正确或不完整的. 其他答案中的一个常见错误是他们没有考虑所有整数。一个正确的程序应该解决所有整数的问题,包括正整数和负整数以及零(零也是整数)。

在 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 和其他一些整数测试了这段代码,它似乎可以工作。

于 2016-02-01T15:41:31.987 回答
2

另一种选择,使用“简单数学”。

integer = 3

for power in range(1,6):
    a = (integer ** (1.0/power))
    if math.ceil(a) == a:
        print a, power

>> 3.0 1
于 2012-11-30T16:05:57.067 回答
2

一般来说,修改循环内循环的内容不是一个好主意。pwr当您使用它来迭代时,没有理由摆弄range(1,6).

您的代码试图做的是测试root ** pwr == integer的连续值pwr和固定值,root直到pwr达到 6。然后您希望它添加一个root并重复。这最自然地表述为两个嵌套的 for 循环:

for root in range(0,integer):
    for pwr in range(1,6):
        if root ** pwr == integer:
            print root, pwr

无论如何,这是一种相当昂贵的方法,因此我建议您在此处查看其他一些解决方案。但是,您应该记住这一点,因为它是如何使用 for 循环的一个很好的例子。

要回答关于循环为何终止的问题,您必须考虑 python 如何处理迭代器。当 for 循环内的代码块终止时,python 将设置pwr为 iterators 方法返回的值next()(它完全按照您的想法执行)。当迭代器中没有更多值时,next()将引发StopIteration异常,Python 将退出循环。关键是 Python 不会pwr通过每次迭代加 1 来修改 的值,它会覆盖该值。所以你循环将运行 5 次,因为那是有多少项目range(1,6)

为了澄清,请运行以下代码:

for i in range(0,9):
    print i
    i += 5
    print i
于 2012-11-30T16:10:30.040 回答
1

integer ** 1总是满足条件。

另一种选择(假设你真的想要1 < pwr < 6):

检查是否有某个基数a和一个数字nceil(a ** log_a(n)) == n。如果是这样 - 那么a ** log_a(n)这就是你的答案。 对范围内所有可能的 '
重复此操作。a

(这里log_a(n)是以 a 为底的对数,可以计算为log(n)/log(a)

于 2012-11-30T15:34:50.970 回答
1

正如其他人所提到的,这是John Guttag的Introduction to Computation and Programm Using Python中的手指练习。

虽然上述一些响应可能有效(老实说,我没有测试过),但更简单的方法将产生所需的结果并适应负整数,例如:

x = int(input("Enter an integer: "))
root = 0

while root < abs(x):
    root += 1
    for pwr in range(1,6):
        if root ** pwr == abs(x):
            if x < 0:
                print(-root, "to the power of", pwr, "=", x)
            else:
                print(root, "to the power of", pwr, "=", x)
于 2017-12-15T15:15:37.203 回答
1

我有一个逻辑错误,在试图弄清楚它可能是什么时,我浪费了很多时间,我认为这可能是一个常见的错误。我忘了重置pwr外循环中的值。

这是当前版本:

root=0
pwr=1
check=0
integer=int(input('Enter the number:'))
while(root**pwr<abs(integer)):
    while(pwr<6):
        if root**pwr==abs(integer):
            check=1
            print('Root =',root,'or -'+ str(root),'and Power =',pwr)
        pwr+=1
    root+=1
    pwr=1    #<--------------Resetting pwr to 1 inside the outer loop
if check!=1:
    print('No such combination exists')

我希望这有助于节省一些时间。

于 2018-01-13T03:54:23.237 回答
1

这就是我想出的。正如在上一篇文章中提到的,pwr 的范围应该是 2-6,因为整数到 pwr 1 的答案总是存在的,并且练习表明存在不存在这样对的整数。

x = int(input('Enter an integer: '))
root = 0
pwr = 2
while pwr > 1 and pwr < 7:
    while root**pwr < x:
        root = root + 1
    if root**pwr == x:
        print(str(root) + '**' + str(pwr), '==', str(x))
        break
    else:
        root = 1
        pwr = pwr + 1
else:
    print('no such pair exists')
于 2018-08-09T20:25:10.433 回答
1

打印递减函数的长版本答案 - 仅用于小数字

x = int(input('Enter an integer:'))

pwr = [1,2,3,4,5]
mypairs = []

for p in pwr:
    root = 0 
    while root**p < abs(x):
        print('Value of decrementing function abs(x) - root**p is',\
              abs(x)-root**p)
        root = root + 1
    if root**p == abs(x) and p%2 !=0:
        print('For the power %s there exists such a pair, shown in final list.'%p)

    if root**p != abs(x):
        print('For the power %s there does not exist any such pairs.'%p)
    else:
        if x < 0:
            if p%2 == 0 :
                print('For the power %s there does not exist any such pairs'%p)
            else:
                root = -root            
                mypairs.append([root,p])
        else:
            mypairs.append([root,p])
print(mypairs)

无需递减函数即可快速回答

x = int(input('Enter an integer:'))

pwr = [1,2,3,4,5]
mypairs = []

for p in pwr:
    root = 0 
    while root**p < abs(x):
        root = root + 1
    if root**p != abs(x):
        print('For the power %s there does not exist any such pairs.'%p)
    else:
        if x < 0:
            if p%2 == 0 :
                print('For the power %s there does not exist any such pairs'%p)
            else:
                root = -root            
                mypairs.append([root,p])
        else:
            mypairs.append([root,p])
print(mypairs)
于 2019-02-26T07:16:59.377 回答
0

这是 John Guttag 的“使用 Python 进行计算和编程简介”第 3 章的手指练习,内容如下:

编写一个程序,要求用户输入一个整数并打印两个整数,root 和 pwr,使得 0 < pwr < 6 并且 root**pwr 等于用户输入的整数。如果不存在这样的对,它应该打印一条消息。

鉴于作者指出可能不存在对,我假设 pwr 的条件应该是 1 < pwr < 6 否则总会有一个解决方案(整数**1)。我的回答是,仅使用书中已经介绍过的概念:

num = int(raw_input('Enter a positive integer: '))
pwr = 2
root = 1
ans = ''
while pwr < 6:
    while root**pwr <= num:
        if root**pwr == num:       
            print 'the root is ',root,
            print 'the power is ', pwr
            ans = True
        root += 1        
    pwr += 1
    root = 1
if ans != True:
    print'No such pair of integers exist'
于 2014-03-14T00:41:52.023 回答
0

首先,如果我们输入一个整数,例如 1024,那么我们就有 1024^1 = 1024。所以这个问题总会有解决方案:

n = int(input('Enter an integer: '))
pwr = 1
root = 1
found = False

while root <= n:
    if root**pwr == n:
        print('root =',root, 'pwr =', pwr)
        found = True
    pwr = pwr + 1
    if pwr == 6:
        pwr = 1
        root = root + 1

if not found:
    print('No such pair exist.')
于 2014-07-17T22:40:28.957 回答
0

这是基于archery1234提交的答案。感谢archery1234 a,我对这个很陌生,没有帮助我无法开始。我喜欢所提供的答案,因为它只使用了书中到目前为止解释的概念,所以我觉得它接近 Guttag 博士可能希望我们学习的内容(while 循环中的 while 循环)。下面的代码满足 0 < pwr < 6 的条件,而不总是仅仅终止于作为根输入的整数和 pwr = 1。

integer = abs(int(raw_input("Enter an integer: ")))
pwr = 1
root = 2
ans = ' '
if abs(integer) == 1:
    print "No such pair of integers exists"
else:
    while root < abs(integer):
        while root**pwr <= integer:
            if root**pwr == integer:
                print "The root is ",root,";"
                print "The power is ",pwr,"."
                ans = True
            pwr += 1
        root += 1
        pwr = 1
    if ans != True:
        print "No such pair of integers exist"
于 2014-10-17T13:04:13.120 回答
0

我正在解决这个问题,我的答案有效:

number = int(raw_input("Enter a number: "))
    i = 1

    pwr = 1
    test = 0
    while i <= number/2:
        while pwr < 6:
            if i ** pwr == number:
                print i
                test = 1
            pwr = pwr + 1
        i = i + 1
        pwr = 1
    if test == 0:
        print 'No such pair of integers exist.'
于 2015-01-18T19:30:14.013 回答
0

这是我的回答:

usr = int(raw_input("Enter an integer > "))
paired = False
for pwr in range(1,6):
    root = 0
    while (usr - root**pwr > 0):
        root += 1
    if usr == root**pwr:
        paired = True
        print "root is " + str(root) + " and ",
        print "power is " + str(pwr)
        break
if paired == False:
    print "No pair"
于 2016-01-16T16:49:35.557 回答
0

我已经设法用你在 Gattug 的书中从第 1 章到第 3.1 章获得的知识解决了这个问题。这个手指练习花了我两个星期才完成。我也刚开始编码。

这是我的解决方案:

num = int(raw_input('Enter an integer: ')) 
root = num 
power = 1 

if root**power == abs(num):
   print ' First pair of integers which equal the integer:', num, 'is root = ', root, 'power = ', power
   root -= 1
while root**power != abs(num) and root > 0:
while power < 6 and root**power != abs(num):
      if not(root**power == abs(num)):
         power +=1
      if not(root**power == abs(num)):
         power +=1 
if power >= 6 and root**power != abs(num):
    power = 1
    root -= 1
if root**power == abs(num):
print 'Second pair of integers which equal the integer:', num, 'is root = ', root, 'power = ', power
elif root**power != abs(num) and root == 0:
print ' there is no other pair of integers that equal', num

我已经做到了,这是教你编码的最好的书

于 2016-01-31T07:11:20.637 回答
0

试图在不重新定义手指练习规范的情况下做到这一点,只使用本书迄今为止介绍的内容——这适用于正整数和负整数,据我所知,它将列出所有可能的对,包括 root=number , pwr=1。其中一个关键似乎是在正确的位置使用 abs,如果用户整数为负数,请确保将 root 设置为负数。希望这有助于像所有其他深思熟虑的贡献一样帮助我的人。

num = int(raw_input('Enter an integer: '))
pwr = 1
root = 1
ans = ''
while pwr < 6:
    while root**pwr <= abs(num):
        if root**pwr == abs(num):
            if num<0:
                root=-root
        print 'the root is ',root, 'the power is ', pwr
        ans = True
        root= abs(root)+1
    pwr += 1
    root = 1
if ans != True:
    print'No such pair of integers exist'
于 2016-04-18T19:00:01.597 回答
0

我正在自学python,我的解决方案如下。

num = int(input('Please enter integer: '))
list= []
list1=[]
for root in range (0,num):
    for pwr in range (1,6):
        if root**pwr == num:
            list.append([root,pwr])
        else:
            list1.append(0)
if list ==[]:
    print ('No root exist')
else:
    print (list)

我创建了列表以保存其中的所有根和 pwrs。

于 2016-06-15T14:26:38.200 回答
0

我喜欢布拉格的解决方案,但我认为它有所改进。如果找到解决方案,例如在布拉格的解决方案中以最低值结束,我会停止它, 16 将返回 2^3 和 4^2 ,这是真正的答案。我自己已经放入了非零部分并使用 for 解决了它,但我意识到,正如 Pragu 雄辩地指​​出的那样,我们还没有在书中到达那里。这就是我所做的。

# -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 12:03:09 2018

@author: chief
"""

import random #this imports the random function
mysteryNumber = int(input('Please enter a non-zero positive integer: ')) #give me input Seymour!
if mysteryNumber <= 0: #did they give me a non-zero positive integer?
    print("that wasn't a non-zero positive integer doofenshmirtz!! I'll fix that for you") #Carl would understand
    if mysteryNumber < 0: #make it a positive integer
        mysteryNumber = -mysteryNumber
    if mysteryNumber == 0: #make it a non zero integer by generating random number
        mysteryNumber = random.randint(1,100)
print ('Your number is', mysteryNumber)
root=0 #set the variables or clear the pallet if you will
pwr=1
check=0

while(root**pwr<abs(mysteryNumber)): #first while loop 
    while(pwr<6) and check == 0: # this and logical stops it at the earliest answer otherwise 16 will give you two answers as will 81
        if root**pwr == abs(mysteryNumber): #if then loop checks did you find the answer, if yes then next 2 lines are active, if no then to the else line
            check=1
            print('The root =',root,'or -'+ str(root),'and Power =',pwr, 'will yield', mysteryNumber)
        pwr+=1 #else line, adds 1 to the pwr and moves back to the while statement of while<6
    root+=1 #While pwr <6 is done so we go onto the next root
    pwr=1    #<--------------Resetting pwr to 1 inside the outer loop
if check!=1: #the first while is done now, if we found an answer this argument returns false and the line below doesn't get executed
    print('No rational combination of root and power exists for', mysteryNumber)
于 2018-01-13T18:50:49.487 回答
0
number = int(raw_input("Enter a number: "))
pwr = 1
root = 2

while root < number:
    pwr = 1
    while pwr < 6:
        if root*pwr == number:
            print'Numbers are', (root, pwr)
        pwr += 1
    root += 1
    print('No such numbers')
于 2018-02-26T15:54:49.787 回答
0

我认为这个问题已经得到解答,但希望这可以扩展当前的工作状态。任何反馈表示赞赏!

我目前正在 MIT OpenCourseWare 上解决这个问题。我想提出一个解决方案,可以打印给定整数的所有可能的 root/pwr 组合,同时将详尽的猜测限制为最小数量。这是我的回答:

intNum = int(input("Please enter an integer: "));
neg = False;

if intNum < 0:
    neg = True;

root = 0;
pwr = 2;

print("The integer is: ", intNum);
# Will always have at least one root/pwr such that intNum=root and pwr = 1
print ("rootFOUND: ", intNum, " pwrFOUND : ", 1);

while 0 < pwr < 6:
    while root**pwr <= abs(intNum):
#        print ("root: ", root, " pwr: ", pwr);
        if root**pwr == abs(intNum):
            if neg and pwr%2 != 0:
                print ("rootFOUND: ", -root, " pwrFOUND : ", pwr);
            elif not neg:
                print ("rootFOUND: ", root, " pwrFOUND : ", pwr);
        root += 1;
    pwr += 1;
    root = 0;

我想考虑的边界是:

  1. 如果整数是正数
  2. 如果整数是负数
  3. 如果整数为零

思考过程:

  1. 通过将初始根值设置为零并在 root**pwr 小于输入的整数时递增来实现正整数。

  2. First 完成了一个负整数,总是检查整数是否为负数。其次,随着 root 的增加,root**pwr 会根据整数的绝对值进行检查。最后必须考虑的事实是,负整数只有在指数为奇数时才能通过指数语句找到。这是通过检查整数是否为负数和指数是否为奇数来完成的。

  3. 通过将初始根设置为零并在退出内部 while 循环时始终将根重置为零来完成零整数检查。

以下是一些输出:

Please enter an integer: -4096
The integer is:  -4096
rootFOUND:  -4096  pwrFOUND :  1
rootFOUND:  -16  pwrFOUND :  3

Please enter an integer: 4096
The integer is:  4096
rootFOUND:  4096  pwrFOUND :  1
rootFOUND:  64  pwrFOUND :  2
rootFOUND:  16  pwrFOUND :  3
rootFOUND:  8  pwrFOUND :  4

Please enter an integer: 0
The integer is:  0
rootFOUND:  0  pwrFOUND :  1
rootFOUND:  0  pwrFOUND :  2
rootFOUND:  0  pwrFOUND :  3
rootFOUND:  0  pwrFOUND :  4
rootFOUND:  0  pwrFOUND :  5
于 2018-08-02T18:35:52.193 回答
0

我相信这可能是一个更优雅的解决方案,因为它以最少的初始化提供了所有可能的根,并且根据 Guttag 文本仅使用 while 循环。请试一试。我相信它适用于所有用例。

我使用根等于整数来打破循环,以便我可以在每次迭代时重置功率。这可以防止 while 循环的任何过载。(根==整数与幂等于1的情况相同)

integer = int(input("Enter an integer please: "))
root = 0
pwr = 0
while root**pwr < abs(integer):
    root = root + 1
    while pwr < 6:
        pwr = pwr + 1
        if root**pwr == integer:
            print("Root:", root, ", Power:", pwr)
    if root == integer:
        break
    pwr = 0

整数 = 343 的输出:

根:7,功率:3

根:343,功率:1

于 2019-02-18T08:48:49.073 回答
0

这就是我使用两个while循环所拥有的

x = int(input('Enter an integer'))
root = 0
pwr = 0

while(root**pwr < abs(x)):

    while(root**pwr < abs(x) and pwr < 6):
        pwr += 1
        #print('root',root, ' power', pwr, 'result', root**pwr)
        if(root**pwr == abs(x)):
            if(x<=0):
                print('root', -root, 'power', pwr)
            else:
                print('root', root, 'power', pwr)
            break

    if(root**pwr == abs(x)):
        break
    else:
        root+=1
        pwr = 0

if(root**pwr!=x):
    print('no result found')

于 2019-04-10T17:48:50.590 回答
0
#instead of asking for input, i input random so you could test faster 
#and greater range of integers

input = randint(-10000,10000)
root = 0
power = 1

while root <= abs(input):
  if root**power == abs(input):
      break
  # if power is within bounds, increment, else reset it to 1 and increment 
  # root to loop through
  if power < 6:
      power = power + 1
  else:
      power = 1
      root = root + 1

if root**power != abs(input):
    print("There are no perfect integers")
else:
    if input < 0:
        root = -root
    print("Root:",root,"; Power:",power)
于 2019-10-19T22:32:25.483 回答
0

这是使用Python 3.7.6的最新答案(2020 年 6 月) ,用于John Guttag 的《使用 Python 进行计算和编程简介》的第二版。

正如巨无霸所写

正如其他人所指出的,这是 John Guttag 的《使用 Python 进行计算和编程导论》第 3.1 节(详尽枚举)的手指练习,这是大规模开放在线课程 MITx:6.00.1x 计算机科学导论和使用 Python 编程。教科书和课程使用 Python 2.7。...其他答案中的一个常见错误是他们没有考虑所有整数。一个正确的程序应该解决所有整数的问题,包括正整数和负整数以及零(零也是整数)。

在 Guttag 书中的这个练习之前,我们已经介绍了 while 循环,但没有介绍 for 循环和 range 函数,这两者都将在下一节中介绍。

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

x = int(input('Enter an integer to analyze '))
root = 0
pwr = 1
while pwr < 6:   
    while root**pwr < abs(x):
        root += 1     
    if abs(root**pwr) != abs(x):
        print('no root at the power', pwr, 'for', x)
    else:
        if x < 0:
            root = -root
            if pwr%2 != 0:
                print (root, "**", pwr, '=', x)
            else:
                print('no root at the power', pwr, 'for', x)                
        else:
            print (root, "**", pwr, '=', x)         
    root = 0    
    pwr += 1 

这个解决方案对所有整数都有效,使用Python 3,稍微短一些(相对于迄今为止在参考书第二版中获得的知识),并且通过打印每个幂的答案稍微更完整(据我所知)即使不存在这样的对

它将返回类似的结果

Enter an integer to analyze -8
-8 ** 1 = -8
no root at the power 2 for -8
-2 ** 3 = -8
no root at the power 4 for -8
no root at the power 5 for -8   
于 2020-06-07T10:23:00.990 回答
0
x = int(input("Enter an Integer :"))
root = 1
pwr = 0


while root**pwr != abs(x) and x != 0 :
    if pwr == 6 :
        pwr = 0
        root = root + 1
    else :
        pwr = pwr + 1
if x > 0 :
    print(root,"**",pwr,"==",x)
elif x < 0 :
    if pwr%2 == 0 :
        print ("no solution")
    else :
        print(-1*root,"**",pwr,"==",x)
else :
    print("no solution")

大家好,我认为有很多方法可以解决这个问题。目前我也只是从书中学习phyton。

由于这是使用“while”的迭代部分的问题,我认为预期的解决方案也使用“while”。

于 2020-08-14T18:25:40.053 回答
0
integer = int(input('Enter an integer: '))


root = 0
ans=0
isTrue=False
while (root < integer):    
    for pwr in range(1,6):
       ans=root**pwr      
    
       if ans==integer:            
           print(root, 'to the power', pwr, '=', ans)
           isTrue= True        
   root = root+1 

if isTrue != True:
    print('No such pair of integers exists')
           
    
于 2021-01-05T16:35:41.257 回答