Taskintro
Check whether a list contains a value
Also called list contains, array includes, membership test, in operator, value in list, linear search, find an item in a list, includes.
Tell whether a value is one of the items of a list, and know which equality each language uses, how NaN and object items behave, and when a set is the better structure.
- Evidence
- Code in 10 languages
Task
Tell whether a value is in a list. The function contains(items, value) returns true if some item of items is equal to value, and false if not. For example, contains([1, 2, 3], 2) is true, and contains([1, 2, 3], 4) is false.
The function must not change items. Each item and the value are 32-bit signed integers, and the list has 0 to 1000 items.
Solutions
| Language | Contains | Equality used |
|---|---|---|
| Python | value in items |
is, then == |
| JavaScript, TypeScript | items.includes(value) |
SameValueZero |
| Java | Arrays.stream(items).anyMatch(x -> x == value), list.contains(value) |
== for int, Objects.equals for a List |
| C# | Array.IndexOf(items, value) >= 0, list.Contains(value) |
EqualityComparer<T>.Default |
| Go | slices.Contains(items, value) |
== |
| Rust | items.contains(&value) |
PartialEq |
| C | a loop with == |
==, or strcmp for strings |
| C++ | std::ranges::contains(items, value) |
== |
| Bash | a loop with [[ $item == "$value" ]] |
string equality |
- Python. "For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y)"1.
- JavaScript. "The includes() method compares searchElement to elements of the array using the SameValueZero algorithm"2. TypeScript uses the same method on a
readonly number[]. - Java.
List.containsreturns true "if and only if this list contains at least one element e such that Objects.equals(o, e)"3. The input is anint[], so the solution uses a stream ofint. - C#.
List<T>.Contains"determines equality using the default equality comparer EqualityComparer.Default for T"4, and "This method performs a linear search"4. The solution usesArray.IndexOfon the array. - Go. "Contains reports whether v is present in s"5. The item type must be comparable. For other tests,
slices.ContainsFunctakes a function. - Rust.
containstakes a reference to the value, as initems.contains(&value)6. - C. C has no contains function for an
intarray. The solution compares each item with==and returns at the first match. - C++.
std::ranges::contains"Checks whether or not the source range contains the target value value"7. With an older standard library, compare the result ofstd::findwith the end:std::findreturns "an iterator to the first element in the source range [first, last) that satisfies specific criteria (or last if there is no such iterator)"8. - Bash. For
[[ ... == ... ]], "the string to the right of the operator is considered a pattern"9. The solution puts the value in double quotes, so the right side is a string. The function returns the status 0 for found and 1 for not found, so a caller can use it as the test of anif.
Each solution is a linear search: it compares the value with the items in order, so it takes time in proportion to the length of the list. A program that tests many values against one list can put the items in a set once, and then each test takes about the same time for any size.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: an empty list contains no value, so the result is false.single-yesandsingle-no: a list of one item.firstandlast: the value at the first and at the last position. A loop with a bound off by one misses one of them.duplicates: the value can be in the list more than once, and the result is still true.negativeandzero-absent: negative items, and 0 when the list has no 0. A test that uses a position as a truth value fails here.limitandlimit-absent: the smallest 32-bit integer is found in a list that has it, and is not found in a list that has only the largest.- Each test checks that
itemsdoes not change. The task find the index of a value also gives the position.
Pitfalls
- Python
intests identity before equality. Becausex in yisany(x is e or x == e for e in y)1, a NaN object is found in a list that holds the same object, thoughnan == nanis false. A different NaN object is not found. Also,True == 1in Python, soTrue in [1]is true:
nan = float("nan")
print(nan == nan, nan in [nan], float("nan") in [nan])
print(True in [1], 1.0 in [1])
False True False
True True
- JavaScript
indexOfdoes not find NaN, and 0 is falsy. SameValueZero works "like strict equality === (where -0 and +0 are considered equal), with the exception that NaN is considered equal to itself"2. But forindexOf, "NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN"10. Also,if (a.indexOf(x))is false whenxis the first item, because the position 0 is falsy. Useincludesfor a yes or no answer:
const a = [1, NaN];
console.log(a.includes(NaN), a.indexOf(NaN));
console.log(a.indexOf(1) ? "found" : "not found");
console.log(a.includes(1) ? "found" : "not found");
true -1
not found
found
- Java
Arrays.asListof anint[]is a list of one array.asList(T... a)"Returns a fixed-size list backed by the specified array"11, butTcannot beint. SoArrays.asList(new int[] {1, 2, 3})is aList<int[]>with one item, andcontains(1)is false. Also,containsusesObjects.equals3, and anIntegeris never equal to aLong, soList.of(1L).contains(1)is false:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3};
System.out.println(Arrays.asList(a).contains(1) + " " + Arrays.asList(a).size());
System.out.println(Arrays.stream(a).anyMatch(x -> x == 1));
List<Long> b = List.of(1L, 2L);
System.out.println(b.contains(1) + " " + b.contains(1L));
}
}
false 1
true
false true
- C#
Containscompares class objects by reference.Containsuses the default equality comparer4. "For class types, two objects are equal if they refer to the same object in memory"12, unless the class overridesEquals. A record has value equality. So a new object with the same fields is not found in a list of a class, but it is found in a list of a record:
var classes = new List<PointClass> { new() { X = 1, Y = 2 } };
var records = new List<PointRecord> { new(1, 2) };
Console.WriteLine(classes.Contains(new PointClass { X = 1, Y = 2 }));
Console.WriteLine(records.Contains(new PointRecord(1, 2)));
class PointClass
{
public int X { get; init; }
public int Y { get; init; }
}
record PointRecord(int X, int Y);
False
True
- Go
slices.Containsdoes not find NaN.Containsuses==, and "Two floating-point values are compared as defined by the IEEE 754 standard"13. In IEEE 754, NaN is not equal to any value, NaN too. Useslices.ContainsFunc5 withmath.IsNaN:
package main
import (
"fmt"
"math"
"slices"
)
func main() {
a := []float64{1, math.NaN()}
fmt.Println(slices.Contains(a, math.NaN()))
fmt.Println(slices.ContainsFunc(a, math.IsNaN))
}
false
true
- Rust
containsneeds a&T, so a&strdoes not work on aVec<String>. A call such asv.contains(&s)with a&strnamedsdoes not compile, because the item type isString. "If you do not have a &T, but some other value that you can compare with one (for example, String implements PartialEq), you can use iter().any"6:
fn main() {
let v = vec![String::from("a"), String::from("b")];
println!("{}", v.contains(&String::from("b")));
println!("{}", v.iter().any(|s| s == "b"));
}
true
true
- C
==on strings compares the pointers. Two arrays with the same characters are at different addresses, so==is false.strcmpreturns "Zero if lhs and rhs compare equal"14:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *names[] = {"ann", "bob"};
char want[] = "bob";
bool by_pointer = false;
bool by_text = false;
for (size_t i = 0; i < 2; i++) {
if (names[i] == want) {
by_pointer = true;
}
if (strcmp(names[i], want) == 0) {
by_text = true;
}
}
printf("%d %d\n", by_pointer, by_text);
return 0;
}
0 1
- C++
std::binary_searchneeds a sorted range. It "Checks if an element equivalent to value exists in the partitioned source range [first, last)"15, and the behavior is undefined if the range is not partitioned15. On an unsorted vector, it can miss an item that is there. Sort the vector first, or usestd::ranges::contains. The output is from the GCC library:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{5, 1, 4, 2, 3};
std::cout << std::ranges::contains(v, 1) << " " << std::binary_search(v.begin(), v.end(), 1) << "\n";
std::ranges::sort(v);
std::cout << std::binary_search(v.begin(), v.end(), 1) << "\n";
}
1 0
1
- Bash an unquoted right side is a pattern, and a joined string finds parts of items. The right side of
==is a pattern9, so withx='*',[[ $item == $x ]]is true for each item. A test on the joined list,[[ " ${a[*]} " == *" $x "* ]], findsYorkin the itemNew York. Loop over the items and quote the value:
a=("New York" Paris)
x='*'
for item in "${a[@]}"; do
if [[ $item == $x ]]; then echo "unquoted: $item"; fi
if [[ $item == "$x" ]]; then echo "quoted: $item"; fi
done
x=York
if [[ " ${a[*]} " == *" $x "* ]]; then echo "joined: found"; fi
unquoted: New York
unquoted: Paris
joined: found
Related tasks
- Filter a list: keep all the items that match, not only test for one.
- Search a sorted list: find a value in a sorted list in fewer steps.
- Remove duplicates from a list: uses a membership test for each item.
- Count the items of each kind: count the matches instead of stopping at the first.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
def contains(items: list[int], value: int) -> bool:
"""Return True if some item of items is equal to value."""
# in compares each item with value, so it takes time in proportion to len(items).
return value in items
test_contains.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
import pytest
from contains import contains
CASES = {
"present": ([1, 2, 3], 2, True),
"absent": ([1, 2, 3], 4, False),
"empty": ([], 0, False),
"single-yes": ([5], 5, True),
"single-no": ([5], 0, False),
"first": ([7, 8, 9], 7, True),
"last": ([7, 8, 9], 9, True),
"duplicates": ([2, 2, 2], 2, True),
"negative": ([-1, -2, -3], -2, True),
"zero-absent": ([-1, 1], 0, False),
"limit": ([2147483647, -2147483648], -2147483648, True),
"limit-absent": ([2147483647], -2147483648, False),
}
@pytest.mark.parametrize("name", CASES)
def test_contains(name):
items, value, want = CASES[name]
items0 = list(items)
assert contains(items, value) is want
assert items == items0
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
#include "contains.hpp"
#include <algorithm>
#include <span>
bool contains(std::span<const int> items, int value) {
// std::ranges::contains is new in C++23. Before it, compare
// std::find(first, last, value) with last.
return std::ranges::contains(items, value);
}
contains.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
#pragma once
#include <span>
// contains returns true if some item of items is equal to value.
bool contains(std::span<const int> items, int value);
test_contains.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
#include "contains.hpp"
#include <climits>
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<int> &items, int value, bool want) {
if (contains(items, value) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("present", std::vector<int>{1, 2, 3}, 2, true);
check("absent", std::vector<int>{1, 2, 3}, 4, false);
check("empty", std::vector<int>{}, 0, false);
check("single-yes", std::vector<int>{5}, 5, true);
check("single-no", std::vector<int>{5}, 0, false);
check("first", std::vector<int>{7, 8, 9}, 7, true);
check("last", std::vector<int>{7, 8, 9}, 9, true);
check("duplicates", std::vector<int>{2, 2, 2}, 2, true);
check("negative", std::vector<int>{-1, -2, -3}, -2, true);
check("zero-absent", std::vector<int>{-1, 1}, 0, false);
check("limit", std::vector<int>{INT_MAX, INT_MIN}, INT_MIN, true);
check("limit-absent", std::vector<int>{INT_MAX}, INT_MIN, false);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
import java.util.Arrays;
final class Contains {
private Contains() {}
/** Returns true if some item of items is equal to value. */
static boolean contains(int[] items, int value) {
// Arrays.asList(items) would be a List<int[]> with one item, so use a stream of int.
return Arrays.stream(items).anyMatch(x -> x == value);
}
}
ContainsTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
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 ContainsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("present", new int[] {1, 2, 3}, 2, true),
Arguments.of("absent", new int[] {1, 2, 3}, 4, false),
Arguments.of("empty", new int[] {}, 0, false),
Arguments.of("single-yes", new int[] {5}, 5, true),
Arguments.of("single-no", new int[] {5}, 0, false),
Arguments.of("first", new int[] {7, 8, 9}, 7, true),
Arguments.of("last", new int[] {7, 8, 9}, 9, true),
Arguments.of("duplicates", new int[] {2, 2, 2}, 2, true),
Arguments.of("negative", new int[] {-1, -2, -3}, -2, true),
Arguments.of("zero-absent", new int[] {-1, 1}, 0, false),
Arguments.of("limit", new int[] {2147483647, Integer.MIN_VALUE}, Integer.MIN_VALUE, true),
Arguments.of("limit-absent", new int[] {2147483647}, Integer.MIN_VALUE, false));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void contains(String name, int[] items, int value, boolean want) {
int[] items0 = items.clone();
assertEquals(want, Contains.contains(items, value));
assertArrayEquals(items0, items);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
#include "contains.h"
#include <stdbool.h>
#include <stddef.h>
bool contains(const int *items, size_t n, int value) {
for (size_t i = 0; i < n; i++) {
if (items[i] == value) {
return true;
}
}
return false;
}
contains.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
#ifndef CONTAINS_H
#define CONTAINS_H
#include <stdbool.h>
#include <stddef.h>
// contains returns true if one of the n items is equal to value.
bool contains(const int *items, size_t n, int value);
#endif
test_contains.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
#include "contains.h"
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// C has no empty array, so an empty list is the array {0} with a count of 0.
#define CHECK(name, n, items, value, want) \
do { \
const int x[] = items; \
if (contains(x, n, value) != (want)) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("present", 3, L(1, 2, 3), 2, true);
CHECK("absent", 3, L(1, 2, 3), 4, false);
CHECK("empty", 0, L(0), 0, false);
CHECK("single-yes", 1, L(5), 5, true);
CHECK("single-no", 1, L(5), 0, false);
CHECK("first", 3, L(7, 8, 9), 7, true);
CHECK("last", 3, L(7, 8, 9), 9, true);
CHECK("duplicates", 3, L(2, 2, 2), 2, true);
CHECK("negative", 3, L(-1, -2, -3), -2, true);
CHECK("zero-absent", 2, L(-1, 1), 0, false);
CHECK("limit", 2, L(INT_MAX, INT_MIN), INT_MIN, true);
CHECK("limit-absent", 1, L(INT_MAX), INT_MIN, false);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
public static class Contains
{
// Returns true if some item of items is equal to value. Array.IndexOf
// compares each item with the default equality comparer of int.
public static bool Of(int[] items, int value) => Array.IndexOf(items, value) >= 0;
}
ContainsTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
using Xunit;
public sealed class ContainsTests
{
public static TheoryData<string, int[], int, bool> Cases => new()
{
{ "present", new int[] { 1, 2, 3 }, 2, true },
{ "absent", new int[] { 1, 2, 3 }, 4, false },
{ "empty", new int[0], 0, false },
{ "single-yes", new int[] { 5 }, 5, true },
{ "single-no", new int[] { 5 }, 0, false },
{ "first", new int[] { 7, 8, 9 }, 7, true },
{ "last", new int[] { 7, 8, 9 }, 9, true },
{ "duplicates", new int[] { 2, 2, 2 }, 2, true },
{ "negative", new int[] { -1, -2, -3 }, -2, true },
{ "zero-absent", new int[] { -1, 1 }, 0, false },
{ "limit", new int[] { 2147483647, int.MinValue }, int.MinValue, true },
{ "limit-absent", new int[] { 2147483647 }, int.MinValue, false },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] items, int value, bool want)
{
Assert.NotNull(name);
var items0 = (int[])items.Clone();
Assert.Equal(want, Contains.Of(items, value));
Assert.Equal(items0, items);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
/**
* Returns true if some item of items is equal to value.
* @param {number[]} items
* @param {number} value
* @returns {boolean}
*/
export function contains(items, value) {
// includes returns a boolean. indexOf returns a position, and 0 is falsy.
return items.includes(value);
}
contains.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { contains } from "./contains.js";
const cases = [
["present", [1, 2, 3], 2, true],
["absent", [1, 2, 3], 4, false],
["empty", [], 0, false],
["single-yes", [5], 5, true],
["single-no", [5], 0, false],
["first", [7, 8, 9], 7, true],
["last", [7, 8, 9], 9, true],
["duplicates", [2, 2, 2], 2, true],
["negative", [-1, -2, -3], -2, true],
["zero-absent", [-1, 1], 0, false],
["limit", [2147483647, -2147483648], -2147483648, true],
["limit-absent", [2147483647], -2147483648, false],
];
for (const [name, items, value, want] of cases) {
test(name, () => {
const items0 = [...items];
assert.equal(contains(items, value), want);
assert.deepEqual(items, items0);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
export function contains(items: readonly number[], value: number): boolean {
// includes returns a boolean. indexOf returns a position, and 0 is falsy.
return items.includes(value);
}
contains.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { contains } from "./contains.ts";
const cases: [string, number[], number, boolean][] = [
["present", [1, 2, 3], 2, true],
["absent", [1, 2, 3], 4, false],
["empty", [], 0, false],
["single-yes", [5], 5, true],
["single-no", [5], 0, false],
["first", [7, 8, 9], 7, true],
["last", [7, 8, 9], 9, true],
["duplicates", [2, 2, 2], 2, true],
["negative", [-1, -2, -3], -2, true],
["zero-absent", [-1, 1], 0, false],
["limit", [2147483647, -2147483648], -2147483648, true],
["limit-absent", [2147483647], -2147483648, false],
];
for (const [name, items, value, want] of cases) {
test(name, () => {
const items0 = [...items];
assert.equal(contains(items, value), want);
assert.deepEqual(items, items0);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
// Package contains tells whether a slice has a value.
package contains
import "slices"
// Contains reports whether some item of items is equal to value.
func Contains(items []int, value int) bool {
return slices.Contains(items, value)
}
contains_test.go 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
package contains
import (
"math"
"slices"
"testing"
)
var cases = []struct {
name string
items []int
value int
want bool
}{
{"present", []int{1, 2, 3}, 2, true},
{"absent", []int{1, 2, 3}, 4, false},
{"empty", []int{}, 0, false},
{"single-yes", []int{5}, 5, true},
{"single-no", []int{5}, 0, false},
{"first", []int{7, 8, 9}, 7, true},
{"last", []int{7, 8, 9}, 9, true},
{"duplicates", []int{2, 2, 2}, 2, true},
{"negative", []int{-1, -2, -3}, -2, true},
{"zero-absent", []int{-1, 1}, 0, false},
{"limit", []int{2147483647, math.MinInt32}, math.MinInt32, true},
{"limit-absent", []int{2147483647}, math.MinInt32, false},
}
func TestContains(t *testing.T) {
for _, c := range cases {
items0 := slices.Clone(c.items)
if got := Contains(c.items, c.value); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
if !slices.Equal(c.items, items0) {
t.Errorf("%s: the input changed", c.name)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
/// Returns true if some item of items is equal to value.
pub fn contains(items: &[i32], value: i32) -> bool {
// contains takes a reference to the value.
items.contains(&value)
}
tests/contains_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
use algo_check_whether_a_list_contains_a_value::contains;
#[test]
fn cases() {
let cases: &[(&str, &[i32], i32, bool)] = &[
("present", &[1, 2, 3], 2, true),
("absent", &[1, 2, 3], 4, false),
("empty", &[], 0, false),
("single-yes", &[5], 5, true),
("single-no", &[5], 0, false),
("first", &[7, 8, 9], 7, true),
("last", &[7, 8, 9], 9, true),
("duplicates", &[2, 2, 2], 2, true),
("negative", &[-1, -2, -3], -2, true),
("zero-absent", &[-1, 1], 0, false),
("limit", &[2147483647, i32::MIN], i32::MIN, true),
("limit-absent", &[2147483647], i32::MIN, false),
];
for &(name, items, value, want) in cases {
assert_eq!(contains(items, value), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
# contains VALUE ITEM...
# Returns 0 if one of the items is equal to VALUE as a string, and 1 if not.
contains() {
local value=$1 item
shift
for item in "$@"; do
# The quotes make the right side a string, not a pattern.
if [[ $item == "$value" ]]; then
return 0
fi
done
return 1
}
test_contains.bats 34 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/contains.sh"
}
check() { # check VALUE "ITEMS" WANT: WANT is yes or no
local -a items
read -r -a items <<<"$2"
if contains "$1" "${items[@]}"; then
[ "$3" = yes ]
else
[ "$3" = no ]
fi
}
@test "present" { check 2 "1 2 3" yes; }
@test "absent" { check 4 "1 2 3" no; }
@test "empty" { check 0 "" no; }
@test "single-yes" { check 5 "5" yes; }
@test "single-no" { check 0 "5" no; }
@test "first" { check 7 "7 8 9" yes; }
@test "last" { check 9 "7 8 9" yes; }
@test "duplicates" { check 2 "2 2 2" yes; }
@test "negative" { check -2 "-1 -2 -3" yes; }
@test "zero-absent" { check 0 "-1 1" no; }
@test "limit" { check -2147483648 "2147483647 -2147483648" yes; }
@test "limit-absent" { check -2147483648 "2147483647" no; }
@test "pattern" { if contains "*" a b; then return 1; fi; contains "*" a "*"; }
@test "spaces" { if contains York "New York" Paris; then return 1; fi; contains "New York" "New York" Paris; }
References
- The Python Language Reference, Expressions, 6.10.2 Membership test operations
- MDN Web Docs, Array.prototype.includes(), Description
- Java SE 25 API, Interface List, contains(Object o)
- .NET API reference, List<T>.Contains(T), Remarks
- Go standard library, package slices, func Contains and func ContainsFunc
- Rust standard library, Primitive Type slice, contains
- cppreference.com, std::ranges::contains, Description
- cppreference.com, std::find, Description
- Bash Reference Manual, 3.2.5.2 Conditional Constructs, [[...]]
- MDN Web Docs, Array.prototype.indexOf(), Description
- Java SE 25 API, Class Arrays, asList(T... a)
- C# language reference, Records, Value equality
- The Go Programming Language Specification, Comparison operators
- cppreference.com, strcmp, Return value
- cppreference.com, std::binary_search, Description
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 B5BWVX Edit this page History Report an error Markdown