Transmitting a random packet

A question a friend of a friend got at a Google interview: a router needs to receive $N$ data packets (represent them as strings), and needs to transmit one of the $N$ packets, uniformly at random (i.e., each packet should have an equal probability of being transmitted.

Extra condition: you cannot use more than five memory slots.

Let's solve this problem without the extra condition:

In [1]:
import random

def receive_packet(packet):
    global packets, N #Note that this is not strictly necessary
                      #The only situation where this *is* necessary
                      #is when we need to go
                      #N = <something new> or
                      #packets = <something new>
                      
                      
    packets.append(packet)
    
    if len(packets) == N:
        packets.append(packet)
        ind = int(random.random()*N) #a random integer between
                                     #0 and N-1
        return packets[ind]          #A random packet
    
    
    #else:
    #   return None 
    #The above is optional -- None is returned by default
    
if __name__ == '__main__':
    #Define global variables
    packets = []
    N = 6
    #Now, send 6 packets. After the 6th packet is sent in, we
    #expect receive_packet() to return a random packet from 
    #amonth the 6 packets
    receive_packet("aeee")
    receive_packet("abcd")
    receive_packet("abcd")
    receive_packet("aeee")
    receive_packet("abcd")
    print(receive_packet("abcd"))
aeee