当前位置:网站首页>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
边栏推荐
- Unity中实现点选RenderTexture中的3D模型
- 工程水文学复习资料
- C language "the third is" upgrade (mode selection + AI chess)
- 【7.28】代码源 - 【Fence Painting】【合适数对(数据加强版)】
- Efficient use of RecyclerView Section 1
- 删除表格数据或清空表格
- Efficient use of RecyclerView Section 2
- 复制延迟案例(3)-单调读
- ASP.NET Core 产生连续 Guid
- How useful is four-quadrant time management?
猜你喜欢

6-22漏洞利用-postgresql数据库密码破解

WPF project - basic usage of controls entry, you must know XAML
![[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development](/img/f6/311d5a4c70993df6291250d2025d3f.jpg)
[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development

外媒所言非虚,苹果降价或许是真的在清库存

The use of button controls

Kubernetes common commands

What is the difference between BI software in the domestic market?

Getting Started with TextBlock Control Basic Tools Usage, Get Started

i.MX6ULL驱动开发 | 33 - NXP原厂网络设备驱动浅读(LAN8720 PHY)

Kubernetes原理剖析与实战应用手册,太全了
随机推荐
01 Encounter typescript, build environment
[CUDA study notes] First acquaintance with CUDA
复制延迟案例(3)-单调读
button控件的使用
Use of radiobutton
Replication Latency Case (1) - Eventual Consistency
jeecg主从数据库读写分离配置「建议收藏」
form 表单提交后,使页面不跳转[通俗易懂]
Oracle dynamically registers non-1521 ports
ML.NET related resources
org.apache.jasperException(could not initialize class org)
R language ggplot2 visualization: use the ggmapplot function of the ggpubr package to visualize the MA plot (MA-plot), the font.legend parameter and the font.main parameter to set the title and legend
Why don't you make a confession during the graduation season?
TRACE32 - C source code association
基于ABP实现DDD
TRACE32 - Common Operations
Implement anti-shake and throttling functions
删除表格数据或清空表格
Emmet 语法
AVH Deployment Practice (1) | Deploying the Flying Paddle Model on Arm Virtual Hardware