I am writing a program that calculates the factorial of a number, I am able to display the correct answer, however along with the answer I need the actual calculation to display, I am having trouble with that. So for example, when the user enters 4, I need it to display as:
I have been trying to figure out the right code, but do not know what to do.
Here is the code I have so far
number = int(input("Enter a number to take the factorial of: "))
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print (factorial)
Right now, it displays the correct answer, however I need for it to include the equation as well as follows: 4! = 1 x 2 x 3 x 4 = 24
The simplest approach is to construct the string as you are iterating:
equation = str(number) + "! = "
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
equation += str(i) + "x"
equation = equation[:-1] + " = " + str(factorial)
print(equation)
Note that this method appends an unwanted 'x' after the last factor. This is removed by equation[:-1].
Alternatively, you could append this one-line solution to the end of your code. It uses the join method of the string class to concatenate an array of strings:
print(str(number) + "! = " + "x".join(str(n) for n in range(1, number + 1)) + " = " + str(factorial))
As you loop through the numbers to be multiplied, you can append each number's character to a string containing the equation, e.g ans, and print it at last. At the end of the code, I omitted the last letter because I didn't want an extra 'x' to be displayed.
def fact(number):
num_string=str(number)
factorial = 1
ans=num_string+"!="
for i in range(1, number + 1):
factorial = factorial * i
ans+=str(i)+"x"
ans=ans[:-1]
print(ans)
return factorial
fact(4)
You can append each value to the list and then print the equation using the f-string:
num = 5
l = []
f = 1
for i in range(1, num + 1):
f *= i
l.append(i)
print(f"{num}! = {' x '.join(map(str, l))} = {f}")
# 5! = 1 x 2 x 3 x 4 x 5 = 120
Related
If the user input of the following code is 5 for example. Then the output I get is 3+33+333+3333+33333+37035. How can I have my output be 3+33+333+3333+33333=37035.
I've tried sep, end, but can't seem to get it to print the + as a separator and the = at the end before the result (=370350).
n = int(input('Enter a positive integer: '))
sequence_number=3
sums = 0
for i in range(n):
print(sequence_number, end='+') with + between each
sums = sums+sequence_number # this will add the numbers
sequence_number = sequence_number * 10 + 3
print(sums)
If you have a better way to write this code im all ears!
You have two options:
Check if this is the last iteration, and use a space instead of + if it is:
for i in range(n):
if i == n-1: end_char = ' '
else: end_char = '+'
print(sequence_number, end=end_char)
...
Append all numbers to a list, and then join them with + outside the for loop:
lhs = []
for i in range(n):
lhs.append(sequence_number)
...
print("+".join(lhs), f"= {sums}")
It'd actually be easier to keep your sequence_number as a string for repetition:
limit = 5
digit = '3'
sequence = [digit * count for count in range(1, limit+1)]
# ['3', '33', '333', '3333', '33333']
total = sum(map(int, sequence))
# 37035
print(f'{"+".join(sequence)}={total}')
# 3+33+333+3333+33333=37035
Some print statements omitted for brevity.
Use list comprehension and string operations:
lst = [str(sequence_number)*(i+1) for i in range(n)]
>>> "=".join(["+".join(lst),str(sum(map(int,lst)))])
'3+33+333+3333+33333=37035'
Using join and f-strings to build the actual string you want to print is almost always a better option than messing around with the print parameters IMO; if nothing else, it makes it easier to reuse the string if you ever need to do something other than print it.
Some other answers have shown how to do this by building a list; I'll show a way to do it with inline generator expressions. Assigning the things you'll be using more than once (namely the stringified sequence_number and the range you need to iterate over) to short variable names makes it possible to express it very compactly:
n = range(1, int(input('Enter a positive integer: '))+1)
s = "3"
print(f"{'+'.join(s*i for i in n)}={sum(int(s*i) for i in n)}")
This is a possible solution:
n = int(input('Enter a positive integer: '))
sequence_number = 3
sums = sequence_number
print(sequence_number, end='')
for i in range(1, n):
print(f'+{sequence_number}', end='')
sums += sequence_number
sequence_number = sequence_number * 10 + 3
print(f'={sums}')
Another option:
n = int(input('Enter a positive integer: '))
sequence_number = 3
sums = 0
for i in range(n):
print(sequence_number, end=('+' if i != n-1 else '='))
sums += sequence_number
sequence_number = sequence_number * 10 + 3
print(sums)
I've been trying to code a system to solve one of those "Are you a bot" type of captchas in a game.
Pretty much what it does is gives you a mathematical question from 1-200 numbers (ex 19 + 163) and asks you to solve it at random times throughout the gameplay.
with Pyautogui I managed to find the numbers accordingly on the screen (scanning the region for the number 1-9, then adding it to the according variable (i made 5 variables from number1 to number5)
Using the example above (19 + 163) it would correspond with
19
number1 = 1, number2 = 9
163
number3 = 1, number4 = 6 and number5 = 3
and then i made a simple calculating system which is :
sum1 = ((number1 * 10) + number2)
sum2 = ((number3 * 100) + (number4 * 10) + number5)
sum = sum1 + sum2
print(sum)
But is there a way to make it so that the sum will display it in 3 seperate numbers instead of showing let's say (sum = 193) it would show (sum = 1, 9, 3) and then type it out in the answer area (I had an idea of using import keyboard for typing the answer out but i'm not sure if it works in this case)
or even better in this case if there is a way to take the sum and then make it type it out in the answer area by the code?
https://imgur.com/a/XYXrgeX (Picture of the Bot captcha)
Try this:
sum1 = ((number1 * 10) + number2)
sum2 = ((number3 * 100) + (number4 * 10) + number5)
sum_ = sum1 + sum2
lst = list(str(sum_))
sum_ = ""
for i in lst:
sum_ = sum_ + str(i) + ", "
print(sum_[:-2])
This basically turns the sum into a list of digits and then combines then all while adding commas in between.
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))
How can I do factorial based on the multiply function? Thats what I have and the problem I'm running into is it gives me 0 instead of 5 != 120.
EDIT NEWEEST: how can I fix the double factorial to give me the right number?
if I do 5, it should give me 5!!= 15 but it gives me 12 why is that?
SOURCE CODE
def multiply(num1,num2):
sum_of_multiplication= 0
for i in range(num2):
sum_of_multiplication = add(sum_of_multiplication,num1)
return sum_of_multiplication
def factorial(num1):
factorial_num = num1
for i in range(1,num1):
num1 = multiply(factorial_num,num1)
print(factorial_num)
print(str(num1) + "!= " + str(factorial_num))
def double_factorial(num1):
double_factorial_num = 2
for i in range(1,num1-2):
double_factorial_num = multiply(double_factorial_num, i)
print(double_factorial_num)
print(str(num1) + "!!= " + str(double_factorial_num))
double_factorial = double_factorial(int(input("please enter your intger:")))
It is because you are including 0 in your multiplication. In the range function (in the factorial function), put 1 as the first parameter to make it look like range(1,num1). This way the multiplication will start at 1, not 0.
Your factorial() is slightly off due to a range() issue, which is an easy mistake to make but you should be able to fix it quickly by reviewing the documentation for range(). However, your double_factorial() function has no hope of success as you fail to deal with a key issue up front, the parity (odd or even) of the number:
def add(a, b):
return a + b
def multiply(a, b):
my_sum = 0
for _ in range(b):
my_sum = add(my_sum, a)
return my_sum
def factorial(number):
product = 1
for multiplicand in range(2, number + 1):
product = multiply(product, multiplicand)
print(str(number) + "!", "=", product)
def double_factorial(number):
parity = number % 2 + 2 # start at 2 or 3
product = 1
for multiplicand in range(parity, number + 1, 2):
product = multiply(product, multiplicand)
print(str(number) + "!!", "=", product)
number = int(input("please enter your integer: "))
factorial(number)
double_factorial(number)
OUTPUT
> python3 test.py
please enter your integer: 5
5! = 120
5!! = 15
>
The pattern is given below. The number of rows is to be specified by the user. In this image it is 6. I know how to print the upper half but I am finding difficulty in the lower half. Please help.
I tried this code:
def asterisk_triangle(n):
x = 1
while (x <= n):
print("*" * x)
x = x + 1
return
If you have top half done, the bottom is similar, but reversed (rather than printing a number of stars equal to the row number, print a number of starts equal to the total number of rows minus the current row number). For example:
num = raw_input("Please enter number: ")
for i in range(num):
print "*" * i
then the opposite would be:
for j in range(num):
print "*" * (num-i)
def pattern(lines):
for i in range(0, lines / 2):
print "*" * i
for i in range(lines / 2, 0, -1):
print "*" * i