Python: Reverse Words and Swap Cases

Implement a function that takes a string consisting of words separated by single spaces and returns a string containing all those words but in the reverse order and such that all the cases of letters in the original string are swapped, i.e. lowercase letters become uppercase and uppercase letters become lowercase.


Example 

Sentence = "rUns dOg"
Reverse the word order and swap the case of all letters then return the string "DoG RuNS".


Function description

Complete the function
reverse_words_order_and_swap_cases in the editor.


The function has the following parameter(s):

  • string sentence: a given string of space separated words.
  • Returns: a string containing all the words from the sentence but in the reverse order and such that all cases of letters in the sentence string are swapped.

Constraints:
  • sentence contains only English letters and spaces.
  • sentence begins and ends with a letter.
  • There are no two consecutive spaces in sentence.
  • There are at most 10 words in sentence.
  • The lengths of each of the words is at most 10.


Solution:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
print 'hello world!'def swap_case(word):
    return ''.join([character.lower() if character.isupper() else character.upper() for character in word])


def reverse_words_order_and_swap_cases(sentence):
    words = sentence.split(' ')[::-1]
    return ' '.join([swap_case(word) for word in words])


print(swap_case('hello'))



Labels : #hackerrank certification ,#python (basic) ,

Post a Comment