简体   繁体   中英

High Order Map Function with Lambda Expression Python

I'm trying to write a higher order function that will take 2 lambda expressions and a list and will return the result. I have my code below.

#Square
square = lambda x:x ** 2

#Mod_2
mod_2 = lambda x:x % 2

def map(f,x):
  return f(x)

It looks very simple, and should be. This is the error I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "main.py", line 8, in map
    return f(x)
  File "main.py", line 2, in <lambda>
    square = lambda x:x ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

Here's what the results should be:

>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>> map(square, [])
[]
>>> map(mod_2, range(1, 11))
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]

This is NOT homework, and is simply and way to understand higher order functions better. Also, this is not a repeat of any other submission because this is fixing MY code, not how to do the problem itself. If it needs rethinking, please reply and tell me how. Thank you!

Use a list comprehension:

def map(f,x):
    return [f(i) for i in x]

You can use a lambda here too:

map = lambda f, x: [f(i) for i in x]

Or just use the map() built-in.

map() is a built-in function. Why are you redefining it? Delete def map().

#Square
square = lambda x: x**2

#Mod_2
mod_2 = lambda x:x % 2

r1 = list(map(square, [1, 2, 3, 4]))
r2 = list(map(mod_2, range(1, 11)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM