0

I am currently attempting to build a code that randomly selects food items from a table (which have a macro nutrient breakdown).

What i would like to know is how do i tell Python "Print the index of the food you randomly selected as a list"?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Boyo
  • 9
  • 1
  • One approach would be to search the item in the list (using the `index` method). But I guess it's much easier to simply randomly select an index, not an item - and then you have the index for free, and the item is easily accessed (using `[]` operator) – Neo Jul 01 '20 at 15:11
  • 1
    It would be better to reframe the title of your post. Macro-nutrient isn't a Python construct and the problem that you are trying to solve is a programming one, not biochemistry. :) Could you tell us what have you tried so far? Code snippets will be helpful. – navneethc Jul 01 '20 at 15:11

1 Answers1

0

Assume our input looks like:

import numpy as np

macro_nutrients = [
    'carbohydrates',
    'fats',
    'dietary_fiber',
    'minerals',
    'proteins',
    'vitamins',
    'water'
]

You have several options:

  1. If your macro-nutrients are stored in a list-like structure, you can do:

    el = np.random.choice(macro_nutrients)
    idx = macro_nutrients.index(el)
    print(el, ";  Is the index correct?:", el == macro_nutrients[idx])
    
    # or you can just write:
    idx = np.random.randint(0, len(macro_nutrients) - 1)
    print(macro_nutrients[idx])
    

    For [].index() you can check this SO answer for caveats.

  2. If you have a table-like structure (e.g. numpy 2d array):

    # we will simulate it by permuting the above list several times and adding the
    # permutation as a row in the new 2d array:
    mat = np.array([np.random.permutation(macro_nutrients.copy()),
                   np.random.permutation(macro_nutrients.copy()),
                   np.random.permutation(macro_nutrients.copy()),
                   np.random.permutation(macro_nutrients.copy())])
    
    # flatten() will convert your table back to 1d array
    np.random.choice(mat.flatten())
    
    # otherwise, you can use something like:
    row = np.random.randint(0, mat.shape[0] - 1)
    col = np.random.randint(0, mat.shape[1] - 1)
    print(mat[row, col])
    
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
cyau
  • 449
  • 4
  • 14