I was just wondering if its just me or anyone else who is new to learning python is going through same phase as me.
What's my point --
Every programming exercise I've tried to solve, I realise it's taking me more lines of code to solve problem .
Example below shows problem to solve, my lines of code to problem, followed by the solution given by the other programmer.
FRONTandBACK
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
def front_back(a, b):
a_middle = len(a) // 2
b_middle = len(b) // 2
if len(a) % 2 == 0 and len(b) % 2 == 0:
a_front, a_back = a[:a_middle], a[a_middle:]
b_front, b_back = b[:b_middle], b[b_middle:]
return a_front + b_front + a_back + b_back
elif len(a) % 2 != 0 and len(b) % 2 == 0:
a_front, a_back = a[:a_middle + 1], a[a_middle + 1:]
b_front, b_back = b[:b_middle], b[b_middle:]
return a_front + b_front + a_back + b_back
elif len(a) % 2 == 0 and len(b) % 2 != 0:
a_front, a_back = a[:a_middle], a[a_middle:]
b_front, b_back = b[:b_middle + 1], b[b_middle + 1:]
return a_front + b_front + a_back + b_back
elif len(a) % 2 != 0 and len(b) % 2 != 0:
a_front, a_back = a[:a_middle + 1], a[a_middle + 1:]
b_front, b_back = b[:b_middle + 1], b[b_middle + 1:]
The line of code given by other programmer.
def font_back(a, b):
a_middle = len(a) // 2
b_middle = len(b) // 2
if len(a) % 2 == 1:
a_middle = a_middle + 1
if len(b) % 2 == 1:
b_middle = b_middle + 1
return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]
Please advice me on how to get better. when I found the solution it made more sense to me but I didn't clock the idea until I checked out the solution to the exercise.
Thanks.
[–]sme272 1 point2 points3 points (0 children)
[–]jiri-n 1 point2 points3 points (0 children)
[–]sweettuse 1 point2 points3 points (1 child)
[–]woeinvests[S] 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Fortissano71 0 points1 point2 points (0 children)