Error in getting the running median
<p>I am trying to get a running median for a number of integers. For example: 6 elements will come one by one, let say 12,4,5,3,8,7  for which running median at each input is 12,8,5,4.5,6,5 respectively. I wrote a python code but it seems to give incorrect answer. Help is appreciated .</p>

<pre><code>n = int(raw_input().strip())
s=[]
for i in xrange(n):
    a=int(raw_input())
    if len(s)==0: 
        s.append(a)
        print "%.1f" % a
    else:
        for j in xrange(len(s)):
            if a&lt;s[j]:
                s.insert(j,a)
        if a&gt;=s[-1]:
            s.append(a)
        if len(s)%2==0:
            print "%.1f" % float((s[len(s)/2] + s[len(s)/2 -1])/2.0)
        else:
            print  "%.1f" % s[len(s)/2]
</code></pre>

<pre><code>n = int(raw_input().strip())
s=[]
for i in xrange(n):
    a=int(raw_input())
    if len(s)==0: 
        s.append(a)
        print "%.1f" % a
    else:
        for j in xrange(len(s)):
            if a&lt;s[j]:
                s.insert(j,a)
                break # inserted this break
        if a&gt;=s[-1]:
            s.append(a)
        if len(s)%2==0:
            print "%.1f" % float((s[len(s)/2] + s[len(s)/2 -1])/2.0)
        else:
            print  "%.1f" % s[len(s)/2]
</code></pre>

<p>This was the output and input:</p>

<pre><code> 6
 12
12.0
 4
8.0
 5
5.0
 3
4.5
 8
5.0
 7
6.0
</code></pre>

<p>The issue was in your <code>for j in xrange(len(s))</code> you were inserting as long as a was less then the next value. You didn't just insert once, that added more values than you wanted into the list. Adding a <code>break</code> will only insert once, at the time it finds the first spot it belongs too. </p>

python python-2.7