Fill In Program
Solution 1:
Since this is homework, I won't give you the answer, but here are some leading questions:
- How would you use
randint(a,b)
to give you either 0 or 1? - How do you convert an integer to a string?
- How can you build up a string with a for loop?
If you can answer those, you've solved the problem.
Solution 2:
Inside the for-loop.
Solution 3:
Since it's clearly classwork, here's some pseudo-code to start with:
define randString01(num):
set str to ""
count = num
while count is greater than zero:
if randint(0,1) is zero:
append "0" to str
else:
append "1" to str
subtract one from count
return str
Your string of n
occurences of the character n
will not help here by the way. It will either give you a zero-sized "0" string or a one-sized "1" string. In other words, all ones.
Okay, what you have in your comment seems okay (at least in structure):
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
but I'm just a little uncertain about your str()
and append()
lines. Since you've done the bulk of the work, here are my minor changes to get this going under Python:
from random import randint
def randString01(num):
x = ""
count = num
while count > 0:
if randint(0,1) == 0:
x = x + "0"
else:
x = x + "1"
count -= 1
return x
print randString01(7) ## And add these to call the function.
print randString01(7)
print randString01(9)
print randString01(9)
This outputs:
1011000
1010011
110001000
110101001
Solution 4:
if you don't have to use the exact syntax above, this can be accomplished with 1 line of code.
concepts:
string.join takes an iterable you can create an iterable of random string by inlining the for loop in to a list comprehension
the resulting code is as follows.
''.join([str(random.randint(0,1)) for i in range(n)])
Post a Comment for "Fill In Program"