Finding all possible case permutations in Python

后端 未结 1 817
后悔当初
后悔当初 2020-12-02 00:35

I need to work out a list of all possible permutations of case only in python for example with input of ar it would return [ \'ar\',\'Ar\',\'aR\',\'AR\']

相关标签:
1条回答
  • 2020-12-02 01:07
    def all_casings(input_string):
        if not input_string:
            yield ""
        else:
            first = input_string[:1]
            if first.lower() == first.upper():
                for sub_casing in all_casings(input_string[1:]):
                    yield first + sub_casing
            else:
                for sub_casing in all_casings(input_string[1:]):
                    yield first.lower() + sub_casing
                    yield first.upper() + sub_casing
    

    >>> [x for x in all_casings("foo")]
    ['foo', 'Foo', 'fOo', 'FOo', 'foO', 'FoO', 'fOO', 'FOO']
    >>> list(all_casings("foo"))
    ['foo', 'Foo', 'fOo', 'FOo', 'foO', 'FoO', 'fOO', 'FOO']
    
    0 讨论(0)
提交回复
热议问题