Home > OS >  How to replace an integer in Python without using int()
How to replace an integer in Python without using int()

Time:11-13

I'm learning Python from Brian Heinold's A Practical Introduction to Python Programming where exercise 24 in chapter 6 reads 'In calculus, the derivative of x4 is 4x3. The derivative of x5 is 5x4. The derivative of x6 is 6x5. This pattern continues. Write a program that asks the user for input like x^3 or x^25 and prints the derivative. For example, if the user enters x^3, the program should print out 3x^2.' I figured it out. Easy. However the trick is that should be solved without using int() since it has not been mentioned in the book so far. Could you please tell me how to do that?

Here is my solution:

original = input("Enter an x with a power: ")
part1 = original[2:]
part2 = original[0]
part3 = original[1]
part4 = str(int(original[2:])-1)
derivative = part1   part2   part3   part4
print("The derivative is", derivative)

CodePudding user response:

Ok i'll explain what I meant in the comments. If these are strings, not numbers, what is the pattern? Replace the last digit with the digit just before it in the digit sequence, e.g. turn a final "5" into a "4". Unless it's a zero, in which case do that to the digit before and add a "9". Like this:

digits = "0123456789"
power = "25"     # from user input
last = power[-1]
if last != "0":
    # Subtract from the last digit, e.g. "2"   "4"
    newpower = power[:-1]   digits[digits.index(last)-1]
else:
    # Subtract one from the tens, e.g. 30 -> 29
    tens = power[-2]
    newpower = power[:-2]    digits[digits.index(tens)-1]   "9"

It won't work for numbers like 100, 200 etc., for that you'd need another level or you'd need to turn this into a tricky loop. Left as an exercise to the learner ;-)

CodePudding user response:

My The idea is to use the ASCII value of the digits from 0 to 9 start from 48 – 57.

original = input("Enter an x with a power: ")
part1 = original[2:]
part2 = original[0]
part3 = original[1]
c=0
part4 = original[2:]

for i in part4: 
 
    c = c * 10   (ord(i) - 48) 
part4 = str(c-1)



derivative = part1   part2   part3   part4
print(part4)
print("The derivative is", derivative)

output #

Enter an x with a power: x^25
The derivative is 25x^24
  • Related