Lambda Kazi na Functional Programming ndani Python

Lambda Kazi

  • Katika Python, a lambda ni chaguo la kukokotoa lisilojulikana linaloundwa kwa kutumia lambda neno kuu.
  • Lambda vitendaji vinajumuisha usemi mmoja, rahisi na mara nyingi hutumika unapohitaji kitendakazi kifupi bila kufafanua kitendakazi tofauti.
  • Sintaksia ya lambda chaguo za kukokotoa ni: lambda arguments: expression

Mfano:

# Lambda function to calculate square  
square = lambda x: x**2  
print(square(5))   # Output: 25  
  
# Lambda function to calculate the sum of two numbers  
add = lambda a, b: a + b  
print(add(3, 7))   # Output: 10  

 

Functional Programming

  • Functional Programming ni mtindo wa upangaji kulingana na utumiaji wa vitendaji na epuka vigeuzo vya hali.
  • Katika Python, unaweza kutekeleza Functional Programming kwa kutumia mbinu kama map(), filter(), reduce(), na lambda kazi.
  • Kazi hizi hukuruhusu kufanya shughuli kwenye data bila kubadilisha hali yao.

Mfano:

# Using map() and lambda function to calculate squares of numbers in a list  
numbers = [1, 2, 3, 4, 5]  
squared_numbers = list(map(lambda x: x**2, numbers))  
print(squared_numbers)   # Output: [1, 4, 9, 16, 25]  
  
# Using filter() and lambda function to filter even numbers in a list  
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))  
print(even_numbers)   # Output: [2, 4]  

Functional Programming katika Python hufanya msimbo wako kusomeka zaidi, kudumishwa, na kupanuka. Pia hukusaidia kuepuka masuala yanayohusiana na vigeuzo vya hali na ni mtindo maarufu wa upangaji katika uundaji wa programu.