Exercise 96 *

Write an algorithm in Python as a function which takes a text string as parameter and which returns the list of words containing at least two uppercase letters. Example if

 s = 'The PySide GUI library is more popular than PyQt'

, the function returns the list:

['GUI', 'PySide', 'PyQt']

Solution

# create a function that returns the number of uppercase letters in a string
def numberMaj (s):
# define and initialize a variable which counts the number of capitals letters
counter = 0

# browsing through all characters of the string s
for x in s:
# increment the counter each time the character encountered is in uppercase
if x.isupper():
counter = counter + 1
return counter

# Function which returns the list of words which contain at least 2 capital letters
def wordsTwoUppercase (s):
# initialization of the list of words that contains at least 2 capital letters
listTwoShift = []

# convert string s to a list
L = s.split ()

# browsing through all words in list L
for word in L:
# test if the 'word' element contains a capital letter or not
if numberMaj(word) >= 2:
listTwoShift.append (word)
return listTwoShift

# Example
s = 'PySide GUI library is more popular than PyQt'
print ("The list of words with at least 2 capitals is:", wordsTwoUppercase(s))
# The output is:
# The list of words with at least 2 capitals is: ['PySide', 'GUI', 'PyQt']
Younes Derfoufi
my-courses.net

Leave a Reply