π Python
Have you ever wanted to write a function that can accept any number of arguments without pre-defining them all? That's where
π These special syntaxes let your functions be incredibly flexible, handling varying inputs like a pro.
* Collects any number of positional arguments into a
* Think of it for inputs where order matters, but quantity doesn't.
* Collects any number of keyword arguments into a
* Think of it for named inputs (like settings or attributes).
π― Use
*args & *kwargs: Flexible Functions, Unlimited Arguments β¨Have you ever wanted to write a function that can accept any number of arguments without pre-defining them all? That's where
*args and *kwargs come in!π These special syntaxes let your functions be incredibly flexible, handling varying inputs like a pro.
*args (Asterisk Args):* Collects any number of positional arguments into a
tuple.* Think of it for inputs where order matters, but quantity doesn't.
*kwargs (Double Asterisk Kwargs):* Collects any number of keyword arguments into a
dictionary.* Think of it for named inputs (like settings or attributes).
def process_data(fixed_arg, *args, **kwargs):
print(f"Fixed argument: {fixed_arg}")
if args:
print(f"Additional positional arguments (tuple): {args}")
if kwargs:
print(f"Keyword arguments (dict): {kwargs}")
# Usage Examples:
process_data("Required")
# Output: Fixed argument: Required
process_data("Required", 1, 2, 3)
# Output:
# Fixed argument: Required
# Additional positional arguments (tuple): (1, 2, 3)
process_data("Required", name="Alice", age=30, city="NY")
# Output:
# Fixed argument: Required
# Keyword arguments (dict): {'name': 'Alice', 'age': 30, 'city': 'NY'}
process_data("Required", 10, "hello", option="fast", debug=True)
# Output:
# Fixed argument: Required
# Additional positional arguments (tuple): (10, 'hello')
# Keyword arguments (dict): {'option': 'fast', 'debug': True}
π― Use
*args and *kwargs to build versatile, future-proof functions that adapt to diverse needs!β€2π₯2π1
Forwarded from Free Programming Books
πA Byte of Python
βοΈ Author: Swaroop C H
Read Online
#Python
ββββββββββββββββββββ
π @free_programming_books_bds π
βοΈ Author: Swaroop C H
Read Online
#Python
ββββββββββββββββββββ
π @free_programming_books_bds π
β€3π₯2
βCommon Pandas Terms
1. Series: A one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
2. DataFrame: A two-dimensional, size-mutable, and potentially heterogeneous tabular data structure with labeled axes (rows and columns).
3. Index: The labels for the rows of a Series or DataFrame, used for fast identification and alignment of data.
4. read_csv: A widely used function to load data from a Comma-Separated Values file into a Pandas DataFrame.
5. head() / tail(): Methods used to quickly inspect the first or last few rows (default is 5) of a DataFrame or Series.
6. loc: A label-based data selection method used to access a group of rows and columns by their labels or a boolean array.
7. iloc: An integer-location based selection method used to access data by its numerical position (0-based indexing).
8. Shape: An attribute that returns a tuple representing the dimensionality of the DataFrame (number of rows, number of columns).
9. Describe: A method that generates descriptive statistics (mean, count, std, min, max, etc.) for numerical columns in a DataFrame.
10. GroupBy: A process involving splitting the data into groups based on some criteria, applying a function, and combining the results.
11. Aggregation (agg): The process of computing a summary statistic (like sum, mean, or count) for each group in a dataset.
12. Merge: A function used to combine two DataFrames based on a common key or index, similar to a SQL JOIN operation.
13. Concatenation (concat): The process of "gluing" together multiple DataFrames or Series along a particular axis (either rows or columns).
14. dropna: A method used to remove missing values (NaN) from a Series or DataFrame.
15. fillna: A method used to replace missing values (NaN) with a specified value or a calculated value (like the mean or median).
16. Apply: A powerful method that allows you to apply a function along an axis of the DataFrame or on a Series.
17. Pivot Table: A method used to summarize and reshape data into a spreadsheet-style table, often used for multi-dimensional analysis.
18. Melt: A function used to transform a "wide" DataFrame into a "long" format, unpivoting columns into rows.
19. Vectorization: The process of performing operations on entire arrays (columns) at once without the need for explicit Python loops, ensuring high performance.
20. DatetimeIndex: A specialized type of index in Pandas that handles date and time information, enabling powerful time-series analysis and resampling.
1. Series: A one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
2. DataFrame: A two-dimensional, size-mutable, and potentially heterogeneous tabular data structure with labeled axes (rows and columns).
3. Index: The labels for the rows of a Series or DataFrame, used for fast identification and alignment of data.
4. read_csv: A widely used function to load data from a Comma-Separated Values file into a Pandas DataFrame.
5. head() / tail(): Methods used to quickly inspect the first or last few rows (default is 5) of a DataFrame or Series.
6. loc: A label-based data selection method used to access a group of rows and columns by their labels or a boolean array.
7. iloc: An integer-location based selection method used to access data by its numerical position (0-based indexing).
8. Shape: An attribute that returns a tuple representing the dimensionality of the DataFrame (number of rows, number of columns).
9. Describe: A method that generates descriptive statistics (mean, count, std, min, max, etc.) for numerical columns in a DataFrame.
10. GroupBy: A process involving splitting the data into groups based on some criteria, applying a function, and combining the results.
11. Aggregation (agg): The process of computing a summary statistic (like sum, mean, or count) for each group in a dataset.
12. Merge: A function used to combine two DataFrames based on a common key or index, similar to a SQL JOIN operation.
13. Concatenation (concat): The process of "gluing" together multiple DataFrames or Series along a particular axis (either rows or columns).
14. dropna: A method used to remove missing values (NaN) from a Series or DataFrame.
15. fillna: A method used to replace missing values (NaN) with a specified value or a calculated value (like the mean or median).
16. Apply: A powerful method that allows you to apply a function along an axis of the DataFrame or on a Series.
17. Pivot Table: A method used to summarize and reshape data into a spreadsheet-style table, often used for multi-dimensional analysis.
18. Melt: A function used to transform a "wide" DataFrame into a "long" format, unpivoting columns into rows.
19. Vectorization: The process of performing operations on entire arrays (columns) at once without the need for explicit Python loops, ensuring high performance.
20. DatetimeIndex: A specialized type of index in Pandas that handles date and time information, enabling powerful time-series analysis and resampling.
β€4
π’ Python
If you ever need to loop through a list and get both the item and its index? Stop using
π Python's
Output:
π― Always use
enumerate(): Loop with Index, The Pythonic Way! β¨If you ever need to loop through a list and get both the item and its index? Stop using
range(len())!π Python's
enumerate() function gives you a clean, efficient, and Pythonic way to do exactly that.my_fruits = ["apple", "banana", "cherry"]
# β The Clumsy Way (Avoid!)
# for i in range(len(my_fruits)):
# print(f"Fruit {i}: {my_fruits[i]}")
# β The Pythonic Way: enumerate()
for index, fruit in enumerate(my_fruits):
print(f"Fruit {index}: {fruit}")
Output:
Fruit 0: apple
Fruit 1: banana
Fruit 2: cherry
π― Always use
enumerate() when you need an index alongside your iterable items. It's cleaner, safer, and makes your loops shine!β€5π2
β‘οΈ Python Sets: Stop Nesting Loops for Comparisons
Nested loops to find common items between lists are a performance killer. As your data grows, checking
Python Sets use hash tables to turn these comparisons into lightning-fast math operations.
π― Stop "searching" through lists to find overlaps or differences. Convert your data to
Nested loops to find common items between lists are a performance killer. As your data grows, checking
if item in list inside another loop slows down your code exponentially. Python Sets use hash tables to turn these comparisons into lightning-fast math operations.
# Two lists with 1 million items
list_a = list(range(1_000_000))
list_b = list(range(500_000, 1_500_000))
# β THE SLOW WAY: Nested lookup (O(n^2))
# This could take minutes on large lists
# common = [x for x in list_a if x in list_b]
# β THE PRO WAY: Set Math (O(n))
# This happens almost instantly
common = set(list_a) & set(list_b) # Intersection
diff = set(list_a) - set(list_b) # Items in A but not B
π― Stop "searching" through lists to find overlaps or differences. Convert your data to
set() and use math symbols (&, -, ^) to handle large-scale comparisons in milliseconds.β€5
Forwarded from Free Programming Books
Annotated Algorithms in Python.pdf
2.6 MB
π Annotated Algorithms in Python
βοΈ Author: Massimo Di Pierro
π Year: 2021
π Pages: 376
π§ This open book is assembled from lectures given by the author over a period of 10 years at the School of Computing of DePaul University. The lectures cover multiple classes, including Analysis and Design of Algorithms, Scientific Computing, Monte Carlo Simulations, and Parallel Algorithms. These lectures teach the core knowledge required by any scientist interested in numerical algorithms and by students interested in computational finance.
#Algorithms
βοΈ Author: Massimo Di Pierro
π Year: 2021
π Pages: 376
π§ This open book is assembled from lectures given by the author over a period of 10 years at the School of Computing of DePaul University. The lectures cover multiple classes, including Analysis and Design of Algorithms, Scientific Computing, Monte Carlo Simulations, and Parallel Algorithms. These lectures teach the core knowledge required by any scientist interested in numerical algorithms and by students interested in computational finance.
#Algorithms
β€4
βAsynchronous Programming in Python
Asynchronous programming allows applications to handle multiple tasks simultaneously without blocking. This is especially useful for I/O-bound operations, such as web requests, where waiting can lead to inefficiencies.
βKey Concepts
β’ Event Loop: Manages and dispatches events or tasks.
β’ Coroutines: Functions defined with
β’ Tasks: Wrappers for coroutines that run concurrently.
βBenefits
1. Improved Performance: Handles more requests in less time.
2. Better Resource Utilization: Non-blocking I/O optimizes system resource use.
3. Responsive Applications: Keeps user interfaces responsive during background processing.
βGetting Started with
The
βExplanation
β’
β’
β’
βReal-World Application: Web Scraping
Using
Asynchronous programming allows applications to handle multiple tasks simultaneously without blocking. This is especially useful for I/O-bound operations, such as web requests, where waiting can lead to inefficiencies.
βKey Concepts
β’ Event Loop: Manages and dispatches events or tasks.
β’ Coroutines: Functions defined with
async def that can pause execution.β’ Tasks: Wrappers for coroutines that run concurrently.
βBenefits
1. Improved Performance: Handles more requests in less time.
2. Better Resource Utilization: Non-blocking I/O optimizes system resource use.
3. Responsive Applications: Keeps user interfaces responsive during background processing.
βGetting Started with
asyncioThe
asyncio library provides the tools for asynchronous programming. Hereβs a simple example simulating data fetching from multiple URLs:import asyncio
import random
async def fetch_data(url):
print(f"Fetching data from {url}...")
await asyncio.sleep(random.uniform(1, 3)) # Simulate network delay
print(f"Data fetched from {url}")
return f"Data from {url}"
async def main():
urls = ["http://example.com", "http://example.org", "http://example.net"]
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
print("All data fetched:", results)
# Run the main function
asyncio.run(main())
βExplanation
β’
fetch_data(url): An asynchronous function simulating data fetching.β’
asyncio.sleep(): A non-blocking sleep that allows other tasks to run.β’
asyncio.gather(): Runs multiple coroutines concurrently.βReal-World Application: Web Scraping
Using
aiohttp, you can perform asynchronous HTTP requests efficiently. Hereβs an example:import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def scrape(urls):
tasks = [fetch(url) for url in urls]
return await asyncio.gather(*tasks)
urls = ["http://example.com", "http://example.org", "http://example.net"]
# Run the scraping function
results = asyncio.run(scrape(urls))
print("Scraped data:", results)
β€4
Forwarded from Programming Quiz Channel
What is the output of this code?
x = [1, 2, 3]
y = x y.append(4) print(len(x))
x = [1, 2, 3]
y = x y.append(4) print(len(x))
Anonymous Quiz
22%
3
40%
4
27%
Error
11%
Undefined
β€4