Python Program to create an OTP by squaring and concatenating the odd digits of a number


The task is to create a One-Time Password (OTP) by squaring and concatenating the odd digits of a given number. 

Input Output Scenarios

Following are the input-output scenarios for creating an OTP by squaring and concatenating the odd digits of a number

Input number = 123456789
Output OTP: 19254981

The odd digits in the number are 1, 3, 5, 7, 9. Squaring each of these digits gives us 1, 9, 25, 49, 81. Concatenating these squared digits together gives us the OTP 19254981.

Input: 54321
Output: 2591

The odd digits in the input number are 5, 3, and 1. Squaring these digits gives us 25, 9, and 1. Concatenating these squared digits gives us the OTP 2591.

Approach

We can follow the below steps to create an OTP by squaring and concatenating the odd digits of a given number.

  • Define a function that takes a number as input.

  • Initialize an empty list to store the squared odd digits.

  • Iterate over the digits of the number. 

  • For each digit, check if it is odd by using the modulo operator (digit % 2 != 0). If the digit is odd, square it (digit ** 2) and store it.

  • After processing all the digits, join the squared digits together using the join method, which concatenates the elements of a list into a single string. The squared digits are joined without any separator, resulting in a single string.

  • Return the concatenated OTP string.

Example

Here is an example that creates an OTP by squaring and concatenating the odd digits of a given number.

def create_otp(number):
    odd_digits = []
    while number > 0:
        digit = number % 10
        if digit % 2 != 0:
            odd_digits.append(str(digit ** 2))
        number //= 10
    otp = "".join(odd_digits[::-1])
    return otp

#  Define the input number
number = 789
print("Input number:", number)
otp = create_otp(number)
print("OTP:", otp)

Output

Input number: 789
OTP: 4981

Example

In this example, we will create a function that takes a number as input. The function converts the number to a string and iterates over each digit. If a digit is odd (i.e., not divisible by 2), the function squares the digit and appends it to a list.

After processing all the digits, the function uses a generator expression to convert each squared digit into a string. These squared digits are then joined together using the join() function, resulting in the formation of the OTP.

def create_otp(number):
    odd_digits = [int(digit) for digit in str(number) if int(digit) % 2 != 0]
    otp = "".join(str(digit**2) for digit in odd_digits)
    return otp

#  Define the input number
number = 12349
print("Input number:", number)
otp = create_otp(number)
print("OTP:", otp)

Output

Input number: 12349
OTP: 1981

Updated on: 29-Aug-2023

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements