Home > other >  (Python) Can someone help me with what I have wrong in my code?
(Python) Can someone help me with what I have wrong in my code?

Time:10-07

The objective is to return the multiple of three that occurs within a string. I only have to worry about the multiples 3,6,9 and use a dictionary. For example, 0939639 would return 9 since it appeared 3 times while the other multiple of three appeared less than that.

Here is my code:

def count_threes(n):
    # Turning the number into a string
    x = len(str(n))

    # Setting the keys(multiple of threes) to 0 as the default count
    dict = {3: 0,
            6: 0,
            9: 0}

    # Loop through the string. If the number is a multiple of 3, it increments the key's value.
    for el in n:
        num = int(el)
        if num % 3 == 0 and num != 0:
            dict[el]  = 1

    # Gets the maximum value and returns the key
    max_val = max(dict, key=dict.get)
    return max_val

I do have a given test file to test the function on. I keep getting a KeyError so it's having a hard time pulling the key. I can't seem to figure out where in my code is wrong.

CodePudding user response:

Your dict contains int as key, and el is a string, so you can't find it in the dict, use num to access the dict


Also, don't name it dict that is the dictionary constructor keyword, and you can use a defaultdict that saves you to write initial values

from collections import defaultdict

def count_threes(value):
    counter = defaultdict(int)
    for char in value:
        num = int(char)
        if num and num % 3 == 0:
            counter[num]  = 1

    return max(counter, key=counter.get)

print(count_threes('09396390000'))  # 9

CodePudding user response:

You just need to change:

    dict[el]  = 1

to:

    dict[num]  = 1

The dict keys are integers, not strings, so you need to use the integer value, num, as the key.

CodePudding user response:

There were the following issues in the code:

  • you should refrain from keeping dictionary names as the actual datatype (you kept it as dict)
  • you took the len of the number which wasn't required, we just had to convert it to a string
  • you were looping through n and not x, and we can't loop through an integer using "in" keyword
  • the key you were using was the string of "el", i.e which was looping through x, you had to keep the key as num
def count_threes(n):
    # Turning the number into a string
    x = str(n)

    # Setting the keys(multiple of threes) to 0 as the default count
    _dict = {3: 0,
            6: 0,
            9: 0}

    # Loop through the string. If the number is a multiple of 3, it increments the key's value.
    for el in x:
        num = int(el)
        if num % 3 == 0 and num != 0:
            _dict[num]  = 1

    # Gets the maximum value and returns the key
    max_val = max(_dict, key=_dict.get)
    return max_val
  • Related