Two Sigma | Phone Screen | Random stock generation
Anonymous User
3101

Having some problems with the interview problems

Write a function that returns a random stock pick from a given list of stocks. The random function cannot return a stock pick that has already been returned until the list is exhausted. Repeat the process.

Follow-up: when adding a stock to the pool, the stock needs to wait a generation to be eligible for random generation. i.e. if "appl" is added to the pool, it needs to wait until one random function is called to be a valid return value

import random
class random_stock_generator():
    def __init__(self):
        self.start = 0
        self.stocklist = []
        self.blacklist = []
        
    def add(self, name):
        if name not in self.stocklist:
            self.stocklist.append(name)
        
    def remove(self, name):
        self.stocklist.remove(name)
        
    def random(self):
        n = len(self.stocklist)-1
        
        if self.start > n:
            self.stocklist.extend(self.blacklist)
            self.start = 0
            
        r = random.randint(self.start, n)
        out = self.stocklist[r]
        
        temp = self.stocklist[self.start]
        self.stocklist[self.start] = self.stocklist[r]
        self.stocklist[r] = temp
        
        self.start += 1
        
        return out
Comments (3)