How do I go about inserting a \"yield generator\" into this Python code? import
ID: 3590336 • Letter: H
Question
How do I go about inserting a "yield generator" into this Python code?
import csv
NaN=float('NaN')
def parseNums(x):
try:
return float(x)
except:
return NaN
def Numify_Columns(Row,Columns):
for column in Columns:
Row[column]=parseNums(Row[column])
count=0
total=0.0
COLUMNS=["HIGHDEG","INEXPFTE"]
FILE='MERGEDCONVERT.csv'
#Columns= # .... FILL in
data=open(FILE, 'rU')
#Create the reader
reader = csv.DictReader(data)
for Row in reader:
if Row["STABBR"] == "IL" and Row ["CITY"] == "Chicago":
Numify_Columns(Row,COLUMNS)
if Row["HIGHDEG"]>=2:
count=count+1
total=total+Row["INEXPFTE"]
Avg=total/count
print "The average is ", Avg
data.close()
Explanation / Answer
What is Yield generator?
In the above example
for column in Columns:
def gen(n):
for column in Columns(n):
print(column) //generates the value before yielding value is reached
yield column //generator generates the next function till it reaches the yield value
print (column) //the function runs for the last time after reaching the yielding value
value=gen(n)
next(gen) //gets the next value for the iteration
Row[column]=parseNums(Row[column])
It executes the above function through yield generator.
FILE='MERGEDCONVERT.csv'
File "<FILE='MERGEDCONVERT.csv'>",line 1, in <module>
next(value)
//stop iteration
Similarly,
for Row in reader:
if Row["STABBR"] == "IL" and Row ["CITY"] == "Chicago":
Numify_Columns(Row,COLUMNS)
def gen(n):
for Row in reader(n):
if (Row["STABBR"] == "IL" and Row ["CITY"] == "Chicago"):
print(Row)
yield row
print (Row)
value=gen()
next(gen)
if Row["HIGHDEG"]>=2:
count=count+1
def row(n):
While True:
if (row["HIGHDEG"]>=2):
yield count
count+=1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.