0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

文字の順序を問わず全ての部分文字列を出力するプログラム

Last updated at Posted at 2023-08-21

引数に与えられた文字列に何の文字列が含まれているか、全ての部分文字列を出力するプログラムです。文字列中の文字の順序の違う文字列も全て出力します。

itertoolsモジュールのpermutationsを使っています。

名前を'per.py'といいます。ソースをコピペした後、
chmod +x per.py
として実行権限をつけて動かして下さい。

2023年8月23日 メモリ節約のため、shiracamusさんの指摘通りにコードを書き換えました。

per.py
#!/usr/bin/python3
import sys
import itertools

if len(sys.argv)==2:
    per=list(sys.argv[1])
else:
    print("Usage: per.py <string>")
    exit(1)
for i in range(1,len(per)+1):
    for j in itertools.permutations(per, i):
        print("".join(j))

例えば、catでは次のようになります。

$ per.py cat
c
a
t
ca
ct
ac
at
tc
ta
cat
cta
act
atc
tca
tac

実践

長い文字列では膨大な出力数になりますので、時間がかかるでしょう。

例えば、maekawataisukeに含まれるひらがなの単語を全部出力するには、以下のようにします。

$ per.py maekawataisuke |rk|grep -x -i -f - ~/dic/jm.txt

大量のメモリを消費し、/tmpの容量が足りなくなるので、/tmpを大容量Diskに移してします。

maekawataisukeに含まれる全ての英単語ならば次のようです。

$ per.py maekawataisuke|grep -x -i -f - ~/dic/dic.txt

ここで、rkはローマ字かな変換、dic.txtは英単語だけの辞書、jm.txtはひらがなの単語だけの辞書です。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?