Python - creating a list with 2 characteristics bug

Posted by user2733911 on Stack Overflow See other posts from Stack Overflow or by user2733911
Published on 2013-11-08T19:45:06Z Indexed on 2013/11/08 21:53 UTC
Read the original article Hit count: 132

Filed under:
|
|

The goal is to create a list of 99 elements. All elements must be 1s or 0s. The first element must be a 1. There must be 7 1s in total.

import random
import math
import time

# constants determined through testing                                                                                                       

generation_constant = 0.96

def generate_candidate():
    coin_vector = []
    coin_vector.append(1)
    for i in range(0, 99):
        random_value = random.random()
        if (random_value > generation_constant):
            coin_vector.append(1)
        else:
            coin_vector.append(0)
    return coin_vector

def validate_candidate(vector):
    vector_sum = sum(vector)
    sum_test = False
    if (vector_sum == 7):
        sum_test = True
    first_slot = vector[0]
    first_test = False
    if (first_slot == 1):
        first_test = True
    return (sum_test and first_test)

vector1 = generate_candidate()
while (validate_candidate(vector1) == False):
    vector1 = generate_candidate()
print vector1, sum(vector1), validate_candidate(vector1)

Most of the time, the output is correct, saying something like

[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] 7 True

but sometimes, the output is:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 False

What exactly am I doing wrong?

© Stack Overflow or respective owner

Related posts about python

Related posts about list