OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Remove duplicate strings while preserving their first occurrence

Python

Deduplicate a bounded string list without changing its order, casing, whitespace or Unicode normalization.

Python code excerpt: Remove duplicate strings while preserving their first occurrence. Version 1.0.0. Read the full recipe for code, sources and recorded test scope.

Use this helper when preparing a small ordered list for an import or a local batch. The first occurrence of each exact string is kept and the removed count is returned. It compares string values directly, so visually similar strings can remain distinct.

Before you start

  • Python 3.12 standard library and the reviewed pinned runtime; no third-party packages.
  • One UTF-8 JSON request on stdin, at most 20000 encoded bytes. One extra byte may be read to detect overflow.
  • Use synthetic examples when sharing requests. The program does not read configuration files, environment variables or network services.

Build and check

  1. Save the downloaded source as remove-duplicate-strings-python.py.
  2. Save the example JSON request below as request.json.
  3. Run python3 remove-duplicate-strings-python.py < request.json.
  4. Compare stdout with the expected JSON. Exit 0 processes a valid request; invalid input exits 2 with empty stdout and a generic stderr message.

Limits to understand

  • The request must contain exactly values, an array of at most 1000 strings. Integers, null, objects and nested arrays are rejected.
  • Matching is exact. Case, leading/trailing whitespace, embedded newlines and Unicode normalization are preserved. For example, composed and decomposed accented text can remain distinct.
  • This is not identifier canonicalization, fuzzy matching, case-insensitive deduplication or a streaming processor for large files.
  • Duplicate JSON keys, non-finite numbers and unpaired Unicode surrogates are rejected. Input is bounded to 20000 UTF-8 bytes.

Run it

python3 remove-duplicate-strings-python.py < request.json

Example input

{"values":["alpha","beta","alpha","Alpha"]}

Expected output

{"values":["alpha","beta","Alpha"],"removed":1}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
import json
import math
import sys


def reject_constant(_):
    raise ValueError()


def parse_float(text):
    value = float(text)
    if not math.isfinite(value):
        raise ValueError()
    return value


def has_surrogate(text):
    return any(0xD800 <= ord(char) <= 0xDFFF for char in text)


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result or has_surrogate(key):
            raise ValueError()
        result[key] = value
    return result


def main():
    try:
        if len(sys.argv) != 1:
            raise ValueError()
        raw = sys.stdin.buffer.read(20001)
        if len(raw) > 20000:
            raise ValueError()
        text = raw.decode('utf-8', errors='strict')
        data = json.loads(
            text,
            object_pairs_hook=unique_object,
            parse_constant=reject_constant,
            parse_float=parse_float,
        )
        if type(data) is not dict or set(data) != {'values'}:
            raise ValueError()
        values = data['values']
        if type(values) is not list or len(values) > 1000:
            raise ValueError()
        seen = set()
        unique = []
        for value in values:
            if type(value) is not str or has_surrogate(value):
                raise ValueError()
            if value not in seen:
                seen.add(value)
                unique.append(value)
        output = json.dumps(
            {'values': unique, 'removed': len(values) - len(unique)},
            ensure_ascii=False,
            separators=(',', ':'),
            allow_nan=False,
        ).encode('utf-8')
    except Exception:
        sys.stderr.write('Invalid input\n')
        return 2
    sys.stdout.buffer.write(output)
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Run the documented example and compare its parsed JSON output.
  • Confirm invalid input exits 2 and does not echo request contents to stdout.
  • 30 independent CLI cases passed on the exact reviewed source in the pinned Python sandbox.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 1.0.0 · Documentation reviewed 2026-11-14.

    30 independent CLI cases passed in rootless Docker on the pinned Python 3.12 image, with 512 MiB RAM, 1 CPU and no network. Includes the documented example, malformed input, Unicode and the inclusive 20000-byte boundary. Other runtimes and all possible inputs have not been verified.