Issue
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.
Solution
>>> 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
Answered By - G_M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.