Amazon Interview Question
Research ScientistsCountry: United States
Interview Type: Phone Interview
Is there any other limitations?
In PHP:
function divide_input(array $input) {
$num_input = count($input);
$testing = array();
$keys = array_rand($input, floor($num_input*0.2));
foreach ($keys as $key) {
$testing[] = $input[$key];
unset($input[$key]);
}
unset($key);
return array($input, $testing);
}
In python
- Larry December 14, 2013{{
from random import random, randint, sample
#Given an array, divide it into two parts for monte carlo simulations
#with 80% of them as training and the rest as testing.
#without with repeated elements
def monte_carlo_split_without(array):
train = sample(array,int(0.8*len(array)))
test = list(set(array)-set(train))
return train,test
#with with repeated elements
def monte_carlo_split_with(array):
train = []
test = []
for ar in array:
if random() > 0.8:
test.append(ar)
else:
train.append(ar)
return train,test
#testing
if __name__ == '__main__':
a = sample(range(1,1000),300)
b = [randint(1,1000) for i in range(0,300)]
train, test = monte_carlo_split_with(b)
print len(train)+len(test)
print float(len(train))/len(b)
train, test = monte_carlo_split_without(a)
print len(train)+len(test)
print float(len(train))/len(b)
}}