Code zur Kombination von Werten ohne Widerholung?

1 Antwort

Hallo.

Wie wäre es hiermit:

def combinations(l):
  n = len(l)
  def combinationList(i, c):
    if i == n:
      print(tuple(c))
    else:
      for j in range(n):
        if l[j] not in c:
          combinationList(i+1, c + [l[j]])    
  combinationList(0, [])
  
# Beispielaufruf
lst = [1, 2, 3]
combinations(lst)

Den Code kannst du auch für andere Programmiersprachen adaptieren. Wenn du in Python unterwegs bist, kannst du aber auch direkt die standardmäßig verfügbare Bibliothek itertools benutzen:

from itertools import permutations

def combinations(l):
  for c in permutations(l):
    print(c)
    
# Beispielaufruf
lst = [1, 2, 3]
combinations(lst)
Woher ich das weiß:Studium / Ausbildung – Diplom Wirtschaftsinformatiker