- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find how many distinct rotation groups are there for a list of words in Python
Suppose we have rotation group for a string that holds all of its unique rotations. If the input is like, "567" then this can be rotated to "675" and "756" and they are all in the same rotation group. Now if we have a list of strings words, we have to group each word by their rotation group, and find the total number of groups.
So, if the input is like words = ["xyz", "ab", "ba", "c", "yzx"], then the output will be 3, as There are three rotation groups − ["xyz", "yzx"], ["ab", "ba"], ["c"].
To solve this, we will follow these steps −
- s:= a new set
- ct:= 0
- for each i in words, do
- if i not in s, then
- ct := ct + 1
- for j in range 0 to size of i, do
- temp := substring of i[from index j to end] concatenate substring of i [from beginning to j])
- insert temp to s
- if i not in s, then
- return ct
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, words): s=set() ct=0 for i in words: if i not in s: ct+=1 for j in range(len(i)): s.add(i[j:]+i[:j]) return ct ob = Solution() print(ob.solve(["xyz", "ab", "ba", "c", "yzx"]))
Input
["xyz", "ab", "ba", "c", "yzx"]
Output
3
Advertisements