My code has a mathematical function that iterates over a list of county class objects and returns the county with the max voter turnout along with that turnout in a tuple.
class County : def __init__(self, init_name, init_population, init_voters): self.name = init_name self.population = init_population self.voters = init_voters def highest_turnout(data) : max_turnout_county = data max_turnout = (data.voters / data.population) for i in range(0,6): if (data[i].voters / data[i].population) > max_turnout: max_turnout_county = data[i].name max_turnout = (data[i].voters / data[i].population) return (max_turnout_county, max_turnout) allegheny = County("allegheny", 1000490, 645469) philadelphia = County("philadelphia", 1134081, 539069) montgomery = County("montgomery", 568952, 399591) lancaster = County("lancaster", 345367, 230278) delaware = County("delaware", 414031, 284538) chester = County("chester", 319919, 230823) bucks = County("bucks", 444149, 319816) data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks] result = highest_turnout(data) print(result) # prints the output of the function
In its current state, it will return the desired output.
However, if I change the county with the highest output, for example, if I change Allegheny voters from 645469 to 1000480 so that Allegheny is now the max turnout county the output will no longer return the county name in the tuple as expected, but rather the memory location.
(<submission.County object at 0x7f8e37d3cc18>, 0.9999900048976001)
Why is my code outputting memory location in the second case but not the first case and how would I fix this?
There is bug in your code.
In first line, you are assigning whole County object to the
max_turnout_county = data
later, you are assigning only the attribute name:
max_turnout_county = data[i].name
To fix, you can just change first line to:
max_turnout_county = data.name
Answered By – Blomex
Answer Checked By – Robin (BugsFixing Admin)