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

what is wrong with my code

str_ method

morse.py
class Letter:
    def __str__(self):
        dot=''
        dash=''
        for item in self.pattern:
            if(item=='.'):
                if(self.pattern.index(item)==-1):
                    dot+= 'dot'
                else:
                    dot+='dot-'
            elif(item=='_'):
                if(self.pattern.index(item)==-1):

                    dash+= 'dash'
                else:
                    dash+='dash'
        return dot+dash
    def __init__(self, pattern=None):
        self.pattern = pattern


class S(Letter):
    def __init__(self):
        pattern = ['.', '.', '.']
        super().__init__(pattern)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

There are two issues with the code. First, using index test is not sufficient to detect the last item in the pattern. A simpler solution would be to append with a hyphen in all cases, then return the pattern with the last hyphen removed.

The second issue is treating the dot strong and dash string separately then concatenating them. This will jumble the order of the pattern in the case of ['.', '_', '.']. Instead use a single string o append all the new bits.

Post back if you need more help. Good luck!!!