Oct-14-2017, 04:15 AM
Just started learning Python and was running through a decent tutorial from Google and there is a lab section where they give me a problem and I provide the solution. On one particular problem, my code works fine but looking at their solution code, it seems they used more code to get to the same result. So it got me curious, which of these solutions would be more desirable?
Normally, I would include the full runnable code, but in this instance, I am only interested in the best practice, just know it does yield the exact same result:
Mine:
I get that I may be splitting hairs here, but trying to ensure I start and continue using best practices from the get-go.
Thanks!
Normally, I would include the full runnable code, but in this instance, I am only interested in the best practice, just know it does yield the exact same result:
Mine:
# C. fix_start # Given a string s, return a string # where all occurences of its first char have # been changed to '*', except do not change # the first char itself. # e.g. 'babble' yields 'ba**le' # Assume that the string is length 1 or more. # Hint: s.replace(stra, strb) returns a version of string s # where all instances of stra have been replaced by strb. def fix_start(s): truncs=s[1:] return s[0]+truncs.replace(s[0],"*")This is theirs:
# B. both_ends # Given a string s, return a string made of the first 2 # and the last 2 chars of the original string, # so 'spring' yields 'spng'. However, if the string length # is less than 2, return instead the empty string. def both_ends(s): # +++your code here+++ # LAB(begin solution) if len(s) < 2: return '' first2 = s[0:2] last2 = s[-2:] return first2 + last2 # LAB(replace solution) # return # LAB(end solution)I like to be as efficient as possible and strive for the least amount of code to get the job done and I feel I did it where they didn't, though I suppose, without knowing the code itself, theirs is slightly more easier to understand what is being done (if, of course, the explanation of what the intent is wasn't right above it)
I get that I may be splitting hairs here, but trying to ensure I start and continue using best practices from the get-go.
Thanks!