ページ 11

[python]定めた文字列の全通りの出力

Posted: 2016年4月10日(日) 11:47
by ねこ-*-
入力した文字が"a"と"b"と"1"だったとします。
これらから文字列を作成した時
a, b, 1, aa, ab, a1, ba, bb, b1, 1a, 1b, 11, aaa,・・・

このように指定した文字と数字を使って文字列を作成したいです。
アルゴリズムをコードで欲しいです。
宜しくお願いします。 

Re: [python]定めた文字列の全通りの出力

Posted: 2016年4月10日(日) 14:40
by みけCAT
[Python]連続した文字列作成のコードとほとんど同様にできます。

コード:

import sys

def moziretu(chars):
    def moziretu_internal(len):
        if len <= 0:
            yield ''
        else:
            for c in chars:
                for s in moziretu_internal(len - 1):
                    yield c + s
    length = 1
    while True:
        for ret in moziretu_internal(length):
            yield ret
        length += 1

chars = list(sys.stdin.readline().rstrip())

isfirst = True
for m in moziretu(chars):
    if not isfirst:
        sys.stdout.write(', ')
    sys.stdout.write(m)
    isfirst = False

Re: [python]定めた文字列の全通りの出力

Posted: 2016年4月11日(月) 00:43
by かずま
4文字までにしています。もっとたくさんにしたければ変更してください。

コード:

def generate(t, s, n):
    if n == 0:
        print t + ",",
    else:
        for c in s:
            generate(t + c, s, n - 1)

s = raw_input("> ")
for i in range(4):
    generate("", s, i + 1)