TAGS :Viewed: 1 - Published at: a few seconds ago

[ diving a string depending on a variable ]

I have a piece of code (that was kindly written by someone from stackoverflow) which separates conditions based on a time variable:

factors = {"factor 1" : "10 minutes",
"factor 2" : "2 minutes",
"factor 3" : "8 minutes",
"factor 4" : "20 minutes",
"factor 5" : "7 minutes"
}

wantedTime = 19;
String_1={}
String_2={}
total = 0
for k,v in factors.items():## or factors.iteritems()
    time = int(v.split(" ")[0])
    if total+time <= wantedTime:
        total +=time
        String_1[k]=v
    else:
        String_2[k]=v 

However, it always seems to select the same variables for the first string. For instance if i run this script 5 times where i want 19 minutes worth of variables, it always splits them in the same way. What I want is for it to be randomised:

so sometimes it selects factor 4, sometimes it selects factors 1 and 3.

Thank you in advance

Answer 1


I think you can just shuffle the iterable:

import random

for k, v in sorted(factors.items(), key=lambda k: random.random()):

Answer 2


Converted my comment into an answer for the sake of it.

from random import randint
factors = {"factor 1" : "10 minutes",
"factor 2" : "2 minutes",
"factor 3" : "8 minutes",
"factor 4" : "20 minutes",
"factor 5" : "7 minutes"
}

wantedTime = 19;
String_1={}
String_2={}
total = 0
for k in list(factors.keys())[randint(0, 1000)%len(factors)-1]:
    v = factors[k]
    time = int(v.split(" ")[0])
    if total+time <= wantedTime:
        total +=time
        String_1[k]=v
    else:
        String_2[k]=v