Question

How to use lambda? and other abstract list functions such as map, filter, etc?

How to use lambda? and other abstract list functions such as map, filter, etc?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

LAMBDA

The lambda feature was added to Python due to the demand from Lisp programmers.

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

The general syntax of a lambda function is quite simple:

lambda argument_list: expression

Sample Program 0n Lambda:

sum = lambda x, y : x + y
sum(3,4)

Output:

7

MAP:

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)

produces a new iterator, applying function to each element in list.

Requires: datatype consumed by function must match type in list

syntax of map:

map(function, list)

Sample Program On MAP:

def pull_to_passing(mark):
if mark < 50 and mark > 46:
print('50')
else:
print(mark)
list(map(pull_to_passing, [34, 89, 46, 49, 52]))

output:

34 89 46 50 52

Example2:

# Add two lists using map and lambda

numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]

result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))

Output:

[5,7,9]

Example3:

# List of strings
l = ['sat', 'bat', 'cat', 'mat']

# map() can listify the list of strings individually
test = list(map(list, l))
print(test)

Output:

[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]

FILTER:

produces an iterator matching the elements in list for which function produces True.

Requires: type consumed by function must match type in list.

syntax of filter:

filter(function, list)

Sample Program On Filter:

def fun(variable):

    letters = ['a', 'e', 'i', 'o', 'u']

    if (variable in letters):

        return True

    else:

        return False

  sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']

  filtered = filter(fun, sequence)

print('The filtered letters are:')

for s in filtered:

    print(s)

Output

e e

Application

It is normally used with Lambda functions to separate list, tuple, or sets.

Sample Example of application

# a list contains both even and odd numbers.

seq = [0, 1, 2, 3, 5, 8, 13]

  

# result contains odd numbers of the list

result = filter(lambda x: x % 2==1, seq)

print(list(result))

  

# result contains even numbers of the list

result = filter(lambda x: x % 2 == 0, seq)

print(list(result))

Add a comment
Know the answer?
Add Answer to:
How to use lambda? and other abstract list functions such as map, filter, etc?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Use scheme to solve this: MUST USE A COMBINATION OF MAP AND FILTER or MAP AND...

    Use scheme to solve this: MUST USE A COMBINATION OF MAP AND FILTER or MAP AND APPLY: THIS ANSWER IS NOT WHAT I NEED: (define perfect-square-helper (lambda (x y) (if (null? x) (reverse y) (if (integer? (sqrt (car x))) (perfect-square-helper (cdr x) (cons (car x) y)) (perfect-square-helper (cdr x) y))))) (define perfect-square (lambda (x) (perfect-square-helper x '()))) (define x '(1 2 9 16 5 64)) (perfect-square x) Map/Apply/Filter 7. Perfect Squares (10 Points) Using a combination of map, apply and/or...

  • bigrams = text_file.flatMap(lambda line: line.split(".")) \ .map(lambda line: line.strip().split(" ")) \ .flatMap(lambda xs: (tuple(x) for x...

    bigrams = text_file.flatMap(lambda line: line.split(".")) \ .map(lambda line: line.strip().split(" ")) \ .flatMap(lambda xs: (tuple(x) for x in zip(xs, xs[1:]))) bigrams.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y) This code gives me a list of bigrams from my file. Can this be edited so it gives, unigrams/trigrams/quadgrams etc?

  • Map, Filter, and Reduce are three functions commonly used in functional programming. For this assignment you...

    Map, Filter, and Reduce are three functions commonly used in functional programming. For this assignment you will be implementing all three, along with three minor functions that can be passed to them. Map The map function takes as arguments a function pointer and a integer vector pointer. It applies the function to every element in the vector, storing the results in-order in a new vector. It then returns a pointer to a new vector. You should pass your square function...

  • Assuming x and y each are a list of integers, answer the following questions. Use a...

    Assuming x and y each are a list of integers, answer the following questions. Use a as a running variable. If necessary use b as an additional running variable. Do not use any other variables as you do not need. a. Write a Python statement using lambda calculus map to map x to y where every element of y is incremented by 1. b. Write a Python statement using lambda calculus reduce to reduce x to s, where s is...

  • For Python, I am a little confused on the use of reduce,map, and lambda. My assignment wants me t...

    For Python, I am a little confused on the use of reduce,map, and lambda. My assignment wants me to not use .join() and write a SINGLE LINE function to join each letter in a list with another string.(See problem below). Using reduce, map, and lambda, write the single-expression function myJoin(L, sep) that takes a non-empty list L and a string sep, and without calling sep.join(L), works roughly the same as that returning a single string with the values in L...

  • Using Racket Recursion, tail-recursion, high-order functions and functional programming. 1. Modify our filter function so that...

    Using Racket Recursion, tail-recursion, high-order functions and functional programming. 1. Modify our filter function so that it is tail-recursive. You may use the letrec form but do not use any additional forms and functions besides those we've talked about in class. (define filter (lambda (input-list func)     (cond ((null? input-list) '())           ((func (car input-list))            (cons (car input-list) (filter (cdr input-list) func)))           (else            (filter (cdr input-list) func))))) 2. Test your filter function on '(25 -22 44 56...

  • Select all correct options in the list below about concrete and abstract classes Select one or...

    Select all correct options in the list below about concrete and abstract classes Select one or more: a. Concrete classes can be instantiated b. Abstract classes must contain at least one abstract method c. Only concrete classes can be super classes d. Abstract classes (using the "abc" library) can be instantiated e. Concrete classes often contain abstract methods f. Both concrete and abstract classes can be super classes that other classes inherit from g. Only abstract classes can be super...

  • In Python (and make it a function, with sample input, output): Write map function from scratch,...

    In Python (and make it a function, with sample input, output): Write map function from scratch, that does not use lambda functions. It should take a list of real numbers, and a string, which describes a formula in terms of x as input, and output a list with elements that are equal to the elements of the original list taken through the function.

  • The Abstract and List of Alternatives, from the answer of " Explain how it would be possible to u...

    The Abstract and List of Alternatives, from the answer of " Explain how it would be possible to use a man-in-the-middle attack if the legitimate AP does not implement 802.11i. Also explain how a user could be persuaded to use an evil twin AP. "

  • In this module you learned how to create polymorphic code using virtual functions. A file filter...

    In this module you learned how to create polymorphic code using virtual functions. A file filter reads an input file, transforms it in some way, and writes the results to an output file. Write an abstract file filter class that defines a pure virtual function for transforming a character. Create one subclass of your file filter class that performs encryption, another that transforms a file to all uppercase, and another that creates an unchanged copy of the original file. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT