reversing a string - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: reversing a string (/thread-11623.html) |
reversing a string - kerzol81 - Jul-18-2018 Hello, I was given a homework, the output should look like this: W Wo Wor Worl World World World H World He World Hel World Hell World Hello The teacher suggested this solution: userInput = 'Hello World' userInput = userInput.split(' ') userInput = userInput[::-1] userInput = ' '.join(userInput) tmp = '' for char in userInput: tmp += char print(tmp)I dont understand why we need an additional tmp variable. Could someone please explain it to me, or have a better, more pythonic solution? RE: reversing a string - ichabod801 - Jul-18-2018 You don't need the tmp variable. You could loop over the indexes directly: for end in range(1, len(userInput) + 1): print(userInput[:end])However, looping over indexes is generally considered very much not Pythonic, so I expect your teacher was trying to avoid giving you bad habits. I'm not seeing a really Pythonic way of doing it (that is, keeping for char in userInput: ) without a variable to hold the string as you are building it.
RE: reversing a string - nilamo - Jul-18-2018 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/master/Modules/itertoolsmodule.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 HelloThat 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'] RE: reversing a string - perfringo - Jul-18-2018 I like nilamo solution. One possible way without itertools: user_input = 'Hello World' text = ' '.join(user_input.split()[::-1]) tmp = '' for char in text: tmp = ''.join((tmp, char)) print(tmp) |