编写一个python程序来尽可能地排列字符串 正确的三个字符的字母序列
例如:
INPUT : "ahdgbice"
OUTPUT: {'abc', 'bcd', 'ghi', 'cde'}
任何人都可以建议我做一个优化的方法,我已经尝试并成功生成输出但我对我的代码不满意所以任何人请建议我一个适当的优化方法来解决这个问题。
答案 0 :(得分:2)
这可能是一个不错的结果:
foreach (TextBox tb in myTextBoxes) {
tb.Content = "UPDATED CONTENT!";
}
工作原理:
在这种情况下生成一个字符串>>> import itertools as it
>>> in_s="ahdgbice"
>>> in_test=''.join([chr(e) for e in range(ord(min(in_s)),ord(max(in_s))+1)])
>>> {s for s in map(lambda e: ''.join(e), (it.combinations(sorted(in_s),3))) if s in in_test}
{'abc', 'ghi', 'bcd', 'cde'}
,以测试子字符串是否按字母顺序排列:abc..khi
使用in_test=''.join([chr(e) for e in range(ord(min(in_s)),ord(max(in_s))+1)])
in_s
的3个字母子串的每个组合
测试子字符串是否通过测试排序是否为map(lambda e: ''.join(e), (it.combinations(sorted(in_s),3)))
答案 1 :(得分:0)
解决方案:它不是优化的解决方案,但它符合要求
# for using array import numpy lib
import numpy as np
#input string
str_1="ahdgbice"
#breaking the string into characters by puting it into a list.
list_1=list(str_1)
# for sorting we copy that list value in an array
arr_1=np.array(list_1)
arr_2=np.sort(arr_1)
# some temp variables
previous=0
str_2=""
list_2=list()
#logic and loops starts here : looping outer loop from 0 to length of sorted array
for outer in range(0,len(arr_2)):
#looping inner loop from outer index value to length of sorted array
for inner in range(outer,len(arr_2)):
value=arr_2[inner]
#ord() return an ascii value of characters
if(previous is 0):
previous=ord(value)
#difference between two consecutive sequence is always 1 or -1
# e.g ascii of a= 97, b=98 ,So a-b=-1 or b-a=1 and used abs() to return absolute value
if(abs(previous-ord(value)) is 1):
str_2=str_2+value # appending character with previous str_2 values
previous=ord(value) # storing current character's ascii value to previous
else:
str_2=value # assigning character value to str_2
previous=ord(value) # storing current character's ascii value to previous
# for making a string of three characters
if(len(str_2) == 3):
list_2.append(str_2)
# Logic and loops ends here
# put into the set to remove duplicate values
set_1=set(list_2)
#printing final output
print(set_1)
输出:
{'abc', 'bcd', 'ghi', 'cde'}
答案 2 :(得分:0)
我会使用itertool
模块的permutations
函数来获取输入的所有三元素排列的列表,然后针对每个结果查看它是否与排序相同本身的版本。