python - Thinking Recursively when it comes to list manipulation -
from random import * def number(n): if n>0: return [ choice( [0,1] ) in range(n)] else: return ("only positive #'s!")
how recursively?
let's n=5
, [0,1,2,3,4]
each # replaced either 0
or 1
. can't seem wrap head around doing list manipulation recursively.
here's 1 option:
from random import choice # don't use * imports def number_recursive(n): if n < 0: raise valueerror('n must positive') if n == 0: return [] return [choice((0, 1))] + number_recursive(n-1)
note raising of error rather returning string; tells caller more directly went wrong.
Comments
Post a Comment