Lambda Ayyuka da Functional Programming a Python

Lambda Ayyuka

  • A cikin Python, a lambda wani aiki ne da ba a san sunansa ba wanda aka ƙirƙira ta amfani da lambda kalmar maɓalli.
  • Lambda Ayyuka sun ƙunshi magana guda ɗaya, sauƙi mai sauƙi kuma ana amfani da su sau da yawa lokacin da kake buƙatar taƙaitaccen aiki ba tare da ayyana wani aikin daban ba.
  • Ma'anar aikin lambda shine: lambda arguments: expression

Misali:

# 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 salo ne na shirye-shirye dangane da amfani da ayyuka da kuma nisantar sauye-sauye na yanayi.
  • A cikin Python, zaku iya aiwatarwa Functional Programming ta amfani da hanyoyi kamar map(), filter(), reduce(), da lambda ayyuka.
  • Waɗannan ayyuka suna ba ku damar yin ayyuka akan bayanai ba tare da canza yanayinsu ba.

Misali:

# 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 a cikin Python sa lambar ku ta zama abin karantawa, ana iya kiyayewa, da kuma tsawaitawa. Hakanan yana taimaka muku guje wa batutuwan da suka shafi ma'auni masu mahimmanci kuma sanannen salon shirye-shirye ne a cikin haɓaka software.