Python - Find the latest valid time that can be obtained by replacing the unknown/hidden digits

PythonServer Side ProgrammingProgramming

When it is required to find the valid time which can be obtained by replacing unknown digits, a method is defined that checks to find the unknown/hidden digit, and then converts it into a different value depending on the value present in the index.

Example

Below is a demonstration of the same

def find_latest_time(my_time):
   my_time = list(my_time)
   for i in range(len(my_time)):
      if my_time[i] == "?":
         if i == 0: my_time[i] = "2" if my_time[i+1] in "?0123" else "1"
         elif i == 1: my_time[i] = "3" if my_time[0] == "2" else "9"
         elif i == 3: my_time[i] = "5"
         else: my_time[i] = "9"
   print("".join(my_time))

my_str = '0?:?3'
print("The time is :")
print(my_str)
print("The latest valid time is : ")
find_latest_time(my_str)

Output

The time is :
0?:?3
The latest valid time is :
09:53

Explanation

  • A method named ‘find_latest_time’ is defined that takes a time as a parameter.

  • It is converted to a list.

  • It is iterated over and checked to see for the hidden/unknown time values.

  • If the value of the iterator is 0 or 1 or 3, it is replaced with a specific value.

  • Outside the method, a string is defined, and is displayed on the console.

  • The method is called by passing this value.

  • The output is displayed on the console.

raja
Published on 20-Sep-2021 11:10:00
Advertisements