Exercise 94 *

Write a Python algorithm which extract from a string text the list of words whose first character is identical to the last. Example if s = "radar number 212", the algorithm returns the list ['radar', '212']

Solution

# function which tests if the first character is identical to the last
def first_end (s):
if s [0] == s [-1]:
return True
else:
return False

# Function which determines the list of words whose first character is identical to the last
def list_first_end (s):
# convert the string s to a list:
L = s.split()
# initialization of the searched list
l_first_end = []

for word in L:
if first_end (word):
l_first_end.append (word)
return l_first_end

# Example
s = "radar number 212"
print ("The searched list is:", list_first_end (s))
# The output is: The searched list is: ['radar', '212']
Younes Derfoufi
my-courses.net

Leave a Reply