Basics of Python – Regular Expression Module

In this Page, We are Providing Basics of Python – Regular Expression Module. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – Regular Expression Module

Regular expression module

re module in python: A regular expression (also called RE, or regex, or regex pattern) is a specialized approach in Python, using which programmers can specify rules for the set of possible strings that need to be matched; this set might contain English sentences, e-mail addresses, or anything. REs can also be used to modify a string or to split it apart in various ways.

Meta characters

Most letters and characters will simply match themselves. For example, the regular expression test will match the string test exactly. There are exceptions to this rule; some characters are special “meta characters”, and do not match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Some of the meta characters are discussed below:

Meta character

Description

Example

[ ]

Used to match a set of characters.

[time]

The regular expression would match any of the characters t, i, m, or e.

[a-z]

The regular expression would match only lowercase characters.

Used to complement a set of characters. [time]

The regular expression would match any other characters than t, i, m or e.

$

Used to match the end of string only. time$

The regular expression would match time in ontime, but will not match time in timetable.

*

Used to specify that the previous character can be matched zero or more times. tim*e

The regular expression would match strings like timme, tie and so on.

+

Used to specify that the previous character can be matched one or more times. tim+e

The regular expression would match strings like timme, timmme, time and so on.

?

Used to specify that the previous character can be matched either once or zero times. tim ?e

The regular expression would only match strings like time or tie.

{ }

The curly brackets accept two integer values. The first value specifies the minimum number of occurrences and the second value specifies the maximum of occurrences. tim{1,4}e

The regular expression would match only strings time, timme, timmme or timmmme.

Regular expression module functions

Some of the methods of re module as discussed below:

re. compile ( pattern )
The function compile a regular expression pattern into a regular expression object, which can be used for matching using its match ( ) and search ( ) methods, discussed below.

>>> import re
>>> p=re.compile ( ' tim*e ' )

re. match ( pattern, string )
If zero or more characters at the beginning of the string match the regular expression pattern, match-( ) return a corresponding match object instance. The function returns None if the string does not match the pattern.

re. group ( )
The function return the string matched by the RE.

>>> m=re .match ( ' tim*e' , ' timme pass time ' )
>>> m. group ( )
' timme '

The above patch of code can also be written as:

>>> p=re. compile ( ' tim*e ' )
>>> m=p.match ( ' timme pass timme ' )
>>> m.group ( )
'timme'

re. search ( pattern, string )
The function scans through string looking for a location where the regular expression pattern produces a match, and returns a corresponding match object instance. The function returns None if no position in the string matches the pattern.

>>> m=re.search( ' tim*e ' ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

re.start ( )
The function returns the starting position of the match.

re.end ( )
The function returns the end position of the match.

re.span ( )
The function returns a tuple containing the ( start, end ) indexes of the match.

>>> m=re.search ( ' tim*eno passtimmmeee ' )
>>> m.start ( )
7
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.start ( )
7 
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

re. findall ( pattern, string )
The function returns all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.findall ( ' tim*e ' , ' timeee break no pass timmmeee ' )
>>> m 
[ ' time ' , ' timmme ' ]

The above patch of code can also be written as:

>>> p=re . compile ( ' tim*e ' )
>>> m=p.findall ( ' timeee break no pass timmmeee ' )
>>> m
[ ' time ', ' timmme ' ]

re. finditer ( pattern, string )
The function returns an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in a string. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.finditer ( ' tim*e ', ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .           print match.group ( )
. . .           print match.span ( )
time 
( 0 , 4 ) 
timmme 
( 21 , 27 )

The above patch of code can also be written as:

>>> p=re.compile( ' tim*e ' )
>>> m=p.finditer ( ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .         print match.group ( )
. . .         print match.span ( )
time 
( 0 , 4 ) 
timmme
( 21 , 27 )

Python count occurrences of character in string – Count Occurrences of a Single or Multiple Characters in String and Find their Index Positions

Count Occurrences of a Single or Multiple Characters in String and Find their Index Positions

Count occurrences of character in list python: A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

In this article we are going to count single characters /multiple characters in a given string.

Examples:

1)Count occurrences of single characters in a given string

Input: 

given_string="btechgeeks" character ='e'

Output:

count of  e is : 3

2)Count occurrences of multiple characters in a  given string

Input:

given_string="btechgeeks" character =['e' , 'c' , 's' ]

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Count occurrences of single/multiple characters in a given string and indices of them

Python count occurrences of character in string: There are several methods  some of them are:

Method #1:Using count() function

Find all occurrences of a character in a string python: The count() method in the string class returns the number of times a substring appears in the string. In simple terms, the count() method looks for a substring in a string and returns the number of times it appears.

1)Count occurrence of single character using count() function

Count occurrences of character in string python: We can count the occurrence of single character using count() as given below.

Below is the implementation:

# given string
string = "btechgeeks"
# given character which should be counted
character = 'e'
# counting the number of occurences of given character in the string
charcount = string.count(character)
print("count of ", character, "is :", charcount)

Output:

count of  e is : 3

2)Count occurrence of multiple characters using count() function

  • Traverse the list of characters whose frequency is to be calculated.
  • Using count function print the frequency of respective characters.

Below is the implementation:

# given string
string = "btechgeeks"
# given characters list which should be counted
charlist = ['e', 'c', 's']
# traverse the charlist
for char in charlist:
    # counting the number of occurences of given character in the string
    charcount = string.count(char)
    print("count of ", char, "is :", charcount)

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Method #2:Using Counter() function which is in collections module

Find number of occurrences of a character in a string python: Counter is a set and dict subset. Counter() takes an iterable entity as an argument and stores the elements as keys and the frequency of the elements as a value. So, in collections, if we transfer a string. When you call Counter(), you’ll get a Counter class object with characters as keys and their frequency in a string as values.

Counter() returns a Counter type object (a subclass of dict) with all characters in the string as keys and their occurrence count as values. We’ll use the [] operator to get the occurrence count of the character’s’ from it.

1)Count occurrence of single character using Counter() function

Python count how many times a character appears in a string: Counting the frequency of character using Counter() function

Below is the implementation:

from collections import Counter
# given string
string = "btechgeeks"
# given character which should be counted
character = 'e'
# counting the frequency of all characters using counter() function
freq = Counter(string)
# counting the number of occurences of given character in the string using [] operator
charcount = freq[character]
print("count of ", character, "is :", charcount)

Output:

count of  e is : 3

2)Count occurrence of multiple characters using Counter() function

  • Traverse the list of characters whose frequency is to be calculated.
  • We can count their frequency using [] operator

Below is the implementation:

from collections import Counter
# given string
string = "btechgeeks"
# given characters list which should be counted
charlist = ['e', 'c', 's']
# counting the frequency of all characters using counter() function
freq = Counter(string)
# traverse the charlist
for char in charlist:
    # counting the number of occurences of given character in the string using [] operator
    charcount = freq[char]
    print("count of ", char, "is :", charcount)

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Finding single character index positions in a string

Method #3:Using regex to count and print indices of occurrences of a string

Python count occurrences in string: Build a regex pattern that matches the character to find the index positions of that character in a string. Then iterate through all of the pattern matches in the string, adding their index positions to a list.

Below is the implementation:

import re
# given main string
string = 'Hello this is BTechGeeks'
# given character
char = 'e'
# Make a regex pattern that matches the given character
pattern = re.compile(char)
# Iterate over all the matches of regex pattern
matchiterator = pattern.finditer(string)
# taking empty list
indexlist = []
# initializing count to 0
charcount = 0
for matchobject in matchiterator:
    indexlist.append(matchobject.start())
    charcount = charcount + 1
print("Count of given character ", char, "is :", charcount)
print("indices of given characters :", indexlist)

Output:

Count of given character  e is : 4
indices of given characters : [1, 16, 20, 21]

Related Programs:

Numpy ceil – Python NumPy ceil() Function

Python NumPy ceil() Function

NumPy ceil() Function:

Numpy ceil: The ceil() function of the NumPy module returns the ceiling value of the given input array or data. The ceiling of the scalar x is the smallest integer “i”, such that i >= x.

Syntax:

numpy.ceil(x, out=None)

Parameters

x: This is required. It is an array (array-like) having elements for which the ceiling values are calculated.

out: This is optional. It is the location where the result will be saved. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.

Return Value: 

NP ceil: The ceiling value of each element of x is returned.

NumPy ceil() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the above given array as an argument to the ceil() function of the numpy module to get the ceiling values of the given array elements
  • Store it in another variable.
  • Print the ceiling values of the given array elements.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([20.3, 5.5, 8.8, 30.076, 12.123])           
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array as an argument to the ceil() function of the 
# numpy module to get the ceiling values of the given array elements
# Store it in another variable.
ceil_vals = np.ceil(gvn_arry)
# Print the ceiling values of the given array elements
print("The ceiling values of the given array elements:")
print(ceil_vals)

Output:

The above given array is:
[20.3  5.5  8.8  30.076  12.123]
The ceiling values of the given array elements:
[21.  6.  9.  31.  13.]

Example2: Negative values are given for the Array

np.ceil: Here, we give the array which includes the elements with negative values.

For example, Let the number given = -1.7

The ceiling value for -1.7 = -1

When we calculate the ceiling value for a given negative number, the larger integer number, like -1.7, will be -1 rather than -2. Because -1 is a higher number than -1.7, and -2 is a smaller number than -1.7

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list of negative values as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the above-given array as an argument to the ceil() function of the numpy module to get the ceiling values of the given array elements with negative values.
  • Store it in another variable.
  • Print the ceiling values of the given array elements.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list of negative values as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([-20.3, -1.5, -2.8, -3, -12.6])           
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array as an argument to the ceil() function of the 
# numpy module to get the ceiling values of the given array elements
# Store it in another variable.
ceil_vals = np.ceil(gvn_arry)
# Print the ceiling values of the given array elements
print("The ceiling values of the given array elements:")
print(ceil_vals)

Output:

The above given array is:
[-20.3 -1.5 -2.8 -3. -12.6]
The ceiling values of the given array elements:
[-20. -1. -2. -3. -12.]

 

Numpy amin – numpy.amin() | Find minimum value in Numpy Array and it’s index | Python Numpy amin() Function

numpy.amin() Find minimum value in Numpy Array and it’s index

Numpy amin: In this tutorial, we have shared the numpy.amin() statistical function of the Numpy library with its syntax, parameters, and returned values along with a few code examples to aid you in understanding how this function works. Also, you can easily find the minimum value in Numpy Array and its index using Numpy.amin() with sample programs.

numpy.amin()

np.amin: The numpy.amin() function returns minimum value of an array. Also, it is a statistical function of the NumPy library that is utilized to return the minimum element of an array or minimum element along an axis.

Syntax:

The syntax needed to use this function is as follows:

numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>)

In this, we will pass two arguments-

where

  • a: It is the array from where we have to find min value
  • axis: It is optional and if not provided then it will pass the NumPy array and returns the min value.
    • If it’s given then it will return for an array of min values along the axis i.e.
    • In the case of axis=0 then it returns an array containing min value for each column.
    • In the case of axis=1 then it returns an array containing min value for each row.

Parameters:

Numpy minimum: Now it’s time to explain the parameters of this method:

  • a: This parameter shows the input data that is in the form of an array.
  • axis: It is an optional parameter registering the Axis or axes along which to operate. The value of this parameter can be int or a tuple of int values and also has a default value as None.
  • out: This optional parameter is applied to show an alternative output array in which the result becomes stored. The value of this parameter is in the form of an ndarray.
  • keepdims: By this optional parameter(having boolean value), the result will broadcast perfectly against the input array. If this option is set to True, the axes which are overcome are left in the result as dimensions with size one.
  • initial: This is a scalar and optional parameter used to show the maximum value of an output element.
  • where: This is an optional parameter used to indicate the elements to compare for the value.

Return Value:

Numpy array min: The minimum of an array – arr[ndarray or scalar], scalar if the axis is None; the result is an array of dimension a.ndim – 1 if the axis is mentioned.

Also Refer:

Example on NumPy amin() Function

a = np.arange(9).reshape((3,3))

print("The Array is :")
print(a)

print("Minimum element in the array is:",np.amin(a))         

print("Minimum element along the first axis of array is:",np.amin(a, axis=0))  

print("Minimum element along the second axis of array is:",np.amin(a, axis=1))

Output:

The Array is : [[0 1 2] [3 4 5] [6 7 8]]

Minimum element in the array is: 0

Minimum element along the first axis of array is: [0 1 2]

Minimum element along the second axis of array is: [0 3 6]

Find the minimum value in a 1D Numpy Array

Numpy minimum of array: So now we are going to use numpy.amin() to find out the minimum element from a 1D array.

import numpy
arr = numpy.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17])
# Get the minimum element from a Numpy array
minElement = numpy.amin(arr)
print('Minimum element from Numpy Array : ', minElement)

Output:

Minimum element from Numpy Array : 11

Find minimum value & its index in a 2D Numpy Array

Python index of minimum: So here we are going to find out the min value in the 2D array.

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])# Get the minimum element from a Numpy array
minElement = numpy.amin(arr2D)
print('Minimum element from Numpy Array : ', minElement)

Output:

Minimum element from Numpy Array : 11

Find min values along the axis in 2D numpy array | min in rows or columns:

Numpy min: If we pass axis=0 then it gives an array containing min of every column,

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])
# Get the minimum values of each column i.e. along axis 0
minInColumns = numpy.amin(arr2D, axis=0)
print('min value of every column: ', minInColumns)

Output:

min value of every column: [11 12 11]

If we pass axis=1 then it gives an array containing min of every row,

import numpy 
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16], 
                      [17, 15, 11], 
                     [12, 14, 15]]) 
# Get the minimum values of each row i.e. along axis 1 
minInColumns = numpy.amin(arr2D, axis=1) 
print('min value of every column: ', minInColumns)

Output:

min value of every column: [11 14 11 12]

Find the index of minimum value from the 2D numpy array

So here we are going to discuss how to find out the axis and coordinate of the min value in the array.

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])
result = numpy.where(arr2D == numpy.amin(arr2D))
print('Tuple of arrays returned : ', result)
print('List of coordinates of minimum value in Numpy array : ')
# zip the 2 arrays to get the exact coordinates
listOfCordinates = list(zip(result[0], result[1]))
# travese over the list of cordinates
for cord in listOfCordinates:
    print(cord)

Output:

Tuple of arrays returned : (array([0, 2], dtype=int32), array([0, 2], dtype=int32))
List of coordinates of minimum value in Numpy array :
(0, 0)
(2, 2)

numpy.amin() & NaN

if there is a NaN in the given numpy array then numpy.amin() will return NaN as minimum value.

import numpy
arr = numpy.array([11, 12, 13, 14, 15], dtype=float)
arr[3] = numpy.NaN
print('min element from Numpy Array : ', numpy.amin(arr))

Output:

min element from Numpy Array : nan

Numpy tolist – Python NumPy ndarray.tolist() Function

Python NumPy ndarray.tolist() Function

NumPy ndarray.tolist() Function:

Numpy tolist: The ndarray.tolist() function of the NumPy module converts the ndarray(n-Dimensional arary) to python list(nested).

That means it returns a python list that contains a copy of the array contents.

The data is transformed to the closest built-in Python type that is compatible.

If the array’s dimension is 0, the nested list will not be a list at all, but a normal Python scalar, because the depth of the nested list is 0.

Syntax:

numpy.ndarray.tolist()

Parameters

This function doesn’t accept any parameters

Return value

A Python list containing array elements, which may be nested is returned.

NumPy ndarray.tolist() Function in Python

Example1

Here, the Numpy arrays are transformed to Python lists.

Approach:

  • Import numpy module using the import keyword
  • Pass some random number to the array() function of the Numpy module to create a 0-Dimensional array.
  • Store it in a variable.
  • Create an array(1-Dimensional) of some random range using the arange() function of the numpy module.
  • Store it in another variable.
  • Create an array of some random range and reshape it to some random rows and columns using the reshape() function.
  • Store it in another variable.
  • Here it creates a 2-Dimensional array.
  • Convert the above given 0-Dimensional array to list using the tolist() function
  • Convert the above given 1-Dimensional array to list using the tolist() function
  • Convert the above given 2-Dimensional array to list using the tolist() function
  • Print the above obtained 0-Dimensional list.
  • Print the above obtained 1-Dimensional list.
  • Print the above obtained 2-Dimensional list.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np

# Pass some random number to the array() function of the Numpy module
# to create a 0-Dimensional array.
# Store it in a variable.
gvn_arry0D = np.array(40)
# Create an array(1-Dimensional) of some random range using the arange()
# function of the numpy module.
# Store it in another variable.
gvn_arry1D = np.arange(2, 7)
# Create an array of some random range and reshape it to some random rows 
# and columns using the reshape() function.
# Store it in another variable.
# Here it creates a 2-Dimensional array.
gvn_arry2D = np.arange(1, 5).reshape(2,2)

# Convert the above given 0-Dimensional array to list using the tolist() function 
Lst_0D = gvn_arry0D.tolist()
# Convert the above given 1-Dimensional array to list using the tolist() function
Lst_1D = gvn_arry1D.tolist()
# Convert the above given 2-Dimensional array to list using the tolist() function
Lst_2D = gvn_arry2D.tolist()

# Print the above obtained 0-Dimensional list
print("The above obtained 0-Dimensional list is: ", Lst_0D)
# Print the above obtained 1-Dimensional list
print("The above obtained 1-Dimensional list is:", Lst_1D)
# Print the above obtained 2-Dimensional list
print("The above obtained 2-Dimensional list is: ", Lst_2D)

Output:

The above obtained 0-Dimensional list is: 40
The above obtained 1-Dimensional list is: [2, 3, 4, 5, 6]
The above obtained 2-Dimensional list is: [[1, 2], [3, 4]]

Example2

Approach:

  • Import numpy module using the import keyword
  • Create an array of some random range using the arange() function of the numpy module.
  • Store it in a variable.
  • Here it creates a 1-Dimensional array.
  • Print the given array
  • Print the type of the given array using the type() function
  • Print the type of random element from the given array using the type() function
  • Convert the above given 1-Dimensional array to list using the tolist() function
  • Store it in another variable.
  • Print the above obtained 1-Dimensional list
  • Print the type of the above obtained 1-Dimensional list using the type() function
  • Print the type of random element from the obtained 1-Dimensional list using the type() function.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Create an array of some random range using the arange()
# function of the numpy module.
# Store it in a variable.
# Here it creates a 1-Dimensional array.
gvn_arry1D = np.arange(2, 7)

# Print the given array
print("The given array is:\n", gvn_arry1D)
# Print the type of the given array using the type() function
print("The type of the given array is:\n", type(gvn_arry1D))
# Print the type of random element from the given array using the type() function
print("The type of random element from the given array is:")
print(type(gvn_arry1D[2]))
print()

# Convert the above given 1-Dimensional array to list using the tolist() function
# Store it in another variable.
Lst_1D = gvn_arry1D.tolist()

# Print the above obtained 1-Dimensional list
print("The above obtained 1-Dimensional list is:\n", Lst_1D)
# Print the type of the above obtained 1-Dimensional list using the type() function
print("The type of the above obtained 1-Dimensional list is:")
print(type(Lst_1D))
# Print the type of random element from the obtained 1-Dimensional list
# using the type() function
print("The type of random element from the obtained 1-Dimensional list is:")
print(type(Lst_1D[2]))

Output:

The given array is:
[2 3 4 5 6]
The type of the given array is:
<class 'numpy.ndarray'>
The type of random element from the given array is:
<class 'numpy.int64'>

The above obtained 1-Dimensional list is:
[2, 3, 4, 5, 6]
The type of the above obtained 1-Dimensional list is:
<class 'list'>
The type of random element from the obtained 1-Dimensional list is:
<class 'int'>

Numpy tan – Python NumPy tan() Function

numpy-tan()-function

Numpy Module:

Numpy tan: NumPy is a Python module that is used to work with arrays.

It also has functions for working with linear algebra, the Fourier transform, and matrices.

Travis Oliphant designed NumPy in 2005. It is an open-source project that you are free to use.

NumPy is an abbreviation for Numerical Python.

Uses of NumPy Module:

Numpy tangent: Lists in Python serve the same purpose as arrays, although they are slower to process.

NumPy’s goal is to provide array objects that are up to 50 times faster than ordinary Python lists.

The array object in NumPy is named ndarray, and it comes with a slew of helper methods that make working with ndarray a breeze.

Arrays are often utilized in data science, where speed and resources are critical.

NumPy tan() Function:

np.tan: The NumPy tan() function computes the trigonometric tangent of an angle in radians.

Syntax:

numpy.tan(array, out=None)

Parameters

array: This is required.The items of the array whose tangent values are to be calculated.
out: This is optional. The output array’s shape. It specifies the location where the result will be saved. If given, it must have a shape to which the inputs are broadcast to. If not given or None, a freshly-allocated array is returned.

NumPy tan() Function in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list of angles as an argument to the array() function to create an array. Store it in a variable.
  • Convert the above-given array angles to radians using numpy.pi/180.
  • Store it in another variable.
  • Get the tangent values of the above array angles using the tan() function of numpy module and store it in another variable.
  • Print the tangent values of the above-given array angles.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list of angles as an argument to the array() function to 
# create an array. Store it in a variable.
gvn_arry = np.array([180, 45, 0, 90])
# Convert the above given array angles to radians using numpy.pi/180
# Store it in another variable.
gvn_arry = gvn_arry*np.pi/180
# Get the tangent values of the above array angles using the tan() function of 
# numpy module and store it in another variable.
rslt= np.tan(gvn_arry)
# Print the tangent values of the above given array angles
print("The tangent value of above given array angles = \n", rslt)

Output:

The tangent value of above given array angles = 
[-1.22464680e-16 1.00000000e+00 0.00000000e+00 1.63312394e+16]

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import numpy module using the import keyword.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Pass the above list as an argument to the array() function to create an array. Store it in a variable.
  • Convert the above-given array angles to radians using numpy.pi/180.
  • Store it in another variable.
  • Get the tangent values of the above array angles using the tan() function of numpy module and store it in another variable.
  • Print the tangent values of the above-given array angles.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Give the list as user input using the list(),map(),split(),int 
# functions and store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Pass the above list as an argument to the array() function to create an array.
# Store it in a variable.
gvn_arr = np.array(gvn_lst)
# Convert the above given array angles to radians using numpy.pi/180
# Store it in another variable.
gvn_arry = gvn_arry*np.pi/180
# Get the tangent values of the above array angles using the tan() function of 
# numpy module and store it in another variable.
rslt= np.tan(gvn_arry)
# Print the tangent values of the above given array angles
print("The tangent value of above given array angles = \n", rslt)

Output:

Enter some random List Elements separated by spaces = 45 120 0 30
The tangent value of above given array angles = 
[0.05488615 0.01370864 0. 0.02742244]

Print diamond pattern in python – Program to Print Half Diamond Star Pattern in C,C++, and Python

Print diamond pattern in python: Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Given the number of rows of the diamond pattern, the task is to print the Half diamond Pattern in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows =7

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

Example2:

Input:

Given number of rows =9
Given Character to print ='<'

Output:

9<
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
<

Program to Print Half Diamond Star Pattern in C, C++, and Python

Below are the ways to print Half Diamond Star Pattern in C, C++, and python.

Method #1: Using For loop (Star Character)

Approach:

  • Give the number of rows of the number of diamond pattern as static input and store it in a variable.
  • Loop from 0 to the number of rows using For loop.
  • Loop till the first iterator value using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • After the end of two For loops Loop from 1 to the number of rows using For loop.
  • Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows of the number of diamond pattern as static input and store it in a variable.
rowsnumber = 7
# Loop from 0 to the number of rows using For loop.
for m in range(0, rowsnumber):
        # Loop till the first iterator value using another For loop(Nested For loop).
    for n in range(0, m+1):
        # In the inner for loop Print the star character with space.
        print('*', end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()
# After the end of two For loops Loop from 1 to the number of rows using For loop.
for m in range(1, rowsnumber):
    # Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
    for n in range(m, rowsnumber):
        # In the inner for loop Print the star character with space.
        print('*', end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    //Give the number of rows of the number of diamond pattern  \
  //  as static input and store it in a variable.
    int rowsnumber = 7;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << "* ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << "* ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    return 0;
}

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    //Give the number of rows of the number of diamond pattern  \
  //  as static input and store it in a variable.
    int rowsnumber = 7;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("* ");
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For
    // loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("* ");
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    return 0;
}

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

Method #2: Using For loop (User Character)

Approach:

  • Give the number of rows of the number of diamond pattern as user input and store it in a variable.
  • Loop from 0 to the number of rows using For loop.
  • Loop till the first iterator value using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • After the end of two For loops Loop from 1 to the number of rows using For loop.
  • Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • The Exit of the Program.

1) Python Implementation

  • Give the number of rows as user input using int(input()) and store it in a variable.
  • Give the Character as user input using input() and store it in another variable.

Below is the implementation:

# Give the number of rows  as user input using int(input()) and store it in a variable.
rowsnumber = int(input(
    'Enter some random number of rows  = '))
# Give the Character as user input using input() and store it in another variable.
givencharacter = input('Enter some random character = ')
# Loop from 0 to the number of rows using For loop.
for m in range(0, rowsnumber):
        # Loop till the first iterator value using another For loop(Nested For loop).
    for n in range(0, m+1):
        # In the inner for loop Print the star character with space.
        print(givencharacter, end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()
# After the end of two For loops Loop from 1 to the number of rows using For loop.
for m in range(1, rowsnumber):
    # Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
    for n in range(m, rowsnumber):
        # In the inner for loop Print the star character with space.
        print(givencharacter, end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()

Output:

Enter some random number of rows = 9
Enter some random character = <
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
< 

2) C++ Implementation

  • Give the number of rows as user input using cin and store it in a variable.
  • Give the Character as user input using cin and store it in another variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows
    // as user input using cin and store it in a
    // variable.
    int rowsnumber;
    char givencharacter;
    cout << "Enter some random number of rows = " << endl;
    cin >> rowsnumber;
    // Give the Character as user input using cin and store
    // it in another variable.
    cout << "Enter some random character = " << endl;
    cin >> givencharacter;
    cout << endl;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << givencharacter << " ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For
    // loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << givencharacter << " ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    return 0;
}

Output:

Enter some random number of rows = 
9
Enter some random character = 
<
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
<

3) C Implementation

  • Give the number of rows as user input using scanf and store it in a variable.
  • Give the Character as user input using scanf and store it in another variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows
    //  as user input using scanf and store it in a
    // variable.
    int rowsnumber;
    char givencharacter;
    // Give the Character as user input using scanf and
    // store it in another variable.
    scanf("%d", &rowsnumber);
    scanf("%c", &givencharacter);
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("%c ", givencharacter);
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For
    // loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("%c ", givencharacter);
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    return 0;
}

Output:

9<
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
<

Related Programs:

Python encode string to bytes – How to convert String to Bytes in Python?

How to convert String to Bytes in Python

Python encode string to bytes: In this post, we’ll look at how to convert Python String to Bytes and Python Bytes to String. Python type conversion has grown in popularity due to its feature of data used in different forms during various operations.

Python conversion of String to bytes and bytes to String is important because it is required when working with files, etc.

Bytes are simply encoded objects of string that can be stored on a disk and returned to their original form by decoding them to string.

Strings and bytes vary within this string are a sequence of characters, whereas byte objects are an arrangement of bytes.

Converting String to Bytes in Python

Python convert string to byte: There are several methods for converting a string to bytes.

Method #1: Using bytes() method

Python convert str to bytes: The bytes() method in Python’s CPython library allows us to convert String to bytes.

It should be noted that the UTF-8 format is utilized for encoding.

Syntax:

bytes(string, 'utf-8')

Approach:

  • Give the sting as static input and store it in a variable.
  • Print the given string
  • Print the datatype of the given string by passing it as an argument to the type() function.
  • Pass the given string, ‘UTF-8’ as arguments to the bytes() function to convert the given string into bytes and store it in another variable.
  • Here UTF-8 format is used for encoding.
  • Print the given string after converting it into bytes
  • Print the datatype of the above variable i.e, after conversion by passing it as an argument to the type() function.
  • The Exit of the Program.

Below is the implementation:

# Give the sting as static input and store it in a variable.
gvn_str = 'Hello this is btechgeeks' 
# Print the given string
print("The given string:\n", gvn_str)
# Print the datatype of the given string by passing it as an argument 
# to the type() function.
print("datatype:", type(gvn_str))
print()
# Pass the given string, 'UTF-8' as arguments to the bytes() function 
# to convert the given string into bytes and store it in another variable.
# Here UTF-8 format is used for encoding.
byte_str = bytes(gvn_str,'UTF-8')
# Print the given string after converting into bytes
print("The given string after converting into bytes:")
print(byte_str)
# Print the datatype of the above variable by passing it as an argument 
# to the type() function.
print("datatype after conversion:", type(byte_str))

Output:

The given string:
Hello this is btechgeeks
datatype: <class 'str'>

The given string after converting into bytes:
b'Hello this is btechgeeks'
datatype after conversion: <class 'bytes'>

Method #2: Using encode() method

Approach:

  • Give the sting as static input and store it in a variable.
  • Print the given string
  • Print the datatype of the given string by passing it as an argument to the type() function.
  • Apply encode() function on the given string by passing ‘UTF-8’ as an argument to it to convert the given string into bytes and store it in another variable.
  • Here UTF-8 format is used for encoding.
  • Print the given string after converting into bytes
  • Print the datatype of the above variable by passing it as an argument to the type() function.
  • The Exit of the Program.

Below is the implementation:

# Give the sting as static input and store it in a variable.
gvn_str = 'Hello this is btechgeeks' 
# Print the given string
print("The given string:\n", gvn_str)
# Print the datatype of the given string by passing it as an argument 
# to the type() function.
print("datatype:", type(gvn_str))
print()
# Apply encode() function on the given string by passing 'UTF-8' as argument to it  
# to convert the given string into bytes and store it in another variable.
# Here UTF-8 format is used for encoding.
byte_str = gvn_str.encode('UTF-8')
# Print the given string after converting into bytes
print("The given string after converting into bytes:")
print(byte_str)
# Print the datatype of the above variable by passing it as an argument 
# to the type() function.
print("datatype after conversion:", type(byte_str))

Output:

The given string:
Hello this is btechgeeks
datatype: <class 'str'>

The given string after converting into bytes:
b'Hello this is btechgeeks'
datatype after conversion: <class 'bytes'>

Python check last character of string – Check the First or Last Character of a String in Python

Python check last character of string: In Python, strings are sequences of bytes that represent Unicode characters. Due to the lack of a character data form in Python, a single character is simply a one-length string. To access the string’s components, use square brackets.

Examples:

Checking the last character:

Input:

string="BTechGeeks" lastcharacter='s'

Output:

Last character of string endswith s

Input:

string="BTechGeeks" lastcharacter='p'

Output:

Last character of string do no not end with p

Checking the first character:

Input:

string = 'BTechGeeks'  firstchar = 'B'

Output:

First character of string start with B

Input:

string = 'BTechGeeks'  firstchar = 'r'

Output:

First character of string do no not start with r

Checking the Last and First Character of the String

There are several ways to check first and last character of the string some of them are:

Checking last Character:

Method #1: Using negative slicing

Select the last element with a negative index to verify the condition on the string’s last character.

Below is the implementation:

# given string
string = 'BTechGeeks'
lastchar = 'p'
# check the last character ends with s
if(string[-1] == lastchar):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #2:Using length of string

To check the condition on a string’s last character, first determine the length of the string. Then, at index size -1, check the content of the character.

Below is the implementation:

string = 'BTechGeeks'
lastchar = 's'
# calculating length of string
length = len(string)
# check the last character ends with s
if(string[length-1] == lastchar):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #3:Using endswith()

If a string ends with the specified suffix, the endswith() method returns True; otherwise, it returns False.

Below is the implementation:

string = 'BTechGeeks'
lastchar = 's'
# calculating length of string
length = len(string)
# check the last character ends with s using endswith()
if(string.endswith(lastchar)):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #4: Checking whether the string’s last character matches any of the given multiple characters

In comparison to the previous solutions, endswith() adds a new function. We may also move a tuple of characters to endswith(), which will check whether the last character of the string matches any of the characters in the specified tuple or not.

Below is the implementation:

# Given string and characters
string = 'BTechGeeks'
lastchars = ('s', 'p', 'e')
# check the first character of the given string
if(string.endswith(lastchars)):
    print('Given string ends with one of the given characters')

Output:

Given string ends with one of the given characters

Checking First Character:

Method #5:Using index 0 to get first character

A string is a set of characters, with indexing starting at 0. To find the first character in a string, select the character at the 0th index.

Below is the implementation:

# Given string and character
string = 'BTechGeeks'
firstchar = 'B'
# check the first character of the given string
if(string[0] == firstchar):
    print('First character of string start with', firstchar)
else:
    print('First character of string do no not start with', firstchar)

Output:

First character of string start with B

Method #6:Using startswith()

Python’s String class has a function called startswith() that takes a character or a tuple of characters and checks whether a string begins with that character or not. Let’s use this to see if our string’s first character is ‘B’

Below is the implementation:

# Given string
string = 'BTechGeeks'
firstchar = 'B'
# check the first character of the given string
if(string.startswith(firstchar)):
    print('First character of string start with', firstchar)
else:
    print('First character of string do no not start with', firstchar)

Output:

First character of string start with B

Method #7:Checking whether the string’s last character matches any of the given multiple characters

startswith () adds a extra function . We may also transfer a character tuple, and it will check if the first character of the string matches any of the characters in the tuple.

Below is the implementation:

# Given string and first char
string = 'BTechGeeks'
firstchars = ('s', 'p', 'B')
# check the first character of the given string
if(string.startswith(firstchars)):
    print('given string starts with one of the given characters')

Output:

given string starts with one of the given characters

Related Programs:

Python iterate through list backwards – Python : Different ways to Iterate over a List in Reverse Order

Different ways to Iterate over a List in Reverse Order

Python iterate through list backwards: Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.

We’ll look at a few different ways to iterate over a List in Reverse Order in this article.

Example:

Input:

givenlist=['hello' , 'world' , 'this', 'is' ,'python']

Output:

python
is 
this
world
hello

Print list in reverse order

Python iterate list backwards: There are several ways to iterate through a list in reverse order some of them are:

Method #1 : Using for loop and range()

Iterate through list backwards python: When it comes to iterating through something, the loop is always helpful. To iterate in Python, we use the range() function. This approach is known as range ([start], stop[, step]).

start: This is the sequence’s first index.
stop: The range will continue until it reaches this index, but it will not include it.
step: The difference between each sequence element.

range(len(givenlist)-1, -1, -1)

this will return numbers from n to 1 i.e reverse indexes.

In the for loop, use the range() function and the random access operator [] to access elements in reverse.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Iterate over the list in reverse order using for loop and range()

for index in range(len(givenlist) - 1, -1, -1):
    print(givenlist[index])

Output:

python
is 
this
world
hello

Method #2: Using while loop

In Python, the while loop is used to iterate through a block of code as long as the test expression (condition) is true. This loop is typically used when we don’t know how many times to iterate ahead of time.

  • First, we used the len() method to determine the length of the list.
  • The index variable is set to the length of the list -1.
  • It’s used to display the list’s current index when iterating.This loop will continue until the index value reaches 0.
  • The index value is decremented by one each time.
  • The print line will print the list’s current iteration value.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Point position to the last element in list
position = len(givenlist) - 1

# Iterate till 1st element and keep on decrementing position
while position >= 0:
    print(givenlist[position])
    position = position - 1

Output:

python
is 
this
world
hello

Method #3: Using list Comprehension and slicing

givenlist[::-1]

It will generate a temporary reversed list.

Let’s apply this to iterating over the list in reverse in List comprehension.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Using list comprehension and slicing
[print(element) for element in givenlist[::-1]]

Output:

python
is 
this
world
hello

Method #4: Using for loop and reversed()

reversed(givenlist)

The reversed() function returns an iterator that iterates through the given list in reverse order.

Let’s use for loop  to iterate over that reversed sequence.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Using for loop and reversed function
for element in reversed(givenlist):
    print(element)

Output:

python
is 
this
world
hello

Method #5 : Using List Comprehension and reversed() function

reversed(givenlist)

The reversed() function returns an iterator that iterates through the given list in reverse order.

let us use list comprehension to print list in reverse order.

Below is the implementation:

# Given list
givenlist = ['hello', 'world', 'this', 'is', 'python']

# Iterate over the list using List Comprehension and [::-1]
[print(element) for element in reversed(givenlist)]

Output:

python
is 
this
world
hello

Related Programs: