Найти - Пользователи
Полная версия: Написание функции
Начало » Python для новичков » Написание функции
1
solyarity
Здравствуйте, возможно, кто-то может помочь мне с написанием довольно сложной функции. У меня какая-то каша в голове, туго получается.

Write a function to_weird that accepts any number of strings, and returns the same strings with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the index 0 is even, therefore that character should be upper cased.
The passed in string will only consist of alphabetical characters and spaces(' ‘). Spaces will only be present if there are multiple words. Words will be separated by a single space(’ ').
Examples:
to_weird (“String”) -> returns “StRiNg”
to_weird (“Weird string case”) -> returns “WeIrD StRiNg CaSe”
Rodegast
Ты думаешь тут все такие умные что английский знают?
Romissevd
И где наработки, того что туго получается?
old_monty
solyarity
Вот, сделал очень наскоро (без применения map, lambda и т.д).
 def to_weird(strings):
    result = ''
    words = strings.split()
    new_words = []
    for word in words:
       new_word = ''
       for n,c in enumerate(word):
          if n%2 == 0:
             new_c = c.upper() 
          else: 
             new_c = c.lower()
          new_word += new_c
       new_words.append(new_word)
       result = ' '.join(new_words) 
    return result
    
print(to_weird("Weird string case"))
solyarity
Спасибо огромное
py.user.next
old_monty
Вот, сделал очень наскоро
Пробелы теряет она
 "  abc  def  "
 "AbC DeF"

  
>>> import re
>>> 
>>> def tr(s):
...     lst = []
...     is_even = True
...     for c in s:
...         lst.append((is_even and c.upper()) or c)
...         is_even = not is_even
...     out = ''.join(lst)
...     return out
... 
>>> def cap_in_words_even(s):
...     return re.sub(r'\S+', lambda mo: tr(mo.group()), s)
... 
>>> cap_in_words_even('abcd')
'AbCd'
>>> cap_in_words_even('abc defghi')
'AbC DeFgHi'
>>> cap_in_words_even('  abc  def  ')
'  AbC  DeF  '
>>>
old_monty
py.user.next
Пробелы теряет она
  "  abc  def  "
 "AbC DeF"
Вот зачем переделываешь условие задачи?
Было же ясно сказано:
solyarity
Words will be separated by a single space(’ ').
Examples:
to_weird (“String”) -> returns “StRiNg”
to_weird (“Weird string case”) -> returns “WeIrD StRiNg CaSe”
А вообще, спасибо. Интересное решение.
py.user.next
old_monty
Вот зачем переделываешь условие задачи?
Да, не заметил я в конце это условие. А пробелы по краям подходят под условие. Но тут не это главное; главное, что обычно нет этого условия про один пробел межу словами, есть понятие “пустое пространство” (whitespace). Тогда слова можно подавать в программу не только в одной строке, но и по одному в строке на нескольких строках, так как конец строки является whitespace.
FishHook
 def to_weird(s):
   return  "".join("{}{}".format(x[0].upper(), x[1]) for x in zip_longest(s[::2], s[1::2], fillvalue=""))
def cap_in_words_even(s):
   return re.sub(r'\S+', lambda mo: to_weird(mo.group()), s)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB