|
| 1 | +# The starting point for this code is from GPT4: https://chat.openai.com/share/df0f70f0-b2a0-44b7-8c48-e252ad95ca24 |
| 2 | +# At this point it has no tests, etc. |
| 3 | +from pymongo import MongoClient |
| 4 | + |
| 5 | +class Rule: |
| 6 | + def __init__(self, word, divisor): |
| 7 | + self.word = word |
| 8 | + self.divisor = divisor |
| 9 | + |
| 10 | +def get_rules_from_db(collection): |
| 11 | + # Fetches rules from MongoDB, sorted by the divisor in ascending order |
| 12 | + rules = [] |
| 13 | + try: |
| 14 | + rules_data = collection.find({}).sort("divisor", 1) # Sorting by 'divisor' in ascending order |
| 15 | + for rule in rules_data: |
| 16 | + rules.append(Rule(rule['word'], rule['divisor'])) |
| 17 | + except Exception as e: |
| 18 | + print(f"An error occurred while fetching rules from MongoDB: {e}") |
| 19 | + return rules |
| 20 | + |
| 21 | +def fizz_buzz(i, rules=None): |
| 22 | + # Uses default rules from MongoDB if no rules are specified |
| 23 | + if rules is None: |
| 24 | + rules = default_rules_from_db |
| 25 | + output = [] |
| 26 | + for rule in rules: |
| 27 | + if i % rule.divisor == 0 or str(rule.divisor) in str(i): |
| 28 | + output.append(rule.word) |
| 29 | + return ''.join(output) if output else str(i) |
| 30 | + |
| 31 | +# MongoDB connection setup |
| 32 | +client = MongoClient('mongodb://localhost:27017/') # Connect to your MongoDB server |
| 33 | +db = client['fizzbuzz_db'] # Specify the database |
| 34 | +collection = db['rules'] # Specify the collection |
| 35 | + |
| 36 | +# Fetch default rules from MongoDB |
| 37 | +default_rules_from_db = get_rules_from_db(collection) |
| 38 | + |
| 39 | +# Example usage of the fizz_buzz function with MongoDB |
| 40 | +print([fizz_buzz(i) for i in range(1, 16)]) # Uses default rules |
0 commit comments