Python Forum
John Guttag Python Book Finger Exercise 5
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
John Guttag Python Book Finger Exercise 5
#1
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  John Guttag Book Finger Exercise 2. pritesh 6 10,820 Feb-09-2020, 08:08 PM
Last Post: Larz60+
  John Guttag Book - Finger Exercise 3 pritesh 3 7,964 Aug-15-2018, 03:40 AM
Last Post: collectorKim

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020