Monday, 17 March 2025

Python Coding challenge - Day 410| What is the output of the following Python Code?

 


Code Explanation:

1. Importing Required Libraries

from scipy.linalg import det

import numpy as np

from scipy.linalg import det → This imports the det() function from the scipy.linalg module. The det() function is used to calculate the determinant of a matrix.

import numpy as np → This imports the numpy library and gives it the alias np. NumPy is a powerful library for numerical operations and matrix manipulations.


2. Creating the Matrix

matrix = np.array([[4, 2], [3, 1]])

np.array() → This function is used to create a NumPy array. In this case, it creates a 2x2 matrix using the nested lists [[4, 2], [3, 1]].

The matrix looks like this:

3. Calculating the Determinant

print(det(matrix))

det(matrix) → This calls the det() function to calculate the determinant of the matrix.

Determinant Formula for a 2x2 Matrix:

det(A)=ad−bc

Where the matrix is:

det(A)=(4⋅1)−(2⋅3)=4−6=−2

print() → Displays the result of the determinant on the console.

Final Output

-2.0

Python Coding challenge - Day 409| What is the output of the following Python Code?

 

Code Explanation:

1. Importing TensorFlow

import tensorflow as tf

This line imports the TensorFlow library, a popular framework for machine learning and deep learning tasks.

tf is the alias used to refer to TensorFlow functions and modules.

2. Creating a Tensor

x = tf.constant([-1.0, 0.0, 1.0])

tf.constant() creates an immutable tensor (a multi-dimensional array) with the values [-1.0, 0.0, 1.0].

Tensors are similar to NumPy arrays and are the core data structure in TensorFlow.

3. Applying the Sigmoid Function

sigmoid = tf.nn.sigmoid(x)

tf.nn.sigmoid() applies the sigmoid activation function element-wise to the input tensor.


It squashes the input values to a range between 0 and 1, making it useful for binary classification tasks.

Applying to each input value:

4. Printing the Result

print(sigmoid)

This prints the output tensor containing the sigmoid values for each input.

The expected output will be:

[0.26894143 0.5 0.7310586]

TensorFlow may display it with additional information like data type (dtype) depending on the environment.

 Final Output

 [0.27, 0.5, 0.73]

Python Coding challenge - Day 408| What is the output of the following Python Code?


 

1. Importing the Required Library

from sklearn.metrics import accuracy_score

sklearn.metrics: This is a module in the Scikit-Learn library that provides functions to evaluate the performance of machine learning models.

accuracy_score(): This function calculates the accuracy of a model's predictions.

It compares the predicted values to the actual values and computes the accuracy using the formula:

Accuracy=Number of Correct Predictions/Total Number of Predictions

2. Defining the Actual Values (True Labels)

y_true = [0, 1, 1, 0]

y_true represents the actual values or ground truth labels.

In this case, there are 4 data points labeled as 0 or 1.

0: Usually represents Negative (e.g., No disease, No spam, etc.)

1: Represents Positive (e.g., Disease present, Spam detected, etc.)

3. Defining the Predicted Values

y_pred = [0, 1, 0, 0]

y_pred contains the predictions made by a machine learning model for the same 4 data points.

Each value is either 0 or 1, indicating the predicted class.

4. Calculating the Accuracy Score

print(accuracy_score(y_true, y_pred))

The accuracy_score() function takes two inputs:

y_true → Actual values

y_pred → Predicted values


Final Output:

0.75

Python Powerhouse: A Step-by-Step Guide for All Programmers

 


Python Powerhouse: A Step-by-Step Guide for All Programmers

Python has become one of the most powerful and widely used programming languages in the world. Whether you're a beginner taking your first steps in coding or an experienced programmer looking to refine your skills, Python Powerhouse: A Step-by-Step Guide for All Programmers is designed to help you master Python with a structured and hands-on approach. This book serves as a comprehensive guide, covering fundamental to advanced concepts with practical applications and real-world projects.

Why Learn Python?

Python is known for its simple syntax, versatility, and strong community support. It is used in various fields, including web development, data science, artificial intelligence, automation, game development, and more. With Python, programmers can create powerful applications with minimal code, making it a go-to language for both beginners and experts.

Book Overview

This book is structured to guide programmers through every stage of Python development, from writing basic scripts to working on complex projects. It emphasizes problem-solving techniques and best coding practices while providing real-world examples and hands-on projects.

Key Topics Covered:

1. Python Fundamentals: Building a Strong Foundation

  • Understanding Python syntax and structure

  • Variables, data types, and type conversion

  • Operators and expressions

  • Taking user input and displaying output

  • Writing and running Python scripts

2. Control Flow: Mastering Decision Making and Loops

  • Conditional statements (if, elif, else)

  • Looping constructs (for and while loops)

  • Nested loops and conditional expressions

  • Using break, continue, and pass statements

  • List comprehensions for efficient coding

3. Functions and Modular Programming

  • Defining and calling functions

  • Understanding parameters, arguments, and return values

  • Recursion and lambda functions

  • Organizing code with modules and packages

  • Working with built-in Python functions

4. Object-Oriented Programming (OOP) in Python

  • Introduction to classes and objects

  • Implementing inheritance and polymorphism

  • Encapsulation and abstraction

  • Operator overloading and method overriding

  • Writing maintainable and scalable OOP code

5. Working with Data: Files, JSON, and Databases

  • Reading and writing text files

  • Working with CSV and JSON formats

  • Interacting with databases using SQLite

  • Introduction to SQL queries in Python

  • Handling large datasets efficiently

6. Error Handling and Debugging Techniques

  • Understanding common programming errors

  • Using try, except, finally for error handling

  • Raising and handling custom exceptions

  • Logging and debugging Python applications

  • Best practices for writing bug-free code

7. Python for Web Development

  • Introduction to web frameworks: Flask and Django

  • Creating and handling HTTP requests

  • Building RESTful APIs with Python

  • Connecting Python with front-end technologies

  • Deploying Python web applications

8. Data Science and Machine Learning with Python

  • Introduction to data science and analytics

  • Using NumPy, pandas, and Matplotlib for data manipulation and visualization

  • Basic concepts of machine learning with Scikit-learn

  • Training and evaluating models with real-world datasets

  • Exploring deep learning frameworks like TensorFlow and PyTorch

9. Automating Tasks with Python

  • Writing scripts to automate repetitive tasks

  • Web scraping with BeautifulSoup and Selenium

  • Automating email and file management

  • Working with APIs and third-party services

  • Scheduling automation tasks with Python

10. Advanced Python Programming

  • Working with multi-threading and concurrency

  • Functional programming with Python

  • Network programming and socket communication

  • Exploring Python's standard library and advanced features

  • Writing efficient, optimized, and scalable Python applications

Hands-On Projects

Throughout the book, readers will work on real-world projects that reinforce their learning, including:

  • Building a To-Do List Application using Tkinter for GUI programming

  • Developing a Weather App using APIs and data visualization

  • Creating a Web Scraper to extract data from websites

  • Building a Machine Learning Model for predictive analysis

  • Automating File Management with Python scripting

Who Should Read This Book?

  • Beginners looking for a structured introduction to Python.

  • Intermediate programmers who want to enhance their Python skills.

  • Professionals and developers looking to apply Python in real-world projects.

  • Data analysts and engineers who need a strong foundation in Python programming.

  • Students and educators interested in learning and teaching Python effectively.

Why Choose This Book?

  • Step-by-Step Learning: A clear and progressive approach to mastering Python.

  • Hands-On Projects: Reinforce concepts with real-world applications.

  • Comprehensive Coverage: Covers fundamental to advanced Python topics.

  • Industry-Relevant Skills: Learn how Python is used in web development, automation, data science, and more.

  • Best Practices: Focuses on clean, efficient, and maintainable code.


Kindle : Python Powerhouse: A Step-by-Step Guide for All Programmers

Hard Copy : Python Powerhouse: A Step-by-Step Guide for All Programmers

Conclusion

Python Powerhouse: A Step-by-Step Guide for All Programmers is your go-to resource for mastering Python programming. Whether you're a novice coder or an experienced developer, this book will equip you with the skills needed to excel in Python and apply it in diverse domains.

Learn Python the Easy Way: A Practical QuickStudy for Absolute Beginners


 


Learn Python the Easy Way: A Practical QuickStudy for Absolute Beginners

Python is one of the most beginner-friendly programming languages, widely used in data science, web development, automation, and more. The book "Learn Python the Easy Way: A Practical QuickStudy for Absolute Beginners" is designed to provide an easy-to-follow introduction to Python, making it accessible for complete beginners with no prior programming experience.

Why Learn Python?

Python is known for its simple syntax, versatility, and strong community support. It is used in various fields, including artificial intelligence, machine learning, cybersecurity, and scientific computing. This book serves as an ideal guide for those who want to start their programming journey without feeling overwhelmed.

Book Overview

This book takes a hands-on, practical approach to learning Python, ensuring that readers can apply their knowledge immediately. It covers the fundamentals of Python, problem-solving techniques, and real-world applications, making it perfect for beginners looking to build a strong foundation in coding.

Key Topics Covered:

1. Introduction to Python and Setting Up Your Environment

  • What is Python, and why should you learn it?

  • Differences between Python 2 and Python 3

  • Installing Python and setting up an IDE (PyCharm, VS Code, or Jupyter Notebook)

  • Writing and running your first Python script

  • Understanding the Python interactive shell

2. Basic Python Syntax and Data Types

  • Understanding variables, data types, and operators

  • Working with strings, numbers, and Boolean values

  • Type conversions and formatting output

  • Using lists, tuples, sets, and dictionaries for data storage

  • Indexing and slicing sequences

3. Control Flow: Making Decisions with Python

  • Writing conditional statements (if, elif, else)

  • Using loops (for, while) to automate repetitive tasks

  • Implementing list comprehensions for efficient coding

  • Using break, continue, and pass statements

  • Nested loops and conditional expressions

4. Functions and Modular Programming

  • Defining and calling functions

  • Understanding arguments, return values, and scope

  • Writing reusable and modular code with Python functions

  • Lambda functions for concise expressions

  • Using built-in functions and creating custom modules

  • Importing and using external modules

5. Object-Oriented Programming (OOP) in Python

  • Introduction to classes and objects

  • Implementing inheritance and polymorphism

  • Understanding encapsulation and abstraction

  • Working with constructors and destructors

  • Operator overloading and method overriding

  • Best practices for writing OOP code in Python

6. Working with Files and Data Handling

  • Reading and writing files using Python (open(), read(), write())

  • Handling CSV and JSON data formats

  • Working with databases using SQLite and SQL queries in Python

  • File handling best practices (error handling, working with large files)

  • Parsing and extracting data from text files

7. Error Handling and Debugging

  • Common programming errors and how to avoid them

  • Using try, except, finally for error handling

  • Raising and handling custom exceptions

  • Using logging for debugging applications

  • Debugging Python scripts efficiently with breakpoints and IDE tools

8. Introduction to Libraries and Real-World Applications

  • Exploring popular Python libraries like NumPy, pandas, and Matplotlib

  • Automating tasks with Python scripts (batch file processing, web scraping)

  • Building simple web applications with Flask and Django

  • Data visualization using Matplotlib and Seaborn

  • Introduction to machine learning with Scikit-learn

  • Working with APIs and integrating external services

Why Choose This Book?

  • Beginner-Friendly Approach: Designed specifically for absolute beginners with step-by-step explanations.

  • Hands-On Learning: Each concept is reinforced with practical exercises and real-world applications.

  • QuickStudy Format: Focuses on essential concepts without unnecessary complexity.

  • Practical Applications: Learn how to apply Python in real-world scenarios, from automation to data analysis.

  • Project-Based Learning: Develop real projects to solidify your skills.

Who Should Read This Book?

  • Students and beginners looking to learn programming from scratch.

  • Professionals who want to add Python to their skill set for career growth.

  • Hobbyists and enthusiasts interested in learning coding in an easy and practical way.

  • Aspiring data analysts and developers who need a quick yet effective introduction to Python.

  • Educators looking for a structured way to teach Python to beginners.

Additional Resources and Exercises

To reinforce learning, this book provides:

  • Coding challenges and exercises at the end of each chapter.

  • Step-by-step project tutorials covering automation, web development, and data analysis.

  • Access to online resources, including sample code and reference materials.

  • Interactive quizzes to test your understanding of key concepts.


Hard Copy : Learn Python the Easy Way: A Practical QuickStudy for Absolute Beginners

Kindle : Learn Python the Easy Way: A Practical QuickStudy for Absolute Beginners

Conclusion

The book "Learn Python the Easy Way: A Practical QuickStudy for Absolute Beginners" is the perfect guide for anyone looking to start programming with Python. It offers a structured and practical approach to learning, helping readers gain confidence in their coding skills quickly.

Whether you're a student, a professional, or someone with a curiosity for coding, this book will equip you with the fundamental knowledge needed to become proficient in Python. Start your journey today and unlock the power of programming!

Applied Statistics with Python: Volume I: Introductory Statistics and Regression


 

Applied Statistics with Python: Volume I: Introductory Statistics and Regression

Statistics is the backbone of data analysis, and Python has become one of the most powerful tools for statistical computing. The book "Applied Statistics with Python: Volume I: Introductory Statistics and Regression" provides an in-depth exploration of fundamental statistical concepts and their practical applications using Python. It is designed for beginners and intermediate learners who want to build a strong foundation in statistics and regression analysis with real-world data.


Why Learn Applied Statistics with Python?

In today's data-driven world, statistical analysis is essential in fields such as business analytics, finance, healthcare, engineering, and social sciences. Python, with its extensive libraries like NumPy, pandas, SciPy, and statsmodels, provides a robust framework for performing statistical analysis efficiently. This book not only introduces key statistical concepts but also teaches you how to implement them using Python, making it a valuable resource for students, analysts, and data science professionals.


Book Overview

This volume focuses on introductory statistics and regression analysis, providing a structured learning path to develop statistical thinking and practical programming skills. It covers descriptive statistics, probability distributions, hypothesis testing, and regression models, all using Python.

Key Topics Covered:

1. Introduction to Statistics and Python for Data Analysis

  • Overview of statistics and its real-world applications
  • Setting up the Python environment for statistical computing
  • Introduction to NumPy, pandas, Matplotlib, and Seaborn

2. Descriptive Statistics and Data Visualization

  • Measures of central tendency (mean, median, mode)
  • Measures of dispersion (variance, standard deviation, range, IQR)
  • Graphical representation of data (histograms, boxplots, scatterplots)

3. Probability Distributions and Inferential Statistics

  • Understanding probability theory and random variables
  • Common probability distributions (normal, binomial, Poisson)
  • Central Limit Theorem and sampling distributions

4. Hypothesis Testing and Confidence Intervals

  • Formulating null and alternative hypotheses
  • t-tests, chi-square tests, and ANOVA
  • Constructing confidence intervals for population parameters

5. Regression Analysis: Understanding Relationships Between Variables

  • Introduction to regression models and their applications
  • Simple linear regression: interpreting coefficients and making predictions
  • Multiple linear regression: handling multiple predictors
  • Evaluating model performance using R-squared and residual analysis

6. Practical Case Studies and Real-World Applications

  • Applying statistics in business and economics
  • Using regression in healthcare and social sciences
  • Predictive modeling and data-driven decision-making


Why Choose This Book?

Hands-On Learning: Step-by-step Python code implementations for every statistical concept.

Beginner-Friendly: Ideal for students, professionals, and anyone new to statistics.

Real-World Applications: Practical examples from diverse fields like finance, healthcare, and business.

Foundation for Data Science: Builds essential skills for machine learning and predictive analytics.


Who Should Read This Book?

Students and professionals looking to understand statistical analysis.

Data analysts and business professionals seeking to enhance their analytical skills.

Researchers in social sciences, healthcare, and engineering.

Anyone interested in using Python for statistical computations.

Hard Copy : Applied Statistics with Python: Volume I: Introductory Statistics and Regression

Kindle : Applied Statistics with Python: Volume I: Introductory Statistics and Regression


Conclusion

The book "Applied Statistics with Python: Volume I: Introductory Statistics and Regression" serves as a comprehensive guide to mastering statistical concepts using Python. By the end of the book, readers will have a strong grasp of statistical analysis techniques and be capable of implementing them in real-world scenarios using Python.

Learn Quantum Computing with Python and IBM Quantum

 


Learn Quantum Computing with Python and IBM Quantum

Quantum computing is revolutionizing the way we approach complex problem-solving, offering exponential computational power beyond classical systems. The course "Learn Quantum Computing with Python and IBM Quantum" provides a hands-on approach to understanding and programming quantum computers using Python and IBM’s Quantum Experience. This course is designed to bridge the gap between theoretical quantum mechanics and practical implementation using real quantum hardware.

Why Learn Quantum Computing?

Quantum computing represents the next frontier in computation, solving problems that classical computers struggle with, such as optimization, cryptography, and drug discovery. Unlike classical computers that use bits (0s and 1s), quantum computers use qubits, which leverage the principles of superposition and entanglement to perform parallel computations. This fundamental shift in processing power has vast implications for industries like finance, artificial intelligence, and material science.

Course Overview

This course is designed for learners interested in exploring quantum computing through practical coding exercises. It provides a structured introduction to the fundamentals of quantum mechanics, quantum circuits, and quantum algorithms, while equipping students with hands-on programming experience using Qiskit, IBM’s open-source quantum computing framework.

Key Topics Covered:

Introduction to Quantum Computing:

  • Overview of classical vs. quantum computing
  • Fundamentals of quantum mechanics
  • Understanding qubits, superposition, and entanglement


Quantum Circuits and Gates:

  • Introduction to quantum gates: Hadamard, Pauli, CNOT, and Toffoli gates
  • Building and manipulating quantum circuits using Qiskit
  • Quantum measurement and quantum state visualization


Quantum Algorithms:

  • Grover's Search Algorithm (used for searching unsorted databases faster than classical methods)
  • Shor’s Algorithm (used for integer factorization, a threat to classical encryption)
  • Quantum Fourier Transform (foundation of many quantum algorithms)
  • Exploring quantum teleportation and superdense coding


IBM Quantum Experience:

  • Introduction to IBM Quantum Lab and cloud-based quantum computing
  • Running quantum circuits on IBM's real quantum hardware
  • Simulating quantum programs before execution


Advanced Applications and Research Topics:

  • Quantum machine learning: Using quantum computing to enhance AI and ML models
  • Quantum cryptography: Securing communication with quantum key distribution (QKD)
  • Exploring variational quantum algorithms for optimization problems


Why Choose This Course?

Hands-on Learning: Students work directly with IBM’s real quantum computers via the IBM Quantum Experience, gaining practical experience in executing quantum programs.

Beginner-Friendly Approach: No prior quantum mechanics background is required, as the course focuses on Python programming with Qiskit and gradually introduces quantum concepts.

Industry-Relevant Skills: Learn techniques and algorithms that are currently being researched for future applications in finance, pharmaceuticals, and AI.

Community Support: Engage with IBM’s quantum computing community, collaborate on projects, and stay updated with the latest advancements in quantum research.


Who Should Take This Course?

This course is ideal for:

Python programmers curious about quantum computing and its applications

Students and researchers in physics, computer science, engineering, and mathematics

Data scientists and AI practitioners interested in integrating quantum computing into their workflows

Technology professionals looking to upskill and explore emerging fields


Course Benefits and Outcomes

By completing this course, learners will:

Gain a solid understanding of quantum computing principles

Develop skills in quantum programming using Qiskit

Be able to design and execute quantum circuits on real IBM quantum hardware

Understand and implement key quantum algorithms

Be well-prepared to explore advanced quantum computing research


Hard Copy : Learn Quantum Computing with Python and IBM Quantum

Kindle : Learn Quantum Computing with Python and IBM Quantum

Conclusion

The "Learn Quantum Computing with Python and IBM Quantum" course is an excellent starting point for anyone interested in exploring the future of computing. Quantum technology is set to transform industries, and gaining expertise in this field will open up exciting opportunities. By the end of the course, learners will be able to understand quantum principles, write quantum programs, and run them on IBM's real quantum hardware.

Sunday, 16 March 2025

Galaxy Swirl Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

num_stars=1000

theta=np.linspace(0,4*np.pi,num_stars)

r=np.exp(0.3*theta)

noise=np.random.normal(scale=0.2,size=(num_stars,2))

x=r*np.cos(theta)+noise[:,0]

y=r*np.sin(theta)+noise[:,-1]

plt.figure(figsize=(6,6),facecolor="black")

plt.scatter(x,y,color="white",s=2)

plt.scatter(-x,-y,color="white",s=2)

plt.axis('off')

plt.title("Galaxy swirl pattern",fontsize=14,color="white")

plt.show()

#source code --> clcoding.com


Code Explanation

Step 1: Import Required Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy (np): Used for numerical computations, like creating arrays, generating random values, and performing trigonometric calculations.

matplotlib.pyplot (plt): Used for creating and customizing the visualization.


Step 2: Define the Number of Stars

num_stars = 1000  

This sets the total number of stars that will be plotted in the galaxy.

A larger number (e.g., 5000) would create a denser galaxy.


Step 3: Generate Spiral Angle (ฮธ)

theta = np.linspace(0, 4 * np.pi, num_stars)  

theta represents the angle in radians.

np.linspace(0, 4 * np.pi, num_stars) generates 1000 values from 0 to 4ฯ€ (two full turns).

This controls the swirl or spiral effect in the galaxy.


Step 4: Compute Spiral Radius (r)

r = np.exp(0.3 * theta)  

This is the equation of a logarithmic spiral:

r=e 0.3ฮธ

 exp(0.3 * theta) ensures that the spiral expands outward as theta increases.

The factor 0.3 controls the tightness of the swirl:

Lower values (e.g., 0.2) → Tighter spiral.

Higher values (e.g., 0.5) → More open swirl.


Step 5: Introduce Random Noise (Star Distribution)

noise = np.random.normal(scale=0.2, size=(num_stars, 2))

This adds randomness to the star positions to make them look more natural.

np.random.normal(scale=0.2, size=(num_stars, 2)):

Generates Gaussian noise with a mean of 0 and a standard deviation of 0.2.

The shape (num_stars, 2) means each star gets a random X and Y offset.

This makes the stars appear slightly scattered instead of forming a perfect spiral.


Step 6: Convert Polar Coordinates to Cartesian Coordinates

x = r * np.cos(theta) + noise[:, 0]

y = r * np.sin(theta) + noise[:, 1]

Converts the polar coordinates (r, theta) into Cartesian coordinates (x, y).

Equations:

x=r⋅cos(ฮธ)+random noise

y=r⋅sin(ฮธ)+random noise

The random noise slightly shifts each star away from the perfect spiral, creating a realistic galaxy.

Step 7: Set Up the Plot with a Black Background

plt.figure(figsize=(8, 8), facecolor="black")

Creates a new figure with a square aspect ratio (8×8 inches).

facecolor="black" sets the background color to black for a space-like appearance.


Step 8: Plot the Stars (White Dots)

plt.scatter(x, y, color="white", s=2)  

plt.scatter(x, y, color="white", s=2):

Plots each star as a tiny white dot.

s=2: Controls the size of each star (can be increased for a brighter look).


Step 9: Create a Symmetric Swirl

plt.scatter(-x, -y, color="white", s=2)

This mirrors the swirl in the opposite direction.

Instead of just x, y, we plot -x, -y to create a symmetric pattern, making the galaxy more balanced.


Step 10: Hide the Axes for a Clean Look

plt.axis("off")

Removes the X and Y axes, making the visualization look more like deep space.


Step 11: Add a Title

plt.title("Galaxy Swirl Pattern", fontsize=14, color="white")

Adds a title "Galaxy Swirl Pattern" in white color.


Step 12: Display the Final Plot

plt.show()

Renders the final galaxy swirl on the screen.


Rose Curve Pattern using python

 


import numpy as np
import matplotlib.pyplot as plt
a=5
k=7
theta=np.linspace(0,2*np.pi,1000)
r=a*np.cos(k*theta)
x=r*np.cos(theta)
y=r*np.sin(theta)
plt.figure(figsize=(6,6),facecolor="black")
plt.plot(x,y,color='magenta',linewidth=2)
plt.axis('off')
plt.title(f"Rose curve pattern(k={k})",color="white",fontsize=14)
plt.show()
#source code --> clcoding.com

Code Explanation: 

Step 1: Import Required Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy (np): Used for numerical computations (e.g., generating angle values for the curve).

matplotlib.pyplot (plt): Used for plotting the Rose Curve.


Step 2: Define Parameters for the Rose Curve

a = 5  

k = 7  

a (Amplitude): Controls the size of the rose curve.

k (Frequency): Defines the number of petals in the Rose Curve.

If k is odd, the Rose Curve has k petals.

If k is even, the Rose Curve has 2k petals.


Step 3: Generate Theta Values (Angle in Radians)

theta = np.linspace(0, 2 * np.pi, 1000)

theta represents the angle in radians, ranging from 0 to 2ฯ€ (a full circle).

np.linspace(0, 2 * np.pi, 1000) generates 1000 equally spaced values between 0 and 2ฯ€, ensuring a smooth curve.


Step 4: Compute r (Polar Radius) for the Rose Curve

r = a * np.cos(k * theta)

This is the polar equation of the Rose Curve:

r=a⋅cos(kฮธ)

a (5) scales the curve, affecting the size.

k * theta determines the oscillation frequency of the petals.


Step 5: Convert Polar Coordinates to Cartesian Coordinates

x = r * np.cos(theta)

y = r * np.sin(theta)

Since matplotlib plots in Cartesian coordinates (x, y), we convert from polar to Cartesian:

x=r⋅cos(ฮธ)

y=r⋅sin(ฮธ)

This transforms the radius (r) and angle (theta) into X, Y coordinates.





Step 6: Set Up the Figure for Plotting

plt.figure(figsize=(6,6), facecolor="black")

figsize=(6,6): Creates a square figure (6x6 inches).

facecolor="black": Sets the background color to black for a stylish effect.


Step 7: Plot the Rose Curve

plt.plot(x, y, color='magenta', linewidth=2)

plt.plot(x, y, color='magenta', linewidth=2)

x, y: The calculated coordinates of the Rose Curve.

color='magenta': Sets the line color to magenta (pinkish-purple).

linewidth=2: Controls the thickness of the curve.


Step 8: Hide Axes for a Clean Look

plt.axis("off")

Hides the X and Y axes to make the design look more artistic.


Step 9: Add a Title

plt.title(f"Rose Curve (k={k})", color="white", fontsize=14)

Displays a title:

Uses f"Rose Curve (k={k})" to dynamically show the value of k in the title.

color="white" makes the title white for visibility on a black background.

fontsize=14 sets the font size.


Step 10: Display the Plot

plt.show()

Displays the final Rose Curve plot.


Star Constellation Pattern using Python

 


import numpy as np

import matplotlib.pyplot as plt

num_stars = 30  

x_vals = np.random.uniform(0, 10, num_stars)

y_vals = np.random.uniform(0, 10, num_stars)

sizes = np.random.randint(20, 100, num_stars)

num_connections = 10

connections = np.random.choice(num_stars, (num_connections, 2), replace=False)

fig, ax = plt.subplots(figsize=(8, 8), facecolor='black')

ax.set_facecolor("black")

ax.scatter(x_vals, y_vals, s=sizes, color='white', alpha=0.8)

for start, end in connections:

    ax.plot([x_vals[start], x_vals[end]], [y_vals[start], y_vals[end]], 

            color='white', linestyle='-', linewidth=0.8, alpha=0.6)

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

plt.title("Star Constellation Pattern", fontsize=14, fontweight="bold", color="white")

plt.show()

#source code --> clcoding.com


Code Explanation:

Import Required Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: Used for generating random numbers (star positions, sizes, and connections).

matplotlib.pyplot: Used for creating the star constellation plot.


Define Number of Stars

num_stars = 30  

Specifies the total number of stars in the pattern.


Generate Random Star Positions

x_vals = np.random.uniform(0, 10, num_stars)

y_vals = np.random.uniform(0, 10, num_stars)

Generates num_stars random x and y coordinates.

np.random.uniform(0, 10, num_stars): Creates values between 0 and 10 to place stars randomly in a 10x10 grid.


Assign Random Star Sizes

sizes = np.random.randint(20, 100, num_stars)

Assigns a random size to each star.

np.random.randint(20, 100, num_stars): Generates star sizes between 20 and 100, making some stars appear brighter than others.


Create Random Connections Between Stars

num_connections = 10

connections = np.random.choice(num_stars, (num_connections, 2), replace=False)

num_connections = 10: Specifies that 10 pairs of stars will be connected with lines.

np.random.choice(num_stars, (num_connections, 2), replace=False):

Randomly selects 10 pairs of star indices (from 0 to num_stars-1).

Ensures that each pair is unique (replace=False).

These pairs form the constellation-like connections.


Create the Figure and Set Background

fig, ax = plt.subplots(figsize=(6, 6), facecolor='black')

ax.set_facecolor("black")

plt.subplots(figsize=(6,6)): Creates a 6x6 inches figure.

facecolor='black': Sets the entire figure background to black.

ax.set_facecolor("black"): Ensures the plot area (inside the figure) is also black.

Plot Stars as White Dots

ax.scatter(x_vals, y_vals, s=sizes, color='white', alpha=0.8)

Plots stars using scatter():

x_vals, y_vals: Star positions.

s=sizes: Varying sizes of stars.

color='white': Stars are white.

alpha=0.8: Adds slight transparency to blend the stars naturally.


Draw Lines to Connect Some Stars (Constellation Effect)

for start, end in connections:

    ax.plot([x_vals[start], x_vals[end]], [y_vals[start], y_vals[end]], 

            color='white', linestyle='-', linewidth=0.8, alpha=0.6)

Loops through each selected star pair (start, end).

Uses ax.plot() to draw a faint white line between the two stars.

color='white': Makes lines visible on a black background.

linestyle='-': Uses solid lines.

linewidth=0.8: Thin lines for a delicate look.

alpha=0.6: Faint transparency to make lines blend smoothly.


Remove Axis Labels for a Clean Look

ax.set_xticks([])

ax.set_yticks([])

ax.set_frame_on(False)

Removes x and y ticks (ax.set_xticks([]), ax.set_yticks([])) so no numerical labels are shown.

Removes plot frame (ax.set_frame_on(False)) to give a seamless night-sky effect.


Add a Title and Display the Plot

plt.title("Star Constellation Pattern", fontsize=14, fontweight="bold", color="white")

plt.show()

Adds a title "Star Constellation Pattern" in white.

plt.show() displays the final constellation pattern.


Popular Posts

Categories

100 Python Programs for Beginner (118) AI (161) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (254) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (226) Data Strucures (14) Deep Learning (76) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (49) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (198) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1222) Python Coding Challenge (904) Python Quiz (350) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)