###################################################################### # Given a
ID: 3747807 • Letter: #
Question
######################################################################
# Given a sequence, S, an integer i < len(S) and a second integer j,
# return a (new) sequence consisting of S with the last i characters
# repeated exactly j times.
#
# Note: i > 0 should also be required, else -0 will repeat the whole
# sequence, not the 0th last element.
#
# >>> extendSequence([1, 2, 3], 2, 2)
# [1, 2, 3, 2, 3]
# >>> extendSequence((1, 3, 5, 6), 2, 3)
# (1, 3, 5, 6, 5, 6, 5, 6)
#
def extendSequence(S, i, j):
return(S[:-i] + j*S[-i:])
For the solution, i don't understand why there is a [:-i]
Can you please explain how they found this out
Explanation / Answer
S[:-i] lives out last i items from list S S[-i:] gives last i items from list S j * S[-i:] gives last i items from list S, repeated j times. S[:-i] + j*S[i:] -> gives a list of first len(S)-i elements concatenated with last i items repeated j times.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.