[PLUG] Beginning Python Question #7
Holger Stephan
holger001 at frogleg.net
Wed Jul 13 16:44:24 UTC 2005
Rich Shepard wrote:
> I found a function that accepts input of a list of items (s) and an
> integer
> (k), and produces another list of all combinations of s things taken k at a
> time. The initial code is this:
>
> def klistcombs(s, k):
> """Returns list of combinations of S taken K at a time.
>
> S must be a list.
> K must be >= 0.
> If K > len(S), an empty list is returned.
> Else if K is 0, a singleton list containing an empty list
> is returned.
> The k-combinations are returned in lexicographic order
> of their indices.
> """
> output = open('components.out', 'w')
> input = open('components.in', 'r')
> s = input.read()
>
> I added the file statements because I want to use a text file on disk as
> the source of the input list. However, it's not working.
>
> When I run interactively, I get an illegal syntax error at the final 'n'
> when I specify:
>
>>>> klistcombs(components.in, 2)
>
> File "<stdin>", line 1
> klistcombs(components.in, 2)
> ^
> SyntaxError: invalid syntax
>
> If I change the name of the file so there is no extension, the error
> changes to:
>
>>>> klistcombs(components, 2)
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> NameError: name 'components' is not defined
>
> Since I cannot get past invoking the function, I assume the error is
> in the
> way the function is defined. How can I define klistcombs() so that it will
> look for the input list externally, on the hard drive?
>
> Thanks,
>
> Rich
>
Rich: I haven't followed all this (and probably shouldn't respond) but
parameter 's' is supposed to be a string, right? Then call it with
klistcombs("components.in", 2). Are you just missing the quotes?
BTW, it wouldn't be hard to read the file in line by line and do a
string.split on it to get the two lists.
Holger
More information about the PLUG
mailing list