0

Still being new to Python, I had to create a function that checks for doubles and if doubles are found it should return 'has duplicates'. So I have already finished the code correctly, but I'm more confused about why it originally found "bookkeeper" to have no duplicates with the code below.


def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

def has_duplicates(string):
    x = histogram(string)
    for b, c in x.items():
        if c > 1:
            return True
        else:
            return False

for string in test_dups:
    if has_duplicates(string):
        print(string, "has duplicates")
    else:
        print(string, "has no duplicates")

Output:

zzz has duplicates
dog has no duplicates
bookkeeper has no duplicates
subdermatoglyphic has no duplicates
subdermatoglyphics has duplicates

This is what I changed to make it work. But I would really like to understand why 'bookkeeper' didn't test correctly.

def has_duplicates(string):
    x = histogram(string)
    for b, c in x.items():
        if c > 1:
            return True
    else:
        return False
Torxed
  • 22,866
  • 14
  • 82
  • 131

1 Answers1

0

Your has_duplicates function returns too soon. Take a look at this for-loop:

for b, c in x.items():
        if c > 1:
            return True
        else:
            return False

Assuming that x is not empty, this for-loop will only have one iteration. This is so, because you only ask the question c > 1 once, and then immediately return either True or False, terminating the for-loop and the function prematurely. Basically, this has the effect of only checking for doubles for the first key-value pair in the dictionary x.

You want to give the for-loop a chance to ask the same question for all key-value pairs. Of course, once you find one key-value pair which has a value greater than one, you have an "early-out", and don't need to look at the rest of the key-value pairs.

Paul M.
  • 10,481
  • 2
  • 9
  • 15