-1

How do NFT projects combine their assets with all possible combinations in python? e.g. Cryptokitties: you have like 10 eyes shape, 10 skin colors, etc. to combine these assets, you get let's say 10000 combinations, each one is unique. Can someone give me an example of a script that does this?

Neuron
  • 5,141
  • 5
  • 38
  • 59
  • The simplest way would be to just have a bunch of nested for loops. The more generic way is `itertools.product()`. – AKX Sep 01 '21 at 12:45

2 Answers2

0

very specific question...

but here is how to get all combinations of elements of set of lists:

eyes = [...]
hairs = [...]
colors = [...]

combinations = [[eye, hair, color] for eye in eyes for hair in hairs for color in colors]
0

For instance like this, using itertools.product to get the Cartesian product of the cat features.

There's some additional mangling required to turn the dict of feature name -> feature values into something palatable by that function, but it's fairly simple.

import itertools

features = {
    "eyes": ["red", "purple", "blue"],
    "fur": ["leopard", "tabby", "black"],
    "tail": ["long", "short"],
}

feature_names, feature_values = zip(*features.items())  # transpose item pairs

for feature_value_set in itertools.product(*feature_values):  # generate value sets
    # zip feature names and generated values together to a dict:
    cat_specs = dict(zip(feature_names, feature_value_set))
    print(cat_specs)

This prints out the 3 * 3 * 2 = 18 lines

{'eyes': 'red', 'fur': 'leopard', 'tail': 'long'}
{'eyes': 'red', 'fur': 'leopard', 'tail': 'short'}
{'eyes': 'red', 'fur': 'tabby', 'tail': 'long'}
{'eyes': 'red', 'fur': 'tabby', 'tail': 'short'}
{'eyes': 'red', 'fur': 'black', 'tail': 'long'}
{'eyes': 'red', 'fur': 'black', 'tail': 'short'}
{'eyes': 'purple', 'fur': 'leopard', 'tail': 'long'}
{'eyes': 'purple', 'fur': 'leopard', 'tail': 'short'}
{'eyes': 'purple', 'fur': 'tabby', 'tail': 'long'}
{'eyes': 'purple', 'fur': 'tabby', 'tail': 'short'}
{'eyes': 'purple', 'fur': 'black', 'tail': 'long'}
{'eyes': 'purple', 'fur': 'black', 'tail': 'short'}
{'eyes': 'blue', 'fur': 'leopard', 'tail': 'long'}
{'eyes': 'blue', 'fur': 'leopard', 'tail': 'short'}
{'eyes': 'blue', 'fur': 'tabby', 'tail': 'long'}
{'eyes': 'blue', 'fur': 'tabby', 'tail': 'short'}
{'eyes': 'blue', 'fur': 'black', 'tail': 'long'}
{'eyes': 'blue', 'fur': 'black', 'tail': 'short'}
AKX
  • 152,115
  • 15
  • 115
  • 172