My 'lowest common multiple' program hangs, and doesn't output an answer - python

I have been trying to get more into programming, so I've been trying to make a simple program that takes two numbers as input, and computes the lowest common multiple. I did this in Python because I don't know how to take input in Java. What happens now is the program just hangs after I input my numbers, and nothing happens. Any pointers here would be greatly appreciated. Thank you.
#LCM Calculator
#Author: Ethan Houston
#Language: Python
#Date: 2013-12-27
#Function: Program takes 2 numbers as input, and finds the lowest number
# that goes into each of them
def lcmCalculator(one, two):
""" takes two numbers as input, computes a number that evenly
divides both numbers """
counter = 2 #this is the number that the program tried to divide each number by.
#it increases by 1 if it doesn't divide evenly with both numbers.
while True:
if one % counter == 0 and two % counter == 0:
print counter
break
else:
counter += 1
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")
print lcmCalculator(first_number, second_number)

Your logic is a bit off. This line:
if one % counter == 0 and two % counter == 0:
needs to be rewritten like this:
if counter % one == 0 and counter % two == 0:
Also, your function should return counter instead of print it. This has two advantages:
It will keep the script from printing None at the end (the function's default return value).
It allows you to condense these two lines:
print counter
break
into just one:
return counter
Finally, as #FMc noted in a comment, you can improve the efficiency of the function by doing two things:
Starting counter at the smaller of the function's two arguments.
Incrementing counter by this value.
Below is a version of your script that addresses all this:
#LCM Calculator
#Author: Ethan Houston
#Language: Python
#Date: 2013-12-27
#Function: Program takes 2 numbers as input, and finds the lowest number
# that goes into each of them
def lcmCalculator(one, two):
""" takes two numbers as input, computes a number that evenly
divides both numbers """
counter = min_inp = min(one, two)
while True:
if counter % one == 0 and counter % two == 0:
return counter
else:
counter += min_inp
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")
print lcmCalculator(first_number, second_number)
Oh, and one more thing. input in Python 2.x evaluates its input as real Python code. Meaning, it is dangerous to use with uncontrolled input.
A better approach is to use raw_input and then explicitly convert the input into integers with int:
first_number = int(raw_input("Enter your first number: "))
second_number = int(raw_input("Enter your second number: "))

Try this:
#!/usr/local/cpython-2.7/bin/python
def lcmCalculator(one, two):
""" takes two numbers as input, computes a number that evenly
divides both numbers """
counter = 2 #this is the number that the program tried to divide each number by.
#it increases by 1 if it doesn't divide evenly with both numbers.
while True:
if counter % one == 0 and counter % two == 0:
break
else:
counter += 1
return counter
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = int(input("Enter your first number: "))
second_number = int(input("Enter your second number: "))
print lcmCalculator(first_number, second_number)

You need to let the loop end if it finds no factor, instead of while True:
def lcmCalculator(one, two):
counter = 2
while counter <= min(one, two):
if one % counter == 0 and two % counter == 0:
return counter
else:
counter += 1
return "No common factor found"
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")
print lcmCalculator(first_number, second_number)

Related

How to remember previous numbers inputted in loop?

What I want to do, is to write a program that given a sequence of real numbers entered by the user, calculates the mean. Entering the sequence should be finished by inputting ’end’. To input more than 1 number I try:
num=input("Enter the number: ")
while num!="end":
num = input("Enter the number: ")
But I don't want the program to "forget" the first 'num', because I'll need to use it later to calculate the mean. What should I write to input and then use more than one value, but not a specific number of values? User should can enter the values until they enter 'end'. All of values need to be use later to calculate the mean. Any tip for me?
First, define an empty list.
numbers = []
Then, ask for your input in an infinite loop. If the input is "end", break out of the loop. If not, append the result of that input() to numbers. Remember to convert it to a float first!
while True:
num = input("Enter a number: ")
if num == "end":
break
numbers.append(float(num))
Finally, calculate the mean:
mean = sum(numbers) / len(numbers)
print("Mean: ", mean)
However, note that calculating the mean only requires that you know the sum of the numbers and the count. If you don't care about remembering all the numbers, you can just keep track of the sum.
total = 0
count = 0
while True:
num = input("Enter a number: ")
if num == "end":
break
total += float(num)
count += 1
print("Mean: ", total / count)
Mean is sum of all nos/total nos. Let's take input from user and add it to list, because we can easily use sum() function to find sum and len() function to find total nos. Your code:
obs=[]
while True:
num=input("Enter number: ")
if num=="end":
break
else:
obs.append(int(num))
print("Mean: ",(sum(obs)/len(obs)))

How to loop a function def in python until I write the number 0

I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()

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. ;)

Continually prompting user for input in Python

Objective: * Write a python program that repeatedly prompts for input of a positive number until the sum of the numbers is greater than 179. Use at least three modules/functions in your solution.
* The largest number entered cannot exceed 42.
* When the sum of the numbers exceeds 179, print the sum of the numbers, the largest number entered and smallest number entered.
I just need some guidance, specifically for the "input_numbers" module. There must be an easier way to do this than to make a variable for each number. The code is not complete. I haven't even started on the two other modules yet. Thanks in advance.
def input_numbers():
while True:
num1 = raw_input("Enter a positive integer no greater than 42 ")
if num1 <= 0:
print "That is not a positive integer. Try again "
elif num1 > 42:
print "The number cannot exceed 42. Try again "
num2 = raw_input("Enter another positive integer ")
if num2 <= 0:
print "That is not a positive integer. Try again "
elif num2 > 42:
print "The number cannot exceed 42. Try again "
num3 = raw_input("Enter another positive integer ")
if num3 <= 0:
print "That is not a positive integer. Try again "
elif num3 > 42:
print "The number cannot exceed 42. Try again "
num4 = raw_input("Enter another positive integer ")
if num4 <= 0:
print "That is not a positive integer. Try again "
elif num4 > 42:
print "The number cannot exceed 42. Try again "
num5 = raw_input("Enter another positive integer ")
if num5 <= 0:
print "That is not a positive integer. Try again "
elif num5 > 42:
print "The number cannot exceed 42. Try again "
elif sum(num1, num2, num3, num4, num5) > 179:
print_numbers()
add_numbers()
def add_numbers():
print_numbers()
def print_numbers():
input_numbers()
You can knock out all three function requirements by encapsulating each step of your program. Rather than having your loop inside of a function, we'll let main control the loop, and we'll control the flow by passing data into and out of function calls.
Let's rework your input_numbers() function a bit.
def get_input_number():
num = int(raw_input("Enter a positive integer no greater than 42 "))
if num <= 0 or num > 42:
print "Invalid input. Try again "
get_input_number()
else:
return num
So, instead of having input_numbers control the loop as well as the input handling and validation, we have it do just what its name implies: It asks for input, validates it, and then, if it's good, it returns the value to the caller, but if it's bad, it writes a message, and calls itself again to the user can enter good input.
The next function we'll set up is straight from your list of requirements. From all of the numbers that the user enters, we need to find the biggest one. From the language alone, we can determine that we're looking through a set of numbers, and thus, this is a good place to break out a list. Assuming we store all of the users input in a list, we can then pass that list to a function and perform operations on it, like so.
def get_greatest_number(input_list):
highest = input_list[0]
for i in input_list:
if i > highest:
highest = i
return highest
We set the first element of the list to a variable highest and then check all other elements in the list against that initial value. If we find one that's bigger, we then reassign the highest variable to the element that was bigger. Once we do this for each element in the list, the number inside of highest will now be, just that, the highest number, and so, we'll return it to the main program.
Similarly, we can do the same for finding the smallest.
def get_smallest_number(input_list):
smallest = input_list[0]
for i in input_list:
if i < smallest:
smallest = i
return smallest
Finally, we get to our main loop. Here we declare an empty list, number_list to store all the numbers in. And we use the sum of that as our loop condition.
if __name__ == '__main__':
number_list = []
while sum(number_list) < 179:
number_list.append(get_input_number())
In the body of the loop, we call our get_input_number() and append its result to the list we made. Once the sum of the numbers in the list exceed 179, the while loop will exit and we can finally show the user the results.
print
print '-------------------------'
print 'total of numbers entered: %d' % sum(number_list)
print 'greatest number entered: %d' % get_greatest_number(number_list)
print 'smallest number entered: %d' % get_smallest_number(number_list)
Here we can the get_greatest_number and get_smallest_number we made, and we give them the list of numbers as an argument. They'll loop though the lists, and then return the appropriate values to the print statements.
Yes, of course there's a better way than making a variable for each number. Store them in a list. Storing them in a list also makes finding their sum and the highest and lowest value easy (there are built-in functions for this).
As a further hint, you'll want to use two loops, one inside the other. The outer loop keeps the user entering numbers until their sum exceeds 179. The inner loop keeps the user entering a single number until it's between 1 and 42 inclusive.
def get_int(prompt=''):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def get_values():
values = []
total = 0
while total <= 179:
val = get_int('Enter a positive integer <= 42: ')
if 0 <= val <= 42:
values.append(val)
total += val
return values
def print_info(values):
print 'Sum is {}'.format(sum(values))
print 'Largest value is {}'.format(max(values))
print 'Smallest value is {}'.format(min(values))
def main():
values = get_values()
print_info(values)
if __name__=="__main__":
main()
You can repeatedly poll the number in a loop, and add the inputs into a list, e.g.
def input_numbers():
user_inputs = [] # a list of all user's inputs
while True:
num = raw_input("Enter a positive integer no greater than 42 ")
try:
num = int(num) # convert input string to integer
if num <= 0:
print "That is not a positive integer. Try again "
elif num > 42:
print "The number cannot exceed 42. Try again "
user_inputs.append(num)
except ValueError: # conversion to integer may fail (e.g. int('string') ?)
print 'Not a Number:', num
if some_condition_regarding(user_inputs):
break # eventually break out of infinite while loop
here some well-known tricks:
def min_and_max(your_num_list)
min=your_num_list[0]
max=your_num_list[0]
for num in your_num_list:
if num < min:
min=num
if max > num
max=num
return min,max
When you're writing a standalone Python program, it’s a good practice to use a main function. it allows you to easily add some unit tests, use your functions or classes from other modules (if you import them), etc.
And as others already said, it is a good idea to create a list and append a new element to it each time the user enters a valid number (until the sum of the numbers axceeds 179). If user entered an incorrect value, then just don’t append anything to the list and skip to the next iteration (so the user will be asked to enter a number again).
So basically it could look like this:
def validate_entered_number(num):
"""
Checks if the number is positive and is less or equal to 42.
Returns True if the number matches these conditions,
otherwise it returns False.
"""
if num < 0:
print "That is not a positive integer."
return False
if num > 42:
print "The number cannot exceed 42."
return False
return True
def main():
entered_numbers = []
while True:
try:
num = int(raw_input("Enter a positive integer less or equal to 42: "))
except ValueError:
print "You should enter a number"
continue
if validate_entered_number(num):
entered_numbers.append(num)
if sum(entered_numbers) > 179:
print "The sum of the numbers is %s" % sum(entered_numbers)
print "The smallest number entered is %s" % min(entered_numbers)
print "The largest number entered is %s" % max(entered_numbers)
return
if __name__ == "__main__":
main()
In fact, I can imagine a situation where you would want to just store the sum of the numbers, the smallest number and the largest number in three variables and update these variables in each iteration (add current number to the sum and compare it to the currently known smallest and larger numbers and update the corresponding variables when necessary), but in this case the longest list you can possibly have is only 180 elements (if all numbers are 1 and the user doesn’t enter 0 or you have modified the program to deny entering 0), which is very small amount of elements for a list in Python. But if you had to deal with really big amounts of numbers, I’d recommend to switch to a solution like this.
Thanks to everyone who answered. I've written the following code and it works nearly perfectly except the last module. If you exit the program after the first run (by pressing 0) it will exit, but if you run it a second time pressing 0 won't make it exit. It'll just go back to the beginning of the program. I don't know why.
Note: The assignment has various requirements that I had to incorporate in my code. Hence the unnecessary modules, global variables, and comments.
maxNum = 42 # declares global variable maxNum
target = 179 # declares global variable target
def user_input(): # prompts user to input a number 42 or less until all add up to 179
x = 0
nums = []
while sum(nums) <= target:
nums.append(int(raw_input("Enter a number: ")))
if int(nums[x]) > int(maxNum):
print "Number cannot exceed 42."
user_input()
else:
x += 1
print_nums(nums,x)
def print_nums(nums,x): # prints the sum of the numbers, the smallest, and the largest
print "Sum of all numbers is", sum(nums)
nums.sort()
x -= 1
print "Largest number entered is", nums[x]
print "Smallest number entered is", nums[0]
decide()
def decide(): # allows user to continue the program or exit
exit = raw_input("<9 to enter a new set of number. 0 to exit.> ")
while True:
if int(exit) == 0:
return
elif int(exit) == 9:
user_input()
user_input()

Using random.randint help in python

The following code is my attempt at simulating a lottery.
import random
def lottery(numbers):
lottoNumbers = [randint('0,100') for count in range(3)]
if numbers == lottoNumbers:
print('YOU WIN $10,000')
else:
print('YOU LOSE,DUN DUN DUNNN!')
return numbers
def main():
numbers = int(input('Enter a number: '))
if numbers == lottoNumbers:
numbers = lottery(numbers)
else:
numbers = lottery(numbers)
main()
Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys?
Thanks for your help everyone.
You seem a bit confused about what the role of the arguments in a function are. You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.
Also, the function is trying to return x, when x hasn't been assigned within the function. Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x.
Here's a quick example I've done where you pass their three numbers as a list as an argument to the function.
import random
theirNumbers=[5,24,67]
def checkNumbers(theirNumbers):
lottoNumbers = []
for count in range(3)
lottoNumbers.append(random.randint(0,100))
winning = True
for number in theirNumbers:
if not each in lottoNumbers: winning=False
if winning == True: print("Winner!")
There are a few things wrong with your implementation, to name a few:
if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so:
def randm():
return return_value
You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so:
list_name = [randint(0,100) for x in range(x)]
This will generate randint(0,100) x times in a list, which will allow you to access all the values later.
To fix up your code as close to what you were attempting as possible I would do:
import random
def randm(user_numbers):
number = []
for count in range(3):
number.append(random.randint(0, 100))
print(number)
return user_numbers == number
if randm(x):
print('WINNER')
If you are looking for a very pythonic way of doing this task,
you might want to try something like this:
from random import randint
def doLotto(numbers):
# make the lotto number list
lottoNumbers = [randint(0,100) for x in range(len(numbers))]
# check to see if the numbers were equal to the lotto numbers
if numbers == lottoNumbers:
print("You are WinRar!")
else:
print("You Lose!")
I'm assuming from your code (the print() specifically) that you are using python 3.x+
Try to post your whole code. Also mind the indentation when posting, there it looks like the definition of your function would be empty.
I'd do it like this:
import random
def lottery():
win = True
for i in range(3):
guess = random.randint(1,100)
if int(raw_input("Please enter a number...")) != guess:
win = False
break
return win
Let so do this in few steps.
First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs.
First lets create function to make lottery:
def makeLottery(slotCount, maxNumber):
return tuple(random.randint(1,maxNumber) for slot in range(slotCount))
Next lets create function to ask user's guess:
def askGuess(slotCount, maxNumber):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = parseGuess(userInput,slotCount,maxNumber)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))
return numbers
here we are using another function and custom exception class, lets create them:
def parseGuess(userInput, slotCount,maxNumber):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
return numbers
class GuessError(Exception):
def __init__(self,wrongCount = False, notInRange = False):
super(GuessError,self).__init__()
self.wrongCount = wrongCount
self.notInRange = notInRange
and finally function to check solution and conratulate user if he will win:
def checkGuess(lottery,userGuess):
if lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
As you can see many functions here uses common data to work. So it should suggest you to collect whole code in single class, let's do it:
class Lottery(object):
def __init__(self, slotCount, maxNumber):
self.slotCount = slotCount
self.maxNumber = maxNumber
self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))
def askGuess(self):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = self.parseGuess(userInput)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
continue
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
continue
return numbers
def parseGuess(self,userInput):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
return numbers
def askAndCheck(self):
userGuess = self.askGuess()
if self.lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
finally lets check how it works:
>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123 asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!

Categories

Resources