kopia lustrzana https://github.com/animator/learn-python
Merge branch 'main' into main
commit
a6568094cb
|
@ -0,0 +1,117 @@
|
|||
## Working with Dates and Times in Python
|
||||
Handling dates and times is an essential aspect of many programming tasks.
|
||||
Python provides robust modules to work with dates and times, making it easier to perform operations like formatting, parsing, and arithmetic.
|
||||
This guide provides an overview of these modules and their key functionalities.
|
||||
|
||||
## 1. 'datetime' Module
|
||||
The datetime module supplies classes for manipulating dates and times. The main classes in the datetime module are:
|
||||
|
||||
* date: Represents a date (year, month, day).
|
||||
* time: Represents a time (hour, minute, second, microsecond).
|
||||
* datetime: Combines date and time information.
|
||||
* timedelta: Represents the difference between two dates or times.
|
||||
* tzinfo: Provides time zone information objects.
|
||||
|
||||
**Key Concepts:**
|
||||
|
||||
* Naive vs. Aware: Naive datetime objects do not contain time zone information, while aware datetime objects do.
|
||||
* Immutability: date and time objects are immutable; once created, they cannot be changed.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import datetime
|
||||
# Get the current date and time
|
||||
now = datetime.datetime.now()
|
||||
print("Current date and time:", now)
|
||||
```
|
||||
|
||||
## 2. Formatting Dates and Times
|
||||
Formatting involves converting datetime objects into human-readable strings. This is achieved using the strftime method, which stands for "string format time."
|
||||
You can specify various format codes to dictate how the output string should be structured.
|
||||
|
||||
**Common Format Codes:**
|
||||
|
||||
* %Y: Year with century (e.g., 2024)
|
||||
* %m: Month as a zero-padded decimal number (e.g., 01)
|
||||
* %d: Day of the month as a zero-padded decimal number (e.g., 15)
|
||||
* %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 13)
|
||||
* %M: Minute as a zero-padded decimal number (e.g., 45)
|
||||
* %S: Second as a zero-padded decimal number (e.g., 30)
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import datetime
|
||||
|
||||
now = datetime.datetime.now()
|
||||
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
print("Formatted current date and time:", formatted_now)
|
||||
```
|
||||
|
||||
## 3. Parsing Dates and Times
|
||||
Parsing is the process of converting strings representing dates and times into datetime objects. The strptime method, which stands for "string parse time,"
|
||||
allows you to specify the format of the input string.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import datetime
|
||||
|
||||
date_string = "2024-05-15 13:45:30"
|
||||
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
|
||||
print("Parsed date and time:", date_object)
|
||||
```
|
||||
|
||||
## 4. Working with Time Differences
|
||||
The timedelta class is used to represent the difference between two datetime objects. This is useful for calculations involving durations, such as finding the
|
||||
number of days between two dates or adding a certain period to a date.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import datetime
|
||||
|
||||
date1 = datetime.datetime(2024, 5, 15, 12, 0, 0)
|
||||
date2 = datetime.datetime(2024, 5, 20, 14, 30, 0)
|
||||
|
||||
difference = date2 - date1
|
||||
print("Difference:", difference)
|
||||
print("Days:", difference.days)
|
||||
print("Total seconds:", difference.total_seconds())
|
||||
```
|
||||
|
||||
## 5. Time Zones
|
||||
Time zone handling in Python is facilitated by the pytz library. It allows you to convert naive datetime objects into timezone-aware objects and perform
|
||||
operations across different time zones.
|
||||
|
||||
**Key Concepts:**
|
||||
|
||||
* Timezone-aware: A datetime object that includes timezone information.
|
||||
* Localization: The process of associating a naive datetime with a time zone.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import datetime
|
||||
import pytz
|
||||
|
||||
# Define a timezone
|
||||
tz = pytz.timezone('Asia/Kolkata')
|
||||
|
||||
# Get the current time in a specific timezone
|
||||
now = datetime.datetime.now(tz)
|
||||
print("Current time in Asia/Kolkata:", now)
|
||||
```
|
||||
|
||||
## 6. Date Arithmetic
|
||||
Date arithmetic involves performing operations like addition or subtraction on date or datetime objects using timedelta. This is useful for calculating future
|
||||
or past dates based on a given date.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import datetime
|
||||
|
||||
today = datetime.date.today()
|
||||
future_date = today + datetime.timedelta(days=10)
|
||||
print("Date after 10 days:", future_date)
|
||||
```
|
||||
|
||||
## Summary
|
||||
Python’s datetime module and the pytz library provide comprehensive tools for working with dates, times, and time zones. They enable you to perform a wide range
|
||||
of operations, from basic date manipulations to complex time zone conversions.
|
|
@ -1,3 +1,5 @@
|
|||
# List of sections
|
||||
|
||||
- [Decorators/\*args/**kwargs](decorator-kwargs-args.md)
|
||||
- [Working with Dates & Times in Python](dates_and_times.md)
|
||||
- [Regular Expressions in Python](regular_expressions.md)
|
||||
|
|
|
@ -0,0 +1,96 @@
|
|||
## Regular Expressions in Python
|
||||
Regular expressions (regex) are a powerful tool for pattern matching and text manipulation.
|
||||
Python's re module provides comprehensive support for regular expressions, enabling efficient text processing and validation.
|
||||
|
||||
## 1. Introduction to Regular Expressions
|
||||
A regular expression is a sequence of characters defining a search pattern. Common use cases include validating input, searching within text, and extracting
|
||||
specific patterns.
|
||||
|
||||
## 2. Basic Syntax
|
||||
Literal Characters: Match exact characters (e.g., abc matches "abc").
|
||||
Metacharacters: Special characters like ., *, ?, +, ^, $, [ ], and | used to build patterns.
|
||||
|
||||
**Common Metacharacters:**
|
||||
|
||||
* .: Any character except newline.
|
||||
* ^: Start of the string.
|
||||
* $: End of the string.
|
||||
* *: 0 or more repetitions.
|
||||
* +: 1 or more repetitions.
|
||||
* ?: 0 or 1 repetition.
|
||||
* []: Any one character inside brackets (e.g., [a-z]).
|
||||
* |: Either the pattern before or after.
|
||||
|
||||
## 3. Using the re Module
|
||||
|
||||
**Key functions in the re module:**
|
||||
|
||||
* re.match(): Checks for a match at the beginning of the string.
|
||||
* re.search(): Searches for a match anywhere in the string.
|
||||
* re.findall(): Returns a list of all matches.
|
||||
* re.sub(): Replaces matches with a specified string.
|
||||
|
||||
Examples:
|
||||
```bash
|
||||
import re
|
||||
|
||||
# Match at the beginning
|
||||
print(re.match(r'\d+', '123abc').group()) # Output: 123
|
||||
|
||||
# Search anywhere
|
||||
print(re.search(r'\d+', 'abc123').group()) # Output: 123
|
||||
|
||||
# Find all matches
|
||||
print(re.findall(r'\d+', 'abc123def456')) # Output: ['123', '456']
|
||||
|
||||
# Substitute matches
|
||||
print(re.sub(r'\d+', '#', 'abc123def456')) # Output: abc#def#
|
||||
```
|
||||
|
||||
## 4. Compiling Regular Expressions
|
||||
Compiling regular expressions improves performance for repeated use.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import re
|
||||
|
||||
pattern = re.compile(r'\d+')
|
||||
print(pattern.match('123abc').group()) # Output: 123
|
||||
print(pattern.search('abc123').group()) # Output: 123
|
||||
print(pattern.findall('abc123def456')) # Output: ['123', '456']
|
||||
```
|
||||
|
||||
## 5. Groups and Capturing
|
||||
Parentheses () group and capture parts of the match.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
import re
|
||||
|
||||
match = re.match(r'(\d{3})-(\d{2})-(\d{4})', '123-45-6789')
|
||||
if match:
|
||||
print(match.group()) # Output: 123-45-6789
|
||||
print(match.group(1)) # Output: 123
|
||||
print(match.group(2)) # Output: 45
|
||||
print(match.group(3)) # Output: 6789
|
||||
```
|
||||
|
||||
## 6. Special Sequences
|
||||
Special sequences are shortcuts for common patterns:
|
||||
|
||||
* \d: Any digit.
|
||||
* \D: Any non-digit.
|
||||
* \w: Any alphanumeric character.
|
||||
* \W: Any non-alphanumeric character.
|
||||
* \s: Any whitespace character.
|
||||
* \S: Any non-whitespace character.
|
||||
Example:
|
||||
```bash
|
||||
import re
|
||||
|
||||
print(re.search(r'\w+@\w+\.\w+', 'Contact: support@example.com').group()) # Output: support@example.com
|
||||
```
|
||||
|
||||
## Summary
|
||||
Regular expressions are a versatile tool for text processing in Python. The re module offers powerful functions and metacharacters for pattern matching,
|
||||
searching, and manipulation, making it an essential skill for handling complex text processing tasks.
|
|
@ -0,0 +1,171 @@
|
|||
# Regression
|
||||
|
||||
|
||||
* Regression is a supervised machine learning technique which is used to predict continuous values.
|
||||
|
||||
|
||||
> Now, Supervised learning is a category of machine learning that uses labeled datasets to train algorithms to predict outcomes and recognize patterns.
|
||||
|
||||
* Regression is a statistical method used to model the relationship between a dependent variable (often denoted as 'y') and one or more independent variables (often denoted as 'x'). The goal of regression analysis is to understand how the dependent variable changes as the independent variables change.
|
||||
# Types Of Regression
|
||||
|
||||
1. Linear Regression
|
||||
2. Polynomial Regression
|
||||
3. Stepwise Regression
|
||||
4. Decision Tree Regression
|
||||
5. Random Forest Regression
|
||||
6. Ridge Regression
|
||||
7. Lasso Regression
|
||||
8. ElasticNet Regression
|
||||
9. Bayesian Linear Regression
|
||||
10. Support Vector Regression
|
||||
|
||||
But, we'll first start with Linear Regression
|
||||
# Linear Regression
|
||||
|
||||
* Linear regression is a fundamental statistical method used to model the relationship between a dependent variable (often denoted as
|
||||
𝑌) and one or more independent variables (often denoted as
|
||||
𝑋). The relationship is assumed to be linear, meaning that changes in the independent variables are associated with changes in the dependent variable in a straight-line fashion.
|
||||
|
||||
The basic form of linear regression for a single independent variable is:
|
||||
|
||||
**𝑌=𝛽0+𝛽1𝑋+𝜖**
|
||||
|
||||
Where:
|
||||
|
||||
* Y is the dependent variable.
|
||||
* X is the independent variable.
|
||||
* 𝛽0 is the intercept, representing the value of Y when X is zero
|
||||
* 𝛽1 is the slope coefficient, representing the change in Y for a one-unit change in X
|
||||
* ϵ is the error term, representing the variability in Y that is not explained by the linear relationship with X.
|
||||
|
||||
# Basic Code of Linear Regression
|
||||
|
||||
* This line imports the numpy library, which is widely used for numerical operations in Python. We use np as an alias for numpy, making it easier to reference functions and objects from the library.
|
||||
```
|
||||
import numpy as np
|
||||
```
|
||||
|
||||
* This line imports the LinearRegression class from the linear_model module of the scikit-learn library.scikit-learn is a powerful library for machine learning tasks in Python, and LinearRegression is a class provided by it for linear regression.
|
||||
```
|
||||
from sklearn.linear_model import LinearRegression
|
||||
```
|
||||
* This line creates a NumPy array X containing the independent variable values. In this example, we have a simple one-dimensional array representing the independent variable. The reshape(-1, 1) method reshapes the array into a column vector, necessary for use with scikit-learn
|
||||
|
||||
```
|
||||
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
|
||||
```
|
||||
* This line creates a NumPy array Y containing the corresponding dependent variable values. These are the observed values of the dependent variable corresponding to the independent variable values in X.
|
||||
```
|
||||
Y = np.array([2, 4, 5, 8, 5])
|
||||
```
|
||||
|
||||
* This line creates an instance of the LinearRegression class, which represents the linear regression model. We'll use this object to train the model and make predictions.
|
||||
```
|
||||
model = LinearRegression()
|
||||
```
|
||||
|
||||
* This line fits the linear regression model to the data. The fit() method takes two arguments: the independent variable (X) and the dependent variable (Y). This method estimates the coefficients of the linear regression equation that best fit the given data.
|
||||
```
|
||||
model.fit(X, Y)
|
||||
```
|
||||
* These lines print out the intercept (beta_0) and coefficient (beta_1) of the linear regression model. model.intercept_ gives the intercept value, and model.coef_ gives an array of coefficients, where model.coef_[0] corresponds to the coefficient of the first independent variable (in this case, there's only one).
|
||||
```
|
||||
print("Intercept:", model.intercept_)
|
||||
print("Coefficient:", model.coef_[0])
|
||||
```
|
||||
|
||||
* These lines demonstrate how to use the trained model to make predictions for new data.
|
||||
* We create a new NumPy array new_data containing the values of the independent variable for which we want to predict the dependent variable values.
|
||||
* We then use the predict() method of the model to obtain the predictions for these new data points. Finally, we print out the predicted values.
|
||||
```
|
||||
new_data = np.array([[6], [7]])
|
||||
predictions = model.predict(new_data)
|
||||
print("Predictions:", predictions)
|
||||
```
|
||||
# Assumptions of Linear Regression
|
||||
|
||||
# Linearity:
|
||||
|
||||
* To assess the linearity assumption, we can visually inspect a scatter plot of the observed values versus the predicted values.
|
||||
* If the relationship between them appears linear, it suggests that the linearity assumption is reasonable.
|
||||
```
|
||||
import matplotlib.pyplot as plt
|
||||
predictions = model.predict(X)
|
||||
plt.scatter(predictions,Y)
|
||||
plt.xlabel("Predicted Values")
|
||||
plt.ylabel("Observed Values")
|
||||
plt.title("Linearity Check: Observed vs Predicted")
|
||||
plt.show()
|
||||
```
|
||||
# Homoscedasticity:
|
||||
* Homoscedasticity refers to the constant variance of the residuals across all levels of the independent variable(s). We can visually inspect a plot of residuals versus predicted values to check for homoscedasticity.
|
||||
```
|
||||
residuals = Y - predictions
|
||||
plt.scatter(predictions, residuals)
|
||||
plt.xlabel("Predicted Values")
|
||||
plt.ylabel("Residuals")
|
||||
plt.title("Homoscedasticity Check: Residuals vs Predicted Values")
|
||||
plt.axhline(y=0, color='red', linestyle='--') # Add horizontal line at y=0
|
||||
plt.show()
|
||||
|
||||
```
|
||||
# Normality of Residuals:
|
||||
* To assess the normality of residuals, we can visually inspect a histogram or a Q-Q plot of the residuals.
|
||||
```
|
||||
import seaborn as sns
|
||||
|
||||
sns.histplot(residuals, kde=True)
|
||||
plt.xlabel("Residuals")
|
||||
plt.ylabel("Frequency")
|
||||
plt.title("Normality of Residuals: Histogram")
|
||||
plt.show()
|
||||
|
||||
import scipy.stats as stats
|
||||
|
||||
stats.probplot(residuals, dist="norm", plot=plt)
|
||||
plt.title("Normal Q-Q Plot")
|
||||
plt.show()
|
||||
|
||||
```
|
||||
# Metrics for Regression
|
||||
|
||||
|
||||
# Mean Absolute Error (MAE)
|
||||
|
||||
* MAE measures the average magnitude of the errors in a set of predictions, without considering their direction. It is the average of the absolute differences between predicted and actual values.
|
||||
```
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
mae = mean_absolute_error(Y, predictions)
|
||||
print(f"Mean Absolute Error (MAE): {mae}")
|
||||
|
||||
```
|
||||
# Mean Squared Error (MSE)
|
||||
|
||||
* MSE measures the average of the squares of the errors. It gives more weight to larger errors, making it sensitive to outliers.
|
||||
```
|
||||
from sklearn.metrics import mean_squared_error
|
||||
|
||||
mse = mean_squared_error(Y, predictions)
|
||||
print(f"Mean Squared Error (MSE): {mse}")
|
||||
```
|
||||
# Root Mean Squared Error (RMSE)
|
||||
* RMSE is the square root of the MSE. It provides an error metric that is in the same units as the dependent variable, making it more interpretable.
|
||||
```
|
||||
rmse = np.sqrt(mse)
|
||||
print(f"Root Mean Squared Error (RMSE): {rmse}")
|
||||
|
||||
```
|
||||
# R-squared (Coefficient of Determination)
|
||||
* R-squared measures the proportion of the variance in the dependent variable that is predictable from the independent variables. It ranges from 0 to 1, where 1 indicates a perfect fit.
|
||||
```
|
||||
from sklearn.metrics import r2_score
|
||||
|
||||
r2 = r2_score(Y, predictions)
|
||||
print(f"R-squared (R^2): {r2}")
|
||||
```
|
||||
|
||||
> In this tutorial, The sample dataset is there for learning purpose only
|
||||
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
# List of sections
|
||||
|
||||
- [Section title](filename.md)
|
||||
- [Regression in Machine Learning](Regression.md)
|
||||
- [Confusion Matrix](confusion-matrix.md)
|
||||
- [Support Vector Machine Algorithm](support-vector-machine.md)
|
||||
|
||||
|
|
|
@ -0,0 +1,84 @@
|
|||
# Rock Paper Scissors Game
|
||||
|
||||
This is a simple implementation of the classic rock-paper-scissors game in Python.
|
||||
|
||||
## Code Explanation:
|
||||
|
||||
In this section, we import the required libraries (`tkinter` for GUI and `random` for generating computer choices) and define two functions:
|
||||
|
||||
- `determine_winner(user_choice, computer_choice)`:
|
||||
- This function determines the winner of the game based on the choices made by the user and the computer.
|
||||
- It returns a tuple containing the result of the game and the computer's choice.
|
||||
|
||||
- `play_game()`:
|
||||
- This function handles the gameplay logic.
|
||||
- It gets the user's choice from the radio buttons, generates a random choice for the computer, determines the winner using the `determine_winner()` function, and updates the result and computer pick labels accordingly.
|
||||
|
||||
### Imports and Function Definitions:
|
||||
```python
|
||||
import tkinter as tk
|
||||
import random
|
||||
|
||||
def determine_winner(user_choice, computer_choice):
|
||||
"""Determine the winner of the game."""
|
||||
if user_choice == computer_choice:
|
||||
return "It's a tie!", computer_choice
|
||||
elif (user_choice == "rock" and computer_choice == "scissors") or \
|
||||
(user_choice == "paper" and computer_choice == "rock") or \
|
||||
(user_choice == "scissors" and computer_choice == "paper"):
|
||||
return "You win!", computer_choice
|
||||
else:
|
||||
return "Computer wins!", computer_choice
|
||||
|
||||
def play_game():
|
||||
"""Play the game and display the result."""
|
||||
user_choice = user_var.get()
|
||||
computer_choice = random.choice(["rock", "paper", "scissors"])
|
||||
result, computer_pick = determine_winner(user_choice, computer_choice)
|
||||
result_label.config(text=result)
|
||||
computer_label.config(text=f"Computer picked: {computer_pick}")
|
||||
```
|
||||
### GUI Setup:
|
||||
```python
|
||||
# Create main window
|
||||
root = tk.Tk()
|
||||
root.title("Rock Paper Scissors")
|
||||
|
||||
# User choice options
|
||||
user_var = tk.StringVar()
|
||||
user_var.set("rock") # Default choice
|
||||
choices = ["rock", "paper", "scissors"]
|
||||
for choice in choices:
|
||||
rb = tk.Radiobutton(root, text=choice, variable=user_var, value=choice)
|
||||
rb.pack()
|
||||
```
|
||||
- Here, we create the main window for the game using `tkinter.Tk()`. We set the title to "Rock Paper Scissors".
|
||||
- We define a `StringVar` to store the user's choice and set the default choice to "rock".
|
||||
- We create radio buttons for the user to choose from ("rock", "paper", "scissors") and pack them into the main window.
|
||||
```
|
||||
```
|
||||
### Play Button and Result Labels:
|
||||
```python
|
||||
# Play button
|
||||
play_button = tk.Button(root, text="Play", command=play_game)
|
||||
play_button.pack()
|
||||
|
||||
# Result label
|
||||
result_label = tk.Label(root, text="", font=("Helvetica", 16))
|
||||
result_label.pack()
|
||||
|
||||
# Computer pick label
|
||||
computer_label = tk.Label(root, text="", font=("Helvetica", 12))
|
||||
computer_label.pack()
|
||||
```
|
||||
- We create a "Play" button that triggers the `play_game()` function when clicked, using `tkinter.Button`.
|
||||
- We create two labels to display the result of the game (`result_label`) and the computer's choice (`computer_label`). Both labels initially display no text and are packed into the main window.
|
||||
```
|
||||
```
|
||||
|
||||
### Mainloop:
|
||||
```python
|
||||
root.mainloop()
|
||||
```
|
||||
- Finally, we start the Tkinter event loop using `root.mainloop()`, which keeps the GUI window open and responsive until the user closes it.
|
||||
-
|
|
@ -0,0 +1,36 @@
|
|||
## Dice Roller
|
||||
|
||||
The aim of this project is to replicate a dice and generate a random number from the numbers 1 to 6.
|
||||
|
||||
For this first we will import the random library which will help make random choices.
|
||||
|
||||
```
|
||||
import random
|
||||
def dice():
|
||||
dice_no = random.choice([1,2,3,4,5,6])
|
||||
return "You got " + str(dice_no)
|
||||
```
|
||||
|
||||
The above snippet of code defines a function called `dice()` which makes the random choice and returns the number that is generated.
|
||||
|
||||
```
|
||||
def roll_dice():
|
||||
print("Hey Guys, you will now roll a single dice using Python!")
|
||||
while True:
|
||||
start=input("Type \'k\' to roll the dice: ").lower()
|
||||
if start != 'k':
|
||||
print("Invalid input. Please try again.")
|
||||
continue
|
||||
print(dice())
|
||||
roll_again = input("Do you want to reroll? (Yes/No): ").lower()
|
||||
if roll_again != 'yes':
|
||||
break
|
||||
print("Thanks for rolling the dice.")
|
||||
roll_dice()
|
||||
```
|
||||
|
||||
The above code defines a function called `roll_dice()` which interacts with the user.
|
||||
|
||||
It prompts the user to give an input and if the input is `k`,the code proceeds further to generate a random number or gives the message of invalid input and asks the user to try again.
|
||||
|
||||
After the dice has been rolled once, the function asks the user whether they want a reroll in the form of a `yes` or `no` question. The dice is rolled again if the user gives `yes` as an answer and exits the code if the user replies with anything other than yes.
|
|
@ -1,3 +1,5 @@
|
|||
# List of sections
|
||||
|
||||
- [Section title](filename.md)
|
||||
- [Dice Roller](dice_roller.md)
|
||||
- [Rock Paper Scissors Game](Rock_Paper_Scissors_Game.md)
|
||||
- [Path Finder](path-finder.md)
|
||||
|
|
|
@ -0,0 +1,120 @@
|
|||
# Path Finder
|
||||
This Python script uses the curses library to visualize the process of finding a path through a maze in real-time within a terminal window. The program represents the maze as a list of lists, where each list represents a row in the maze, and each string element in the lists represents a cell in the maze. The maze includes walls (#), a start point (O), and an end point (X), with empty spaces ( ) that can be traversed.
|
||||
## The script includes the following main components:
|
||||
- Visualization Functions: <br>
|
||||
print_maze(maze, stdscr, path=[]): This function is used to display the maze in the terminal. It utilizes color pairs to distinguish between the maze walls, the path, and unexplored spaces. The current path being explored is displayed with a different color to make it stand out.
|
||||
|
||||
- Utility Functions: <br>
|
||||
find_start(maze, start): This function searches the maze for the starting point (marked as O) and returns its position as a tuple (row, col). <br>
|
||||
find_neighbors(maze, row, col): This function identifies the valid adjacent cells (up, down, left, right) that can be moved to from the current position,
|
||||
ignoring any walls or out-of-bound positions.
|
||||
|
||||
- Pathfinding Logic: <br>
|
||||
find_path(maze, stdscr): This function implements a Breadth-First Search (BFS) algorithm to find a path from the start point to the end point (X). It uses a
|
||||
queue to explore each possible path sequentially. As it explores the maze, it updates the display in real-time, allowing the viewer to follow the progress
|
||||
visually. Each visited position is marked and not revisited, ensuring the algorithm efficiently covers all possible paths without repetition.
|
||||
|
||||
Overall, the script demonstrates an effective use of the curses library to create a dynamic visual representation of the BFS algorithm solving a maze, providing both an educational tool for understanding pathfinding and an example of real-time data visualization in a terminal.
|
||||
|
||||
#### Below is the code of the path finder
|
||||
|
||||
|
||||
```python
|
||||
import curses
|
||||
from curses import wrapper
|
||||
import queue
|
||||
import time
|
||||
|
||||
# Define the structure of the maze as a list of lists where each inner list represents a row.
|
||||
maze = [
|
||||
["#", "O", "#", "#", "#", "#", "#", "#", "#"],
|
||||
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
|
||||
["#", " ", "#", "#", " ", "#", "#", " ", "#"],
|
||||
["#", " ", "#", " ", " ", " ", "#", " ", "#"],
|
||||
["#", " ", "#", " ", "#", " ", "#", " ", "#"],
|
||||
["#", " ", "#", " ", "#", " ", "#", " ", "#"],
|
||||
["#", " ", "#", " ", "#", " ", "#", "#", "#"],
|
||||
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
|
||||
["#", "#", "#", "#", "#", "#", "#", "X", "#"]
|
||||
]
|
||||
|
||||
# Function to print the current state of the maze in the terminal.
|
||||
def print_maze(maze, stdscr, path=[]):
|
||||
BLUE = curses.color_pair(1) # Color pair for walls and free paths
|
||||
RED = curses.color_pair(2) # Color pair for the current path
|
||||
|
||||
for i, row in enumerate(maze):
|
||||
for j, value in enumerate(row):
|
||||
if (i, j) in path:
|
||||
stdscr.addstr(i, j*2, "X", RED) # Print path character with red color
|
||||
else:
|
||||
stdscr.addstr(i, j*2, value, BLUE) # Print walls and free paths with blue color
|
||||
|
||||
# Function to locate the starting point (marked 'O') in the maze.
|
||||
def find_start(maze, start):
|
||||
for i, row in enumerate(maze):
|
||||
for j, value in enumerate(row):
|
||||
if value == start:
|
||||
return i, j
|
||||
return None
|
||||
|
||||
# Function to find a path from start ('O') to end ('X') using BFS.
|
||||
def find_path(maze, stdscr):
|
||||
start = "O"
|
||||
end = "X"
|
||||
start_pos = find_start(maze, start) # Get the start position
|
||||
|
||||
q = queue.Queue()
|
||||
q.put((start_pos, [start_pos])) # Initialize the queue with the start position
|
||||
|
||||
visited = set() # Set to keep track of visited positions
|
||||
|
||||
while not q.empty():
|
||||
current_pos, path = q.get() # Get the current position and path
|
||||
row, col = current_pos
|
||||
|
||||
stdscr.clear() # Clear the screen
|
||||
print_maze(maze, stdscr, path) # Print the current state of the maze
|
||||
time.sleep(0.2) # Delay for visibility
|
||||
stdscr.refresh() # Refresh the screen
|
||||
|
||||
if maze[row][col] == end: # Check if the current position is the end
|
||||
return path # Return the path if end is reached
|
||||
|
||||
# Get neighbors (up, down, left, right) that are not walls
|
||||
neighbors = find_neighbors(maze, row, col)
|
||||
for neighbor in neighbors:
|
||||
if neighbor not in visited:
|
||||
r, c = neighbor
|
||||
if maze[r][c] != "#":
|
||||
new_path = path + [neighbor]
|
||||
q.put((neighbor, new_path))
|
||||
visited.add(neighbor)
|
||||
|
||||
# Function to find the valid neighboring cells (not walls or out of bounds).
|
||||
def find_neighbors(maze, row, col):
|
||||
neighbors = []
|
||||
if row > 0: # UP
|
||||
neighbors.append((row - 1, col))
|
||||
if row + 1 < len(maze): # DOWN
|
||||
neighbors.append((row + 1, col))
|
||||
if col > 0: # LEFT
|
||||
neighbors.append((row, col - 1))
|
||||
if col + 1 < len(maze[0]): # RIGHT
|
||||
neighbors.append((row, col + 1))
|
||||
return neighbors
|
||||
|
||||
# Main function to setup curses and run the pathfinding algorithm.
|
||||
def main(stdscr):
|
||||
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK) # Initialize color pair for blue
|
||||
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) # Initialize color pair for red
|
||||
|
||||
find_path(maze, stdscr) # Find the path using BFS
|
||||
stdscr.getch() # Wait for a key press before exiting
|
||||
|
||||
wrapper(main) # Use the wrapper to initialize and finalize curses automatically.
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
# List of sections
|
||||
|
||||
- [Section title](filename.md)
|
||||
- [Introduction](introduction.md)
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
# Introduction
|
||||
|
||||
## What is NumPy?
|
||||
|
||||
NumPy is a powerful array-processing library in Python, essential for scientific computing. It provides efficient data structures and tools for working with multidimensional arrays.
|
||||
|
||||
## Key Features
|
||||
|
||||
1. **Efficient Arrays:** NumPy offers high-performance N-dimensional array objects for swift data manipulation.
|
||||
2. **Broadcasting:** Advanced broadcasting enables seamless element-wise operations on arrays of varying shapes.
|
||||
3. **Interoperability:** NumPy seamlessly integrates with C, C++, and Fortran, enhancing performance and versatility.
|
||||
4. **Mathematical Tools:** Comprehensive support for linear algebra, Fourier transforms, and random number generation.
|
||||
|
||||
## Installation
|
||||
|
||||
Ensure Python is installed in your system. If not you can install it from here([official Python website](https://www.python.org/)),then install NumPy via:
|
||||
|
||||
```bash
|
||||
pip install numpy
|
||||
```
|
||||
|
||||
## Importing NumPy
|
||||
|
||||
To access NumPy functions, import it with the alias `np`.
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
```
|
||||
|
||||
Using `np` as an alias enhances code readability and is a widely adopted convention.
|
|
@ -0,0 +1,63 @@
|
|||
# Pandas DataFrame
|
||||
|
||||
The Pandas DataFrame is a two-dimensional, size-mutable, and possibly heterogeneous tabular data format with labelled axes. A data frame is a two-dimensional data structure in which the data can be organised in rows and columns. Pandas DataFrames are comprised of three main components: data, rows, and columns.
|
||||
|
||||
In the real world, Pandas DataFrames are formed by importing datasets from existing storage, which can be a Excel file, a SQL database or CSV file. Pandas DataFrames may be constructed from lists, dictionaries, or lists of dictionaries, etc.
|
||||
|
||||
|
||||
Features of Pandas `DataFrame`:
|
||||
|
||||
- **Size mutable**: DataFrames are mutable in size, meaning that new rows and columns can be added or removed as needed.
|
||||
- **Labeled axes**: DataFrames have labeled axes, which makes it easy to keep track of the data.
|
||||
- **Arithmetic operations**: DataFrames support arithmetic operations on rows and columns.
|
||||
- **High performance**: DataFrames are highly performant, making them ideal for working with large datasets.
|
||||
|
||||
|
||||
### Installation of libraries
|
||||
|
||||
`pip install pandas` <br/>
|
||||
`pip install xlrd`
|
||||
|
||||
- **Note**: The `xlrd` library is used for Excel operations.
|
||||
|
||||
Example for reading data from an Excel File:
|
||||
|
||||
```python
|
||||
import pandas as pd
|
||||
|
||||
l = pd.read_excel('example.xlsx')
|
||||
d = pd.DataFrame(l)
|
||||
print(d)
|
||||
```
|
||||
Output:
|
||||
```python
|
||||
Name Age
|
||||
0 John 12
|
||||
```
|
||||
|
||||
|
||||
Example for Inserting Data into Excel File:
|
||||
|
||||
```python
|
||||
import pandas as pd
|
||||
|
||||
l = pd.read_excel('file_name.xlsx')
|
||||
d = {'Name': ['Bob', 'John'], 'Age': [12, 28]}
|
||||
d = pd.DataFrame(d)
|
||||
L = pd.concat([l, d], ignore_index = True)
|
||||
L.to_excel('file_name.xlsx', index = False)
|
||||
print(L)
|
||||
```
|
||||
|
||||
Output:
|
||||
```python
|
||||
Name Age
|
||||
0 Bob 12
|
||||
1 John 28
|
||||
```
|
||||
|
||||
### Usage of Pandas DataFrame:
|
||||
|
||||
- Can be used to store and analyze financial data, such as stock prices, trading data, and economic data.
|
||||
- Can be used to store and analyze sensor data, such as data from temperature sensors, motion sensors, and GPS sensors.
|
||||
- Can be used to store and analyze log data, such as web server logs, application logs, and system logs
|
|
@ -1,3 +1,4 @@
|
|||
# List of sections
|
||||
|
||||
- [Pandas Series Vs NumPy ndarray](pandas_series_vs_numpy_ndarray.md)
|
||||
- [Excel using Pandas DataFrame](excel_with_pandas.md)
|
||||
|
|
Ładowanie…
Reference in New Issue