-2
import sys
a = int(sys.argv[1])
def count_holes(n):
    dic = {'1':0, '2':0, '3':0, '4':1, '5':0, '6':1, '7':0, '8':2, '9':1}
    l = str(n)
    counter = 0
    i = 1

    for i in l:
        while i != len(l):
            counter = counter + dic[l[i]]
    print(counter)
count_holes(a)

i got this: counter = counter + dic[l[i]] TypeError: string indices must be integers

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

2

You're making this too complicated. You're getting that TypeError because you are trying to use the characters of l to index l. But you don't need to index into l, just directly iterate over the chars in the number string.

Here's a repaired version of your code.

import sys

def count_holes(n):
    dic = {'1':0, '2':0, '3':0, '4':1, '5':0, '6':1, '7':0, '8':2, '9':1}
    counter = 0
    for c in str(n):
        counter += dic[c]
    return counter

a = int(sys.argv[1])
print(count_holes(a))

Here's some test code:

for i in (12357, 4, 66, 8, 999):
    print(i, count_holes(i))

and its output

12357 0
4 1
66 2
8 2
999 3
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • Good answer. And now you can see that the whole function body could be rewritten as: `return sum({'0':0, '4':1, '6':1, '8':2, '9':1}.get(c, 0) for c in str(n))`. – Matthias Aug 03 '17 at 12:46
  • @Matthias Sure (although your dict should have '0':1), but I get the feeling this is homework, and that the OP is supposed to be practicing loops, so I didn't want to condense the code _too_ much. – PM 2Ring Aug 03 '17 at 13:08
  • That's why I said "Good answer". Your answer is the perfect explanation how the code should be if we want to keep the OPs structure. I just couldn't resist to add my solution (and adding the handling of the number zero btw). – Matthias Aug 03 '17 at 13:24
  • @Matthias Fair enough. And thanks! – PM 2Ring Aug 03 '17 at 13:32
0

When you say i in l, i cycles through characters in the string l. So i is a string and can't be used as an index. You could enumerate() the string and use a second variable in the loop as your index.

If n somehow contains len(n) in it I could see how the while loop might exit but I'm not sure if that's what you are going for. Although i and len(l) are different types, so you have that going for you... Which is nice.

4mAstro
  • 43
  • 1
  • 1
  • 7