
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Permutations with Perfect Square Adjacent Pairs in Python
Suppose we have a list of numbers called nums. We have to find the number of permutations of nums such that sum of every pair of adjacent values is a perfect square. Two permutations A and B are unique when there is some index i where A[i] is not same as B[i].
So, if the input is like nums = [2, 9, 7], then the output will be 2, as we have [2, 7, 9] and [9, 7, 2]
To solve this, we will follow these steps −
res := 0
Define a function util() . This will take i
-
if i + 1 is same as size of nums , then
res := res + 1
return
visited := a new empty set
-
for j in range i + 1 to size of nums, do
s := nums[i] + nums[j]
-
if s is not visited and (square root of s)^2 is s, then
mark s as visited
swap nums[i + 1] and nums[j]
util(i + 1)
swap nums[i + 1] and nums[j]
From the main method do the following −
visited := a new set
-
for i in range 0 to size of nums, do
swap nums[i] and nums[0]
-
if nums[0] is not visited, then
util(0)
mark nums[0] as visited
swap nums[i] and nums[0]
return res
Let us see the following implementation to get better understanding −
Example
from math import sqrt class Solution: def solve(self, nums): self.res = 0 def util(i): if i + 1 == len(nums): self.res += 1 return visited = set() for j in range(i + 1, len(nums)): s = nums[i] + nums[j] if s not in visited and int(sqrt(s)) ** 2 == s: visited.add(s) nums[i + 1], nums[j] = nums[j], nums[i + 1] util(i + 1) nums[i + 1], nums[j] = nums[j], nums[i + 1] visited = set() for i in range(len(nums)): nums[i], nums[0] = nums[0], nums[i] if nums[0] not in visited: util(0) visited.add(nums[0]) nums[i], nums[0] = nums[0], nums[i] return self.res ob = Solution() nums = [2, 9, 7] print(ob.solve(nums))
Input
[2, 9, 7]
Output
2