A1g
A1g

Reputation: 93

How to get all possible subset of the string in python

I have a case in which I want to generate all possible subset or the combination of the given string. so far I tried this:

def list_string(str):
   level=['']
   if len(str) <=1:
       level += str
       return level
   else:
      for item in range(len(str)):
          n_list=[]
          for item1 in level:
              n_list.append(item1 + str[item])
          level += n_list
         . return level

so if I call print list_string('ab')

I get only ['', 'a', 'b', 'ab'] I am missing 'ba' in the list. can anyone tell me where I am doing wrong. I want to do this without using itertools or modules.

Upvotes: 0

Views: 6129

Answers (4)

Y. Yazarel
Y. Yazarel

Reputation: 1503

Using list comprehension,

str= 'ab'
def subset(str)-> List[str]:
    lst= ['']
    res = ['']

    for i in range(len(str)):
        lst= [t+a for t in lst for a in str if t!=a]
        res += lst
    return res

this method returns the permutations:

['', 'a', 'b', 'ab', 'ba']

Upvotes: -1

user14437744
user14437744

Reputation:

def ios(stringinput, sub = "", i= 0):
    if i == len(stringinput):
        return [sub]
    else:
        return ios(stringinput, sub+ stringinput[i], i+1 ) + ios(stringinput, sub, i+1)



print(ios("abc"))

Upvotes: 1

GleasonK
GleasonK

Reputation: 1022

Better off using itertools but this is an interesting bit of recursion

def list_string(strn):
  level=[]
  def permute(prefix, suffix):
    level.append(prefix)
    if len(suffix)==0:
       return
    for i in range(len(suffix)):
      permute(prefix + suffix[i], suffix[:i]+suffix[i+1:])
  permute("",strn)
  return level

t = list_string("hey")
# ['', 'h', 'he', 'hey', 'hy', 'hye', 'e', 'eh', 'ehy', 'ey', 'eyh', 'y', 'yh', 'yhe', 'ye', 'yeh']

Upvotes: 6

Yax
Yax

Reputation: 2189

I think you should use list comprehension:

def list_string(str):
  level = [x+y for x in str for y in str if len(str) > 1]
  return level

Then run list_string('ab')

it should return

['aa', 'ab', 'ba', 'bb']

Now work the if statement to your conditions. Hope this help?

Upvotes: -2

Related Questions