Perform x simulations and collect the data in a CSV file

0

I would like to know how to perform 1000 simulations of the following code and collect all the output data in a CSV file containing two columns (l1, l2) and eight rows (ABCDEFGH) with the respective frequency of appearance of the letters a length of the 1000 simulations.

import random
l1= random.choice("ABCDEFGH")
l2= random.choice("ABCDEFGH")

The eight rows should represent the times that l1 and l2 have turned out to be each letter throughout the 1000 simulations. That is, a table that collects the sequence of occurrence of each letter in l1 and l2, throughout the 1000 simulations. For that we need to collect the data in two columns (l1, l2) and eight rows (ABCDEFGH).

    
asked by pyring 03.01.2017 в 12:02
source

1 answer

1

Here what you have to do is repeat the operation 1000 times. For this, use range() .

As for collecting data, a dictionary seems like a good solution. How about defaultdict to not have to initialize it?

from collections import defaultdict

l1=defaultdict(int)
l2=defaultdict(int)

for i in range(1000):
    l1[random.choice("ABCDEFGH")]+=1
    l2[random.choice("ABCDEFGH")]+=1

Writing to a csv file should be trivial.

For example, it returns to me:

In [20]: l1
Out[20]: 
defaultdict(int,
            {'A': 120,
             'B': 121,
             'C': 125,
             'D': 137,
             'E': 138,
             'F': 126,
             'G': 110,
             'H': 123})

In [21]: l2
Out[21]: 
defaultdict(int,
            {'A': 144,
             'B': 121,
             'C': 120,
             'D': 121,
             'E': 127,
             'F': 122,
             'G': 113,
             'H': 132})
    
answered by 03.01.2017 / 12:22
source