Python

Program to Display the Multiplication Table

Python Program to Display the Multiplication Table

Given a number the task is to print the multiplication table of the given number from 1 to 10.

Prerequisite:

1)For Loop in python

2)While Loop in python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Examples:

Example 1:

Input:

number=8

Output:

8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80

Example 2:

Input:

number=34

Output:

34 * 1 = 34
34 * 2 = 68
34 * 3 = 102
34 * 4 = 136
34 * 5 = 170
34 * 6 = 204
34 * 7 = 238
34 * 8 = 272
34 * 9 = 306
34 * 10 = 340

Program to Print the Multiplication Table

Below are the ways to print the multiplication table:

Method #1:Using for loop

Approach:

To iterate 10 times, we used the for loop in combination with the range() function. The range() function’s arguments are as follows: (1, 11). That is, greater than or equal to 1 and less than 11.

We’ve shown the variable num multiplication table (which is 8 in our case). To evaluate for other values, adjust the value of num in the above program.

Below is the implementation:

# given number
number = 8
# using for loop with range
for i in range(1, 11):
    print(number, "*", i, "=", number*i)

Output:

8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80

Method #2:Using While loop

Approach:

  • First we initialize a variable say multiplicationfactor to 1.
  • We increment the value of  multiplicationfactor by 1 till the multiplicationfactor is less than or equal to 10.
  • Print the multiplication table.

Below is the implementation:

# given number
number = 8
# initializing a variable say multiplication factor to 1
multiplicationfactor = 1
# loop till multiplicationfactor is less than or equal to 10
while(multiplicationfactor <= 10):
    print(number, "*", multiplicationfactor, "=", number*multiplicationfactor)
    # increment the multiplicationfactor by 1
    multiplicationfactor = multiplicationfactor+1

Output:

8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80

Related Programs:

Python Program to Display the Multiplication Table Read More »

Program to Find the Sum of Natural Numbers

Python Program to Find the Sum of Natural Numbers

Natural Number:

A natural number, as the name implies, is a number that occurs often and clearly in nature. It is a whole number with no negative digits.

Some mathematicians agree that a natural number must contain 0 while others do not. As a result, a list of natural numbers can be described as follows

N= 1 , 2 , 3 , 4 , 5 etc.

Prerequisite:

  1. For Loop in python
  2. While Loop in python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Examples:

Example 1:

Input :

number = 5

Output:

Sum of natural numbers till 5 = 15

Example 2:

Input :

number = 43

Output:

Sum of natural numbers till 43 = 946

Program to Find the Sum of Natural Numbers in Python

Below are the ways to print the sum of natural numbers in python:

Method #1:Using for loop

  • Take a variable say sum and initialize to 0
  • Iterate from 1 to N using for loop and range() function.
  • For each iteration add the iterater value to sum.
  • Print the sum.

Below is the implementation:

# given number
number = 5
# Take a variable say sum and initialize to 0.
sum = 0
# Iterate from 1 to number using for loop and range function
for i in range(1, number+1):
    # add the iterater value to sum.
    sum = sum + i
# print the sum
print("Sum of natural numbers till", number, "=", sum)

Output:

Sum of natural numbers till 5 = 15

Method #2:Using while loop

  • Take a variable say sum and initialize to 0
  • The while loop was used to iterate until number became zero.
  • In each loop iteration, we have added the number to sum and decreased the value of number by 1.
  • Print the sum.

Below is the implementation:

# given number
number = 5
# Take a variable say sum and initialize to 0.
sum = 0
# iterate till the number becomes 0 using while loop
while(number != 0):
    # add the number value to sum
    sum = sum+number
    # decrement the number
    number = number-1
# print the sum
print("Sum of natural numbers", "=", sum)

Output:

Sum of natural numbers = 15

Method #3:Using mathematical formula

Instead of iterating till number the best and efficient solution is to use mathematical formula given below.

Formula:

sum = ( n * (n +1) ) / 2

Below is the implementation:

# given number
number = 5
# Using mathematical formula
sum = (number * (number+1))//2
# print the sum
print("Sum of natural numbers till", number, "=", sum)

Output:

Sum of natural numbers till 5 = 15

Related Programs:

Python Program to Find the Sum of Natural Numbers Read More »

Compute the Power of a Number

Python Program to Compute the Power of a Number

Power:

A power is an expression that describes repeated multiplication of the same factor.

Examples:

Example1:

Positive Exponent:

Input:

base = 7 power = 4

Output:

The result is 2401

Example2:

Negative Exponent:

Input:

base = 7 power = -2

Output:

The result is 0.02040816326530612

This article will teach you how to compute the power of a number.

Calculate the Power of a Number

Below are the ways to calculate the power of a number :

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using While loop

  • Scan the base and power values.
  • Create a variable resultValue and initialize it with 1.
  • Using the while loop, we continue to multiply the resultValue by the base until the exponent reaches zero.
  • Print the resultValue.

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# initialize the result value to 1
resultValue = 1
# Loop till power becomes 0
while powerValue != 0:
    resultValue = resultValue * baseValue
    powerValue = powerValue-1

print("The result is", resultValue)

Output:

The result is 2401

Method #2: Using For loop

  • Instead of a while loop, we’ve used a for loop here.
  • Scan the base and power values.
  • Create a variable resultValue and initialize it with 1.
  • The exponent is decremented by one for each iteration, and the resultValue is multiplied by the base exponent a number of times.
  • Print the resultValue.

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# initialize the result value to 1
resultValue = 1
# Loop till power becomes 0 using for loop
for i in range(powerValue):
    resultValue = resultValue*baseValue
    # decrement the powerValue
    powerValue = powerValue-1

print("The result is", resultValue)

Output:

The result is 2401

Note:

If you have a negative exponent, none of the above methods will function.
You must use the pow() function from the Python library to accomplish this.

Method #3:Using pow() function

We can calculate the power value using pow() function.

It works for negative exponent too.

1)Calculating the power of positive exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# calculating the power of base
resultValue = pow(baseValue, powerValue)
# print the result
print("The result is", resultValue)

Output:

The result is 2401

2)Calculating the power of negative exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = -2
# calculating the power of base
resultValue = pow(baseValue, powerValue)
# print the result
print("The result is", resultValue)

Output:

The result is 0.02040816326530612

Method #4:Using ** operator in Python

We can calculate the power value using ** .

It works for negative exponent too.

1)Calculating the power of positive exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = 4
# calculating the power of base
resultValue = baseValue**powerValue
# print the result
print("The result is", resultValue)

Output:

The result is 2401

2)Calculating the power of negative exponent

Below is the implementation:

# given base value and power value
baseValue = 7
powerValue = -2
# calculating the power of base
resultValue = baseValue**powerValue
# print the result
print("The result is", resultValue)

Output:

The result is 0.02040816326530612

Related Programs:

Python Program to Compute the Power of a Number Read More »

Python Program to Solve Quadratic Equation

Python Program to Solve Quadratic Equation

Solve Quadratic Equation using Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Quadratic Equation

Quadratics or quadratic equations are polynomial equations of the second degree, which means that they contain at least one squared word.

ax2 + bx + c = 0

where x is an unknown variable and the numerical coefficients a , b , c.

2)Discriminant value

Discriminant = b ^ 2 - 4 * a *c

Based on the value of discriminant there are three types of roots for Quadratic Equation

3)Calculating roots of Quadratic Equation

roots = ( -b + sqrt(b ^ 2 - 4 * a *c) ) / (2 * a)   , ( -b - sqrt(b ^ 2 - 4 * a *c) ) / (2 * a)

Where sqrt is square root.

4)Types of roots

i)Real and distinct roots

When the Value of discriminant is greater than 0 then there exist two distinct roots for the quadratic equation

which can be calculated using the above roots formula.

Examples:

Input:

a = 2
b = -7
c = 6

Output:

The two distinct roots are : 
(2+0j)
(1.5+0j)

ii)Real and equal roots

When the Value of discriminant is equal to 0 then there exist two equal roots for the quadratic equation .

which can be calculated using the above roots formula.

Examples:

Input:

a = 1
b = -4
c = 4

Output:

The two equal roots are : 
2.0 2.0

iii)Complex roots

When the Value of discriminant is greater than 0 then there exist two complex roots for the quadratic equation .

which can be calculated using the above roots formula.

Examples:

Input:

a = 5
b = 2
c = 3

Output:

There exists two complex roots:
(-1+1.7320508075688772j)
(-1-1.7320508075688772j)

5)Approach

  • To perform complex square root, we imported the cmath module.
  • First, we compute the discriminant.
  • Using if..elif..else we do the below steps
  • If the value of discriminant is  greater than 0 then we print real roots using mathematical formula.
  • If the value of discriminant is  equal to 0 then we print two equal roots using mathematical formula.
  • If the value of discriminant is  less than 0 then we print two complex roots using mathematical formula.

6)Implementation:

Below is the implementation:

# importing cmath
import cmath
# given a,b,c values
a = 2
b = -7
c = 6
discriminant = (b**2) - (4*a*c)
# checking if the value of discriminant is greater than 0
if(discriminant > 0):
    # here exist the two distinct roots and we print them
    # calculating the roots
    root1 = (-b+discriminant) / (2 * a)
    root2 = (-b-discriminant) / (2 * a)
    # printing the roots

    print("The two distinct roots are : ")
    print(root1)
    print(root2)
# checking if the value of discriminant is equal to 0
elif(discriminant == 0):
    # here exist the two equal roots
    # calculating single root here discriminant is 0 so we dont need to write full formulae
    root = (-b)/(2*a)
    # printing the root
    print("The two equal roots are : ")
    print(root, root)
# else there exists complex roots
else:
    # here exist the two complex roots
    # calculating complex roots
    realpart = -b/(2*a)
    complexpart = discriminant/(2*a)*(-1)
    # printing the roots
    print("There exists two complex roots:")
    print(realpart, "+", complexpart, "i")
    print(realpart, "-", complexpart, "i")

Output:

The two distinct roots are : 
(2+0j)
(1.5+0j)

Related Programs:

Python Program to Solve Quadratic Equation Read More »

Pandas : Convert a DataFrame into a list of rows or columns in python | (list of lists)

Converting a DataFrame into a list of rows or columns in python | (list of lists)

In this article, we will discuss how we can convert a dataframe into a list, by converting each row or column into a list and creating a python lists from them.

Let’s first, create a dataframe,

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
print(studentId)
Output :
     Name     Age       City           Score
0    Arun      23     Chennai         127.0
1   Priya       31      Delhi            174.5
2   Ritik        24     Mumbai         181.0
3   Kimun     37    Hyderabad     125.0
4   Sinvee    16      Delhi              175.5
5    Kunu    28     Mumbai           115.0
6    Lisa      31       Pune              191.0

Convert a Dataframe into a list of lists – Rows Wise :

In the dataframe created above, we must fetch each line as a list and create a list of these lists.

Let’s see how we can do this

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])

# By Converting a dataframe to the list of rows (list of lists)
listOfRows = studentId.to_numpy().tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 23, 'Chennai', 127.0], ['Priya', 31, 'Delhi', 174.5], ['Ritik', 24, 'Mumbai', 181.0], ['Kimun', 37, 'Hyderabad', 125.0], ['Sinvee', 16, 'Delhi', 175.5], ['Kunu', 28, 'Mumbai', 115.0], ['Lisa', 31, 'Pune', 191.0]]
<class 'list'>

It Converted the data name into a sequential target list, that is, each linked list contains a line of data names. But what happened in one line ?

How did it work?

Let’s divide one line above into several lines to understand the concept behind it.

Step 1: Convert the Dataframe to a nested Numpy array using DataFrame.to_numpy() :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = studentId.to_numpy()
print(numpy_2d_array)
print(type(numpy_2d_array))
Output :
[['Arun' 23 'Chennai' 127.0]
['Priya' 31 'Delhi' 174.5]
['Ritik' 24 'Mumbai' 181.0]
['Kimun' 37 'Hyderabad' 125.0]
['Sinvee' 16 'Delhi' 175.5]
['Kunu' 28 'Mumbai' 115.0]
['Lisa' 31 'Pune' 191.0]]
<class 'numpy.ndarray'>

Actually DataFrame.to_numpy() converts data name into Numpy array. So we have a 2D Numpy array here. We have confirmed that by printing the type of returned item.

Step 2: Convert 2D Numpy array into a list of lists :

Numpy provides a function tolist(), which converts Numpy Array into a list. Let’s call that function in the object built above 2D Numpy,

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = studentId.to_numpy()

# By Converting 2D numpy array to the list of lists
listOfRows = numpy_2d_array.tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 23, 'Chennai', 127.0], ['Priya', 31, 'Delhi', 174.5], ['Ritik', 24, 'Mumbai', 181.0], ['Kimun', 37, 'Hyderabad', 125.0], ['Sinvee', 16, 'Delhi', 175.5], ['Kunu', 28, 'Mumbai', 115.0], ['Lisa', 31, 'Pune', 191.0]]
<class 'list'>

It converted 2D Numpy Array into a list.

So, this is how we changed the dataframe to 2D Numpy Array and then List of Lists, where each nested list represents a dataframe line.

Convert a Dataframe into a list of lists – Column Wise :

Now turn each column into a list and create a list of these lists,

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# Convert a dataframe to the list of columns i.e. list of lists
listOfRows = studentId.transpose().values.tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 'Priya', 'Ritik', 'Kimun', 'Sinvee', 'Kunu', 'Lisa'], [23, 31, 24, 37, 16, 28, 31], ['Chennai', 'Delhi', 'Mumbai', 'Hyderabad', 'Delhi', 'Mumbai', 'Pune'], [127.0, 174.5, 181.0, 125.0, 175.5, 115.0, 191.0]]

<class 'list'>

How did it work?

It works on the same concept we discussed above, just one more step here i.e.

Step 1: Transpose the dataframe to convert rows as columns and columns as rows :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])



# Transposing the dataframe, rows are now columns and columns are now rows
transposedObj = studentId.transpose()
print(transposedObj)

Output :
0      1       2          3       4       5      6
Name      Arun  Priya   Ritik      Kimun  Sinvee    Kunu   Lisa
Age         23     31      24         37      16      28     31
City   Chennai  Delhi  Mumbai  Hyderabad   Delhi  Mumbai   Pune
Score    127.0  174.5   181.0      125.0   175.5   115.0  191.0

transposedObj is a transpose of the original data i.e. lines in studentId with columns in transposedObj and columns in studentId are lines in transposedObj.

Step 2: Convert the Dataframe to a nested Numpy array using DataFrame.to_numpy() :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# Transposing the dataframe, rows are now columns and columns are now rows
transposedObj = studentId.transpose()


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = transposedObj.to_numpy()
print(numpy_2d_array)
print(type(numpy_2d_array))
Output :
[['Arun' 'Priya' 'Ritik' 'Kimun' 'Sinvee' 'Kunu' 'Lisa']
[23 31 24 37 16 28 31]
['Chennai' 'Delhi' 'Mumbai' 'Hyderabad' 'Delhi' 'Mumbai' 'Pune']
[127.0 174.5 181.0 125.0 175.5 115.0 191.0]]
<class 'numpy.ndarray'>

Step 3: Convert 2D Numpy array into a list of lists. :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# Transposing the dataframe, rows are now columns and columns are now rows
transposedObj = studentId.transpose()


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = transposedObj.to_numpy()

#By Converting 2D numpy array to the list of lists
listOfRows = numpy_2d_array.tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 'Priya', 'Ritik', 'Kimun', 'Sinvee', 'Kunu', 'Lisa'], [23, 31, 24, 37, 16, 28, 31], ['Chennai', 'Delhi', 'Mumbai', 'Hyderabad', 'Delhi', 'Mumbai', 'Pune'], [127.0, 174.5, 181.0, 125.0, 175.5, 115.0, 191.0]]
<class 'list'>

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Select items from a Dataframe

Pandas : Convert a DataFrame into a list of rows or columns in python | (list of lists) Read More »

Python Programming – NumPy

Learn NumPy Library in Python – Complete Guide

Creating Numpy Arrays

  • Create NumPy Arrays from list, tuple, or list of lists
  • Create NumPy Arrays from a range of evenly spaced numbers using np.arrange().
  • Create NumPy Array of zeros (0’s) using np.zeros()
  • Create 1D / 2D NumPy Array filled with ones (1’s) using np.ones()
  • Create NumPy Array of different shapes & initialize with identical values using numpy.full()
  • Create NumPy Array with same sized samples over an interval in Python using numpy.linspace()
  • Create a NumPy Array of bool value.

Adding Elements in Numpy Array

Searching in Numpy Arrays

Get Metadata of Numpy Array

Selecting elements from Numpy Array

Modifying a Numpy Array

Converting NumPy Array to Other Data Structures

Numpy Array and File I/O

Verify Contents of Numpy Array

Counting Elements in Numpy Array

Advance Topics about Numpy Array

  • What is a Structured Numpy Array and how to create and sort it in Python?
  • numpy.zeros() & numpy.ones() | Create a numpy array of zeros or ones

Python Programming – NumPy

NUMPY

As discussed previously, simple one dimensional array operations can be executed using list, tuple etc. But carrying out multi-dimensional array operations using list is not easy. Python has an array module which provides methods for creating array, but they are slower to index than list. A good choice for carrying array operations is by using “NumPy” package.

NumPy is a Python package (licensed under the BSD license) which is helpful in scientific computing by providing multi-dimensional array object, various derived objects (such as masked arrays and matrices), and collection of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, basic linear algebra, basic statistical operations, and many more. At the core of the NumPy package, there is array object which encapsulates n-dimensional arrays of homogeneous data types. There are several important differences between the NumPy array and the standard Python sequence:

  • NumPy array has a fixed size at creation, unlike Python list (which can grow dynamically). Changing the size of a ndarray will create a new array and delete the original.
  • All elements in a NumPy array are required to be of the same data type.
  • NumPy array facilitates advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python’s built-in sequences.

History

NumPy is built on (and is a successor to) the successful “Numeric” package. Numeric was reasonably complete and stable, remains available, but is now obsolete. Numeric was originally written in 1995 largely by Jim Hugunin, while he was a graduate student at MIT. In 2001, Travis Oliphant along with Eric Jones and Pearu Peterson created “SciPy”, which had the the strenght of Numeric package along additional functionality. At about the same time as SciPy was being built, some Numeric users were hitting up against the limited capabilities of Numeric.

As a result, “numarray” (now obselete) was created by Perry Greenfield, Todd Miller, and RickWhite at the Space Science Telescope Institute as a replacement for Numeric. In early 2005, Travis Oliphant initiated an effort to bring the diverging community together under a common framework. The effort was paid off with the release of a new package Numpy (with version 0.9.2) in early 2006, which is an amalgam of the code base of Numeric with additional features of numarray. The NumPy name was christened from the unofficial name of “Numerical Python”.

Universal functions

NumPy provides familiar mathematical functions such as sin ( ), cos ( ), exp ( ), etc. In NumPy, these are called “universal functions”. Within NumPy, these functions operate element-wise on an array, producing an array as output.

>>> a=np . arange ( 3 ) 
>>> a 
array ( [ 0 , 1 , 2 ] ) 
>>> np . exp ( a ) 
array ( [ 1 . , 2 . 71828183 , 7 . 3890561 ] )
>>> np . sqrt ( a ) 
array ( [ 0 . , 1 . , 1 . 41421356 ] )

The Matrix Class

There is also a matrix class, which returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations.

>>> np . matrix ( [ [ 1 . 0 , 2 . 0 ] , [ 3 . 0 , 4 . 0 ] ] ) 
matrix ( [ [ 1 . , 2 . ] , 
[ 3 . , 4 . ] ] )
>>> a=np . matrix ( ' 1 . 0 2 . 0 ; 3 . 0 4 . 0 ' ) 
>>> a
matrix ( [ [ 1 . , 2 . ] , 
[ 3 . , 4 . ] ] )
>>> a . T                                                                           # Transpose of a matrix
matrix ( [ [ 1 . , 3 . ] ,
[ 2 . , 4 .] ] ) 
>>> x=np . matrix ( ' 5 . 0 7 . 0 ' )
>>> y=x.T
>>> y
matrix ( [ [ 5 . ] ,
[ 7 . ] ] )
>>> a*y                                                                          # Matrix multiplication
matrix ( [ [ 19 . ] ,
[ 43 . ] ] )
>>> a.I                                                                           # Inverse of a matrix
matrix ( [ [ -2 . , 1 . ] ,
[ 1 . 5 , -0 . 5 ] ] )

In this Page, We are Providing Python Programming – NumPy. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – NumPy Read More »

numpy.count_nonzero() – Python

Using numpy.count_nonzero() Function

In this article we will discuss about how to count values based on conditions in 1D or 2D Numpy Arrays using numpy.count_nonzero() function in python. So let’s explore the topic.

numpy.count_nonzero() :

A function numpy.count_nonzero() is provided by Numpy module in python to count the non-zero values in array,

Syntax- numpy.count_nonzero(arr, axis=None, keepdims=False)

Where,

  • arr : It represents the array like object in which we want to count the non zero values.
  • axis : It represents along which we want to count the values. If the value is 1 then then it will count non zero values in rows  and if the value is 0 then it will count non zero values in columns and if the value is None then it will count non zero values by flattening the arrays.
  • kepdims : It takes the bool value and if the value is True, then the axes that are counted are left in the result as dimensions with size one.

Which returns int or array of int containing count of non zero values in numpy array and if the Axis is provided then it returns the array of count of values along the axis.

Counting non zero values in a Numpy Array :

Suppose we have a numpy array with some zeros and non zero values. Now we will count the non zero values using numpy.count_nonzero() function.

So let’s see the program to understand how it actually works.

# Program :

import numpy as np
# numpy array from list created
arr = np.array([2, 3, 0, 5, 0, 0, 5, 0, 5])
# Counting non zero elements in numpy array
count = np.count_nonzero(arr)
print('Total count of non-zero values in NumPy Array: ', count)
Output :
Total count of non-zero values in NumPy Array: 5

Counting True values in a numpy Array :

As we know in python True is equivalent to 1 and False is equivalent to 0 then we can use the numpy.count_nonzero() function to count the True values in a bool numpy array.

# Program :

import numpy as np
# Numpy Array of bool values created
arr = np.array([False, True, True, True, False, False, False, True, True])
# Counting True elements in numpy array
count = np.count_nonzero(arr)
print('Total count of True values in NumPy Array: ', count)
Output :
Total count of True values in NumPy Array: 5

Counting Values in Numpy Array that satisfy a condition :

It is very simple to count the non-zero values as we did in previous example we only passed the complete numpy array , here we will pass the condition.

So lets see the example to understand it clearly.

# Program :

import numpy as np
# A Numpy array of numbers is created
arr = np.array([2, 3, 1, 5, 4, 2, 5, 6, 5])
# Count even number of even elements in array
count = np.count_nonzero(arr % 2 == 0)
print('Total count of Even Numbers in Numpy Array: ', count)
Output :
Total count of Even Numbers in Numpy Array: 4

In the above example which element will satisfy the condition the value will be True and which will not satisfy the value will be false. And it will count the True values.

Counting Non-Zero Values in 2D Numpy Array :

By using the same numpy.count_nonzero() function we can count the non-zero values in a 2D array where the default axis value is None.

So lets see the example to understand it clearly.

# Program :

import numpy as np
# 2D Numpy Array created 
arr_2d = np.array( [[20, 30, 0],
                    [50, 0, 0],
                    [50, 0, 50]])
# counting of non zero values in complete 2D array
count = np.count_nonzero(arr_2d)
print('Total count of non zero values in complete 2D array: ', count)
Output :
Total count of non zero values in complete 2D array:  5

Counting Non-Zero Values in each row of 2D Numpy Array :

To count the non-zero values in each row of 2D numpy array just pass value of axis as 1.

So lets see the example to understand it clearly.

# Program :

import numpy as np
# Create 2D Numpy ARray
arr = np.array( [[20, 30, 0],
                    [50, 0, 0],
                    [50, 0, 50]])
# Get count of non zero values in each row of 2D array
count = np.count_nonzero(arr, axis=1)
print('Total count of non zero values in each row of 2D array: ', count)
Output :
Total count of non zero values in each row of 2D array: [2 1 2]

Counting Non-Zero Values in each column of 2D Numpy Array :

To count the non-zero values in each columnof 2D numpy array just pass value of axis as 0.

So lets see the example to understand it clearly.

# Program :

import numpy as np
# 2D Numpy Array created
arr = np.array( [[20, 30, 0],
                    [50, 0, 0],
                    [50, 0, 50]])
# counting of non zero values in each column of 2D array
count = np.count_nonzero(arr, axis=0)
print('Total count of non zero values in each column of 2D array: ', count)
Output :
Total count of non zero values in each column of 2D array: [3 1 1]

 

 

 

numpy.count_nonzero() – Python Read More »

Python Reverse String

How to Reverse a String in Python

String:

Arrays are Strings. Strings in Python, like many other common programming languages, are sequences of bytes that represent unicode characters. However, since Python lacks a character data form, a single character is simply a one-length string. Square brackets may be used to access the string’s components.

Given a string , the task is to reverse the given string in Python.

Examples:

Example1:

Input:

given_string="vikram"

Output:

The reversed string of vikram = markiv

Example2:

Input:

given_string="wor45rd"

Output:

The reversed string of wor45rd = dr54row

Explanation:

Here 4,5 are also considered as character so it is reversed succesfully

Example3:

Input:

given_string="BTechGeeks"

Output:

The reversed string of BTechGeeks = skeeGhceTB

Here it ignores the case so the reversed string contains many uppercase characters.

Reverse the string in Python

There are several ways to reverse the string in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Using Slicing

Approach:

  • Scan the given string.
  • Reverse the string using slicing using [::-1] which indicates that we traverse from end
  • Print the reversed string.

Below is the implementation:

# given string
given_string = "vikram"
# calculating the length of string
length = len(given_string)
# Reversing the string using slicing
reverse_string = given_string[len(given_string)::-1]
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

Method #2: Using join() and reversed function

We can reverse the string easily by using join() and reversed string like below.

Approach:

  • Scan the given string.
  • join the reversed string using join() function.(We can reverse the string while joining using reversed function).
  • Store it in any variable say rev_string
  • Print the reversed rev_string.

Below is the implementation:

# given string
given_string = "vikram"
# reversing using join and reversed function
rev_string = ''.join(reversed(given_string))
# print the reversed string
print("The reversed string of", given_string, "=", rev_string)

Output:

The reversed string of vikram = markiv

Method #3:Using for loop and string concatenation

Approach: 

  • Scan the givenstring.
  • Take a empty string say revstring.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • print the revstring.

Below is the implementation:

# given string
given_string = "vikram"
# taking empty string
reverse_string = ""
# calculating the length of string
length = len(given_string)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+given_string[index]
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

Method #4:Using list  and join functions

Approach:

  • Scan the given string.
  • Convert this string to list of characters using list() function.
  • Reverse the list using reverse() function
  • Join the list using join() function to get reversed string.
  • Print the reversed string.

Below is the implementation:

# given string
given_string = "vikram"
# converting to list of characters
stringlist = list(given_string)
# reverse the list
stringlist.reverse()
# convert this list to string using join
reverse_string = ''.join(stringlist)
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

Method #5 : Using while loop

This method is similar to method #2(using for loop)

Approach: 

  • Scan the givenstring.
  • Take a empty string say revstring.
  • Take a variable length which gives the length of string.
  • Loop till length is greater than or equal to 0.
  • For each iteration
  • Add each character to revstring using string concatenation.
  • Decrement the length by 1.
  • print the revstring.

Below is the implementation:

# given string
given_string = "vikram"
# taking empty string
reverse_string = ""
# calculating the length of string
length = len(given_string)-1
# using while loop
while(length >= 0):
    # adding the character of string to reverse_string
    reverse_string = reverse_string+given_string[length]
    # decrement the length
    length = length-1
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

These are methods to print the reversed string we can print directly by using loops and range() function but it doesn’t reverse the string it just print the reversed value of string.
Related Programs:

How to Reverse a String in Python Read More »

Check Palindrome in Python

Python program to check if a string is palindrome or not

Palindrome:

If a number reads the same both forward and backward, it is called a Palindrome number. And the insane part is that it doesn’t just apply to numbers. Even if a string reads the same in both directions, it is always a Palindrome!

Examples for string palindrome

Example 1:

Input: 

given_string = madam

Output:

The given string madam is palindrome

Explanation:

Here the madam word reads same from front and end so it is palindrome

Example 2:

Input: 

given_string = vicky

Output:

The given string vicky is not palindrome

Explanation:

Here vicky and ykciv are not equal so it is not a palindrome

Examples for number palindrome

Example 1:

Input: 

given_number =12321

Output:

The given number 12321 is palindrome

Explanation:

Here the number 12321  reads same from front and end so it is palindrome

Example 2:

Input: 

given_number =12345

Output:

The given number 12345 is not palindrome

Explanation:

Here 12345 and 54321 are not equal so it is not a palindrome

Checking Palindrome in Python

There are several ways to check whether the given number is palindrome or not some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using while loop to check whether the number is palindrome

Algorithm:

  • Scan the given number
  • Take another variable say duplicate_num and initialize it with given number
  • Set the variable reverse_number to 0.
  • Loop while number > 0 Loop while number > 0
  • Multiply reverse_number by 10 and add the remainder to reverse_number like below
  • reverse_number = (reverse_number * 10) + remainder
  • Divide the given number by 10 to remove the last digit.
  • If the duplicate_num and reverse_number are equal then it is palindrome.
  • Else it is not palindrome.

Below is the implementation:

# given number
given_num = 12321
# taking another variable to store the copy of original number
# and initialize it with given num
duplicate_num = given_num
# Take a variable reverse_number and initialize it to null
reverse_number = 0
# using while loop to reverse the given number
while (given_num > 0):
    # implementing the algorithm
    # getting the last digit
    remainder = given_num % 10
    reverse_number = (reverse_number * 10) + remainder
    given_num = given_num // 10
# if duplicate_num and reverse_number are equal then it is palindrome
if(duplicate_num == reverse_number):
    print("The given number", duplicate_num, "is palindrome")
else:
    print("The given number", duplicate_num, "is not palindrome")

Output:

The given number 12321 is palindrome

Method #2: Using for loop and string concatenation to check whether the number is palindrome

Approach: 

  • Scan the given number.
  • Take a empty string say revstring.
  • Convert the given number to string using str() function say strnum for this string.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • If the revstring and string_num are equal then it is palindrome.
  • Else it is not palindrome.

Below is the Implementation:

# given number
given_num = 12321
# taking empty string
reverse_string = ""
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+strnum[index]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == strnum):
    print("The given number", given_num, "is palindrome")
else:
    print("The given number", given_num, "is not palindrome")

Output:

The given number 12321 is palindrome

Method #3:Using for loop and string concatenation to check whether the string is palindrome

Approach: 

  • Scan the givenstring.
  • Take a empty string say revstring.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • If the revstring and givenstring are equal then it is palindrome.
  • Else it is not palindrome.

Below is the Implementation:

# given string
given_string = "madam"
# taking empty string
reverse_string = ""
# calculating the length of string
length = len(given_string)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+given_string[index]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == given_string):
    print("The given string", given_string, "is palindrome")
else:
    print("The given string", given_string, "is not palindrome")

Output:

The given string madam is palindrome

Method #4:Using slicing to check whether the number is palindrome

Approach:

  • Scan the given number.
  • Convert the given number to string using str() function say strnum for this string.
  • Reverse the string using slicing
  • If the revstring and string_num are equal then it is palindrome.
  • Else it is not palindrome.

Below is the implementation:

# given number
given_num = 12321
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Reversing the string using slicing
reverse_string = strnum[len(strnum)::-1]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == strnum):
    print("The given number", given_num, "is palindrome")
else:
    print("The given number", given_num, "is not palindrome")

Output:

The given number 12321 is palindrome

Method #5: Using slicing to check whether the string is palindrome

Approach:

  • Scan the given string.
  • Reverse the string using slicing
  • If the revstring and string are equal then it is palindrome.
  • Else it is not palindrome.

Below is the implementation:

# given string
given_string = "madam"
# calculating the length of string
length = len(given_string)
# Reversing the string using slicing
reverse_string = given_string[len(given_string)::-1]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == given_string):
    print("The given string", given_string, "is palindrome")
else:
    print("The given string", given_string, "is not palindrome")

Output:

The given string madam is palindrome

Related Programs:

Python program to check if a string is palindrome or not Read More »

Python- How to convert a timestamp string to a datetime object using datetime.strptime()

Python: How to convert a timestamp string to a datetime object using datetime.strptime()

In this tutorial, we will learn how to convert a timestamp string to a datetime object using datetime.strptime(). Also, you can understand how to to create a datetime object from a string in Python with examples below.

String to a DateTime object using datetime.strptime()

Thestrptime()method generates a datetime object from the given string.

Datetime module provides a datetime class that has a method to convert string to a datetime object.

Syntax:

datetime.strptime(date_string, format)

So in the above syntax, you can see that it accepts a string containing a timestamp. It parses the string according to format codes and returns a datetime object created from it.

First import datetime class from datetime module to use this,

from datetime import datetime

Also Read:

Complete Format Code List

Format CodesDescriptionExample
%dDay of the month as a zero-padded decimal number01, 02, 03, 04 …, 31
%aWeekday as the abbreviated nameSun, Mon, …, Sat
%AWeekday as full nameSunday, Monday, …, Saturday
%mMonth as a zero-padded decimal number01, 02, 03, 04 …, 12
%bMonth as an abbreviated nameJan, Feb, …, Dec
%BMonth as full nameJanuary, February, …, December
%yA Year without century as a zero-padded decimal number00, 01, …, 99
%YA Year with a century as a decimal number0001, …, 2018, …, 9999
%HHour (24-hour clock) as a zero-padded decimal number01, 02, 03, 04 …, 23
%MMinute as a zero-padded decimal number01, 02, 03, 04 …, 59
%SSecond as a zero-padded decimal number01, 02, 03, 04 …, 59
%fMicrosecond as a decimal number, zero-padded on the left000000, 000001, …, 999999
%IHour (12-hour clock) as a zero-padded decimal number01, 02, 03, 04 …, 12
%pLocale’s equivalent of either AM or PMAM, PM
%jDay of the year as a zero-padded decimal number01, 02, 03, 04 …, 366

How strptime() works?

In thestrptime()class method, it takes two arguments:

  • string (that be converted to datetime)
  • format code

In the accordance with the string and format code used, the method returns its equivalent datetime object.

Let’s see the following example, to understand how it works:

python strptime method example

where,

%d – Represents the day of the month. Example: 01, 02, …, 31
%B – Month’s name in full. Example: January, February etc.
%Y – Year in four digits. Example: 2018, 2019 etc.

Examples of converting a Time String in the format codes using strptime() method

Just have a look at the few examples on how to convert timestamp string to a datetime object using datetime.strptime() in Python and gain enough knowledge on it.

Example 1:

Let’s take an example,

from datetime import datetime
datetimeObj = datetime.strptime('2021-05-17T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 15:11:45.456777
<class 'datetime.datetime'>

So in the above example, you can see that we have converted a time string in the format “YYYY-MM-DDTHH::MM::SS.MICROS” to a DateTime object.

Let’s take another example,

Example 2:

from datetime import datetime
datetimeObj = datetime.strptime('17/May/2021 14:12:22', '%d/%b/%Y %H:%M:%S')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 14:12:22
<class 'datetime.datetime'>

So this is the other way to show timestamp here we have converted a time string in the format “DD/MM/YYYY HH::MM::SS” to a datetime object.

Example 3:

If we want to show the only date in this format “DD MMM YYYY”. We do like this,

from datetime import datetime
datetimeObj = datetime.strptime('17 May 2021', '%d %b %Y')
# Get the date object from datetime object
dateObj = datetimeObj.date()
print(dateObj)
print(type(dateObj))

Output:

2021-05-17
<class 'datetime.date'>

Example 4:

So if we want to show only time “‘HH:MM:SS AP‘” in this format. We will do like that,

from datetime import datetime
datetimeObj = datetime.strptime('08:12:22 PM', '%I:%M:%S %p') 
# Get the time object from datetime object 
timeObj = datetimeObj.time()
print(timeObj) 
print(type(timeObj))

Output:

20:12:22
<class 'datetime.time'>

Example 5:

If we want to show our timestamp in text format. We will execute like that,

from datetime import datetime
textStr = "On January the 17th of 2021 meet me at 8 PM"
datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p")
print(datetimeObj)

Output:

2021-01-17 20:00:00

Conclusion:

So in the above tutorial, you can see that we have shown different methods of how to convert a timestamp string to a datetime object using datetime.strptime(). Thank you!

Python: How to convert a timestamp string to a datetime object using datetime.strptime() Read More »