Home > Backend Development > Python Tutorial > How Can Cartesian Product Generate Permutations with Repetitions?

How Can Cartesian Product Generate Permutations with Repetitions?

Barbara Streisand
Release: 2024-12-21 21:52:38
Original
433 people have browsed it

How Can Cartesian Product Generate Permutations with Repetitions?

Getting Permutations with Repetitions Using Cartesian Product

Introduction

When generating permutations from a list, the standard itertools library skips combinations where elements repeat. To obtain all possible permutations, including those with repetitions, the Cartesian product is used.

Itertools Permutations

The permutations() function in itertools generates permutations without repetitions. In the case of dice rolls, this excludes combinations like (1, 1), where the same number appears on both dice.

Cartesian Product

The Cartesian product between two sets creates a new set containing all ordered pairs where the first element comes from the first set and the second element comes from the second set. For example, the Cartesian product of {1, 2} and {3, 4} is {(1, 3), (1, 4), (2, 3), (2, 4)}.

Applying Cartesian Product to Dice Rolls

To generate all possible dice roll combinations with repetitions using the Cartesian product:

import itertools
x = [1, 2, 3, 4, 5, 6]
dice_combinations = [p for p in itertools.product(x, repeat=2)]
Copy after login

Example Result

The output will be a list of 36 ordered pairs, including combinations like (1, 1):

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
Copy after login

Random Dice Roll

A random dice roll can be obtained by selecting a pair from the Cartesian product list:

import random
random_roll = random.choice(dice_combinations)
Copy after login

The above is the detailed content of How Can Cartesian Product Generate Permutations with Repetitions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template