Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
reversing a string
#3
I would say the "pythonic" way, would be to use the itertools module. Though, I doubt your professor would appreciate seeing that lol. Unfortunately, itertools is written in c, not python, so seeing how you could do that yourself doesn't really help: https://github.com/python/cpython/blob/m...le.c#L3424


>>> text = 'Hello World'
>>> text = ' '.join(text.split()[::-1])
>>> text
'World Hello'
>>> import itertools
>>> for permutation in itertools.accumulate(text):
...   print(permutation)
...
W
Wo
Wor
Worl
World
World
World H
World He
World Hel
World Hell
World Hello
That said, if I were to write it in python, I would probably do something like this:
>>> def accum(iterable):
...   iterable = iter(iterable)
...   total = next(iterable)
...   yield total
...   for remaining in iterable:
...     total += remaining
...     yield total
...
>>> text
'World Hello'
>>> list(accum(text))
['W', 'Wo', 'Wor', 'Worl', 'World', 'World ', 'World H', 'World He', 'World Hel', 'World Hell', 'World Hello']
Reply


Messages In This Thread
reversing a string - by kerzol81 - Jul-18-2018, 02:32 PM
RE: reversing a string - by ichabod801 - Jul-18-2018, 05:21 PM
RE: reversing a string - by nilamo - Jul-18-2018, 06:34 PM
RE: reversing a string - by perfringo - Jul-18-2018, 09:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  reversing strings westbob 4 2,651 Jun-11-2019, 04:11 PM
Last Post: buran
  Reversing a String grkiran2011 1 2,379 Dec-02-2017, 04:43 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020