The task is to read several lines from the standard input. The number of lines is specified in the first input line (say, N), and then follows N lines, which must be read without using for, if, and so on. It is necessary to do this only with the help of functional programming elements. I broke my head, I can not figure out how to do it. Somewhere on the subconscious spinning, you need to use range (N), but why I don’t understand what to apply. What are the ideas?
2 answers
It is possible so:
In [49]: N = 3 In [50]: a = list(map(lambda _: input('Input a string: '), range(N))) Input a string: aaa Input a string: bbb Input a string: ccc In [51]: print(a) ['aaa', 'bbb', 'ccc'] map(lambda _:looks ugly. - jfs
|
Conveniently use itertools.islice to get N lines from a file lazily:
import sys from itertools import islice N = int(next(sys.stdin)) lines = islice(sys.stdin, N) The file is an iterator over rows in Python.
|
forandifformally, but it can be considered an "element of functional programming" Haskell, which is a purely functional language and has a similar construction with the same name. - jfs