Saturday, 2 December 2023

Python Data Structures and Algorithms (Free PDF)


 

A knowledge of data structures and the algorithms that bring them to life is the key to

building successful data applications. With this knowledge, we have a powerful way to

unlock the secrets buried in large amounts of data. This skill is becoming more important in

a data-saturated world, where the amount of data being produced dwarfs our ability to

analyze it. In this book, you will learn the essential Python data structures and the most

common algorithms. This book will provide basic knowledge of Python and an insight into

the exciting world of data algorithms. We will look at algorithms that provide solutions to

the most common problems in data analysis, including sorting and searching data, as well

as being able to extract important statistics from data. With this easy-to-read book, you will

learn how to create complex data structures such as linked lists, stacks, and queues, as well

as sorting algorithms such as bubble sort and insertion sort. You will learn the common

techniques and structures used in tasks such as preprocessing, modeling, and transforming

data. We will also discuss how to organize your code in a manageable, consistent, and

extendable way. You will learn how to build components that are easy to understand,

debug, and use in different applications.

A good understanding of data structures and algorithms cannot be overemphasized. It is an

important arsenal to have in being able to understand new problems and find elegant

solutions to them. By gaining a deeper understanding of algorithms and data structures,

you may find uses for them in many more ways than originally intended. You will develop

a consideration for the code you write and how it affects the amount of memory and

CPU cycles to say the least. Code will not be written for the sake of it, but rather with a

mindset to do more using minimal resources. When programs that have been thoroughly

analyzed and scrutinized are used in a real-life setting, the performance is a delight to

experience. Sloppy code is always a recipe for poor performance. Whether you like

algorithms purely from the standpoint of them being an intellectual exercise or them

serving as a source of inspiration in solving a problem, it is an engagement worthy of

pursuit.

The Python language has further opened the door for many professionals and students to

come to appreciate programming. The language is fun to work with and concise in its

description of problems. We leverage the language's mass appeal to examine a number of

widely studied and standardized data structures and algorithms.

The book begins with a concise tour of the Python programming language. As such, it is not

required that you know Python before picking up this book.

Download PDF : Python Data Structures and Algorithms

Buy : Hands-On Data Structures and Algorithms with Python: Store, manipulate, and access data effectively and boost the performance of your applications, 3rd Edition


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

 


Code : 

tuple1 = (1, 2, 4, 3) 

tuple2 = (1, 2, 3, 4) 

print(tuple1 < tuple2) 


Solution and Explanation : 

The above code is comparing two tuples, tuple1 and tuple2, using the less than (<) operator. This comparison is done element-wise.

In this case, the first elements of both tuples are the same (1), so it moves on to the second elements. The second elements are also the same (2). It continues this process until it finds a pair of elements where one is less than the corresponding element in the other tuple.

In your example:

tuple1: (1, 2, 4, 3)
tuple2: (1, 2, 3, 4)

At the third position, tuple1 has 4, and tuple2 has 3. Since 3 is less than 4, the result of the comparison is False.

So, when you run this code, it will print:

False

Python Code for Periodic Table Elements

 




Code :

import periodictable

# Get details of an element by atomic number
Atomic_No = int(input("Enter Element Atomic No :"))
element = periodictable.elements[Atomic_No] 
print('Atomic number:', element.number)
print('Symbol:', element.symbol)
print('Name:', element.name)
print('Atomic mass:', element.mass)
print('Density:', element.density)
#clcoding.com


Output : 

Enter Element Atomic No :26
Atomic number: 26
Symbol: Fe
Name: iron
Atomic mass: 55.845
Density: 7.874

Friday, 1 December 2023

Create Your First Web App with Python and Flask

 


What you'll learn

Create Web Applications with Flask

Use WTForms and SQLAlchemy in Flask Applications

Use Templates in Flask Applications

About this Guided Project

In this 2-hour long project-based course, you will learn the basics of web application development with Python using the Flask framework. Through hands on, practical experience, you will go through concepts like creating a Flask Application, using Templates in Flask Applications, using SQLAlchemy and SQLite with Flask, and using Flask and WTForms. You will then apply the concepts to create your first web application with Python and Flask.

This course is aimed at learners who are looking to get started with web application development using Python, and have some prior programming experience in the Python programming language. The ideal learner has understanding of Python syntax, HTML syntax, and computer programming concepts.

Note: This course works best for learners who are based in the North America region. We’re currently working on providing the same experience in other regions.


Join Free : Create Your First Web App with Python and Flask



Real-time Currency Converter with Python

 


pip install forex_python

Code : 

from forex_python.converter import CurrencyRates
c = CurrencyRates()
amount = int(input("Enter the amount: "))
from_currency = input("From Currency: ").upper()
to_currency = input("To Currency: ").upper()

print(from_currency, " To ", to_currency, amount)
result = c.convert(from_currency, to_currency, amount)
print(result)

#clcoding.com

Output : 

Enter the amount: 10
From Currency: EUR
To Currency: INR
EUR  To  INR 10
888.9

What is the result of the following python code?

 What is the result of the following python code?


x = {1: "a", 2: "b"}

y = x.keys()

print(y)

Solution and Explanation:

The code you provided creates a dictionary x with keys 1 and 2, and then assigns the keys of the dictionary to the variable y. Finally, it prints the values of y. However, in Python 3, y will be a view object (dict_keys) representing the keys of the dictionary. To see the keys as a list, you can convert it to a list:

x = {1: "a", 2: "b"}

y = list(x.keys())

print(y)

Output: [1, 2]


 Let's break down the code step by step:

Dictionary Creation:

x = {1: "a", 2: "b"}

Here, a dictionary x is created with keys 1 and 2, each associated with a corresponding value ("a" and "b").

Getting Keys:

y = x.keys()

In this line, the keys() method is used on the dictionary x to obtain a view object that represents the keys of the dictionary. The dict_keys view is a dynamic view of the dictionary's keys.

Printing:

print(y)

This line prints the result of y, which is the dict_keys view. However, in Python 3, this view is not automatically converted to a list when printed.

If you want to see the keys as a list, you can convert the dict_keys view to a list, like this:

y = list(x.keys())

print(y)

Output:

[1, 2]

The final output, after converting the dict_keys view to a list, is a list containing the keys of the dictionary x. In this case, it's [1, 2].


a = [] b = [a.append(i) for i in range(5)] print(a) print(b)

Code : 

a = []

b = [a.append(i) for i in range(5)]

print(a)

print(b)


Solution and Explanation: 

This code outputs the following:

[0, 1, 2, 3, 4]
[None, None, None, None, None]
List a is modified by the loop, and the loop overwrites the list b with None.

here is the explanation of the code:

The list comprehension [a.append(i) for i in range(5)] creates a list of None values. This is because the expression a.append(i) returns None, and the list comprehension only stores the return values of the expressions it contains.

The loop overwrites the list b with None because the list comprehension is evaluated before the loop. This means that the list b is already a list of None values by the time the loop starts.

The list a is modified by the loop because the expression a.append(i) appends the value i to the list a. This is because the expression a.append(i) is evaluated inside the loop, and the list a is modified in place.

Therefore, the output of the code is:

a: [0, 1, 2, 3, 4]
b: [None, None, None, None, None]

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

 


Code :

i=j=[3]
i+=j
print(i,j)

Solution and Explanation:


In this Python code:

i = j = [3]

i += j

print(i, j)

Both i and j are assigned the same list [3]. The += operator is used to extend the list i by appending the elements of list j to it.


After the execution of the code, the output will be:

[3, 3] [3, 3]

Here's the breakdown:


i = j = [3]: Both i and j are assigned the list [3].

i += j: The += operator modifies the list i by appending the elements of list j to it. So, i becomes [3, 3].

print(i, j): Prints the values of i and j.

As a result, both i and j are [3, 3].







What is the output of the following python code?

 What is the output of the following python code?

x = 5

y = x > 3

print(y)


a) 5

b) 3

c) True

d) False


Solution and Explanation: 

The output of the given Python code will be:

True

Explanation:

x = 5: Assigns the value 5 to the variable x.
y = x > 3: Compares whether the value of x is greater than 3 and assigns the result (True or False) to the variable y.
print(y): Prints the value of y.
In this case, x is indeed greater than 3 (as x is 5), so the comparison x > 3 evaluates to True. Therefore, the output of the code is True. So, the correct option is:

c) True

a = "240" print(a.zfill(4))

 Code :

a = "240"

print(a.zfill(4))


Solution and Explanation : 

The zfill() method in Python is used to pad a string with zeros (0) on the left side until the string reaches the specified width. In your case, you've specified a width of 4.


Here's how it works:

a = "240"

result = a.zfill(4)

print(result)

Output:

0240

In this example, the original string "240" has a length of 3. The zfill(4) method pads zeros on the left side to make the length of the string 4. Therefore, the result is "0240".

my_list=[11,22,33,44,55] del my_list[:] print(my_list)

 Code :

my_list=[11,22,33,44,55]

del my_list[:]

print(my_list)


Solution and Explanation:

The above code  deletes all elements from the list my_list using the del statement with the slice [:]. This is a common way to clear a list in Python.

Here's a breakdown of the code:

del my_list[:]: This deletes all elements in the list. The [:] is a slice that includes all elements of the list.

After executing this code, the list my_list will be empty. If you print my_list after the deletion, you will get:

[]

So, the output of the provided code will be an empty list ([]).

a = (10, '20', 30) print(min(a))

Code : 

a = (10, '20', 30)

print(min(a))

Solution and Explanation: 

The min() function compares the elements in the tuple lexicographically (in the case of strings) or numerically (in the case of numbers) and returns the smallest element. If the elements are of different types, it may raise a TypeError.


In your case, the tuple a contains elements of different types: an integer (10), a string ('20'), and another integer (30). The min() function will compare them based on their natural order. In this case, it will compare the integer 10, the string '20', and the integer 30.

The comparison is done lexicographically for strings, so '20' is considered smaller than both 10 and 30. Therefore, the output of the min(a) expression will be '20'.

If you run the provided code, the output will be:

20

Thursday, 30 November 2023

Python Basics: Automation and Bots

 


What you'll learn

Learn how to play faster and looser and more casual with code, skimming and copying code from the Internet.

Discuss code flow and the order that your computer reads the code you write. This introduces us to a whole other level of thinking in code.

Logic can be harnessed to do useful stuff. We'll make it concrete by performing tasks like building an anagram finder.

Apply Python by robocall and spam text yourself through the Twilio API.

There are 4 modules in this course

Understanding the flow of running code is a major part of learning to think in code and of coding itself. In this course we will study the flow of code through several demonstrations and walkthroughs. We'll experience turning logic into useful work by running Python that automatically reads all of Shakespeare, and by setting Python up to give you a call on the phone. In technical terms, this course will demonstrate Python loops, list comprehensions, and conditional statements, while at a higher level we'll discuss code style and good practices for code.


Join Free : Python Basics: Automation and Bots


Creative Thinking: Techniques and Tools for Success (Free Course)

 


What you'll learn

Understand what creative thinking techniques are

Comprehend their importance in tackling global challenges as well as in everyday problem-solving scenarios

Select and apply the appropriate technique based on the opportunity to seize or the problem to tackle


There are 7 modules in this course

In today’s ever-growing and changing world, being able to think creatively and innovatively are essential skills. It can sometimes be challenging to step back and reflect in an environment which is fast paced or when you are required to assimilate large amounts of information. Making sense of or communicating new ideas in an innovative and engaging way, approaching problems from fresh angles, and producing novel solutions are all traits which are highly sought after by employers.


This course will equip you with a ‘tool-box’, introducing you to a selection of behaviours and techniques that will augment your innate creativity. Some of the tools are suited to use on your own and others work well for a group, enabling you to leverage the power of several minds.  You can pick and choose which of these tools or techniques suit your needs and interests, focusing on some or all of the selected approaches and in the order that fits best for you.


The practical approach of this course enables you to acquire an essential skill-set for generating ideas, with plenty of:

- Fun e-tivities and exercises;

- Practical lectures and tips;

- Video representations of the techniques in action.


By the end of this course you should be able to:

- Pick a type of brainstorming you think will be useful to apply to a challenge

- Use alphabet brainstorming in tackling a challenge

- Use grid brainstorming in tackling a challenge

- Use a morphological chart to synthesise a solution to a challenge

- Use the TRIZ contradiction matrix to identify recommended inventive principles

- Apply SCAMPER to a range of challenges


The greatest innovators aren’t necessarily the people who have the most original idea. Often, they are people- or teams- that have harnessed their creativity to develop a new perspective or more effective way of communicating an idea. You can train your imagination to seize opportunities, break away from routine and habit, and tap into your natural creativity.


Join this course and a community of practitioners in CREATIVITY!

Join Free - Creative Thinking: Techniques and Tools for Success




What is wrong with “is” in Python ?

 


In Python, the is keyword is used to test object identity, which checks if two variables reference the same object in memory. However, it's important to note that the behavior you're observing is specific to the implementation of Python and may vary based on different factors, such as the Python interpreter and optimizations.

In CPython (the reference implementation of Python), small integers are cached for performance reasons. This means that integers in a certain range are the same object in memory to optimize memory usage and speed up operations. In your first example:

a = 256
b = 256
print(a is b)  # True
This is True because a and b both reference the same object in memory due to the integer caching optimization.

In second example:

a = 257
b = 257
print(a is b)  # False
This is False because the integers 257 and 257 are not cached, so they are distinct objects in memory.

While using is for comparing integers might work in some cases, it's generally recommended to use the == operator for equality testing. The == operator compares the values of the objects, which is more reliable and is the standard way to check if two variables hold the same value:

print(a == b)  # True for both examples
So, in summary, while a is b may work for small integers due to caching, it's not guaranteed and is not considered a good practice for equality testing. Always use == when comparing values.

Wednesday, 29 November 2023

c = True or False print(not not c)

 c = True or False

print(not not c)

In the first line, True or False evaluates to True because it uses the logical OR operator (or). This means that the variable c is assigned the value True.


In the second line, not not c is equivalent to not (not c). The not operator negates the value, so not c is not True, which is False. Then, the outer not negates this result again, making it not False, which evaluates to True.

So, the final output of the code will be:

True

This is because c is assigned the value True, and the double not operation results in True.






State whether the following statements are True or False (Classes and Objects)


a. Class attributes and object attributes are same.

Answer

False

b. A class data member is useful when all objects of the same class must

share a common item of information.

Answer

True

c. If a class has a data member and three objects are created from this class,

then each object would have its own data member.

Answer

True

d. A class can have class data as well as class methods.

Answer

True

e. Usually data in a class is kept private and the data is accessed /

manipulated through object methods of the class.

Answer

True

f. Member functions of an object have to be called explicitly, whereas, the

_init_( ) method gets called automatically.

Answer

True

g. A constructor gets called whenever an object gets instantiated.

Answer

True

h. The _init_( ) method never returns a value.

Answer

True

i. When an object goes out of scope, its _del_( ) method gets called

automatically.

Answer

True

j. The self variable always contains the address of the object using which

the method/data is being accessed.

Answer

True

k. The self variable can be used even outside the class.

Answer

False

l. The _init_( ) method gets called only once during the lifetime of an

object.

Answer

True

m. By default, instance data and methods in a class are public.

Answer

True

n. In a class 2 constructors can coexist-a 0-argument constructor and a 2-

argument constructor.

Answer

True

100 Python questions, one for each day of the challenge:


1 Print the length of the string "Hello, world!".

2 Print the sum of the numbers 1 and 2.

3 Print the Fibonacci sequence up to the 10th term.

4 Check whether a number is prime or not.

5 Find the factorial of a number.

6 Print a multiplication table for a given number.

7 Check whether a string is a palindrome or not.

8 Convert a temperature from Celsius to Fahrenheit.

9 Convert a temperature from Fahrenheit to Celsius.

10 Check whether a year is a leap year or not.

11 Write a function to check whether a string is a pangram or not.

12 Write a function to find the longest common substring of two strings.

13 Write a function to reverse a string.

14 Write a function to check whether a number is a perfect square or not.

15 Write a function to find the greatest common divisor (GCD) of two numbers.

16 Write a function to find the least common multiple (LCM) of two numbers.

17 Write a function to check whether a number is an Armstrong number or not.

18 Write a function to find the kth permutation of a given set of numbers.

19 Write a function to find the next lexicographical permutation of a given string.

20 Write a function to check whether a graph is bipartite or not.

21 Write a function to find the shortest path between two nodes in a graph.

22 Write a function to find the minimum spanning tree of a graph.

23 Write a function to find the diameter of a tree.

24 Write a function to check whether a tree is a binary search tree or not.

25 Write a function to insert a node into a binary search tree.

26 Write a function to delete a node from a binary search tree.

27 Write a function to search for a node in a binary search tree.

28 Write a function to find the inorder successor of a node in a binary search tree.

29 Write a function to find the preorder successor of a node in a binary search tree.

30 Write a function to find the postorder successor of a node in a binary search tree.

31 Write a function to find the level order traversal of a binary tree.

32 Write a function to find the height of a binary tree.

33 Write a function to check whether a binary tree is balanced or not.

34 Write a function to convert an infix expression to a postfix expression.

35 Write a function to convert a postfix expression to an infix expression.

36 Write a function to evaluate a postfix expression.

37 Write a function to find the maximum depth of a nested list.

38 Write a function to flatten a nested list.

39 Write a function to check whether a linked list is a palindrome or not.

40 Write a function to reverse a linked list.

41 Write a function to insert a node into a linked list.

42 Write a function to delete a node from a linked list.

43 Write a function to search for a node in a linked list.

44 Write a function to find the middle node in a linked list.

45 Write a function to find the nth node from the end of a linked list.

46 Write a function to merge two sorted linked lists.

47 Write a function to find the intersection point of two linked lists.

48 Write a function to find the union of two linked lists.

49 Write a function to check whether a linked list is circular or not.

50 Write a function to find the length of a linked list.

51 Write a function to find the median of a list of numbers.

52 Write a function to find the mode of a list of numbers.

53 Write a function to find the range of a list of numbers.

54 Write a function to find the variance of a list of numbers.

55 Write a function to find the standard deviation of a list of numbers.

56 Write a function to find the covariance of two lists of numbers.

57 Write a function to find the correlation coefficient of two lists of numbers.

58 Write a function to fit a linear regression model to a dataset.

59 Write a function to fit a logistic regression model to a dataset.

60 Write a function to perform k-means clustering on a dataset.

61 Write a function to implement the Naive Bayes classification algorithm.

62 Write a function to implement the Support Vector Machine (SVM) classification algorithm.

63 Write a function to implement the Random Forest classification algorithm.

64 Write a function to implement the K-Nearest Neighbors (KNN) classification algorithm.

65 Write a function to implement the Decision Tree classification algorithm.

66 Write a function to implement the Naive Bayes classification algorithm for spam filtering.

67 Write a function to implement the Support Vector Machine (SVM) classification algorithm for sentiment analysis.

68 Write a function to implement the Random Forest classification algorithm for image recognition.

69 Write a function to implement the K-Nearest Neighbors (KNN) classification algorithm for handwriting recognition.

70 Write a function to implement the Decision Tree classification algorithm for medical diagnosis.

71 Define a class to represent a bank account.

72 Define a class to represent a student.

73 Define a class to represent a book.

74 Define a class to represent an employee.

75 Define a class to represent a car.

76 Implement inheritance in a class hierarchy for animals.

77 Implement polymorphism in a class hierarchy for shapes.

78 Implement encapsulation in a class to represent a bank account.

79 Implement abstraction in a class to represent a

80 Implement a stack data structure using Python.

81 Implement a queue data structure using Python.

82 Implement a linked list data structure using

83 Implement a double-linked list data structure using Python.

84 Implement a circular linked list data structure using Python.

85 Implement a binary search tree data structure using Python.

86 Implement an AVL tree data structure using Python.

87 Implement a red-black tree data structure using Python.

88 Implement a hash table data structure using Python.

89 Implement a heap data structure using Python.

90 Implement a graph data structure using Python.

91 Implement a directed graph data structure using Python.

92 Implement a weighted graph data structure using Python.

93 Implement a breadth-first search algorithm for traversing a graph.

94 Implement a depth-first search algorithm for traversing a graph.

95 Implement Dijkstra's algorithm for finding the shortest path in a weighted graph.

96 Implement Kruskal's algorithm for finding the minimum spanning tree of a weighted graph.

97 Implement Prim's algorithm for finding the minimum spanning tree of a weighted graph.

98 Implement a sorting algorithm, such as bubble sort, insertion sort, merge sort, or quick sort.

99 Implement a searching algorithm, such as binary search or linear search.

100 Write a Python program to solve a real-world problem, such as building a simple web scraper, a text summarizer, or a financial data analyzer.

print ((False == False) in [False]) print (False == (False in [False])) print (False == False in [False])

 Code :

print(False == False) in [False]

print (False == (False in [False]))

print (False == False in [False])


Answer:

False
False
True

Solution and Explanation:

Let's go through each line:

print((False == False) in [False])
False == False is True.
The expression becomes True in [False].
Since True is not in the list [False], the final result is False.
The output for this line is False.

print(False == (False in [False]))
False in [False] is True.
The expression becomes False == True.
The output for this line is False.

print(False == False in [False])
This expression is equivalent to (False == False) and (False in [False]).
Both conditions are True.
The output for this line is True.




Python Coding challenge - Day 80 | What is the output of the following Python code?

 



Code :

list1 = ["1.0", "a", "0.1", "1", "-1"]

list2 = sorted(list1, key=lambda x: float(x) if x.isdigit() else float('inf'))

print(list2)

Answer : ['1', '1.0', 'a', '0.1', '-1']

Solution and Explanation: 

list1 = ["1.0", "a", "0.1", "1", "-1"]

This line creates a list named list1 and assigns it the values ["1.0", "a", "0.1", "1", "-1"].

list2 = sorted(list1, key=lambda x: float(x) if x.isdigit() else float('inf'))

This line creates a list named list2 and assigns it the sorted values of list1. The key argument specifies that the sorting should be done by converting the elements to floats if they are digits, and otherwise using the value float('inf'). This means that the strings "-1", "a", and "0.1" will be sorted as if they were the numbers -1, inf, and 0.1, respectively.

print(list2)

This line prints the value of list2 to the console.

Here is a table that summarizes the steps involved in sorting the list:

Step Action

1 Create a list named list1 and assign it the values ["1.0", "a", "0.1", "1", "-1"].

2 Create a list named list2 and assign it the sorted values of list1.

3 Sort list2 using the key argument, which specifies that the sorting should be done by converting the elements to floats if they are digits, and otherwise using the value float('inf').

4 Print the value of list2 to the console.


Tuesday, 28 November 2023

How many objects are created in the following code snippet?

 How many objects are created in the following code snippet?

a = 10

b = a

c = b

Answer : one 

a is assigned the value 10, creating an integer object with the value 10.

b is assigned the value of a, so it refers to the same integer object as a. No new object is created in this step; it just points to the existing object.

c is assigned the value of b, so it also refers to the same integer object as a and b. Again, no new object is created in this step.

a = 20 b = 40 print(globals( )) print(locals( ))

 Code :

a = 20

b = 40

print(globals( ))

print(locals( ))


Solution and Explanation: 

The globals() function returns a dictionary representing the current global symbol table, while the locals() function returns a dictionary representing the current local symbol table. When you print these dictionaries in your code, you'll see the global and local variables along with their values.

Here's the modified code:

a = 20
b = 40

print("Global variables:")
print(globals())

print("\nLocal variables:")
print(locals())

When you run this code, you will see the global and local variables along with their values. Keep in mind that the output might vary depending on where you run this code (e.g., in a script or an interactive environment like a Jupyter notebook).

Note: The locals() function inside a function or method will return the local symbol table of that function or method. If you run it in the global scope, it will return the same result as globals().

The output will typically look like this:

Global variables:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <...>, '__spec__': None, '__annotations__': {}, '__builtins__': <...>, '__file__': 'your_file_path', '__cached__': None, 'a': 20, 'b': 40}

Local variables:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <...>, '__spec__': None, '__annotations__': {}, '__builtins__': <...>, '__file__': 'your_file_path', '__cached__': None, 'a': 20, 'b': 40}


The dictionaries returned by globals() and locals() contain information about the global and local namespaces, respectively. In this case, the global variables a and b are included in both dictionaries. The keys in the dictionaries include special variables like __name__, __doc__, etc., along with your defined variables.

The output might vary slightly depending on where you run this code and the specific environment you are using.

Download YouTube videos using Python

 


Code : 


# Download YouTube videos using Python

pip install yt-dlp


import yt_dlp

# Enter the url for the download 

url = input("Enter video url: ")

ydl_opts = {}

with yt_dlp. YoutubeDL (yd1_opts) as ydl: 

      ydl.download ([url])

print("Video downloaded successfully!")

#clcoding.com

Enter video url: https://youtu.be/b1kbLwvqugk


Python code to find info about Chemical Formula

 


pip install pubchempy


import pubchempy as pcp


# Define the chemical formula of the hydrocarbon

chemical_formula = input("Enter chemical Formula : ")  

try:

    # Search PubChem for the compound by its chemical formula

    compound = pcp.get_compounds(chemical_formula, 'formula')[0]


    # Display information about the compound

    print(f"Name: {compound.iupac_name}")

    print(f"Common Name: {compound.synonyms[0]}")

    print(f"Molecular Weight: {compound.molecular_weight}")

    print(f"Formula: {compound.molecular_formula}")


    # You can access more properties as needed

except IndexError:

    print(f"No information found for {chemical_formula}.Please check formula.")


    #clcoding.com

Monday, 27 November 2023

Python Coding challenge - Day 79 | What is the output of the following Python code?

 


Code : 

import sys, getopt

sys.argv =['C:\\a.py', '-h', 'word1', 'word2']

options, arguments = getopt.getopt(sys.argv[1:],'s:t:h')

print(options)


Solution and Explanation:

This code outputs the following:

[('-h', '')]
The getopt.getopt() function takes two arguments:

The first argument is the sequence of arguments to be parsed. This is typically sys.argv[1:], which is a list of all the command-line arguments except for the program name.

The second argument is the option string. This is a string of characters, where each character represents an option. If an option requires an argument, the character is followed by a colon. For example, the option string "s:t:h" defines three options:

-s: This option requires an argument, which is stored in the optarg variable.
-t: This option requires an argument, which is stored in the optarg variable.
-h: This option does not require an argument.
The getopt.getopt() function returns a list of two-element tuples. Each tuple consists of an option character and its argument, if any. For example, the tuple ('-h', '') indicates that the -h option was specified without an argument.

In this case, the command-line arguments are ['C:\\a.py', '-h', 'word1', 'word2']. The option string is 's:t:h'. Therefore, the getopt.getopt() function returns the list [('-h', '')], which indicates that the -h option was specified without an argument.


How will you store a hexadecimal value E0A485 in a bytes data type?

 In Python, you can store a hexadecimal value like E0A485 in a bytes data type using the bytes.fromhex() method. Here's an example:

hex_value = "E0A485"

bytes_data = bytes.fromhex(hex_value)

print(bytes_data)

This code will output a bytes object representing the hexadecimal value:

b'\xe0\xa4\x85'

Each pair of hexadecimal digits is converted to its corresponding byte value in the bytes object. In this example, E0 becomes \xe0, A4 becomes \xa4, and 85 becomes \x85.

Python 101: 2nd Edition

 


The second edition of Python 101 (50,000+ eBook readers alone) uses Python 3 to teach you how to program successfully. This book can be read by people with no programming experience, although understanding basic computer terminology is recommended.


While Python 101 teaches you all the basics that you need to know, it also dives into many intermediate level topics too. This book is split up into four sections:

The Python Language

Intermediate Topics

Creating Sample Applications

Distributing Your Code


This book has been completely rewritten from the ground up. There are many new chapters and coverage of new features in Python 3.

Another new feature is that Python 101 has Review Questions for every chapter. The book also includes an answer key in the back.

Unlike most beginner Python books, Python 101 explains how to create simple applications. It also goes on to teach you how to distribute your code as a Windows executable.

Amazon Buy : Python 101: 2nd Edition 

Gumroad Buy : Python 101: 2nd Edition

c = "clcoding" print(c[:-2]) print(c[-2:])

 Code :

c = "clcoding"

print(c[:-2])

print(c[-2:])


Solution and Explanations: 

here are the step-by-step solutions:

Step 1:

Define the variable c and assign the string "clcoding" to it.

c = "clcoding"

Step 2:

Print the substring of c that starts at the beginning of the string and goes up to the second to last character. This can be done using the slicing syntax c[:-2].

print(c[:-2])

Output:

clcodi

Step 3:

Print the substring of c that starts at the second to last character and goes up to the end of the string. This can be done using the slicing syntax c[-2:].

print(c[-2:])

Output:

ng

State whether the following statements are True or False for Python Dictionaries

 a. Dictionary elements can be accessed using position-based index.

Answer

False

b. Dictionaries are immutable.

Answer

False

c. Insertion order is preserved by a dictionary.

Answer

False

d. The very first key - value pair in a dictionary d can be accessed using the

expression d[0].

Answer

False

e. courses.clear( ) will delete the dictionary object called courses.

Answer

False

f. It is possible to nest dictionaries.

Answer

True

g. It is possible to hold multiple values against a key in a dictionary.

Answer

True


Let's go through each statement one by one:


a. Dictionary elements can be accessed using position-based index.

Answer: False

Explanation: Dictionary elements are accessed using keys, not position-based indices. You use the key to retrieve the associated value.

b. Dictionaries are immutable.

Answer: False

Explanation: Dictionaries are mutable, meaning you can modify their content by adding, removing, or updating key-value pairs.

c. Insertion order is preserved by a dictionary.

Answer: False

Explanation: Prior to Python 3.7, dictionaries did not guarantee order preservation. However, starting from Python 3.7, the insertion order is guaranteed to be preserved.

d. The very first key-value pair in a dictionary d can be accessed using the expression d[0].

Answer: False

Explanation: Dictionary elements are not accessed by numerical indices but by keys. There is no guarantee that the keys are numerical, so attempting to access d[0] would not necessarily give you the first key-value pair.

e. courses.clear() will delete the dictionary object called courses.

Answer: False

Explanation: courses.clear() will remove all items from the dictionary called courses, but the dictionary object itself still exists.

f. It is possible to nest dictionaries.

Answer: True

Explanation: Yes, it is possible to have dictionaries as values within another dictionary, creating nested or hierarchical structures.

g. It is possible to hold multiple values against a key in a dictionary.

Answer: True

Explanation: Yes, a key in a dictionary can have a list, tuple, set, or another dictionary as its associated value, allowing you to store multiple values against a single key.


Python Coding challenge - Day 78 | What is the output of the following Python code?

 


Code : 

list1 = ["1.0", "a", "0.1", "1", "-1"]
list2 = sorted(list1)
print(list2)

Solution and Explanations 

The sorted function in Python sorts elements lexicographically (in dictionary order), which means strings are sorted based on their Unicode code points. In your example, the list list1 contains a mix of string representations of numbers and letters. When you use sorted(list1), it will sort the elements lexicographically:

list1 = ["1.0", "a", "0.1", "1", "-1"]
list2 = sorted(list1)
print(list2)
The output will be:
['-1', '0.1', '1', '1.0', 'a']

Here's the breakdown:

'-1' comes first because '-' has a lower Unicode code point than '0'.
'0.1' comes next because '0' has a lower code point than '1'.
'1' comes after '0.1'.
'1.0' comes after '1'.
'a' comes last because letters generally have higher Unicode code points than numbers.

If you want to sort the list based on numeric values, you may consider converting the elements to the appropriate numeric types before sorting. For example:

list1 = ["1.0", "a", "0.1", "1", "-1"]
list2 = sorted(list1, key=lambda x: float(x) if x.replace(".", "", 1).isdigit() else x)
print(list2)
This will output:

['-1', '0.1', '1', '1.0', 'a']
Here, the key argument is used to specify a custom sorting key. The lambda function checks if the string can be converted to a float (ignoring the first occurrence of a decimal point), and if so, it converts it to a float for sorting. This way, numeric values are sorted numerically, and non-numeric values are sorted lexicographically.


 Let's go step by step through the process:


Given Lists:
list1 = ["1.0", "a", "0.1", "1", "-1"]

Use sorted Function:
list2 = sorted(list1)
At this point, list2 is created by sorting the elements of list1 lexicographically.

list2 = ['-1', '0.1', '1', '1.0', 'a']
As explained earlier, the sorting is based on Unicode code points, so the order may not be numeric.

Printing the Result:
print(list2)

The output will be:
['-1', '0.1', '1', '1.0', 'a']
This output reflects the lexicographical sorting of the strings.

Custom Sorting for Numeric Values:
If you want to sort based on numeric values, you can use a custom sorting key. Here's how you can do it:

list2 = sorted(list1, key=lambda x: float(x) if x.replace(".", "", 1).isdigit() else x)
This lambda function checks if the string can be converted to a float (ignoring the first occurrence of a decimal point). If it can, it converts it to a float for sorting.

list2 = ['-1', '0.1', '1', '1.0', 'a']
The output is the same as the previous step because all values can be converted to floats, and they are sorted based on their numeric values.

This step-by-step explanation should clarify how the given list is sorted and how you can customize the sorting for numeric values.

Sunday, 26 November 2023

Numerical Python Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib (Free PDF)


 


Leverage the numerical and mathematical modules in Python and its standard library as well as popular open source numerical Python packages like NumPy, SciPy, FiPy, matplotlib and more. This fully revised edition, updated with the latest details of each package and changes to Jupyter projects, demonstrates how to numerically compute solutions and mathematically model applications in big data, cloud computing, financial engineering, business management and more.

Numerical Python, Second Edition, presents many brand-new case study examples of applications in data science and statistics using Python, along with extensions to many previous examples. Each of these demonstrates the power of Python for rapid development and exploratory computing due to its simple and high-level syntax and multiple options for data analysis.

After reading this book, readers will be familiar with many computing techniques including array-based and symbolic computing, visualization and numerical file I/O, equation solving, optimization, interpolation and integration, and domain-specific computational problems, such as differential equation solving, data analysis, statistical modeling and machine learning.

What You'll Learn

Work with vectors and matrices using NumPy

Plot and visualize data with Matplotlib

Perform data analysis tasks with Pandas and SciPy

Review statistical modeling and machine learning with statsmodels and scikit-learn

Optimize Python code using Numba and Cython

Who This Book Is For


Developers who want to understand how to use Python and its related ecosystem for numerical computing.

Buy : Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib


PDF Download : Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib


The Little Book of Deep Learning François Fleuret (Free PDF)

 


Unlock the Power of Deep Learning Embark on an extraordinary journey into the realm of cutting-edge technology with The Little Book of Deep Learning . Discover the secrets behind one of the most revolutionary advancements of our time, and witness how it is transforming industries across the globe. Explore the intricate world of neural networks and artificial intelligence as you delve into the minds of experts and pioneers. Gain unparalleled insights into the principles, algorithms, and applications of deep learning, unraveling complex concepts with ease. From image recognition to natural language processing, uncover the limitless possibilities that await you within these pages. Witness how deep learning is reshaping medicine, finance, entertainment, and more, igniting a new era of innovation. Written by a leading authority in the field, this captivating book distills the essence of deep learning, providing a comprehensive yet accessible guide for both beginners and seasoned professionals. Its engaging narrative and practical examples will empower you to harness the true potential of this transformative technology. Don't miss your chance to join the ranks of those who have unlocked the power of deep learning. Whether you're a student, researcher, or industry enthusiast, The Little Book of Deep Learning is your gateway to a world of unlimited possibilities.

Buy : The Little Book of Deep Learning


PDF Download : The Little Book of Deep Learning Free PDF



Python® Notes for Professionals book (Free PDF)

 


Getting started with Python Language

  1. Python Data Types
  2. Indentation
  3. Comments and Documentation
  4. Date and Time
  5. Date Formatting
  6. Enum
  7. Set
  8. Simple Mathematical Operators
  9. Bitwise Operators
  10. Boolean Operators
  11. Operator Precedence
  12. Variable Scope and Binding
  13. Conditionals
  14. Comparisons
  15. Loops
  16. Arrays
  17. Multidimensional arrays
  18. Dictionary
  19. List
  20. List comprehensions
  21. List slicing (selecting parts of lists)
  22. groupby()
  23. Linked lists
  24. Linked List Node
  25. Filter
  26. Heapq
  27. Tuple
  28. Basic Input and Output
  29. Files & Folders I/O
  30. os.path
  31. Iterables and Iterators
  32. Functions
  33. Defining functions with list arguments
  34. Functional Programming in Python
  35. Partial functions
  36. Decorators
  37. Classes
  38. Metaclasses
  39. String Formatting
  40. String Methods
  41. Using loops within functions
  42. Importing modules
  43. Difference between Module and Package
  44. Math Module
  45. Complex math
  46. Collections module
  47. Operator module
  48. JSON Module
  49. Sqlite3 Module
  50. The os Module
  51. The locale Module
  52. Itertools Module
  53. Asyncio Module
  54. Random module
  55. Functools Module
  56. The dis module
  57. The base64 Module
  58. Queue Module
  59. Deque Module
  60. Webbrowser Module
  61. tkinter
  62. pyautogui module
  63. Indexing and Slicing
  64. Plotting with Matplotlib
  65. graph-tool
  66. Generators
  67. Reduce
  68. Map Function
  69. Exponentiation
  70. Searching
  71. Sorting, Minimum and Maximum
  72. Counting
  73. The Print Function
  74. Regular Expressions (Regex)
  75. Copying data
  76. Context Managers (“with” Statement)
  77. The __name__ special variable
  78. Checking Path Existence and Permissions
  79. Creating Python packages
  80. Usage of "pip" module: PyPI Package Manager
  81. pip: PyPI Package Manager
  82. Parsing Command Line arguments
  83. Subprocess Library
  84. setup.py
  85. Recursion
  86. Type Hints
  87. Exceptions
  88. Raise Custom Errors / Exceptions
  89. Commonwealth Exceptions
  90. urllib
  91. Web scraping with Python
  92. HTML Parsing
  93. Manipulating XML
  94. Python Requests Post
  95. Distribution
  96. Property Objects
  97. Overloading
  98. Polymorphism
  99. Method Overriding
  100. User-Defined Methods
  101. String representations of class instances: __str__ and __repr__ methods
  102. Debugging
  103. Reading and Writing CSV
  104. Writing to CSV from String or List
  105. Dynamic code execution with `exec` and `eval`
  106. PyInstaller - Distributing Python Code
  107. Data Visualization with Python
  108. The Interpreter (Command Line Console)
  109. *args and **kwargs
  110. Garbage Collection
  111. Pickle data serialisation
  112. Binary Data
  113. Idioms
  114. Data Serialization
  115. Multiprocessing
  116. Multithreading
  117. Processes and Threads
  118. Python concurrency
  119. Parallel computation
  120. Sockets
  121. Websockets
  122. Sockets And Message Encryption/Decryption Between Client and Server
  123. Python Networking
  124. Python HTTP Server
  125. Flask
  126. Introduction to RabbitMQ using AMQPStorm
  127. Descriptor
  128. tempfile NamedTemporaryFile
  129. Input, Subset and Output External Data Files using Pandas
  130. Unzipping Files
  131. Working with ZIP archives
  132. Getting start with GZip
  133. Stack
  134. Working around the Global Interpreter Lock (GIL)
  135. Deployment
  136. Logging
  137. Web Server Gateway Interface (WSGI)
  138. Python Server Sent Events
  139. Alternatives to switch statement from other languages
  140. List destructuring (aka packing and unpacking)
  141. Accessing Python source code and bytecode
  142. Mixins
  143. Attribute Access
  144. ArcPy
  145. Abstract Base Classes (abc)
  146. Plugin and Extension Classes
  147. Immutable datatypes(int, float, str, tuple and frozensets)
  148. Incompatibilities moving from Python 2 to Python 3
  149. 2to3 tool
  150. Non-official Python implementations
  151. Abstract syntax tree
  152. Unicode and bytes
  153. Python Serial Communication (pyserial)
  154. Neo4j and Cypher using Py2Neo
  155. Basic Curses with Python
  156. Templates in python
  157. Pillow
  158. The pass statement
  159. CLI subcommands with precise help output
  160. Database Access
  161. Connecting Python to SQL Server
  162. PostgreSQL
  163. Python and Excel
  164. Turtle Graphics
  165. Python Persistence
  166. Design Patterns
  167. hashlib
  168. Creating a Windows service using Python
  169. Mutable vs Immutable (and Hashable) in Python
  170. configparser
  171. Optical Character Recognition
  172. Virtual environments
  173. Python Virtual Environment - virtualenv
  174. Virtual environment with virtualenvwrapper
  175. Create virtual environment with virtualenvwrapper in windows
  176. sys
  177. ChemPy - python package
  178. pygame
  179. Pyglet
  180. Audio
  181. pyaudio
  182. shelve
  183. IoT Programming with Python and Raspberry PI
  184. kivy - Cross-platform Python Framework for NUI Development
  185. Pandas Transform: Preform operations on groups and concatenate the results
  186. Similarities in syntax, Differences in meaning: Python vs. JavaScript
  187. Call Python from C#
  188. ctypes
  189. Writing extensions
  190. Python Lex-Yacc
  191. Unit Testing
  192. py.test
  193. Profiling
  194. Python speed of program
  195. Performance optimization
  196. Security and Cryptography
  197. Secure Shell Connection in Python
  198. Python Anti-Patterns
  199. Common Pitfalls
  200. Hidden Features
  201. Example book pages

Download : Python® Notes for Professionals book





Its hard to believe, but the best 6 machine learning books are completely free:

 



- Deep Learning - https://lnkd.in/gxpnZ6Sa

- Dive into Deep Learning - d2l.ai

- Machine Learning Engineering - https://lnkd.in/eVCAYh4

- Python Data Science Handbook - https://lnkd.in/ehfZ-Tx

- Probabilistic Machine Learning - https://lnkd.in/gcSBFgk

- Machine Learning Yearning - https://lnkd.in/d3bC2d2R

Approaching (Almost) Any Machine Learning Problem (PDF Book)

 


This book is for people who have some theoretical knowledge of machine learning and deep learning and want to dive into applied machine learning. The book doesn't explain the algorithms but is more oriented towards how and what should you use to solve machine learning and deep learning problems. The book is not for you if you are looking for pure basics. The book is for you if you are looking for guidance on approaching machine learning problems. The book is best enjoyed with a cup of coffee and a laptop/workstation where you can code along.


Table of contents:

- Setting up your working environment

- Supervised vs unsupervised learning

- Cross-validation

- Evaluation metrics

- Arranging machine learning projects

- Approaching categorical variables

- Feature engineering

- Feature selection

- Hyperparameter optimization

- Approaching image classification & segmentation

- Approaching text classification/regression

- Approaching ensembling and stacking

- Approaching reproducible code & model serving


There are no sub-headings. Important terms are written in bold.


I will be answering all your queries related to the book and will be making YouTube tutorials to cover what has not been discussed in the book. To ask questions/doubts, please create an issue on github repo: https://github.com/abhishekkrthakur/approachingalmost

Buy Link : Approaching (Almost) Any Machine Learning Problem 


PDF Link : Approaching (Almost) Any Machine Learning Problem



The Principles of Deep Learning Theory (Free PDF)

 

This textbook establishes a theoretical framework for understanding deep learning models of practical relevance. With an approach that borrows from theoretical physics, Roberts and Yaida provide clear and pedagogical explanations of how realistic deep neural networks actually work. To make results from the theoretical forefront accessible, the authors eschew the subject's traditional emphasis on intimidating formality without sacrificing accuracy. Straightforward and approachable, this volume balances detailed first principle derivations of novel results with insight and intuition for theorists and practitioners alike. This self contained textbook is ideal for students and researchers interested in artificial intelligence with minimal prerequisites of linear algebra, calculus. informal probability theory. it can easily fill a semester long course on deep learning theory. For the first time, the exciting practical advances in modern artificial intelligence capabilities can be matched with a set of effective principles, providing a timeless blueprint for theoretical research in deep learning. 

Book Buy : The Principles of Deep Learning Theory: An Effective Theory Approach to Understanding Neural Networks


Book Main page : https://arxiv.org/abs/2106.10165


PDF Link : https://arxiv.org/pdf/2106.10165.pdf

10 BOOKS THAT WILL BOOST YOUR PRODUCTIVITY!

 













10 BOOKS THAT WILL BOOST YOUR PRODUCTIVITY!

1. Focus on What Matters: A Collection of Stoic Letters on Living Well https://amzn.to/3RgjAJe

2. How to Finish Everything You Start https://amzn.to/3N1KtOr

3. Do It Today: Overcome Procrastination, Improve Productivity, and Achieve More Meaningful Things https://amzn.to/3uDL9mK

4. Atomic Habits: An Easy and Proven Way to Build Good Habits and Break Bad Ones https://amzn.to/49UM3vy

5. Deep Work: Rules for Focused Success in a Distracted World https://amzn.to/3T0lPSo

6. Attention Span: Finding Focus for a Fulfilling Life https://amzn.to/3uv1Lgx


8. Do Epic Shit https://amzn.to/3QZfaFc

9. Do the Hard Things First: How to Win Over Procrastination and Master the Habit of Doing Difficult Work (Bulletproof Mindset Mastery Series https://amzn.to/47Nry1Z

10. Do the Impossible: How to Become Extraordinary and Impact the World at Scale (Becoming Extraordinary, Book 1) https://amzn.to/3Ghgrm7

Match the following for the each values !!

 


Answer

tpl1 = ('A',) - Tuple

tpl1 = ('A') - String

t = tpl[::-1] - Sorts tuple

('A', 'B', 'C', 'D') - tuple of strings

[(1, 2), (2, 3), (4, 5)] - list of tuples

tpl = tuple(range(2, 5)) - (2, 3, 4)

([1, 2], [3, 4], [5, 6]) - tuple of lists

t = tuple('Ajooba') - tuple of length 6


Explanation: 

tpl1 = ('A',) - This creates a tuple named tpl1 containing a single element 'A'. Note the comma after 'A', which is essential for creating a tuple with a single element.


tpl1 = ('A') - This actually creates a string, not a tuple. To create a tuple with a single element, you need to include a comma: tpl1 = ('A',).


t = tpl[::-1] - This reverses the order of elements in the tuple tpl. The [::-1] slicing notation is used to reverse the sequence.


('A', 'B', 'C', 'D') - This is a tuple of strings with four elements: 'A', 'B', 'C', and 'D'.


[(1, 2), (2, 3), (4, 5)] - This is a list of tuples, where each tuple contains two integers.


tpl = tuple(range(2, 5)) - This creates a tuple named tpl with elements generated using range(2, 5), resulting in the tuple (2, 3, 4).


([1, 2], [3, 4], [5, 6]) - This is a tuple of lists, where each list contains two integers.


t = tuple('Ajooba') - This creates a tuple named t from the characters of the string 'Ajooba'. The resulting tuple has six elements, one for each character.

Saturday, 25 November 2023

Python Programming for Data Analysis (Free PDF)

 


This textbook grew out of notes for the ECE143 Programming for Data Analysis class that the author has been teaching at University of California, San Diego, which is a requirement for both graduate and undergraduate degrees in Machine Learning and Data Science. This book is ideal for readers with some Python programming experience. The book covers key language concepts that must be understood to program effectively, especially for data analysis applications. Certain low-level language features are discussed in detail, especially Python memory management and data structures. Using Python effectively means taking advantage of its vast ecosystem. The book discusses Python package management and how to use third-party modules as well as how to structure your own Python modules.  The section on object-oriented programming explains features of the language that facilitate common programming patterns.

After developing the key Python language features, the book moves on to third-party modules that are foundational for effective data analysis, starting with Numpy. The book develops key Numpy concepts and discusses internal Numpy array data structures and memory usage. Then, the author moves onto Pandas and details its many features for data processing and alignment. Because strong visualizations are important for communicating data analysis, key modules such as Matplotlib are developed in detail, along with web-based options such as Bokeh, Holoviews, Altair, and Plotly.


The text is sprinkled with many tricks-of-the-trade that help avoid common pitfalls. The author explains the internal logic embodied in the Python language so that readers can get into the Python mindset and make better design choices in their codes, which is especially helpful for newcomers to both Python and data analysis. 

To get the most out of this book, open a Python interpreter and type along with the many code samples.

Buy : Python Programming for Data Analysis 

PDF Download : 


Python Coding challenge - Day 77 | What is the output of the following Python code?

 

Code : 


def fun(a, *args, s='!'):
    print(a, s)
    for i in args:
        print(i, s)

fun(10)

Solution and Explanation: 

Function Definition:

def fun(a, *args, s='!'):

The function fun is defined to take at least one argument a, followed by any number of additional positional arguments (*args), and an optional keyword argument s with a default value of '!'.


Print the First Argument and Suffix:

print(a, s)

This line prints the value of the first argument a followed by the value of the keyword argument s.


Loop through Additional Arguments:

for i in args:

    print(i, s)

This loop iterates through any additional positional arguments provided (if any) and prints each one followed by the value of the keyword argument s.


Function Call:

fun(10)

The function is called with the argument 10. Since no additional positional arguments are provided, only the first print statement is executed.


When you run this code, it will output:

10 !

What will be the output of the following Python code ?

Code : 

s = [a + b for a in ['They ', 'We '] for b in ['are gone!', 'have come!']]

print(s)


Solution and Explanation :  

This code uses list comprehension to create a list s by concatenating elements from two nested lists. Here's the breakdown:

s = [a + b for a in ['They ', 'We '] for b in ['are gone!', 'have come!']]

Two nested for loops are used in the list comprehension.

The outer loop iterates over elements a in the list ['They ', 'We '].

The inner loop iterates over elements b in the list ['are gone!', 'have come!'].

The expression a + b concatenates the current elements from both loops.

The result is a new list s containing all possible concatenations of elements from the outer and inner loops.

If you print the list s, you will get:

['They are gone!', 'They have come!', 'We are gone!', 'We have come!']

This is because it combines each element from the first list with each element from the second list, resulting in all possible combinations.

a = set() for n in range(21, 30): if n % 2 == 0: a.add(n) print(a)

 Code : 

a = set()

for n in range(21, 30):

    if n % 2 == 0:

        a.add(n)

print(a)

Solution and Explanation:

Let's break down the code step by step:

Initialize an empty set:

a = set()

A new empty set named a is created.

Loop through a range of numbers (21 to 29):

for n in range(21, 30):

The for loop iterates over the numbers from 21 to 29 (inclusive).

Check if the number is even:

if n % 2 == 0:

The if statement checks if the current number (n) is even by using the modulo operator (%) to check if it's divisible by 2.


Add even numbers to the set:

a.add(n)

If the condition in the if statement is true (meaning n is even), the current even number is added to the set a using the add method.


Print the set after the loop:

print(a)

The print(a) statement is outside the for loop, so it will be executed after the loop has finished. It prints the final contents of the set a.

In summary, when you run this code, it will output the set of even numbers between 21 and 29. In this specific case, the set a will contain the even numbers 22, 24, 26, and 28.


In one line : a = {n for n in range(21, 30) if n % 2 == 0}






State whether the following statements are True or False in Python

 



a. Tuple comprehension offers a fast and compact way to generate a tuple.

Answer

True

b. List comprehension and dictionary comprehension can be nested.

Answer

True

c. A list being used in a list comprehension cannot be modified when it is

being iterated.

Answer

True

d. Sets being immutable cannot be used in comprehension.

Answer

False

e. Comprehensions can be used to create a list, set or a dictionary.

Answer

True

Introduction to Artificial Intelligence (AI)

 


What you'll learn

Describe what is AI, its applications, use cases, and how it is transforming our lives

Explain terms like Machine Learning, Deep Learning and Neural Networks 

Describe several issues and ethical concerns surrounding AI

Articulate advice from experts about learning and starting a career in AI 

There are 4 modules in this course

In this course you will learn what Artificial Intelligence (AI) is, explore use cases and applications of AI, understand AI concepts and terms like machine learning, deep learning and neural networks. You will be exposed to various issues and concerns surrounding AI such as ethics and bias, & jobs, and get advice from experts about learning and starting a career in AI.  You will also demonstrate AI in action with a mini project.

This course does not require any programming or computer science expertise and is designed to introduce the basics of AI to anyone whether you have a technical background or not. 

Join Free  - Introduction to Artificial Intelligence (AI)

Popular Posts

Categories

100 Python Programs for Beginner (51) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) 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 (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (358) Python Quiz (22) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

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