jython - Finding length of list without using the 'len' function in python -
in high school assignment part of make function find average number in list of floating points. can't use len , such sum(numlist)/float(len(numlist))
isn't option me. i've spent hour researching , racking brain way find list length without using len
function, , i've got nothing hoping either shown how or pointed in right direction. me stack overflow, hope. :)
use loop add values list, , count them @ same time:
def average(numlist): total = 0 count = 0 num in numlist: total += num count += 1 return total / count
if might passed empty list, might want check first , either return predetermined value (e.g. 0
), or raise more helpful exception zerodivisionerror
you'll if don't checking.
if you're using python 2 , list might integers, should either put from __future__ import division
@ top of file, or convert 1 of total
or count
float
before doing division (initializing 1 of them 0.0
work).
Comments
Post a Comment