I am working to recreate a dice game known as Knucklebones in Python as a fun personal project.
For the game logic, I need to multiply all matching values in a list and then add the remaining values.
Example 1:
numbers = [3, 3, 2]
This list should multiply both 3 and 3 together then add 2 for a total of 11.
Example 2:
numbers2 = [4, 4, 4]
This list should multiply 4 by 4 by 4 for a total of 64
Example 3:
numbers3 = [2, 4, 6]
Nothing should be multiplied in this list. All numbers should be added for a total of 12.
Can someone please help me with the logic surrounding this?
CodePudding user response:
I think this should work
I will advise to use a modified Counter from the built in module collections.
The counter by default will count just the entries of all the list them as it works similar to a dictionary is fairly simple to multiply all entries and sum them up
here you have more info:
https://docs.python.org/3/library/collections.html
https://realpython.com/python-counter/
from collections import Counter
class MyCounter(Counter):
def __ini__(*arg, **kwargs):
super().__init__(*arg, **kwargs)
def sum_entries(self):
total = 0
for key, val in self.items():
total = key**val
return total
out = MyCounter([3, 3, 2])
output = out.sum_entries()
output
out = MyCounter([3, 3, 2])
output = out.sum_entries()
print(output)
11
out = MyCounter([4, 4, 4])
output = out.sum_entries()
print(output)
64
out = MyCounter([2, 4, 6])
output = out.sum_entries()
print(output)
12
EDIT
As suggested in the comments To avoid having a class if it seems to complicated
from collections import Counter
out = Counter([3, 3, 2])
total = 0
for key, val in out.items():
total = key**val
CodePudding user response:
Built-in approach. Used dict.fromkeys
to initialize to zero the counter (and remove duplicates). Then fix the frequency of the outcomes with the loop and apply the "Knucklebones" rule.
numbers = [3, 3, 2]
d = dict.fromkeys(numbers, 0)
for n in numbers:
d[n] = 1
res = sum(k**frequency for k, frequency in d.items())
print(res)