I am trying to solve Finger Exercise 3.1, and I can't figure out what I am doing wrong here. When I enter '1' as the integer, it returns 0 and 0.
I am a complete newbie to programming and Stack Overflow, so I'm not sure if I am doing this correctly, but I figured I would give it a shot.
This is the problem: Write a program that asks the user to enter 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.
And here is my solution thus far:
x = int(raw_input('Enter a positive integer: '))
root = 0
pwr = 0
while pwr < 6:
pwr += 1
while root**pwr < x:
root += 1
if root**pwr == x:
print "The root is " + str(root) + " and the power is " + str(pwr)
else:
print "No such pair of integers exists."
How can I fix my code so that it returns the correct integers? What am I doing wrong here? What logic am I missing?
One problem is that, while you do have conditions that end your loops, they will always go all the way up to the maximum allowed condition. You could solve that with break or, as shown, by using return in a function. Also, instead of using a counter, use the xrange() function (range() in Python 3).
>>> def p(num):
... for power in xrange(6):
... for root in xrange(num/2+1):
... if root**power==num:
... return root, power
...
>>> r, pwr = p(8)
>>> print 'The root is', r, 'and the power is', pwr
The root is 2 and the power is 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With