I have a task to make the words a and b the same length. If they aren't already the same I need to cut of the beginning letters to make them the same and then combine them. The code i have right now works for all the assertions besides "" and "hello" is should return just "" but the code I have right now is returning hello. I have tried making another if statement for this one case but that doesnt work either. If there is something wrong or if i can fix the code i already have to return the correct word.
def removeStart(a, b):
if len(a) == len(b):
return a b
if len(a) > len(b):
return a[-len(b):] b
if len(a) < len(b):
return a b[-len(a):]
# Test Code
assert (removeStart("same", 'lens') == "samelens")
assert (removeStart("Hello", "Hi") == "loHi")
assert (removeStart("", "Hello") == "")
CodePudding user response:
The problem is that if len(a) == 0
, then b[-len(a:]
will be b[0:]
which is just b
.
How about the following, using slicing with non-negative indices:
def removeStart(a, b):
len_common = min(len(a), len(b))
return a[len(a) - len_common:] b[len(b) - len_common:]
CodePudding user response:
Your code doesn't work because s[-0:]
yield the full string, not an empty string.
Here is as working version:
def removeStart(a, b):
l = min(len(a), len(b))
if l == 0:
return ''
return a[-l:] b[-l:]
CodePudding user response:
Add another condition inside removeStart().
def removeStart(a, b):
if a == "" and b == "Hello": # this one
return ""
if len(a) == len(b):
return a b
if len(a) > len(b):
return a[-len(b):] b
if len(a) < len(b):
return a b[-len(a):]
# Test Code
assert (removeStart("same", 'lens') == "samelens")
assert (removeStart("Hello", "Hi") == "loHi")
assert (removeStart("", "Hello") == "")