Isocalendar python – Python Pandas Timestamp.isocalendar() Function

Python Pandas Timestamp.isocalendar() Function

What is Timestamp?

Isocalendar python: A timestamp is a sequence of characters or encoded information that identifies when a particular event occurred, typically providing the date and time of day, and can be accurate to a fraction of a second.

The timestamp method is used for a variety of synchronization purposes, including assigning a sequence order to a multievent transaction so that the transaction can be canceled if a fault occurs. A timestamp can also be used to record time in reference to a specific starting point in time.

Uses of Timestamp:

Isocalendar: Timestamps are used to maintain track of information stored online or on a computer. A timestamp indicates when data was generated, shared, modified, or removed.

Here are some examples of how timestamps can be used:

  • A timestamp in a computer file indicates when the file was last modified.
  • Photographs with digital cameras have timestamps that show the date and time of day they were taken.
  • The date and time of the post are included in social media posts.
  • Timestamps are used in online chat and instant messages to record the date and time that a message was delivered, received, or viewed.
  • Timestamps are used in blockchain blocks to confirm the validity of transactions, such as those involving cryptocurrencies.
  • To secure the integrity and quality of data, data management relies on timestamps.
  • Timestamps are used in digital contracts and digital signatures to signify when a document was signed.

Pandas Timestamp.isocalendar() Function:

The Timestamp.isocalendar() function Pandas gives a tuple comprising of 3 elements i.e, ISO year, week number, and weekday for the given Timestamp object.

Syntax:

 Timestamp.isocalendar()

Parameters: It has no arguments

Return Value:

The tuple with 3 elements is returned by the Timestamp.isocalendar() function

Pandas Timestamp.isocalendar() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random year, month, day, hour, second, tz =’Asia/Kolkata’ (Timezone) as the arguments to the Timestamp() function of the pandas module to get the Timestamp object.
  • Print the above-obtained Timestamp object.
  • Apply isocalendar() function on the above Timestamp object to get the date in the given timestamp object by using ISO calendar.
  • Here it returns a tuple comprising of 3 elements i.e, ISO year, week number, and weekday
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
  
# Pass some random year, month, day, hour, second, tz = 'Asia/Kolkata'
# (Timezone) as the arguments to the Timestamp() function of the
# pandas module to get the Timestamp object
time_stamp_obj = pd.Timestamp(year = 2017,  month = 6, day = 10, hour = 5, 
                            second = 22, tz = 'Asia/Kolkata')
  
# Print the above obtained Timestamp object
print("The above obtained Timestamp object:", time_stamp_obj)
# Apply isocalendar() function on the above Timestamp object to 
# get the date in the given timestamp object by using ISO calendar.
# Here it returns a tuple comprising of 3 elements i.e, ISO year, week number, and weekday
print("The tuple with 3 elements i.e, ISO year, week number, and weekday:")
time_stamp_obj.isocalendar()

Output:

The above obtained Timestamp object: 2017-06-10 05:00:22+05:30
The tuple with 3 elements i.e, ISO year, week number, and weekday:
(2017, 23, 6)

Example2

Approach:

  • Import pandas module using the import keyword.
  • Pass some random year, month, day, hour, second, tz =’US/Central'(Timezone) as the arguments to the Timestamp() function of the pandas module to get the Timestamp object.
  • Print the above-obtained Timestamp object
  • Apply isocalendar() function on the above Timestamp object to get the date in the given timestamp object by using ISO calendar.
  • Here it returns a tuple comprising of 3 elements i.e, ISO year, week number, and weekday
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
  
# Pass some random year, month, day, hour, second, tz = 'US/Central'
# (Timezone) as the arguments to the Timestamp() function of the
# pandas module to get the Timestamp object
time_stamp_obj = pd.Timestamp(year = 2020,  month = 8, day = 30, hour = 12, 
                            second = 30, tz = 'US/Central')
  
# Print the above obtained Timestamp object
print("The above obtained Timestamp object:", time_stamp_obj)
# Apply isocalendar() function on the above Timestamp object to 
# get the date in the given timestamp object by using ISO calendar.
# Here it returns a tuple comprising of 3 elements i.e, ISO year, week number, and weekday
print("The tuple with 3 elements i.e, ISO year, week number, and weekday:")
time_stamp_obj.isocalendar()

Output:

The above obtained Timestamp object: 2020-08-30 12:00:30-05:00
The tuple with 3 elements i.e, ISO year, week number, and weekday:
(2020, 35, 7)

 

Check if a string is a rotation of another string – Python Program to Determine Whether one String is a Rotation of Another

Program to Determine Whether one String is a Rotation of Another

In the previous article, we have discussed Python Program to Shuffle a List
Given a string, and the task is to determine whether one string is a rotation of another.

Examples:

Example1:

Input:

Given first string = "btechgeeks"
Given second string = "geeksbtech"

Output:

The given second string is the rotation of the given second string

Example2:

Input:

Given first string = "pqrst"
Given second string = "sggsf"

Output:

The given second string is not the rotation of the given second string

Program to Determine Whether one String is a Rotation of Another

Check if a string is a rotation of another string: Below are the ways to determine whether one string is the rotation of another.

Method #1: Using String Concatenation (Static Input)

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Check if the length of the first string is not equal to the length of the second string using the if conditional statement and using the len() function.
  • If the statement is true, print “The given second string is not the rotation of the given first string”.
  • Else concatenate the first string with the first string itself using the ‘+ ‘ operator and store it in a variable say “conat_str”.
  • Check if the second string is present in the “conca_str” using the if conditional statement.
  • If the statement is true, print  “The given second string is the rotation of the given first string”.
  • Else print  “The given second string is not the rotation of the given first string”.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
fst_str = "pqrst"
# Give the second string as static input and store it in another variable.
secnd_str = "stpqr"
# Check if the length of the first string is not equal to the length of the second
# string using the if conditional statement and using the len() function.
if(len(fst_str) != len(secnd_str)):
    # If the statement is true, print "The given second string is not the rotation of the given first string".
    print("The given second string is not the rotation of the given first string")
else:
    # Else concatenate the first string with the first string itself using the '+ ' operator
    # and store it in a variable say "conat_str".
    conct_str = fst_str + fst_str
# Check if the second string is present in the "conca_str" using the if
# conditional statement.
    if(secnd_str in conct_str):
        # If the statement is true, print  "The given second string is the rotation of the given first string".
        print("The given second string is the rotation of the given  first string")
    else:
        # Else print  "The given second string is not the rotation of the given first string".
        print("The given second string is not the rotation of the first given string")

Output:

The given second string is the rotation of the second string

Method #2: Using String Concatenation (User Input)

Approach:

  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Check if the length of the first string is not equal to the length of the second string using the if conditional statement and using the len() function.
  • If the statement is true, print “The given second string is not the rotation of the given first string”.
  • Else concatenate the first string with the first string itself using the ‘+ ‘ operator and store it in a variable say “conat_str”.
  • Check if the second string is present in the “conca_str” using the if conditional statement.
  • If the statement is true, print  “The given second string is the rotation of the given first string”.
  • Else print  “The given second string is not the rotation of the given first string”.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as user input using input() function and store it in a variable.
fst_str = input("Enter some random string = ")
# Give the second string as user input using input() function and store it in another variable.
secnd_str = input("Enter some random string = ")
# Check if the length of the first string is not equal to the length of the second
# string using the if conditional statement and using the len() function.
if(len(fst_str) != len(secnd_str)):
    # If the statement is true, print "The given second string is not the rotation of the given first string".
    print("The given second string is not the rotation of the given first string")
else:
    # Else concat the first string with the first string itself using the '+ ' operator
    # and store it in a variable say "conat_str".
    conct_str = fst_str + fst_str
# Check if the second string is present in the "conca_str" using the if
# conditional statement.
    if(secnd_str in conct_str):
        # If the statement is true, print  "The given second string is the rotation of the given first string".
        print("The given second string is the rotation of the given first string")
    else:
        # Else print  "The given second string is not the rotation of the given first string".
        print("The given second string is not the rotation of the given first string")

Output:

Enter some random string = btechgeeks
Enter some random string = geeksbtech
The given second string is the rotation of the second string

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.

Towers of hanoi recursion python – Python Program to Implement Tower of Hanoi Using Recursion

Program to Implement Tower of Hanoi Using Recursion

Towers of hanoi recursion python: Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Recursion in Python:

Tower of hanoi python: The Oxford English Dictionary defines recursion as the repeated use of a recursive technique or term.

When a function calls itself repeatedly until it meets a stated stopping condition, this is referred to as recursion. This type of function is known as a recursive function.

The technique of explaining an action in terms of itself is known as recursion.

Use of Recursion:

Tower of hanoi python code: In general, recursive code is shorter and easier to write than iterative code. When loops are built or interpreted, they are generally transformed into recursive functions. Recursion is most useful for activities that can be broken down into smaller subtasks.

Format of Recursive Function:

A recursive function is made up of two major components:

Base Case: The base case is where all further calls to the same function end, implying that no additional recursive calls are made.
Recursive Case: In the recursive case, the function calls itself till it reaches the base case.
The answer to the primary problem is represented in terms of lesser problems until the smallest problem meets the base case in a recursive function.

Tower of Hanoi:

Python towers of hanoi: It is a mathematical puzzle game in which three identical rods and n discs of varying sizes are used. In the first rod, the discs are positioned so that the largest disc is at the bottom and the smallest is at the top. To complete the puzzle, put the discs in the same order in the final rod via the middle rod.

Rules of Towers of Hanoi:

At any given time, only one disc can be transferred.
Each move requires taking the uppermost disc from one of the stacks and placing it on top of another, i.e. a disc can only be moved if it is the uppermost disc on a stack.
A larger disc may not be stacked on top of a smaller disc.

Examples:

Example1:

Input:

given number of disks = 3

Output:

Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [3] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }

Example2:

Input:

given number of disks = 4

Output:

Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [3] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { A }
Move disk [2] from rod [ C ] to rod { B }
Move disk [1] from rod [ A ] to rod { B }
Move disk [4] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [2] from rod [ B ] to rod { A }
Move disk [1] from rod [ C ] to rod { A }
Move disk [3] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }

Program to Implement Tower of Hanoi Using Recursion in Python

1)Using Recursion(Static Input)

Approach:

  • Give the number of discs as static input and store it in a variable.
  • Create a recursive function called tower of Hanoi and pass two arguments: the number of discs n and the names of the rods such as source, aux, and destination.
  • When the number of discs is one, we can define the base case. Simply move the single disc from source to target and return in this scenario.
  • Now, use the target as the auxiliary to shift the remaining n-1 discs from source to auxiliary.
  • The remaining 1 disc then moves from source to target.
  • Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.

Below is the implementation:

# Create a recursive function called tower of Hanoi and pass two arguments:
# the number of discs n and the names of the rods
# such as source, aux, and destination.


def Towers_Of_Hanoi(numdisks, frm_disc, to_disc, aux_disc):
  # When the number of discs is one, we can define the base case. Simply move the
  # single disc from source to target and return in this scenario.
    if numdisks == 1:
        print("Move disk [1] from rod [",
              frm_disc, "] to rod {", to_disc, '}')
        return
    # Now, use the target as the auxiliary to
    # shift the remaining n-1 discs from source to auxiliary.
    Towers_Of_Hanoi(numdisks-1, frm_disc, aux_disc, to_disc)
    # The remaining 1 disc then moves from source to target.

    # Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.
    print("Move disk ["+str(numdisks) + "] from rod [",
          str(frm_disc)+" ] to rod {", to_disc, '}')
    Towers_Of_Hanoi(numdisks-1, aux_disc, to_disc, frm_disc)


# Give the number of discs as static input and store it in a variable.
numdisks = 4
# passing the given number of disks as argument to the towers of hanoi recursive function .
Towers_Of_Hanoi(numdisks, 'A', 'C', 'B')

Output:

Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [3] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { A }
Move disk [2] from rod [ C ] to rod { B }
Move disk [1] from rod [ A ] to rod { B }
Move disk [4] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [2] from rod [ B ] to rod { A }
Move disk [1] from rod [ C ] to rod { A }
Move disk [3] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }

2)Using Recursion(User Input)

Approach:

  • Give the number of discs as user input using the int(input()) function which converts the string to an integer.
  • Store it in a variable.
  • Create a recursive function called tower of Hanoi and pass two arguments: the number of discs n and the names of the rods such as source, aux, and destination.
  • When the number of discs is one, we can define the base case. Simply move the single disc from source to target and return in this scenario.
  • Now, use the target as the auxiliary to shift the remaining n-1 discs from source to auxiliary.
  • The remaining 1 disc then moves from source to target.
  • Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.

Below is the implementation:

# Create a recursive function called tower of Hanoi and pass two arguments:
# the number of discs n and the names of the rods
# such as source, aux, and destination.


def Towers_Of_Hanoi(numdisks, frm_disc, to_disc, aux_disc):
  # When the number of discs is one, we can define the base case. Simply move the
  # single disc from source to target and return in this scenario.
    if numdisks == 1:
        print("Move disk [1] from rod [",
              frm_disc, "] to rod {", to_disc, '}')
        return
    # Now, use the target as the auxiliary to
    # shift the remaining n-1 discs from source to auxiliary.
    Towers_Of_Hanoi(numdisks-1, frm_disc, aux_disc, to_disc)
    # The remaining 1 disc then moves from source to target.

    # Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.
    print("Move disk ["+str(numdisks) + "] from rod [",
          str(frm_disc)+" ] to rod {", to_disc, '}')
    Towers_Of_Hanoi(numdisks-1, aux_disc, to_disc, frm_disc)


# Give the number of discs as user input using
# the int(input()) function which converts the string to an integer.
# Store it in a variable.
numdisks = int(input('Enter some random number of disks = '))
# passing the given number of disks as argument to the towers of hanoi recursive function .
Towers_Of_Hanoi(numdisks, 'A', 'C', 'B')

Output:

Enter some random number of disks = 5
Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [3] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }
Move disk [4] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [2] from rod [ C ] to rod { A }
Move disk [1] from rod [ B ] to rod { A }
Move disk [3] from rod [ C ] to rod { B }
Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [5] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }
Move disk [3] from rod [ B ] to rod { A }
Move disk [1] from rod [ C ] to rod { B }
Move disk [2] from rod [ C ] to rod { A }
Move disk [1] from rod [ B ] to rod { A }
Move disk [4] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [3] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }

It prints all the valid moves of the disks.

Related Programs:

Numpy hsplit – Python NumPy hsplit() Function

Python NumPy hsplit() Function

NumPy hsplit() Function:

Numpy hsplit: The hsplit() function of the Numpy module is used to split an array into multiple sub-arrays horizontally (column-wise).

hsplit is equivalent to split with axis=1, and regardless of the array dimension, the array is always split along the second axis.

Syntax:

numpy.hsplit(array, indices_or_sections)

Parameters

array: This is required. It is the input array to be split into multiple sub-arrays.

indices_or_sections: This is required. It specifies the indices or sections as an int or a 1-D array.

  • If indices_or_sections is an integer, N, the array will be divided horizontally into N equal arrays. An error is raised if such a split is not possible.
  • If indices_or_sections is a one-dimensional(1D) array of sorted integers, the entries indicate where the array is split horizontally.
  • If an index exceeds the horizontal dimension of the array, an empty sub-array is returned correspondingly.

Return Value: 

Hssplit: A list of sub-arrays as views into the given array is returned.

NumPy hsplit() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list(multi-dimensional) as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the given array, indices value(here it is 3) as an argument to the hsplit() function to horizontally split the array.
  • Store it in another variable.
  • Print the above horizontally split Array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list(multi-dimensional) as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array, indices value(here it is 3) as an argument to the hsplit()function to 
# horizontally split the array
# Store it in another variable.
splt_arry = np.hsplit(gvn_arry, 3)
# Print the above horizontally split Array
print("The above horizontally split Array is:")
print(splt_arry)

Output:

The above given array is:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
The above horizontally split Array is:
[array([[1],
            [4],
            [7]]), array([[2],
            [5],
            [8]]), array([[3],
            [6],
            [9]])]

Example2

Hsplit: When indices_or_sections is given as a 1-dimensional array of sorted integers, the elements indicate where the array is split horizontally.

# Import numpy module using the import keyword
import numpy as np
# Pass some random list(multi-dimensional) as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[11, 12, 13, 14],
                   [15, 16, 17, 18],
                   [19, 20, 21, 22]])
                  
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array, indices value as 1D array as an argument to the hsplit() to 
# horizontally split the array
# Store it in another variable.
splt_arry = np.hsplit(gvn_arry, [1,2])
# Print the above horizontally split Array
print("The above horizontally split Array is:")
print(splt_arry)

Output:

The above given array is:
[[11 12 13 14]
 [15 16 17 18]
 [19 20 21 22]]
The above horizontally split Array is:
[array([[11],
           [15],
           [19]]), array([[12],
           [16],
           [20]]), array([[13, 14],
           [17, 18],
           [21, 22]])]

Pandas iat – Python Pandas DataFrame iat[] Property

Python Pandas DataFrame iat[] Property

Pandas iat: Python is an excellent language for data analysis, due to a strong ecosystem of data-centric Python tools. One of these packages is Pandas, which makes importing and analyzing data a lot easier.

Pandas DataFrame iat[] Property:

Pandas .iat: The iat[] property of the pandas module can be used to get a single value for a row/column pair based on integer position.

In that both allow integer-based lookups, they are similar to iloc. If you simply need to get or set a single value in a DataFrame or Series, you should use iat[].

 Note: If an integer position is out of bounds, an IndexError is thrown.

Pandas DataFrame iat[] Property in Python

Example1

Here, the iat[] property is used to get and set the elements of the DataFrame.

Approach:

  • Import pandas module using the import keyword.
  • Import NumPy module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Print the given dataframe.
  • Pass some random position(row, column) to the iat[] property to get the value at that given position
     and print the result.
  • Pass some random data to the random position(row, column) to the iat[] property to set
    the value at that given position.
  • Print the dataframe after modification
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Import NumPy module using the import keyword.
import numpy as np
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
data_frme = pd.DataFrame({
  "emp_name": ["john", "nick" , "jessy", "mary"],
  "emp_age": [25, 35, 38, 22],
  "emp_salary": [25000, 40000, 22000, 80000]},
  index= [1, 2, 3, 4]
)

print("The given DataFrame:")
print(data_frme)
print()
# Pass some random position(row, column) to the iat[] property to get 
# the value at that given position and print the result.
print("The value present at the given position[2, 1] in the dataframe:")
print(data_frme.iat[2, 1])

# Pass some random data to the random position(row, column) to the iat[] property to set 
# the value at that given position
data_frme.iat[0, 1] = 60
print()
# Print the dataframe after modification
print("The dataframe after modification:")
print(data_frme)

Output:

The given DataFrame:
  emp_name  emp_age  emp_salary
1     john       25       25000
2     nick       35       40000
3    jessy       38       22000
4     mary       22       80000

The value present at the given position[2, 1] in the dataframe:
38

The dataframe after modification:
  emp_name  emp_age  emp_salary
1     john       60       25000
2     nick       35       40000
3    jessy       38       22000
4     mary       22       80000

Example2

The iat[] property can also be used to get the elements of a Series.

NOTE: The row, column always starts from 0 index.

Approach:

  • Import pandas module using the import keyword.
  • Import NumPy module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Print the given dataframe
  • Pass the row number to the iloc[] and column number to the iat[] function
  • to get the value at the given position and print the result
  • Note: The row, col always starts from 0 index.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Import NumPy module using the import keyword.
import numpy as np
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
data_frme = pd.DataFrame({
  "emp_name": ["john", "nick" , "jessy", "mary"],
  "emp_age": [25, 35, 38, 22],
  "emp_salary": [25000, 40000, 22000, 80000]},
  index= [1, 2, 3, 4]
)
# Print the  given dataFrame
print("The given DataFrame:")
print(data_frme)
print()
# Pass the row number to the iloc[] and column number to the iat[] function
# to get the value at the given position and print the result
# Note: The row, col always starts from 0 index.
print("The element present at 1st row, 2nd column:")
print(data_frme.iloc[1].iat[2])

Output:

The given DataFrame:
  emp_name  emp_age  emp_salary
1     john       25       25000
2     nick       35       40000
3    jessy       38       22000
4     mary       22       80000

The element present at 1st row, 2nd column:
40000

 

Dataframe pop – Python Pandas DataFrame pop() Function

Python Pandas DataFrame pop() Function

Pandas DataFrame pop() Function:

Dataframe pop: The pop() function of the Pandas DataFrame removes the given column from the DataFrame and returns the removed columns as a Pandas Series object. If the given item is not found, the function throws a KeyError exception.

Syntax:

DataFrame.pop(label)

Parameters:

label: This is required. It indicates the label of the column that has to be removed.

Return Value:

Pandas pop: The pop() function of the Pandas DataFrame returns the removed column, as a Pandas Series object.

Pandas DataFrame pop() Function in Python

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe
  • Drop/remove some random column from the dataframe using the pop() function by passing the column name as an argument to it.
  • Here we removed the “emp_age” column from the dataframe
  • Print the altered dataframe after the removal of “emp_age” column.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "emp_name": ["john", "nick" , "jessy", "mary"],
  "emp_age": [25, 35, 38, 22],
  "emp_salary": [25000, 40000, 22000, 80000]},
  index= [1, 2, 3, 4]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Drop/remove some random column from the dataframe using the pop() function
# by passing the column name as an argument to it.
# Here we removed the "emp_age" column from the dataframe
data_frme.pop("emp_age")
# Print the altered dataframe after the removal of "emp_age" column
print("The altered dataframe after the removal of 'emp_age' column:")
print(data_frme)

Output:

The given Dataframe:
  emp_name  emp_age  emp_salary
1     john       25       25000
2     nick       35       40000
3    jessy       38       22000
4     mary       22       80000

The altered dataframe after the removal of 'emp_age' column:
  emp_name  emp_salary
1     john       25000
2     nick       40000
3    jessy       22000
4     mary       80000

 

Pandas dataframe first row – Drop first row of pandas dataframe (3 Ways)

How to delete first row of pandas dataframe in Python ?

Pandas dataframe first row: In this article we will discuss about different ways to delete first row of pandas dataframe in Python.

Method-1 : By using iloc attribute :

An iloc attribute is there in Pandas by using which we can select a portion of the dataframe that may be few columns or rows which is simply called as position based indexing.

Syntax - df.iloc[start_row:end_row , start_column, end_column]

Where,

  • start_row : It refers to the row position from where it will start selection.(Default value is 0)
  • end_row : It refers to the row position from where it will end selection.(Default value is upto last row of the dataframe)
  • start_column : It refers to the column position from where it will start selection.(Default value is 0)
  • end_column : It refers to the column position from where it will end selection.(Default value is upto last column of the dataframe)

So, we can select all the rows of the dataframe except the first row and assign back the selected rows to the original variable which will give an effect that the first row has been deleted from the dataframe.

To achieve this, select dataframe from row-2 and select all columns. Row-2 means we will select from index position-1 (as index position starts from 0 in dataframe) upto last row. And to select all columns use default values i.e (:)

i.e

df = df.iloc[1: , :]

So let’s see the implementation of it.

# Program :

import pandas as pd
# List of tuples created
empoyees = [('A',1,'a',10),
            ('B',2,'b',20),
            ('C',3,'c',30) ,
            ('D',4,'d',40)]
# DataFrame object created
df = pd.DataFrame(  empoyees, columns=['Upper', 'Smaller', 'Lower', 'Bigger'])
print("Contents of the original Dataframe : ")
print(df)
# Dropping first row 
df = df.iloc[1: , :]
print("Contents of modified Dataframe : ")
print(df)
Output :
Contents of the original Dataframe : 
  Upper  Smaller  Lower Bigger
0   A         1          a           10
1   B         2          b           20
2   C         3          c           30
3   D        4           d          40
Contents of modified Dataframe : 
    Upper Smaller Lower Bigger
1     B       2            b        20
2     C       3            c        30
3     D       4            d        40

Method-2 : Using drop() function :

There is an drop() function in Panda’s dataframe which can be used to delete any rows from the dataframe.  To make sure that rows only will be deleted then select axis=0 and pass argument inplace=True.

So let’s see the implementation of it.

# Program :

import pandas as pd
# List of tuples created
empoyees = [('A',1,'a',10),
            ('B',2,'b',20),
            ('C',3,'c',30) ,
            ('D',4,'d',40)]
# DataFrame object created
df = pd.DataFrame(  empoyees, columns=['Upper', 'Smaller', 'Lower', 'Bigger'])
print("Contents of the original Dataframe : ")
print(df)
# Dropping first row 
df.drop(index=df.index[0], 
        axis=0, 
        inplace=True)
        
print("Contents of modified Dataframe : ")
print(df)
Output : 
Contents of the original Dataframe : 
    Upper Smaller Lower Bigger
0     A           1         a       10
1     B           2         b       20
2     C           3         c       30
3     D           4         d      40
Contents of modified Dataframe : 
    Upper Smaller Lower Bigger
1     B         2           b       20
2     C         3           c       30
3     D        4            d       40

Method-3 : Using tail() function :

In python, dataframe provides a tail(n) function which returns last ‘n’ rows. So to select all the rows except first row we can pass tail(n-1) which means first row deleted. And it assign back the selected rows to the original variable.

So let’s see the implementation of it.

# Program :

import pandas as pd
# List of tuples created
empoyees = [('A',1,'a',10),
            ('B',2,'b',20),
            ('C',3,'c',30) ,
            ('D',4,'d',40)]
# DataFrame object created
df = pd.DataFrame(  empoyees, columns=['Upper', 'Smaller', 'Lower', 'Bigger'])
print("Contents of the original Dataframe : ")
print(df)

# Deleting first row by selecting last n-1 rows
df = df.tail(df.shape[0] -1)
        
print("Contents of modified Dataframe : ")
print(df)
Output :
Contents of the original Dataframe : 
     Upper Smaller Lower Bigger
0      A         1          a         10
1      B         2          b         20
2      C         3          c         30
3      D         4          d        40
Contents of modified Dataframe : 
    Upper Smaller Lower Bigger
1     B         2          b       20
2     C         3          c       30
3     D         4          d       40

 

Numpy unique – Python: Find Unique Values in a Numpy Array With Frequency and Indices

Methods to find unique values in a numpy array with frequency and indices

Numpy get unique values: In this article, we will discuss how to find unique values, rows, and columns in a 1D & 2D Numpy array. Before going to the methods first we see numpy.unique() method because this method is going to be used.

numpy.unique() method

Numpy unique: numpy.unique() method help us to get the unique() values from given array.

syntax:numpy.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)

Parameters

  1. array-Here we have to pass our array from which we want to get unique value.
  2. return_index- If this parameter is true then it will return the array of the index of the first occurrence of each unique value. By default it is false.
  3. return_counts-If this parameter is true then it will return the array of the count of the occurrence of each unique value. By default it is false.
  4. axis- It is used in the case of nd array, not in 1d array. axis=1 means we have to do operation column-wise and axis=0 means we have to do operation row-wise.

Now we will see different methods to find unique value with their indices and frequencies in a numpy array.

case 1-When our array is 1-D

  • Method 1-Find unique value from the array

Numpy unique values: As we only need unique values and not their frequencies and indices hence we simply pass our numpy array in the unique() method because the default value of other parameters is false so we don’t need to change them. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
  • Method 2-Find unique value from the array along with their indices

Numpy frequency count: In this method, as we want to get unique values along with their indices hence we make the return_index parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,index=np.unique(arr,return_index=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("First index of unique values are:")
print(index)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
First index of unique values are:
[0 2 3 4 5 6 7]
  • Method 3-Find unique value from the array along with their frequencies

Numpy count unique: In this method, as we want to get unique values along with their frequencies hence we make the return_counts parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,count=np.unique(arr,return_counts=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("Count of unique values are:")
for i in range(0,len(unique_values)):
  print("count of ",unique_values[i]," is ",count[i])

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
Count of unique values are:
count of  1  is  3
count of  2  is  2
count of  3  is  2
count of  4  is  2
count of  5  is  1
count of  6  is  1
count of  7  is  2

Case 2: When our array is 2-D

  • Method 1-Find unique value from the array

Numpy unique: Here we simply pass our array and all the parameter remain the same. Here we don’t make any changes because we want to work on both rows and columns. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique values are
[1 2 3 6]

Method 2-Get unique rows

Numpy unique: As here want to want to work only on rows so here we will make axis=0 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=0)
print("Original array is")
print(arr)
print("------------------")
print("Unique rows are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique rows are
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]]

Method 3-Get unique columns

As here want to want to work only on columns so here we will make axis=1 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=1)
print("Original array is")
print(arr)
print("------------------")
print("Unique columns are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique columns are
[[1 1 2]
 [1 3 2]
 [1 6 2]
 [1 1 2]]

so these are the methods to find unique values in a numpy array with frequency and indices.

 

Numpy 2d to 1d – Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array | How to make a 2d Array into a 1d Array in Python?

Python Convert Matrix or 2D Numpy Array to a 1D Numpy Array

Numpy 2d to 1d: This article is all about converting 2D Numpy Array to a 1D Numpy Array. Changing a 2D NumPy array into a 1D array returns in an array containing the same elements as the original, but with only one row. Want to learn how to convert 2d Array into 1d Array using Python? Then, stay tuned to this tutorial and jump into the main heads via the available links shown below:

Convert 2D Numpy array / Matrix to a 1D Numpy array using flatten()

How to convert a 2d array into a 1d array: Python Numpy provides a function flatten() to convert an array of any shape to a flat 1D array.

Firstly, it is required to import the numpy module,

import numpy as np

Syntax:

ndarray.flatten(order='C')
ndarray.flatten(order='F')
ndarray.flatten(order='A')

Order: In which items from the array will be read

Order=’C’: It will read items from array row-wise

Order=’F’: It will read items from array row-wise

Order=’A’: It will read items from array-based on memory order

Suppose we have a 2D Numpy array or matrix,

[7 4 2]
[5 3 6]
[2 9 5]

Which we have to convert in a 1D array. Let’s use this to convert a 2D numpy array or matrix to a new flat 1D numpy array,

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

If we made any changes in our 1D array it will not affect our original 2D array.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)
# Modify the flat 1D array
flat_array[0] = 50
print('Modified Flat Array: ')
print(flat_array)
print('Original Input Array: ')
print(arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

Modified Flat Array:
[50 4 2 5 3 6 2 9 5]

Original Input Array:
[[7 4 2]
[5 3 6]
[2 9 5]]

Also Check:

Convert 2D Numpy array to 1D Numpy array using numpy.ravel()

Numpy have  a built-in function ‘numpy.ravel()’ that accepts an array element as parameter and returns a flatten 1D array.

Syntax:

numpy.ravel(input_arr, order='C')

Let’s make use of this syntax to convert 2D array to 1D array,

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)

Output:

Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]

If we made any changes in our 1D array using numpy.ravel() it will also affect our original 2D array.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)
# Modify the 2nd element  in flat array
flat_array[1] = 12
# Changes will be reflected in both flat array and original 2D array
print('Modified Flattened 1D Numpy array:')
print(flat_array)
print('2D Numpy Array:')
print(arr)

Output:

Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]
Modified Flattened 1D Numpy array:
[ 7 12 2 5 3 6 2 9 5]
2D Numpy Array:
[[ 7 12 2]
[ 5 3 6]
[ 2 9 5]]

Convert a 2D Numpy array to a 1D array using numpy.reshape()

Numpy provides a built-in function reshape() to convert the shape of a numpy array,

It accepts three arguments-

  • a: Array which we have to be reshaped
  • newshape: Newshape can be a tuple or integer
  • order: The order in which items from the input array will be used
import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array of size 9
flat_arr = np.reshape(arr, 9)
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

In the above example, we have pass 9 as an argument because there were a total of 9 elements (3X3) in the 2D input array.

numpy.reshape() and -1 size

This function can be used when the input array is too big and multidimensional or we just don’t know the total elements in the array. In such scenarios, we can pass the size as -1.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array without mentioning the actual size
flat_arr = np.reshape(arr, -1)
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

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

With the help of reshape() function, we can view the input array and any modification done in the view object will be reflected in the original input too.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
[5, 3, 6],
[2, 9, 5]])
flat_arr = np.reshape(arr,-1)
print('1D Numpy Array:')
print(flat_arr)
# Modify the element at the first row and first column in the 1D array
arr[0][0] = 11
print('1D Numpy Array:')
print(flat_arr)
print('2D Numpy Array:')
print(arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

1D Numpy Array:
[11 4 2 5 3 6 2 9 5]

2D Numpy Array:

[[11 4 2]
[ 5 3 6]
[ 2 9 5]]

Convert 2D Numpy array to 1D array but Column Wise

If we pass the order parameter in reshape() function as “F” then it will read 2D input array column-wise. As we will show below-

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Read 2D array column by column and create 1D array from it
flat_arr = np.reshape(arr, -1, order='F')
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 5 2 4 3 9 2 6 5]

Count characters in string recursion – Python Program to Count Number of Uppercase Letters in a String using Recursion

Program to Count Number of Uppercase Letters in a String using Recursion

Count characters in string recursion: In the previous article, we have discussed Python Program to Count Number of Digits in a Number using Recursion

Given a string and the task is to count the number of uppercase letters present in a given string using recursion.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given String = "Hello This is Btechgeeks"

Output:

The Number Of UpperCase characters Present in the above given String { Hello This is Btechgeeks } = 3

Example2:

Input:

Given String = "GOOD morning btechgeeks"

Output:

The Number Of UpperCase characters Present in the above given String { GOOD morning btechgeeks } = 4

Program to Count Number of Uppercase Letters in a String using Recursion in Python

Below are the ways to count the number of uppercase letters present in a given string using recursion in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable say cnt and initialize its value to 0.
  • Pass the given string and length of the given string-1 as the arguments to the cntUpprCase_chactrs function and store it in a variable rslt_cnt.
  • Create a recursive function to say cntUpprCase_chactrs which takes the given string and a variable p (initially it is the length of the given string ) and returns the count of uppercase characters in a given string.
  • Make the cnt a global declaration.
  • Check if the character present at the index p of the given string is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If the statement is true, then increment the value of cnt by 1 and store it in the same variable.
  • Check if the value of p is greater than 0 using the if conditional statement.
  • If the statement is true, pass the given string and p-1 as the arguments to the cntUpprCase_chactrs function.{Recursive logic}
  • Return the value of cnt.
  • Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
  • If the statement is true, then print “There are no UpperCase characters in a given string”.
  • Else print the number of uppercase characters present in the above-given string.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say cntUpprCase_chactrs which takes the given string and
# a variable p (initially it is the length of the given string ) as the arguments to
# the cntUpprCase_chactrs function which returns the count of uppercase characters in
# a given string.


def cntUpprCase_chactrs(gvn_strng, p):
  # Make the cnt a global declaration.
    global cnt
    # Check if the character present at the index p of the given string is greater than or
    # equal to 'A' and less than or equal to 'Z' using the if conditional statement.
    if (gvn_strng[p] >= 'A' and gvn_strng[p] <= 'Z'):
        # If the statement is true, then increment the value of cnt by 1 and store it in the
        # same variable.
        cnt += 1
    # Check if the value of p is greater than 0 using the if conditional statement.
    if (p > 0):
        # If the statement is true, pass the given string and p-1 as the arguments to the
        # cntUpprCase_chactrs function.{Recursive logic}
        cntUpprCase_chactrs(gvn_strng, p - 1)
    # Return the value of cnt.
    return cnt


# Give the string as static input and store it in a variable.
gvn_strng = "Hello This is Btechgeeks"
# Take a variable say cnt and initialize its value to 0.
cnt = 0
# Pass the given string and length of the given string-1 as the arguments to the
# cntUpprCase_chactrs function and store it in a variable rslt_cnt.
rslt_cnt = cntUpprCase_chactrs(gvn_strng, len(gvn_strng)-1)
# Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
if(rslt_cnt == 0):
  # If the statement is true, then print "There are no UpperCase characters in a given
  # string".
    print("There are no UpperCase characters in a given string")
else:
  # Else print the number of uppercase characters present in the above-given string.
    print(
        "The Number Of UpperCase characters Present in the above given String {", gvn_strng, "} =", rslt_cnt)

Output:

The Number Of UpperCase characters Present in the above given String { Hello This is Btechgeeks } = 3

Method #2: Using Recursion (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable say cnt and initialize its value to 0.
  • Pass the given string and length of the given string-1 as the arguments to the cntUpprCase_chactrs function and store it in a variable rslt_cnt.
  • Create a recursive function to say cntUpprCase_chactrs which takes the given string and a variable p (initially it is the length of the given string ) as the arguments to the cntUpprCase_chactrs function which returns the count of uppercase characters in a given string.
  • Make the cnt a global declaration.
  • Check if the character present at the index p of the given string is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If the statement is true, then increment the value of cnt by 1 and store it in the same variable.
  • Check if the value of p is greater than 0 using the if conditional statement.
  • If the statement is true, pass the given string and p-1 as the arguments to the cntUpprCase_chactrs function.{Recursive logic}
  • Return the value of cnt.
  • Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
  • If the statement is true, then print “There are no UpperCase characters in a given string”.
  • Else print the number of uppercase characters present in the above-given string.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say cntUpprCase_chactrs which takes the given string and
# a variable p (initially it is the length of the given string ) as the arguments to
# the cntUpprCase_chactrs function which returns the count of uppercase characters in
# a given string.


def cntUpprCase_chactrs(gvn_strng, p):
  # Make the cnt a global declaration.
    global cnt
    # Check if the character present at the index p of the given string is greater than or
    # equal to 'A' and less than or equal to 'Z' using the if conditional statement.
    if (gvn_strng[p] >= 'A' and gvn_strng[p] <= 'Z'):
        # If the statement is true, then increment the value of cnt by 1 and store it in the
        # same variable.
        cnt += 1
    # Check if the value of p is greater than 0 using the if conditional statement.
    if (p > 0):
        # If the statement is true, pass the given string and p-1 as the arguments to the
        # cntUpprCase_chactrs function {Recursive logic}
        cntUpprCase_chactrs(gvn_strng, p - 1)
    # Return the value of cnt.
    return cnt


# Give the string as user input using the input() function and 
# store it in a variable.
gvn_strng = input("Enter some Random String = ")
# Take a variable say cnt and initialize its value to 0.
cnt = 0
# Pass the given string and length of the given string-1 as the arguments to the
# cntUpprCase_chactrs function and store it in a variable rslt_cnt.
rslt_cnt = cntUpprCase_chactrs(gvn_strng, len(gvn_strng)-1)
# Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
if(rslt_cnt == 0):
  # If the statement is true, then print "There are no UpperCase characters in a given
  # string".
    print("There are no UpperCase characters in a given string")
else:
  # Else print the number of uppercase characters present in the above-given string.
    print(
        "The Number Of UpperCase characters Present in the above given String {", gvn_strng, "} =", rslt_cnt)

Output:

Enter some Random String = GOOD morning btechgeeks
The Number Of UpperCase characters Present in the above given String { GOOD morning btechgeeks } = 4

If you wanna write simple python programs as a part of your coding practice refer to numerous Simple Python Program Examples existing and learn the approach used.