I understand what the lambda function is, its an anonymous function in one line, however why using it, and what really is it? I mean every code I looked at, has it and don't forget map() reduce and filter() function are used with it, what are all these used for and why, I did my research but I still don't understand, (I have a baby's brain 🧠 y'all)
Videos
A lambda expression returns a function object, so you call it the same as you would any other function, with ().
>>> (lambda x : x + 3)(5)
8
A more "normal"-looking function call works the same way, except the function object is referenced by name, rather than directly. The following demonstrate three different ways of accomplishing the same thing: calling a function that returns the value of its argument plus three.
def foo_by_statement(x):
return x + 3
foo_by_expression = lambda x: x + 3
print foo_by_statement(2)
print foo_by_expression(2)
print (lambda x: x + 3)(2)
The first is the traditional way of binding a function object to a name, using the def statement. The second is an equivalent binding, using direct assignment to bind a name to the result of a lambda expression. The third is again calling the return value of a lambda expression directly without binding it to a name first.
Normally, you never actually write code like this. lambda expressions are most useful for generating function objects that are only needed as arguments to higher-order functions. Rather than having to define the function and bind it to a name you will never use again, you simply create the value and pass it immediately as an argument. For example:
plus_three = map(lambda x: x+3, [1,2,3])
When you define a function, python creates a function object and assigns it to a name. When you define a lambda, python creates a function object but doesn't assign it to a name. This is useful in several situations but a common use case is when you want to do a small conversion but don't want to bother with writing a regular function (and having to decide what to name it). Suppose I want to take the power of some numbers, I can
>>> for num in map(lambda i,j: i**j, range(10), range(10)):
... print num
...
1
1
4
27
256
3125
46656
823543
16777216
387420489
Here, map takes a function and calls it with a sequence of parameters.
Instead of cramming everything into a lambda expression, I would just create a function that did everything you need it to do (from your comment, it sounds like you want to apply certain rules to a sentence in a certain order). You can always use that function in list comprehension, map, reduce, etc. Since I don't know exactly what your rules are though, this is the best example I can give:
a = ["This is not a sentence. That was false.",
"You cannot play volleyball. You can play baseball.",
"My uncle once ate an entire bag of corn chips! I am not lying!"]
def f(paragraph):
sentences = paragraph.split(".")
result = []
for i in range(len(sentences)):
//apply rules to sentences
if "not" in sentences[i]:
result.append("negative")
else:
result.append("positive")
return result
my_result = [f(x) for x in a]
Your function could use some improvement:
negation_words = {"no", "not", "never"}
sad_words = {"miss", "loss", "gone", "give", "lost"}
def count_occurrences(s, search_words, negation_words=negation_words):
count = 0
neg = False
for word in s.lower().split(): # should also strip punctuation
if word in search_words and not neg:
count += 1
neg = word in negation_words
return count
print("\n".join(["sad"] * count_occurrences(s, sad_words)))