On 31/10/06, Jorge Azedo <[EMAIL PROTECTED]> wrote: > def randomList(n1,n2,len): > '''n1-n2 range of numbers, len - length of the final list > > Returns a list''' > > i=0 > rndlist=[] > if len > n2: > return 'The length of the list must be greater than n2'
Comment --- think about raising an exception here, instead of returning an error message string. > Not sure if the indentation in this message is correct, but the module > works, so that's not the problem. What I really want to ask is: Any > suggestions on how to improve the documentation part of the module? I'd > like to warn the user about the fact that len must be greater than n2 > before he runs it, but I can't think of a short enough way to say it so > that it still appears in that little window that shows up when you > start writing the arguments to a function. > Sorry if this is confusing Not sure what you mean about the "little window" -- is that an IDLE thing? (I don't use IDLE, sorry) Another comment -- I would avoid using 'len' as the name of an argument, since 'len' is also the builtin length function. It's not an error to reuse the name, but most python programmers would expect len to be the builtin when reading code. For example, instead of n1,n2,len, I would probably do something like: def randomList(lo, hi, n) Comment three -- as Luke points out, you probably need another constraint to avoid looping endlessly. Perhaps 'hi-lo <= (n+1)'. Fourth comment -- you could enforce your range constraints by using assert. ie: def randomList(lo, hi, n): assert lo <= hi assert 0 <= n <= hi assert hi-lo <= n+1 What about this: def randomList(lo, hi, n): """Return n distinct random integers taken from range(lo, hi+1), where n <= hi. lo, hi, n :: int output :: [int] Constraints: lo <= hi 0 <= n <= hi hi-lo <= n+1 >>> sorted(randomList(1, 9, 9)) == range(1, 10) >>> randomList(1, 10, 0) == [] >>> randomList(4, 3, 2) AssertionError >>> randomList(7, 8, 5) AssertionError >>> randomList(-5, 7, 9) AssertionError """ (those things at the end are doctests. Read about them in the doctest module. Also, I haven't tested these doctests :-) ) (incidentally, apart from your condition on n <= hi, your function is equivalent to: def randomList(lo, hi, n): return random.sample(range(lo, hi+1), n) ) -- John. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor