Advertisement
Forceisthop

Untitled

Jul 21st, 2023
1,034
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. # Python3 program to find
  2. # palindromic string
  3. from collections import defaultdict
  4.  
  5. def getCount(N, s):
  6.  
  7.     # Stores frequency array
  8.     # and its count
  9.     mp = defaultdict(lambda: 0)
  10.  
  11.     # Total number of pairs
  12.     ans = 0
  13.  
  14.     for i in range(N):
  15.  
  16.         # Initializing array of size 26
  17.         # to store count of character
  18.         a = [0] * 26
  19.  
  20.         # Counting occurrence of each
  21.         # character of current string
  22.         for j in range(len(s[i])):
  23.             a[ord(s[i][j]) - ord('a')] += 1
  24.  
  25.         # Convert each count to parity(0 or 1)
  26.         # on the basis of its frequency
  27.         for j in range(26):
  28.             a[j] = a[j] % 2
  29.  
  30.         # Adding to answer
  31.         ans += mp[tuple(a)]
  32.  
  33.         # Frequency of single character
  34.         # can be possibly changed,
  35.         # so change its parity
  36.         for j in range(26):
  37.             changedCount = a[:]
  38.             if (a[j] == 0):
  39.                 changedCount[j] = 1
  40.             else:
  41.                 changedCount[j] = 0
  42.             ans += mp[tuple(changedCount)]
  43.  
  44.         mp[tuple(a)] += 1
  45.  
  46.     return ans
  47.  
  48. # Driver code
  49. if __name__ == '__main__':
  50.    
  51.     N = 4
  52.     A = [ "ball", "all", "call", "bal" ]
  53.  
  54.     print(getCount(N, A))
  55.  
  56. # This code is contributed by Shivam Singh
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement