I have a polynomial class:
class Polynomial:
def __init__(self, *termpairs):
self.termdict = dict(termpairs)
To add an instance to this class, you enter the following:
P = Polynomial((3,2), (4,5), (9,8))
Now I'm trying to create a function that reads information from a text file, and from that text file, it creates an instance of the Polynomial class. The information is stored in the text file like this:
4 6
2 3
9 8
3 5
0 42
So far, the function looks like this:
def read_file(polyfilename):
polyfilename = open("polyfilename.txt", "r")
poly1 = polyfilename.read()
polyfilename.close()
poly1 = [line.split() for line in poly1.split("\n")]
poly1 = [[int(y) for y in x] for x in poly1]
for item in poly1:
return Polynomial(item)
It only creates a Polynomial instance for the first pair in the text file, how can I make a Polynomial instance for all of the pairings in the text file?
EDIT: I now have this as my function:
def read_file(polyfilename):
polyfilename = open("polyfilename.txt", "r")
poly = polyfilename.read()
polyfilename.close()
poly = [line.split() for line in poly.split("\n")]
poly = [[int(y) for y in x] for x in poly]
return Polynomial(poly[0], poly[1], poly[2], poly[3], poly[4])
It gives me the answer I'm looking for, however, the length of these text files can vary, so typing poly[1], poly[2] won't work. Is there a way I can go through each index no matter what the length is?
All you need is
instead of
Docs here ... read the paragraph starting with """If the syntax *expression appears in the function call"""
Bonus: Your function doesn't use its arg, reuses the name
poly
like crazy, and isn't idiomatic, so I rewrote the whole thing:HTH
At a quick glance, it looks like this is returning after the first one is created, so you only get one back. Try replace the
return
statement with ayield
then:In case it helps the first response here is a good summary of yield. Again this is just from a quick look at what you've written.
Produces
return always exits the function immediately upon calling and can only return one item. So if you want multiple items (in a sense) to be returned, you must pack them in a list, then return that.
In place of the for loop:
You will of course have to deal with this new result as a list.