Reputation: 27
I'm studying python and there's a lab I can't seem to crack. We have a line e.g. shacnidw
, that has to be transformed to sandwich
. I somehow need to iterate with a for
loop and pick the letters with odd indexes first, followed by backward even indexes. Like pick a letter with index 1,3,5,7,8,6,4,2.
It looks pretty obvious to use a list or slices, but we aren't allowed to use these functions yet. I guess the question is just how do I do it?
Upvotes: 2
Views: 1276
Reputation: 2210
Your text looks to be in a specific pattern that can be achieved using the following syntax.
1, 3, 5, 7 : for n in range(1, size, 2) : steps of 2 in forward direction
8, 6, 4, 2 : for m in range(size, 0, -2) : steps of 2 in reverse direction
By building the string with the above indices we can easily arrive at the intended result.
string = 'shacnidw'
result = ''
size = len(string) - 1
for n in range(0, size, 2):
result += string[n]
for m in range(size, 0, -2):
result += string[m]
print(result)
Result
sandwich
Upvotes: 2
Reputation: 430
I hope I am understanding your question right. Check the below code.
s = 'shacnidw'
s_odd = ""
s_even = ""
for i in range(len(s)):
if i%2 == 0:
s_even += s[i]
for i in range(len(s), 0, -1):
if i%2 == 1:
s_odd += s[i]
print(s_even + s_odd)
I hope it might help.
Upvotes: 3
Reputation: 361977
Programming is all about decomposing complex problems into simpler ones. Try breaking it down into smaller steps.
for
loop?Tackling those two steps ought to get you on the right track.
Upvotes: 2