I am making a function which will make a list which includes a histogram of a requested list and requested values to use as the values of the histogram. Values above the requested value are included last.
The program is working with a list that is sorted in ascending order numerically, but when a list that is not sorted is used as input, the program seems to discard random values and not evaluate in the same way.
the code:
def histogram(sample, binBoundaries):
c=0
if not binBoundaries:
li = [len(sample)]
return print(li)
for x in sample:
if x > binBoundaries[-1]: #if the value is greater than last bin
c = c+1 #number of values greater increases
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in sample: #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
for i in dic:
listofvalues.append(dic[i])
listofvalues.append(c)
print(listofvalues)
histogram([5, 4, 2, 3], [3])
this will result in an output of [1, 2], where the real output should be [2,2]
Is there something I’m just not seeing that is making the number not be calculated? Let me know where I have gone wrong if you could!
Your problem is that you are removing items from the list
samplewhile you are iterating over it, this is a bad idea because it will result in skipping some elements.Try taking out the line
sample.remove(x), you should get the expected result. If you really do need to remove elements from the input list you should refactor to make sure you still check every element in the list. One option is to iterate over the list in reverse usingfor x in reversed(sample).It also looks like you may be removing elements in the wrong place,
sample.remove(x)looks like it should be inside of theifdirectly above it. Try the following code: