I solved the logical part of the following exercise, but can't find a simple solution to output in the required format. It looks like a list within a list to me.
Problem description:
Write a program that will take a string of digits and give you all the possible consecutive slices of length n in that string.
Raise an error if n is larger than the length of the string.
Examples For example, the string "01234" has the following 2-digit slices:
[[0, 1], [1, 2], [2, 3], [3, 4]]
The same string has the following 4-digit slices:
[[0, 1, 2, 3], [1, 2, 3, 4]]
This is my code which is working fine except the way it returns the answer is different so can't submit it.
digits = "01234"
n = 4
result = [None]*(len(digits)-n+1) #create a list with required size
for x in range(0, len(digits)-n+1):
result[x] = digits[x:n]
n += 1
print(result)
This code prints ['0123', '1234']
, which is the correct answer but I want it in this format: [[0, 1, 2, 3], [1, 2, 3, 4]]
(edit) adding this line solved my problem suggested by mkrieger1, thanks
This is the final code:
def series_slices(digits, n):
digits = [int(x) for x in digits]
result = []
for x in range(0, len(digits)-n+1):
result.append(list(digits[x:n]))
n += 1
return result