Python Classroom Series – 10/Jul/2021

Sell Functionality to reduce quantity in inventory

Python Anonymous Functions/Lambda Functions

  • In Python, anonymous function is a function that is defined without a name.
  • Generally normal functions are defined using def keyword, where as anonymous functions are defined using the lambda keyword
  • Syntax:
lambda arguments: expression
  • Basic example Preview
  • Use of Lambda functions in python:
  • Example use with filter() Preview
  • Example use with map() Preview
  • Lambda can be implement to choose the product
selected_product: models.Product = list(filter(lambda product: product.id == id),products)[0]

Using List Comprehensions

  • Consider the employees and try to find all the employees having salary greater than or equal to 1 lakh as top earners
  • To find the top earners the code is
employees = {
    'Alice': 100000,
    'Bob': 98000,
    'Cena': 127000,
    'Dwayne': 158000,
    'Frank': 88000
}

# find the top earner (every one with salary greater than or equal to 1 lakh)

top_earners = []
for name,salary in employees.items():
    if salary >= 100000:
        top_earners.append((name,salary))

print(top_earners)

  • One liner
## One-liner

top_earners = [(n,s) for n,s in employees.items() if s >= 100000 ]
print(top_earners)

Reading a File

  • Traditional approach:
file_name = 'data/info.txt'

file_object = open(file_name)
lines = []
for line in file_object:
    lines.append(line.strip())
print(lines)
file_object.close()
  • one_liner
print([line.strip() for line in open('data/info.txt')])

Combinining List Comprehensions and Slicing

  • Assume we have a large dataset which has stock market prices of some stock during a week
  • To create a data sample for some alogrithm, we decided to take every alternate stock price in a day

price = [
    [ 9.9, 9.8, 9.7, 9.5, 9.4 ],
    [ 9.5, 9.6, 9.4, 9.4, 9.2 ],
    [ 8.4, 7.9, 7.9, 8.2, 8.1 ],
    [ 7.1, 5.9, 4.1, 4.8, 5.2 ]
]

sample = [ line[::2] for line in price ]
print(sample)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin