Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Solution: Count unique characters

  • set
import sys

if len(sys.argv) != 2:
    exit("Need a string to count")

text = sys.argv[1]

unique = ''
for cr in text:
    if cr not in unique:
        unique += cr

print(len(unique))

The above solution works, but there is a better solution using sets that we have not learned yet. Nevertheless, let me show you that solution:

import sys

if len(sys.argv) != 2:
    exit("Need a string to count")

text = sys.argv[1]

set_of_chars = set(text)

print(len(set_of_chars))