I am doing the Python Koans to practise Python a bit more and I got to the greed dice project. It is a very simple dice game that scores a set of up to five rolls.
These are the rules:
# A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. #
Calls are made like this:
score([5])
score([1, 5, 5, 1])
score([3, 3, 3])
This is my implementation:
def score(dice):
result = 0
if len(dice) <= 5:
dice_copy = sorted(dice)
dice_dict = dict((i, dice_copy.count(i)) for i in dice_copy)
if dice_dict.get(1) >= 3:
result += 1000
dice_dict[1] -= 3
for number in dice_dict:
if dice_dict.get(number) >= 3:
result += number * 100
dice_dict[number] -= 3
if 1 in dice_dict:
result += dice_dict[1] * 100
if 5 in dice_dict:
result += dice_dict[5] * 50
return result
I am looking for:
- comments and tips on my code
- suggestions of Python-style ways of doing this
- improvement and optimizations of my code
- ideas of how to implement this in more interesting, original or interesting ways
I sorted the list before creating the dictionary because I think that would make the dictionary creation faster, but I ran some tests and found out that sorting the list actually makes the program slightly slower. I suppose my intention would only be effective in larger lists. Is my guess right?