Ancient Astronaut Theory in Python

PythonServer Side ProgrammingProgramming

Suppose er have a string dictionary, the dictionary is representing a partial lexicographic ordering of ancient astronauts' dictionary. So, if we have a string s, we have to check whether it's a lexicographically sorted string according to this ancient astronaut dictionary or not.

So, if the input is like dictionary = "bdc", s = "bbbb h ddd i cccc", then the output will be True

To solve this, we will follow these steps −

  • l := size of astro_dict

  • if l is same as 0, then

    • return True

  • i := 0

  • for each character c in s, do

    • if c in astro_dict, then

      • while i < l and astro_dict[i] is not c, do

        • i := i + 1

      • if i >= l or astro_dict[i] is not c, then

        • return False

  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, astro_dict, s):
      l = len(astro_dict)
      if l == 0:
         return True
      i = 0
      for c in s:
         if c in astro_dict:
            while i < l and astro_dict[i] != c:
               i += 1
            if i >= l or astro_dict[i] != c:
               return False
      return True
ob = Solution()
print(ob.solve("bdc","bbbb h ddd i cccc"))

Input

"bdc","bbbb h ddd i cccc"

Output

True
raja
Updated on 02-Sep-2020 12:52:14

Advertisements