Ronnie
Ronnie

Reputation: 157

Help me fix a program

Hello I have gotten a program that gives an output of a random series of 0s and 1s of length n. However, there is a slight problem in my program because I get syntax error. I am using Sage. What should I fix?

from random import randint
def randString01(num):
    x = str() 
    count = num 
    while count >0: 
        if randint(0,1) == 0: 
            append.x(0)   
        else: 
            append.x(1) 
        count -= 1
    x=str(x) 
    return x

Upvotes: 0

Views: 185

Answers (3)

I82Much
I82Much

Reputation: 27326

as others noted, you shouldn't use 'append'

from random import randint
def randString01(num):
    x = str() 
    count = num 
    while count >0: 
        if randint(0,1) == 0: 
            x += "0"   
        else: 
            x += "1" 
        count -= 1
    x=str(x) 
    return x

Second, this is not pythonic at all. You should look into list comprehensions.

def randString01(num):
    return ''.join([str(randint(0,1)) for x in range(num)])

Sample usage:

>>> randString01(5)
'01101'
>>> randString01(100)
'0110101001101001000110101100101100100100110001011111111101101010010011110000000
101010011001000000000'

To break this into simpler pieces, I'll illustrate each piece.

str.join

str.join(iterable)¶ Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

>>> ",".join(["Beans","Eggs","Bacon"])
'Beans,Eggs,Bacon'

I use this command with the empty string to paste together all my numerical values

range

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(100)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 4
2, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 6
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 8
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

I use range to make sure my inner loop repeats the correct number of times

list comprehension

>>> [x for x in [1,2,3]]
[1, 2, 3]
>>> [2*x for x in [1,2,3]]
[2, 4, 6]
>>> [str(x) for x in [1,2,3]]
['1', '2', '3']
>>> [str(5) for x in range(5)]
['5', '5', '5', '5', '5']
>>> [str(randint(0,1)) for x in range(5)]
['1', '0', '0', '1', '1']

Note that I call str(randint(0,1)) to ensure that the values in my list are string elements, rather than integers. If you try to call str.join(a list of numbers), you'll get an error:

>>> ''.join[1,2,3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is unsubscriptable

So tying it together, the piece in brackets creates a list of string elements, either ones or zeros. The ''.join(list) concatenates each digit to the next, forming a single string.

EDIT:

Thanks to TokenMacGuy in the comments who points out that the list creation is unnecessary. It is sufficient to define randString01 as

def randString01(num):
    return ''.join(str(randint(0,1)) for x in range(num))

This is because the generator object returned by the argument to join is iterable, and all the str.join method needs to work is an iterable object. It is better to use the generator than the list because it allows lazy evaluation, which isn't a big deal in this case, but it could be if the list were exceptionally large. See the PEP 289 page for more on generators.

This is some pretty advanced stuff, but please don't be scared off of python by this example. See how beautiful the code can be (a single line as opposed to ~10), when you can use very high level abstractions rather than low level control structures.

Upvotes: 5

jgritty
jgritty

Reputation: 11925

I think you want something more like this:

def randString01(length):
    my_string = ""
    for count in range(length):
        my_string += str(randint(0,1))
    return my_string

Upvotes: 0

Manux
Manux

Reputation: 3713

You are trying to use the append method of a list, on a string.

First, strings have no append method.

Second, you would need to write x.append("0").*

And last (since strings have no append method), what you want to write is x+="0", or x = x+"0".

Also, you don't need that final x=str(x) since x is already a string.

*In python, to call the method of an object, the syntax is object.methodname(args),

Upvotes: 1

Related Questions