-2

For example, I have a list such as [2, 4, 7, 9, 6, 12, 38]. I want to firstly recognize each number by whether it is odd, then add 100 to each odd and 101 to each even,finally get two lists. There are 3 steps: 1. Number matching that it is odd or even 2. Add a proper decimal to each odd and even 3. Group to two list

In python, might need 3 minimal functions, but still how should we reach the goal by using Functional programming?

Feng Lei
  • 19
  • 5
  • Please read hits googling 'stackexchange homework" & show what you are able to do. If you get stuck then post a [mcve]. Questions asking for code meeting a specification are not valid SO questions. – philipxy Aug 22 '18 at 05:36

1 Answers1

1

The order of the steps seems forced and makes functional programming a lot harder, so with an open order a Python implementation would be the following:

odd = lambda x: x % 2 == 1
even = lambda x: not odd(x)
l = [2, 4, 7 ,9 ,36]
listodd = [i + 100 for i in l if odd(i)]
listeven = [i + 101 for i in l if no odd(i)]

So every list is created with one expression, and list comprehensions are definitely valid functional programming. Another way to express the list comprehension would be with filter and map:

listodd = map(filter(l, odd), lambda x: x + 100)
listeven = map(filter(l, even), lambda x: x + 101)

The code is still highly redundant, but as for now I have no idea how to write this shorter and cleaner.

univalence
  • 146
  • 4
  • 1
    You're close, but remember you can do logic from within the list comprehension/lambda. What you were looking for are `[n + 100 if odd(n) else n + 101 for n in list_in]` and `list(map(lambda n: n + 100 if odd(n) else n + 101, list_in))` (note given python3 your map has arguments the wrong way around, and map doesn't return a list type) – Ross Mackay Aug 21 '18 at 18:01
  • Thank you all. Nice solution and it helps a lot. – Feng Lei Aug 29 '18 at 11:56