Taskintro
Partition a list
Also called split a list by a predicate, partition by a test, separate odd and even, partitioningBy, split into two lists.
Split a list into the items that pass a test and the items that do not, here the odd and the even integers, and keep the order of the items in each part.
- Evidence
- Code in 10 languages
Task
Split a list of integers into two lists: the odd items and the even items. The function partition_odd(items) returns the two lists as a pair, the odd items first. Each list keeps the input order. For example, partition_odd([1, 2, 3, 4, 5]) is ([1, 3, 5], [2, 4]).
An item is odd if the remainder of the item divided by 2 is not 0, so -3 is odd. Each item goes into exactly one of the two lists. The items are 32-bit signed integers, and the list can be empty. Then the result is two empty lists.
Solutions
| Language | Split into the odd and the even items |
|---|---|
| Python | a loop that appends each item to one of two lists |
| JavaScript, TypeScript | a loop that pushes each item to one of two arrays |
| Java | two filter calls on Arrays.stream(items) |
| C# | a loop that adds each item to one of two lists |
| Go | a loop that appends each item to one of two new slices |
| Rust | items.iter().copied().partition(|x| x % 2 != 0) |
| C | a loop that writes to two output arrays and sets two counts |
| C++ | std::ranges::partition_copy with two std::back_inserter |
| Bash | a loop that adds each item to one of two arrays, then two lines of output |
- The test. Each solution uses
x % 2 != 0, notx % 2 == 1. The remainder of a negative odd item is -1 in each of these languages, except Python. In Python,-3 % 2is 1, so both tests work there. - Rust.
partition"Consumes an iterator, creating two collections from it"1. The first collection has the items for which the predicate returns true. - C. The caller gives two output arrays. Each must have room for n items, because all the items can go into one of them.
- Bash. A function can only print text, so the solution prints the odd items on the first line and the even items on the second line. A line is empty when it has no items.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: an empty list gives two empty lists.one-side: all the items are odd, or all are even, so one of the two lists is empty.negative: -3 and -1 are odd, and -2 is even.zero: 0 is even.order:[9, 8, 1, 2]gives[9, 1]and[8, 2], not sorted lists.extremes: 2147483647 is odd, and -2147483648 is even.duplicates: equal items stay in the result.
Pitfalls
- Python an iterator gives its items only once.
filterfalsereturns "only those for which the predicate returns a false value"2. In the example,filteruses all the items of the iterator, sofilterfalsegets no items. Use a list, or one loop:
from itertools import filterfalse
def is_odd(x):
return x % 2 != 0
items = iter([1, 2, 3, 4])
odd = list(filter(is_odd, items))
even = list(filterfalse(is_odd, items))
print(odd, even)
items = [1, 2, 3, 4]
print(list(filter(is_odd, items)), list(filterfalse(is_odd, items)))
[1, 3] []
[1, 3] [2, 4]
- JavaScript Object.groupBy has no property for an empty group. The result is "A null-prototype object with properties for all groups, each assigned to an array containing the elements of the associated group"3. In the example, no item is odd, so
groups.oddisundefined. Use?? []:
const groups = Object.groupBy([2, 4], (x) => (x % 2 !== 0 ? "odd" : "even"));
console.log(groups.odd);
console.log(groups.odd ?? []);
undefined
[]
- Java groupingBy can give null. For
partitioningBy, "The returned Map always contains mappings for both false and true keys"4. In the example,groupingBywith the same test givesnullfor the keytrue:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Map<Boolean, List<Integer>> parts =
Stream.of(2, 4).collect(Collectors.partitioningBy(x -> x % 2 != 0));
System.out.println(parts.get(true) + " " + parts.get(false));
Map<Boolean, List<Integer>> groups =
Stream.of(2, 4).collect(Collectors.groupingBy(x -> x % 2 != 0));
System.out.println(groups.get(true) + " " + groups.get(false));
}
}
[] [2, 4]
null [2, 4]
- C# a dictionary of groups has no key for an empty group. For a lookup, "If the key is not found in the collection, an empty sequence is returned"5. In the example, the dictionary from
GroupByhas no keytrue:
using System;
using System.Linq;
int[] items = [2, 4];
var lookup = items.ToLookup(x => x % 2 != 0);
Console.WriteLine(lookup[true].Count());
var groups = items.GroupBy(x => x % 2 != 0).ToDictionary(g => g.Key, g => g.ToArray());
Console.WriteLine(groups.ContainsKey(true));
0
False
- Go a filter into a[:0] changes the input. "This trick uses the fact that a slice shares the same backing array and capacity as the original"6. In the example, the filter writes into the array of
a, soachanges. For a partition that keeps the input, append to new slices:
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4}
// b shares the array of a, so the appends change a.
b := a[:0]
for _, x := range a {
if x%2 != 0 {
b = append(b, x)
}
}
fmt.Println(b, a)
}
[1 3] [1 3 3 4]
- Rust x % 2 == 1 misses negative odd items. In the example,
-3 % 2is -1, so the testx % 2 == 1puts no item in the first collection:
fn main() {
let items = [-3, -2, -1, 0];
let (wrong, _): (Vec<i32>, Vec<i32>) = items.iter().copied().partition(|x| x % 2 == 1);
let (odd, even): (Vec<i32>, Vec<i32>) = items.iter().copied().partition(|x| x % 2 != 0);
println!("{}", -3 % 2);
println!("{wrong:?} {odd:?} {even:?}");
}
-1
[] [-3, -1] [-2, 0]
- C the remainder has the sign of the dividend. The quotient is "truncated towards zero"7, and "(a/b)*b + a%b == a"7. Thus
-3 / 2is -1 and-3 % 2is -1:
#include <stdio.h>
int main(void) {
int x = -3;
printf("%d %d\n", x / 2, x % 2);
printf("%s\n", x % 2 == 1 ? "odd" : "not odd");
printf("%s\n", x % 2 != 0 ? "odd" : "not odd");
return 0;
}
-1 -1
not odd
odd
- C++ std::partition changes the range in place. To keep the order of the items in each part, use
std::stable_partition, which "divides elements into two groups while preserving their relative order within each group"8. For two new containers and an unchanged input, usestd::partition_copy. In the example, the result iterator is the start of the second part:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4, 5};
auto mid = std::stable_partition(v.begin(), v.end(), [](int x) { return x % 2 != 0; });
for (std::size_t i = 0; i < v.size(); i++) {
std::cout << v[i] << (i + 1 < v.size() ? " " : "\n");
}
std::cout << (mid - v.begin()) << '\n';
}
1 3 5 2 4
3
- Bash (( )) gives the status 1 for the value 0. "If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1."9 Thus
if ((x % 2 != 0))works as a test, but((count++))has the status 1 whencountwas 0:
count=0
((count++))
echo "status $?"
((count++))
echo "status $?"
status 1
status 0
Related tasks
- Filter a list: keep only the items that pass a test.
- Group items by a key: split a list into more than two groups.
- Count the items of each kind: count the items of each group.
- Iterate in chunks: split a list into parts of a fixed size.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/partition-a-list/.
def partition_odd(items: list[int]) -> tuple[list[int], list[int]]:
"""Return the odd items and the even items of items, each in input order."""
odd: list[int] = []
even: list[int] = []
for x in items:
# x % 2 != 0 is true for each odd item, also for -3.
(odd if x % 2 != 0 else even).append(x)
return odd, even
test_partition_odd.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/partition-a-list/.
import pytest
from partition_odd import partition_odd
CASES = {
"mixed": ([1, 2, 3, 4, 5], ([1, 3, 5], [2, 4])),
"tens": ([10, 15, 20, 25], ([15, 25], [10, 20])),
"empty": ([], ([], [])),
"all-odd": ([1, 3], ([1, 3], [])),
"all-even": ([2, 4], ([], [2, 4])),
"negative": ([-3, -2, -1, 0], ([-3, -1], [-2, 0])),
"zero": ([0], ([], [0])),
"order": ([9, 8, 1, 2], ([9, 1], [8, 2])),
"extremes": ([-2147483648, 2147483647], ([2147483647], [-2147483648])),
"duplicates": ([3, 3, 2, 2], ([3, 3], [2, 2])),
}
@pytest.mark.parametrize("name", CASES)
def test_partition_odd(name):
items, want = CASES[name]
assert partition_odd(items) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
#include "partition_odd.hpp"
#include <algorithm>
#include <iterator>
std::pair<std::vector<int>, std::vector<int>> partition_odd(std::span<const int> items) {
std::vector<int> odd;
std::vector<int> even;
std::ranges::partition_copy(items, std::back_inserter(odd), std::back_inserter(even),
[](int x) { return x % 2 != 0; });
return {odd, even};
}
partition_odd.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
#pragma once
#include <span>
#include <utility>
#include <vector>
// partition_odd returns the odd items and the even items, each in input order.
std::pair<std::vector<int>, std::vector<int>> partition_odd(std::span<const int> items);
test_partition_odd.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
#include "partition_odd.hpp"
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<int> &items, const std::vector<int> &odd,
const std::vector<int> &even) {
auto [got_odd, got_even] = partition_odd(items);
if (got_odd != odd || got_even != even) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("mixed", std::vector<int>{1, 2, 3, 4, 5}, std::vector<int>{1, 3, 5}, std::vector<int>{2, 4});
check("tens", std::vector<int>{10, 15, 20, 25}, std::vector<int>{15, 25}, std::vector<int>{10, 20});
check("empty", std::vector<int>{}, std::vector<int>{}, std::vector<int>{});
check("all-odd", std::vector<int>{1, 3}, std::vector<int>{1, 3}, std::vector<int>{});
check("all-even", std::vector<int>{2, 4}, std::vector<int>{}, std::vector<int>{2, 4});
check("negative", std::vector<int>{-3, -2, -1, 0}, std::vector<int>{-3, -1}, std::vector<int>{-2, 0});
check("zero", std::vector<int>{0}, std::vector<int>{}, std::vector<int>{0});
check("order", std::vector<int>{9, 8, 1, 2}, std::vector<int>{9, 1}, std::vector<int>{8, 2});
check("extremes", std::vector<int>{(-2147483647 - 1), 2147483647}, std::vector<int>{2147483647}, std::vector<int>{(-2147483647 - 1)});
check("duplicates", std::vector<int>{3, 3, 2, 2}, std::vector<int>{3, 3}, std::vector<int>{2, 2});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
import java.util.Arrays;
final class PartitionOdd {
private PartitionOdd() {}
/** Returns two arrays: the odd items and the even items, each in input order. */
static int[][] partitionOdd(int[] items) {
int[] odd = Arrays.stream(items).filter(x -> x % 2 != 0).toArray();
int[] even = Arrays.stream(items).filter(x -> x % 2 == 0).toArray();
return new int[][] {odd, even};
}
}
PartitionOddTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class PartitionOddTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("mixed", new int[] {1, 2, 3, 4, 5}, new int[] {1, 3, 5}, new int[] {2, 4}),
Arguments.of("tens", new int[] {10, 15, 20, 25}, new int[] {15, 25}, new int[] {10, 20}),
Arguments.of("empty", new int[] {}, new int[] {}, new int[] {}),
Arguments.of("all-odd", new int[] {1, 3}, new int[] {1, 3}, new int[] {}),
Arguments.of("all-even", new int[] {2, 4}, new int[] {}, new int[] {2, 4}),
Arguments.of("negative", new int[] {-3, -2, -1, 0}, new int[] {-3, -1}, new int[] {-2, 0}),
Arguments.of("zero", new int[] {0}, new int[] {}, new int[] {0}),
Arguments.of("order", new int[] {9, 8, 1, 2}, new int[] {9, 1}, new int[] {8, 2}),
Arguments.of("extremes", new int[] {-2147483648, 2147483647}, new int[] {2147483647}, new int[] {-2147483648}),
Arguments.of("duplicates", new int[] {3, 3, 2, 2}, new int[] {3, 3}, new int[] {2, 2}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void partitionOdd(String name, int[] items, int[] odd, int[] even) {
int[][] got = PartitionOdd.partitionOdd(items);
assertEquals(2, got.length);
assertArrayEquals(odd, got[0]);
assertArrayEquals(even, got[1]);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
#include "partition_odd.h"
void partition_odd(const int *items, size_t n, int *odd, size_t *n_odd, int *even, size_t *n_even) {
size_t no = 0;
size_t ne = 0;
for (size_t i = 0; i < n; i++) {
if (items[i] % 2 != 0) {
odd[no++] = items[i];
} else {
even[ne++] = items[i];
}
}
*n_odd = no;
*n_even = ne;
}
partition_odd.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
#ifndef PARTITION_ODD_H
#define PARTITION_ODD_H
#include <stddef.h>
// partition_odd writes the odd items of items[0..n) to odd and the even items
// to even, each in input order. odd and even must each have room for n items.
// It sets *n_odd and *n_even to the counts.
void partition_odd(const int *items, size_t n, int *odd, size_t *n_odd, int *even, size_t *n_even);
#endif
test_partition_odd.c 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
#include "partition_odd.h"
#include <stdbool.h>
#include <stdio.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
static bool same(const int *got, size_t k, const int *want, size_t m) {
if (k != m) {
return false;
}
for (size_t i = 0; i < m; i++) {
if (got[i] != want[i]) {
return false;
}
}
return true;
}
// Each list has a 0 in it when it is empty, because C has no empty array.
// The counts give the real lengths.
#define CHECK(name, n, given, mo, wo, me, we) \
do { \
const int g[] = given; \
const int o[] = wo; \
const int e[] = we; \
int odd[sizeof g / sizeof g[0]]; \
int even[sizeof g / sizeof g[0]]; \
size_t no = 0; \
size_t ne = 0; \
partition_odd(g, n, odd, &no, even, &ne); \
if (!same(odd, no, o, mo) || !same(even, ne, e, me)) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("mixed", 5, L(1, 2, 3, 4, 5), 3, L(1, 3, 5), 2, L(2, 4));
CHECK("tens", 4, L(10, 15, 20, 25), 2, L(15, 25), 2, L(10, 20));
CHECK("empty", 0, L(0), 0, L(0), 0, L(0));
CHECK("all-odd", 2, L(1, 3), 2, L(1, 3), 0, L(0));
CHECK("all-even", 2, L(2, 4), 0, L(0), 2, L(2, 4));
CHECK("negative", 4, L(-3, -2, -1, 0), 2, L(-3, -1), 2, L(-2, 0));
CHECK("zero", 1, L(0), 0, L(0), 1, L(0));
CHECK("order", 4, L(9, 8, 1, 2), 2, L(9, 1), 2, L(8, 2));
CHECK("extremes", 2, L((-2147483647 - 1), 2147483647), 1, L(2147483647), 1, L((-2147483647 - 1)));
CHECK("duplicates", 4, L(3, 3, 2, 2), 2, L(3, 3), 2, L(2, 2));
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
using System.Collections.Generic;
public static class PartitionOdd
{
// Split returns the odd items and the even items, each in input order.
public static (int[] Odd, int[] Even) Split(int[] items)
{
var odd = new List<int>();
var even = new List<int>();
foreach (int x in items)
{
// Use != 0, not == 1: the remainder of a negative item can be negative.
(x % 2 != 0 ? odd : even).Add(x);
}
return (odd.ToArray(), even.ToArray());
}
}
PartitionOddTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
using Xunit;
public sealed class PartitionOddTests
{
public static TheoryData<string, int[], int[], int[]> Cases => new()
{
{ "mixed", new int[] { 1, 2, 3, 4, 5 }, new int[] { 1, 3, 5 }, new int[] { 2, 4 } },
{ "tens", new int[] { 10, 15, 20, 25 }, new int[] { 15, 25 }, new int[] { 10, 20 } },
{ "empty", new int[0], new int[0], new int[0] },
{ "all-odd", new int[] { 1, 3 }, new int[] { 1, 3 }, new int[0] },
{ "all-even", new int[] { 2, 4 }, new int[0], new int[] { 2, 4 } },
{ "negative", new int[] { -3, -2, -1, 0 }, new int[] { -3, -1 }, new int[] { -2, 0 } },
{ "zero", new int[] { 0 }, new int[0], new int[] { 0 } },
{ "order", new int[] { 9, 8, 1, 2 }, new int[] { 9, 1 }, new int[] { 8, 2 } },
{ "extremes", new int[] { -2147483648, 2147483647 }, new int[] { 2147483647 }, new int[] { -2147483648 } },
{ "duplicates", new int[] { 3, 3, 2, 2 }, new int[] { 3, 3 }, new int[] { 2, 2 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] items, int[] odd, int[] even)
{
Assert.NotNull(name);
var got = PartitionOdd.Split(items);
Assert.Equal(odd, got.Odd);
Assert.Equal(even, got.Even);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
/**
* @param {number[]} items
* @returns {[number[], number[]]}
*/
export function partitionOdd(items) {
const odd = [];
const even = [];
for (const x of items) {
// Use !== 0, not === 1: the remainder of a negative item can be negative.
if (x % 2 !== 0) {
odd.push(x);
} else {
even.push(x);
}
}
return [odd, even];
}
partition_odd.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { partitionOdd } from "./partition_odd.js";
const cases = [
["mixed", [1, 2, 3, 4, 5], [[1, 3, 5], [2, 4]]],
["tens", [10, 15, 20, 25], [[15, 25], [10, 20]]],
["empty", [], [[], []]],
["all-odd", [1, 3], [[1, 3], []]],
["all-even", [2, 4], [[], [2, 4]]],
["negative", [-3, -2, -1, 0], [[-3, -1], [-2, 0]]],
["zero", [0], [[], [0]]],
["order", [9, 8, 1, 2], [[9, 1], [8, 2]]],
["extremes", [-2147483648, 2147483647], [[2147483647], [-2147483648]]],
["duplicates", [3, 3, 2, 2], [[3, 3], [2, 2]]],
];
for (const [name, items, want] of cases) {
test(name, () => {
assert.deepEqual(partitionOdd(items), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
export function partitionOdd(items: readonly number[]): [number[], number[]] {
const odd: number[] = [];
const even: number[] = [];
for (const x of items) {
// Use !== 0, not === 1: the remainder of a negative item can be negative.
if (x % 2 !== 0) {
odd.push(x);
} else {
even.push(x);
}
}
return [odd, even];
}
partition_odd.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { partitionOdd } from "./partition_odd.ts";
const cases: [string, number[], [number[], number[]]][] = [
["mixed", [1, 2, 3, 4, 5], [[1, 3, 5], [2, 4]]],
["tens", [10, 15, 20, 25], [[15, 25], [10, 20]]],
["empty", [], [[], []]],
["all-odd", [1, 3], [[1, 3], []]],
["all-even", [2, 4], [[], [2, 4]]],
["negative", [-3, -2, -1, 0], [[-3, -1], [-2, 0]]],
["zero", [0], [[], [0]]],
["order", [9, 8, 1, 2], [[9, 1], [8, 2]]],
["extremes", [-2147483648, 2147483647], [[2147483647], [-2147483648]]],
["duplicates", [3, 3, 2, 2], [[3, 3], [2, 2]]],
];
for (const [name, items, want] of cases) {
test(name, () => {
assert.deepEqual(partitionOdd(items), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
// Package partitionodd splits a slice into its odd and even items.
package partitionodd
// PartitionOdd returns the odd items and the even items, each in input order.
// It makes new slices, so the input does not change.
func PartitionOdd(items []int) (odd, even []int) {
for _, x := range items {
if x%2 != 0 {
odd = append(odd, x)
} else {
even = append(even, x)
}
}
return odd, even
}
partition_odd_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
package partitionodd
import (
"slices"
"testing"
)
var cases = []struct {
name string
items []int
odd []int
even []int
}{
{"mixed", []int{1, 2, 3, 4, 5}, []int{1, 3, 5}, []int{2, 4}},
{"tens", []int{10, 15, 20, 25}, []int{15, 25}, []int{10, 20}},
{"empty", []int{}, []int{}, []int{}},
{"all-odd", []int{1, 3}, []int{1, 3}, []int{}},
{"all-even", []int{2, 4}, []int{}, []int{2, 4}},
{"negative", []int{-3, -2, -1, 0}, []int{-3, -1}, []int{-2, 0}},
{"zero", []int{0}, []int{}, []int{0}},
{"order", []int{9, 8, 1, 2}, []int{9, 1}, []int{8, 2}},
{"extremes", []int{-2147483648, 2147483647}, []int{2147483647}, []int{-2147483648}},
{"duplicates", []int{3, 3, 2, 2}, []int{3, 3}, []int{2, 2}},
}
func TestPartitionOdd(t *testing.T) {
for _, c := range cases {
odd, even := PartitionOdd(c.items)
if !slices.Equal(odd, c.odd) || !slices.Equal(even, c.even) {
t.Errorf("%s: got %v %v, want %v %v", c.name, odd, even, c.odd, c.even)
}
}
}
func TestInputDoesNotChange(t *testing.T) {
items := []int{2, 1, 4, 3}
PartitionOdd(items)
if !slices.Equal(items, []int{2, 1, 4, 3}) {
t.Errorf("the input changed: %v", items)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
/// Returns the odd items and the even items, each in input order.
pub fn partition_odd(items: &[i32]) -> (Vec<i32>, Vec<i32>) {
// copied() gives i32 values, not references. `x % 2 != 0` is true for -3.
items.iter().copied().partition(|x| x % 2 != 0)
}
tests/partition_odd_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/partition-a-list/.
use algo_partition_a_list::partition_odd;
#[test]
fn cases() {
let cases: Vec<(&str, &[i32], Vec<i32>, Vec<i32>)> = vec![
("mixed", &[1, 2, 3, 4, 5], vec![1, 3, 5], vec![2, 4]),
("tens", &[10, 15, 20, 25], vec![15, 25], vec![10, 20]),
("empty", &[], vec![], vec![]),
("all-odd", &[1, 3], vec![1, 3], vec![]),
("all-even", &[2, 4], vec![], vec![2, 4]),
("negative", &[-3, -2, -1, 0], vec![-3, -1], vec![-2, 0]),
("zero", &[0], vec![], vec![0]),
("order", &[9, 8, 1, 2], vec![9, 1], vec![8, 2]),
("extremes", &[-2147483648, 2147483647], vec![2147483647], vec![-2147483648]),
("duplicates", &[3, 3, 2, 2], vec![3, 3], vec![2, 2]),
];
for (name, items, odd, even) in cases {
assert_eq!(partition_odd(items), (odd, even), "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/partition-a-list/.
# partition_odd ITEM...
# Prints two lines: the odd items, then the even items, each in input order
# and separated by spaces. A line is empty if it has no items.
partition_odd() {
local -a odd=() even=()
local x
for x in "$@"; do
if ((x % 2 != 0)); then
odd+=("$x")
else
even+=("$x")
fi
done
printf '%s\n' "${odd[*]}" "${even[*]}"
}
test_partition_odd.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/partition-a-list/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/partition_odd.sh"
}
check() { # check ODD_LINE EVEN_LINE GIVEN...
local want_odd=$1 want_even=$2 got want
shift 2
# The x keeps the trailing newlines, which $(...) removes.
got=$(partition_odd "$@"; printf x)
want=$(printf '%s\n' "$want_odd" "$want_even"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "mixed" { check "1 3 5" "2 4" 1 2 3 4 5; }
@test "tens" { check "15 25" "10 20" 10 15 20 25; }
@test "empty" { check "" ""; }
@test "all-odd" { check "1 3" "" 1 3; }
@test "all-even" { check "" "2 4" 2 4; }
@test "negative" { check "-3 -1" "-2 0" -3 -2 -1 0; }
@test "zero" { check "" "0" 0; }
@test "order" { check "9 1" "8 2" 9 8 1 2; }
@test "extremes" { check "2147483647" "-2147483648" -2147483648 2147483647; }
@test "duplicates" { check "3 3" "2 2" 3 3 2 2; }
References
- Rust standard library, trait Iterator, partition
- The Python Standard Library, itertools, itertools.filterfalse()
- MDN Web Docs, Object.groupBy(), Return value
- Java SE 25 API, Class Collectors, partitioningBy(Predicate)
- .NET API reference, Lookup<TKey,TElement>.Item[TKey] property, Remarks
- Go Wiki, SliceTricks, Filtering without allocating
- cppreference.com, Arithmetic operators (C), Multiplicative operators
- cppreference.com, std::partition, See also
- Bash Reference Manual, 3.2.5.2 Conditional Constructs, ((...))
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag PVEFE0 Edit this page History Report an error Markdown