Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lab solved #79

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,383 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e",
"metadata": {},
"source": [
"# Lab | Lambda Functions, Map, Reduce, Filter"
]
},
{
"cell_type": "markdown",
"id": "6f8e446f-16b4-4e21-92e7-9d3d1eb551b6",
"metadata": {},
"source": [
"Objective: The objective of this lab is to help students gain familiarity with using anonymous lambda functions and map, reduce, and filter methods in Python."
]
},
{
"cell_type": "markdown",
"id": "0120f101-3f9a-444c-84b9-a10a990a5f95",
"metadata": {},
"source": [
"Lambda functions, map, reduce, and filter are all related to functional programming in Python. \n",
"\n",
"**Lambda functions** are anonymous functions in Python, which means that they do not need to be defined with a name. They are typically used for short, one-line functions that are not going to be used elsewhere in the code. \n",
"\n",
"Lambda functions can take any number of arguments, but they can only contain a single expression. They are often used in combination with other built-in functions like map, reduce, and filter to perform operations on lists or other iterables."
]
},
{
"cell_type": "markdown",
"id": "7afb4d9e-63a9-4326-87f1-a0915769721c",
"metadata": {},
"source": [
"**Map** is a function that applies a given function to every element of a list, returning a new list with the transformed values. It's a useful way to apply the same operation to every element of a list, without having to write a for loop.\n",
"\n",
"**Reduce** is a function that applies a given function to the first two elements of a list, then applies the same function to the result and the next element, and so on, until it has reduced the list to a single value. It's useful for performing cumulative operations like summing or multiplying a list of numbers.\n",
"\n",
"**Filter** is a function that takes a function and a list, and returns a new list containing only the elements of the original list for which the function returns True. It's a useful way to selectively extract elements from a list based on a certain condition."
]
},
{
"cell_type": "markdown",
"id": "053ee1bc-59fa-4cf8-9191-916b6cdc5811",
"metadata": {},
"source": [
"All of these concepts can be used to make your code more concise and expressive, especially when working with lists or other iterables. They are also useful in data manipulation tasks, such as cleaning and transforming data in a pandas DataFrame. By practicing with these concepts in the lab, you will gain a better understanding of how to use them in a variety of programming tasks."
]
},
{
"cell_type": "markdown",
"id": "65df3710-f236-4818-9a4f-43bfd53cad7c",
"metadata": {},
"source": [
"## Challenge 1"
]
},
{
"cell_type": "markdown",
"id": "0e704740-6ac4-49d0-b25b-960cf8511a04",
"metadata": {},
"source": [
"In this Challenge we will use the following data, which is a list of bank transactions:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "08463071-9351-4d49-8d29-4fcb817fb177",
"metadata": {},
"outputs": [],
"source": [
"transactions = [(-1200, 'debit'), (2500, 'credit'), (-100, 'debit'), (850, 'credit'), (-250, 'debit'), (1500, 'credit'), (-300, 'debit'), (5000, 'credit'), (-850, 'debit'), (1000, 'credit')]"
]
},
{
"cell_type": "markdown",
"id": "ae7d88f0-a8e7-4f74-98d3-802306bdcf07",
"metadata": {},
"source": [
"### Exercise 1"
]
},
{
"cell_type": "markdown",
"id": "16796011-a618-499a-a57f-4ca61d0a77e7",
"metadata": {},
"source": [
"Create a new list called credits that includes all of the debit transactions from the list transactions.\n",
"\n",
"Use the filter() function to create a new list called debits."
]
},
{
"cell_type": "code",
"execution_count": 205,
"id": "0781335d-39cf-403d-b86a-ca908a09fe55",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(-1200, 'debit'),\n",
" (-100, 'debit'),\n",
" (-250, 'debit'),\n",
" (-300, 'debit'),\n",
" (-850, 'debit')]"
]
},
"execution_count": 205,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"debits = list(filter(lambda x: x[1] == 'debit', transactions))\n",
"debits"
]
},
{
"cell_type": "markdown",
"id": "37ca34af-7f87-44f2-a45d-1a1e2ef8c194",
"metadata": {},
"source": [
"### Exercise 2"
]
},
{
"cell_type": "markdown",
"id": "546c5aa2-6f16-4285-9c47-0f788b23552c",
"metadata": {},
"source": [
"Create a new list that includes all of the debit transactions from the list transactions, sorted in descending order by amount.\n",
"\n",
"- Use the previously created debits list.\n",
"- Define a lambda function called sort_descending that takes two tuples and returns True if the transaction amount of the first tuple is greater than the transaction amount of the second tuple.\n",
"- Use the sorted() function with a lambda fucntion and debits to create a new list."
]
},
{
"cell_type": "code",
"execution_count": 54,
"id": "25073469-7258-4fc6-b0a0-ef8ea57688fe",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(-100, 'debit'),\n",
" (-250, 'debit'),\n",
" (-300, 'debit'),\n",
" (-850, 'debit'),\n",
" (-1200, 'debit')]"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sort_descending = lambda x: x[0]\n",
"desc_sorted_debits = sorted(credits, key = sort_descending, reverse=True)\n",
"desc_sorted_debits"
]
},
{
"cell_type": "markdown",
"id": "bee57a6e-19a3-4708-9b70-3b41a215353f",
"metadata": {},
"source": [
"## Challenge 2: Interest Calculation"
]
},
{
"cell_type": "markdown",
"id": "4e7c9f00-7c48-4c39-9de1-14db7fc468eb",
"metadata": {},
"source": [
"### Exercise 1"
]
},
{
"cell_type": "markdown",
"id": "3500df4c-91bd-4f8f-9ffe-4d6a51460bc6",
"metadata": {},
"source": [
"Write Python code to take a list of bank account balances, and returns a new list containing the balance after one year of interest has been added. Use the map function to apply this function to the list of bank accounts, and take an interest rate of 0.05."
]
},
{
"cell_type": "code",
"execution_count": 56,
"id": "e1de9d03-f029-4e2e-9733-ae92e3de7527",
"metadata": {},
"outputs": [],
"source": [
"# create list of bank account balances\n",
"balances = [100, 50, -25, 1000, -10]"
]
},
{
"cell_type": "code",
"execution_count": 149,
"id": "2f253b7e-5300-4819-b38f-9fc090554f51",
"metadata": {},
"outputs": [],
"source": [
"interest1 = lambda x: x*0.05+x\n",
"new_balances = list(map(interest1, balances))\n"
]
},
{
"cell_type": "markdown",
"id": "6a515b75-8ccb-4ee3-9dc0-f36d72ac66a0",
"metadata": {},
"source": [
"### Exercise 2"
]
},
{
"cell_type": "markdown",
"id": "7022779a-7611-428b-8f7d-138e923a63b8",
"metadata": {},
"source": [
"Write Python code to take a list of bank account dictionaries, each containing the account balance and interest rate, and returns a new list of dictionaries containing the balance after one year of interest has been added. Use the map function to apply this function to the list of bank accounts."
]
},
{
"cell_type": "code",
"execution_count": 82,
"id": "69e24c3b-385e-44d6-a8ed-705a3f58e696",
"metadata": {},
"outputs": [],
"source": [
"accounts = [\n",
" {'balance': 1000, 'interest_rate': 0.02},\n",
" {'balance': 2000, 'interest_rate': 0.01},\n",
" {'balance': 500, 'interest_rate': 0.03},\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 145,
"id": "0906a9b0-d567-4786-96f2-5755611b885e",
"metadata": {},
"outputs": [],
"source": [
"interest2 = lambda account: account['balance'] * account['interest_rate'] + account['balance']\n",
"new_account_balances = list(map(interest2, accounts))\n",
"new_account = []\n",
"for bal in new_account_balances:\n",
" new_account.append({'balance':bal})"
]
},
{
"cell_type": "markdown",
"id": "69788c08-90c5-4c15-be3d-55ac4a963fe2",
"metadata": {},
"source": [
"## Challenge 3: Balance Reduction"
]
},
{
"cell_type": "markdown",
"id": "81536227-379c-461f-b564-6695957bd0c1",
"metadata": {},
"source": [
"### Exercise 1"
]
},
{
"cell_type": "markdown",
"id": "1006852a-42fc-4aae-bc0a-c771a94f6b2d",
"metadata": {},
"source": [
"Write Python code to take the new list of bank account balances (balances list after applying an interest_rate of 0.05, result of Challenge 2 Exercise 1), and print the total amount of negative balances. Use filter and reduce function."
]
},
{
"cell_type": "code",
"execution_count": 165,
"id": "6284dbd3-e117-411e-8087-352be6deaed4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-36.75\n"
]
}
],
"source": [
"from functools import reduce\n",
"\n",
"neg_bal = list(filter(lambda x: x < 0, new_balances))\n",
"neg_bal_sum = reduce(lambda x, y: x + y, neg_bal)\n",
"\n",
"print(neg_bal_sum)"
]
},
{
"cell_type": "markdown",
"id": "3926594f-3204-4de3-a6bf-bd87069a82cc",
"metadata": {},
"source": [
"### Exercise 2"
]
},
{
"cell_type": "markdown",
"id": "6149139b-43db-473b-a10e-8bff9a38dcbf",
"metadata": {},
"source": [
"Write a Python function called calculate_balance that takes a bank account dictionary as an argument and returns the remaining balance after subtracting all the withdrawals.\n",
"\n",
"Then, use the map function and the calculate_balance function to apply it to the list accounts. This should give you a list of remaining balances after all the withdrawals have been subtracted."
]
},
{
"cell_type": "code",
"execution_count": 201,
"id": "da2264b5-298e-4b45-99df-852b94e90d15",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[650, 1600, 275]"
]
},
"execution_count": 201,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"accounts = [\n",
" {'balance': 1000, 'withdrawals': [100, 50, 200]},\n",
" {'balance': 2000, 'withdrawals': [300, 100]},\n",
" {'balance': 500, 'withdrawals': [50, 100, 75]},\n",
"]\n",
"\n",
"calculate_balance = lambda account: account['balance'] - sum(account['withdrawals'])\n",
"\n",
"test = list(map(calculate_balance, accounts))\n",
"test"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "15adb8f8-a152-4ccf-85a2-502d064ff762",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "conda-base-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading