当前位置:网站首页>Summary of the implementation method of string inversion "recommended collection"
Summary of the implementation method of string inversion "recommended collection"
2022-07-31 15:48:00 【Full stack programmer webmaster】
大家好,又见面了,我是你们的朋友全栈君.
文章目录 - 方法1:Symmetric exchange method
- 方法2:函数递归法
- 方法3:列表反转法
- 方法4:Loop reverse iterative method
- 方法5:Reverse slice method
- 方法6:Traversal index method
- 方法7:Reverse traversal index method
- 方法8:List popup method
- 方法9:Reverse loop iteration method
- 方法10:cumulative addition
- 方法11:匿名函数法
- 方法12:Reverse list method
- 方法13:Two-way queue sorting method
- 方法14:Two-way queue inversion method
方法1:Symmetric exchange method
str = 'abcdef'
def f(s):
s = list(s)
if len(s) <=1:
return s
i = 0
length = len(s)
while i < length/2:
s[i],s[length - 1 - i] = s[length - 1 - i],s[i]
i += 1
return ''.join(s)
newStr = f(str)
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: Iterates over the elements in the first half of the string,Then swap with the element at the position where the second half is symmetrical,to achieve string reversal.
方法2:函数递归法
str = 'abcdef'
print(str[:-1]) # str[:-1] Truncate all but the last element(-1 表示最后一个元素的索引)
def fun(s):
if len(s) <= 1:
return s
return s[-1] + fun(s[:-1])
newStr = fun(str)
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 使用递归的思想,建立函数,Add strings in reverse order,until the string length is less than or equal to1后停止.
方法3:列表反转法
str = 'abcdef'
ll = list(str) # list()method converts a string to a list ['a', 'b', 'c', 'd', 'e', 'f']
ll.reverse() # 将list反转,变成了 ['f', 'e', 'd', 'c', 'b', 'a']
newStr = ''.join(ll) # 采用join()方法遍历列表,合并成一个字符串
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: Python中,Lists can be reversed,We just convert the string to a list,使用reverse()方法,进行反转,Then use stringsjoin()方法遍历列表,合并成一个字符串.
方法4:Loop reverse iterative method
str1 = 'abcdef'
str2 = ''
for i in str1:
str2 = i + str2
print('String before inversion:', str1) # abcdef
print('反转后的字符串:', str2) # fedcba说明: Strings are a type of sequence,我们可以使用for循环遍历字符串,然后,Constantly reverse assignment to variablesstr2,最后输出变量str2,This completes the string inversion.
方法5:Reverse slice method
str = 'abcdef'
newStr = str[::-1]
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: Take advantage of the slice feature,一步到位
方法6:Traversal index method
str = 'abcdef'
newStr = ''
for i in range(1, len(str)+1):
newStr = newStr + str[-i]
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: *Strings as sequences,Index processing is possible,So we iterate over the index numbers first,Then extract the letters in reverse order,Then merge into strings.
方法7:Reverse traversal index method
str = 'abcdef'
newStr = ''
print(len(str)) # 6
for i in range(len(str)-1, -1, -1):
newStr = newStr + str[i]
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明:range()函数有三个参数:start,end,step,且左闭右开,We start with the last index,The first index ends,Traverse the index in reverse order,Then extract the string in reverse,最后合并
方法8:List popup method
str = 'abcdef'
str = list(str) # 将字符串str转换成列表 ['a', 'b', 'c', 'd', 'e', 'f']
newStr = ''
while len(str) > 0:
newStr = newStr + str.pop()
print('反转后的字符串:', newStr) # fedcba说明: Lists have a popup methodpop(),The last element pops up by default.Add to the empty string each time an element is popped newStr中,Finally, the inversion of the original string is realized.
方法9:Reverse loop iteration method
str = 'abcdef'
newStr = ''
for i in str[::-1]:
newStr = newStr + i
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba代码改进:
str = 'abcdef'
newStr = ''.join(i for i in str[::-1])
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 使用列表解析式,然后通过join()方法,Reverse merged strings.
方法10:cumulative addition
str = 'abcdef'
from functools import reduce
def f(x,y):
return y + x
newStr = reduce(f,str)
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 使用python中的reduce()函数.First create a function for adding strings in reverse order,Then pass in the string along with the newly created functionreduce()函数中,Perform the cumulative addition of strings in reverse order,Finally implement the reversed string.
方法11:匿名函数法
str = 'abcdef'
from functools import reduce
newStr = reduce(lambda x,y:y+x,str)
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明:方法10的进阶版,使用lambdaAn anonymous function creates a function for adding strings in reverse order,Then do the cumulative addition,Get the string reversed result.
方法12:Reverse list method
str = 'abcdef'
ll = list(str) # 将字符串str转换成列表 ['a', 'b', 'c', 'd', 'e', 'f']
ll.sort(reverse=True) # 列表降序排列
newStr = ''.join(ll)
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: Listedsort(reverse=True)方法,降序排列,不过,There is a downside to this method,It's not ascending or descending in string order,而是按 “ASCII 字符顺序” 进行排序,所以,If the string is not sorted in ascending order,Then after running,The ordering will be wrong.
方法13:Two-way queue sorting method
str = 'abcdef'
import collections
newStr = collections.deque()
for i in str:
newStr.appendleft(i)
newStr = ''.join(newStr)
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: 遍历字符串,Add to the left to the two-way queue,最后使用join()方法合并,实现字符串反转.
方法14:Two-way queue inversion method
str = 'abcdef'
import collections
newStr = collections.deque()
newStr.extend(list(str))
newStr.reverse()
newStr = ''.join(newStr)
print('String before inversion:', str) # abcdef
print('反转后的字符串:', newStr) # fedcba说明: Also use a two-way queue,Convert the string to a list and add it to the queue,Then the whole thing is reversed,使用join()方法合并,实现字符串反转.
文章参考:小詹学Python 公众号的 《The interviewer lets 5 种 python method implements string inversion ?Sorry I have16种……》
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/127982.html原文链接:https://javaforall.cn
边栏推荐
猜你喜欢
随机推荐
ML.NET相关资源整理
After Grafana is installed, the web opens and reports an error
Insert into data table to insert data
C language "the third is" upgrade (mode selection + AI chess)
7、常见面试口语提问问题汇总
TRACE32 - C source code association
外媒所言非虚,苹果降价或许是真的在清库存
ML.NET related resources
ansible学习笔记02
数据库的范式(第一范式,第二范式,第三范式,BCNF范式)「建议收藏」
ansible study notes 02
苹果官网样式调整 结账时产品图片“巨大化”
[MySQL] Mysql paradigm and the role of foreign keys
How does automated testing create business value?
01 邂逅typescript,环境搭建
mysql黑窗口~建库建表
工程水文学复习资料
The normal form of the database (first normal form, second normal form, third normal form, BCNF normal form) "recommended collection"
update data table update
MySQL基础篇【单行函数】









