-1

I know this is a topic that there are already several threads for. I've reviewed them and understand what this error means, but for some reason cannot get it to work for my code.

I'm trying to code a simple Python function that takes a list of integers as input and outputs the integers in the list that are exactly twice the amount of the previous integer in the list. Here is the code I have so far:

    def doubles(lst):
         i = -1
         for num in lst:
            if num == num[i + 1] / 2:
               print(num)

Now I know the issue is that it is trying to print this integer as a string. I have tried editing the codes last line to say print(str(num)) and that does not work, nor does changing my if statement in line 4. Any assistance would be greatly appreciated!

Polyphase29
  • 475
  • 1
  • 4
  • 17

3 Answers3

2
if num == num[i + 1] / 2:

should be

if num == lst[i + 1] / 2:

Also, I recommend using enumerate to iterate over the list with indexes, but there are better ways of doing such a thing, as shown in galaxyan's answer

Community
  • 1
  • 1
Joseph Young
  • 2,758
  • 12
  • 23
1

you can zip original list and list begin from second element,then compare two elements

def doubles(lst):
   return [ i for i,j in zip(lst,lst[1:]) if j==i*2 ]

example:

lst = [1,2,3,5,66,2,4,5]
print doubles(lst)
[1, 2]
galaxyan
  • 5,944
  • 2
  • 19
  • 43
0

You're attempting to subscript an item in the list, not the list itself. Instead of iterating the items, you could iterate the list's indexes:

def doubles(lst):
     for i in range(0, len(lst) - 1):
        if lst[i] == lst[i + 1] / 2:
           print(lst[i])
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thanks for the quick help guys. I tried iterating through the indexes earlier and ran into a different error, "list index out of range". I just tried it again and am encountering the same problem. Any tips on resolving that error? – Polyphase29 Jul 30 '16 at 18:28
  • @Mark arg, off-by-one error :-( See my edited answer. – Mureinik Jul 30 '16 at 18:31