-2

This is what I have so far:

def generateCosets(str, n):
    equalStr = []
    for i in range(0, n):
        part = getNthLetters(str, n)
        equalStr.append(part)
    return equalStr


def getNthLetters(text, n):
    builtstring = ''
    for i in range(0, len(text)):
        if i % n == 0:
            builtstring = builtstring + text[i]
    return builtstring

If I run this code:

s0 = '12345678'
myArr = generateCosets(s0,2)
print(myArr[0], myArr[1])

it yields:

1357 1357

instead of:

1357 2468

I just don't know how to make the for loop start from i+1 every time I use the getNthLetters method

deadshot
  • 8,881
  • 4
  • 20
  • 39

3 Answers3

0

you can use slicing on string

s0[0::2]
'1357'
s0[1::2]
'2468'
0

You can solve this problem by checking the parity of the indexes at your initial string:

s0 = '12345678'
print(''.join([i if int(i)%2 != 0 else "" for i in s0]), ''.join([i if int(i)%2 == 0 else "" for i in s0]))
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
0

You can use slice notation (check Understanding slice notation) with step:

def generate_cosets(text, n):
    for i in range(n):
        yield text[i::n]

Usage:

s0 = '12345678'
print(*generate_cosets(s0, 2))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35