Python | Check possible bijection between sequence of characters and digits

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

True


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.