views:

231

answers:

3

Do not code like this. Please, read the hints by the accepted answer. I tried to remove the junk but I coundn't.

Code

import sys

a = []
i=0

for line in sys.stdin:
        try:
                n = float(line)
                a.append(n)
                i+=1
        except ValueError:
                print 'Number please!';
                continue
        if n < 0:
                if i % 2 == 1:
                        a.pop(-1)
                break

ratios = []    
ratios.append( a.pop(-1) / a.pop(-2) )

print a[-1]
+3  A: 

list.pop() removes the item from the list, and it defaults to the last item.

last = a.pop()
secondlast = a.pop()
ratios.append(last / secondlast)
Ignacio Vazquez-Abrams
It should still work with long lists. This change does not fix the problem. It has apparently something to with sanitizing.
HH
A: 
  1. You can't use sys.stdin if you expect people to type in stuff. It's buffered. Use raw_input instead.

  2. Don't append the input before you have validated that it should be appended. It's daft, because they you need to remove it again. That makes no sense.

  3. You never use i, so get rid of that.

  4. 'I calculate the ratio "list.pop(-1) / list.pop(-2)"' Aha. And what is it you are trying to do? Calculate the ratio between each pair if inputs? In that case you need a while loop in the end too. And get rid of the '-1' and '-2' in the pop() calls.

Other than that it seems to work, barring that you don't really explain what the problem is.

Lennart Regebro
A: 

From the description, you don't need to remember the whole list, you just need the previous two items. Also, you need to decide what to do if the current input is -1 and one of the previous is not valid. So you'll also want some kind of flag to mark whether you'll actually return if the current input is -1, or only add valid items to what you're keeping, depending on the goal.

While you're deciding that, first build a function that uses raw_input and echoes what you input, and also filters for valid items.

telliott99