Reputation:
I have to rearrange a five letter word. The code I have right now works in the sense that it rearranges the word but I need it to keep the first and last letters the same. I've tried adding different parts and splitting.
How should I change it to keep these parts the same?
def in_lat(word):
return word[::-1]
assert (in_lat("first") == "fsrit")
Upvotes: 1
Views: 115
Reputation: 20659
We can use tuple unpacking1 here. We just have separated the word as the first character, the middle part of the string and the last character. We can generalize this approach to work with arbitrary-length strings.
def func(wrd): # if we give "abcd" as `wrd`
if len(wrd) < 2:
return wrd
else:
# 'a' ['b', 'c'] 'd'
# ‖ ‖ ‖
first, *mid, last = wrd
return "".join([first, *mid[::-1], last])
# return first + "".join(mid[::-1]) + last
Sample outputs:
In [16]: func("a")
Out[16]: 'a'
In [17]: func("ab")
Out[17]: 'ab'
In [18]: func("abc")
Out[18]: 'abc'
In [19]: func("abcd")
Out[19]: 'acbd'
In [20]: func("")
Out[20]: ''
1. PEP 3132 -- Extended Iterable Unpacking
Upvotes: 2
Reputation: 177991
Keep the first and last, but only reverse the middle section. Recall that a slice is a half-open interval, so start from -2 (2nd to last letter) down to but not including 0 (first letter), counting backwards with -1:
def in_lat(word):
return word[0] + word[-2:0:-1] + word[-1]
assert in_lat("first") == "fsrit"
You should add a check that the word is at least 4 letters long...
Upvotes: 2