Python

Python: numpy.reshape() function Tutorial with examples

Understanding numpy.reshape() function Tutorial with examples

In this article we will see how we can use numpy.reshape() function to change the shape of a numpy array.

numpy.reshape() :

Syntax:- numpy.reshape(a, newshape, order='C')

where,

  • a : Array, list or list of lists which need to be reshaped.
  • newshape : New shape which is a tuple or a int. (Pass tuple for converting a 2D or 3D array and Pass integer for creating array of 1D shape.)
  • order : Order in which items from given array will be used. (‘C‘: Read items from array in row-wise manner, ‘F‘: Read items from array in column-wise manner, ‘A‘: Read items from array based on memory order of items)

Converting shapes of Numpy arrays using numpy.reshape() :

Use numpy.reshape() to convert a 1D numpy array to a 2D Numpy array :

To pass 1D numpy array to 2D numpy array we will pass array and tuple i.e. (3×3) as numpy to reshape() function.

import numpy as sc
# Produce a 1D Numpy array from a given list
numArr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 92])
print('Original Numpy array:')
print(numArr)
# Convert the 1D Numpy array to a 2D Numpy array
arr_twoD = sc.reshape(numArr, (3,3))
print('2D Numpy array:')
print(arr_twoD)
Output :
Original Numpy array:
[10 20 30 40 50 60 70 80 92]
2D Numpy array:
[[10 20 30]
 [40 50 60]
 [70 80 90]]

New shape must be compatible with the original shape :

The new shape formed must be compatible with the shape of array passed i.e. if rows denoted by ‘R’, columns by ‘C’, total no. of items by ‘N’ then new shape must satisfy the relation R*C=N otherwise it will give rise to error.

import numpy as sc
# Produce a 1D Numpy array from a given list
numArr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 92])
print('Original Numpy array:')
print(numArr)
# convert the 1D Numpy array to a 2D Numpy array
arr_twoD = sc.reshape(numArr, (3,2))
print('2D Numpy array:')
print(arr_twoD)
Output :
ValueError: total size of new array must be unchanged

Using numpy.reshape() to convert a 1D numpy array to a 3D Numpy array :

We can convert a 1D numpy array into 3D numpy array passing array and shape of 3D array as tuple to reshape() function.

import numpy as sc
# Produce a 1D Numpy array from a given list
numArr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 91, 95, 99])
print('Original Numpy array:')
print(numArr)
# Convert the 1D Numpy array to a 3D Numpy array
arr_threeD = sc.reshape(numArr, (3,2,2))
print('3D Numpy array:')
print(arr_threeD)
Output :
Original Numpy array:
[10 20 30 40 50 60 70 80 90 91 95 99]
3D Numpy array:
[[[10 20]
  [30 40]]
 [[50 60]
  [70 80]]
 [[90 91]
  [95 99]]]

Use numpy.reshape() to convert a 3D numpy array to a 2D Numpy array :

We can also even convert a 3D numpy array to 2D numpy array.

import numpy as sc
# Create a 3D numpy array
arr_threeD = sc.array([[[10, 20],
                   [30, 40],
                   [50, 60]],
                 [[70, 80],
                  [90, 91],
                  [95, 99]]])
print('3D Numpy array:')
print(arr_threeD)
# Converting 3D numpy array to numpy array of size 2x6
arr_twoD = sc.reshape(arr_threeD, (2,6))
print('2D Numpy Array:')
print(arr_twoD)
Output :
3D Numpy array:
[[[10 20]
  [30 40]
  [50 60]]
 [[70 80]
  [90 91]
  [95 99]]]
2D Numpy Array:
[[10 20 30 40 50 60]
 [70 80 90 91 95 99]]

Use numpy.reshape() to convert a 2D numpy array to a 1D Numpy array :

If we pass a numpy array and ‘-1’ to reshape() then it will get convert into array of any shape to a flat array.

import numpy as sc
arr_twoD = sc.array([[10, 20, 30],
                [30, 40, 50],
                [60, 70, 82]])     
# Covert numpy array of any shape to 1D array
flatn_arr = sc.reshape(arr_twoD, -1)
print('1D Numpy array:')
print(flatn_arr) 
Output :
1D Numpy array:
[10 20 30 30 40 50 60 70 82]

numpy.reshape() returns a new view object if possible :

If possible in some scenarios reshape() function returns a view of the passed object. If we modify anything in view object it will reflect in main objet and vice-versa.

import numpy as sc
# create a 1D Numpy array
num_arr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 92])  
# Get a View object of any shape 
arr_twoD = sc.reshape(num_arr, (3,3))
print('Original array:')
print(arr_twoD)
# Modify the 5th element of the original array 
# Modification will also be visible in view object
num_arr[4] = 9
print('Modified 1D Numpy array:')
print(num_arr)
print('2D Numpy array:')
print(arr_twoD)
Output :
Original array:
[[10 20 30]
 [40 50 60]
 [70 80 92]]
Modified 1D Numpy array:
[10 20 30 40  9 60 70 80 90]
2D Numpy array:
[[10 20 30]
 [40  9 60]
 [70 80 90]]

How to check if reshape() returned a view object ?

In some scenarios reshape() function may not return a view object. We can check what object reshape() returns by seeing its base attribute if it is view or not.

If base attribute is None then it is not a view object, else it is a view object i.e. base attribute point to original array object.

import numpy as sc
# create a 1D Numpy array
num_arr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
arr_twoD = sc.reshape(num_arr, (3,3))
if arr_twoD.base is not None:
    print('arr_twoD is a view of original array')
    print('base array : ', arr_twoD.base)
Output :
arr_twoD is a view of original array
base array :  [10 20 30 40 50 60 70 80 90]

numpy.reshape() & different type of order parameters :

We can also pass order parameter whose value can be ‘C’ or ‘F’ or ‘A’. This parameter will decide in which order the elements of given array will be used. Default value of order parameter is ‘C’.

Convert 1D to 2D array row wise with order ‘C’ :

                By passing order paramter ‘C’ in reshape() function the given array will be read row wise.

import numpy as sc
# create a 1D Numpy array
num_arr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 92])
print('original array:')
print(num_arr)
# Covert 1D numpy array to 2D by reading array in row wise manner
arr_twoD = sc.reshape(num_arr, (3, 3), order = 'C')
print('2D array being read in row wise manner:')
print(arr_twoD)
Output :
original array:
[10 20 30 40 50 60 70 80 92]
2D array being read in row wise manner:
[[10 20 30]
 [40 50 60]
 [70 80 90]]

Convert 1D to 2D array column wise with order ‘F’ :

                By passing order parameter ‘C’ in reshape() function the given array will be read row wise.

import numpy as sc
# create a 1D Numpy array
num_arr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 92])
print('original array:')
print(num_arr)
# Covert 1D numpy array to 2D by reading array in column wise manner
arr_twoD = sc.reshape(num_arr, (3, 3), order = 'F')
print('2D array being read in column wise manner:')
print(arr_twoD)
Output :
original array:
[10 20 30 40 50 60 70 80 92]
2D array being read in column wise manner:
[[10 40 70]
 [20 50 80]
 [30 60 90]]

Convert 1D to 2D array by memory layout with parameter order “A” :

                If we pass order as ‘A’ in reshape() function, then items of input array will be read  basis on internal memory unit.

Here it will read elements based on memory layout of original given array and it does not consider the current view of input array

import numpy as sc
# create a 1D Numpy array
num_arr = sc.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
print('Original 1D array: ',num_arr)
# Create a 2D view object and get transpose view of it
arr_twoD = sc.reshape(num_arr, (3, 3)).T
print('2D transposed View:')
print(arr_twoD)
# Read elements in row wise from memory layout of original 1D array
flatn_arr = sc.reshape(arr_twoD, 9, order='A')
print('Flattened 1D array')
print(flatn_arr)
Output :
Original 1D array:  [10 20 30 40 50 60 70 80 90]
2D transposed View:
[[10 40 70]
 [20 50 80]
 [30 60 90]]
Flattened 1D array
[10 20 30 40 50 60 70 80 90]

Convert the shape of a list using numpy.reshape() :

  • In reshape() function we can pass list or list of list instead of array.
import numpy as sc
num_list = [10,20,30,40,50,60,70,80,90]
# To convert a list to 2D Numpy array
arr_twoD = sc.reshape(num_list, (3,3))
print('2D Numpy array:')
print(arr_twoD)
Output :
2D Numpy array:
[[10 20 30]
 [40 50 60]
 [70 80 90]]
  • We can also convert a 2D numpy array to list of list
import numpy as sc
num_list = [10,20,30,40,50,60,70,80,90]
# Convert a given list to 2D Numpy array
arr_twoD = sc.reshape(num_list, (3,3))
print('2D Numpy array:')
print(arr_twoD)
# Convert the 2D Numpy array to list of list
list_list = [ list(elem) for elem in arr_twoD]
print('List of List: ')
print(list_list)
Output :
2D Numpy array:
[[10 20 30]
 [40 50 60]
 [70 80 90]]
List of List:
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]

 

 

Python: numpy.reshape() function Tutorial with examples Read More »

Pandas : Change data type of single or multiple columns of Dataframe in Python

Changeing data type of single or multiple columns of Dataframe in Python

In this article we will see how we can change the data type of a single or multiple column of Dataframe in Python.

Change Data Type of a Single Column :

We will use series.astype() to change the data type of columns

Syntax:- Series.astype(self, dtype, copy=True, errors='raise', **kwargs)

where Arguments:

  • dtype : It is python type to which whole series object will get converted.
  • errors : It is a way of handling errors, which can be ignore/ raise and default value is ‘raised’. (raise- Raise exception in case of invalid parsing , ignore- Return the input as original in case of invalid parsing
  • copy : bool (Default value is True) (If False- Will make change in current object , If True- Return a copy)

Returns: If copy argument is true, new Series object with updated type is returned.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different data type of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
print(studObj)
print(studObj.dtypes)
Output :
Name        Age       Hobby         Height
0  Rohit      34        Swimming     155
1  Ritik        25        Cricket          179
2  Salim      26        Music            187
3   Rani       29       Sleeping         154
4   Sonu      17       Singing          184
5  Madhu    20       Travelling       165
6   Devi       22        Art                141

Name      object
Age          int64
Hobby     object
Height     int64
dtype:      object

Change data type of a column from int64 to float64 :

We can change data type of a column a column e.g.  Let’s try changing data type of ‘Age’ column from int64 to float64. For this we have to write Float64 in astype() which will get reflected in dataframe.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different datatype of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Change data type of column 'Age' to float64
studObj['Age'] = studObj['Age'].astype('float64')
print(studObj)
print(studObj.dtypes)
Output :
Name   Age       Hobby  Height
0  Rohit  34.0    Swimming     155
1  Ritik  25.0     Cricket     179
2  Salim  26.0       Music     187
3   Rani  29.0    Sleeping     154
4   Sonu  17.0     Singing     184
5  Madhu  20.0  Travelling     165
6   Devi  22.0         Art     141
Name       object
Age           float64
Hobby      object
Height      int64
dtype: object

Change data type of a column from int64 to string :

Let’s try to change the data type of ‘Height’ column to string i.e. Object type. As we know by default value of astype() was True, so it returns a copy of passed series with changed Data type which will be assigned to studObj['Height'].

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Change data type of column 'Marks' from int64 to float64
studObj['Age'] = studObj['Age'].astype('float64')
# Change data type of column 'Marks' from int64 to Object type or string
studObj['Height'] = studObj['Height'].astype('object')
print(studObj)
print(studObj.dtypes)
Output :
Name   Age       Hobby Height
0  Rohit  34.0    Swimming    155
1  Ritik  25.0     Cricket    179
2  Salim  26.0       Music    187
3   Rani  29.0    Sleeping    154
4   Sonu  17.0     Singing    184
5  Madhu  20.0  Travelling    165
6   Devi  22.0         Art    141
Name       object
Age           float64
Hobby      object
Height     object
dtype: object

Change Data Type of Multiple Columns in Dataframe :

To change the datatype of multiple column in Dataframe we will use DataFeame.astype() which can be applied for whole dataframe or selected columns.

Synatx:- DataFrame.astype(self, dtype, copy=True, errors='raise', **kwargs)

Arguments:

  • dtype : It is python type to which whole series object will get converted. (Dictionary of column names and data types where given colum will be converted to corrresponding types.)
  • errors : It is a way of handling errors, which can be ignore/ raise and default value is ‘raised’.
  • raise : Raise exception in case of invalid parsing
  • ignore : Return the input as original in case of invalid parsing
  • copy : bool (Default value is True) (If False- Will make change in current object , If True- Return a copy)

Returns: If copy argument is true, new Series object with updated type is returned.

Change Data Type of two Columns at same time :

Let’s try to convert columns ‘Age’ & ‘Height of int64 data type to float64 & string respectively. We will pass a Dictionary to Dataframe.astype() where it contain column name as keys and new data type as values.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different datatype of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Convert the data type of column Age to float64 & column Marks to string
studObj = studObj.astype({'Age': 'float64', 'Height': 'object'})
print(studObj)
print(studObj.dtypes)
Output :
Name   Age       Hobby Height
0  Rohit  34.0    Swimming    155
1  Ritik  25.0     Cricket    179
2  Salim  26.0       Music    187
3   Rani  29.0    Sleeping    154
4   Sonu  17.0     Singing    184
5  Madhu  20.0  Travelling    165
6   Devi  22.0         Art    141
Name       object
Age           float64
Hobby      object
Height     object
dtype: object

Handle errors while converting Data Types of Columns :

Using astype() to convert either a column or multiple column we can’t pass the content which can’t be typecasted. Otherwise error will be produced.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different datatype of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Trying to change dataype of a column with unknown dataype
try:
        studObj['Name'] = studObj['Name'].astype('xyz')
except TypeError as ex:
        print(ex)

Output :
data type "xyz" not understood

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 – Modify a Dataframe

Pandas : Change data type of single or multiple columns of Dataframe in Python Read More »

Python Word Count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists)

Python Word Count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists)

In this tutorial, we will discuss python word count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists). Also, you guys can see some of the approaches on Output a List of Word Count Pairs. Let’s use the below links and have a quick reference on this python concept.

How to count the number of words in a sentence, ignoring numbers, punctuation, and whitespace?

First, we will take a paragraph after that we will clean punctuation and transform all words to lowercase. Then we will count how many times each word occurs in that paragraph.

Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
for char in '-.,\n':
Text=Text.replace(char,' ')
Text = Text.lower()
# split returns a list of words delimited by sequences of whitespace (including tabs, newlines, etc, like re's \s) 
word_list = Text.split()
print(word_list)

Output:

['python', 'can', 'be', 'easy', 'to', 'pick', 'up', 'whether', 
"you're", 'a', 'first', 'time', 'programmer', 'or', "you're",
 'experienced', 'with', 'other', 'languages', 'the', 'following', 
'pages', 'are', 'a', 'useful', 'first', 'step', 'to', 'get', 'on', 'your', 
'way', 'writing', 'programs', 'with', 'python!the', 'community',
 'hosts', 'conferences', 'and', 'meetups', 'collaborates', 'on', 'code', 
'and', 'much', 'more', "python's", 'documentation', 'will', 'help', 'you',
 'along', 'the', 'way', 'and', 'the', 'mailing', 'lists', 'will', 'keep', 'you', 'in',
 'touch', 'python', 'is', 'developed', 'under', 'an', 'osi', 'approved', 'open',
 'source', 'license', 'making', 'it', 'freely', 'usable', 'and', 'distributable', 
'even', 'for', 'commercial', 'use', "python's", 'license', 'is', 'administered', 
'python', 'is', 'a', 'general', 'purpose', 'coding', 'language—which', 'means', 
'that', 'unlike', 'html', 'css', 'and', 'javascript', 'it', 'can', 'be', 'used', 'for', 'other', 
'types', 'of', 'programming', 'and', 'software', 'development', 'besides', 'web', 
'development', 'that', 'includes', 'back', 'end', 'development', 'software', 
'development', 'data', 'science', 'and', 'writing', 'system', 'scripts', 'among', 'other', 'things']

So in the above output, you can see a list of word count pairs which is sorted from highest to lowest.

Thus, now we are going to discuss some approaches.

Also Check:

Output a List of Word Count Pairs (Sorted from Highest to Lowest)

1. Collections Module:

The collections module approach is the easiest one but for using this we have to know which library we are going to use.

from collections import Counter

Counter(word_list).most_common()

In this, collections module, we will import the counter then implement this in our programme.

from collections import Counter
Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
word_list = Text.split()
count=Counter(word_list).most_common()
print(count)

Output:

[('and', 7), ('a', 3), ('other', 3), ('is', 3), ('can', 2), ('be', 2), ('to', 2), 
("you're", 2), ('first', 2), ('with', 2), ('on', 2), ('writing', 2), ("Python's", 2),
 ('will', 2), ('you', 2), ('the', 2), ('it', 2), ('for', 2), ('software', 2), ('development,', 2), 
('Python', 1), ('easy', 1), ('pick', 1), ('up', 1), ('whether', 1), ('time', 1), ('programmer', 1),
 ('or', 1), ('experienced', 1), ('languages.', 1), ('The', 1), ('following', 1), ('pages', 1), ('are', 1), 
('useful', 1), ('step', 1), ('get', 1), ('your', 1), ('way', 1), ('programs', 1), ('Python!The', 1), 
('community', 1), ('hosts', 1), ('conferences', 1), ('meetups,', 1), ('collaborates', 1), ('code,', 1), 
('much', 1), ('more.', 1), ('documentation', 1), ('help', 1), ('along', 1), ('way,', 1), ('mailing', 1),
 ('lists', 1), ('keep', 1), ('in', 1), ('touch.Python', 1), ('developed', 1), ('under', 1), ('an', 1),
 ('OSI-approved', 1), ('open', 1), ('source', 1), ('license,', 1), ('making', 1), ('freely', 1),
 ('usable', 1), ('distributable,', 1), ('even', 1), ('commercial', 1), ('use.', 1), ('license', 1), 
('administered.Python', 1), ('general-purpose', 1), ('coding', 1), ('language—which', 1), ('means', 1),
 ('that,', 1), ('unlike', 1), ('HTML,', 1), ('CSS,', 1), ('JavaScript,', 1), ('used', 1), ('types', 1), ('of', 1), 
('programming', 1), ('development', 1), ('besides', 1), ('web', 1), ('development.', 1), ('That', 1), 
('includes', 1), ('back', 1), ('end', 1), ('data', 1), ('science', 1), ('system', 1), ('scripts', 1), ('among', 1), ('things.', 1)]

2. Using For Loops:

This is the second approach and in this, we will use for loop and dictionary get method.

from collections import Counter
Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
word_list = Text.split()
# Initializing Dictionary
d = {}
# counting number of times each word comes up in list of words (in dictionary)
for word in word_list: 
    d[word] = d.get(word, 0) + 1
word_freq = []
for key, value in d.items():
    word_freq.append((value, key))
word_freq.sort(reverse=True) 
print(word_freq)

Output:

[(7, 'and'), (3, 'other'), (3, 'is'), (3, 'a'), (2, "you're"), (2, 'you'), (2, 'writing'),
 (2, 'with'), (2, 'will'), (2, 'to'), (2, 'the'), (2, 'software'), (2, 'on'), (2, 'it'), (2, 'for'), (
2, 'first'), (2, 'development,'), (2, 'can'), (2, 'be'), (2, "Python's"), (1, 'your'), (1, 'whether'),
 (1, 'web'), (1, 'way,'), (1, 'way'), (1, 'useful'), (1, 'used'), (1, 'use.'), (1, 'usable'), (1, 'up'), 
(1, 'unlike'), (1, 'under'), (1, 'types'), (1, 'touch.Python'), (1, 'time'), (1, 'things.'), (1, 'that,'), 
(1, 'system'), (1, 'step'), (1, 'source'), (1, 'scripts'), (1, 'science'), (1, 'programs'),
 (1, 'programming'), (1, 'programmer'), (1, 'pick'), (1, 'pages'), (1, 'or'), (1, 'open'), 
(1, 'of'), (1, 'much'), (1, 'more.'), (1, 'meetups,'), (1, 'means'), (1, 'making'), (1, 'mailing'),
 (1, 'lists'), (1, 'license,'), (1, 'license'), (1, 'language—which'), (1, 'languages.'), (1, 'keep'),
 (1, 'includes'), (1, 'in'), (1, 'hosts'), (1, 'help'), (1, 'get'), (1, 'general-purpose'), (1, 'freely'), 
(1, 'following'), (1, 'experienced'), (1, 'even'), (1, 'end'), (1, 'easy'), (1, 'documentation'),
 (1, 'distributable,'), (1, 'development.'), (1, 'development'), (1, 'developed'), (1, 'data'), 
(1, 'conferences'), (1, 'community'), (1, 'commercial'), (1, 'collaborates'), (1, 'coding'), 
(1, 'code,'), (1, 'besides'), (1, 'back'), (1, 'are'), (1, 'an'), (1, 'among'), (1, 'along'), (1, 'administered.Python'),
 (1, 'The'), (1, 'That'), (1, 'Python!The'), (1, 'Python'), (1, 'OSI-approved'), (1, 'JavaScript,'), (1, 'HTML,'), (1, 'CSS,')]

So in the above approach, we have used for loop after that we reverse the key and values so they can be sorted using tuples. Now we sorted from lowest to highest.

3. Not using Dictionary Get Method:

So in this approach, we will not use the get method dictionary.

from collections import Counter
Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
word_list = Text.split()
# Initializing Dictionary
d = {}

# Count number of times each word comes up in list of words (in dictionary)
for word in word_list:
    if word not in d:
        d[word] = 0
    d[word] += 1
word_freq = []
for key, value in d.items():
    word_freq.append((value, key))
word_freq.sort(reverse=True)
print(word_freq)

Output:

[(7, 'and'), (3, 'other'), (3, 'is'), (3, 'a'), (2, "you're"), (2, 'you'), (2, 'writing'),
 (2, 'with'), (2, 'will'), (2, 'to'), (2, 'the'), (2, 'software'), (2, 'on'), (2, 'it'), (2, 'for'), (2, 'first'), 
(2, 'development,'), (2, 'can'), (2, 'be'), (2, "Python's"), (1, 'your'), (1, 'whether'), (1, 'web'),
 (1, 'way,'), (1, 'way'), (1, 'useful'), (1, 'used'), (1, 'use.'), (1, 'usable'), (1, 'up'), (1, 'unlike'),
 (1, 'under'), (1, 'types'), (1, 'touch.Python'), (1, 'time'), (1, 'things.'), (1, 'that,'), (1, 'system'), 
(1, 'step'), (1, 'source'), (1, 'scripts'), (1, 'science'), (1, 'programs'), (1, 'programming'), 
(1, 'programmer'), (1, 'pick'), (1, 'pages'), (1, 'or'), (1, 'open'), (1, 'of'), (1, 'much'),
 (1, 'more.'), (1, 'meetups,'), (1, 'means'), (1, 'making'), (1, 'mailing'), (1, 'lists'), (1, 'license,'), 
(1, 'license'), (1, 'language—which'), (1, 'languages.'), (1, 'keep'), (1, 'includes'), (1, 'in'), (1, 'hosts'),
 (1, 'help'), (1, 'get'), (1, 'general-purpose'), (1, 'freely'), (1, 'following'), (1, 'experienced'), 
(1, 'even'), (1, 'end'), (1, 'easy'), (1, 'documentation'), (1, 'distributable,'), (1, 'development.'),
 (1, 'development'), (1, 'developed'), (1, 'data'), (1, 'conferences'), (1, 'community'), (1, 'commercial'),
 (1, 'collaborates'), (1, 'coding'), (1, 'code,'), (1, 'besides'), (1, 'back'), (1, 'are'), (1, 'an'), (1, 'among'),
 (1, 'along'), (1, 'administered.Python'), (1, 'The'), (1, 'That'), (1, 'Python!The'), (1, 'Python'), 
(1, 'OSI-approved'), (1, 'JavaScript,'), (1, 'HTML,'), (1, 'CSS,')]

4. Using Sorted:

# initializing a dictionary
d = {};

# counting number of times each word comes up in list of words
for key in word_list: 
    d[key] = d.get(key, 0) + 1

sorted(d.items(), key = lambda x: x[1], reverse = True)

Conclusion:

In this article, you have seen different approaches on how to count the number of words in a sentence, ignoring numbers, punctuation, and whitespace. Thank you!

Python Word Count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists) Read More »

Program to Find Square Root of a Number in C++ and Python Programming

Python Program to Find the Square Root | Square Root in C++

Given a number ,the task is to find the square root of the given number.

Note :

Square root exists for even complex numbers too.

Examples:

Example1:

Input:

number = 16

Output:

The Square root of the given number 16 = 4.0

Example2:

Input:

number = 4 + 3 j

Output:

The Square root of the given number (4+3j) = (2.1213203435596424+0.7071067811865476j)

Example3:

Input:

number = 12

Output:

The Square root of the given number 12 = 3.4641016151377544

Program to Find Square Root 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:For Positive numbers in Python using math.sqrt function

The math module in Python’s standard library can be used to solve math problems in code. It has a lot of useful functions like remainder() and factorial() (). sqrt, the Python square root function, is also included ().

That’s what there is to it! You can now measure square roots with math.sqrt().

sqrt() has a simple user interface.

It only requires one parameter, x, which represents the square for which you are attempting to calculate the square root (as you might recall). This would be 16 in the previous case.

The square root of x as a floating point number is returned by sqrt(). This will be 4.0 in the case.

We store the number in number and use the sqrt function to find the square root in this program. This program can be used for any positive real number. However, it does not deal for negative or complex numbers.

Below is the implementation:

# importing math module
import math
# given number
number = 16
# finding square root
numberSqrt = math.sqrt(number)
# printing the square root of  given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number 16 = 4.0

Method #2:Using ** operator

We can calculate square root of a number easily by using ** operator.

Below is the implementation:

# importing math module
import math
# given number
number = 16
# finding square root
numberSqrt = number**0.5
# printing the square root of given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number 16 = 4.0

Method #3:Using sqrt function in C++

In C++, the sqrt() function returns the square root of a number.

The <cmath> header file defines this feature.
A single non-negative argument is passed to the sqrt() function.

A domain error occurs when a negative argument is passed to the sqrt() function.

Below is the implementation:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{ // given number
    float number = 16, numberSqrt;
    // calculating the square root of the given number
    numberSqrt = sqrt(number);
    // printing the square root of the given number
    cout << "The square root of the given number " << number
         << " = " << numberSqrt;

    return 0;
}

Output:

The square root of the given number 16 = 4

Method #4:Using cmath.sqrt() function in python

The sqrt() function from the cmath (complex math) module will be used in this program.

Below is the implementation:

# importing cmath module
import cmath
# given complex number
number = 4 + 3j
# finding square root of the given complex number
numberSqrt = cmath.sqrt(number)
# printing the square root of  given number
print("The Square root of the given number", number, "=", numberSqrt)

Output:

The Square root of the given number (4+3j) = (2.1213203435596424+0.7071067811865476j)

Note:

We must use the eval() function instead of float() if we want to take a complex number as input directly, such as 4+5j

In Python, the eval() method can be used to transform complex numbers into complex objects.

 
Related Programs:

Python Program to Find the Square Root | Square Root in C++ Read More »

Program to Trim Whitespace From a String

Python Program to Trim Whitespace From a String

Strings:

A string in Python is an ordered collection of characters that is used to represent and store text-based data. Strings are stored in a contiguous memory area as individual characters. It can be accessed in both forward and backward directions. Characters are merely symbols. Strings are immutable Data Types in Python, which means they can’t be modified once they’ve been generated.

Trim in Python:

What does it mean to trim a string, and how do you accomplish it in Python? Trimming a string refers to the process of removing whitespace from around text strings.

Given a string, the task is to trim the white spaces in the given string.

Examples:

Example1:

Input:

given_string = "    B     T  e  c  h   G    e       e      k   s       "

Output:

Before removing white spaces given string=   B Tec  h G e         e    k s    
after removing white spaces given string= BTechGeeks

Removing trialing and leading whitespaces

Example3:

Input:

given_string = "            croyez              "

Output:

Before removing white spaces given string=         croyez             
after removing white spaces given string= croyez

Example2:

Input:

given_string = "          BtechGeeks          "

Output:

Before removing white spaces given string=           BtechGeeks               
after removing white spaces given string= BtechGeeks

Program to Trim Whitespace From a String in Python

There are several ways to trim the whitespace from the given string 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 replace() function

Replace() function:

The replace() method copies the string and replaces the previous substring with the new substring. The original string has not been altered.

If the old substring cannot be retrieved, the copy of the original string is returned.

We can use the replace() function in python to trim the white spaces in Python.

We need to replace the white space with empty string to achieve our task.

Below is the implementation:

# given string
given_string = "  B Tec  h G e        e    k s    "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# removing white spaces from the given string
# using replace() function
# we replace white space with empty string

given_string = given_string.replace(" ", "")
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)

Output:

Before removing white spaces given string=   B Tec  h G e        e    k s    
after removing white spaces given string= BTechGeeks

Method #2:Using split() and join() functions

Below is the implementation:

# given string
given_string = "          B  t      echG   eeks               "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# removing white spaces from the given string
given_string = "".join(given_string.split())
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)

Output:

Before removing white spaces given string=           B  t      echG   eeks               
after removing white spaces given string= BtechGeeks

Removing only leading and Trailing whitespaces:

Method #3:Using strip()

String in Python. The strip() function, as the name implies, eliminates all leading and following spaces from a string. As a result, we may use this method in Python to completely trim a string.

Syntax:

string.strip(character)

Character : It is a non-mandatory parameter. If the supplied character is supplied to the strip() function, it will be removed from both ends of the string.

Below is the implementation:

# given string
given_string = "          BtechGeeks               "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# removing white spaces from the given string
# removing trailing and leading white spaces

given_string = given_string.strip()
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)

Output:

Before removing white spaces given string=           BtechGeeks               
after removing white spaces given string= BtechGeeks

strip() removes the leading and trailing characters from a string, as well as whitespaces.

However, if the string contains characters such as ‘\n’ and you wish to remove only the whitespaces, you must specifically mention it in the strip() method, as seen in the following code.

Explanation:

Here the regular Expression removes only the leading and trailing whitespaces from the given string

Method #4:Using Regex

We can remove leading and trailing whitespaces in regex as shown below:

Below is the implementation:

# importing regex
import re
# given string
given_string = "       BtechGeeks        "
# printing the original string before removing white spaces
print("Before removing white spaces given string=", given_string)
# using regex to remove trailing and leading white spaces from the given string
given_string = re.sub(r'^\s+|\s+$', '', given_string)
# printing the original string before after white spaces
print("after removing white spaces given string=", given_string)
Before removing white spaces given string=        BtechGeeks        
after removing white spaces given string= BtechGeeks

Explanation:

Here the regular Expression removes only the leading and trailing whitespaces from the given string
Related Programs:

Python Program to Trim Whitespace From a String Read More »

Program to Remove Punctuations From a String

Python Program to Remove Punctuations From a String

Strings:

A string in Python is an ordered collection of characters that is used to represent and store text-based data. Strings are stored in a contiguous memory area as individual characters. It can be accessed in both forward and backward directions. Characters are merely symbols. Strings are immutable Data Types in Python, which means they can’t be modified once they’ve been generated.

Punctuation:

Punctuation is the practice, action, or method of putting points or other small marks into texts to help comprehension; the division of text into phrases, clauses, and so on.

Punctuation is really effective. They have the ability to completely alter the meaning of a sentence.

Given a string, the task is to remove the punctuations from the given string in python.

Examples:

Example1:

Input:

given_string="BTechGeeks, is best : for ! Python.?[]() ;"

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Example2:

Input:

given_string="pythond dsf,;]]][-*&$%@#^()!or ! Python.?[]() ;"

Output:

printing the given string after removing the punctuations : 
pythond dsfor  Python

Remove Punctuations From a String in Python

When working with Python strings, we frequently run into situations where we need to remove specific characters. This can be used for data preprocessing in the Data Science domain as well as day-to-day programming. Let’s look at a few different approaches to doing this work.

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 for loop and string concatenation

This is the most brute method of accomplishing this operation. We do this by checking for punctuations in raw strings that contain punctuations, and then constructing a string without those punctuations.

To begin, we’ll create a string of punctuations. Then, using a for loop, we iterate over the specified string.

The membership test is used in each iteration to determine if the character is a punctuation mark or not. If the character is not punctuation, we add (concatenate) it to an empty string. Finally, we show the string that has been cleaned up.

Below is the implementation:

# taking a string which stores all the punctuations and
# initialize it with some punctuations
punctuationString = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# given string which we want  to remove the punctuation marks
given_string = "BTechGeeks, is best: for !Python.?[]() ;"

# Taking a empty which stores all the characteers of original string without punctuations
noPunctuationString = ""
# removing all punctuations from the string
# Traversing the original string
for character in given_string:
  # if character not in punctuationString which means it is not a punctuation
  # hence concate this character to noPunctuationString
    if character not in punctuationString:
        noPunctuationString = noPunctuationString + character

# printing the given string after removing the punctuations
print("printing the given string after removing the punctuations : ")
print(noPunctuationString)

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Method #2:Using for loop and replace() function

This is the most brute method of accomplishing this operation. We do this by checking for punctuations in raw strings that contain punctuations, and then constructing a string without those punctuations.

Approach:

  • Make a string out of all the punctuation characters.
  • Create a for loop and an if statement for each iteration such that if a punctuation character is detected, it is replaced by a white space.

Below is the implementation:

# taking a string which stores all the punctuations and
# initialize it with some punctuations
punctuationString = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# given string which we want  to remove the punctuation marks
given_string = "BTechGeeks, is best: for !Python.?[]() ;"

# removing all punctuations from the string
# Traversing the original string
for character in given_string:
  # if character  in punctuationString which means it is  a punctuation
  # hence replace it with white space
    if character in punctuationString:
        given_string = given_string.replace(character, "")
# printing the given string after removing the punctuations
print("printing the given string after removing the punctuations : ")
print(given_string)

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Method #3:Using Regex

The regex module in Python allows us to work with and alter various regular expressions.

To deal with regular expressions, we’ll need to import the library listed below:

import re

To remove the punctuation marks, we’ll use re.sub(pattern, replacement, given string).
Pattern : We wish to replace the punctuation marks or the pattern of expressions with this pattern.
Replacement: The string that will be used to replace the pattern.
We’ll also utilise the re.sub() method to replace the punctuation marks with the substitute ‘ ‘, which is a white space.

Below is the implementation:

# importing regex
import re
# given string which we want  to remove the punctuation marks
given_string = "BTechGeeks, is best: for !Python.?[]() ;"
# using regex
noPunctuationString = re.sub(r'[^\w\s]', '', given_string)

# printing the given string after removing the punctuations
print("printing the given string after removing the punctuations : ")
print(noPunctuationString)

Output:

printing the given string after removing the punctuations : 
BTechGeeks is best for Python

Related Programs:

Python Program to Remove Punctuations From a String Read More »

Python Program to Swap Two Variables

Python Program to Swap Two Variables

Swapping:

Swapping two variables in computer programming means that the variables values are swapped.

Given two variables x , y the task is to swap the variable values.

Examples:

Example1:(Integer Values Swapping)

Input:

p=1372 q=4129

Output:

printing the values of integer variables p and q before swapping
p = 1372
q = 4129
printing the values of integer variables p and q after swapping
p = 4129
q = 1372

Example2:(Boolean Values Swapping)

Input:

p=True q=False

Output:

printing the values of boolean variables p and q before swapping
p = True
q = False
printing the values of boolean variables p and q after swapping
p = False
q = True

Example3:(Decimal Values Swapping)

Input:

p = 2738.321  q = 83472.421

Output:

printing the values of decimal variables p and q before swapping
p = 2738.321
q = 83472.421
printing the values of decimal variables p and q after swapping
p = 83472.421
q = 2738.321

Example4:(String Values Swapping)

Input:

p="Vicky" q="Tara"

Output:

printing the values of string variables p and q before swapping
p = vicky
q = Tara
printing the values of string variables p and q after swapping
p = Tara
q = vicky

Swapping two Variables in Python

There are several ways to swap two variables 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 temporary Variable

A temp variable is the easiest way to change the values of two variables. The temp variables will save the value of the fist variable (temp = a), allow the two variables to swap (a = b), and assign the them to the second variable. The temp variables will then be saved.

Below is the implementation:

# given variables of different types
# given two integer variables
p = 1372
q = 4129
# printing the values of p and q before swapping
print("printing the values of integer variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two integers
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of integer variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two decimal variables
p = 2738.321
q = 83472.421
# printing the values of p and q before swapping
print("printing the values of decimal variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two decimal variables
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of decimal variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two boolean variables
p = True
q = False
# printing the values of p and q before swapping
print("printing the values of boolean variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two boolean values
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of boolean variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two string variables
p = "vicky"
q = "Tara"
# printing the values of p and q before swapping
print("printing the values of string variables p and q before swapping")
print("p =", p)
print("q =", q)
# using temp variable to swap the two string
# swapping two variables
tempo = p
p = q
q = tempo
# printing the values of p and q after swapping
print("printing the values of string variables p and q after swapping")
print("p =", p)
print("q =", q)

Output:

printing the values of integer variables p and q before swapping
p = 1372
q = 4129
printing the values of integer variables p and q after swapping
p = 4129
q = 1372
printing the values of decimal variables p and q before swapping
p = 2738.321
q = 83472.421
printing the values of decimal variables p and q after swapping
p = 83472.421
q = 2738.321
printing the values of boolean variables p and q before swapping
p = True
q = False
printing the values of boolean variables p and q after swapping
p = False
q = True
printing the values of string variables p and q before swapping
p = vicky
q = Tara
printing the values of string variables p and q after swapping
p = Tara
q = vicky

Method #2:Using comma operator in Python without temporary variable(Tuple Swap)

The tuple packaging and sequence unpackaging can also be used to change the values of two variables without a temporary variable. There are a number of methods in which tuples can be created, including by dividing tuples using commas. In addition, Python evaluates the right half of a task on its left side. Thus the variables are packed up and unpacked with the same amount of commas separating the target variables on the left hand side by selecting the comma on the right hand hand side of the sentence.

It may be used for more than two variables, provided that both sides of the state have the same amount of variables

Below is the implementation:

# given variables of different types
# given two integer variables
p = 1372
q = 4129
# printing the values of p and q before swapping
print("printing the values of integer variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of integer variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two decimal variables
p = 2738.321
q = 83472.421
# printing the values of p and q before swapping
print("printing the values of decimal variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of decimal variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two boolean variables
p = True
q = False
# printing the values of p and q before swapping
print("printing the values of boolean variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of boolean variables p and q after swapping")
print("p =", p)
print("q =", q)
# given two string variables
p = "vicky"
q = "Tara"
# printing the values of p and q before swapping
print("printing the values of string variables p and q before swapping")
print("p =", p)
print("q =", q)
# swapping two variables
p, q = q, p
# printing the values of p and q after swapping
print("printing the values of string variables p and q after swapping")
print("p =", p)
print("q =", q)

Output:

printing the values of integer variables p and q before swapping
p = 1372
q = 4129
printing the values of integer variables p and q after swapping
p = 4129
q = 1372
printing the values of decimal variables p and q before swapping
p = 2738.321
q = 83472.421
printing the values of decimal variables p and q after swapping
p = 83472.421
q = 2738.321
printing the values of boolean variables p and q before swapping
p = True
q = False
printing the values of boolean variables p and q after swapping
p = False
q = True
printing the values of string variables p and q before swapping
p = vicky
q = Tara
printing the values of string variables p and q after swapping
p = Tara
q = vicky

Related Programs:

Python Program to Swap Two Variables Read More »

Program to Count the Number of Digits Present In a Number

Python Program to Count the Number of Digits Present In a Number

Count the number of numbers in a number using Python. We learn how to count the total number of digits in a number using python in this tutorial. The program receives the number and prints the total number of digits in the given number. We’ll show you three ways to calculate total numbers in a number.

Examples:

Example1:

Input:

number = 27482

Output:

The total digits present in the given number= 5

Example2:

Input:

number = 327

Output:

The total digits present in the given number= 3

Program to Count the Number of Digits Present In a Number in Python

There are several ways to count the number of digits present in a number 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

The idea behind this approach is to keep eliminating the number’s rightmost digit one by one until the number reaches zero. The following algorithm will be used for this approach:

Approach:

  • Scan the input or give static input and store it in number variable
  • Make one counter variable to keep track of the entire number count. At the start of the program, set this variable to zero.
  • Using a while loop, eliminate the number’s rightmost digit or convert the number to this new number. For instance, if the number is 782, convert it to 78, then to 7, and lastly to 0.
  • On each conversion, increment the counter variable by one. Continue until the number reaches zero. This counter variable will hold the total digit count of the number at the end of the while loop.
  • Print the counter variable.

Below is the implementation:

# given number
given_number = 27482
# initializing a variable that counts the digit of the given number.
# initlaize it with 0
digits_count = 0
# using while loop to traverse digit by digit of the given number
while (given_number > 0):
    # divide the number by 10
    given_number = given_number//10
    # increment the count
    digits_count = digits_count + 1
# printing the digits count of the given number
print("The total digits present in the given number=", digits_count)

Output:

The total digits present in the given number= 5

Explanation:

  • The while loop is iterated in this program until the test expression given_num!= 0 is evaluated to 0 (false).
  • After the first repetition, given_num will be divided by 10 and will have the value 2748. The count is then increased to 1.
  • The result of given_num after the second iteration is 274, and the count is increased to 2.
  • The value of given_num will be 27 after the third iteration, and the count will be 3.
  • The value of given_num will be 2 after the fourth iteration, and the count will be increased to 4.
  • The value of given_num will be 0 after the fourth iteration, and the count will be increased to 5.
  • The loop then ends when the condition is false.

Method #2:Using string length function

We begin by converting the number value to a string using str (). The length of the string is then determined using len ().

Below is the implementation:

# given number
given_number = 27482
# converting the given_number to string using str() function
strnum = str(given_number)
# finding the digits of the given_number using len() function
digits_count = len(strnum)
# printing the digits count of the given number
print("The total digits present in the given number=", digits_count)

Output:

The total digits present in the given number= 5

Method #3:Converting number to list and calculating length of list

Approach:

  • We first convert the given number to string using str function.
  • Then we convert this string to list of digits using list() function.
  • Then calculate the length of list using len() function in list.

Below is the implementation:

# given number
given_number = 27482
# converting the given_number to list of digits using list() function
numberslist = list(str(given_number))
# finding the digits of the given_number using len() function
digits_count = len(numberslist)
# printing the digits count of the given number
print("The total digits present in the given number=", digits_count)

Output:

The total digits present in the given number= 5

This is similar to method #2
Related Programs:

Python Program to Count the Number of Digits Present In a Number Read More »

Program to Display Calendar

Program to Display Calendar in Python

To work with date-related tasks, Python has a built-in function called calendar. In this posts, you will learn how to display the calendar for a specific date.

The calendar class in Python’s Calendar module allows for calculations based on date, month, and year for a variety of tasks. Furthermore, the Text Calendar and HTML Calendar classes in Python allow you to customize the calendar and use it as needed.

Examples:

Input:

given year=2001 month =2

Output:

   February 2001
Mo Tu We Th Fr Sa Su
                   1   2   3  4
 5    6    7    8   9  10 11
12  13 14  15 16  17 18
19  20 21  22 23  24 25
26  27 28

Program to Display Calendar 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.

1)Displaying the month

To print a calendar in Python, we can use the built-in function month() from the Calendar module. To display a Calendar for a given month, the function month() requires two arguments: the first is the year in four-digit format, such as 2003, 1997, 2018, and the second is the month in two-digit format, such as 01, 04, 12, and so on.

This program prompts the user for the year and month, and then calls the month() function, which displays the Calendar for the given month for a given year, based on the input.

Below is the implementation:

# importing calendar function
import calendar

# given year
given_year = 2001

# given month
given_month = 2

# printing the calendar of given year and month
print(calendar.month(given_year, given_month))

Output:

   February 2001
Mo Tu We Th Fr Sa Su
                   1   2   3  4
 5    6    7    8   9  10 11
12  13 14  15 16  17 18
19  20 21  22 23  24 25
26  27 28

2)Displaying the year

The calendar module is imported in the program  below. The module’s built-in function calender() accepts a year and displays the calendar for that year.

Below is the implementation:

# importing calendar function
import calendar
# given year
given_year = 2001
# printing the calendar of given year
print(calendar.calendar(given_year))

Output:

                                                            2001
   
      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
        1  2  3  4  5  6  7                1  2  3  4                1  2  3  4
 8    9  10  11 12 13 14       5  6  7  8  9 10 11       5  6  7  8  9 10 11
15  16  17   18   19   20   21      12 13 14 15 16 17 18      12 13 14 15 16 17 18
22  23  24  25 26 27 28      19 20 21 22 23 24 25      19 20 21 22 23 24 25
29 30 31                  26 27 28                  26 27 28 29 30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                   1                         1  2  3  4  5  6                   1  2  3
 2  3  4  5  6  7  8                7  8  9 10 11 12 13          4  5  6  7  8  9 10
 9 10 11 12 13 14 15      14 15 16 17 18 19 20        11 12 13 14 15 16 17
16 17 18 19 20 21 22      21 22 23 24 25 26 27        18 19 20 21 22 23 24
23 24 25 26 27 28 29      28 29 30 31                            25 26 27 28 29 30
30

        July                                August                   September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
                   1                          1  2  3  4  5                                              1  2
 2  3  4  5  6  7  8                  6  7  8  9 10 11 12                   3  4  5  6  7  8  9
 9 10 11 12 13 14 15      13 14 15 16 17 18 19         10 11 12 13 14 15 16
16 17 18 19 20 21 22      20 21 22 23 24 25 26         17 18 19 20 21 22 23
23 24 25 26 27 28 29      27 28 29 30 31                 24 25 26 27 28 29 30
30 31

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7                1  2  3  4                            1  2
 8  9 10 11 12 13 14                5  6  7  8  9 10 11                      3  4  5  6  7  8  9
15 16 17 18 19 20 21      12 13 14 15 16 17 18      10 11 12 13 14 15 16
22 23 24 25 26 27 28      19 20 21 22 23 24 25      17 18 19 20 21 22 23
29 30 31                             26 27 28 29 30            24 25 26 27 28 29 30
                                                    31

 
Related Programs:

Program to Display Calendar in Python Read More »

Find the Largest Among Three Numbers

Python Program to Find the Largest Among Three Numbers

Given three numbers the task is to find the largest number among the three numbers.

Prerequisite:

Python IF…ELIF…ELSE Statements

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:

Input:

number1 = 3
number2 = 5
number3 = 7

Output:

The largest number among the three numbers = 7

Input:

number1 = 9
number2 = 9
number3 = 2

Output:

The largest number among the three numbers = 9

Determine the largest of three numbers

Below are the ways to determine the largest among the three numbers:

Method #1 :Using Conditional Statements

The three numbers are stored in number 1, number 2, and number 3, in that order. We use the if…elif…else ladder to find and show the largest of the three.

Here we compare one number with other two numbers using if..elif…else ladder.

Below is the implementation:

# function which returns the largest number among the three numbers
def findLargest(number1, number2, number3):
  # comparing first number with other two numbers
    if (number1 >= number2) and (number1 >= number3):
        return(number1)
      # comparing second number with other two numbers
    elif (number2 >= number1) and (number2 >= number3):
        return(number2)
    else:
        return(number3)


number1 = 3
number2 = 5
number3 = 7
# passing the three numbers to find largest number among the three numbers
print("The largest number among the three numbers =",
      findLargest(number1, number2, number3))

Output:

The largest number among the three numbers = 7

Method #2: Using max function

We can directly use max function to know the largest number among the three numbers.

We provide the given three numbers as arguments to max function and print it.

Below is the implementation:

number1 = 3
number2 = 5
number3 = 7
# using max function to find largest numbers
maxnum = max(number1, number2, number3)
print("The largest number among the three numbers =",
      maxnum)

Output:

The largest number among the three numbers = 7

Method #3: Converting the numbers to list and using max function to print max element of list

Approach:

  • Convert the given number to list using [].
  • Print the maximum element of list using max() function

Below is the implementation:

number1 = 3
number2 = 5
number3 = 7
# converting given 3 numbers to list
listnum = [number1, number2, number3]
# using max function to find largest numbers from the list
maxnum = max(listnum)
print("The largest number among the three numbers =",
      maxnum)

Output:

The largest number among the three numbers = 7

Related Programs:

Python Program to Find the Largest Among Three Numbers Read More »