Exercise 91 **

Write an algorithm in python as a function that transforms a string text T into a list where words containing numbers are placed at the end of the list. Example if T = "Python_1 created in 1991. Currently it is in version Python_3.9"the algorithm returns the list: ['created', 'in', 'Currently', 'it', 'is', 'in', 'version', 'Python_1', '1991.', 'Python_3.9' ]

Solution

# function which tests if a given word contains a number or not
def digit_in_word (word):
# initialization of a counter
counter = 0
for x in word:
if x.isdigit():
counter = counter + 1

if counter > 0:
return True
else:
return False

# function which transforms a string into a list by moving all words containing numbers at the end
def moveDigit (T):
# transformation of the text string T into a list
L = T.split ()

# initialization of the list of words which do not contain any digits
L_without_digit = []

# initialization of the list of words which contain at least one digit
L_with_digit = []

# browse the elements of list L and find words that contain numbers
for word in L:
if digit_in_word (word):
L_with_digit.append (word)
else:
L_without_digit.append (word)

result = L_without_digit + L_with_digit

return result

# Example
T = "Python_1 created in 1991. Currently it is in version Python_3.9"
print (moveDigit (T))
# the output is:
# ['created', 'in', 'Currently', 'it', 'is', 'in', 'version', 'Python_1', '1991.', 'Python_3.9']
Younes Derfoufi
my-courses.net

Leave a Reply