Download datasets/python_curriculum.jsonl from noah33565/Poloniu: direct link, hf CLI and curl.
- Browser
- Download file 6.12 kB
-
https://huggingface.co/spaces/noah33565/Poloniu/resolve/main/datasets/python_curriculum.jsonl
- Command line
-
hf download hf://spaces/noah33565/Poloniu/datasets/python_curriculum.jsonl
-
curl -L -o python_curriculum.jsonl https://huggingface.co/spaces/noah33565/Poloniu/resolve/main/datasets/python_curriculum.jsonl
6.12 kB
| {"messages":[{"role":"user","content":"Schreibe ein Python-CLI-Programm mit argparse, das eine Textdatei als UTF-8 liest und Zeilen, Wörter und Zeichen zählt. Trenne Berechnung und Datei-I/O und behandle Dateifehler."},{"role":"assistant","content":"Die reine Funktion `analyze` lässt sich unabhängig testen; `main` kümmert sich nur um Argumente und Datei-I/O.\n```python\nimport argparse\nfrom pathlib import Path\n\ndef analyze(text: str) -> dict[str, int]:\n return {\"lines\": len(text.splitlines()), \"words\": len(text.split()), \"characters\": len(text)}\n\ndef main() -> int:\n parser = argparse.ArgumentParser(description=\"Zählt Textmerkmale.\")\n parser.add_argument(\"file\", type=Path)\n args = parser.parse_args()\n try:\n result = analyze(args.file.read_text(encoding=\"utf-8\"))\n except (OSError, UnicodeDecodeError) as error:\n parser.error(f\"Datei kann nicht gelesen werden: {error}\")\n for name, count in result.items():\n print(f\"{name}: {count}\")\n return 0\n\nif __name__ == \"__main__\":\n raise SystemExit(main())\n```\nRandfall: `analyze(\"\")` gibt für alle drei Werte null zurück."}]} | |
| {"messages":[{"role":"user","content":"Mach aus `eval(input())` einen sicheren Python-Rechner. Unterstütze +, -, * und /, validiere Eingaben und verhindere Division durch null."},{"role":"assistant","content":"`eval` würde beliebigen Python-Code ausführen. Diese Lösung erlaubt nur vier Operatoren und meldet ungültige Eingaben gezielt.\n```python\ndef calculate(left: float, operator: str, right: float) -> float:\n operations = {\n \"+\": lambda: left + right,\n \"-\": lambda: left - right,\n \"*\": lambda: left * right,\n \"/\": lambda: left / right,\n }\n if operator not in operations:\n raise ValueError(\"Unbekannter Operator.\")\n if operator == \"/\" and right == 0:\n raise ZeroDivisionError(\"Division durch null.\")\n return operations[operator]()\n\ndef main() -> None:\n try:\n left = float(input(\"Erste Zahl: \"))\n operator = input(\"Operator (+, -, *, /): \" ).strip()\n right = float(input(\"Zweite Zahl: \"))\n print(f\"Ergebnis: {calculate(left, operator, right):g}\")\n except (ValueError, ZeroDivisionError) as error:\n print(f\"Fehler: {error}\")\n\nif __name__ == \"__main__\":\n main()\n```\nFür Geldbeträge wäre `decimal.Decimal` geeigneter als `float`."}]} | |
| {"messages":[{"role":"user","content":"Schreibe eine Python-Funktion, die Preise aus einer CSV-Spalte `price` liest. Fehlende Spalten und ungültige Zahlen sollen Fehler nennen; ergänze zwei pytest-Tests."},{"role":"assistant","content":"`DictReader` ermöglicht Zugriff über Spaltennamen. Ich prüfe den Header und gebe bei ungültigen Daten die CSV-Zeilennummer aus.\n```python\nimport csv\nfrom pathlib import Path\n\ndef read_prices(path: Path) -> list[float]:\n with path.open(encoding=\"utf-8\", newline=\"\") as file:\n reader = csv.DictReader(file)\n if not reader.fieldnames or \"price\" not in reader.fieldnames:\n raise ValueError(\"CSV benötigt die Spalte 'price'.\")\n prices = []\n for line, row in enumerate(reader, start=2):\n try:\n prices.append(float(row[\"price\"]))\n except (TypeError, ValueError) as error:\n raise ValueError(f\"Ungültiger Preis in Zeile {line}.\") from error\n return prices\n```\n```python\n# test_prices.py\nimport pytest\nfrom prices import read_prices\n\ndef test_reads_prices(tmp_path):\n path = tmp_path / \"prices.csv\"\n path.write_text(\"price\\n2.5\\n4\\n\", encoding=\"utf-8\")\n assert read_prices(path) == [2.5, 4.0]\n\ndef test_missing_column(tmp_path):\n path = tmp_path / \"prices.csv\"\n path.write_text(\"name\\nTea\\n\", encoding=\"utf-8\")\n with pytest.raises(ValueError, match=\"price\"):\n read_prices(path)\n```\nAusführen mit `pytest -q`."}]} | |
| {"messages":[{"role":"user","content":"Entwirf eine robuste Python-Funktion, die Dateien mit einer Endung rekursiv findet, versteckte Ordner überspringt und Fehler beim Zugriff meldet."},{"role":"assistant","content":"`os.walk` erlaubt, versteckte Ordner vor dem Abstieg aus der Verzeichnisliste zu entfernen. Das Ergebnis wird sortiert, damit die Ausgabe reproduzierbar ist.\n```python\nimport os\nfrom pathlib import Path\n\ndef find_files(root: Path, suffix: str) -> list[Path]:\n if not root.is_dir():\n raise NotADirectoryError(f\"Kein Ordner: {root}\")\n if not suffix.startswith(\".\"):\n raise ValueError(\"Die Endung muss mit einem Punkt beginnen.\")\n found: list[Path] = []\n def report_error(error: OSError) -> None:\n print(f\"Übersprungen: {error.filename}: {error.strerror}\")\n for folder, directories, filenames in os.walk(root, onerror=report_error):\n directories[:] = [name for name in directories if not name.startswith(\".\")]\n for filename in filenames:\n path = Path(folder) / filename\n if path.suffix.casefold() == suffix.casefold():\n found.append(path)\n return sorted(found)\n```\nBeispiel: `find_files(Path(\".\"), \".py\")`. Für sehr große Ordner kann man die Liste später durch einen Iterator ersetzen."}]} | |
| {"messages":[{"role":"user","content":"Ich bekomme `TypeError: unsupported operand type(s) for +: 'int' and 'str'`. Wie finde ich die Ursache und behebe sie, statt den Fehler zu verstecken?"},{"role":"assistant","content":"`input()` und CSV-Werte sind zunächst Text. Wandle den Wert an der Eingabegrenze um und validiere ihn dort; `str(total)` wäre falsch, wenn du rechnen möchtest.\n```python\ndef parse_count(raw: str) -> int:\n try:\n value = int(raw.strip())\n except ValueError as error:\n raise ValueError(f\"Anzahl muss eine ganze Zahl sein: {raw!r}\") from error\n if value < 0:\n raise ValueError(\"Anzahl darf nicht negativ sein.\")\n return value\n\ntotal = 0\ntotal += parse_count(input(\"Anzahl: \"))\nprint(total)\n```"}]} |