Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7884765
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T04:53:22+00:00 2026-06-03T04:53:22+00:00

For example, given the two letters A and B, I’d like to generate all

  • 0

For example, given the two letters A and B, I’d like to generate all strings of length n that have x A’s and y B’s.

I’d like this to be done efficiently. One way that I’ve considered is to build a length x list of A’s, and then insert y B’s into the list every possible way. But insertion into a python list is linear, so this method would suck as the list gets big.

PERFORMANCE GOAL (this may be unreasonable, but it is my hope): Generate all strings of length 20 with equal numbers of A and B in time less than a minute.

EDIT: Using permutations(‘A’ * x, ‘B’ * y) has been suggested. While not a bad idea, it’s wasting a lot. If x = y = 4, you’d generate the string ‘AAAABBBB’ many times. Is there a better way that might generate each string only once? I’ve tried code to the effect of set(permutations(‘A’ * x, ‘B’ * y)) and it is too slow.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T04:53:24+00:00Added an answer on June 3, 2026 at 4:53 am

    Regarding your concerns with the performance, here is an actual generator implementation of your idea (without insert). It finds the positions for B and fill the list accordingly.

    import itertools
    
    def make_sequences(num_a, num_b):
        b_locations = range(num_a+1)
        for b_comb in itertools.combinations_with_replacement(b_locations, num_b):
            result = []
            result_a = 0
            for b_position in b_comb:
                while b_position > result_a:
                    result.append('A')
                    result_a += 1
                result.append('B')
            while result_a < num_a:
                result.append('A')
                result_a += 1
            yield ''.join(result)
    

    It does perform better. Comparing with the Greg Hewgill‘s solution (naming it make_sequences2):

    In : %timeit list(make_sequences(4,4))
    10000 loops, best of 3: 145 us per loop
    
    In : %timeit make_sequences2(4,4)
    100 loops, best of 3: 6.08 ms per loop
    

    Edit

    A generalized version:

    import itertools
    
    def insert_letters(sequence, rest):
        if not rest:
            yield sequence
        else:
            letter, number = rest[0]
            rest = rest[1:]
            possible_locations = range(len(sequence)+1)
            for locations in itertools.combinations_with_replacement(possible_locations, number):
                result = []
                count = 0
                temp_sequence = sequence
                for location in locations:
                    while location > count:
                        result.append(temp_sequence[0])
                        temp_sequence = temp_sequence[1:]
                        count += 1
                    result.append(letter)
                if temp_sequence:
                    result.append(temp_sequence)
                for item in insert_letters(''.join(result), rest):
                    yield item
    
    def generate_sequences(*args):
        '''
        arguments : squence of (letter, number) tuples
        '''
        (letter, number), rest = args[0], args[1:]
        for sequence in insert_letters(letter*number, rest):
            yield sequence
    

    Usage:

    for seq in generate_sequences(('A', 2), ('B', 1), ('C', 1)):
        print seq
    
    # Outputs
    # 
    # CBAA
    # BCAA
    # BACA
    # BAAC
    # CABA
    # ACBA
    # ABCA
    # ABAC
    # CAAB
    # ACAB
    # AACB
    # AABC
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given two strings, I want to find all common substrings of a specified length,
This is easier to explain with an example. Given these two classes: public class
Given the following HTML example... <div id='div1'>div one</div> <div id='div2'>div two</div> ...I found that
Given two resources http://example.com/places/1 http://example.com/places/2 How should the endpoint look like to merge both
Write a Java function such that Given two strings, word and a separator, return
Given two tables: (incoming greatly reduced/simplified example that exhibits the key problem) app_data represents
Given two strings, I'd like to be able to -- in Python -- be
For example, given the list ['one', 'two', 'one'] , the algorithm should return True
Example: given two dates below, finish is always greater than or equal to start
Given two bytes, how would I find the length of the common bits at

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.