I am a python student that's new to python and I am required to write a program that calculates the factorial of an input number to find the possible ways to arrange letters in a Scrabble game with only the "while" loop construct.
For example: I request for an input number from a user through a line like this initially:
n = int(input("Enter an integer:"))
and afterwards i need to go about finding the entire factorial with a loop. How do I go about doing this? Below is my entire code and can someone tell me what's wrong with it? It just keeps printing a value of 20:
number_of_letters = int(input("Enter the numbers of letters you have in hand:"))
n = number_of_letters
def factorial(number_of_letters):
while number_of_letters > 1:
a = number_of_letters
n = n - 1
result = a * n
print('The number of combination for {}-letters words is {}'.format(number_of_letters, result)) # To display output
break
return result # Do not remove this line
I think the problem is that you are comparing number_of_letters > 1 while decreasing n and keeping number_of_letters without changes.
Also, i don't know what are you trying to archive with the break statement, and the return statement should be inside the function but outside the while
Related
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}')
I have some python code below to find the maximum and minimum values from a given input, but I'm not sure why I need to include number=int(input()) again within the while loop. If I remove this line of code in the while loop, the program enters an infinite loop and I'm not sure why.
number = int(input())
min_value = number
max_value = number
while (number>0):
if (number>max_value):
max_value = number
if (number<min_value):
min_value = number
number=int(input())
print(min_value, 'and', max_value)
Try this :
user_input = input("Enter the numbers separated by a space ").split()
int_list = list(map(int, user_input))
print ("Max number:",max(int_list), "\nMin number:",min(int_list))`
The code will ask for input multiple times as it does not make sense to find maximum and minimum if you have only one number. Also, it will help you to exit the while loop whenever a 0 is entered.
Hey so im pretty new to programming in general and I was having a crack at a question I found for the collatz function,
The code I wrote after some trial and error is as follows:
def collatz(number):
if number % 2 == 0:
number = number//2
print(number)
return number
elif number%2 != 0:
number = 3*number + 1
print(number)
return number
n = int(input("plz enter the number:"))
while n != 1:
n = collatz(n)
Output:
plz enter the number:3
10
5
16
8
4
2
1
This code works but im not sure how the variable values are being alloted, cuz after running this program I can see that in the shell "number = 3" but "n = 1", why is this the case? Shouldnt "number" also equal to 1? Because I am returning the value of number within the function?
Also just to clear my concepts, at the initial moment when I input n = 3, at that moment n = number = 3, then does this returned value of "number" automatically become the new value of n, when i call it in the while loop?
Just wanted to check cuz im a little weak when it comes to doing stuff that needs to pass parameters.
edit:
Why is this case diff then what was just answered?
def testfile(number):
number = number -1
print(number)
return number
n = int(input("enter:"))
while n != 2:
n = testfile(n)
Output:
enter:5
4
3
2
When the input is given as n = 5, then why does number = 3 instead of 5 as was just explained below?
Here's how your program works.
You ask for a number and store it in variable n.
You open a loop which continues until n is 1
Every time the loop repeats, you're calling your function and passing a COPY of n. If you add one to the copy inside the function, your original n will not change.
The COPY is called number. You perform your little tricks with number, output it to the screen, and here's the confusing part: you return a copy of number right back to your loop. And where does it go? It goes right back to n. This overwrites whatever was in n previously.
Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)
I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.
n = raw_input("Enter number")
a = 1
while a < n:
a = 1
print(a*a)
a += 1
if a > n:
break
When I run this code it infinitely prints "1" ... I'm guessing that the value of a does not increase by += so it's a=1 forever. How do I fix this?
There are some problems. First, your input (what raw_input() returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
Second, you are setting a = 1 each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line
a = 1
Finally, it's not necesary to check if a > n, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
There is a small error in your code:
while a < n:
a=1 # `a` is always 1 :)
print a*a
a += 1
if a > n:
break
You're setting the value of a back to 1 on every iteration of the loop, so every time it checks against n, the value is 2. Remove the a=1 line.
As others have noted, your specific problem is resetting a each time you loop. A much more Pythonic approach to this is the for loop:
for a in range(1, n):
print(a ** 2)
This means you don't have to manually increment a or decide when to break or otherwise exit a while loop, and is generally less prone to mistakes like resetting a.
Also, note that raw_input returns a string, you need to make it into an int:
n = int(raw_input("Enter number: "))
an even better idea is to make a simple function
def do_square(x):
return x*x
then just run a list comprehension on it
n = int(raw_input("Enter #:")) #this is your problem with the original code
#notice we made it into an integer
squares = [do_square(i) for i in range(1,n+1)]
this is a more pythonic way to do what you are trying to do
you really want to use functions to define functional blocks that are easy to digest and potentially can be reused
you can extend this concept and create a function to get input from the user and do some validation on it
def get_user_int():
#a function to make sure the user enters an integer > 0
while True:
try:
n = int(raw_input("Enter a number greater than zero:"))
except TypeError:
print "Error!! expecting a number!"
continue;
if n > 0:
return n
print "Error: Expecting a number greater than zero!"
and then you can build your input right into your list
squares = [do_square(i) for i in range(1,get_user_int()+1)]
and really do_square is such a simple function we could easily just do it in our loop
squares = [x*x for x in range(1,get_user_int())]
The first line in your loop sets's a to one on every iteration.
You assign a=1 inside the loop. That means it's overwriting the a+=1.
try this:
n = eval(raw_input("Enter number"))
a=1
while a < n:
print a*a
a += 1
The issue here is that the value of a gets overridden every time you enter in the loop
Problem is in the condition of the while loop, to print squares of numbers upto a limiting value, try this..
def powers(x):
n=1
while((n**2)<=x):
print(n**2, end =' ')
n +=1