Open In App

Python | Check possible bijection between sequence of characters and digits

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string ‘char_seq'(sequence of characters) and a positive integer ‘dig_seq'(sequence of digits), Write a Python program to find possible bijection or one-one onto relationship between ‘char_seq’ and ‘dig_seq’ such that each character matches to one and only one digit. 

Examples:

Input : char_seq = 'bxdyxb'
        dig_seq = 123421
Output : True

Input : char_seq = 'bxdyxb'
        dig_seq = 123321
Output : False

  Method #1: Using zip method This method simply zips the ‘char_seq’ and ‘dig_seq’ and checks if corresponding digits and characters matches or not. 

Python3




# Python3 program to Check possible bijection
# between sequence of characters and digits
 
def is_bijection(char_seq, dig_seq):
    z = zip(str(char_seq), str(dig_seq))
    res = all(
    (z1[0] == z2[0]) == (z1[1] == z2[1]) for z1 in z for z2 in z)
     
    return res
     
# Driver code
char_seq = 'bxdyxb'
dig_seq = 123421
print(is_bijection(char_seq, dig_seq))


Output

True

  Method #2: Using itertools.groupby method This method uses the same approach with a slight difference, it uses itertools.groupby to match characters with digits. 

Python3




# Python3 program to Check possible bijection
# between sequence of characters and digits
import itertools
 
def is_bijection(char_seq, dig_seq):
    z = sorted(zip(str(char_seq), str(dig_seq)))
    res = all(gx == gy
          for k, g in itertools.groupby(z, key = lambda res: res[0])
          for gx in g for gy in g)
     
    return res
     
# Driver code
char_seq = 'bxdyxb'
dig_seq = 123421
print(is_bijection(char_seq, dig_seq))


Output

True

 Method #3: It works by iterating through the input sequences and creating a dictionary that maps characters to digits. For each character and digit pair, if the character is already in the dictionary and the digit does not match the one already mapped to the character, then the bijection is not valid and the function returns False. Otherwise, the character and digit are added to the dictionary. If the loop completes, then the bijection is valid and the function returns True.

Python3




def is_bijection(char_seq, dig_seq):
    # Create a dictionary to map characters to digits
    dig_seq=str(dig_seq)
    char_dict = {}
    # Iterate through the character and digit pairs
    for c, d in zip(char_seq, dig_seq):
        # If the character is already in the dictionary
        if c in char_dict:
            # If the digit does not match the one already mapped to the character,
            # then the bijection is not valid
            if char_dict != d:
                return False
        else:
            # Add the character and digit to the dictionary
            char_dict = d
    # If the loop completes, then the bijection is valid
    return True
 
char_seq = 'bxdyxb'
dig_seq = 123421
print(is_bijection(char_seq, dig_seq))
#This code is contributed by Edula Vinay Kumar Reddy


Output

True

 Time complexity: O(n) and 
Auxiliary space: O(n), where n is the length of the input sequences.

Method #4: By repeatedly going through the input sequences, it builds a dictionary that converts characters to numbers. The bijection is invalid and the function returns False for any character and digit pair where the character is already present in the dictionary and the digit does not match the one previously mapped to the character. The character and digit are added to the vocabulary in all other cases. The bijection is true and the function returns True if the loop is finished.

Python




# Python program to Check possible bijection
# between sequence of characters and digits
def is_bijection(char_seq, dig_seq):
    dig_seq_str = str(dig_seq)
    if len(char_seq) != len(dig_seq_str):
        return False
 
    char_to_dig = {}
    dig_to_char = {}
 
    for char, dig in zip(char_seq, dig_seq_str):
        if char in char_to_dig and char_to_dig[char] != dig:
            return False
        if dig in dig_to_char and dig_to_char[dig] != char:
            return False
        char_to_dig[char] = dig
        dig_to_char[dig] = char
 
    return True
 
# drive code
char_seq = 'bxdyxb'
dig_seq = 123421
print(is_bijection(char_seq, dig_seq))


Output

True

Time Complexity : O(n)
Auxiliary Space: O(n)



Similar Reads

Find a bijection from X to Y without conditionals in Python
In mathematics, a bijection is a function between the two sets that is both injective and surjective. Finding a bijection from the set X to set Y without using the conditionals involves mapping each element of X to the unique element of the Y without relying on the if-else statements. In this article, we will explain the methods of Finding a biject
2 min read
Python Program to check whether it is possible to make a divisible by 3 number using all digits in an array
Given an array of integers, the task is to find whether it's possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If it is possible then print "Yes" and if not print "No". Examples: Input : arr[] = {40, 50, 90} Output : Yes We can construct a number which is divisible by 3, for example 945000.
2 min read
Python3 Program to Rearrange array elements into alternate even-odd sequence by anticlockwise rotation of digits
Given an array arr[] consisting of N positive integers, the task is to rotate the digits of array elements in an anti-clockwise direction such that elements of the array elements are in alternate even-odd or odd-even form. If multiple solutions exists, then print any one of them. Otherwise, print -1. Examples: Input: arr[] = { 143, 251, 534, 232, 8
4 min read
Python | Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Let's discuss certain ways in which this is achieved. Method #1 : Using List comprehension In this method, we just consider each
6 min read
Python Program to print all Possible Combinations from the three Digits
Given 3 digits a, b, and c. The task is to find all the possible combinations from these digits. Examples: Input: [1, 2, 3] Output: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Input: [0, 9, 5] Output: 0 9 5 0 5 9 9 0 5 9 5 0 5 0 9 5 9 0 Method 1: Brute force or Naive approach The naive approach is to run 3 loops from 0 to 3 and print all the numbers from t
2 min read
Possible Words using given characters in Python
Given a dictionary and a character array, print all valid words that are possible using characters from the array. Note: Repetitions of characters is not allowed. Examples: Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] Output : go, me, goal. This problem has existing solution please refer Print all
5 min read
Python | Find all possible substrings after deleting k characters
Given a string and an Integer k, write a Python program to find all possible substrings of the given string after deleting k characters. Examples: Input : geeks, k = 1 Output : {'gees', 'eeks', 'geks', 'geek'} Input : dog, k = 1 Output : {'do', 'dg', 'og'} Approach #1 : Naive Approach This is the recursive naive approach to find all possible substr
5 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #1 : Using loop + slicing In this, we perform task
5 min read
Sum of the digits of square of the given number which has only 1's as its digits
Given a number represented as string str consisting of the digit 1 only i.e. 1, 11, 111, .... The task is to find the sum of digits of the square of the given number. Examples: Input: str = 11 Output: 4 112 = 121 1 + 2 + 1 = 4 Input: str = 1111 Output: 16 Naive approach: Find the square of the given number and then find the sum of its digits. Below
6 min read
Python3 Program to Find Maximum value possible by rotating digits of a given number
Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N. Examples: Input: N = 657Output: 765Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765. Input: N = 7092Output: 9270Explanation:All rotations of 7092 are {7092, 2709, 9270, 09
2 min read
Article Tags :
Practice Tags :