0

I have question regarding checking a condition and running a random choice afterwards which depends on this check. To make it simple: I have six possible outcomes (e.g. names) and each of them has a specific probability for the following random choice experiment. If the experiment turns out to be 1, I want to print a text or something similar (not important). My question is if there is possibility to integrate the check for the result into the following loop or/and if there is a way find a smoother solution than my first approach:

Name = 'Tom' # (result of another process)
p_tom = 0.32
p_daniel = 0.19
#(and so on…)
employees = ['Tom', 'Daniel', 'Clarke', 'Eric', 'William', 'Max']
for i in employees:
     if name in employees and employees == 'Tom':
         result = np.random.binomial(1,p_tom)

Thanks in advance. My steps in python are only slightly improving.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
TimSqua
  • 59
  • 2

2 Answers2

1

employees == 'Tom' - will never be True - employees is a list, not a string.

It would be better to do

import numpy as np

name = 'Tom' # (result of another process)

specific_prob = {'Tom':0.32, 'Daniel':0.19, 'Clarke':0.05, 'Eric':0.29} # etc

employees = ['Tom', 'Daniel', 'Clarke', 'Eric', 'William', 'Max']
for i in employees:
    result = np.random.binomial(1,  specific_prob.get(name, 0.42))
    # do something

No conditionals needed and if the name is not in your specific_prob 0.42 is assumed: see Why dict.get(key) instead of dict[key]?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thanks, this seems to be quite more effective. Is it possible to add the check for the 'result' to the loop as well? So that if the check for 'Tom' is true and the binomial experiment is 1, something is printed? (I am not sure, on which layer I can add this check for the result) – TimSqua Dec 02 '20 at 16:44
  • @TimSqua ... directly below `result = ...` put `if result==1: do smth` ? How much python do you know? – Patrick Artner Dec 02 '20 at 16:46
1

Problem is

  1. your Name and name is not the same
  2. you have not import numpy
  3. pip3 install numpy

check out this:

from numpy import random
Name = "Tom" #(result of another process)
p_tom = 0.32
p_daniel = 0.19
#(and so on…)
employees = ["Tom", "Daniel", "Clarke", "Eric", "William", "Max"]
for i in employees:
     if Name in i :
         result = random.binomial(1,p_tom)
         print(result)
         
Abi Chhetri
  • 1,131
  • 10
  • 15