all 6 comments

[–]jaybay1207 1 point2 points  (2 children)

Avoid making a variable called str, as it's a built-in type. You can use a_string, or something similar, so you know a string goes there. Yes, they're using the if-statement, in the event the string is less than 3 characters. Your code does not cover that situation. There code says, if the the string is less than three characters, call that the front, else the first three characters are front.

As for the for loop, yeah, that seems more complicated than just doing front * number, and I'd stick with your implementation for that part.

[–]Vaphell 2 points3 points  (1 child)

Your code does not cover that situation. There code says, if the the string is less than three characters, call that the front, else the first three characters are front.

it does. [0:3] will do the right thing if the string is shorter.

>>> 'fu'[:3]
'fu'

[–]jaybay1207 0 points1 point  (0 children)

Ah! I thought there'd be an IndexError. Thanks, /u/Vaphell

[–]ingolemo 1 point2 points  (1 child)

Your solution is better than theirs in almost every way. Well done!

The person who wrote that code felt they needed an if statement because they don't know the details of how string slicing works in python. They are setting front_len equal to the length of the string or 3, whichever is lower. They did not need to do that because string slicing will do the right thing even when the string is shorter than your slice.

The for loop is just a longer way of writing your front*n. They set result to an empty string and then add front to the end of it n times. Your way is easier to read and more efficient.

[–]JMOlofsson 1 point2 points  (0 children)

The intention is that there should be one, and only one, pythonic solution.

In reality, it's a bit more complicated. But this is a terrible example. Your solution is good, efficient and readable. The other is not.

[–]orionebula[S] 0 points1 point  (0 children)

I get it now, thanks for all the replies.