Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Basics of PYTHON(DSA)
Description: PYTHON,DSA ,that is data structures and algorithms of python control statments, numpy
Description: PYTHON,DSA ,that is data structures and algorithms of python control statments, numpy
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Data Types and Operators
Welcome to this lesson on Data Types and Operators! You'll learn about:
● Data Types: Integers, Floats, Booleans, Strings, Lists, Tuples, Sets,
Dictionaries
● Operators: Arithmetic, Assignment, Comparison, Logical, Membership,
Identity
● Built-In Functions, Compound Data Structures, Type Conversion
● Whitespace and Style Guidelines
1
...
It helps
us to see what exactly is happening in our code
...
Now this happens because you haven't told python what to alctually do with it
...
print() in python is a useful builtin function that we
can use to display input value as text in the output
...
Arithmetic Operators
An arithmetic operator is a mathematical function that takes 2 operands and
performs a calculation on them
...
Python has several arithmetic operators most of which follow the
usual rules of mathematics
...
● + Addition
● - Subtraction
● * Multiplication
● / Division
● % Mod (the remainder after dividing)
● ** Exponentiation (note that ^ does not do this operation, as you might have
seen in other languages)
● // Divides and rounds down to the nearest integer
[ Now sometime people might confuse this (^)Caret symbol for Exponentiation as
you might have seen it in other languages but in python this symbol is used to do
bitwise XOR operation
...
]
Task:
Now perform all the arithematic operations on the numbers 7 and 2
...
5
1
49
3
3
...
Look at this mathematical equation (2+3*5) what do you think will be the answer 25
or 17
...
● Brackets
● Exponents
● Division and Multiplication (left to right)
● Addition and Substraction (left to right)
Preference given to the operator that comes first in BEDMAS
...
Your net expenditure for the
past 5 months has been 1200, 2000, 800, 1500 and 1700
...
[]
# write your code here
Expected output:
1440
...
Two rooms in a house needs to be
filled
...
Tiles come in
packages of 7 and each tile is 1ftx1ft in size
1) How many tiles are needed?
2) You buy 17 packages each containing 6 tiles each
...
# write the code that calculates how many tiles will be left over
...
Variables:
Understanding variables is very important in any programming language they are
used all the time in python
...
Variables are used to store information to be referenced and
manipulated in a computer program
...
[]
month=12
print(month)
Now its your turn create a variable named rent with its value being 1700
[]
# create and print the varibale rent down below
Expected output:
1700
In any case, whatever term is on the left side, is now a name for whatever value is on
the right side
...
For example if we run this code we will get 3 as the output here as in the first line we
assigned 3 to a and in the second line we assigned a to b so when we print b we get
3 as the output
...
Multiple Assignment Operator:
Suppose you are making a program where in you enter the dimensions of the tank
and it will give the volume of the tank as the output
...
height , length , width = 3 , 6 , 2
volume = height * length * width
print(volume)
ou can use this when you are assigning closely related variables such as height
width length or coordinates such as x, y , z of an object
...
length = squareroot(x^2 + y^2 + z^2)
[]
# write your code here
Expected output:
8
...
Variable Naming Conventions:
There are some rules we need to follow while giving a name for a Python variable
...
● Rule-2: A variable name can only contain A-Z,a-z,0-9 and underscore(_)
...
● Rule-4: You cannot use special characters with the variable name such as
such as $,%,#,&,@
...
● Rule-5: Variable names are case sensitive
...
● Rule-6: Do not use reserve keyword as a variable name for example keywords
like class, for, def, del, is, else, try, from, etc
...
Creating
names that are descriptive of the values often will help you avoid using any of
these words
...
#It will execute one by one and will show the error
...
for
example: when taking inputs for the height of a tree of a box the appropriate
variable name will be just height not x not h not height_of_the_tree
...
[]
# pythonic way
my_height = 58
my_lat = 40
my_long = 105
[]
# not pythonic way
my height = 58 # wont work
MYLONG = 40 # will work still avoid using it
MyLat = 105 # will work still avoid using it
Though the last two of these would work in python, they are not pythonic ways to
name variables
...
What if we want to change or update the value of a variable for example take the
example of rent = 1700, suppose the rent has hiked and the new rent is 2000 we can
just assign the variable its new value as:
[]
rent = 1700
rent = 2000
print(rent)
This is called overwriting the variable , i
...
If we had then caused some damages to the property during our crazy house party
and we have to pay for them then we can just apply these changes directly to this
variable
...
Because such increment and assignment operations are very common python has a
very special assignment operator for this
...
+= is a example of assignment operator -=
*= /= are some more examples of assignment operators
...
Question:
You are managing your finances using python:
● complete the tasks mentioned in the comments
...
Note that this code uses scientific notation to define large numbers
...
2e6 is
equal to 1
...
[]
# the amount of money in your bank account is 1
...
2e6
# money recieved every year in form of salary
salary = 9
...
# Add the salary to the bank account amt variable
# increase the amt by 4% that you recieved from the bank as intrest
# substract 1
...
0
7
...
For example
dividing one integer by another gives us a number that isn't an integer, in python we
represent such a number as a float, which is short for floating point number
...
14, are called floating-point numbers (or
floats)
...
0 would be a
floating-point number
...
You can check the datatype of any value by using the builtin function of type, that
returns the type of an object
...
[]
a=3
b = 2
...
We can
also covert one datatype to another by constructing new objects of those types with
int and float
...
eg 28
...
Similarly converting int to float just adds a decimal at the end of the number and a 0
after that
...
0
[]
a = float(3)
b = int(28
...
As float can represent very large range of numbers
python must use approximation to represent these numbers
...
23 is in reality slightly more than 0
...
such that if we
add up 0
...
Although the difference is very small but it exists
never the less and you should know about it
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
23 + 0
...
9)
8
...
[]
print(4/0)
what you should have seen when you submitted the Divide by Zero code above,
Traceback means
*"What was the programming doing when it broke"! *
This part is usually less helpful than the very last line of your error
...
Python is enforcing the rules of arithmetic!
In general, there are two types of errors to look out for
● Exceptions
● Syntax
An Exception is a problem that occurs when the code is running, but a 'Syntax Error'
is a problem detected when Python checks the code before it runs it
...
9
...
Bool is short for Boolean
which can have a value of either True or False
...
Boolean algebra us the framework on which all electronic devices and built and
exists fundamentally in every line of code inside a computer
...
There are many comparison operators in python, as you can see here are all of them
...
Working with boolean has its own set of operators called as logical operators
...
Lets understand if via an example:
[]
rent = 1200
is_affordable = rent > 1000 and rent < 2000
print(is_affordable)
Here we check if the rent of a house is affordable or not, here in the second line we
evaluate both the sides ie rent > 1000, yes, so it is true while the second condition is
rent < 200, that too is true
...
In
other words if the rent is greater than 1000 and less than 2000 then only it is
affordable
...
[]
mum_population, mum_area = 20411000, 4355
del_population, del_area = 30291000, 1484
mum_francisco_pop_density = mum_population/mum_area
del_de_janeiro_pop_density = del_population/del_area
# Print True if Mumbai is denser than Delhi, and False otherwise
Expected output:
False
10
...
String is a immutable order of
sequences of characters (eg, Letters, numbers, spaces and symbols
...
You can create a string by using quotes as seen here, you can use either single /
double quotes they both work equally well but there are some cases where you
might prefer one over the other which we will be discussing below
...
We can also assign a string to a variable just like float and int
...
[]
type(motto)
String can contain any character number symbol space within the quotes
...
[]
dialogue = "shiva said, "you learn as you grow""
Python provides 2 easy ways to handle such problem:
1
...
This will solve
your problem for having double quotes within the string
...
[]
dialogue = 'shiva said, "you learn as you grow"'
print(dialogue)
2
...
The backslash helps python to know that the the single quote
should be interpreted as part of the string rather than the quote that ends the
string
...
For example we can use the '+' to combine / concatenate 2 strings together
and we can use '*' to repeat the string let us look at an example for each
...
We can
add another string containing just a space in between the words to do so
...
However unlike multiplication and addition operators the other arithmetic operators
like division and subtraction cannot be used on strings any attempt to do so would
result in an error that string is an unsupported datatype for the division/subtraction
operator
...
As the
name suggests (it returns the length of an object ie
...
It takes in values in a parenthesis and returns the length of the string
...
The len() function outputs a value 7 that is then stored in a
variable called as word_length which is then printed out
...
First run it with Test Run to view the error message
...
[]
# TODO: Fix this string!
gandhi_quote = 'If you don't ask, you don't get it'
Question:
In this question you have to print the accuracy logs of a model in training
...
98"
# TODO: print a log message using the variables above
# This message should have the same format as this one:
# "the accuracy of ResNET50 model in 100th iteration is: 42
...
As a business card designer find if the name can fit into a business card
...
Type and Type Conversion Revision:
Till now we have covered 4 different datatypes int, float, bool and string
...
[]
print(type(75))
print(type(75
...
This is to note that here we have called the function print on another function type to
output the return value of the function type
...
here it will be type
...
There might be sometimes when you don't have the control over the type of the data
being provided to you like one that has been received from a user as in input
...
As we had previously seen in the integers and
floats video
...
0 from an int 3 and assigned it to a
new variable called decimal
[]
decimal = float(3)
print(decimal)
print(type(decimal))
In this next example we created a string from the integer variable marks and
used that to create a larger string
...
"
print(result)
we can also create an float from string
[]
marks = "15"
print(type(marks))
marks = float(marks)
print(type(marks))
Question:
In this quiz, you’ll need to change the types of the input and output data in order to
get the result you want
...
Print out a
string of the form "This week's total sales: xxx", where xxx will be the actual total of
all the numbers
...
[]
mon_sales = "121"
tues_sales = "105"
wed_sales = "110"
thurs_sales = "98"
fri_sales = "95"
#TODO: Print a string with this format: This week's total sales: xxx
# You will probably need to write some lines of code before the print statement
...
String Methods:
Methods are like some of the functions you have already seen:
● len("this")
● type(12)
● print("Hello world")
These three above are functions - notice they use parentheses, and accept one or
more arguments
...
Methods actually are functions
that are called using dot notation
...
lower()
...
So there are some
built-in methods that are available for all strings, different methods that are available
for all integers, etc
...
Each of these methods accepts the string itself as the first argument of the method
...
Let's look at the output for a few examples
...
islower())
print(my_string
...
find('a'))
You can see that the count and find methods both take another argument
...
islower() method does not accept another argument
...
Gaining a strong grasp of the
foundations of programming will allow you to use those foundations to use
documentation to build so much more than someone who tries to memorize all the
built-in methods in Python
...
a
...
We can best illustrate how to use format() by looking at some examples:
[]
# Example 1
print("EG:1")
print("Mohammed has {} balloons"
...
format(animal, action))
# Example 3
print("EG:3")
maria_string = "Maria loves {} and {}"
print(maria_string
...
More advanced students can learn more about the formal syntax for using the
format() string method here
...
Lists and Membership Operators:
Data structures are containers that organize and group data types together in
different ways
...
It is a mutable ordered sequence of elements
...
Each
element in the list is a string that signifies the name of a student
...
[]
students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner']
List are ordered, we can look up individual elements by their index, we can look
elements from a list just like we have done below
...
We can also access the elements from the end of the list using negative index as
seen in the examples below
...
[]
print(students[20])
Question:
Try to use len() to pull the last element from the above list
[]
# TODO: write your code here
students[len(students)-1]
13
...
Membership Operators:[Lists]
In addition to accessing individual elements froma a list, we can use pythons
sliceing notation to access a subsequence of a list
...
Look at an
example
[]
students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce',
'henry', 'clark', 'diana']
student = "Barry"
# slice a particular range
marvel = students[4:7]
flash = student[1:3]
print(marvel)
print(flash)
[]
# slice from the end
dc = students[7:]
flash = student[1:]
print(dc)
print(flash)
[]
# slice from the begining
normal = students[:4]
flash = student[:3]
print(normal)
print(flash)
[]
# length of the list and the string
print(len(students))
print(len(student))
Of the types we have seen lists are most familier to strings, both supports the len()
function, indexing and slicing
...
Another thing that they both supports aare membership operators:
● in: evaluates if an object on the left side is included in the object on the right
side
...
[]
greeting = "Hello there"
print('her' in greeting, 'her' not in greeting)
[]
print('ShapeAI' in students, 'ShapeAI' not in students)
13
...
Mutability and Order:
So how are Lists diffrent from Strings, both supporst slicing, indexing, in and not in
operators
...
A more important diference is that lists can be modified but string can't
...
[]
students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce',
'henry', 'clark', 'diana']
students[2] = 'ben'
print(students)
[]
student = "Barry"
student[1] = "e"
print(student)
Mutability is about whether or not we can change an object once it has been
created
...
However, if an object cannot be changed without creating a
completely new object (like strings), then the object is considered immutable
...
Both strings and lists are ordered
...
However, you will see some data types in the next sections that will be
unordered
...
Knowing
this about the data structure is really useful!
Additionally, you will see how these each have different methods, so why you would
use one data structure vs
...
Like as you can see below
[]
student = "pam"
character = student
print(character)
character = "peter"
print(character)
print(student)
Lists are diffrent from strings as they are mutable as can be seen from the example
below
[]
students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce',
'henry', 'clark', 'diana']
characters = students
print(characters)
characters[1]= "peter"
print(characters)
print(students)
There are some useful functions for lists that you should get familier with
...
len(): returns how many elements does the list has
...
max(): returns the greatest element of a list
...
min(): returns the smallest element of a list
...
sorted(): returns a copy of the list, in order from smallest to the largest
...
[]
students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce',
'henry', 'clark', 'diana']
student = "barry"
print(max(students))
print(max(student))
a point to note is that even though you can have a list cntaining int and string a
max function will be undefined upon such a list
...
Look at the example below to understand
...
join(["Jack", "O", "Lantern"])
print(sep_str)
In this example we use the string "\n" as the separator so that there is a newline
between each element
...
join
...
[]
name = "-"
...
Forgetting to do so will not trigger an error, but will
also give you unexpected results
...
[]
letters = ['a', 'b', 'c', 'd']
letters
...
Tuples:
A tuple is another useful container
...
They are often used to store related pieces of information
...
Unlike lists, however, tuples are immutable - you
can't add and remove items from tuples, or sort them in place
...
The parentheses are optional when defining tuples, and programmers
frequently omit them if parentheses don't clarify the code
...
7774, 92
...
format(latitude, longtitude))
In the second line, two variables are assigned from the content of the tuple location
...
You can use tuple unpacking to assign the
information from a tuple into multiple variables without having to access them one
by one and make multiple assignment statements
...
7774, 92
...
format(latitude, longtitude))
15
...
One
application of a set is to quickly remove duplicates from a list
...
You can add elements to sets
using the add method, and remove elements using the pop method, similar to lists
...
Remember that sets, unlike lists, are unordered so there is no "last element"
...
add("watermelon") # add an element
print(fruit)
print(fruit
...
Dictionaries and Identity Operators:
A dictionary is a mutable data type that stores mappings of unique keys to values
...
[]
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
Dictionaries can have keys of any immutable type, like integers or tuples, not just
strings
...
[]
print(elements["helium"]) # print the value mapped to "helium"
elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary
We can check whether a value is in a dictionary the same way we check whether a
value is in a list or set with the in keyword
...
get() looks up values in a dictionary, but unlike square brackets, get
returns None (or a default value of your choice) if the key isn't found
...
get("dilithium"))
Carbon is in the dictionary, so True is printed
...
If you expect lookups to sometimes fail,
get might be a better tool than normal square bracket lookups because errors can
crash your program
...
a
...
You can check for the
opposite using is not
...
get("dilithium")
print(n is None)
print(n is not None)
Task:
Define a dictionary named population that contains this data:
Keys -> Values
New York -> 17
...
3
Dhaka -> 13
...
5
[]
population = {"New York":17
...
3, "Dhaka":13
...
5}
print(population)
16
...
Get() with a Default Value:
Dictionaries have a related method that's also useful, get()
...
If you expect lookups to
sometimes fail, get() might be a better tool than normal square bracket lookups
...
get('London'))
[]
population['London']
[]
population
...
16
...
Compound Data Structures:
Previously we have seen a dictonary called elements in which the element names
are maped to their atomic numbers which are integers
...
We can
do that by adjusting this dictionary so that it maps the element names to an other
dictionary, that stores that collection of data
...
00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4
...
[]
helium = elements["helium"] # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"] # get hydrogen's weight
print(helium)
print(hydrogen_weight)
You can also add a new key to the element dictionary
...
999,"symbol":"O"} # create a new oxygen dictionary
elements["oxygen"] = oxygen # assign 'oxygen' as a key to the elements dictionary
print('elements = ', elements)
Question:
Try your hand at working with nested dictionaries
...
After inserting the new entries you
should be able to perform these lookups:
print(elements['hydrogen']['is_noble_gas'])
False
print(elements['helium']['is_noble_gas'])
True
[]
elements = {'hydrogen': {'number': 1, 'weight': 1
...
002602, 'symbol': 'He'}}
# todo: Add an 'is_noble_gas' entry to the hydrogen and helium dictionaries
# hint: helium is a noble gas, hydrogen isn't
elements['helium']['is_noble_gas'] = True
elements['hydrogen']['is_noble_gas'] = False
Control Flow:
Welcome to this lesson on Control Flow! Control flow is the sequence in which your
code is run helping you in decision making
...
For
example suppose that you have subscribed to a sharebike rental service
...
The app contains a credit balance
which then the user can use to rent the bikes
...
100, then
Rs
...
this can be represented as in below:
if bikeapp_balance < 100:
bikeapp_balance += 500
bank_balance -= 500
[]
bikeapp_balance = 99
bank_balance = 1000
print(bikeapp_balance, bank_balance)
if(bikeapp_balance<100):
bikeapp_balance += 500
bank_balance -= 500
print(bikeapp_balance, bank_balance)
99 1000
599 500
● An if statement starts with the if keyword, followed by the condition to be
checked, in this case bikeapp_balance < 100, and then a colon
...
● After this line is an indented block of code to be executed if that condition is
true
...
If
not, the code in this if block is simply skipped
...
g
...
g
...
For example, you'd want to
use if x == 5 rather than if x = 5
...
Lets see it in action using an example:
[]
n=4
if (n%2 == 0):
print("Number " + str(n) + " is even
...
")
Number 4 is even
...
Lets look
at an example:
[]
season = 'fall'
if season == 'spring':
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
harvest the garden!
Summarize If, Elif, Else:
1
...
If this evaluates to True, Python runs the code
indented in this if block and then skips to the rest of the code after the if
statement
...
elif: elif is short for "else if
...
As you can see in the example, you can have multiple elif blocks to
handle different situations
...
else: Last is the else clause, which must come at the end of an if statement if
used
...
The code in an else block is run
if all conditions above that in the if statement evaluate to False
...
Marks -> Grade
100-90 -> A+
90-80 -> A
80-70 -> B
70-60 -> C
60-50 -> D
50-40 -> E
<40 -> F
All of the lower and upper bounds here are inclusive, and marks can only take
on positive integer values up to 100
...
"you have scored *[Grade]* Grade
...
The
states of CA, MN, and NY have taxes of 7
...
5%, and 8
...
Use this
information to take the amount of a purchase and the corresponding state to assure
that they are taxed by the right amount
...
075
total_cost = purchase_amount*(1+tax_amount)
result = "Since you're from {}, your total cost is {}
...
095
total_cost = purchase_amount*(1+tax_amount)
result = "Since you're from {}, your total cost is {}
...
089
total_cost = purchase_amount*(1+tax_amount)
result = "Since you're from {}, your total cost is {}
...
They may contain multiple comparisons operators, logical operators, and
even calculations
...
5 <= (weight / height**2) < 25:
print("BMI is considered 'normal'")
if is_raining and is_sunny:
print("Is there a rainbow?")
if (not unsubscribed) and (location == "USA" or location == "IND"):
print("send email")
For really complicated conditions you might need to combine some ands, ors and
nots together
...
However simple or complex, the condition in an if statement must be a boolean
expression that evaluates to either True or False and it is this value that decides
whether the indented block in an if statement executes or not
...
1
...
Similarly, if False
is not a condition you should use either - the statement following this if statement
would never be executed
...
")
Similarly, it's useless to use any condition that you know will always evaluate to True,
like this example above
...
# Another bad example
if is_cold or not is_cold:
print("This indented code will always get run
...
Be careful writing expressions that use logical operators:
Logical operators and, or and not have specific meanings that aren't quite the same
as their meanings in plain English
...
# Bad example
if weather == "snow" or "rain":
print("Wear boots!")
This code is valid in Python, but it is not a boolean expression, although it reads like
one
...
3
...
# Bad example
if is_cold == True:
print("The weather is cold!")
This is a valid condition, but we can make the code more readable by using the
variable itself as the condition instead, as below
...
Truth Value Testing:
If we use a non-boolean object as a condition in an if statement in place of the
boolean expression, Like in the 2nd example above, Python will check for its truth
value and use that to decide whether or not to run the indented code
...
Here are most of the built-in objects that are considered False in Python:
● constants defined to be false: None and False
● zero of any numeric type: 0, 0
...
format(errors))
else:
print("No errors to fix!")
You have 3 errors to fix!
In this code, errors has the truth value True because it's a non-zero number, so
the error message is printed
...
Ouestion:
Imagine an air traffic control program that tracks three variables, altitude, speed, and
propulsion which for a particular airplane have the values specified below
...
● altitude < 1000 and speed > 100
● (propulsion == "Jet" or propulsion == "Turboprop") and speed < 300 and
altitude > 20000
● not (speed > 400 and propulsion == "Propeller")
● (altitude > 500 and speed > 100) or not propulsion == "Propeller"
[]
altitude = 10000
speed = 250
propulsion = "Propeller"
# write your code here
For Loops:
Python has two kinds of loops - for loops and while loops
...
An iterable is an object that can return one of its elements at a time
...
Example:
[]
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for city in cities:
print(city)
print("Done!")
new york city
mountain view
chicago
los angeles
Done!
Components of a for Loop:
1
...
Following that is city in cities, indicating city is the iteration variable, and cities
is the iterable being looped over
...
3
...
Following the for loop heading is an indented block of code, the body of the
loop, to be executed in each iteration of this loop
...
5
...
In the second iteration of the loop above,
city takes the value of the next element in cities, which is "mountain view"
...
This process repeats until the loop has iterated through all the elements of
the iterable
...
We can tell what the next line after the body of the
loop is because it is unindented
...
A common pattern is to
give the iteration variable and iterable the same names, except the singular
and plural versions respectively (e
...
, 'city' and 'cities')
...
You will
frequently use range() with a for loop to repeat an action a certain number of times,
as in this example:
[]
for i in range(3):
print("Hello!")
Hello!
Hello!
Hello!
range(start=0, stop, step=1)
The range() function takes three integer arguments, the first and third of which are
optional:
● The 'start' argument is the first number of the sequence
...
● The 'stop' argument is 1 more than the last number of the sequence
...
● The 'step' argument is the difference between each number in the sequence
...
Notes on using range():
● If you specify one integer inside the parentheses withrange(), it's used as the
value for 'stop,' and the defaults are used for the other two
...
' Example-
[]
for i in range(2, 6):
print(i)
2
3
4
5
● Or you can specify all three integers for 'start', 'stop', and 'step
...
You can create a list by
appending to a new list at each iteration of the for loop like this:
[]
# Creating a new list
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities
...
title())
[]
for cap_city in capitalized_cities:
print(cap_city)
New York City
Mountain View
Chicago
Los Angeles
Modifying a list is a bit more involved, and requires the use of the range() function
...
This lets us access the elements of the list with cities[index] so that we can
modify the values in the cities list in place
...
title()
[]
for city in cities:
print(city)
New York City
Mountain View
Chicago
Los Angeles
Question:
Write a for loop below that will print out every whole number that is a multiple of 5
and less than or equal to 30
...
To
create a username for each name, make everything lowercase and replace spaces
with underscores
...
replace() method to replace the spaces with underscores
...
[]
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
# write your for loop here
print(usernames)
Question:
Write a for loop that iterates over a list of strings, tokens, and counts how many of
them are XML tags
...
You can tell if a string is an XML tag
if it begins with a left angle bracket "<" and ends with a right angle bracket ">"
...
You can assume that the list of strings will not contain empty strings
...
For example, if the list is items = ['first
string', 'second string'], printing html_str should output:
- first string
- second string
That is, the string's first line should be the opening tag
...
The final line of the
string should be the closing tag
...
In other cases, you'd want to iterate through both the keys and values in the
dictionary
...
Consider this dictionary that
uses names of actors as keys and their characters as values
...
items():
print("Partner 1: {} Partner 2: {}"
...
Ouestion:
You would like to count the number of fruits in your basket
...
Use the dictionary and list to count
the total number of fruits, but you do not want to count the other items in your
basket
...
A for loop over a list executes the body for each element in
the list, a for loop using the range function will execute a no of times specified by the
range function
...
when a loop repeats an
unknown no of times, and ends when some condition is met
...
Here is an example:
[]
card_deck = [4, 11, 8, 5, 13, 2, 8, 10]
hand = []
# adds the last element of the card_deck list to the hand list
# until the values in hand add up to 17 or more
while sum(hand) < 17:
hand
...
pop())
[]
for card in hand:
print(card)
10
8
This example features two new functions
...
Components of a While Loop:
1
...
2
...
In this example, that's sum(hand)
<= 17
...
The while loop heading always ends with a colon :
...
Indented after this heading is the body of the while loop
...
5
...
This process of checking the condition and then executing the loop
repeats until the condition becomes false
...
When the condition becomes false, we move on to the line following the body
of the loop, which will be unindented
...
If the value of the test condition never changes, the result is an infinite
loop!
Question:
Find the factorial of a number using a while loop
...
For example, 6 factorial (written "6!") equals 6 x 5 x 4 x 3 x 2 x 1
= 720
...
We can write a while loop to take any given number and figure out what its factorial
is
...
[]
# number to find the factorial of
number = 6
# start with our product equal to one
product = 1
# track the current number being multiplied
current = 1
# write your while loop here
# multiply the product so far by the current number
# increment current with each iteration until it reaches number
# print the factorial of number
print(product)
Question:
Now use a for loop to find the factorial!
It will now be great practice for you to try to revise the code you wrote above to find
the factorial of a number, but this time, using a for loop
...
Use break_num as the variable that
you'll change each time through the loop
...
Before the loop, what do you want to set break_num equal to? How do you want to
change break_num each time through the loop? What condition will you use to see
when it's time to stop looping?
After the loop is done, print out break_num, showing the value that indicated it was
time to stop looping
...
[]
start_num = 5
end_num = 30
count_by = 3
# write a while loop that uses break_num as the ongoing number to
# check against end_num
print(break_num)
Break and Continue:
For Loop iterate over every element in a sequence, while loops iterate over every
element untill stopping condition is met
...
In these cases we use the break keyword
...
In this case
we will use the continue keyword
...
● break terminates a loop
● continue skips one iteration of a loop
[]
fruits= ["orange", "strawberry", "apple"]
foods = ["apple", "apple", "burger", "toast"]
fruit_count = 0
for food in foods:
if food not in fruits:
print("Not a fruit")
continue
fruit_count += 1
print("Found a fruit!!")
print("Total fruits: ", fruit_count)
Found a fruit!!
Found a fruit!!
Not a fruit
Not a fruit
Total fruits: 2
[]
manifest = [("bananas", 15), ("mattresses", 24), ("dog kennels", 42),
("machine", 120), ("cheeses", 5)]
# skips an iteration when adding an item would exceed the limit
# breaks the loop if weight is exactly the value of the limit
weight = 0
items = []
METHOD 1
current weight: 0
adding bananas (15)
current weight: 15
adding mattresses (24)
current weight: 39
adding dog kennels (42)
current weight: 81
adding machine (120)
current weight: 201
breaking loop now!
Final Weight: 201
Final Items: ['bananas', 'mattresses', 'dog kennels', 'machine']
METHOD 2
current weight: 0
adding bananas (15)
current weight: 15
adding mattresses (24)
current weight: 39
adding dog kennels (42)
current weight: 81
skipping machine (120)
current weight: 81
adding cheeses (5)
Final Weight: 86
Final Items: ['bananas', 'mattresses', 'dog kennels', 'cheeses']
Question:
Write a loop with a break statement to create a string, news_ticker, that is exactly
140 characters long
...
If necessary, truncate the
last headline in the middle so that news_ticker is exactly 140 characters long
...
Use whichever loop
seems most appropriate
...
[]
headlines = ["Local Bear Eaten by Man",
"Legislature Announces New Laws",
"Peasant Discovers Violence Inherent in System",
"Cat Rescues Fireman Stuck in Tree",
"Brave Knight Runs Away",
"Papperbok Review: Totally Triffic"]
news_ticker = ""
# write your loop here
print(news_ticker)
Zip and Enumerate:
zip and enumerate are useful built-in functions that can come in handy when dealing
with loops
...
Each tuple contains the elements in that position from all the iterables
...
format(item, weight))
bananas: 15
mattresses: 24
dog kennels: 42
machine: 120
cheeses: 5
In addition to zipping two lists together, you can also unzip a list into tuples using an
asterisk
...
Enumerate:
enumerate is a built in function that returns an iterator of tuples containing indices
and values of a list
...
[]
items = ['bananas', 'mattresses', 'dog kennels', 'machine', 'cheeses']
for i, item in zip(range(len(items)), items):
print(i, item)
0 bananas
1 mattresses
2 dog kennels
3 machine
4 cheeses
[]
items = ['bananas', 'mattresses', 'dog kennels', 'machine', 'cheeses']
for i, item in enumerate(items):
print(i, item)
0 bananas
1 mattresses
2 dog kennels
3 machine
4 cheeses
Question:
Use zip to write a for loop that creates a string specifying the label and coordinates
of each point and appends it to the list points
...
For example, the string for the first coordinate should be F: 23, 677, 4
...
[]
cast_names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing",
,"Ross Geller", "Phoebe Buffay"]
cast_heights = [172, 168, 172, 166, 170]
cast = # replace with your code
print(cast)
Question:
Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix
...
For example, the first
element of cast should change from "Barney Stinson" to "Barney Stinson 150"
...
For exampls from earlier:
[]
cities = ['new york city', 'mountain view',
'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities
...
title())
print(capitalized_cities)
['New York City', 'Mountain View', 'Chicago', 'Los Angeles']
With the help of list comprehension this can be reduced to:
[]
capitalized_cities = [city
...
You create a list comprehension with brackets [], including an expression to evaluate
for each element in an iterable
...
title() for
each element city in cities, to create each element in the new list, capitalized_cities
...
Lets look at an example:
[]
squares = []
for x in range(9):
squares
...
If you want to add an else, you will get a syntax error
doing this
...
[]
squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)]
List comprehensions are not found in other languages, but are very common in
Python
...
[]
names = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby",
"Lily Aldrin", "Marshall Eriksen"]
first_names = # write your list comprehension here
print(first_names)
Question:
Use a list comprehension to create a list multiples_3 containing the first 20 multiples
of 3
...
[]
scores = {
"Deku": 70,
"Bakugo": 35,
"Tenya": 82,
"Shoto": 23,
"All Might": 98
}
passed = # write your list comprehension here
print(passed)
Loading…
Function In Python_
FileEditViewInsertRuntimeToolsHelp
Share
Code
Text
Copy to Drive
Connect
FUNCTIONS IN PYTHON
Welcome to the lesson on Function! You will learn why and how we use
functions in Python :)
What is a Function and why we use it
A function is a block of which when called perform a specific task
...
To make the code easier to understand and more user friendly
...
Defining a Funnction in Python
In python you define a Function using the keyword def
...
def Fun_Name():
## Here we just defined a function
## The name of the function is Fun_Name
## COOL XD
2
...
e
...
Don't worry we will see calling function in details later
...
For now keep the
name of the function ShapeAI and run the two cells below
...
But what if you want to write a function that print the addition of the
two number that you want?
You have to pass the two values in the function as an argument
...
The function then use the value stored in the variables to perform
addition and print the addition
[]
def ADD(a,b):
print(a+b)
ADD(5,6) #expexted output = 11
11
Calling of a Function
Calling a function means to make a refference in your code to a function that you wrote
...
fun_name(arguments_to_pass_if_any) # This how a function is called
If you notice, while calling the ADD function or any of the function we define
above, we just follow the same pattern
...
NOTE: We can pass the arguments while calling the function using two ways:
● By position, and
● By name
[]
def divide(numinator, denominator):
print(numinator/denominator)
divide(4,2) # Calling by position
divide(denominator=2, numinator=4) # Calling ny name
2
...
0
Task:
Write a function which takes two number as arguments and print the multiplication of the two
numbers
[]
def Multiply(## WRITE THE VARIABLE NAMES):
## WRITE THE CODE TO PRINT THE MULTIPLICATION OF TWO NUMBERS
# Call the multiply function you just defined
Default Values to the Arguments
While defining a function you can set some default values for the arguments in case if user
dosn't pass the argument value Let's look how:
def Area(length=2, breadth=2):
print(length*breadth)
Here if you don't pass the values of length and breadth while calling the function, the
default values the function will take will be 2 and 2 for length and breadth
repectively
...
Return Statement
In the function we saw above, we just print the things which we wanted
...
[]
def Fun(a=5, b=10):
sum=a+b
diff=a-b
return sum, diff
[]
sum, diff = Fun(10,6)
print(f'Addition of the two numbers is {sum}')
print(f'Difference of the two numbers is {diff}')
Addition of the two numbers is 16
Difference of the two numbers is 4
Note: All function have a return statement
...
Function Header:
Let's start with the function header, which is the first line of a function definition
...
The function header always starts with the def keyword, which indicates that
this is a function definition
...
Then comes the function name (here, cylinder_volume), which follows the
same naming conventions as variables
...
3
...
Arguments, or parameters,
are values that are passed in as inputs when the function is called, and are
used in the function body
...
4
...
Function Body:
The rest of the function is contained in the body, which is where the function does its
work
...
The body of a function is the code indented after the header line
...
2
...
3
...
A
return statement consists of the return keyword followed by an expression
that is evaluated to get the output value for the function
...
Below, you'll find a code editor where you can experiment with this
...
1
...
They can’t have spaces, and need to start with a letter or underscore
...
You can’t use reserved words or built-in identifiers that have important
purposes in Python, which you’ll learn about throughout this bootcamp
...
Try to use descriptive names that can help readers understand what the
function does
...
I've
included two test cases that you can use to verify that your function works correctly
...
[]
# write your function here
# test cases for your function
test1 = population_density(10, 1)
expected_result1 = 10
print("expected result: {}, actual result: {}"
...
4)
expected_result2 = 7123
...
format(expected_result2, test2))
Question:
Write a function named readable_timedelta
...
For
example, calling the function and printing the result like this:
print(readable_timedelta(10))
should output the following:
1 week(s) and 3 day(s)
...
def Add(a, b):
return a+b
The code above can be written as:
Add = lambda a,b: a+b
Note: The lambda function can take any number of arguments but can have
only one expression
[]
Sub = lambda a,b: a-b
print(Sub(5,2)) #EXPEXTED OUTPUT: 3
3
Components of a Lambda Function:
1
...
2
...
Similar to functions, the way the
arguments are named in a lambda expression is arbitrary
...
Last is an expression that is evaluated and returned in this function
...
With this structure, lambda expressions aren’t ideal for complex functions, but can
be very useful for short, simple functions
...
The
code below uses map() to find the mean of each list in numbers to create the list
averages
...
Rewrite this code to be more concise by replacing the mean function with a lambda
expression defined within the call to map()
...
[]
def sum(a, b):
answer = a+b
return answer
S = sum(5,6)
print(answer)
Here we will get an error, because the variable answer is defined within the the
function and can't be used outside unless defined
On the other hand, we might have a variable defined outside the function, and we
can access it anywhere outside or within these functions
[]
ans = 0
def print_ans():
print(ans)
print_ans()
print(ans)
0
0
The purpose of the functions is to make the code cleaner and easy to understand
...
One of the most important thing that makes code conataining the function easier to
understand is that the functions have the human defined name, which are easier to
understand i
...
the function to return area of the circle can be named as cir_area,
which makes it easier to recognize as the area of circle
...
While functions can refer to variables defined in a larger scope, this
is very rarely a good idea since you may not know what variables you have
defined if your program has a lot of variables
...
Docstrings are the type of comments that
explains the purpose of a function and how it should be used
...
● The first line of the docstring is the brief explaination of the function perpose
...
NOTE: Every part of the docstring is optional, but it is good habit to write
docstring while defining a function, so that everyone can understand the code
easily
[]
def simple_interest(amount, rate, time):
"""
Calculate the total amount to be paid after adding Simple Interest
...
0
If you think that a longer description would be appropriate for the function, you can
add more information after the one-line summary
...
It's also common to provide some description of the function's
output
...
You can read more about docstring conventions here
...
for e
...
e 3/1
...
NumPy provides Python with an extensive math library capable of performing numerical
computations effectively and efficiently
...
Why Numpy:
You may be wondering why people use NumPy - after all, Python can handle lists, as you
learned in the Intro to Python lessons
...
One such feature is speed
...
This
speed comes from the nature of NumPy arrays being memory-efficient and from optimized
algorithms used by NumPy for doing arithmetic, statistical, and linear algebra operations
...
random
...
time()
mean = sum(x)/len(x)
print(time
...
07553839683533
In [6]:
start = time
...
mean(x)
print(time
...
6675674915313721
Creating NumPy ndarrays:
At the core of NumPy is the ndarray, where nd stands for n-dimensional
...
In other words, an ndarray is a grid that
can take on many shapes and can hold either numbers or strings
...
For instance, you
might use an ndarray to hold the pixel values of an image that will be fed into a Neural Network
for image classification
...
In the following lessons we will see two
ways to create ndarrays:
1
...
Using built-in NumPy functions
In this section, we will create ndarrays by providing Python lists to the NumPy np
...
We should note that for the purposes of clarity, the
examples throughout these lessons will use small and simple ndarrays
...
In [2]:
# We import NumPy into Python
import numpy as np
# We create a 1D ndarray that contains only integers
x = np
...
The shape of an array is the size along each
of its dimensions
...
For example, the shape of an ndarray can be
obtained using the
...
The shape attribute returns a tuple of N positive integers that
specify the sizes of each dimension
...
array([1, 2, 3, 4, 5])
# We print x
print()
print('x = ', x)
print()
# We print information about x
print('x has dimensions:', x
...
dtype)
x = [1 2 3 4 5]
x has dimensions: (5,)
x is an object of type:
e
...
The type() function tells us that x is indeed a NumPy
ndarray
...
dtype attribute tells us that the elements of x are stored in memory as
signed 64-bit integers
...
here
As mentioned earlier, ndarrays can also hold strings
...
array() function a Python
list of strings
...
array(['Hello', 'World'])
# We print x
print()
print('x = ', x)
print()
# We print information about x
print('x has dimensions:', x
...
dtype)
x = ['Hello' 'World']
x has dimensions: (2,)
x is an object of type:
So, while we can
create Python lists with both integers and strings, we can't mix types in ndarrays
...
array() function with a Python list that has both integers and strings, NumPy will interpret
all elements as strings
...
array([1, 2, 'World'])
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about x
print('x has dimensions:', x
...
dtype)
x = ['1' '2' 'World']
x has dimensions: (3,)
x is an object of type:
In [6]:
# We create a rank 2 ndarray that only contains integers
Y = np
...
shape)
print('Y has a total of', Y
...
dtype)
Y=
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Y has dimensions: (4, 3)
Y has a total of 12 elements
Y is an object of type:
We saw that when we
create an ndarray with only integers, NumPy will automatically assign the dtype int64 to its
elements
...
In [7]:
# We create a rank 1 ndarray that contains integers
x = np
...
array([1
...
0,3
...
array([1, 2
...
dtype)
print('The elements in y are of type:', y
...
dtype)
The elements in x are of type: int64
The elements in y are of type: float64
The elements in z are of type: float64
Notice that when we create an ndarray with both floats and integers, as we did with the z ndarray
above, NumPy assigns its elements a float64 dtype as well
...
Since all the
elements of an ndarray must be of the same type, in this case NumPy upcasts the integers in z
to floats in order to avoid losing precision in numerical computations
...
You can specify
the dtype when you create the ndarray using the keyword dtype in the np
...
Let's
see an example:
In [8]:
# We create a rank 1 ndarray of floats but set the dtype to int64
x = np
...
5, 2
...
7, 4
...
9], dtype = np
...
dtype)
x = [1 2 3 4 5]
The elements in x are of type: int64
Once you create an ndarray, you may want to save it to a file to be read later or to be used by
another program
...
In [9]:
# We create a rank 1 ndarray
x = np
...
save('my_array', x)
The above saves the x ndarray into a file named my_array
...
You can load the saved ndarray
into a variable by using the load() function
...
npy, otherwise you will get an error
...
load('my_array
...
dtype)
y = [1 2 3 4 5]
y is an object of type:
These functions allow us to create certain kinds of ndarrays with just one line of code
...
np
...
We can do this by
using the np
...
The function np
...
So, for example, if you wanted to create a rank 2 array with 3 rows and 4
columns, you will pass the shape to the function in the form of (rows, columns), as in the
example below:
In [11]:
# We create a 3 x 4 ndarray full of zeros
...
zeros((3,4))
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X
...
dtype)
X=
[[0
...
0
...
]
[0
...
0
...
]
[0
...
0
...
]]
X has dimensions: (3, 4)
X is an object of type:
zeros() function creates by default an array with dtype
float64
...
np
...
We can do this by
using the np
...
Just like the np
...
ones() function takes as an
argument the shape of the ndarray you want to make
...
X = np
...
shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X
...
1
...
1
...
1
...
ndarray'>
The elements in X are of type: float64
np
...
We can
do this by using the np
...
The np
...
The first argument is the shape of the ndarray you want to make and the second is
the constant value you want to populate the array with
...
X = np
...
shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X
...
ndarray'>
The elements in X are of type: int64
np
...
The function np
...
Since all Identity Matrices are square, the np
...
Let's see an example:
In [14]:
# We create a 5 x 5 Identity matrix
...
eye(5)
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X
...
dtype)
X=
[[1
...
0
...
0
...
1
...
0
...
]
[0
...
1
...
0
...
0
...
1
...
]
[0
...
0
...
1
...
ndarray'>
The elements in X are of type: float64
np
...
diag() function
...
The np
...
diag([10,20,30,50])
# We print X
print()
print('X = \n', X)
print()
X=
[[10 0 0 0]
[ 0 20 0 0]
[ 0 0 30 0]
[ 0 0 0 50]]
np
...
NumPy's np
...
Below we will see examples of each case and how they are used to create
different kinds of ndarrays
...
arange() with only one argument
...
arange(N) will create a rank 1 ndarray with consecutive integers between 0 and N - 1
...
arange(10)
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about the ndarray
print('x has dimensions:', x
...
dtype)
x = [0 1 2 3 4 5 6 7 8 9]
x has dimensions: (10,)
x is an object of type:
arange(start,stop) will create a rank 1 ndarray with evenly
spaced values within the half-open interval [start, stop)
...
Let's see an example
In [17]:
# We create a rank 1 ndarray that has sequential integers from 4 to 9
...
arange(4,10)
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about the ndarray
print('x has dimensions:', x
...
dtype)
x = [4 5 6 7 8 9]
x has dimensions: (6,)
x is an object of type:
arange(start,stop,step) will create a rank 1 ndarray
with evenly spaced values within the half-open interval [start, stop) with step being the distance
between two adjacent values
...
x = np
...
shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x
...
ndarray'>
The elements in x are of type: int64
np
...
arange() function allows for non-integer steps, such as 0
...
For this reason, in the cases where
non-integer steps are required, it is usually better to use the function np
...
The
np
...
This means that both the start and thestop values are included
...
linspace() function needs to be called with at least two arguments in the form
np
...
In this case, the default number of elements in the specified interval will
be N= 50
...
linspace() works better than the np
...
linspace() uses the number of elements we want in a particular interval, instead of the step
between values
...
x = np
...
shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x
...
2
...
55555556 8
...
11111111 13
...
66666667 19
...
22222222 25
...
ndarray'>
The elements in x are of type: float64
As we can see from the above example, the function np
...
We can also see that both the start
and end points, 0 and 25 in this case, are included
...
arange() function) by setting the keyword endpoint =
False in the np
...
Let's create the same x ndarray we created above but now
with the endpoint excluded:
In [20]:
# We create a rank 1 ndarray that has 10 integers evenly spaced between
0 and 25,
# with 25 excluded
...
linspace(0,25,10, endpoint = False)
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about the ndarray
print('x has dimensions:', x
...
dtype)
x = [ 0
...
5 5
...
5 10
...
5 15
...
5 20
...
5]
x has dimensions: (10,)
x is an object of type:
reshape():
So far, we have only used the built-in functions np
...
linspace() to create rank 1
ndarrays
...
reshape() function
...
reshape(ndarray, new_shape) function
converts the given ndarray into the specified new_shape
...
In [21]:
# We create a rank 1 ndarray with sequential integers from 0 to 19
x = np
...
reshape(x, (4,5))
# We print the reshaped x
print()
print('Reshaped x = \n', x)
print()
# We print information about the reshaped x
print('x has dimensions:', x
...
dtype)
Original x = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Reshaped x =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
x has dimensions: (4, 5)
x is an object of type:
This
allows us to apply different functions in sequence in just one line of code
...
Let's see how we
can accomplish the same result as in the above example, but in just one line of code:
In [23]:
# We create a a rank 1 ndarray with sequential integers from 0 to 19
and
# reshape it to a 4 x 5 array
Y = np
...
reshape(4, 5)
# We print Y
print()
print('Y = \n', Y)
print()
# We print information about Y
print('Y has dimensions:', Y
...
dtype)
Y=
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Y has dimensions: (4, 5)
Y is an object of type:
linspace() to create rank 2 arrays,
as shown in the next example
...
We then reshape it to a 5 x 2 ndarray
X = np
...
reshape(5,2)
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X
...
dtype)
X=
[[ 0
...
]
[10
...
]
[20
...
]
[30
...
]
[40
...
]]
X has dimensions: (5, 2)
X is an object of type:
Random ndarrays are
arrays that contain random numbers
...
NumPy offers a variety
of random functions to help us create random ndarrays of any shape
...
0, 1
...
X = np
...
random((3,3))
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X
...
dtype)
X=
[[0
...
40550946 0
...
67423937 0
...
12587685]
[0
...
15787991 0
...
ndarray'>
The elements in x are of type: float64
NumPy also allows us to create ndarrays with random integers within a particular interval
...
random
...
Let's see an example:
In [25]:
# We create a 3 x 2 ndarray with random integers in the half-open
interval [4, 15)
...
random
...
shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X
...
ndarray'>
The elements in X are of type: int64
In some cases, you may need to create ndarrays with random numbers that satisfy certain
statistical properties
...
NumPy allows you create random ndarrays with numbers drawn from various
probability distributions
...
random
...
In [26]:
# We create a 1000 x 1000 ndarray of random floats drawn from normal
(Gaussian) distribution
# with a mean of zero and a standard deviation of 0
...
X = np
...
normal(0, 0
...
shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X
...
mean())
print('The maximum value in X is:', X
...
min())
print('X has', (X < 0)
...
sum(), 'positive numbers')
X=
[[ 0
...
07058648 0
...
-0
...
03274108
-0
...
0427396 0
...
08193541
...
22104453 0
...
17775136]
[ 0
...
01597223 -0
...
-0
...
0522047
-0
...
[-0
...
0268068 0
...
-0
...
04742756
-0
...
1307405 -0
...
17023093
...
03329357 -0
...
06895992]
[ 0
...
1388507 0
...
-0
...
04751616
0
...
ndarray'>
The elements in X are of type: float64
The elements in X have a mean of: 0
...
49171050961052176
The minimum value in X is: -0
...
linspace() function
...
NumPy allows you to use
both positive and negative indices to access elements in the ndarray
...
In [ ]:
# We create a rank 1 ndarray that contains integers from 1 to 5
x = np
...
We do this by accessing the
element we want to change and then using the = sign to assign the new value:
In [27]:
# We create a rank 1 ndarray that contains integers from 1 to 5
x = np
...
To access
elements in rank 2 ndarrays we need to provide 2 indices in the form [row, column]
...
array([[1,2,3],[4,5,6],[7,8,9]])
# We print X
print()
print('X = \n', X)
print()
# Let's access some elements in X
print('This is (0,0) Element in X:', X[0,0])
print('This is (0,1) Element in X:', X[0,1])
print('This is (2,2) Element in X:', X[2,2])
X=
[[1 2 3]
[4 5 6]
[7 8 9]]
This is (0,0) Element in X: 1
This is (0,1) Element in X: 2
This is (2,2) Element in X: 9
Elements in rank 2 ndarrays can be modified in the same way as with rank 1 ndarrays
...
array([[1,2,3],[4,5,6],[7,8,9]])
# We print the original x
print()
print('Original:\n X = \n', X)
print()
# We change the (0,0) element in X from 1 to 20
X[0,0] = 20
# We print X after it was modified
print('Modified:\n X = \n', X)
Original:
X=
[[1 2 3]
[4 5 6]
[7 8 9]]
Modified:
X=
[[20 2 3]
[ 4 5 6]
[ 7 8 9]]
Adding and Deleting elements:
Now, let's take a look at how we can add and delete elements from ndarrays
...
delete(ndarray, elements, axis) function
...
For rank 1 ndarrays the axis
keyword is not required
...
Let's see some examples:
In [30]:
# We create a rank 1 ndarray
x = np
...
array([[1,2,3],[4,5,6],[7,8,9]])
# We print x
print()
print('Original x = ', x)
# We delete the first and last element of x
x = np
...
delete(Y, 0, axis=0)
# We delete the first and last column of y
v = np
...
append(ndarray, elements, axis) function
...
Let's see some
examples:
In [31]:
# We create a rank 1 ndarray
x = np
...
array([[1,2,3],[4,5,6]])
# We print x
print()
print('Original x = ', x)
# We append the integer 6 to x
x = np
...
append(x, [7,8])
# We print x
print()
print('x = ', x)
# We print Y
print()
print('Original Y = \n', Y)
# We append a new row containing 7,8,9 to y
v = np
...
append(Y,[[9],[10]], axis=1)
# We print v
print()
print('v = \n', v)
# We print q
print()
print('q = \n', q)
Original x = [1 2 3 4 5]
x = [1 2 3 4 5 6]
x = [1 2 3 4 5 6 7 8]
Original Y =
[[1 2 3]
[4 5 6]]
v=
[[1 2 3]
[4 5 6]
[7 8 9]]
q=
[[ 1 2 3 9]
[ 4 5 6 10]]
Now let's see now how we can insert values to ndarrays
...
insert(ndarray, index, elements, axis) function
...
Let's see some
examples:
In [ ]:
# We create a rank 1 ndarray
x = np
...
array([[1,2,3],[7,8,9]])
# We print x
print()
print('Original x = ', x)
# We insert the integer 3 and 4 between 2 and 5 in x
...
insert(x,2,[3,4])
# We print x with the inserted elements
print()
print('x = ', x)
# We print Y
print()
print('Original Y = \n', Y)
# We insert a row between the first and last row of y
w = np
...
insert(Y,1,5, axis=1)
# We print w
print()
print('w = \n', w)
# We print v
print()
print('v = \n', v)
NumPy also allows us to stack ndarrays on top of each other, or to stack them side by side
...
vstack() function for vertical stacking, or the np
...
It is important to note that in order to stack ndarrays, the shape of
the ndarrays must match
...
array([1,2])
# We create a rank 2 ndarray
Y = np
...
vstack((x,Y))
# We stack x on the right of Y
...
w = np
...
reshape(2,1)))
# We print z
print()
print('z = \n', z)
# We print w
print()
print('w = \n', w)
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Day_6_Numpy_Part_2
...
NumPy allows you to
use both positive and negative indices to access elements in the ndarray
...
"
]
},
{
"cell_type": "code",
"metadata": {
"id": "lc4fxGwif5cA",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 203
},
"outputId": "d9d39440-2958-4728-d4e7-0602af77e232"
},
"source": [
"import numpy as np\n",
"\n",
"# We create a rank 1 ndarray that contains integers from 1 to 5\n",
"x = np
...
We do this by
accessing the element we want to change and then using the = sign to assign the new value:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "ymAvKfjYgIPx",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "e1151b9b-ddeb-4a1f-de17-01404e54c134"
},
"source": [
"# We create a rank 1 ndarray that contains integers from 1 to 5\n",
"x = np
...
To access
elements in rank 2 ndarrays we need to provide 2 indices in the form [row, column]
...
array([[1,2,3],[4,5,6],[7,8,9]])\n",
"\n",
"# We print X\n",
"print()\n",
"print('X = \\n', X)\n",
"print()\n",
"\n",
"# Let's access some elements in X\n",
"print('This is (0,0) Element in X:', X[0,0])\n",
"print('This is (0,1) Element in X:', X[0,1])\n",
"print('This is (2,2) Element in X:', X[2,2])"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"X = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"This is (0,0) Element in X: 1\n",
"This is (0,1) Element in X: 2\n",
"This is (2,2) Element in X: 9\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TN6nKaJFgbyq",
"colab_type": "text"
},
"source": [
"Elements in rank 2 ndarrays can be modified in the same way as with rank 1 ndarrays
...
array([[1,2,3],[4,5,6],[7,8,9]])\n",
"\n",
"# We print the original x\n",
"print()\n",
"print('Original:\\n X = \\n', X)\n",
"print()\n",
"\n",
"# We change the (0,0) element in X from 1 to 20\n",
"X[0,0] = 20\n",
"\n",
"# We print X after it was modified \n",
"print('Modified:\\n X = \\n', X)\n"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original:\n",
" X = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"Modified:\n",
" X = \n",
" [[20 2 3]\n",
" [ 4 5 6]\n",
" [ 7 8 9]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_bMnSvxFggxp",
"colab_type": "text"
},
"source": [
"## **Adding and Deleting elements:**\n",
"Now, let's take a look at how we can add and delete elements from ndarrays
...
delete(ndarray, elements, axis) function
...
For rank 1 ndarrays the
axis keyword is not required
...
Let's see some examples:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "_SYPaPx0geSl",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 335
},
"outputId": "a0c70b67-45c8-48b1-baf7-6b36730549a8"
},
"source": [
"# We create a rank 1 ndarray \n",
"x = np
...
array([[1,2,3],[4,5,6],[7,8,9]])\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"\n",
"# We delete the first and last element of x\n",
"x = np
...
delete(Y, 0, axis=0)\n",
"\n",
"# We delete the first and last column of y\n",
"v = np
...
append(ndarray, elements, axis) function
...
Let's see
some examples:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "nvvBHVntgkDg",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 352
},
"outputId": "b3608a27-c248-4d0f-99eb-2d53608f27db"
},
"source": [
"# We create a rank 1 ndarray \n",
"x = np
...
array([[1,2,3],[4,5,6]])\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"\n",
"# We append the integer 6 to x\n",
"x = np
...
append(x, [7,8])\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Original Y = \\n', Y)\n",
"\n",
"# We append a new row containing 7,8,9 to y\n",
"v = np
...
append(Y,[[9],[10]], axis=1)\n",
"\n",
"# We print v\n",
"print()\n",
"print('v = \\n', v)\n",
"\n",
"# We print q\n",
"print()\n",
"print('q = \\n', q)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original x = [1 2 3 4 5]\n",
"\n",
"x = [1 2 3 4 5 6]\n",
"\n",
"x = [1 2 3 4 5 6 7 8]\n",
"\n",
"Original Y = \n",
" [[1 2 3]\n",
" [4 5 6]]\n",
"\n",
"v = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"q = \n",
" [[ 1 2 3 9]\n",
" [ 4 5 6 10]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WkxJUwqpgr99",
"colab_type": "text"
},
"source": [
"Now let's see now how we can insert values to ndarrays
...
insert(ndarray, index, elements, axis) function
...
Let's see some
examples:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "bRSlXaH-gpZu",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 319
},
"outputId": "2489f6e0-398c-42d7-9c16-7f04904da4b9"
},
"source": [
"# We create a rank 1 ndarray \n",
"x = np
...
array([[1,2,3],[7,8,9]])\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"\n",
"# We insert the integer 3 and 4 between 2 and 5 in x
...
insert(x,2,[3,4])\n",
"\n",
"# We print x with the inserted elements\n",
"print()\n",
"print('x = ', x)\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Original Y = \\n', Y)\n",
"\n",
"# We insert a row between the first and last row of y\n",
"w = np
...
insert(Y,1,5, axis=1)\n",
"\n",
"# We print w\n",
"print()\n",
"print('w = \\n', w)\n",
"\n",
"# We print v\n",
"print()\n",
"print('v = \\n', v)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original x = [1 2 5 6 7]\n",
"\n",
"x = [1 2 3 4 5 6 7]\n",
"\n",
"Original Y = \n",
" [[1 2 3]\n",
" [7 8 9]]\n",
"\n",
"w = \n",
" [[1 2 3]\n",
" [4 5 6]\n",
" [7 8 9]]\n",
"\n",
"v = \n",
" [[1 5 2 3]\n",
" [7 5 8 9]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-R27FObOgx6r",
"colab_type": "text"
},
"source": [
"NumPy also allows us to stack ndarrays on top of each other, or to stack them side by
side
...
vstack() function for vertical stacking, or the
np
...
It is important to note that in order to stack ndarrays,
the shape of the ndarrays must match
...
array([1,2])\n",
"\n",
"# We create a rank 2 ndarray \n",
"Y = np
...
vstack((x,Y))\n",
"\n",
"# We stack x on the right of Y
...
\n",
"w = np
...
reshape(2,1)))\n",
"\n",
"# We print z\n",
"print()\n",
"print('z = \\n', z)\n",
"\n",
"# We print w\n",
"print()\n",
"print('w = \\n', w)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"x = [1 2]\n",
"\n",
"Y = \n",
" [[3 4]\n",
" [5 6]]\n",
"\n",
"z = \n",
" [[1 2]\n",
" [3 4]\n",
" [5 6]]\n",
"\n",
"w = \n",
" [[3 4 1]\n",
" [5 6 2]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "guOiIr6vuJVV",
"colab_type": "text"
},
"source": [
"## **Slicing ndarrays:**\n",
"As we mentioned earlier, in addition to being able to access individual elements one at a
time, NumPy provides a way to access subsets of ndarrays
...
Slicing is
performed by combining indices with the colon : symbol inside the square brackets
...
ndarray[start:end]\n",
"2
...
ndarray[:end]\n",
"```\n",
"The first method is used to select elements between the start and end indices
...
The third method is
used to select all elements from the first index till the end index
...
We should also note that since ndarrays can be
multidimensional, when doing slicing you usually have to specify a slice for each dimension of
the array
...
\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "HP1atdZBg0Tg",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "96beec84-9af1-40ba-9f06-bd04c4e12e16"
},
"source": [
"# We create a 4 x 5 ndarray that contains integers from 0 to 19\n",
"X = np
...
reshape(4, 5)\n",
"\n",
"# We print X\n",
"print()\n",
"print('X = \\n', X)\n",
"print()\n",
"\n",
"# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 5th
columns\n",
"Z = X[1:4,2:5]\n",
"\n",
"# We print Z\n",
"print('Z = \\n', Z)\n",
"\n",
"# We can select the same elements as above using method 2\n",
"W = X[1:,2:5]\n",
"\n",
"# We print W\n",
"print()\n",
"print('W = \\n', W)\n",
"\n",
"# We select all the elements that are in the 1st through 3rd rows and in the 3rd to 4th
columns\n",
"Y = X[:3,2:5]\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Y = \\n', Y)\n",
"\n",
"# We select all the elements in the 3rd row\n",
"v = X[2,:]\n",
"\n",
"# We print v\n",
"print()\n",
"print('v = ', v)\n",
"\n",
"# We select all the elements in the 3rd column\n",
"q = X[:,2]\n",
"\n",
"# We print q\n",
"print()\n",
"print('q = ', q)\n",
"\n",
"# We select all the elements in the 3rd column but return a rank 2 ndarray\n",
"R = X[:,2:3]\n",
"\n",
"# We print R\n",
"print()\n",
"print('R = \\n', R)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"X = \n",
" [[ 0 1 2 3 4]\n",
" [ 5 6 7 8 9]\n",
" [10 11 12 13 14]\n",
" [15 16 17 18 19]]\n",
"\n",
"Z = \n",
" [[ 7 8 9]\n",
" [12 13 14]\n",
" [17 18 19]]\n",
"\n",
"W = \n",
" [[ 7 8 9]\n",
" [12 13 14]\n",
" [17 18 19]]\n",
"\n",
"Y = \n",
" [[ 2 3 4]\n",
" [ 7 8 9]\n",
" [12 13 14]]\n",
"\n",
"v = [10 11 12 13 14]\n",
"\n",
"q = [ 2 7 12 17]\n",
"\n",
"R = \n",
" [[ 2]\n",
" [ 7]\n",
" [12]\n",
" [17]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CVF0BaLRy-9h",
"colab_type": "text"
},
"source": [
"Notice that when we selected all the elements in the 3rd column, variable q above, the
slice returned a rank 1 ndarray instead of a rank 2 ndarray
...
\n",
"\n",
"It is important to note that when we perform slices on ndarrays and save them into new
variables, as we did above, the data is not copied into the new variable
...
Therefore, we will look at this in a bit more detail
...
Rather, X and Z are now just
two different names for the same ndarray
...
This means that if you make changes in Z you will be in effect changing the elements in X
as well
...
arange(20)
...
ipynb",
"provenance": [],
"collapsed_sections": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "Tjukq5BlGUNj",
"colab_type": "text"
},
"source": [
"## **Boolean Indexing:**\n",
"There are many situations in which we don't know the indices of the elements we want to
select
...
Boolean
indexing can help us in these cases, by allowing us select elements using logical arguments
instead of explicit indices
...
arange(25)
...
This useful when
comparing ndarrays, for example, to find common elements between two ndarrays
...
array([1,2,3,4,5])\n",
"\n",
"# We create a rank 1 ndarray\n",
"y = np
...
intersect1d(x,y))\n",
"print('The elements that are in x that are not in y:', np
...
union1d(x,y))"
],
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"x = [1 2 3 4 5]\n",
"\n",
"y = [6 7 2 8 4]\n",
"\n",
"The elements that are both in x and y: [2 4]\n",
"The elements that are in x that are not in y: [1 3 5]\n",
"All the elements of x and y: [1 2 3 4 5 6 7 8]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "r39N_VAmHYnN",
"colab_type": "text"
},
"source": [
"## **Sort():**\n",
"\n",
"We can also sort ndarrays in NumPy
...
sort() function to sort
rank 1 and rank 2 ndarrays in different ways
...
However, there is a big difference on how the data is
stored in memory in this case
...
sort() is used as a function, it sorts the ndrrays out of place, meaning, that it
doesn't change the original ndarray being sorted
...
sort() sorts the ndarray in place,
meaning, that the original array will be changed to the sorted one
...
random
...
\n",
"print()\n",
"print('Sorted x (out of place):', np
...
To see this we print x
again\n",
"print()\n",
"print('x after sorting:', x)"
],
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original x = [ 2 2 7 9 8 4 2 10 5 7]\n",
"\n",
"Sorted x (out of place): [ 2 2 2 4 5 7 7 8 9 10]\n",
"\n",
"x after sorting: [ 2 2 7 9 8 4 2 10 5 7]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QbBU9jOtH7pq",
"colab_type": "text"
},
"source": [
"let's see how we can sort ndarrays in place, by using sort as a method:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "1Mbvj8oWHwEt",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104
},
"outputId": "8fa1372b-1832-4f78-b02f-221aa47ab809"
},
"source": [
"# We create an unsorted rank 1 ndarray\n",
"x = np
...
randint(1,11,size=(10,))\n",
"\n",
"# We print x\n",
"print()\n",
"print('Original x = ', x)\n",
"\n",
"# We sort x and print the sorted array using sort as a method
...
sort()\n",
"\n",
"# When we sort in place the original array is changed to the sorted array
...
sort() sorts the array but, if the ndarray being sorted has repeated values,
np
...
However, if desired, we can sort only the
unique elements in x by combining the sort function with the unique function
...
random
...
sort(np
...
sort() function whether we are
sorting by rows or columns
...
Let's see some
examples:\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "XdZi81Q4IFv7",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a4201ae6-6e75-4632-9e4c-86476dcc73f9"
},
"source": [
"# We create an unsorted rank 2 ndarray\n",
"X = np
...
randint(1,11,size=(5,5))\n",
"\n",
"# We print X\n",
"print()\n",
"print('Original X = \\n', X)\n",
"print()\n",
"\n",
"# We sort the columns of X and print the sorted array\n",
"print()\n",
"print('X with sorted columns :\\n', np
...
sort(X, axis = 1))"
],
"execution_count": 9,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"Original X = \n",
" [[ 2 5 9 1 7]\n",
" [10 7 6 9 6]\n",
" [ 4 8 3 8 2]\n",
" [ 9 1 5 6 10]\n",
" [ 5 5 10 6 9]]\n",
"\n",
"\n",
"X with sorted columns :\n",
" [[ 2 1 3 1 2]\n",
" [ 4 5 5 6 6]\n",
" [ 5 5 6 6 7]\n",
" [ 9 7 9 8 9]\n",
" [10 8 10 9 10]]\n",
"\n",
"X with sorted rows :\n",
" [[ 1 2 5 7 9]\n",
" [ 6 6 7 9 10]\n",
" [ 2 3 4 8 8]\n",
" [ 1 5 6 9 10]\n",
" [ 5 5 6 9 10]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8B06V3sgKeSG",
"colab_type": "text"
},
"source": [
"## **Question:**\n",
"Create a 5 x 5 ndarray with consecutive integers from 1 to 25 (inclusive)
...
\n",
"X = \n",
"\n",
"# Use Boolean indexing to pick out only the odd numbers in the array\n",
"Y = "
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "l2f8f9ZUKwKH",
"colab_type": "text"
},
"source": [
"## **Arithmtic Operations:**\n",
"Let's start by doing element-wise addition, subtraction, multiplication, and division,
between ndarrays
...
add(), or by using arithmetic symbols, such as +, that resembles more how we write
mathematical equations
...
It is important to note that when performing element-wise operations, the shapes of
the ndarrays being operated on, must have the same shape or be broadcastable
...
Let's start by performing element-wise arithmetic operations
on rank 1 ndarrays:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "0Uk3Dg4qNcYK",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 302
},
"outputId": "53e7a86b-6ef4-41c7-929e-cab4602253d4"
},
"source": [
"# We create two rank 1 ndarrays\n",
"x = np
...
array([5
...
5,7
...
5])\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"\n",
"# We print y\n",
"print()\n",
"print('y = ', y)\n",
"print()\n",
"\n",
"# We perfrom basic element-wise operations using arithmetic symbols and functions\n",
"print('x + y = ', x + y)\n",
"print('add(x,y) = ', np
...
subtract(x,y))\n",
"print()\n",
"print('x * y = ', x * y)\n",
"print('multiply(x,y) = ', np
...
divide(x,y))"
],
"execution_count": 10,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"x = [1 2 3 4]\n",
"\n",
"y = [5
...
5 7
...
5]\n",
"\n",
"x + y = [ 6
...
5 10
...
5]\n",
"add(x,y) = [ 6
...
5 10
...
5]\n",
"\n",
"x - y = [-4
...
5 -4
...
5]\n",
"subtract(x,y) = [-4
...
5 -4
...
5]\n",
"\n",
"x * y = [ 5
...
22
...
]\n",
"multiply(x,y) = [ 5
...
22
...
]\n",
"\n",
"x / y = [0
...
30769231 0
...
47058824]\n",
"divide(x,y) = [0
...
30769231 0
...
47058824]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Cv-lLIRANh6q",
"colab_type": "text"
},
"source": [
"We can also perform the same element-wise arithmetic operations on rank 2 ndarrays
...
"
]
},
{
"cell_type": "code",
"metadata": {
"id": "aM5ZOfYBNfRr",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 699
},
"outputId": "fceff7d7-b52b-433c-aeaa-801c7e61a834"
},
"source": [
"# We create two rank 2 ndarrays\n",
"X = np
...
reshape(2,2)\n",
"Y = np
...
5,6
...
5,8
...
reshape(2,2)\n",
"\n",
"# We print X\n",
"print()\n",
"print('X = \\n', X)\n",
"\n",
"# We print Y\n",
"print()\n",
"print('Y = \\n', Y)\n",
"print()\n",
"\n",
"# We perform basic element-wise operations using arithmetic symbols and functions\n",
"print('X + Y = \\n', X + Y)\n",
"print()\n",
"print('add(X,Y) = \\n', np
...
subtract(X,Y))\n",
"print()\n",
"print('X * Y = \\n', X * Y)\n",
"print()\n",
"print('multiply(X,Y) = \\n', np
...
divide(X,Y))"
],
"execution_count": 11,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"X = \n",
" [[1 2]\n",
" [3 4]]\n",
"\n",
"Y = \n",
" [[5
...
5]\n",
" [7
...
5]]\n",
"\n",
"X + Y = \n",
" [[ 6
...
5]\n",
" [10
...
5]]\n",
"\n",
"add(X,Y) = \n",
" [[ 6
...
5]\n",
" [10
...
5]]\n",
"\n",
"X - Y = \n",
" [[-4
...
5]\n",
" [-4
...
5]]\n",
"\n",
"subtract(X,Y) = \n",
" [[-4
...
5]\n",
" [-4
...
5]]\n",
"\n",
"X * Y = \n",
" [[ 5
...
]\n",
" [22
...
]]\n",
"\n",
"multiply(X,Y) = \n",
" [[ 5
...
]\n",
" [22
...
]]\n",
"\n",
"X / Y = \n",
" [[0
...
30769231]\n",
" [0
...
47058824]]\n",
"\n",
"divide(X,Y) = \n",
" [[0
...
30769231]\n",
" [0
...
47058824]]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sB3FyKXnNokr",
"colab_type": "text"
},
"source": [
"We can also apply mathematical functions, such as sqrt(x), to all elements of an ndarray at
once
...
array([1,2,3,4])\n",
"\n",
"# We print x\n",
"print()\n",
"print('x = ', x)\n",
"\n",
"# We apply different mathematical functions to all elements of x\n",
"print()\n",
"print('EXP(x) =', np
...
sqrt(x))\n",
"print()\n",
"print('POW(x,2) =',np
...
71828183 7
...
08553692 54
...
1
...
73205081 2
...
Statistical functions provide us with statistical information about the elements in an ndarray
...
array([[1,2], [3,4]])\n",
"\n",
"# We print x\n",
"print()\n",
"print('X = \\n', X)\n",
"print()\n",
"\n",
"print('Average of all elements in X:', X
...
mean(axis=0))\n",
"print('Average of all elements in the rows of X:', X
...
sum())\n",
"print('Sum of all elements in the columns of X:', X
...
sum(axis=1))\n",
"print()\n",
"print('Standard Deviation of all elements in X:', X
...
std(axis=0))\n",
"print('Standard Deviation of all elements in the rows of X:', X
...
median(X))\n",
"print('Median of all elements in the columns of X:', np
...
median(X,axis=1))\n",
"print()\n",
"print('Maximum value of all elements in X:', X
...
max(axis=0))\n",
"print('Maximum value of all elements in the rows of X:', X
...
min())\n",
"print('Minimum value of all elements in the columns of X:', X
...
min(axis=1))"
],
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"text": [
"\n",
"X = \n",
" [[1 2]\n",
" [3 4]]\n",
"\n",
"Average of all elements in X: 2
...
3
...
5 3
...
118033988749895\n",
"Standard Deviation of all elements in the columns of X: [1
...
]\n",
"Standard Deviation of all elements in the rows of X: [0
...
5]\n",
"\n",
"Median of all elements in X: 2
...
3
...
5 3
...
"
]
},
{
"cell_type": "code",
"metadata": {
"id": "KPLD2A_UN0Fe",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 368
},
"outputId": "67f75eba-a2ea-4f34-b65a-d298d39a74a1"
},
"source": [
"# We create a 2 x 2 ndarray\n",
"X = np
...
33333333 0
...
1
...
Broadcasting is the term used to describe how NumPy handles element-wise
arithmetic operations with ndarrays of different shapes
...
\n",
"\n",
"In the examples above, NumPy is working behind the scenes to broadcast 3 along the
ndarray so that they have the same shape
...
\n",
"\n",
"Subject to certain constraints, Numpy can do the same for two ndarrays of different
shapes, as we can see below
...
array([1,2,3])\n",
"\n",
"# We create a 3 x 3 ndarray\n",
"Y = np
...
array([1,2,3])
...
In
general, NumPy can do this provided that the smaller ndarray, such as the 1 x 3 ndarray in our
example, can be expanded to the shape of the larger ndarray in such a way that the resulting
broadcast is unambiguous
...
scipy
...
13
...
broadcasting
...
"
]
},
{
"cell_type": "code",
"metadata": {
"id": "5VV4j0doOiSS",
"colab_type": "code",
"colab": {}
},
"source": [
"import numpy as np\n",
"\n",
"X = "
],
"execution_count": null,
"outputs": []
}
]
}
Title: Basics of PYTHON(DSA)
Description: PYTHON,DSA ,that is data structures and algorithms of python control statments, numpy
Description: PYTHON,DSA ,that is data structures and algorithms of python control statments, numpy