Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Permutation of a given string using inbuilt function
Next article icon

Print first n distinct permutations of string using itertools in Python

Last Updated : 07 Jan, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string with duplicate characters allowed, print first n permutations of given string such that no permutation is repeated.

Examples:

  Input : string = "abcab", n = 10  Output : aabbc aabcb aacbb ababc abacb                  abbac abbca abcab abcba acabb    Input : string = "okok", n = 4  Output : kkoo koko kook okko  

Approach:
Python provides an inbuilt method to find the permutations of any given sequence which is present in the itertools package. But this method doesn’t provide unique permutations. Hence to ensure that any permutation is not repeated, we use a set and follow the below conditions:

  • If the permutation is not present in the set, print it and insert it in the set. Increment the count of number of unique permutations.
  • Else, move on to the next permutation.

Below is the implementation of the above approach:




# Python3 program to print first n unique 
# permutations of the string using itertools
from itertools import permutations
  
# Function to print first n unique 
# permutation using itertools 
def nPermute(string, n): 
  
    # Convert the string to list and sort 
    # the characters in alphabetical order
    strList = sorted(list(string))
      
    # Create an iterator
    permList = permutations(strList)
  
    # Keep iterating until we 
    # reach nth unique permutation
    i = 0
    permSet = set()
    tempStr = '' 
      
    while i < n:
        tempStr = ''.join(permList.__next__())
          
        # Insert the string in the set
        # if it is not already included
        # and print it out.
        if tempStr not in permSet:
            permSet.add(tempStr)
            print(tempStr)
            i += 1
      
# Driver code 
if __name__ == "__main__":
  
    string = "ababc"
    n = 10
    nPermute(string, n) 
 
 
Output:
  aabbc  aabcb  aacbb  ababc  abacb  abbac  abbca  abcab  abcba  acabb  


Next Article
Python | Permutation of a given string using inbuilt function

R

rituraj_jain
Improve
Article Tags :
  • Combinatorial
  • DSA
  • Python
  • Technical Scripter
  • Python string-programs
  • Technical Scripter 2018
Practice Tags :
  • Combinatorial
  • python

Similar Reads

  • Python | Permutation of a given string using inbuilt function
    The task is to generate all the possible permutations of a given string. A permutation of a string is a rearrangement of its characters. For example, the permutations of "ABC" are "ABC", "ACB", "BAC", "BCA", "CAB", and "CBA". The number of permutations of a string with n unique characters is n! (fac
    2 min read
  • All permutations of a string using iteration
    A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We hav
    4 min read
  • Print all Unique permutations of a given string.
    Given a string that may contain duplicates, the task is find all unique permutations of given string in any order. Examples: Input: "ABC"Output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]Explanation: Given string ABC has 6 unique permutations as "ABC", "ACB", "BAC", "BCA", "CAB" and "CBA". Input: "A
    12 min read
  • Permutations of a given string using STL
    Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB" Input: s = "XY"Output: "XY", "YX"
    4 min read
  • Print all the permutations of a string without repetition using Collections in Java
    Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. A permutation should not have repeated strings in the output. Examples: Input: str = "aa" Output: aa Note that "aa" w
    2 min read
  • Print all the permutation of length L using the elements of an array | Iterative
    Given an array of unique elements, we have to find all the permutations of length L using the elements of the array. Repetition of elements is allowed.Examples: Input: arr = { 1, 2 }, L=3 Output: 111 211 121 221 112 212 122 222Input: arr = { 1, 2, 3 }, L=2 Output: 11 21 31 12 22 32 13 23 33 Approach
    5 min read
  • Distinct permutations of the string | Set 2
    Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB" Input: s = "XY"Output: "XY", "YX"
    6 min read
  • Distinct permutations of a string containing duplicates using HashSet in Java
    Given a string str that may contain duplicate characters, the task is to print all the distinct permutations of the given string such that no permutation is repeated in the output. Examples: Input: str = "ABA" Output: ABA AAB BAA Input: str = "ABC" Output: ABC ACB BAC BCA CBA CAB Approach: An approa
    2 min read
  • Create multiple copies of a string in Python by using multiplication operator
    In Python, creating multiple copies of a string can be done in a simple way using multiplication operator. In this article, we will focus on how to achieve this efficiently. Using multiplication operator (*)This method is the easiest way to repeat a string multiple times in Python. It directly gives
    1 min read
  • Find the N-th lexicographic permutation of string using Factoradic method
    Given string str with unique characters and a number N, the task is to find the N-th lexicographic permutation of the string using Factoradic method. Examples: Input: str = "abc", N = 3 Output: bac Explanation: All possible permutations in sorted order: abc, acb, bac, bca, cab, cba 3rd permutation i
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences