-2

I have a iterable sequence nums = [1,2,3,4]. I want to create a generator function which, when next(nums) is used, will return the values one by one in reverse order. My goal is to do this using len(). I know the length of the list minus one would be the index of the last item in the list. How would I write the code for the output using len():

    next(nums)
4
    next(nums)
3
    next(nums)
2
    next(nums)
1

EDIT: Forgot to mention no other built-in functions are allowed.

user10019227
  • 117
  • 1
  • 2
  • 7
  • 1
    While this question may not be an exact duplicate of the linked question, it's not one I'm willing to vote to reopen because you haven't show us any effort to solve the problem on your own. Asking Stack Overflow to answer your homework for you is cheating yourself out of a chance to learn how Python works (and may also be cheating in a more literal sense according to the rules of your school). Make an attempt to solve the problem on your own, and then if you run into a specific problem, ask us about that instead of just dropping the assignment on us. (It may even allowed by your instructors!) – Blckknght Aug 08 '18 at 05:00

1 Answers1

0
>>> def solution(lst):
...     dex = len(lst) - 1
...     while dex >= 0:
...         yield lst[dex]
...         dex -= 1
... 
>>> nums = solution([1, 2, 3, 4])
>>> next(nums)
4
>>> next(nums)
3
>>> next(nums)
2
>>> next(nums)
1
>>> next(nums)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration
G_M
  • 3,342
  • 1
  • 9
  • 23