Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Dan Garrison
Dan Garrison
22,457 Points

Is there a better way to handle this challenge (Chance Scoring - OOP)?

I'm specifically looking at Challenge Task 2 of 2 in the chance scoring challenge on OOP. My code works and it passes the challenges, but I feel like it's more complicated then it should be.

My code is attached, but to explain it a bit. I basically created a variable that used the value of index 0 in the hand. I then initiated an empty list. I then compared every dice to the check value and if it matched then I added it to the list. I then checked if the length of the list equaled 5 and if it did then I returned 50 and if it did not then I returned 0.

Is there a better way to handle the challenge?

scoresheets.py
class YatzyScoresheet:
    def score_ones(self, hand):
        return sum(hand.ones)

    def _score_set(self, hand, set_size):
        scores = [0]
        for worth, count in hand._sets.items():
            if count == set_size:
                scores.append(worth*set_size)
        return max(scores)

    def score_one_pair(self, hand):
        return self._score_set(hand, 2)

    def score_chance(self, hand):
        return sum(hand)

    def score_yatzy(self, hand):
        check_value = hand[0]
        check_hand = []
        for die in hand:
            if die == check_value:
                check_hand.append(die)

        if len(check_hand) == 5:
            return 50
        else:
            return 0

2 Answers

Paul Jenkins
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Paul Jenkins
Python Web Development Techdegree Graduate 21,149 Points

Yes, it is. You can iterate through your hand using the hand._sets.items() then check if the count of each item in the hand is 5. If yes, return 50. Otherwise, after you've iterated through the hand and nothing = 5, you can return 0.

'''python def score_yatzy(self, hand): if hand[1:] == hand[:-1]: return 50 else: return 0 '''