educative.io

Could someone find the issue with my code?

I’m using below code but it only works in some case but not others (e.g. is_unique(heythere)).
what’s the issue with it?
how should it be revised to work? thanks in advance.
def is_unique(input_str):

d = dict()

for i in input_str:

if i in dict():

  d[i]+=1

else:

  d[i]=1

return all(value == 1 for value in d.values())


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hello @jessie_Zhao
Thanks for reaching out to us. In python dict() function is a constructor which creates a dictionary. In “if” condition you have written “if i in dict()” => to check whether a letter is already present in dictionary or not (but here dictionary is created in every iteration as you have used dict() function instead of dictionary name “d” ). It will always get false and will go to else condition. So try changing it to " if i in d:" instead of “if i in dict()”. Try the following code.

  def is_unique(input_str):
    d = dict()
    for i in input_str:
        if i in d:
          d[i]+=1
        else:
          d[i]=1
    return all(value == 1 for value in d.values())

print(is_unique("heythere"))

Thanks

Hi Javeria, thank you for the super clear explanation!

1 Like