0

Im trying to split the stings into even parts. For example if I have ['abcdef'], expected output should be ['ab','cd','ef']. I keep getting the same input for the first test 'asdfadsf'/

def solution(s):

    lists = []

    for i in s:
        if len(s) % 2 == 0:
            lists.append(s)
            zip(*[iter(lists)]*2)
        return lists

test.describe("Example Tests")

tests = (
    ("asdfadsf", ['as', 'df', 'ad', 'sf']),
    ("asdfads", ['as', 'df', 'ad', 's_']),
    ("", []),
    ("x", ["x_"]),
)

 for inp, exp in tests:
 test.assert_equals(solution(inp), exp)
Mahdi
  • 3,188
  • 2
  • 20
  • 33
Eggiderm
  • 87
  • 1
  • 6
  • I'd bet money that the asker here is on the same programming course as [this guy](http://stackoverflow.com/q/41432202/1709587) who (badly) asked what looks to be a later question from the same problem sheet at around the same moment that this one was posted. – Mark Amery Jan 02 '17 at 21:18

2 Answers2

1

Try this,

def solutions(s):
    return [j.ljust(2,'_') for j in (s[i:i+2] for i in  range(0,len(s),2))]

Results

In [38]: tests = (
   ....:     ("asdfadsf", ['as', 'df', 'ad', 'sf']),
   ....:     ("asdfads", ['as', 'df', 'ad', 's_']),
   ....:     ("", []),
   ....:     ("x", ["x_"]),
   ....: )
In [39]: for inp, exp in tests:
   ....:     print solutions(inp) == exp 
   ....:     
True
True
True
True
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • To meet the test cases for strings of uneven length, you could use `[s + "_" for s in ['as', 'df', 'ad', 's'] if len(s) < 2]` – blacksite Jan 02 '17 at 18:45
-1

The easiest way to do what you want is with range.

def chunk(input):

    if len(input) % 2 == 1:
        input += '_'

    output = [input[idx:idx+2] for idx in range(0, len(input), 2]
    return output
Batman
  • 8,571
  • 7
  • 41
  • 80