python completes a specific rightward movement of strings
- 2021-06-28 09:24:23
- OfStack
#Completes a specific rightward movement of elements in a string, parameters: string, length of movement such as abcdef, move 2, result: efabcd
#Original method, basic idea: the end element moves to the beginning, the other elements move backwards in turn. The code is as follows:
def move(lt, n):
lt = list(lt) # Convert Strings to Lists
for i in range(n % len(lt)):# Determine how many times to move , For example, when moving from the same length to the same length as the list , There's no need to move
t = lt[len(lt) - 1] # Remove the end element
for j in reversed(range(len(lt) - 1)): # Traverse the list of elements except the end in reverse order
lt[j + 1] = lt[j] # Before 1 After assigning values to 1 Elements
lt[0] = t # Assign the value of the previously fetched end element to the top of the list
return "".join(lt) # Split lists into strings , And back
These methods are based on the C language and do not reflect the benefits of python. Here are a few ways to reflect the benefits of Python
def move(lt, n):
lt = list(lt) # Convert Strings to Lists
for i in range(n % len(lt)): # Determine how many moves to make
lt.insert(0, lt.pop()) # From a list pop Method takes out the end element , In Pass insert Function inserts the removed element at the top of the list
return "".join(lt)
def move(lt, n):
for i in range(n % len(lt)): # Determine how many moves to make
lt = lt[-1] + lt[0:-1] # Slice through a string , Excision last 1 Elements , Then add from the beginning to the last 2 Elements
return lt
These two methods can reflect the simplicity of the Python language, but as a programmer, the C language is fundamental. The first method is written in the python language using the ideas of the C language.