Home > Software engineering >  Using import sys and sys.argv, count the number of unique vowels in a string arguments from the comm
Using import sys and sys.argv, count the number of unique vowels in a string arguments from the comm

Time:03-20

I have the following task:

Import the sys module to use sys.argv. Create a function with a string parameter that will print the number of unique vowels in the string regardless of whether it has uppercase, lowercase, numbers, spaces or unique characters.

For example:

Test 1: python3 countVowels.py Batman 
Test 2: python3 countVowels.py 'The Dark Knight'
Test 3: python3 countVowels.py 'oaIeuOnI t_#pA'

Use sys.argv for the arguments; do not manually insert the arguments to find the number of unique vowels.

For example, do not do this:

print(count_vowels("G0tham City 3ni$peo")) 

I have the following code, some of which has been derived from this answer:

import sys

def count_vowels(text):
    letter = set(text.lower())

    count = 0
    for vowel in 'aeiou':
        if vowel in letters:
            count  = 1
    return count 

print(count_vowels(sys.argv[1:]))

Error Message:

Traceback (most recent call last):
  File "countVowels.py", line 12, in <module>
    print(count_vowels(sys.argv[1:]))
  File "countVowels.py", line 4, in count_vowels
    letter = set(text.lower())
AttributeError: 'list' object has no attribute 'lower'

CodePudding user response:

First issue: You are iterating through a list

print(count_vowels(sys.argv[1:])) # "1:" returns a list, not index 1

This should just be ```python print(count_vowels(sys.argv[1]))

Second issue: you are iterating through the wrong thing

import sys

def count_vowels(text):
    letter = set(text.lower())

    count = 0
    for vowel in 'aeiou': #you should iterate through letter not "aeiou"
        if vowel in letters: #
            count  = 1
    return count 

try this instead:

import sys

def count_vowels(text):
    word = set(text.lower()) #rename for easier identification

    count = 0
    for letter in word: #iterate through word
        if letter in "aeiou": #if "letter" is a vowel, increment
            count  = 1
    return count 

print(count_vowels(sys.argv[1]))

That should work.

Also, to explain set(). This function returns a set with each unique value in it. For example:

set([1,1,2,3,2,3,2,3])

would return:

{1,2,3}

set() does the same for characters. Example:

set("aaabccc")

returns:

{"a","b","c"}

Using set means your function only deals with non re-occuring characters, so you don't have to keep track of whether you have already counted a vowel. Else, for example, you would have to keep track of every "a" that comes through otherwise you would count it more than once.

  • Related