Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This is my first solution to writing a class for counting vowels in a string
- # A second solution follows this one, and is perhaps neater / more efficient
- # Please bear in mind that this is the first time I have ever attempted to write class methods LOL
- class UserMainCode(object):
- @classmethod
- def countvowels(cls, vowels, in1):
- # write code after this line only
- count = 0
- for char in in1:
- if char in vowels:
- count += 1
- return count
- def __init__(self):
- pass # no parameters are passed when initialising the method, so we only need "pass" here
- obj = UserMainCode() # Create an instance of the class, passing no parameters
- allvowels = 'aeiou'
- input1 = 'fggsartuioio'
- # Call the vowel counting method, passing it the vowel string, and the string to be analysed
- vowel_count = obj.countvowels(allvowels, input1)
- print(vowel_count)
- #------------------------------------------------
- # Here is my second and possibly better solution
- class UserMainCode(object):
- @classmethod
- def countvowels(cls, in1):
- # write code after this line only
- count = 0
- for char in in1:
- if char in cls.vowels: # the class already knows what vowels are
- count += 1
- return count
- @classmethod # here we define a second class method
- def __init__(cls, vowels): # the object instantiation defines the set of vowels
- cls.vowels = vowels # create a class attribute that defines what vowels are
- allvowels = 'aeiou'
- myobject = UserMainCode(allvowels) # Make an instance of the class, telling it the vowels
- input1 = 'fggsartuioio'
- vowel_count = myobject.countvowels(input1) # Call the class counting method, passing just the string to analyse
- # We only need to pass the string to be counted
- # as the class already knows what vowels are
- print(vowel_count)
- # output
- # 6
Add Comment
Please, Sign In to add comment