0

I have for loop, and I need to modify it as follows: If we have CarTypes A or B: It will randomly choose methods which are AA, BB, CC, and DD. However, I want the choice to have a bias. So, I want the choice of Method DD will be less than the choice of the rest of methods AA, BB, and CC.

Also, If we have CarTypes C or D: It will randomly choose methods which are AA, BB, CC, DD, EE, and FF. However, I want the choice of Method DD, EE, and FF will be more than the choice of the rest of methods AA, BB, and CC. Any suggestions please?

import random
from enum import Enum
Steps = 11
class CarTypes(Enum):
    A   = 0
    B   = 1
    C   = 2
    D   = 3   
class Methods(Enum):
    AA = 0
    BB = 1
    CC = 2
    DD = 3
    EE = 4
    FF = 5
    GG = 6
        
for iStep in range(Steps):
    Number = 0
    
    if (CarTypes.A.value or CarTypes.B.value):
        N = random.randrange(0, Methods.EE.value)
        if   ( N == Methods.AA.value ):
            Number =+ 1            
        elif ( N == Methods.BB.value ):  
            Number =+ 1         
        elif ( N == Methods.CC.value ):  
            Number =+ 1        
        elif ( N == Methods.DD.value ): 
            Number =+ 1

    elif (CarTypes.C.value or CarTypes.D.value):
        nEvent = random.randrange(0, Methods.GG.value)
        
        if   ( N == Methods.AA.value ):
            Number =+ 1            
        elif ( N == Methods.BB.value ):  
            Number =+ 1      
        elif ( N == Methods.CC.value ):  
            Number =+ 1         
        elif ( N == Methods.DD.value ):  
            Number =+ 1                
        elif ( N == Methods.EE.value ):  
            Number =+ 1         
        elif ( N == Methods.FF.value ): 
            Number =+ 1
        
    
     
mus
  • 3
  • 2
  • [A weighted version of random.choice](https://stackoverflow.com/q/3679694/11082165) might be a better dupe target. – Brian61354270 Aug 15 '23 at 14:48
  • Also, do note that enums are iterable, so you can just sample `list(Methods)` instead of converting to and from integer values. – Brian61354270 Aug 15 '23 at 14:50
  • `CarTypes.A.value or CarTypes.B.value` is probably not doing what you think it does. That expression is always `True`. – Brian61354270 Aug 15 '23 at 14:52
  • Another tip: if there's inherent significance to certain enum variants, you might want to consider adding a method to the enum instead of checking for those variants repeatedly in your code. For example, something like `def is_foo(self): return self in (Methods.A, Methods.B, Methods.C, Methods.D)` to replace the first `if`/`elif` block. – Brian61354270 Aug 15 '23 at 14:55

0 Answers0