0

For example, i = 'cat', how can I get this output: 'at', 'ct', 'ca'?

I wrote a code like this, but totally wrong. Can anyone help?

for x in i:
    print(i.replace('x', ''))
Qing
  • 63
  • 1
  • 2
  • 8

1 Answers1

1

Since you are not permitted to use itertools.combinations you could use its definition as seen in: https://docs.python.org/3.6/library/itertools.html#itertools.combinations

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

string = 'cat'
print([''.join(c) for c in combinations(string, 2)])

Output:

['ca', 'ct', 'at']
solid.py
  • 2,782
  • 5
  • 23
  • 30