I am stuck on applying rules in a class like forcing some values to change if some rule is present and so on. However I am unable to pass rules to the class. Here is my code, and what i require:
class Item:
valid_item_dict = {"a":20, "b":30, "c":40, "d":50}
def __init__(self, item_id):
self.item_id = item_id
self.item_cost = Item.valid_item_dict.get(self.item_id)
class checks:
def __init__(self):
self.content = list()
def cheque(self, item):
self.content.append(item)
def totals(self):
self.total = sum([self.item_counter().get(itm)*Item.valid_item_dict.get(itm) for\
itm in list(self.item_counter().keys())])
return self.total
def item_counter(self):
self.item_count_list = [itms.item_id for itms in self.content]
self.item_count_dict = dict((item, self.item_count_list.count(item)) for item in
self.item_count_list)
return self.item_count_dict
# Adding items to the list
item1 = Item("a")
item2 = Item("a")
item3 = Item("a")
item4 = Item("b")
# instatiance of class
cx = checks()
cx.cheque(item1)
cx.cheque(item2)
cx.cheque(item3)
cx.cheque(item4)
cx.totals()
>>> 90 (20*3 (from a) + 1*30 (from b))
In normal cases this works fine but I have a ton of rules which I need to add and I was earlier thinking of adding if-else rules in totals method of "checks" class. But is their a more generalized way to add these rules. Rule is something like if we have 3 types of product a, then the value of 'a' reduces from 20 to 10. I did go over this question and am trying to use this, but any help would be wonderful. (Python how to to make set of rules for each class in a game)
You may want to use a more direct loop to implement these rules and make your code clearer. I find it easier to maintain complex logic than trying to code golf a 1-line result:
from collections import Counter, namedtuple
Rule = namedtuple("Rule", ["threshold", "newvalue"])
"""rule: if count is greater than or equal to threshold, replace with newvalue"""
class Item:
rules = {'a': Rule(3, 10)}
...
class checks:
...
def totals(self):
counts = Counter(self.content)
self.total = 0
for count in counts:
value = Item.valid_item_dict[count]
rule = Item.rules.get(count, Rule(0, value))
if counts[count] >= rule.threshold:
value = rule.newvalue
self.total += value*counts[count]
return self.total
I'm assuming you want the result of your sample to be 60 and not 90.