0

I managed to find this code online which showed me how to find and print a repeated character in a string. I'm confused as to how it's working though. I don't understand what the h[i] = 0 part is technically doing. Can someone please explain?

a = 'abcdeab'

h = {}

for i in a:
    if i in h:
        print(i)
    else:
        h[i] = 0

I understand how it's iterating over the string, but I don't understand how it's being added to the dictionary in order to be checked if it already exists in that dictionary or not. Setting h[i] = 0 is what's throwing me off. I don't understand why it's being set to 0.

I'm adding this after the problem was answered: I ended up creating a different solution and thought I would post it in case anyone else was looking into the same problem. It is as follows (using a list instead of a dictionary):

a = 'abcdeab'

h = []
for i in a:
    if i in h:
        print(i)
    else:
        h.append(i)

Also, if you're looking for ONLY the first occurrence of a repeated character, you would add break after print(i). In this case, it would only print a instead of both a and b.

Ben Hutton
  • 77
  • 5

1 Answers1

0

The variable h has been defined to be a dictionary. For each letter in your input string, if it be present in the map, it gets printed, otherwise the map gets assigned a (key, value) pair of (letter, 0). That is, an entry is made into the map with the letter as the key, and zero as the (arbitrary) value. Here is your loop with some comments:

for i in a:
    if i in h:       # if the key 'i' exists in the dictionary
        print(i)
    else:
        h[i] = 0     # otherwise add an entry for this letter
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360