Monday, 15 January 2024

Clean Architectures in Python (Free PDF)

 

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

What is a software architecture? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

Why is it called “clean”? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Why “architectures”? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Why Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

About the book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Prerequisites and structure of the book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Typographic conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Why this book comes for free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Submitting issues or patches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

About the author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Changes in the second edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Chapter 01 A day in the life of a clean system . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

The data flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Advantages of a layered architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Chapter 02 Components of a clean architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Chapter 03 A basic example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

Chapter 04 Add a web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Flask setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Test and create an HTTP endpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

WSGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Chapter 05 Error management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Request and responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Basic structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Requests and responses in a use case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

Request validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

Responses and failures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Error management in a use case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

Integrating external systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Chapter 06 Integration with a real external system postgres . . . . . . . . . . . . . . . . . . . 89

Decoupling with interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

A repository based on PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Label integration tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Create SQLAlchemy classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

Orchestration management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

Database fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

Integration tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

Chapter 07 Integration with a real external system mongodb . . . . . . . . . . . . . . . . . . 114

Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

Docker Compose configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Application configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Integration tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

The MongoDB repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

Chapter 08 Run a production ready system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

Build a web stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

Connect to a production-ready database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Colophon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

PDF Download: Clean Architectures in Python A practical approach to better software design




Understanding and Visualizing Data with Python

 


What you'll learn

Properly identify various data types and understand the different uses for each  

Create data visualizations and numerical summaries with Python

Communicate statistical ideas clearly and concisely to a broad audience

Identify appropriate analytic techniques for probability and non-probability samples

Join Free: Understanding and Visualizing Data with Python

There are 4 modules in this course

In this course, learners will be introduced to the field of statistics, including where data come from, study design, data management, and exploring and visualizing data. Learners will identify different types of data, and learn how to visualize, analyze, and interpret summaries for both univariate and multivariate data. Learners will also be introduced to the differences between probability and non-probability sampling from larger populations, the idea of how sample estimates vary, and how inferences can be made about larger populations based on probability sampling.

At the end of each week, learners will apply the statistical concepts they’ve learned using Python within the course environment. During these lab-based sessions, learners will discover the different uses of Python as a tool, including the Numpy, Pandas, Statsmodels, Matplotlib, and Seaborn libraries. Tutorial videos are provided to walk learners through the creation of visualizations and data management, all within Python. This course utilizes the Jupyter Notebook environment within Coursera.

Introduction to Structured Query Language (SQL)

 


What you'll learn

Learn about the basic syntax of the SQL language, as well as database design with multiple tables, foreign keys, and the JOIN operation.

Learn to model many-to-many relationships like those needed to represent users, roles, and courses.

Join Free: Introduction to Structured Query Language (SQL)

There are 4 modules in this course

In this course, you'll walk through installation steps for installing a text editor, installing MAMP or XAMPP (or equivalent) and creating a MySql Database. You'll learn about single table queries and the basic syntax of the SQL language, as well as database design with multiple tables, foreign keys, and the JOIN operation. Lastly, you'll learn to model many-to-many relationships like those needed to represent users, roles, and courses.

Survey Data Collection and Analytics Specialization

 


Advance your subject-matter expertise

Learn in-demand skills from university and industry experts

Master a subject or tool with hands-on projects

Develop a deep understanding of key concepts

Earn a career certificate from University of Michigan

Join Free: Survey Data Collection and Analytics Specialization

Specialization - 7 course series

This specialization covers the fundamentals of surveys as used in market research, evaluation research, social science and political research, official government statistics, and many other topic domains. In six courses, you will learn the basics of questionnaire design, data collection methods, sampling design, dealing with missing values, making estimates, combining data from different sources, and the analysis of survey data. In the final Capstone Project, you’ll apply the skills learned throughout the specialization by analyzing and comparing multiple data sources.


Faculty for this specialisation comes from the Michigan Program in Survey Methodology and the Joint Program in Survey Methodology, a collaboration between the University of Maryland, the University of Michigan, and the data collection firm Westat, founded by the National Science Foundation and the Interagency Consortium of Statistical Policy in the U.S.  to educate the next generation of survey researchers, survey statisticians, and survey methodologists. In addition to this specialization we offer short courses, a summer school, certificates, master degrees as well as PhD programs. 



Statistics with Python Specialization

 


What you'll learn

Create and interpret data visualizations using the Python programming language and associated packages & libraries

Apply and interpret inferential procedures when analyzing real data

Apply statistical modeling techniques to data (ie. linear and logistic regression, linear models, multilevel models, Bayesian inference techniques)

Understand importance of connecting research questions to data analysis methods.

Join Free: Statistics with Python Specialization

Specialization - 3 course series

This specialization is designed to teach learners beginning and intermediate concepts of statistical analysis using the Python programming language. Learners will learn where data come from, what types of data can be collected, study data design, data management, and how to effectively carry out data exploration and visualization. They will be able to utilize data for estimation and assessing theories, construct confidence intervals, interpret inferential results, and apply more advanced statistical modeling procedures. Finally, they will learn the importance of and be able to connect research questions to the statistical and data analysis methods taught to them.

Applied Learning Project

The courses in this specialization feature a variety of assignments that will test the learner’s knowledge and ability to apply content through concept checks, written analyses, and Python programming assessments. These assignments are conducted through quizzes, submission of written assignments, and the Jupyter Notebook environment.

User Experience Research and Design Specialization

 


What you'll learn

 Understand the basics of UX design and UX research

 Use appropriate UX research approaches to inform design decisions

 Design a complete product, taking it from an initial concept to an interactive prototype

Join Free: User Experience Research and Design Specialization

Specialization - 6 course series

Integrate UX Research and UX Design to create great products through understanding user needs, rapidly generating prototypes, and evaluating design concepts. Learners will gain hands-on experience with taking a product from initial concept, through user research, ideation and refinement, formal analysis, prototyping, and user testing, applying perspectives and methods to ensure a great user experience at every step.

Applied Learning Project

This Coursera specialization in UX Research and UX Design concludes with a capstone project, in which learners will incorporate UX Research and Design principles to design a complete product, taking it from an initial concept to an interactive prototype.

Sunday, 14 January 2024

Happy Makar Sankranti using Python

 


import turtle


# Set up the turtle
t = turtle.Turtle()
t.speed(2)
t.penup()

# Define scaling factor
scale_factor = 3.5

# Draw the kite
t.fillcolor("orange")
t.begin_fill()
t.goto(0, 100 * scale_factor)
t.goto(-100 * scale_factor, 0)
t.goto(0, 0)
t.end_fill()

t.fillcolor("pink")
t.begin_fill()
t.goto(100 * scale_factor, 0)
t.goto(0, 100 * scale_factor)
t.goto(0, 0)
t.end_fill()

t.fillcolor("cyan")
t.begin_fill()
t.goto(-100 * scale_factor, 0)
t.goto(0, -100 * scale_factor)
t.goto(0, 0)
t.end_fill()

t.fillcolor("green")
t.begin_fill()
t.goto(100 * scale_factor, 0)
t.goto(0, -100 * scale_factor)
t.end_fill()

t.fillcolor("yellow")
t.begin_fill()
t.goto(50 * scale_factor, -150 * scale_factor)
t.goto(-50 * scale_factor, -150 * scale_factor)
t.goto(0, -100 * scale_factor)
t.end_fill()

# Write text
t.penup()
t.goto(200, 100 * scale_factor)
t.write("Happy Makar Sankranti", align="center", font=("Arial", 16, "bold"))

# Close the turtle graphics window when clicked
turtle.exitonclick()

#clcoding.com

How much do you know about Intricacies Classes and Objects in Python?


 


a. A global function can call a class method as well as an instance method.

Answer

True

b. In Python a function, class, method and module are treated as objects.

Answer

True

c. Given an object, it is possible to determine its type and address.

Answer

True

d. It is possible to delete attributes of an object during execution of the

program.

Answer

True

e. Arithmetic operators, Comparison operators and Compound assignment

operators can be overloaded in Python.

Answer

True

f. The + operator has been overloaded in the classes str, list and int.

Answer

False

Saturday, 13 January 2024

A simple text-based guessing game in Python

 


import random


def guess_the_number():
    # Generate a random number between 1 and 100
    secret_number = random.randint(1, 100)

    print("Welcome to the Guess the Number game!")
    print("I have selected a number between 1 and 100. Can you guess it?")

    attempts = 0

    while True:
        try:
            # Get player's guess
            guess = int(input("Enter your guess: "))
            attempts += 1

            # Check if the guess is correct
            if guess == secret_number:
                print(f"Congratulations! You guessed the number in {attempts} attempts.")
                break
            elif guess < secret_number:
                print("Too low! Try again.")
            else:
                print("Too high! Try again.")

        except ValueError:
            print("Please enter a valid number.")

if __name__ == "__main__":
    guess_the_number()



Bar Graph plot using different Python Libraries


#!/usr/bin/env python
# coding: utf-8

# # 1. Using Matplotlib library

# In[1]:


import matplotlib.pyplot as plt

# Sample data
categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4']
values = [10, 25, 15, 30]

# Create a bar graph
plt.bar(categories, values)

# Adding labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Graph Example')

# Show the graph
plt.show()

#clcoding.com


# # 2. Using Seaborn library

# In[2]:


import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4']
values = [10, 25, 15, 30]

# Create a bar plot using Seaborn
sns.barplot(x=categories, y=values)

# Adding labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')

# Show the plot
plt.show()
#clcoding.com


# # 3. Using Plotly library

# In[3]:


import plotly.express as px

# Sample data
categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4']
values = [10, 25, 15, 30]

# Create an interactive bar graph using Plotly
fig = px.bar(x=categories, y=values, labels={'x': 'Categories', 'y': 'Values'}, title='Bar Graph Example')

# Show the plot
fig.show()
#clcoding.com


# # 4. Using Bokeh library

# In[4]:


from bokeh.plotting import figure, show
from bokeh.io import output_notebook

# Sample data
categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4']
values = [10, 25, 15, 30]

# Create a bar graph using Bokeh
p = figure(x_range=categories, title='Bar Graph Example', x_axis_label='Categories', y_axis_label='Values')
p.vbar(x=categories, top=values, width=0.5)

# Show the plot in a Jupyter Notebook (or use output_file for standalone HTML)
output_notebook()
show(p)
#clcoding.com


# In[ ]:






Python Workout: 50 ten-minute exercises

 


The only way to master a skill is to practice. In Python Workout, author Reuven M. Lerner guides you through 50 carefully selected exercises that invite you to flex your programming muscles. As you take on each new challenge, you’ll build programming skill and confidence.

Summary
The only way to master a skill is to practice. In Python Workout, author Reuven M. Lerner guides you through 50 carefully selected exercises that invite you to flex your programming muscles. As you take on each new challenge, you’ll build programming skill and confidence. The thorough explanations help you lock in what you’ve learned and apply it to your own projects. Along the way, Python Workout provides over four hours of video instruction walking you through the solutions to each exercise and dozens of additional exercises for you to try on your own.

Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.

About the technology
To become a champion Python programmer you need to work out, building mental muscle with your hands on the keyboard. Each carefully selected exercise in this unique book adds to your Python prowess—one important skill at a time.

About the book
Python Workout presents 50 exercises that focus on key Python 3 features. In it, expert Python coach Reuven Lerner guides you through a series of small projects, practicing the skills you need to tackle everyday tasks. You’ll appreciate the clear explanations of each technique, and you can watch Reuven solve each exercise in the accompanying videos.

What's inside

50 hands-on exercises and solutions
Coverage of all Python data types
Dozens more bonus exercises for extra practice

About the reader
For readers with basic Python knowledge.

About the author
Reuven M. Lerner teaches Python and data science to companies around the world.

Table of Contents

1 Numeric types

2 Strings

3 Lists and tuples

4 Dictionaries and sets

5 Files

6 Functions

7 Functional programming with comprehensions

8 Modules and packages

9 Objects

10 Iterators and generators

Hard Copy : Python Workout: 50 ten-minute exercises




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

 


Code :

list1 = [2, 3, 9, 12, 4]
list1.insert(4, 17)
list1.insert(2, 23)
print(list1[-4])  

Explanation:

Let's break down the code step by step:

Initial list: [2, 3, 9, 12, 4]
list1.insert(4, 17): Insert the value 17 at index 4. The list becomes [2, 3, 9, 12, 17, 4].
list1.insert(2, 23): Insert the value 23 at index 2. The list becomes [2, 3, 23, 9, 12, 17, 4].
print(list1[-4]): Print the element at the fourth position from the end of the list. The element at index -4 is 9.
So, the output of the code will be:

9

10 Levels of Writing Python Functions

Level 1: Basic Function

Level 2: Function with Parameters

Level 3: Return Values

Level 4: Default Parameters

Level 5: Docstrings

Level 6: Variable Scope

Level 7: Recursion

Level 8: Lambda Functions

Level 9: Function Decorators

Level 10: Advanced Functions







Friday, 12 January 2024

How much do you know about list in Python?



1. Which value is used to represent the first index of

list?

(a) 1 (b) 0

(c) −1 (d) a

Ans. (b) To access the list’s elements, index number is used. The

index number should be an integer. Index of 0 refers to first

element, 1 refers to second element and so on.


2. Choose the output of following Python code.

1= list ()

print ( 1)

(a) [] (b) ()

(c) [,] (d) Empty

Ans. (a) Empty list can be created in Python using []. To create

empty list, list () is also used.


3. Suppose list

1= [10, 20, 30, 40, 50, 60, 70]

print( 1[−3])

(a) 30 (b) 50

(c) 40 (d) Error

Ans. (b) The index of −1 refers to the last element, −2 refers to the

second last element and so on. Hence, −3 refers to third last

element, i.e. 50.


4. Choose the output from following code.

list1 = [‘A’, ‘R’, ‘I’,‘H’,‘A’,‘N’,‘T’]

print (list1 [7])

(a) T (b) N

(c) A (d) Error

Ans. (d) In the given code, we are trying to access 8th element

from the list which does not exist as we are having total 7

elements for which the last index is 6. So, Python will give

an IndexError.


5. Which function is used to insert an element at

specified position in the list?

(a) extend () (b) append ()

(c) insert () (d) add ()

Ans. (c) insert () function is used to insert an element at specified

position in the list. This method takes two arguments : one

for index number and second for element value.

Syntax list_name.insert(index, element)


6. Choose the correct option for the following.

l1 = [2, 5, 7]

l = l1+ 5

print (l)

(a) [7, 10, 12]

(b) [2, 5, 7, 5]

(c) [5, 2, 5, 7]

(d) TypeError

Ans. (d) + operator cannot add list with other type as number or

string because this operator is used only with list types.

So, it will give TypeError as it can only concatenate list (not

“int”) to list.


7. What is the output of following code?

l1 = [3, 2, 6]

l = l1 * 2

print (l)

(a) [3, 2, 6, 3, 2, 6]

(b) [6, 4, 12]

(c) [3, 4, 12]

(d) TypeError

Ans. (a) * operator can repeat the elements of the list.

Syntax list = list1 * digit


8. Which of the following is true regarding lists in

Python?

(a) Lists are immutable.

(b) Size of the lists must be specified before its initialisation.

(c) Elements of lists are stored in contiguous memory

location.

(d) size(list1) command is used to find the size of lists.

Ans. (c) Elements of lists are stored in contiguous memory

location, so it is true regarding lists in Python.


9. Suppose list1 is [56, 89, 75, 65, 99], what is the

output of list1 [− 2]?

(a) Error (b) 75

(c) 99 (d) 65

Ans. (d) −1 corresponds to the last index in the list, −2 represents

the second last element and so on.

So, the output for list1 [− 2] is 65 because 65 is second last

element of list1.


10. Identify the output of following code.

List1=[1, 2, 3, 7, 9]

L=List1.pop(9)

print(L)

(a) Syntax error (b) 9

(c) [1, 2, 3, 7] (d) None of these

Ans. (a) In pop(9), parentheses put index number instead of

element. In the given list, maximum index number is 4, then

9 is out of index range.


11. Suppose list1 is [2445,133,12454,123], what is the

output of max(list1)?

(a) 2445 (b) 133

(c) 12454 (d)123

Ans. (c) max() returns the maximum element in the list. From

given options, 12454 is the element with maximum value.


12. To add a new element to a list, which command will

we use?

(a) list1.add(8)

(b) list1.append(8)

(c) list1.addLast(8)

(d) list1.addEnd(8)

Ans. (b) We use the function append() to add an element to the list.


13. What will be the output of the following Python

code?

list1=[9, 5, 3, 5, 4]

list1[1:2]=[7,8]

print(list1)

(a) [9,5, 3, 7, 8] (b) [9, 7, 8, 3, 5, 4]

(c) [9,[ 7, 8], 3, 5,4] (d) Error

Ans. (b) In the piece of code, slice assignment has been

implemented. The sliced list is replaced by the assigned

elements in the list.


14. Consider the declaration a=[2, 3, ‘Hello’, 23.0].

Which of the following represents the data type of

‘a’?

(a) String (b) Tuple

(c) Dictionary (d) List

Ans. (d) List contains a sequence of heterogeneous elements

which store integer, string as well as object. It can created to

put elements separated by comma (,) in square brackets [].


15. Identify the output of the following Python

statement.

x=[[1, 2, 3, 4], [5, 6, 7, 8]]

y=x [0] [2]

print(y)

(a) 3 (b) 4

(c) 6 (d) 7

Ans. (a) x is a list, which has two sub-lists in it. Elements of first

list will be represented by [0] [i] and elements of second list

will be represented by [1] [i].


16. Which method will empty the entire list?

(a) pop() (b) clear()

(c) sort() (d) remove()

Ans. (b) clear() method is used to remove all the items of a list.

This method will empty the entire list.

Syntax

list_name.clear()


17. Which of the following allows us to sort the list

elements in descending order?

(a) reverse = True

(b) reverse = False

(c) sort (descending)

(d) sort. descending

Ans. (a) sort() is used to sort the given list in ascending order. The

sort() has an argument called reverse = True. This allows us

to sort the list elements in descending order.


18. Identify the correct output.

>>>l1 = [34, 65, 23, 98]

>>>l1. insert(2, 55)

>>>l1

(a) [34, 65, 23, 55] (b) [34, 55, 65, 23, 98]

(c) [34, 65, 55, 98] (d) [34, 65, 55, 23, 98]

Ans. (d) insert() is used to insert an element at specified position

in the list. This method takes two arguments : one for index

number and second for element value.

Syntax

list_name.insert(index, element)


19. Find the output from the following code.

list1=[2, 5, 4, 7, 7, 7, 8, 90]

del list1[2 : 4]

print(list1)

(a) [2, 5, 7, 7, 8, 90] (b) [5, 7, 7, 7, 8, 90]

(c) [2, 5, 4, 8, 90] (d) Error

Ans. (a) del keyword is used to delete the elements from the list.


20. Slice operation is performed on lists with the use of

(a) semicolon (b) comma

(c) colon (d) hash

Ans. (c) In Python list, there are multiple ways to print the whole

list with all the elements, but to print a specific range of

elements from the list, we use slice operation. Slice

operation is performed on lists with the use of colon (:).

Play Fidget Spinner game using Python




from turtle import *

speed(0)
bgcolor('lightgray')
title('Fidget Spinner Game')

spinner_radius = 250  # Increased radius
spinner_speed = 0
spinner_colors = ['red', 'green', 'blue']

def create_spinner():
    penup()
    goto(0, 0)  # Center the spinner
    pendown()

    for color in spinner_colors:
        fillcolor(color)
        begin_fill()
        circle(spinner_radius/len(spinner_colors))
        end_fill()
        right(360 / len(spinner_colors))

def spin_spinner(x, y):
    global spinner_speed
    spinner_speed += 10

def stop_spinner(x, y):
    global spinner_speed
    spinner_speed = max(0, spinner_speed - 5)

def animate_spinner():
    global spinner_speed
    clear()
    create_spinner()
    right(spinner_speed)
    update()
    ontimer(animate_spinner, 20)

def main():
    setup(600, 600)
    hideturtle()
    tracer(False)
   
    create_spinner()

    onscreenclick(spin_spinner, 1)
    onscreenclick(stop_spinner, 3)

    animate_spinner()

    done()

if __name__ == "__main__":
    main()

What is the output of following Python code?

 What is the output of following Python code?


a =[[0, 1, 2], [3, 4, 5, 6]]

b =a[1] [2]

print (b)

Answer with Explanation:

Let's break down your code step by step:

a = [[0, 1, 2], [3, 4, 5, 6]]

Here, you have defined a list a that contains two sub-lists. The first sub-list is [0, 1, 2], and the second sub-list is [3, 4, 5, 6]. So, a is a list of lists.

b = a[1][2]

This line of code is accessing elements in the nested list. Let's break it down:


a[1] accesses the second sub-list in a. In Python, indexing starts from 0, so a[1] refers to [3, 4, 5, 6].

[2] then accesses the third element in this sub-list. Again, indexing starts from 0, so a[1][2] refers to the element at index 2 in the sub-list [3, 4, 5, 6].

As a result, b is assigned the value 5, which is the third element in the second sub-list.

print(b)

Finally, the print(b) statement outputs the value of b, which is 5, to the console.

So, when you run this code, the output will be:

5

This is because b contains the value at index [1][2] in the nested list a, which is 5.

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

 


Code: 

def fun(num):

    if num > 10:

        return num - 10

    return fun(fun(num + 11))

print(fun(5))

Solution and Explanantion: 


The output of the code is 1.

Here's a breakdown of how the code works:

Function Definition:

The code defines a recursive function named fun that takes a single argument, num.

Base Case:

The if statement checks if num is greater than 10. If it is, the function returns num - 10. This is the base case that stops the recursion.

Recursive Calls:

If num is not greater than 10, the function calls itself twice, creating two recursive calls:
fun(fun(num + 11))
The inner call fun(num + 11) adds 11 to num and passes the result to the fun function again.
The outer call takes the result of the inner call and passes it to the fun function once more.

Execution Flow:

When you call fun(5), here's what happens:
5 is not greater than 10, so the function calls fun(fun(16)).
The inner call fun(16) now executes. 16 is greater than 10, so the base case triggers and returns 16 - 10 = 6.
The outer call now has 6 as its argument. 6 is not greater than 10, so it calls fun(fun(17)).
The inner call fun(17) executes. 17 is greater than 10, so the base case returns 17 - 10 = 7.
The outer call now has 7 as its argument. 7 is not greater than 10, so it calls fun(fun(18)).
This process continues until fun(25) is reached. At this point, the base case returns 25 - 10 = 15.
The values start propagating back through the recursive calls, eventually leading to the final return value of 1.
Key Points:

The code demonstrates recursion, where a function calls itself within its own definition.
The base case is crucial to prevent infinite recursion and ensure the function eventually terminates.
Recursive functions can be helpful for solving problems that can be broken down into smaller, self-similar subproblems. 

Thursday, 11 January 2024

Which of the following are valid return statements?

 

Which of the following are valid return statements?

return (a, b, c)

return a + b + c

return a, b, c


All three of the provided return statements are valid in Python, but they have different implications:

return (a, b, c): This returns a single tuple containing the values of a, b, and c. For example, if a = 1, b = 2, and c = 3, the function would return the tuple (1, 2, 3).

return a + b + c: This returns the sum of a, b, and c. If a = 1, b = 2, and c = 3, the function would return the value 6.

return a, b, c: This returns a tuple containing the values of a, b, and c. This is a more concise way of expressing the first option. For the same example values, it would return the tuple (1, 2, 3).

Choose the one that fits your specific use case and the desired return value format in your function.

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

 


The code you provided is attempting to generate a Fibonacci sequence and append the values to the list lst. However, it seems like there's a small mistake in your code. The range in the list comprehension should go up to 4, not 5, to generate the Fibonacci sequence up to the 4th element. Here's the corrected code:

lst = [0, 1]

[lst.append(lst[k - 1] + lst[k - 2]) for k in range(2, 5)]

print(lst)

After running this code, lst will be:

[0, 1, 1, 2, 3]

This list represents the Fibonacci sequence up to the 4th element. The initial list [0, 1] is extended by three more elements generated by adding the last two elements of the list to get the next one.

How to write program that generates a list of integer coordinates for all points in the first quadrant from (1, 1) to (5, 5) using list comprehension?

 

You can use list comprehension to generate a list of integer coordinates for all points in the first quadrant from (1, 1) to (5, 5). Here's an example in Python:

coordinates = [(x, y) for x in range(1, 6) for y in range(1, 6)]

print(coordinates)

This code will produce a list of tuples where each tuple represents a coordinate in the first quadrant, ranging from (1, 1) to (5, 5). The range(1, 6) is used to include values from 1 to 5 (inclusive) for both x and y.

After running this code, coordinates will contain the following list:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),  (2, 1), (2, 2), (2, 3), (2, 4), (2, 5),  (3, 1), (3, 2), (3, 3), (3, 4), (3, 5),  (4, 1), (4, 2), (4, 3), (4, 4), (4, 5),  (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]


Wednesday, 10 January 2024

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

 


Code :

x = 15

y = 10

result = x if x < y else y

print(result)


Solution and Explanation: 

Let's break down the code step by step:

Variable Initialization:

x = 15
y = 10
Two variables, x and y, are initialized with the values 15 and 10, respectively.

Conditional Expression:

result = x if x < y else y
This line uses a conditional expression. The syntax is a if condition else b, meaning if the condition is true, the value of a is assigned to the variable; otherwise, the value of b is assigned. In this case, it's checking whether x is less than y. If it is true, result will be assigned the value of x, otherwise, it will be assigned the value of y.

Printing the Result:

print(result)
Finally, the code prints the value of result.

Execution:
In this specific example, x (15) is not less than y (10). Therefore, the conditional expression evaluates to y, and the value 10 is assigned to result. The print(result) statement then outputs 10 to the console.

In summary, the code compares the values of x and y and assigns the smaller value to the variable result, which is then printed. In this particular case, the output will be 10 because y is smaller than x.



Tuesday, 9 January 2024

50 Algorithms Every Programmer Should Know

 


Delve into the realm of generative AI and large language models (LLMs) while exploring modern deep learning techniques, including LSTMs, GRUs, RNNs with new chapters included in this 50% new edition overhaul

Purchase of the print or Kindle book includes a free eBook in PDF format.

Key Features

  • Familiarize yourself with advanced deep learning architectures
  • Explore newer topics, such as handling hidden bias in data and algorithm explainability
  • Get to grips with different programming algorithms and choose the right data structures for their optimal implementation

Book Description

The ability to use algorithms to solve real-world problems is a must-have skill for any developer or programmer. This book will help you not only to develop the skills to select and use an algorithm to tackle problems in the real world but also to understand how it works.

You'll start with an introduction to algorithms and discover various algorithm design techniques, before exploring how to implement different types of algorithms, with the help of practical examples. As you advance, you'll learn about linear programming, page ranking, and graphs, and will then work with machine learning algorithms to understand the math and logic behind them.

Case studies will show you how to apply these algorithms optimally before you focus on deep learning algorithms and learn about different types of deep learning models along with their practical use.

You will also learn about modern sequential models and their variants, algorithms, methodologies, and architectures that are used to implement Large Language Models (LLMs) such as ChatGPT.

Finally, you'll become well versed in techniques that enable parallel processing, giving you the ability to use these algorithms for compute-intensive tasks.

By the end of this programming book, you'll have become adept at solving real-world computational problems by using a wide range of algorithms.

What you will learn

  • Design algorithms for solving complex problems
  • Become familiar with neural networks and deep learning techniques
  • Explore existing data structures and algorithms found in Python libraries
  • Implement graph algorithms for fraud detection using network analysis
  • Delve into state-of-the-art algorithms for proficient Natural Language Processing illustrated with real-world examples
  • Create a recommendation engine that suggests relevant movies to subscribers
  • Grasp the concepts of sequential machine learning models and their foundational role in the development of cutting-edge LLMs

Who this book is for

This computer science book is for programmers or developers who want to understand the use of algorithms for problem-solving and writing efficient code.

Whether you are a beginner looking to learn the most used algorithms concisely or an experienced programmer looking to explore cutting-edge algorithms in data science, machine learning, and cryptography, you'll find this book useful.

Python programming experience is a must, knowledge of data science will be helpful but not necessary.

Table of Contents

  1. Core Algorithms
  2. Data Structures
  3. Sorting and Searching Algorithms
  4. Designing Algorithms
  5. Graph Algorithms
  6. Unsupervised Machine Learning Algorithms
  7. Supervised Learning Algorithms
  8. Neural Network Algorithms
  9. Natural Language Processing
  10. Sequential Models
  11. Advanced Machine Learning Models
  12. Recommendation Engines
  13. Algorithmic Strategies for Data Handling
  14. Large-Scale Algorithms
  15. Evaluating Algorithmic Solutions
  16. Practical Considerations

Hard Copy : 50 Algorithms Every Programmer Should Know: Tackle computer science challenges with classic to modern algorithms in machine learning, software design, data systems, and cryptography

How much do you know about Modules and packages in python?

 

a. A function can belong to a module and the module can belong to a

package.

Answer

True

b. A package can contain one or more modules in it.

Answer

True

c. Nested packages are allowed.

Answer

True

d. Contents of sys.path variable cannot be modified.

Answer

False

e. In the statement import a.b.c, c cannot be a function.

Answer

True

f. It is a good idea to use * to import all the functions/classes defined in a

module.

Answer

True

PostgreSQL for Everybody Specialization

 


What you'll learn

How to use the PostgreSQL database effectively

Explore database design principles

Dive into database architecture and deployment strategies

Compare and contrast SQL and NoSQL database design approaches and acquire skills applicable to data mining and application development

Join Free: PostgreSQL for Everybody Specialization

Specialization - 4 course series

Across these four courses, you’ll learn how to use the PostgreSQL database and explore topics ranging from database design to database architecture and deployment. You’ll also compare and contrast SQL and NoSQL approaches to database design. The skills in this course will be useful to learners doing data mining or application development.

Applied Learning Project

This course series utilizes a custom autograding environment for an authentic set of graded and practice assignments, including: creating and manipulating tables, designing data models, constructing advanced queries, techniques for working with text in databases, including regular expressions, and more.

Python Data Structures

 


What you'll learn

Explain the principles of data structures & how they are used

Create programs that are able to read and write data from files

Store data as key/value pairs using Python dictionaries

Accomplish multi-step tasks like sorting or looping using tuples

Join Free: Python Data Structures

There are 7 modules in this course

This course will introduce the core data structures of the Python programming language. We will move past the basics of procedural programming and explore how we can use the Python built-in data structures such as lists, dictionaries, and tuples to perform increasingly complex data analysis. This course will cover Chapters 6-10 of the textbook “Python for Everybody”.  This course covers Python 3.

Web Applications for Everybody Specialization

 


What you'll learn

Installing your development environment

Developing a database application with PHP and MySQL

Using JavaScript to interact with a PHP web app

Modeling many-to-many relationships 

Join Free: Web Applications for Everybody Specialization

Specialization - 4 course series

This Specialization is an introduction to building web applications for anybody who already has a basic understanding of responsive web design with JavaScript,  HTML, and CSS. Web Applications for Everybody is your introduction to web application development. You will develop web and database applications in PHP, using SQL for database creation, as well as functionality in JavaScript, jQuery, and JSON.

Over the course of this Specialization, you will create several web apps to add to your developer portfolio. This Specialization (and its prerequisites) will prepare you, even if you have little to no experience in programming or technology, for entry level web developer jobs in PHP.

You’ll demonstrate basic concepts, like database design, while working on assignments that require the development of increasing challenging web apps. From installing a text editor to understanding how a web browser interacts with a web server to handling events with JQuery, you’ll gain a complete introductory overview of web application development.

Applied Learning Project

The courses in this specialization feature assignments requiring development of increasingly challenging web sites, to demonstrate basic concepts as they are introduced.  The projects will demonstrate the students skills in HTML, CSS, PHP, SQL, and JavaScript.

Popular Posts

Categories

100 Python Programs for Beginner (56) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (228) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (60) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (937) Python Coding Challenge (372) Python Quiz (28) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses