0

I have written some code which takes a sample of 100 numbers and randomly samples them to increase the list of numbers, then cuts them back down to 100 at random.

I am counting the number of iterations through the loop it takes for all the numbers in the list to be the same number.

output = open("results.txt", 'w')
for i in range(100):
    population = range(0, 100)

    TTF = 0

    while len(set(population)) != 1:
        scalingfactor = np.random.poisson(5, 100)
        sample = np.repeat(population, scalingfactor)
        decrease-to-ten = np.random.choice(sample, 100)
        population = decrease-to-ten
        results += 1    
    output.write(str(results))  

I am trying to output the numbers to a text file as a list, but I can't manage it.

output.write(str(results))  

This gives me all the numbers together as one long string of numbers.

output.write(TTF)   

gives me this error:

TypeError: expected a character buffer object

1 Answer 1

1

One way or another, you can only write character buffers to python File objects. And python won't include newlines by default when you write to a file, you have to include those yourselves.

I'll also recommend using a context manager for your File object.

See this code:

with open("results.txt", 'w') as output:
    for i in range(100):
        population = range(0, 100)

        # TTF = 0  # Nothing is done with this number. Why is it here?

        while len(set(population)) != 1:
            scalingfactor = np.random.poisson(5, 100)
            sample = np.repeat(population, scalingfactor)
            decrease-to-ten = np.random.choice(sample, 100)
            population = decrease-to-ten
            results += 1    
        output.write(f"{results}\n")  # Assuming you're using Python >= 3.6

If you're on an older version of Python that doesn't support f-string, replace f"{results}\n" with "{0}\n".format(results)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm using python 2.7 so thanks for the clarification

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.