generic code to reverse alternate words in a sentence using python

Abi

can anyone please help on how to reverse alternate words in a sentence from the end using python.

note: do not use reversed()

eg:

aspire systems is in america

acirema in si systems eripsa

s = 'aspire systems is in america'

l = len(s) - 1

rev = ''

for i in range (0,l):

rev = rev + str(a[l])
l--
  • i couldnt find a way to jump to "in" and print it.
Arthur Hv

Can we use split/join ?

s = 'aspire systems is in america'
li = s.split(' ') #["aspire", "systems", "is", "in", "america"]
#Reverse alternate words
for index in range (0,len(li),2): #0, 2, 4
    rev = ''
    for ch in li[index]: #'a', 's', 'p' ...
        rev = ch + rev
    li[index] = rev
#Now reverse the list of words
revli = []
for word in li:
    revli = word + revli
print ' '.join(revli) #Should print expected result

It should be equivalent to the following code, which uses reversed :

s = 'aspire systems is in america'
li = s.split(' ') #["aspire", "systems", "is", "in", "america"]
#Reverse alternate words
for index in range (0,len(li),2): #0, 2, 4
    li[index] = reversed(li[index])
print ' '.join(reversed(li)) #Should print expected result

I cannot test the code currently, please tell me if anything is missing or if you have any question concerning the code. If you are learning programming, it's important you fully understand it

EDIT: corrected join call

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related