Форум сайта python.su
0
доброго дня всем!
Я тут задачку решал. Опыт не большой, кажется код получился не совсем. Может расскажите как бы вы его написали или упростили. Спасибо заранее.
задача :
likes // must be “no one likes this”
likes // must be “Peter likes this”
likes // must be “Jacob and Alex like this”
likes // must be “Max, John and Mark like this”
likes // must be “Alex, Jacob and 2 others like this”
мое решение:
def likes(n):
if len(n) == 0:
return “no one likes this”
elif len(n) == 1:
a = (n + “ ” + “likes this”)
return(a)
elif len(n) == 2:
b = (n + “ ” + “and” + “ ” + n + “ ” + “like this”)
return b
elif len(n) == 3:
c = (n + “,” + “ ” + n + “ ” + “and” + “ ” + n + “ ” + “like this”)
return c
elif len(n) >= 4:
d = (n + “,” + “ ” + n + “ ” + “and” + “ ” + str(len(n)) + “ ” + “others like this”)
return d
Офлайн
857
>>> def likes(lst): ... length = len(lst) ... if length == 0: ... return '{} likes this'.format('no one') ... elif length == 1: ... return '{} likes this'.format(lst[0]) ... elif length == 2: ... return '{} and {} like this'.format(*lst) ... elif length == 3: ... return '{}, {} and {} like this'.format(*lst) ... else: ... return '{}, {} and {} others like this'.format( ... lst[0], lst[1], len(lst) - 2) ... >>> likes([]) 'no one likes this' >>> likes(['Peter']) 'Peter likes this' >>> likes(['Jacob', 'Alex']) 'Jacob and Alex like this' >>> likes(['Max', 'John', 'Mark']) 'Max, John and Mark like this' >>> likes(['Alex', 'Jacob', 'Peter', 'Max']) 'Alex, Jacob and 2 others like this' >>>
Онлайн