#C13433. Split List into Sublists
Split List into Sublists
Split List into Sublists
You are given a list of integers and an integer \( k \). Your task is to split the list into consecutive sublists, each containing exactly \( k \) elements except possibly the last one which may have fewer elements if there are not enough remaining.
Formally, given a list \( nums \) and an integer \( k \), partition \( nums \) into sublists \( [nums_0, nums_1, \ldots, nums_{k-1}], [nums_k, \ldots, nums_{2k-1}], \ldots \). If \( n \) is the length of \( nums \) and \( n \) is not divisible by \( k \), then the final sublist will have \( n \% k \) elements.
Examples:
- Input:
nums = [1, 2, 3, 4, 5, 6, 7], k = 3
→ Output:[[1, 2, 3], [4, 5, 6], [7]]
- Input:
nums = [4, 1, 3, 2, 5], k = 2
→ Output:[[4, 1], [3, 2], [5]]
Implement a solution that reads input from standard input (stdin) and prints the result to standard output (stdout) in the format of a Python list representation.
inputFormat
The input consists of two lines. The first line contains a space-separated list of integers (the list may be empty). The second line contains a single integer ( k ).
outputFormat
Output a single line: the list of sublists formatted as a Python list representation. Each sublist should be enclosed in square brackets, and the entire output should be enclosed in square brackets.## sample
1 2 3 4 5 6 7
3
[[1, 2, 3], [4, 5, 6], [7]]