Skip to content

Commit c03050d

Browse files
. F alternative way to inject rules into fizzbuzz, with default rules from DB or overriden in memory
Co-Authored-By: Joel Silberman <42779942+jcs-instructor@users.noreply.github.com> Co-Authored-By: 4dsherwood <4dsherwood@users.noreply.github.com>
1 parent 9edf31a commit c03050d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)