user2954438
user2954438

Reputation: 15

Subsets for a string

I was trying to get every subset for a string and could not think how to do it. If anyone can help me that would be great.

>>> string('ab')
    a, b
>>> string('abc')
    a, b, c, ab, ac, bc,
>>> string('abcd')
    a, b, c, d, ab, bc, cd, da, abc, bcd, cda, dab,

These all have to be in the list and there might be n numbers of characters in the string. The program should return all the strings subsets that can be formed.

Upvotes: 1

Views: 761

Answers (2)

akhtarvahid
akhtarvahid

Reputation: 9769

Returns a subset of a string in javascript

function getSubset(str) {
  let subSet = [];
  let i, j, len = str.length; 

  for(i=0; i<len; i++) {
    for(j=i+1; j<=len; j++) {
       subSet.push(str.slice(i, j))
    }
  }
  return subSet;
}

console.log(getSubset('CAT'))
console.log(getSubset('GOD'))

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239453

You can use itertools.combinations and list comprehension like this

from itertools import combinations
def myStrings(s):
    return ["".join(item) for i in range(1,len(s)) for item in combinations(s,i)]

print myStrings('ab')
print myStrings('abc')
print myStrings('abcd')

Output

['a', 'b']
['a', 'b', 'c', 'ab', 'ac', 'bc']
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'bc', 'bd', 'cd', 'abc', 'abd', 'acd', 'bcd']

Upvotes: 1

Related Questions