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 Object-Oriented Python (retired) Inheritance Instance Methods

fahad lashari
fahad lashari
7,693 Points

Need help please

I wanted to change the battlecry() function slightly and add my own tiny upgrades.

My aim was to input something like: 'i can do this' and upon calling the battlecry() function, receiving something like this: 'I CAN DO THIIISSSS!!!!'

I managed to achieve this using two different solutions.

Solution 1:

 def battlecry(self):
     sound = list(self.sound)
     del sound[-2:]
     return ''.join(sound).upper() + (self.sound[-2] + self.sound[-2] + self.sound[-1] + self.sound[-1] + self.sound[-1] + self.sound[-1]).upper() + "!!!!"

Solution 2:

def battlecry(self):
    sound = list(self.sound)
    sound[-2:] = sound[-2] + (sound[-2] + sound[-2] + sound[-1] + sound[-1] + sound[-1] + sound[-1]) + "!!!!"
    return ''.join(sound).upper()

My questions is; Which one of these solutions is more efficient and to broadly put it, 'better'? can you think of any other way to achieve this?

And also I am constantly repeating some of the code such as the sound[-2] and sound[-1] indexes. Is there anyway to shorten this?

I would appreciate any help.

kind regards,

Fahad

1 Answer

Steven Parker
Steven Parker
229,732 Points

:point_right: Your approaches are very similar in efficiency.

I'm not sure either is clearly "better" than the other.

But regarding the repeated elements, remember in Python you can replicate a string a number of times using the multiply (*) operator.

fahad lashari
fahad lashari
7,693 Points

Hi Steven. Can you please explain a bit more? If I do something like:

sound[-2] * 2

Would this return the index twice or simply multiply the value at that index by 2?

How should I implement the multiply operator correctly in this situation.

Kind regards

EDIT sorry that was a stupid question lol. I got the answer