calculator that prints step by step solution in python - python

my son is trying to make a calculator to help him with the many pages of homework that he gets. I know the simple solution would be to tell him about wolfram alpha, but I thought this could be a fun project. I need some help with how to iterate over the rest of the digits and print the solution in a step-by-step format. This is what he has so far:
# Variables
X = input("input the first number with space between digits: ")
Y = int(input("input the second number: "))
Xn = X.split(" ")
if int(Xn[0]) >= Y: # if Y fits in X the do a simple division and return the remainder
Xy1 = int(Xn[0])
fit0 = int(Xy1 / Y)
rem0 = Xy1 - fit0 * Y
print(" It fits " + str(fit0), "times ", " the remainder is: " + str(rem0))
else: # if Y does not fit in X the add the first two strings of X and convert them to integers then do a simple
# division and return the remainder
Xy0 = (int(Xn[0] + Xn[1]))
fit = int(Xy0 / Y)
rem = Xy0 - fit * Y
print(" It fits " + str(fit), "times ", " the remainder is: " + str(rem))

Here, I made an example that prints step by step the division.
I hardcoded the x (dividend with digits separated by spaces) and the divisor.
You can just change it to incorporate the inputs from the user
x = "1 4 8 7"
divisor = 5
# convert x to a list of integers
x = [int(i) for i in x.split(" ")]
dividend = x[0]
i = 0 # index of the current dividend digit
quotient = ""
while i < len(x)-1:
i += 1
quotient += str(dividend // divisor)
remainder = dividend % divisor
print(f"{dividend} / {divisor} -> {dividend // divisor} (remainder {remainder})")
dividend = remainder * 10 + x[i]
quotient += str(dividend // divisor)
remainder = dividend % divisor
print(f"{dividend} / {divisor} -> {dividend // divisor} (remainder {remainder})")
print(f"Result: {quotient} (remainder {remainder})")
This gives as result:
1 / 5 -> 0 (remainder 1)
14 / 5 -> 2 (remainder 4)
48 / 5 -> 9 (remainder 3)
37 / 5 -> 7 (remainder 2)
Result: 297 (remainder 2)

I think I misunderstood the question... why not use float?
x = float(input("input the first number: "))
y = float(input("input the second number: "))
print(f" It fits {x//y} times , the remainder is: {x/y-x//y}")

Related

Program that prompts the user to input 5 integers and outputs these integers in reverse order

I need help with this Python program.
With the input below:
Enter number: 1​
Enter number: 2​
Enter number: 3​
Enter number: 4​
Enter number: 5​
the program must output:
Output: 54321​
My code is:
n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
Its output is "12345" instead of "54321".
What should I change?
try this:
t = 1
rev = ""
while(t <= 5):
n = input("Enter a number:")
t+=1
rev = n + rev
print(rev)
Try:
x = [int(input("Enter a number")) for t in range(0,5)]
print(x[::-1])
There could be an easier way if you create a list and append all the values in it, then print it backwards like that:
my_list = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
my_list.append(n)
my_list.reverse()
for i in range(len(my_list)):
print(my_list[i])
You can try this:
n = 0
t = 1
rev = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
rev.append(n)
rev.reverse()
rev = ''.join(str(i) for i in rev)
print(rev)
Maintaining a numerical context: use "10 raised to t" (10^t)
This code is not very different from your solution because it continues to work on integer numbers and return rev as an integer:
t = 0
rev = 0
while (t < 5):
n = int(input("Enter a number:"))
# ** is the Python operator for 'mathematical raised to'
rev += n * (10 ** t)
t += 1
print(rev)
(10 ** t) is the Python form to do 10^t (10 raised to t); in this context it works as a positional shift to left.
Defect
With this program happens that: if you insert integer 0 as last value, this isn't present in the output.
Example: with input numeric 12340 the output is the number 4321.
How to solve the defect with zfill() method
If you want manage the result as a string and not as a integer we can add zeroes at the start of the string with the string method zfill().
In this context the zfill() method fills the string with zeros until it is 5 characters long.
The program with this modification is showed below:
NUM_OF_INTEGER = 5
t = 0
rev = 0
while (t < NUM_OF_INTEGER):
n = int(input("Enter a number: "))
rev += n * (10 ** t)
t += 1
# here I convert the number 'rev' to string and apply the method 'zfill'
print(str(rev).zfill(NUM_OF_INTEGER))
With previous code with input "12340" the output is the string "04321".
n = int(input("How many number do you want to get in order? "))
list1 = []
for i in range(n):
num = int(input("Enter the number: "))
thislist = [num]
list1.extend (thislist)
list1.sort()
print ("The ascending order of the entered numbers, is: " ,list1)
list1.sort (reverse = True)
print ("The descending order of the entered numbers, is: " ,list1)

How to compute a product of all digits of a negative integer number or zero?

I need compute a product of all digits of an integer number. The algorithm is quit simple. One can see the implementation of the Python.
print("input number:")
n = int(input())
mult = 1
while (n!=0):
mult = mult * (n % 10)
n = n // 10
print("product is", mult)
Question. How to compute a product of all digits of a negative integer number or zero?
My attemp is
print("input number:")
m = int(input())
n = abs(m)
mult = 1
while (n!=0):
mult = mult * (n % 10)
n = n // 10
if (m==0):
print("product is", 0)
elif (m>0):
print("product is", mult)
else:
print("product is", -mult)
I am looking for a solution without an additional variable.
You need to check if n is positive or negative. Based on that mult will be 1 or -1. The rest will be as normal.
print("input number:")
n = int(input())
mult = 1 if n==abs(n) else -1
n=abs(n)
while (n!=0):
mult = mult * (n % 10)
n = n // 10
print("product is", mult)
Alternate, you can use math.prod to calculate the product.
import math
print("input number:")
n = int(input())
mult = (1 if n==abs(n) else -1) * math.prod([int(i) for i in str(abs(n))])
print ('product is', mult)
This will give:
input number:
32
product is 6
input number:
-32
product is -6
If you want to use functools.reduce, then you can do.
from functools import reduce
print("input number:")
n = int(input())
mult = (1 if n==abs(n) else -1) * reduce(lambda x, y: x * y, [int(i) for i in str(abs(n))], 1)
print ('product is', mult)
Output will be:
input number:
32
product is 6
input number:
-32
product is -6
input number:
503
product is 0
It is simple:
Do it like this:
n = int(input("input number:"))
n1 = n
mult1 = 1
while n!=0:
if n1 == 0:
print("the product is",n)
else:
for i in str(n1):
i = int(i)
mult = i*mult1
mult1 = mult
print("product is:",mult)
n = 0
Output:
input number:123456
720
I couldn't do the code for negative numbers.

How do I print 2 variable alternatively n number of time

I got my homework problem. I need to input 2 variables and print them out alternatively n number of times without using if-else or loop statement.
a = input() #character
b = input() #character
n = input("n ")
I want to print out string of "ababa"
e.g.
a = "#"
b = "%"
n = 5
Expected output: #%#%#
or
n = 4
Expected output: #%#%
Since you have shown some effort in your comments I will give an answer. This uses the // integer division and % modulus operators. Note that I had to convert the value of n to an integer.
a = input("a? ") # character
b = input("b? ") # character
n = int(input("n? "))
print((a + b) * (n // 2) + a * (n % 2))

Calculating when the amount will be doubled using while loop

This is a simple exercise found in a book, which asks us to determine how long it takes for an amount to double at a given interest rate. My code is like this:
def main():
x = eval(raw_input("Initial Principal: "))
y = eval(raw_input("Interest rate: "))
count = 0
while x < 2*x:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
What it returns is:
Initial Principal: 1000
Interest rate: 0.5
inf
1734
What's wrong with my code?
Also I wonder if the above code would work if my amount and interest is small, e.g. amount = 1 and interest rate = 0.05, since there would include some floating point arithmetic I guess.
Thank you!
The culprit is the fact that you write:
while x < 2*x:
Since x > 0, that relation will always be False, you do not compare the new x with the old x, you compare the new x with twice the new x.
We can solve this effectively by using a variable x0 that store the initial amount:
def main():
x = x0 = eval(raw_input("Initial Principal: "))
y = eval(raw_input("Interest rate: "))
count = 0
while x < 2*x0:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
But there are still some problems with the code. For example you use eval. Do not use eval unless you absolutely have to: now a person can enter any type of Python code, also code that will break the system. Use float(..) instead to convert a string to an int:
def main():
x = x0 = float(raw_input("Initial Principal: "))
y = float(raw_input("Interest rate: "))
count = 0
while x < 2*x0:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
But now the code is still inefficient. There exists a fast way to calcuate the number of years using logarithms:
from math import log, ceil, pow
def main():
x = x0 = float(raw_input("Initial Principal: "))
y = float(raw_input("Interest rate: "))
count = ceil(log(2.0, y+1.0))
newx = x * pow(1.0+y, count)
print (newx)
print (count)
The problem is your while guard, which checks if the number is less than two times itself. To solve this, save the threshold you want to reach in a variable before the loop, and you have done:
threshold = 2 * x
count = 0
while x < threshold:
x = x * (1 + y)
count = count + 1

How to make loop repeat until the sum is a single digit?

Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.
This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement
n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
this is a sample output of the code
Input an integer: 98765678912398
8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88
8 + 8 = 16
1 + 6 = 7
This should work, no division involved.
n = int(input("Input an integer:"))
while n > 9:
n = sum(map(int, str(n)))
print(n)
It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.
You could utilize recursion.
Try this:
def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
you can try this solution,
if n=98 then your output will be 8
def repitative_sum(n):
j=2
while j!=1:
n=str(n)
j=len(n)
n=list(map(int,n))
n=sum(n)
print(n)
You don't need to convert your integer to a float here; just use the divmod() function in a loop:
def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:
n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
A simple, elegant solution.
I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.
n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number)
sum_int(n)
Again I am unsure about the recursion within a function in Python, but hey, it works :)
If you like recursion, and you must:
>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
def digit_sum(num):
if num < 10:
return num
last_digit = num % 10
num = num / 10
return digit_sum(last_digit + digit_sum(num))
input_num = int(input("Enter an integer: "))
print("result : ",digit_sum(input_num))
This may help you..!
Try with strings comprehension:
new = input("insert your number: ")
new = new.replace(" ","")
new =sum([int(i) for i in new])
if new not in range (10):
new = str(new)
new = sum ([int(i) for i in new])
print (new)
Note that the answers which convert int to str are relying on the python conversion logic to do internally the divmod calculations that we can do explicitly as follows, without introducing the non-numeric string type into an intrinsically numerical calculation:
def boilItDown(n):
while n >= 10:
t = 0
while n:
d, m = divmod(n, 10)
n, t = d, t + m
n = t
return n
n = 98765678912398
print(boilItDown(n))
Output:
7

Categories