# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
[color=red]temp=0
for string in words:
if len(string)>=2 and string[0]==string[len(string)-1]:
temp+=1[/color]
return temp
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
[color=red]xstrings=[]
sstrings=[]
for word in words:
if word.startswith('x'):
xstrings.append(word)
else:
sstrings.append(word)
xstrings.sort()
sstrings.sort()
[sstrings.insert(x,xstrings[x]) for x in range(0,len(xstrings))][/color]
return sstrings
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
return [color=red]sorted(tuples,key=get_last)[/color]
[color=red]def get_last(tu):
return tu[-1][/color]
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
[color=red]temp=0
for string in words:
if len(string)>=2 and string[0]==string[len(string)-1]:
temp+=1[/color]
return temp
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
[color=red]xstrings=[]
sstrings=[]
for word in words:
if word.startswith('x'):
xstrings.append(word)
else:
sstrings.append(word)
xstrings.sort()
sstrings.sort()
[sstrings.insert(x,xstrings[x]) for x in range(0,len(xstrings))][/color]
return sstrings
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
return [color=red]sorted(tuples,key=get_last)[/color]
[color=red]def get_last(tu):
return tu[-1][/color]