Stikka
Stikka

Reputation: 27

Iterate through a string forwards and backwards, extracting alternating characters

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

Answers (3)

Swadhikar
Swadhikar

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

Shag
Shag

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

John Kugelman
John Kugelman

Reputation: 361977

Programming is all about decomposing complex problems into simpler ones. Try breaking it down into smaller steps.

  1. First, can you generate the numbers 1,3,5,7 in a for loop?
  2. Next, can you generate 8,6,4,2 in a second loop?

Tackling those two steps ought to get you on the right track.

Upvotes: 2

Related Questions