how to solve this factorial - python

I've managed to get factors in a list but I can't finish because I'm doing something wrong in the end, the count variable is not updating with the products.
I want to solve it without using the factorial function.
Question:
Write a program which can compute the factorial of a given number.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
user = int(input("Input a number: "))
factors = []
while user > 0:
n = user * (user - 1)
if user == 1:
factors.append(1)
break
else:
factors.append(user)
user -= 1
count = 0 # this should be updating but it's not
for f in range(factors[0]): # I'm not sure if this is the correct range
counting = factors[f] * factors[f + 1] # I'm not sure about this either
count = count + counting
f = f + 1

Just change the last part of your program to:
result = 1
for f in factors:
result *= f
print result

Finding the factorial of a number is simple. I'm no python expert, and it could probably be written simpler but,
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
I think #erip may be right in the comment section.

num = int(input("Input a number: "))
factorial = 1
for i in range(2,num+1): # range isn't inclusive
factorial*=i

Related

WAP in python script to input a multidigit number and find each of the number's factorial

The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')

Collecting multiple unknown inputs

Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!
nums = []
for i in range(0, 4):
number = int(input('Enter number'))
nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)
This code continually asks the user to enter values until they enter a blank (just press enter without typing).
This is the code:
nums = []
# initialse
number = 0
# loop until there isn't an input
while number != "":
# ask for user input
number = input('Enter number:')
# validate the input isn't blank
# prevents errors
if number != "":
# make input integer and add it to list
nums.append(int(number))
avg = sum(nums) / len(nums)
print(max(nums), avg)
Alternatively, if you have the list of numbers:
def maxAndAvg(nums):
avg = sum(nums) / len(nums)
return max(nums), avg
One solution is to have the user specify how many numbers they want to take the average of. For instance:
nums = []
n = int(input('How many numbers: '))
for i in range(n):
number = int(input('Enter number: '))
nums.append(number)
avg = sum(nums) / n
print(max(nums), avg)
Alternatively, if you want a function that itself takes a variable number of arguments, you'll need to use the "*args" operator. For instance,
def my_average(*args):
return sum(args)/len(args)
An example usage:
print(my_average(1),my_average(1,2),my_average(1,2,3))
Result:
1.0 1.5 2.0
Ok, guys this is the correct code to figure this lab out. Did some data mining and some line manipulation to pass all ten tests:
nums = []
while not nums:
number = input()
nums = [int(x) for x in number.split() if x]
avg = int(sum(nums) / len(nums))
print(avg, max(nums))

Loop counter to get factorial

I have been given the following Pseudocode snippet
Function number_function()
Initialise variables factorial, number
Initialise Boolean valid to false
Loop while not valid
Display “Please enter a positive integer greater than 0”
Input number
If number contains numeric characters
Convert number to integer
If number is a positive integer
Set valid to true
End if
End if
End loop
Loop for counter from number to 1
Calculate factorial = factorial x count
If count is not 1
Print count and format with multiply
Else
Print count and format with equals
End if
End loop
Print factorial
End function
I have written this section myself however I am not sure what it means and how to do the loop for counter from number to 1 could anyone help please?
my code so far
def number_function():
factorial = 0
count = 1
number = 0
valid = False
while valid != True:
number = input("Please Enter a positive integer greater than 0 ")
if number.isnumeric():
number = int(number)
if number >= 0:
valid = True
You have to calculate the factorial and print each step of the calculs.
I understand it this way :
def number_function():
factorial = 0
count = 1
number = 0
valid = False
while valid != True:
number = input("Please Enter a positive integer greater than 0 ")
if number.isnumeric():
number = int(number)
if number >= 0:
valid = True
count = number
factorial = 1
while count >= 1:
factorial = factorial * count
if count != 1:
print (count, "*")
else:
print (count, "=")
count -= 1
print (factorial)
number_function()
Example output is:
Please Enter a positive integer greater than 0 3
3 *
2 *
1 =
6
you would want to do something like this:
you will not need a count variable, because your number will be your counter.
i added the print lines at strategic points, so you can follow, what the program does.
they are not neccessary and you can delete them afterwards.
while (number > 0): ## looping while number not reached 0
factorial = factorial * number
print (factorial)
number = number - 1 ## diminish counter variable
print (number)
print (factorial)
this will provide your loop. in its header it will test on the condition and then do your factorial equation, then diminish your number to be multiplied again, but smaller until it reaches zero.
i don't quite understand, what is meant by the rest, maybe my english skills fail me. ;)

Python Program to check if a number is armstrong or not is not working, what am I doing wrong?

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

New to coding python , need help on why my code isnt working?

def Factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
def Fibonacci(num):
i=0
present=1
previous=0
while i<=num:
nextterm=present+previous
present=previous
previous=nextterm
i=i+1
print("The fibonacci number for", i, 'is', nextterm)
def CallFibOrFac(x):
num = 10
if x == 'Fib':
Fibonacci(num)
if x == 'Fac':
print (Factorial(n))
x = input('enter fibonacci or factorial')
num = input('enter value for fibonacci')
Fibonacci(num)
n = input('enter value for factorial'
print(Factorial(n))
I defined all my functions and wrote an if statement, but when I enter Factorial, when it asks for x=input(‘enter fibonacci or factorial’), it gives me the input to ‘enter value for fibonacci’ when I need the n=input(‘enter value for factorial’) to display when I put in "factorial".
Although you have a function to choose whether to call Fib or Fact, you never call that deciding function. Instead, what I take to be your main program utterly ignores the user's first input and proceeds to call both functions.
Back up a few steps. Learn to recognize the user's input and call -- or do not call -- a single function.

Categories

Resources