0

for my assignment at hackerrank, ı need to write a program that takes a string as input and returns that string in back ordering and reversed characters, that means a input like "hELLO wORLD" should return as "Hello World", ı did all the stuff but when ı try to run it, it stops on spaces, don't know how to solve.

def reverse(sentence):
mylist = []
splitted = sentence.split(" ")
for i in range(len(splitted)):
    mylist.append(splitted[-1])
    splitted.pop(-1)
    
for i in mylist:
    chars = []
    for char in i:
        if char.islower():
            char = char.upper()
            chars.append(char)
        elif char.isupper():
            char = char.lower()
            chars.append(char)
        else:
            char = char
            chars.append(char)
    print(chars)
    newmessage = ""
    for i in chars:
        newmessage += str(i)
    print(newmessage)

reverse("helLoWorld")

Ali Dağ
  • 19
  • 5

2 Answers2

0
def reverse(sentence):
complete_string =""
mylist = []
splitted = sentence.split(" ")
for i in range(len(splitted)):
    mylist.append(splitted[-1])
    splitted.pop(-1)

print(mylist)
    
for x,i in enumerate(mylist):
    chars = []
    for char in i:
        if char.islower():
            char = char.upper()
            chars.append(char)
        elif char.isupper():
            char = char.lower()
            chars.append(char)
        else:
            char = char
            chars.append(char)
    print(chars)
    newmessage = ""
    for i in chars:
        newmessage += str(i)
    print(newmessage)
    if len(mylist)-x != 1:
        complete_string += newmessage + " "
    else:
        complete_string += newmessage
print(complete_string)

reverse("hELLO wORLD")

kenoc1
  • 52
  • 5
0

you can check swap case as Chris Charley commented but if you want to use your code, you can skip split the sentence to preserve blank spaces.

def reverse(sentence):
    # mylist = []
    # splitted = sentence.split(" ")
    # for i in range(len(splitted)):
    #     mylist.append(splitted[-1])
    #     splitted.pop(-1)

    chars = []
    for i in sentence:
        for char in i:
            if char.islower():
                char = char.upper()
                chars.append(char)
            elif char.isupper():
                char = char.lower()
                chars.append(char)
            else:
                char = char
                chars.append(char)
        # print(chars)
    newmessage = ""
    for i in chars:
        newmessage += str(i)
    print(newmessage)


reverse('hELLO wORLD')

output:

Hello World
Erick Cruz
  • 66
  • 3
  • thanks but, ı have to rewrite string with back ordering like if input is "hello world" it should prompt "world hello". thats why ı am using split. – Ali Dağ Nov 19 '20 at 14:15
  • well, you can use split after getting **newmessage** to change the order of the sentence. – Erick Cruz Nov 19 '20 at 14:55