Created
August 4, 2018 15:15
-
-
Save kimfucious/562a360c69206f507229df8d2418e6e0 to your computer and use it in GitHub Desktop.
Calculate LCM from multiple numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I was helping my kid with his homework the other day. | |
# He's shown an interest in programming, so we wrote this together. | |
# Be sure to run this with python3, not python 2. | |
# 1. Get a list of numbers through user input, preventing non-integers and 0s as inputs | |
# 2. Create sets from each number factored out to the Nth, based on the largest number in the list | |
# 3. Get the intersection of the sets using and a little *args magic | |
# 4. Use min() on that intersection to determine the LCM. | |
def create_sets(nums): | |
sets = [] | |
for num in nums: | |
sets.append(set([num*i for i in range(1, max(nums)+1)])) | |
prt_lcm(sets) | |
def get_inputs(user_input, numbers): | |
import re | |
if user_input.lower() == "r": | |
create_sets(numbers) | |
elif user_input == "0": | |
print(colored("No zeros allowed.", color="yellow")) | |
prt_rsort_list(numbers) | |
user_input = input("Please enter a number greater than zero: ") | |
get_inputs(user_input, numbers) | |
else: | |
regex = re.compile(r"[^0-9]") | |
match = regex.search(user_input) | |
if match or user_input == "": | |
prt_rsort_list(numbers) | |
user_input = input( | |
"Oops! Please enter a number or 'R' to run the LCM calculation: ") | |
get_inputs(user_input, numbers) | |
else: | |
numbers.append(int(user_input)) | |
prt_rsort_list(numbers) | |
user_input = input( | |
"Enter another number, or 'R' to run the LCM calculation: ") | |
get_inputs(user_input, numbers) | |
def prt_lcm(sets): | |
lcm = min(set.intersection(*sets)) | |
if lcm: | |
print(colored(f"The LCM is {lcm}.", color="red")) | |
else: | |
print("Oops! This should never happen.") | |
def prt_rsort_list(lst): | |
lst.sort(reverse=True) | |
print(colored(f"The current list of numbers is: {lst}.", color="cyan")) | |
from termcolor import colored | |
get_inputs(input("Please enter a number: "), []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment