用python实现19. 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba
时间: 2024-05-08 09:16:50 浏览: 13
思路:
将字符串转化为字符数组,使用递归的方式进行排列,每次固定一个字符,然后对剩下的字符进行排列。
代码实现:
```python
def permutation(s):
if not s:
return []
if len(s) == 1:
return list(s)
res = []
for i in range(len(s)):
for j in permutation(s[:i] + s[i+1:]):
res.append(s[i] + j)
return res
s = input("请输入一个字符串:")
res = permutation(s)
res.sort()
for i in res:
print(i)
```
示例输出:
```
请输入一个字符串:abc
abc
acb
bac
bca
cab
cba
```
相关问题
python实现输入 n 个字符串,请对 n 个字符串按照字典序排列。
好的,这个问题很简单,可以使用python内置的sort方法进行排序,代码如下:
```
n = int(input("请输入字符串个数:"))
strings = []
for i in range(n):
s = input("请输入第{}个字符串:".format(i+1))
strings.append(s)
strings.sort()
print("按照字典序排列的结果为:")
for s in strings:
print(s)
```
python中如何实现多个字符串按照字典序排列
可以使用sorted()函数进行排序,该函数的第一个参数是要排序的字符串列表,第二个参数是key函数,用于指定排序规则。字典序排列可以使用默认的key函数,示例代码如下:
```python
str_list = ["hello", "world", "python"]
sorted_list = sorted(str_list)
print(sorted_list)
```
输出结果为:`['hello', 'python', 'world']`
其中,`sorted(str_list)`返回一个按照字典序排列的字符串列表。如果需要按照字符串长度排序,可以使用`key=len`作为第二个参数,示例代码如下:
```python
str_list = ["hello", "world", "python"]
sorted_list = sorted(str_list, key=len)
print(sorted_list)
```
输出结果为:`['hello', 'world', 'python']`
其中,`key=len`表示按照字符串长度排序。