I'm working out of a book that teaches the principles of computer programming through Python. One of the finger exercises asks that I: Write a program that asks a 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 entered by the user. If no such pair of integers exists, it should print a message to that effect. I wrote a program that does what this asks. I just have one question about testing the equation with the numbers of a list. Here's my code:

x = int(raw_input('Enter an integer: '))
root = 0
pwr = [1,2,3,4,5]
listnum = 0

for root in range(0, x + 1):  
    while pow(root, pwr[listnum]) < x:
        root += 1
        if pow(root, pwr[listnum]) == x:
                print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
                break
        listnum += 1
        if pow(root, pwr[listnum]) == x:
                print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
                break
        listnum += 1
        if pow(root, pwr[listnum]) == x:
                print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
                break
        listnum += 1
        if pow(root, pwr[listnum]) == x:
                print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
                break
        listnum += 1
        if pow(root, pwr[listnum]) == x:
                print str(root) + '^' + str(pwr[listnum]) + ' = ' + str(x)
                break
        listnum = 0
    if pow(root, pwr[listnum]) == x:
        break
    else:
        print 'No combinations within parameters exist'

I'd like to know how to test if pow(root, pwr[listnum]) < x for all 5 increments without having to repeat listnum += 1...if...break repeatedly. If the question is unclear I can try to elaborate more. I've seen a question regarding this exact problem, but none of them clearly answer the specific question I have, so I have no intention of reposting a question. If any other suggestions are to be made, they are much appreciated. Thanks!

有帮助吗?

解决方案

Here's one way to do what you're after:

def find(x):
    for root in range(x + 1):
        for pwr in range(1, 6):
            y = pow(root, pwr)
            if y > x:
                break
            if y == x:
                return root, pwr
    return None

x = int(raw_input('Enter an integer: '))
result = find(x)
if result is None:
    print 'No combinations within parameters exist'
else:
    root, pwr = result
    print root, "**", pwr, "=", x

I'm not sure that's what you do want, though. ^ in Python is bitwise exclusive-or, not exponentiation. So it's peculiar that the problem statement used ^.

Another peculiarity is that "No combinations ..." will never be printed, because no matter what you enter for x, pow(x, 1) == x will be found as a solution.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top