Python Forum
John Guttag Python Book Finger Exercise 5 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: John Guttag Python Book Finger Exercise 5 (/thread-8714.html)



John Guttag Python Book Finger Exercise 5 - pritesh - Mar-04-2018

Hi,
Here's my way of taking a crack at the 5th Finger exercise in the John Guttag book - "Introduction to Computation and Programming Using Python with Application to Understanding Data"

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 exist, it should print a message to that effect.
Note:- I had to add the weird condition "x ** 1 !=x" because at the end the exercise states "If no such pair of integers exist, it should print a message to that effect." Which I think is the author's way of saying " If none of the root and pwr combinations equal to the number you input, print a message accordingly".
Well, any number, if raised to 1 will be equal to itself, so I put the else statement at the end.


#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 exist, it should print a message to that effect.


x = int(input("Enter an integer: "))
pwr = 1 
while pwr < 6 :
    if x < 0:
        root = x
    else:
        root = 0 
    while root ** pwr <= x:
        if root ** pwr == x:
            print(root, " ** ", pwr, "=", x)
        else:
            if x ** 1 != x:
                print(x, "No such integer pair exists.")
        root += 1
    pwr += 1
And here are some output examples:

C:\Users\prite>python rootpwr.py
Enter an integer: 64
64  **  1 = 64
8  **  2 = 64
4  **  3 = 64

C:\Users\prite>python rootpwr.py
Enter an integer: -729
-729  **  1 = -729
-9  **  3 = -729

C:\Users\prite>python rootpwr.py
Enter an integer: 729
729  **  1 = 729
27  **  2 = 729
9  **  3 = 729