Create a scrolling_text function that accepts a string as a parameter, sequentially rearranges all the characters in the string from the zero index to the last one, and returns a list with all the received combinations in upper case.
`
def scrolling_text(string: str) -> list:
pass
`
Example`
scrolling_text("robot")
returns:
[ "ROBOT",
"OBOTR",
"BOTRO",
"OTROB",
"TROBO" ]
`
I know only I return the list in uppercase
CodePudding user response:
The easiest way is to use slices of the string, which is an easy way of getting a subset of an sequence. In Python, str
can be treated as a sequence of characters.
The following function would do it:
def scrolling_text(text: str) -> list[str]:
ret = []
for i in range(len(text)):
ret.append(text[i:] text[:i])
return ret
So this goes through every offset starting at zero and going up to the number of characters in the string. The expression text[i:]
represents the substring from offset i
onwards, and text[:i]
represents the substring up to (but not including) I
.
If you wanted more advanced Python, you could use a list comprehension:
def scrolling_text(text: str) -> list[str]:
return [text[i:] text[:i] for i in range(len(text))]
Or you could use a generator to lazily evaluate the list:
from typing import Iterator
def scrolling_text(text: str) -> Iterator[str]:
for i in range(len(text)):
yield text[i:] text[:i]
CodePudding user response:
This is a pretty basic python code:
def scrolling_text(string: str) -> list:
out = []
string = string.upper()
for i in range(len(string)):
out.append(string[i:] string[:i])
return out
res = scrolling_text("ROBOT")
print(res) # ['ROBOT', 'OBOTR', 'BOTRO', 'OTROB', 'TROBO']