domingo, 15 de enero de 2023

Permutaciones con repetición

Nos planteamos encontrar las permutaciones con repetición de A, repetida cuatro veces, y B, repetida 2 veces. 

El mateix programa amb OOP

import itertools

# Define a class to generate permutations
class PermutationGenerator:
    def __init__(self, letters, repeat, count_A, count_B):
        # Store the arguments as instance variables
        self.letters = letters
        self.repeat = repeat
        self.count_A = count_A
        self.count_B = count_B
    
    def generate_permutations(self):
        # Generate all possible permutations using itertools.product
        result = itertools.product(self.letters, repeat=self.repeat)
        result_set = set()
        # Loop through each permutation and count the number of As and Bs
        for permutation in result:
            if permutation.count("A") == self.count_A and permutation.count("B") == self.count_B:
                # If the permutation meets the desired criteria, add it to the result set
                result_set.add("".join(permutation))
        # Return the set of permutations that meet the desired criteria
        return result_set

# Define a class to print out permutations
class PermutationPrinter:
    def __init__(self, result_set):
        # Store the set of permutations as an instance variable
        self.result_set = result_set
    
    def print_permutations(self):
        # Loop through each permutation in the set and print it out
        for permutation in self.result_set:
            print(permutation)

if __name__ == "__main__":
    # Create an instance of the PermutationGenerator class with the desired arguments
    pg = PermutationGenerator(['A']*4+['B']*2, repeat=6, count_A=4, count_B=2)
    # Generate the set of permutations
    result_set = pg.generate_permutations()
    # Create an instance of the PermutationPrinter class with the resulting set
    pp = PermutationPrinter(result_set)
    # Print out the permutations
    pp.print_permutations()



El programa en Python nos devuelve 15 casos posibles. 

  1. AABBAA
  2. BAAAAB
  3. AABAAB
  4. AAABAB
  5. ABBAAA
  6. BABAAA
  7. AABABA
  8. BBAAAA
  9. AAAABB
  10. ABAAAB
  11. ABABAA
  12. AAABBA
  13. BAABAA
  14. BAAABA
  15. ABAABA

La fórmula de combinatoria para obtener 15 es:






El programa en, pero no OOP, Python

from itertools import product

result = product(['A']*4+['B']*2, repeat=6)
result_set = set()
for permutation in result:
    count_A = permutation.count("A")
    count_B = permutation.count("B")
    if count_A == 4 and count_B == 2:
        result_set.add("".join(permutation))

for permutation in result_set:
    print(permutation)



No hay comentarios:

Publicar un comentario