获取字符串的所有组合词

2 投票
2 回答
4083 浏览
提问于 2025-04-16 02:52

我想要字符串“my first program”的所有组合单词。

2 个回答

0

如果你想在Python中原生地做到这一点...

def recurse_combinations(used, unused, dic ):

    if len(unused) == 0:#If unused is empty we are done
        dic[used]= True #Lets store the result and stop recursing
        return

    for i in range(len(unused)):
        #keep recursing by going through 'unused' characters and adding them to 'used'. Now lets take out the single character we are now using from 'unused'
        recurse_combinations( used + unused[i], unused[:i]+unused[i+1:], dic  )


def recurse_combinations_start( word="my first program"):
    dic = {}

    recurse_combinations( "" , word, dic)

    pprint ( dic.keys() )
    print len(dic.keys())

只需调用这个recurse_combinations_start(),然后把你想用的单词换上就可以了。

8

在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们通常需要将它们转换成一种程序能处理的格式。

例如,如果我们从一个网页上获取了一些信息,这些信息可能是以文本的形式存在的。为了让程序能够使用这些信息,我们需要把它们转化为程序可以理解的结构,比如列表或者字典。这样,程序才能更方便地操作这些数据。

在这个过程中,我们可能会用到一些工具和库,这些工具可以帮助我们更轻松地完成数据转换的工作。通过使用这些工具,我们可以节省很多时间和精力,让我们的程序运行得更顺畅。

总之,数据处理是编程中非常重要的一部分,理解如何将数据转换成合适的格式是每个程序员都需要掌握的技能。

>>> lst = "my first program".split()
>>> set(itertools.permutations(lst))

set([('first', 'my', 'program'),
     ('first', 'program', 'my'),
     ('my', 'first', 'program'),
     ('my', 'program', 'first'),
     ('program', 'first', 'my'),
     ('program', 'my', 'first')])

撰写回答