├── .coveragerc
├── .deepsource.toml
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ └── build.yml
├── .gitignore
├── .pre-commit-config.yaml
├── LICENSE
├── README.md
├── docs
├── assess_costs.html
├── cli.html
├── cli_collect.html
├── cli_recommend.html
├── cli_tag.html
├── compare_spans.html
├── derived_labels_db.html
├── developer_manual
│ └── index.html
├── filter_programs.html
├── flatten_ast.html
├── goodies.html
├── index.html
├── label_programs.html
├── list_programs.html
├── make_db.html
├── map_taxonomy.html
├── md
│ ├── about.md
│ ├── bird_view.md
│ ├── databases.md
│ ├── foreword_user.md
│ ├── glossary.md
│ ├── helpers.md
│ ├── implementation_notes.md
│ ├── pipeline_documentation.md
│ ├── pipeline_tutorial.md
│ ├── preparing.md
│ └── taxonomy.md
├── normalize_predicate.html
├── parse_program.html
├── pdoc_template
│ ├── config.mako
│ ├── credits.mako
│ ├── head.mako
│ └── logo.mako
├── preprocess_source.html
├── recommend_programs.html
├── resources
│ ├── fibonacci.py
│ ├── filter_flow.png
│ ├── flow.png
│ ├── logo.png
│ ├── source_on_github.png
│ ├── sql_query_example.png
│ ├── tree.js
│ ├── tree.png
│ └── waterfall.png
└── user_manual
│ └── index.html
├── examples
├── dummy
│ ├── pipe.py
│ ├── programs_db.json
│ ├── programs_recommendations.md
│ ├── read_me.md
│ ├── syllabus.txt
│ └── taxa_and_programs.txt
├── idioms
│ ├── programs
│ │ ├── 001.0003-print-hello-world.py
│ │ ├── 001.1159-print-hello-world.py
│ │ ├── 002.0011-print-hello-10-times.py
│ │ ├── 002.1493-print-hello-10-times.py
│ │ ├── 002.3117-print-hello-10-times.py
│ │ ├── 003.0019-create-a-procedure.py
│ │ ├── 003.2372-create-a-procedure.py
│ │ ├── 004.0024-create-a-function-which-returns-the-square-of-an-integer.py
│ │ ├── 004.2921-create-a-function-which-returns-the-square-of-an-integer.py
│ │ ├── 005.0663-create-a-2d-point-data-structure.py
│ │ ├── 006.0032-iterate-over-list-values.py
│ │ ├── 007.0183-iterate-over-list-indexes-and-values.py
│ │ ├── 008.0039-initialize-a-new-map-associative-array.py
│ │ ├── 009.1410-create-a-binary-tree-data-structure.py
│ │ ├── 009.3176-create-a-binary-tree-data-structure.py
│ │ ├── 010.0182-shuffle-a-list.py
│ │ ├── 010.1478-shuffle-a-list.py
│ │ ├── 011.0047-pick-a-random-element-from-a-list.py
│ │ ├── 012.0181-check-if-list-contains-a-value.py
│ │ ├── 013.0574-iterate-over-map-keys-and-values.py
│ │ ├── 014.0185-pick-uniformly-a-random-floating-point-number-in-ab.py
│ │ ├── 014.3410-pick-uniformly-a-random-floating-point-number-in-ab.py
│ │ ├── 015.0184-pick-uniformly-a-random-integer-in-ab.py
│ │ ├── 016.1530-depth-first-traversing-of-a-binary-tree.py
│ │ ├── 017.1103-create-a-tree-data-structure.py
│ │ ├── 018.2084-depth-first-traversing-of-a-tree.py
│ │ ├── 019.0197-reverse-a-list.py
│ │ ├── 019.1983-reverse-a-list.py
│ │ ├── 019.3164-reverse-a-list.py
│ │ ├── 020.0573-return-two-values.py
│ │ ├── 021.0084-swap-values-of-variables-a-and-b.py
│ │ ├── 022.0243-convert-string-to-integer.py
│ │ ├── 023.1102-convert-real-number-to-string-with-2-decimal-places.py
│ │ ├── 024.0664-assign-to-string-the-japanese-word-.py
│ │ ├── 025.0195-send-a-value-to-another-thread.py
│ │ ├── 026.0194-create-a-2-dimensional-array.py
│ │ ├── 027.0192-create-a-3-dimensional-array.py
│ │ ├── 027.0193-create-a-3-dimensional-array.py
│ │ ├── 028.0350-sort-by-a-property.py
│ │ ├── 029.0199-remove-item-from-list-by-its-index.py
│ │ ├── 030.0189-parallelize-execution-of-1000-independent-tasks.py
│ │ ├── 031.0188-recursive-factorial-simple.py
│ │ ├── 032.0196-integer-exponentiation-by-squaring.py
│ │ ├── 033.1420-atomically-read-and-update-variable.py
│ │ ├── 034.0625-create-a-set-of-objects.py
│ │ ├── 035.0667-first-class-function--compose.py
│ │ ├── 036.0670-first-class-function--generic-composition.py
│ │ ├── 037.0671-currying.py
│ │ ├── 038.0186-extract-a-substring.py
│ │ ├── 039.0571-check-if-string-contains-a-word.py
│ │ ├── 040.2279-graph-with-adjacency-lists.py
│ │ ├── 041.0187-reverse-a-string.py
│ │ ├── 041.2714-reverse-a-string.py
│ │ ├── 042.1264-continue-outer-loop.py
│ │ ├── 042.3168-continue-outer-loop.py
│ │ ├── 043.0676-break-outer-loop.py
│ │ ├── 043.2733-break-outer-loop.py
│ │ ├── 044.0190-insert-element-in-list.py
│ │ ├── 045.0570-pause-execution-for-5-seconds.py
│ │ ├── 046.0191-extract-beginning-of-string-prefix.py
│ │ ├── 047.0198-extract-string-suffix.py
│ │ ├── 048.0210-multi-line-string-literal.py
│ │ ├── 049.0242-split-a-space-separated-string.py
│ │ ├── 050.0572-make-an-infinite-loop.py
│ │ ├── 051.0230-check-if-map-contains-key.py
│ │ ├── 052.0666-check-if-map-contains-value.py
│ │ ├── 053.0240-join-a-list-of-strings.py
│ │ ├── 053.1933-join-a-list-of-strings.py
│ │ ├── 054.0241-compute-sum-of-integers.py
│ │ ├── 055.0575-convert-integer-to-string.py
│ │ ├── 056.1424-launch-1000-parallel-tasks-and-wait-for-completion.py
│ │ ├── 057.0260-filter-list.py
│ │ ├── 057.3173-filter-list.py
│ │ ├── 058.0665-extract-file-content-to-a-string.py
│ │ ├── 059.0668-write-to-standard-error-stream.py
│ │ ├── 060.1084-read-command-line-argument.py
│ │ ├── 061.0576-get-current-date.py
│ │ ├── 062.1091-find-substring-position.py
│ │ ├── 063.1088-replace-fragment-of-a-string.py
│ │ ├── 064.0274-big-integer--value-3-power-247.py
│ │ ├── 065.1085-format-decimal-number.py
│ │ ├── 066.0672-big-integer-exponentiation.py
│ │ ├── 067.1426-binomial-coefficient-n-choose-k.py
│ │ ├── 068.2271-create-a-bitset.py
│ │ ├── 069.1086-seed-random-generator.py
│ │ ├── 070.1087-use-clock-as-random-generator-seed.py
│ │ ├── 071.0379-echo-program-implementation.py
│ │ ├── 073.0673-create-a-factory.py
│ │ ├── 074.0674-compute-gcd.py
│ │ ├── 075.0675-compute-lcm.py
│ │ ├── 076.1083-binary-digits-from-an-integer.py
│ │ ├── 077.1093-complex-number.py
│ │ ├── 078.1089-do-while-loop.py
│ │ ├── 079.1090-convert-integer-to-floating-point-number.py
│ │ ├── 080.1092-truncate-floating-point-number-to-integer.py
│ │ ├── 081.2270-round-floating-point-number-to-integer.py
│ │ ├── 082.1096-count-substring-occurrences.py
│ │ ├── 083.1805-regex-with-character-repetition.py
│ │ ├── 084.1940-count-bits-set-in-integer-binary-representation.py
│ │ ├── 085.1003-check-if-integer-addition-will-overflow.py
│ │ ├── 086.1004-check-if-integer-multiplication-will-overflow.py
│ │ ├── 087.1139-stop-program.py
│ │ ├── 088.2143-allocate-1m-bytes.py
│ │ ├── 089.1097-handle-invalid-argument.py
│ │ ├── 090.1099-read-only-outside.py
│ │ ├── 091.1098-load-json-file-into-struct.py
│ │ ├── 092.1100-save-object-into-json-file.py
│ │ ├── 093.1082-pass-a-runnable-procedure-as-parameter.py
│ │ ├── 094.1101-print-type-of-variable.py
│ │ ├── 094.1864-print-type-of-variable.py
│ │ ├── 095.2140-get-file-size.py
│ │ ├── 096.1094-check-string-prefix.py
│ │ ├── 097.1095-check-string-suffix.py
│ │ ├── 098.2142-epoch-seconds-to-date-object.py
│ │ ├── 099.1429-format-date-yyyy-mm-dd.py
│ │ ├── 099.2693-format-date-yyyy-mm-dd.py
│ │ ├── 100.1142-sort-by-a-comparator.py
│ │ ├── 101.2172-load-from-http-get-request-into-a-string.py
│ │ ├── 102.2173-load-from-http-get-request-into-a-file.py
│ │ ├── 103.2276-load-xml-file-into-struct.py
│ │ ├── 104.3264-save-object-into-xml-file.py
│ │ ├── 105.1804-current-executable-name.py
│ │ ├── 106.2039-get-program-working-directory.py
│ │ ├── 107.2139-get-folder-containing-current-program.py
│ │ ├── 108.1291-determine-if-variable-name-is-defined.py
│ │ ├── 109.2280-number-of-bytes-of-a-type.py
│ │ ├── 110.1455-check-if-string-is-blank.py
│ │ ├── 111.2168-launch-other-program.py
│ │ ├── 112.2144-iterate-over-map-entries-ordered-by-keys.py
│ │ ├── 113.2157-iterate-over-map-entries-ordered-by-values.py
│ │ ├── 114.2273-test-deep-equality.py
│ │ ├── 115.2138-compare-dates.py
│ │ ├── 116.1257-remove-occurrences-of-word-from-string.py
│ │ ├── 117.1297-get-list-size.py
│ │ ├── 118.1254-list-to-set.py
│ │ ├── 118.3266-list-to-set.py
│ │ ├── 119.1253-deduplicate-list.py
│ │ ├── 119.3263-deduplicate-list.py
│ │ ├── 120.1479-read-integer-from-stdin.py
│ │ ├── 121.3029-udp-listen-and-read.py
│ │ ├── 122.1453-declare-enumeration.py
│ │ ├── 122.1454-declare-enumeration.py
│ │ ├── 123.2146-assert-condition.py
│ │ ├── 124.2152-binary-search-for-a-value-in-sorted-array.py
│ │ ├── 125.2167-measure-function-call-duration.py
│ │ ├── 126.2137-multiple-return-values.py
│ │ ├── 127.2274-source-code-inclusion.py
│ │ ├── 128.2085-breadth-first-traversing-of-a-tree.py
│ │ ├── 129.2282-breadth-first-traversing-in-a-graph.py
│ │ ├── 130.2283-depth-first-traversing-in-a-graph.py
│ │ ├── 131.2083-successive-conditions.py
│ │ ├── 131.2766-successive-conditions.py
│ │ ├── 132.2040-measure-duration-of-procedure-execution.py
│ │ ├── 133.2160-case-insensitive-string-contains.py
│ │ ├── 134.1850-create-a-new-list.py
│ │ ├── 135.2158-remove-item-from-list-by-its-value.py
│ │ ├── 136.2141-remove-all-occurrences-of-a-value-from-a-list.py
│ │ ├── 137.1823-check-if-string-contains-only-digits.py
│ │ ├── 138.2161-create-temp-file.py
│ │ ├── 139.2162-create-temp-directory.py
│ │ ├── 140.2156-delete-map-entry.py
│ │ ├── 141.2159-iterate-in-sequence-over-two-lists.py
│ │ ├── 142.2151-hexadecimal-digits-of-an-integer.py
│ │ ├── 143.2256-iterate-alternatively-over-two-lists.py
│ │ ├── 144.2145-check-if-file-exists.py
│ │ ├── 144.2915-check-if-file-exists.py
│ │ ├── 145.1822-print-log-line-with-datetime.py
│ │ ├── 146.1825-convert-string-to-floating-point-number.py
│ │ ├── 146.1826-convert-string-to-floating-point-number.py
│ │ ├── 146.2739-convert-string-to-floating-point-number.py
│ │ ├── 147.2171-remove-all-non-ascii-characters.py
│ │ ├── 148.1829-read-list-of-integer-numbers-from-stdin.py
│ │ ├── 150.2154-remove-trailing-slash.py
│ │ ├── 151.2166-remove-string-trailing-path-separator.py
│ │ ├── 152.2153-turn-a-character-into-a-string.py
│ │ ├── 153.1980-concatenate-string-with-integer.py
│ │ ├── 154.2155-halfway-between-two-hex-color-codes.py
│ │ ├── 154.2292-halfway-between-two-hex-color-codes.py
│ │ ├── 155.2147-delete-file.py
│ │ ├── 156.2148-format-integer-with-zero-padding.py
│ │ ├── 157.2150-declare-constant-string.py
│ │ ├── 158.2163-random-sublist.py
│ │ ├── 159.2281-trie.py
│ │ ├── 160.2165-detect-if-32-bit-or-64-bit-architecture.py
│ │ ├── 161.2098-multiply-all-the-elements-of-a-list.py
│ │ ├── 162.2164-execute-procedures-depending-on-options.py
│ │ ├── 163.2170-print-list-elements-by-group-of-2.py
│ │ ├── 163.3177-print-list-elements-by-group-of-2.py
│ │ ├── 164.2169-open-url-in-default-browser.py
│ │ ├── 165.2149-last-element-of-list.py
│ │ ├── 166.2272-concatenate-two-lists.py
│ │ ├── 167.2611-trim-prefix.py
│ │ ├── 167.3175-trim-prefix.py
│ │ ├── 168.2277-trim-suffix.py
│ │ ├── 168.3174-trim-suffix.py
│ │ ├── 169.2233-string-length.py
│ │ ├── 170.2275-get-map-size.py
│ │ ├── 171.2446-add-an-element-at-the-end-of-a-list.py
│ │ ├── 172.2442-insert-entry-in-map.py
│ │ ├── 173.2427-format-a-number-with-grouped-thousands.py
│ │ ├── 173.2428-format-a-number-with-grouped-thousands.py
│ │ ├── 173.2429-format-a-number-with-grouped-thousands.py
│ │ ├── 174.2687-make-http-post-request.py
│ │ ├── 175.2613-bytes-to-hex-string.py
│ │ ├── 176.2614-hex-string-to-byte-array.py
│ │ ├── 177.2709-find-files-with-a-given-list-of-filename-extensions.py
│ │ ├── 177.2725-find-files-with-a-given-list-of-filename-extensions.py
│ │ ├── 177.3241-find-files-with-a-given-list-of-filename-extensions.py
│ │ ├── 178.2615-check-if-point-is-inside-rectangle.py
│ │ ├── 179.2688-get-center-of-a-rectangle.py
│ │ ├── 179.2689-get-center-of-a-rectangle.py
│ │ ├── 180.2612-list-files-in-directory.py
│ │ ├── 182.2658-quine-program.py
│ │ ├── 183.3025-make-http-put-request.py
│ │ ├── 184.2701-tomorrow.py
│ │ ├── 185.2820-execute-function-in-30-seconds.py
│ │ ├── 186.2699-exit-program-cleanly.py
│ │ ├── 187.3261-disjoint-set.py
│ │ ├── 188.3171-matrix-multiplication.py
│ │ ├── 188.3284-matrix-multiplication.py
│ │ ├── 189.3236-filter-and-transform-list.py
│ │ ├── 191.3403-check-if-any-value-in-a-list-is-larger-than-a-limit.py
│ │ └── 197.3457-get-a-list-of-lines-from-a-file.py
│ ├── programs_db.json
│ ├── programs_recommendations.md
│ ├── programs_with_labels.py
│ └── read_me.md
├── mini
│ ├── labelled_programs.json
│ ├── labelled_sources.py
│ ├── labels.md
│ ├── programs
│ │ ├── assignment.py
│ │ ├── collatz.py
│ │ ├── fizzbuzz.py
│ │ └── is_even.py
│ ├── programs_db.json
│ ├── programs_with_labels.py
│ ├── read_me.md
│ ├── taxa.json
│ └── taxonomy.tsv
└── simple
│ ├── programs
│ ├── 01_hello_world.py
│ ├── 02_input_name.py
│ ├── 03_friends.py
│ ├── 04_fibonacci.py
│ ├── 05_greet.py
│ ├── 06_regex.py
│ ├── 07_grocery_bill.py
│ ├── 08_arguments.py
│ ├── 09_indent.py
│ ├── 10_time.py
│ ├── 11_bottles.py
│ ├── 12_classes.py
│ ├── 13_unit_testing.py
│ ├── 14_median.py
│ ├── 15_itertools_groupby.py
│ ├── 16_csv.py
│ ├── 18_queens.py
│ ├── 20_prime_numbers.py
│ ├── 21_xml_html_parsing.py
│ ├── 28_queens.py
│ └── 33_guess_the_number.py
│ ├── programs_db.json
│ ├── programs_pipe.py
│ ├── programs_recommendations.md
│ ├── programs_with_labels.py
│ └── read_me.md
├── helpers
├── __init__.py
├── build_pdoc.py
├── context.py
├── draw_flow.py
├── dump_flat_asts.py
├── example.sql
├── make_compare_spans.py
├── make_dummy_db.py
├── make_programming_idioms_folder.py
├── parse_source.py
├── parse_syllabus.py
├── reformat_spec.py
├── suggest_regex.py
└── update_tree.py
├── paroxython
├── __init__.py
├── assess_costs.py
├── cli.py
├── cli_collect.py
├── cli_recommend.py
├── cli_tag.py
├── compare_spans.py
├── derived_labels_db.py
├── filter_programs.py
├── flatten_ast.py
├── goodies.py
├── label_programs.py
├── list_programs.py
├── make_db.py
├── map_taxonomy.py
├── normalize_predicate.py
├── parse_program.py
├── preprocess_source.py
├── recommend_programs.py
├── resources
│ ├── spec.md
│ └── taxonomy.tsv
└── user_types.py
├── poetry.lock
├── pyproject.toml
├── requirements.txt
└── tests
├── context.py
├── make_snapshot.py
├── test_assess_costs.py
├── test_centrifugate_hints.py
├── test_cleanup_source.py
├── test_cli.py
├── test_collect_hints.py
├── test_filter_programs.py
├── test_filter_programs_with_import.py
├── test_filter_programs_with_triples.py
├── test_flatten_ast.py
├── test_goodies.py
├── test_label_programs.py
├── test_list_programs.py
├── test_make_db.py
├── test_map_taxonomy.py
├── test_normalize_predicate.py
├── test_parse_program.py
├── test_recommend_programs.py
└── test_suggest_regex.py
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | omit =
3 | helpers/context.py
4 | helpers/draw_flow.py
5 | helpers/dump_flat_asts.py
6 | helpers/build_pdoc.py
7 | helpers/make_dummy_db.py
8 | helpers/make_compare_spans.py
9 | helpers/reformat_spec.py
10 | helpers/make_programming_idioms_folder.py
11 | helpers/update_tree.py
12 | helpers/parse_source.py
13 | paroxython/__init__.py
14 | paroxython/make_snapshots.py
15 | paroxython/compare_spans.py
16 | tests/*
17 | examples/*
18 | [report]
19 | exclude_lines =
20 | pragma: no cover
21 | if __name__ == .__main__.:
22 | def __repr__
23 | raise NotImplementedError
24 |
--------------------------------------------------------------------------------
/.deepsource.toml:
--------------------------------------------------------------------------------
1 | version = 1
2 |
3 | [[analyzers]]
4 | name = "python"
5 | enabled = true
6 |
7 | [analyzers.meta]
8 | runtime_version = "3.x.x"
9 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: build
2 | on:
3 | push:
4 | branches:
5 | - master
6 | pull_request:
7 | branches:
8 | - master
9 | jobs:
10 | build:
11 | runs-on: '${{ matrix.os }}'
12 | strategy:
13 | matrix:
14 | os:
15 | - ubuntu-18.04
16 | python-version:
17 | - '3.8'
18 | - '3.9'
19 | - '3.10'
20 | steps:
21 | - name: 'Set up Python ${{ matrix.python-version }}'
22 | uses: actions/setup-python@v2
23 | with:
24 | python-version: '${{ matrix.python-version }}'
25 | - uses: actions/checkout@v2
26 | - run: pip install -r requirements.txt
27 | - run: pip install pytest pytest-cov
28 | - run: pip install coverage
29 | - run: pytest --cov=./
30 | - run: 'bash <(curl -s https://codecov.io/bash)'
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | .hypothesis/
51 | .pytest_cache/
52 |
53 | # Translations
54 | *.mo
55 | *.pot
56 |
57 | # Django stuff:
58 | *.log
59 | local_settings.py
60 | db.sqlite3
61 |
62 | # Flask stuff:
63 | instance/
64 | .webassets-cache
65 |
66 | # Scrapy stuff:
67 | .scrapy
68 |
69 | # Sphinx documentation
70 | docs/_build/
71 |
72 | # PyBuilder
73 | target/
74 |
75 | # Jupyter Notebook
76 | .ipynb_checkpoints
77 |
78 | # IPython
79 | profile_default/
80 | ipython_config.py
81 |
82 | # pyenv
83 | .python-version
84 |
85 | # pipenv
86 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
87 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
88 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
89 | # install all needed dependencies.
90 | #Pipfile.lock
91 |
92 | # celery beat schedule file
93 | celerybeat-schedule
94 |
95 | # SageMath parsed files
96 | *.sage.py
97 |
98 | # Environments
99 | .env
100 | .venv
101 | env/
102 | venv/
103 | ENV/
104 | env.bak/
105 | venv.bak/
106 |
107 | # Spyder project settings
108 | .spyderproject
109 | .spyproject
110 |
111 | # Rope project settings
112 | .ropeproject
113 |
114 | # mkdocs documentation
115 | /site
116 |
117 | # mypy
118 | .mypy_cache/
119 | .dmypy.json
120 | dmypy.json
121 |
122 | # Pyre type checker
123 | .pyre/
124 |
125 | # Personal
126 | draft.*
127 | sandbox/
128 | .DS_Store
129 | db.sqlite
130 | *_db.sqlite
131 | helpers/programming-idioms.org.2019-09-28_23-33.json
132 | .vscode/launch.json
133 | html/*
134 | .vscode/settings.json
135 | paroxython/user_manual/*
136 | paroxython/developer_manual/*
137 | paroxython_db.json
138 | paroxython_recommendations.md
139 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | # See https://pre-commit.com for more information
2 | # See https://pre-commit.com/hooks.html for more hooks
3 | repos:
4 | - repo: https://github.com/pre-commit/pre-commit-hooks
5 | rev: v3.2.0
6 | hooks:
7 | - id: trailing-whitespace
8 | exclude: paroxython/resources/spec.md|examples/*
9 | - id: end-of-file-fixer
10 | exclude: docs/.*\.html|examples/*
11 | - id: check-yaml
12 | - id: check-added-large-files
13 | - id: check-json
14 | - id: requirements-txt-fixer
15 | - repo: https://github.com/asottile/pyupgrade
16 | rev: v2.7.2
17 | hooks:
18 | - id: pyupgrade
19 | - repo: https://github.com/psf/black
20 | rev: 22.8.0
21 | hooks:
22 | - id: black
23 | exclude: examples/*|docs/resources/fibonacci.py
24 | args: [--line-length=100]
25 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 laowantong
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/docs/md/about.md:
--------------------------------------------------------------------------------
1 | # About
2 |
3 | ## What's in a name?
4 |
5 | Far from being an arbitrary label, “Paroxython” has been scientifically formulated by an independent laboratory to possess the following properties:
6 |
7 | 1. It features both “Python” and “taxon”.
8 | 2. It provides a future-proof template for adaptations to other languages (Carox, Jaroxava, JaroxavaScript, Garoxo, Laroxua, Ocaroxaml, Haroxaskell, etc.) or fields of knowledge (Haroxarmony, Garoxeography, Maroxagnetohydrodynamics, etc.).
9 | 3. “Paroxytone” denotes a word accented or stressed on the penult[^paroxytone] and translates as “paroxyton” in [my mother tongue](https://youtu.be/M9DCAFUerzs).
10 |
11 | [^paroxytone]:
12 | “paroxytone,” Merriam-Webster.com Dictionary, https://www.merriam-webster.com/dictionary/paroxytone. Accessed 8/7/2020.
13 |
14 |
15 | ## Citing this work
16 |
17 | ```bibtex
18 | @manual{,
19 | title = {Paroxython: Tag and Recommend Python Exercises Based on Algorithmic Features},
20 | author = {{Aristide Grange}},
21 | organization = {Université de Lorraine},
22 | address = {Metz, France},
23 | year = {2020},
24 | url = {https://laowantong.github.io/paroxython/},
25 | }
26 | ```
27 |
28 | ## Collaborating
29 |
30 | Paroxython is on [GitHub](https://github.com/laowantong/paroxython) and welcomes your [issues](https://github.com/laowantong/paroxython/issues) or [pull requests](https://github.com/laowantong/paroxython/pulls). You may:
31 |
32 | - contribute to the code;
33 | - add new features in `spec.md`;
34 | - submit your personal changes to `taxonomy.tsv` for integration in the default taxonomy;
35 | - translate some of this documentation into English.
36 |
37 | If you use Paroxython for your programming course, I would love to get your feedback. If you're a researcher and interested in a scientific collaboration, drop an email to my dot-separated name (cf. previous section) at `univ-lorraine.fr`.
38 |
--------------------------------------------------------------------------------
/docs/md/foreword_user.md:
--------------------------------------------------------------------------------
1 | # How to read this manual
2 |
3 | The different sections of this manual are presented in the theoretical order of operations: you start by preparing your collection of programs, these programs are labeled, these labels are translated into taxa, the results are stored in a database; finally, you filter this database through a command pipeline to extract recommendations.
4 |
5 | In practice, your input is only required for the last stage. That's why we suggest you observe the following order:
6 |
7 | 1. Start by reading the [pipeline tutorial](#pipeline-tutorial): it explains, in a user-friendly style, what you can expect from Paroxython and how you may integrate it into your teaching.
8 | 2. Once you are familiar with this aspect, see if you can improve or enrich the results through some [preparation of the programs in your collection](#preparing-your-program-collection).
9 | 3. If needed, adapt the default [taxonomy](#taxonomy) to your own vision of how to teach programming.
10 | 4. Harness the [full power of the pipeline](#pipeline-documentation) with its most advanced commands.
11 |
12 | Of course, you can consult at any time the [glossary](#glossary) of terms specific to Paroxython.
13 |
--------------------------------------------------------------------------------
/docs/md/implementation_notes.md:
--------------------------------------------------------------------------------
1 | # Implementation notes
2 |
3 | ## User types
4 |
5 | Paroxython makes heavy use of Python 3.5+ [type hints](https://docs.python.org/3/library/typing.html). They are documented directly in [user_types.py](https://repo/paroxython/user_types.py).
6 |
7 | ## Default argument trick
8 |
9 | Several functions or methods declare a compiled and bound regex pattern as an optional argument (see `paroxython.normalize_predicate.normalize_predicate` for an example). Such arguments are not meant to be provided by the caller. Their default value will be used systematically, with the benefit of being evaluated only once. This is arguably better for both performance and encapsulation. More details on [Stack Overflow](https://stackoverflow.com/a/30688691/173003).
10 |
--------------------------------------------------------------------------------
/docs/pdoc_template/config.mako:
--------------------------------------------------------------------------------
1 | <%!
2 | git_link_template = 'https://github.com/laowantong/paroxython/blob/master/{path}#L{start_line}-L{end_line}'
3 | sort_identifiers = False
4 | %>
5 |
--------------------------------------------------------------------------------
/docs/pdoc_template/credits.mako:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/pdoc_template/credits.mako
--------------------------------------------------------------------------------
/docs/pdoc_template/head.mako:
--------------------------------------------------------------------------------
1 | <%!
2 | from pdoc.html_helpers import minify_css
3 | %>
4 | <%def name="homelink()" filter="minify_css">
5 | .homelink {
6 | display: block;
7 | }
8 | .homelink:hover {
9 | color: inherit;
10 | }
11 | .homelink img {
12 | margin: auto;
13 | margin-bottom: .3em;
14 | }
15 | %def>
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/docs/pdoc_template/logo.mako:
--------------------------------------------------------------------------------
1 |
6 |
--------------------------------------------------------------------------------
/docs/resources/fibonacci.py:
--------------------------------------------------------------------------------
1 | %%paroxython
2 | def fibonacci(n):
3 | result = []
4 | (a, b) = (0, 1)
5 | while a < n:
6 | result.append(a)
7 | (a, b) = (b, a + b)
8 | return result
9 |
--------------------------------------------------------------------------------
/docs/resources/filter_flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/resources/filter_flow.png
--------------------------------------------------------------------------------
/docs/resources/flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/resources/flow.png
--------------------------------------------------------------------------------
/docs/resources/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/resources/logo.png
--------------------------------------------------------------------------------
/docs/resources/source_on_github.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/resources/source_on_github.png
--------------------------------------------------------------------------------
/docs/resources/sql_query_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/resources/sql_query_example.png
--------------------------------------------------------------------------------
/docs/resources/tree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/resources/tree.png
--------------------------------------------------------------------------------
/docs/resources/waterfall.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/docs/resources/waterfall.png
--------------------------------------------------------------------------------
/examples/dummy/pipe.py:
--------------------------------------------------------------------------------
1 | [
2 | {}, # no operation nor data
3 | {"operation": "foobar"}, # unknown operation
4 | {"operation": "exclude"}, # no data
5 | {"operation": "exclude", "data": []}, # empty data
6 | {"operation": "impart", "data": "python helpers/parse_syllabus.py {base_path}/syllabus.txt"},
7 | {"operation": "exclude", "data": ["prg7.py", "prg9.py"]},
8 | {"operation": "exclude", "data": ["X/S/M/L/R/D/.*"]},
9 | {"operation": "include", "data": ["O/C.*"]},
10 | {"operation": "hide", "data": ["O/C/H/B"]},
11 | ]
12 |
--------------------------------------------------------------------------------
/examples/dummy/read_me.md:
--------------------------------------------------------------------------------
1 | # False programs created for testing purposes
2 |
3 | The following files are generated by `helpers/make_dummy_db.py`:
4 |
5 | - `programs_db.json`
6 | - `taxa_and_programs.txt`
7 |
8 | The following files were written manually:
9 |
10 | - `pipe.py`
11 | - `syllabus.txt`
12 | - `taxonomy.tsv`
13 |
14 | All remaining files updated during the test execution.
15 |
--------------------------------------------------------------------------------
/examples/dummy/syllabus.txt:
--------------------------------------------------------------------------------
1 | This is an example of syllabus.
2 |
3 | The Python programs already that have already been studied are prefixed by a + symbol.
4 |
5 | For instance, + prg8.py has been studied, but prg7.py has not.
6 |
7 | # EOF marks the end of the useful section.
8 |
9 | Consequentely, + prg6.py is not marked as studied.
10 |
--------------------------------------------------------------------------------
/examples/dummy/taxa_and_programs.txt:
--------------------------------------------------------------------------------
1 | TAXONS
2 | O
3 | O/C
4 | O/C/F
5 | O/C/F/U
6 | O/C/H
7 | O/C/H/B
8 | O/C/H/B/I
9 | O/J
10 | O/N
11 | O/N/P
12 | X
13 | X/G
14 | X/K
15 | X/S
16 | X/S/M
17 | X/S/M/L
18 | X/S/M/L/R
19 | X/S/M/L/R/D
20 | X/S/M/L/R/D/A
21 | X/S/M/L/V
22 | X/W
23 | Y
24 | Y/E
25 | Y/T
26 | Y/T/Q
27 |
28 | PROGRAMS
29 | prg1.py
30 | 1 X/W+7 X/S
31 | 2 X+1 Y/T X/S/M
32 | 3 X/W X/S/M/L/R
33 | 4 X/S+5 Y/T/Q
34 | 5 O/N/P
35 | 6 O/J X/S/M/L/R/D X/S/M/L+2
36 | 7 Y
37 | 8 O/N X/S/M/L/R/D O/J
38 | 9 X/S X/K
39 |
40 | prg2.py
41 | 1 O/N/P Y/T/Q Y
42 | 2 X/S/M/L/R/D O
43 | 3 O/C/H/B X/S/M/L/R/D
44 | 4
45 | 5
46 | 6 X/S/M O
47 | 7 X/S/M/L/R Y/T O/C
48 | 8 X/G X/S/M/L/V+1
49 | 9 X/S/M/L/R/D X/S/M/L/V Y/T/Q O/C/H/B/I
50 |
51 | prg3.py
52 | 1 O/N/P X/K Y/T
53 | 2 X/S/M/L/V
54 | 3 O/C/H/B
55 | 4 X/S/M/L/R+4
56 | 5 O/J X/S/M O/C/F/U O/C/H
57 | 6 O/N/P X/S Y
58 | 7 O
59 | 8 X/S/M/L Y/E
60 | 9 O/C/H/B O/J
61 |
62 | prg4.py
63 | 1 O/N/P X
64 | 2 O/N/P Y/T+1
65 | 3 X/S O+5 Y/T/Q+4 O/C/H/B
66 | 4 X/S/M/L/R/D/A X/G X
67 | 5 X/S/M/L/R O Y
68 | 6 X/S
69 | 7 X/S/M/L/R/D/A X/S/M/L/R/D
70 | 8 O/C/F/U
71 | 9 X/S/M/L
72 |
73 | prg5.py
74 | 1 O/N/P+1 O/C/H/B/I
75 | 2 O/N/P X/K O/N X/S
76 | 3 X
77 | 4 O/C/H/B
78 | 5 X/S/M/L/R/D/A
79 | 6 X/S/M/L/V X O/C
80 | 7 O/C/F O/C/H/B X/K
81 | 8 O/C/H O/N
82 | 9 O/C/H/B/I O/N
83 |
84 | prg6.py
85 | 1 X
86 | 2 O/N Y/T/Q X/W
87 | 3
88 | 4 O/J X/K X
89 | 5 Y/T
90 | 6 O/C/F/U O/C+1 X/S/M/L/V O/N X/S/M/L/R/D/A
91 | 7 O/C/F
92 | 8 X/K
93 | 9 Y/E O/C/H/B/I X/S/M/L/V
94 |
95 | prg7.py
96 | 1 O/J Y/E X/K
97 | 2 O/N O+3 X/S/M/L/R Y/E
98 | 3 O/C/F/U Y/T/Q X O/C/H/B/I
99 | 4 O/C/H/B
100 | 5 Y/T/Q
101 | 6 X/S/M/L
102 | 7 X/S/M/L/R/D
103 | 8 X/S
104 | 9 Y/T X/S/M
105 |
106 | prg8.py
107 | 1 X/W O/C
108 | 2 O/C/F/U
109 | 3 O/N X/S/M/L/R/D/A X/S/M/L/V Y/E
110 | 4 X/S/M/L+2 O/J Y/E O/C
111 | 5 X/K O/N/P
112 | 6 X/S/M/L/R/D O/C/H/B
113 |
114 | prg9.py
115 | 1 X/W
116 | 2 O/N Y
117 | 3 O/C/H Y/T/Q
118 | 4
119 | 5 O/J O/C/H/B/I O/C/H
120 | 6 X/S/M
121 | 7 O/C/H/B/I+2 Y/E X/S/M/L/R X/K X/S/M/L/V
122 | 8 O/J O/C/H/B/I
123 | 9 Y/T O/C/F O X/S/M
124 |
125 |
--------------------------------------------------------------------------------
/examples/idioms/programs/001.0003-print-hello-world.py:
--------------------------------------------------------------------------------
1 | """Print Hello World.
2 |
3 | Print a literal string on standard output
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author:
9 | # Created on 2016-02-18T16:57:54.865234Z
10 | # Last modified on 2019-09-26T16:57:35.227864Z
11 | # Version 2
12 |
13 | # This is for Python 2, but maintains compatibility with Python 3.
14 |
15 | from __future__ import print_function
16 |
17 | print("Hello World")
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/001.1159-print-hello-world.py:
--------------------------------------------------------------------------------
1 | """Print Hello World.
2 |
3 | Print a literal string on standard output
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:54.865234Z
10 | # Last modified on 2019-09-26T16:59:32.747154Z
11 | # Version 2
12 |
13 | # This works in Python 3, and will work in Python 2 with the correct import.
14 |
15 | print("Hello World")
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/002.0011-print-hello-10-times.py:
--------------------------------------------------------------------------------
1 | """Print Hello 10 times.
2 |
3 | Loop to execute some code a constant number of times
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author:
9 | # Created on 2015-11-30T12:37:23.746597Z
10 | # Last modified on 2019-09-27T02:17:54.987284Z
11 | # Version 2
12 |
13 | # Indention is mandatory
14 |
15 | for i in range(10):
16 | print("Hello")
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/002.1493-print-hello-10-times.py:
--------------------------------------------------------------------------------
1 | """Print Hello 10 times.
2 |
3 | Loop to execute some code a constant number of times
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: myguel
9 | # Created on 2016-02-17T11:00:17.942564Z
10 | # Last modified on 2019-09-26T15:27:12.99681Z
11 | # Version 2
12 |
13 | # python 3
14 |
15 | print("Hello\n" * 10)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/002.3117-print-hello-10-times.py:
--------------------------------------------------------------------------------
1 | """Print Hello 10 times.
2 |
3 | Loop to execute some code a constant number of times
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: yatin
9 | # Created on 2019-09-26T21:52:15.599123Z
10 | # Last modified on 2019-09-26T21:52:15.599123Z
11 | # Version 1
12 |
13 | print("Hello\n" * 10)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/003.0019-create-a-procedure.py:
--------------------------------------------------------------------------------
1 | """Create a procedure.
2 |
3 | Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author:
9 | # Created on 2016-02-18T16:57:55.28067Z
10 | # Last modified on 2016-02-18T16:57:55.28067Z
11 | # Version 1
12 |
13 |
14 | def finish(name):
15 | print("My job here is done. Goodbye " + name)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/003.2372-create-a-procedure.py:
--------------------------------------------------------------------------------
1 | """Create a procedure.
2 |
3 | Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: A
9 | # Created on 2018-08-12T11:26:19.78712Z
10 | # Last modified on 2018-08-12T11:26:19.78712Z
11 | # Version 1
12 |
13 | # Without side effects
14 |
15 |
16 | def a():
17 | pass
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/004.0024-create-a-function-which-returns-the-square-of-an-integer.py:
--------------------------------------------------------------------------------
1 | """Create a function which returns the square of an integer.
2 |
3 |
4 | Source: programming-idioms.org
5 | """
6 |
7 | # Implementation author:
8 | # Created on 2016-02-18T16:57:55.3769Z
9 | # Last modified on 2016-02-18T16:57:55.3769Z
10 | # Version 1
11 |
12 | # You don't have to explicitly write the return type
13 |
14 |
15 | def square(x):
16 | return x * x
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/004.2921-create-a-function-which-returns-the-square-of-an-integer.py:
--------------------------------------------------------------------------------
1 | """Create a function which returns the square of an integer.
2 |
3 |
4 | Source: programming-idioms.org
5 | """
6 |
7 | # Implementation author: miszczu
8 | # Created on 2019-09-26T17:03:49.234574Z
9 | # Last modified on 2019-09-26T17:03:49.234574Z
10 | # Version 1
11 |
12 | # You can use power operator
13 |
14 |
15 | def square(x):
16 | return x ** 2
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/005.0663-create-a-2d-point-data-structure.py:
--------------------------------------------------------------------------------
1 | """Create a 2D Point data structure.
2 |
3 | Declare a container type for two floating-point numbers _x and _y
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:57:55.615021Z
10 | # Last modified on 2019-09-26T14:09:14.093527Z
11 | # Version 2
12 |
13 | from dataclasses import dataclass
14 |
15 |
16 | @dataclass
17 | class Point:
18 | x: float
19 | y: float
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/006.0032-iterate-over-list-values.py:
--------------------------------------------------------------------------------
1 | """Iterate over list values.
2 |
3 | Do something with each item _x of an array-like collection _items, regardless indexes.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author:
9 | # Created on 2015-11-30T12:37:24.664036Z
10 | # Last modified on 2015-11-30T12:37:24.664036Z
11 | # Version 1
12 |
13 | for x in items:
14 | doSomething(x)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/007.0183-iterate-over-list-indexes-and-values.py:
--------------------------------------------------------------------------------
1 | """Iterate over list indexes and values.
2 |
3 | Print each index _i with its value _x from an array-like collection _items
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:56.046799Z
10 | # Last modified on 2016-02-18T16:57:56.046799Z
11 | # Version 1
12 |
13 | for i, x in enumerate(items):
14 | print(i, x)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/008.0039-initialize-a-new-map-associative-array.py:
--------------------------------------------------------------------------------
1 | """Initialize a new map (associative array).
2 |
3 | Declare a new map object _x, and provide some (key, value) pairs as initial content.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:56.147637Z
10 | # Last modified on 2017-03-20T06:42:48.892383Z
11 | # Version 2
12 |
13 | x = {"one": 1, "two": 2}
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/009.1410-create-a-binary-tree-data-structure.py:
--------------------------------------------------------------------------------
1 | """Create a Binary Tree data structure.
2 |
3 | The structure must be recursive because _left child and _right child are binary trees too. A node has access to children nodes, but not to its parent.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T16:57:56.226523Z
10 | # Last modified on 2016-02-18T16:57:56.226523Z
11 | # Version 1
12 |
13 |
14 | class Node:
15 | def __init__(self, data):
16 | self.data = data
17 | self.left = None
18 | self.right = None
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/009.3176-create-a-binary-tree-data-structure.py:
--------------------------------------------------------------------------------
1 | """Create a Binary Tree data structure.
2 |
3 | The structure must be recursive because _left child and _right child are binary trees too. A node has access to children nodes, but not to its parent.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: atdt
9 | # Created on 2019-09-27T03:58:30.712754Z
10 | # Last modified on 2019-09-27T03:58:30.712754Z
11 | # Version 1
12 |
13 |
14 | class Node:
15 | def __init__(self, data, left_child, right_child):
16 | self.data = data
17 | self._left_child = left_child
18 | self._right_child = right_child
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/010.0182-shuffle-a-list.py:
--------------------------------------------------------------------------------
1 | """Shuffle a list.
2 |
3 | Generate a random permutation of the elements of list _x
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:56.460583Z
10 | # Last modified on 2016-02-18T16:57:56.460583Z
11 | # Version 1
12 |
13 | # This alters the list
14 |
15 | from random import shuffle
16 |
17 | shuffle(x)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/010.1478-shuffle-a-list.py:
--------------------------------------------------------------------------------
1 | """Shuffle a list.
2 |
3 | Generate a random permutation of the elements of list _x
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Trshant
9 | # Created on 2016-02-18T16:57:56.460583Z
10 | # Last modified on 2016-02-18T16:57:56.460583Z
11 | # Version 1
12 |
13 | # _random._shuffle is a inbuilt function that will shuffle the data.
14 |
15 | import random
16 |
17 | random.shuffle(list)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/011.0047-pick-a-random-element-from-a-list.py:
--------------------------------------------------------------------------------
1 | """Pick a random element from a list.
2 |
3 | List _x must be non-empty.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:25.813051Z
10 | # Last modified on 2015-11-30T12:37:25.813051Z
11 | # Version 1
12 |
13 | import random
14 |
15 | random.choice(x)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/012.0181-check-if-list-contains-a-value.py:
--------------------------------------------------------------------------------
1 | """Check if list contains a value.
2 |
3 | Check if _list contains a value _x.
4 | _list is an iterable finite container.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: programming-idioms.org
10 | # Created on 2016-02-18T16:57:56.731679Z
11 | # Last modified on 2019-06-07T10:27:12.157819Z
12 | # Version 2
13 |
14 | # This indirectly calls list.__contains__() and returns True or False
15 |
16 | x in list
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/013.0574-iterate-over-map-keys-and-values.py:
--------------------------------------------------------------------------------
1 | """Iterate over map keys and values.
2 |
3 | Print each key _k with its value _x from an associative array _mymap
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: JackStouffer
9 | # Created on 2015-11-30T12:37:26.239861Z
10 | # Last modified on 2019-09-26T17:58:43.137592Z
11 | # Version 3
12 |
13 | for k, v in mymap.items():
14 | print(k, v)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/014.0185-pick-uniformly-a-random-floating-point-number-in-ab.py:
--------------------------------------------------------------------------------
1 | """Pick uniformly a random floating point number in [a..b[.
2 |
3 | Pick a random number greater than or equals to _a, strictly inferior to _b. Precondition : _a < _b.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:57.104352Z
10 | # Last modified on 2016-02-18T16:57:57.104352Z
11 | # Version 1
12 |
13 | import random
14 |
15 |
16 | def pick(a, b):
17 | return random.randrange(a, b)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/014.3410-pick-uniformly-a-random-floating-point-number-in-ab.py:
--------------------------------------------------------------------------------
1 | """Pick uniformly a random floating point number in [a..b[.
2 |
3 | Pick a random number greater than or equals to _a, strictly inferior to _b. Precondition : _a < _b.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: vinodv
9 | # Created on 2019-09-28T08:37:42.776686Z
10 | # Last modified on 2019-09-28T08:37:42.776686Z
11 | # Version 1
12 |
13 | import random
14 |
15 | random.uniform(a, b)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/015.0184-pick-uniformly-a-random-integer-in-ab.py:
--------------------------------------------------------------------------------
1 | """Pick uniformly a random integer in [a..b].
2 |
3 | Pick a random integer greater than or equals to _a, inferior or equals to _b. Precondition : _a < _b.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:57.20109Z
10 | # Last modified on 2016-02-18T16:57:57.20109Z
11 | # Version 1
12 |
13 | # Upper bound _b is included.
14 |
15 | import random
16 |
17 | random.randint(a, b)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/016.1530-depth-first-traversing-of-a-binary-tree.py:
--------------------------------------------------------------------------------
1 | """Depth-first traversing of a binary tree.
2 |
3 | Call a function _f on every node of binary tree _bt, in depth-first infix order
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T08:50:27.130406Z
10 | # Last modified on 2016-02-18T09:16:52.625429Z
11 | # Version 2
12 |
13 | # Recursive DFS.
14 |
15 |
16 | def dfs(bt):
17 | if bt is None:
18 | return
19 | dfs(bt.left)
20 | f(bt)
21 | dfs(bt.right)
22 |
--------------------------------------------------------------------------------
/examples/idioms/programs/017.1103-create-a-tree-data-structure.py:
--------------------------------------------------------------------------------
1 | """Create a Tree data structure.
2 |
3 | The structure must be recursive. A node may have zero or more children. A node has access to children nodes, but not to its parent.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:57:57.310492Z
10 | # Last modified on 2017-10-04T20:22:26.702125Z
11 | # Version 2
12 |
13 |
14 | class Node(object):
15 | def __init__(self, value, *children):
16 | self.value = value
17 | self.children = list(children)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/018.2084-depth-first-traversing-of-a-tree.py:
--------------------------------------------------------------------------------
1 | """Depth-first traversing of a tree.
2 |
3 | Call a function _f on every node of a tree, in depth-first prefix order
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cpoulet_42
9 | # Created on 2017-08-09T09:20:28.30958Z
10 | # Last modified on 2017-08-09T09:21:46.384451Z
11 | # Version 2
12 |
13 |
14 | def DFS(f, root):
15 | f(root)
16 | for child in root:
17 | DFS(f, child)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/019.0197-reverse-a-list.py:
--------------------------------------------------------------------------------
1 | """Reverse a list.
2 |
3 | Reverse the order of the elements of list _x .
4 | This may reverse "in-place" and destroy the original ordering.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: programming-idioms.org
10 | # Created on 2015-11-30T12:37:26.805864Z
11 | # Last modified on 2015-11-30T12:37:26.805864Z
12 | # Version 1
13 |
14 | # returns an iterable.
15 | # on lists this creates a new list.
16 |
17 | x = reversed(x)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/019.1983-reverse-a-list.py:
--------------------------------------------------------------------------------
1 | """Reverse a list.
2 |
3 | Reverse the order of the elements of list _x .
4 | This may reverse "in-place" and destroy the original ordering.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: synapton
10 | # Created on 2017-05-14T03:47:52.643616Z
11 | # Last modified on 2019-09-27T02:57:37.321491Z
12 | # Version 3
13 |
14 | # Creates a new, reversed list.
15 |
16 | y = x[::-1]
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/019.3164-reverse-a-list.py:
--------------------------------------------------------------------------------
1 | """Reverse a list.
2 |
3 | Reverse the order of the elements of list _x .
4 | This may reverse "in-place" and destroy the original ordering.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: sgdpk
10 | # Created on 2019-09-27T02:50:36.390766Z
11 | # Last modified on 2019-09-27T02:54:21.628364Z
12 | # Version 2
13 |
14 | # Reverses list in place
15 |
16 | x.reverse()
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/020.0573-return-two-values.py:
--------------------------------------------------------------------------------
1 | """Return two values.
2 |
3 | Implement a function _search which looks for item _x in a 2D matrix _m.
4 | Return indices _i, _j of the matching cell.
5 | Think of the most idiomatic way in the language to return the two values at the same time.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: JackStouffer
11 | # Created on 2015-11-30T12:37:26.87247Z
12 | # Last modified on 2015-11-30T12:37:26.87247Z
13 | # Version 1
14 |
15 |
16 | def search(m, x):
17 | for idx, item in enumerate(m):
18 | if x in item:
19 | return idx, item.index(x)
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/021.0084-swap-values-of-variables-a-and-b.py:
--------------------------------------------------------------------------------
1 | """Swap values of variables a and b.
2 |
3 |
4 | Source: programming-idioms.org
5 | """
6 |
7 | # Implementation author: programming-idioms.org
8 | # Created on 2015-11-30T12:37:26.93472Z
9 | # Last modified on 2015-11-30T12:37:26.93472Z
10 | # Version 1
11 |
12 | a, b = b, a
13 |
--------------------------------------------------------------------------------
/examples/idioms/programs/022.0243-convert-string-to-integer.py:
--------------------------------------------------------------------------------
1 | """Convert string to integer.
2 |
3 | Extract integer value _i from its string representation _s (in radix 10)
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:57.820172Z
10 | # Last modified on 2016-02-18T16:57:57.820172Z
11 | # Version 1
12 |
13 | i = int(s)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/023.1102-convert-real-number-to-string-with-2-decimal-places.py:
--------------------------------------------------------------------------------
1 | """Convert real number to string with 2 decimal places.
2 |
3 | Given real number _x, create its string representation _s with 2 decimal digits following the dot.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:57:57.897385Z
10 | # Last modified on 2016-02-18T16:57:57.897385Z
11 | # Version 1
12 |
13 | s = "{:.2f}".format(x)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/024.0664-assign-to-string-the-japanese-word-.py:
--------------------------------------------------------------------------------
1 | """Assign to string the japanese word ネコ.
2 |
3 | Declare a new string _s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2015-11-30T12:37:27.133314Z
10 | # Last modified on 2015-11-30T12:37:27.133314Z
11 | # Version 1
12 |
13 | s = "ネコ"
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/025.0195-send-a-value-to-another-thread.py:
--------------------------------------------------------------------------------
1 | """Send a value to another thread.
2 |
3 | Share the string value "Alan" with an existing running process which will then display "Hello, Alan"
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Aristide
9 | # Created on 2016-02-18T16:57:58.135862Z
10 | # Last modified on 2022-09-04
11 | # Version 2
12 |
13 | from queue import Queue
14 | from threading import Thread
15 |
16 | q = Queue()
17 |
18 | def worker():
19 | while True:
20 | print(f"Hello, {q.get()}")
21 | q.task_done()
22 |
23 | Thread(target=worker, daemon=True).start()
24 |
25 | q.put("Alan")
26 | q.join()
--------------------------------------------------------------------------------
/examples/idioms/programs/026.0194-create-a-2-dimensional-array.py:
--------------------------------------------------------------------------------
1 | """Create a 2-dimensional array.
2 |
3 | Declare and initialize a matrix _x having _m rows and _n columns, containing real numbers.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:27.532323Z
10 | # Last modified on 2019-09-27T03:01:31.943197Z
11 | # Version 2
12 |
13 | # Python 2.7
14 |
15 | x = [[0 for j in xrange(n)] for i in xrange(m)]
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/027.0192-create-a-3-dimensional-array.py:
--------------------------------------------------------------------------------
1 | """Create a 3-dimensional array.
2 |
3 | Declare and initialize a 3D array _x, having dimensions boundaries _m, _n, _p, and containing real numbers.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:27.593658Z
10 | # Last modified on 2015-11-30T12:37:27.593658Z
11 | # Version 1
12 |
13 | x = [[[0 for k in xrange(p)] for j in xrange(n)] for i in xrange(m)]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/027.0193-create-a-3-dimensional-array.py:
--------------------------------------------------------------------------------
1 | """Create a 3-dimensional array.
2 |
3 | Declare and initialize a 3D array _x, having dimensions boundaries _m, _n, _p, and containing real numbers.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:27.593658Z
10 | # Last modified on 2015-11-30T12:37:27.593658Z
11 | # Version 1
12 |
13 | # NumPy is a third-party library for scientific computing.
14 |
15 | import numpy
16 |
17 | x = numpy.zeros((m, n, p))
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/028.0350-sort-by-a-property.py:
--------------------------------------------------------------------------------
1 | """Sort by a property.
2 |
3 | Sort elements of array-like collection _items in ascending order of _x._p, where _p is a field of the type _Item of the objects in _items.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Roboticus
9 | # Created on 2015-11-30T12:37:27.658885Z
10 | # Last modified on 2015-11-30T12:37:27.658885Z
11 | # Version 1
12 |
13 | # The lambda expression pulls out the field you want to sort by. If you want to sort in reverse order, add reverse=True to the argument list.
14 |
15 | items = sorted(items, key=lambda x: x.p)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/029.0199-remove-item-from-list-by-its-index.py:
--------------------------------------------------------------------------------
1 | """Remove item from list, by its index.
2 |
3 | Remove _i-th item from list _items.
4 | This will alter the original list or return a new list, depending on which is more idiomatic.
5 | Note that in most languages, the smallest valid value for _i is _0.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: programming-idioms.org
11 | # Created on 2015-11-30T12:37:27.739993Z
12 | # Last modified on 2015-11-30T12:37:27.739993Z
13 | # Version 1
14 |
15 | # This alters the original list.
16 |
17 | del items[i]
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/030.0189-parallelize-execution-of-1000-independent-tasks.py:
--------------------------------------------------------------------------------
1 | """Parallelize execution of 1000 independent tasks.
2 |
3 | Launch the concurrent execution of procedure _f with parameter _i from 1 to 1000.
4 | Tasks are independent and _f(_i) doesn't return any value.
5 | Tasks need not run all at the same time, so you may use a pool.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: programming-idioms.org
11 | # Created on 2016-02-18T16:57:58.435578Z
12 | # Last modified on 2016-02-18T16:57:58.435578Z
13 | # Version 1
14 |
15 | from multiprocessing import Pool
16 |
17 | pool = Pool()
18 | for i in range(1, 1001):
19 | pool.apply_async(f, [i])
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/031.0188-recursive-factorial-simple.py:
--------------------------------------------------------------------------------
1 | """Recursive factorial (simple).
2 |
3 | Create recursive function _f which returns the factorial of non-negative integer _i, calculated from _f(_i-1)
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:27.869482Z
10 | # Last modified on 2015-11-30T12:37:27.869482Z
11 | # Version 1
12 |
13 |
14 | def f(i):
15 | if i == 0:
16 | return 1
17 | else:
18 | return i * f(i - 1)
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/032.0196-integer-exponentiation-by-squaring.py:
--------------------------------------------------------------------------------
1 | """Integer exponentiation by squaring.
2 |
3 | Create function _exp which calculates (fast) the value _x power _n.
4 | _x and _n are non-negative integers.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: programming-idioms.org
10 | # Created on 2015-11-30T12:37:27.934762Z
11 | # Last modified on 2016-06-13T00:14:23.672291Z
12 | # Version 2
13 |
14 |
15 | def exp(x, n):
16 | return x ** n
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/033.1420-atomically-read-and-update-variable.py:
--------------------------------------------------------------------------------
1 | """Atomically read and update variable.
2 |
3 | Assign variable _x the new value _f(_x), making sure that no other thread may modify _x between the read and the write.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T16:57:58.598676Z
10 | # Last modified on 2016-02-18T16:57:58.598676Z
11 | # Version 1
12 |
13 | import threading
14 |
15 | lock = threading.Lock()
16 |
17 | lock.acquire()
18 | try:
19 | x = f(x)
20 | finally:
21 | lock.release()
22 |
--------------------------------------------------------------------------------
/examples/idioms/programs/034.0625-create-a-set-of-objects.py:
--------------------------------------------------------------------------------
1 | """Create a Set of objects.
2 |
3 | Declare and initialize a Set _x containing objects of type _T.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: JackStouffer
9 | # Created on 2016-02-18T16:57:58.646023Z
10 | # Last modified on 2016-02-18T16:57:58.646023Z
11 | # Version 1
12 |
13 |
14 | class T(object):
15 | pass
16 |
17 |
18 | x = set(T())
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/035.0667-first-class-function--compose.py:
--------------------------------------------------------------------------------
1 | """First-class function : compose.
2 |
3 | Implement a function _compose (_A -> _C) with parameters _f (_A -> _B) and _g (_B -> _C), which returns composition function _g ∘ _f
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2015-11-30T12:37:28.120844Z
10 | # Last modified on 2015-11-30T12:37:28.120844Z
11 | # Version 1
12 |
13 | # We could have used a named function but a lambda is shorter
14 |
15 |
16 | def compose(f, g):
17 | return lambda a: g(f(a))
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/036.0670-first-class-function--generic-composition.py:
--------------------------------------------------------------------------------
1 | """First-class function : generic composition.
2 |
3 | Implement a function _compose which returns composition function _g ∘ _f for any functions _f and _g having exactly 1 parameter.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:57:58.963839Z
10 | # Last modified on 2016-02-18T16:57:58.963839Z
11 | # Version 1
12 |
13 | # This is the same as for non-generic composition
14 |
15 |
16 | def compose(f, g):
17 | return lambda x: g(f(x))
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/037.0671-currying.py:
--------------------------------------------------------------------------------
1 | """Currying.
2 |
3 | Transform a function that takes multiple arguments into a function for which some of the arguments are preset.
4 |
5 | Source: Adrian
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2015-11-30T12:37:28.255934Z
10 | # Last modified on 2019-09-26T16:59:21.413984Z
11 | # Version 3
12 |
13 | from functools import partial
14 |
15 |
16 | def f(a):
17 | def add(b):
18 | return a + b
19 |
20 | return add
21 |
22 |
23 | print(f(2)(1))
24 |
25 | # add_to_two = partial(f, 2)
26 |
--------------------------------------------------------------------------------
/examples/idioms/programs/038.0186-extract-a-substring.py:
--------------------------------------------------------------------------------
1 | """Extract a substring.
2 |
3 | Find substring _t consisting in characters _i (included) to _j (excluded) of string _s.
4 | (character indexes start at 0 unless specified otherwise)
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: programming-idioms.org
10 | # Created on 2015-11-30T12:37:28.309182Z
11 | # Last modified on 2015-11-30T12:37:28.309182Z
12 | # Version 1
13 |
14 | # Slicing works on strings.
15 |
16 | t = s[i:j]
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/039.0571-check-if-string-contains-a-word.py:
--------------------------------------------------------------------------------
1 | """Check if string contains a word.
2 |
3 | Set boolean _ok to _true if string _word is contained in string _s as a substring, or to _false otherwise.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: JackStouffer
9 | # Created on 2015-11-30T12:37:28.369178Z
10 | # Last modified on 2015-11-30T12:37:28.369178Z
11 | # Version 1
12 |
13 | ok = word in s
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/040.2279-graph-with-adjacency-lists.py:
--------------------------------------------------------------------------------
1 | """Graph with adjacency lists.
2 |
3 | Declare a _Graph data structure in which each _Vertex has a collection of its neighbouring vertices. As an example, set _G to a representation of the "bull graph": https://en.wikipedia.org/wiki/Bull_graph
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T18:52:18.110083Z
10 | # Last modified on 2018-04-08T18:52:18.110083Z
11 | # Version 1
12 |
13 | from collections import defaultdict
14 |
15 |
16 | class Vertex(set):
17 | pass
18 |
19 |
20 | class Graph(defaultdict):
21 | def __init__(self, *paths):
22 | self.default_factory = Vertex
23 | for path in paths:
24 | self.make_path(path)
25 |
26 | def make_path(self, labels):
27 | for l1, l2 in zip(labels, labels[1:]):
28 | self[l1].add(l2)
29 | self[l2].add(l1)
30 |
31 |
32 | G = Graph((0, 1, 2, 3), (1, 4, 2))
33 |
--------------------------------------------------------------------------------
/examples/idioms/programs/041.0187-reverse-a-string.py:
--------------------------------------------------------------------------------
1 | """Reverse a string.
2 |
3 | Create string _t containing the same characters as string _s, in reverse order.
4 | Original string _s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: programming-idioms.org
10 | # Created on 2016-02-18T16:57:59.271208Z
11 | # Last modified on 2018-01-03T23:44:30.749232Z
12 | # Version 2
13 |
14 | t = s.decode("utf8")[::-1].encode("utf8")
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/041.2714-reverse-a-string.py:
--------------------------------------------------------------------------------
1 | """Reverse a string.
2 |
3 | Create string _t containing the same characters as string _s, in reverse order.
4 | Original string _s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Rochelimit
10 | # Created on 2019-09-26T13:57:21.819714Z
11 | # Last modified on 2019-09-26T13:57:21.819714Z
12 | # Version 1
13 |
14 | t = s[::-1]
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/042.1264-continue-outer-loop.py:
--------------------------------------------------------------------------------
1 | """Continue outer loop.
2 |
3 | Print each item _v of list _a which in not contained in list _b.
4 | For this, write an outer loop to iterate on _a and an inner loop to iterate on _b.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: cym13
10 | # Created on 2016-02-18T16:57:59.339267Z
11 | # Last modified on 2016-02-18T16:57:59.339267Z
12 | # Version 1
13 |
14 | # Note that using two loops like this in python is by itself _very un-idiomatic. Also one would be wise to define a custom exception to avoid hiding "real" exceptions.
15 |
16 | for v in a:
17 | try:
18 | for u in b:
19 | if v == u:
20 | raise Exception()
21 | print(v)
22 | except Exception:
23 | continue
24 |
--------------------------------------------------------------------------------
/examples/idioms/programs/042.3168-continue-outer-loop.py:
--------------------------------------------------------------------------------
1 | """Continue outer loop.
2 |
3 | Print each item _v of list _a which in not contained in list _b.
4 | For this, write an outer loop to iterate on _a and an inner loop to iterate on _b.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: sgdpk
10 | # Created on 2019-09-27T03:11:50.496862Z
11 | # Last modified on 2019-09-27T03:13:07.422569Z
12 | # Version 2
13 |
14 | for v in a:
15 | for v_ in b:
16 | if v == v_:
17 | continue
18 | print(v)
19 |
20 | # More idiomatic solution for this specific problem
21 | #
22 | # for v in a:
23 | # if v not in b:
24 | # print(v)
25 |
--------------------------------------------------------------------------------
/examples/idioms/programs/043.0676-break-outer-loop.py:
--------------------------------------------------------------------------------
1 | """Break outer loop.
2 |
3 | Look for a negative value _v in 2D integer matrix _m. Print it and stop searching.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:57:59.387368Z
10 | # Last modified on 2016-02-18T16:57:59.387368Z
11 | # Version 1
12 |
13 | # This is ugly because the pythonic way to solve this problem would be to refactor so that one doesn't have to break out of multiple loops. See PEP3136
14 |
15 |
16 | class BreakOuterLoop(Exception):
17 | pass
18 |
19 |
20 | try:
21 | position = None
22 | for row in m:
23 | for column in m[row]:
24 | if m[row][column] == v:
25 | position = (row, column)
26 | raise BreakOuterLoop
27 | except BreakOuterLoop:
28 | pass
29 |
--------------------------------------------------------------------------------
/examples/idioms/programs/043.2733-break-outer-loop.py:
--------------------------------------------------------------------------------
1 | """Break outer loop.
2 |
3 | Look for a negative value _v in 2D integer matrix _m. Print it and stop searching.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Rochelimit
9 | # Created on 2019-09-26T14:22:03.939368Z
10 | # Last modified on 2019-09-27T03:20:25.894658Z
11 | # Version 2
12 |
13 | # Rather than set break flags, it is better to refactor into a function, then use return to break from all nested loops.
14 |
15 |
16 | def loop_breaking(m, v):
17 | for i, row in enumerate(m):
18 | for j, value in enumerate(row):
19 | if value == v:
20 | return (i, j)
21 | return None
22 |
23 |
24 | print(loop_breaking(([1, 2, 3], [4, 5, 6], [7, 8, 9]), 6))
25 |
--------------------------------------------------------------------------------
/examples/idioms/programs/044.0190-insert-element-in-list.py:
--------------------------------------------------------------------------------
1 | """Insert element in list.
2 |
3 | Insert element _x at position _i in list _s. Further elements must be shifted to the right.
4 |
5 | Source: anonymous
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:59.441924Z
10 | # Last modified on 2016-02-18T16:57:59.441924Z
11 | # Version 1
12 |
13 | s.insert(i, x)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/045.0570-pause-execution-for-5-seconds.py:
--------------------------------------------------------------------------------
1 | """Pause execution for 5 seconds.
2 |
3 | Sleep for 5 seconds in current thread, before proceeding with next instructions.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: JackStouffer
9 | # Created on 2015-11-30T12:37:29.012454Z
10 | # Last modified on 2015-11-30T12:37:29.012454Z
11 | # Version 1
12 |
13 | import time
14 |
15 | time.sleep(5)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/046.0191-extract-beginning-of-string-prefix.py:
--------------------------------------------------------------------------------
1 | """Extract beginning of string (prefix).
2 |
3 | Create string _t consisting of the 5 first characters of string _s.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:29.084287Z
10 | # Last modified on 2015-11-30T12:37:29.084287Z
11 | # Version 1
12 |
13 | t = s[:5]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/047.0198-extract-string-suffix.py:
--------------------------------------------------------------------------------
1 | """Extract string suffix.
2 |
3 | Create string _t consisting in the 5 last characters of string _s.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:29.158754Z
10 | # Last modified on 2015-11-30T12:37:29.158754Z
11 | # Version 1
12 |
13 | t = s[-5:]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/048.0210-multi-line-string-literal.py:
--------------------------------------------------------------------------------
1 | """Multi-line string literal.
2 |
3 | Assign to variable _s a string literal consisting in several lines of text
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: deleplace
9 | # Created on 2016-02-18T16:57:59.794373Z
10 | # Last modified on 2016-02-18T16:57:59.794373Z
11 | # Version 1
12 |
13 | s = """Huey
14 | Dewey
15 | Louie"""
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/049.0242-split-a-space-separated-string.py:
--------------------------------------------------------------------------------
1 | """Split a space-separated string.
2 |
3 | Build list _chunks consisting in substrings of input string _s, separated by one or more space characters.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:59.856562Z
10 | # Last modified on 2016-05-29T09:25:03.631065Z
11 | # Version 2
12 |
13 | # If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns [].
14 |
15 | chunks = s.split()
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/050.0572-make-an-infinite-loop.py:
--------------------------------------------------------------------------------
1 | """Make an infinite loop.
2 |
3 | Write a loop which has no end clause.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: JackStouffer
9 | # Created on 2016-02-18T16:57:59.907374Z
10 | # Last modified on 2016-02-18T16:57:59.907374Z
11 | # Version 1
12 |
13 | while True:
14 | pass
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/051.0230-check-if-map-contains-key.py:
--------------------------------------------------------------------------------
1 | """Check if map contains key.
2 |
3 | Determine whether map _m contains an entry for key _k
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:57:59.979759Z
10 | # Last modified on 2016-02-18T16:57:59.979759Z
11 | # Version 1
12 |
13 | k in m
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/052.0666-check-if-map-contains-value.py:
--------------------------------------------------------------------------------
1 | """Check if map contains value.
2 |
3 | Determine whether map _m contains an entry with value _v, for some key.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:58:00.033381Z
10 | # Last modified on 2016-02-18T16:58:00.033381Z
11 | # Version 1
12 |
13 | v in map.values()
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/053.0240-join-a-list-of-strings.py:
--------------------------------------------------------------------------------
1 | """Join a list of strings.
2 |
3 | Concatenate elements of string list _x joined by the separator ", " to create a single string _y.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2015-11-30T12:37:29.54749Z
10 | # Last modified on 2016-12-22T09:27:39.353014Z
11 | # Version 2
12 |
13 | # This works if _x contains only strings.
14 |
15 | y = ", ".join(x)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/053.1933-join-a-list-of-strings.py:
--------------------------------------------------------------------------------
1 | """Join a list of strings.
2 |
3 | Concatenate elements of string list _x joined by the separator ", " to create a single string _y.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-12-22T09:26:47.916166Z
10 | # Last modified on 2019-05-12T19:56:56.476487Z
11 | # Version 2
12 |
13 | # This works even if some elements in _x are not strings.
14 |
15 | y = ", ".join(map(str, x))
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/054.0241-compute-sum-of-integers.py:
--------------------------------------------------------------------------------
1 | """Compute sum of integers.
2 |
3 | Calculate the sum _s of integer list _x.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: deleplace
9 | # Created on 2015-11-30T12:37:29.615079Z
10 | # Last modified on 2015-11-30T12:37:29.615079Z
11 | # Version 1
12 |
13 | # _sum is a built-in function.
14 |
15 | s = sum(x)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/055.0575-convert-integer-to-string.py:
--------------------------------------------------------------------------------
1 | """Convert integer to string.
2 |
3 | Create the string representation _s (in radix 10) of integer value _i.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: JackStouffer
9 | # Created on 2016-02-18T16:58:00.217404Z
10 | # Last modified on 2016-02-18T16:58:00.217404Z
11 | # Version 1
12 |
13 | s = str(i)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/056.1424-launch-1000-parallel-tasks-and-wait-for-completion.py:
--------------------------------------------------------------------------------
1 | """Launch 1000 parallel tasks and wait for completion.
2 |
3 | Fork-join : launch the concurrent execution of procedure _f with parameter _i from 1 to 1000.
4 | Tasks are independent and _f(_i) doesn't return any value.
5 | Tasks need not run all at the same time, so you may use a pool.
6 | Wait for the completion of the 1000 tasks and then print "Finished".
7 |
8 | Source: deleplace
9 | """
10 |
11 | # Implementation author: TinyFawks
12 | # Created on 2016-02-18T16:58:00.323333Z
13 | # Last modified on 2016-02-18T16:58:00.323333Z
14 | # Version 1
15 |
16 | from multiprocessing import Pool
17 |
18 |
19 | def f(i):
20 | i * i
21 |
22 |
23 | with Pool(processes) as p:
24 | p.map(func=f, iterable=range(1, 1001))
25 |
26 | print("Finished")
27 |
--------------------------------------------------------------------------------
/examples/idioms/programs/057.0260-filter-list.py:
--------------------------------------------------------------------------------
1 | """Filter list.
2 |
3 | Create list _y containing items from list _x satisfying predicate _p. Respect original ordering. Don't modify _x in-place.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: alexis
9 | # Created on 2015-11-30T12:37:29.796657Z
10 | # Last modified on 2019-09-27T03:31:27.393465Z
11 | # Version 2
12 |
13 | # In Python 3, returns filter object, not a list, following a lazy evaluation approach.
14 |
15 | y = filter(p, x)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/057.3173-filter-list.py:
--------------------------------------------------------------------------------
1 | """Filter list.
2 |
3 | Create list _y containing items from list _x satisfying predicate _p. Respect original ordering. Don't modify _x in-place.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: sgdpk
9 | # Created on 2019-09-27T03:28:06.687958Z
10 | # Last modified on 2019-09-27T03:28:06.687958Z
11 | # Version 1
12 |
13 | # List comprehensions tend to be more readable than filter function
14 |
15 | y = [element for element in x if p(element)]
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/058.0665-extract-file-content-to-a-string.py:
--------------------------------------------------------------------------------
1 | """Extract file content to a string.
2 |
3 | Create string _lines from the content of the file with filename _f.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:58:00.469157Z
10 | # Last modified on 2016-02-18T16:58:00.469157Z
11 | # Version 1
12 |
13 | # For more complicated file operations, use a context manager with "with"
14 |
15 | lines = open(f).read()
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/059.0668-write-to-standard-error-stream.py:
--------------------------------------------------------------------------------
1 | """Write to standard error stream.
2 |
3 | Print the message "_x is negative" to standard error (stderr), with integer _x value substitution (e.g. "-2 is negative").
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2015-11-30T12:37:29.950568Z
10 | # Last modified on 2015-11-30T12:37:29.950568Z
11 | # Version 1
12 |
13 | # Python3
14 |
15 | import sys
16 |
17 | print(x, "is negative", file=sys.stderr)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/060.1084-read-command-line-argument.py:
--------------------------------------------------------------------------------
1 | """Read command line argument.
2 |
3 | Assign to _x the string value of the first command line parameter, after the program name.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:00.600634Z
10 | # Last modified on 2016-02-18T16:58:00.600634Z
11 | # Version 1
12 |
13 | # argv[0] is the program name
14 |
15 | import sys
16 |
17 | x = sys.argv[1]
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/061.0576-get-current-date.py:
--------------------------------------------------------------------------------
1 | """Get current date.
2 |
3 | Assign to variable _d the current date/time value, in the most standard type.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: JackStouffer
9 | # Created on 2016-02-18T16:58:00.650629Z
10 | # Last modified on 2016-02-18T16:58:00.650629Z
11 | # Version 1
12 |
13 | import datetime
14 |
15 | d = datetime.datetime.now()
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/062.1091-find-substring-position.py:
--------------------------------------------------------------------------------
1 | """Find substring position.
2 |
3 | Set _i to the position of string _y inside string _x, if exists.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:00.71421Z
10 | # Last modified on 2016-02-18T16:58:00.71421Z
11 | # Version 1
12 |
13 | i = x.find(y)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/063.1088-replace-fragment-of-a-string.py:
--------------------------------------------------------------------------------
1 | """Replace fragment of a string.
2 |
3 | Assign to _x2 the value of string _x with all occurrences of _y replaced by _z.
4 | Assume occurrences of _y are not overlapping.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: nickname
10 | # Created on 2016-02-18T16:58:00.771601Z
11 | # Last modified on 2016-02-18T16:58:00.771601Z
12 | # Version 1
13 |
14 | x2 = x.replace(y, z)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/064.0274-big-integer--value-3-power-247.py:
--------------------------------------------------------------------------------
1 | """Big integer : value 3 power 247.
2 |
3 | Assign to _x the value 3^247
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-02-18T16:58:00.821708Z
10 | # Last modified on 2019-09-26T18:04:10.004233Z
11 | # Version 2
12 |
13 | x = 3 ** 247
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/065.1085-format-decimal-number.py:
--------------------------------------------------------------------------------
1 | """Format decimal number.
2 |
3 | From real value _x in [0,1], create its percentage string representation _s with one digit after decimal point. E.g. 0.15625 -> "15.6%"
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:00.875881Z
10 | # Last modified on 2018-06-24T11:00:03.628976Z
11 | # Version 2
12 |
13 | # .1 means only one digit after decimal point.
14 | # % handles the "multiplication" and shows the percentage sign.
15 |
16 | s = "{:.1%}".format(x)
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/066.0672-big-integer-exponentiation.py:
--------------------------------------------------------------------------------
1 | """Big integer exponentiation.
2 |
3 | Calculate the result _z of _x power _n, where _x is a big integer and _n is a positive integer.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:58:00.945223Z
10 | # Last modified on 2016-02-18T16:58:00.945223Z
11 | # Version 1
12 |
13 | z = x ** n
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/067.1426-binomial-coefficient-n-choose-k.py:
--------------------------------------------------------------------------------
1 | """Binomial coefficient "n choose k".
2 |
3 | Calculate _binom(_n, _k) = _n! / (_k! * (_n-_k)!). Use an integer type able to handle huge numbers.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T16:58:01.001157Z
10 | # Last modified on 2019-06-13T17:13:14.289424Z
11 | # Version 4
12 |
13 | import math
14 |
15 |
16 | def binom(n, k):
17 | return math.factorial(n) // math.factorial(k) // math.factorial(n - k)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/068.2271-create-a-bitset.py:
--------------------------------------------------------------------------------
1 | """Create a bitset.
2 |
3 | Create an object _x to store _n bits (_n being potentially large).
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T06:56:50.980819Z
10 | # Last modified on 2018-04-08T20:04:06.987067Z
11 | # Version 2
12 |
13 | from __future__ import division
14 | import math
15 |
16 | x = bytearray(int(math.ceil(n / 8.0)))
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/069.1086-seed-random-generator.py:
--------------------------------------------------------------------------------
1 | """Seed random generator.
2 |
3 | Use seed _s to initialize a random generator.
4 |
5 | If _s is constant, the generator output will be the same each time the program runs. If _s is based on the current value of the system clock, the generator output will be different each time.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: nickname
11 | # Created on 2016-02-18T16:58:01.100654Z
12 | # Last modified on 2016-02-18T16:58:01.100654Z
13 | # Version 1
14 |
15 | # this creates a new random generator _rand
16 |
17 | import random
18 |
19 | rand = random.Random(s)
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/070.1087-use-clock-as-random-generator-seed.py:
--------------------------------------------------------------------------------
1 | """Use clock as random generator seed.
2 |
3 | Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:01.15413Z
10 | # Last modified on 2016-02-18T16:58:01.15413Z
11 | # Version 1
12 |
13 | # the constructor uses the current time if used without arguments.
14 | # you could also use the functions of the random module (they are using a shared ``Random`` object which is constructed the first time random is imported
15 |
16 | import random
17 |
18 | rand = random.Random()
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/071.0379-echo-program-implementation.py:
--------------------------------------------------------------------------------
1 | """Echo program implementation.
2 |
3 | Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
4 | The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
5 |
6 | Source: christianhujer
7 | """
8 |
9 | # Implementation author: christianhujer
10 | # Created on 2016-02-18T16:58:01.212065Z
11 | # Last modified on 2016-02-18T16:58:01.212065Z
12 | # Version 1
13 |
14 | import sys
15 |
16 | print(" ".join(sys.argv[1:]))
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/073.0673-create-a-factory.py:
--------------------------------------------------------------------------------
1 | """Create a factory.
2 |
3 | Create a factory named _fact for any sub class of _Parent and taking exactly one string _str as constructor parameter.
4 |
5 | Source: bbtemp
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2015-11-30T12:37:30.750423Z
10 | # Last modified on 2017-05-12T12:10:42.285428Z
11 | # Version 3
12 |
13 | # You can use the class like a function.
14 |
15 |
16 | def fact(a_class, str_):
17 | if issubclass(a_class, Parent):
18 | return a_class(str_)
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/074.0674-compute-gcd.py:
--------------------------------------------------------------------------------
1 | """Compute GCD.
2 |
3 | Compute the greatest common divisor _x of big integers _a and _b. Use an integer type able to handle huge numbers.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:58:01.317984Z
10 | # Last modified on 2016-02-18T16:58:01.317984Z
11 | # Version 1
12 |
13 | from fractions import gcd
14 |
15 | x = gcd(a, b)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/075.0675-compute-lcm.py:
--------------------------------------------------------------------------------
1 | """Compute LCM.
2 |
3 | Compute the least common multiple _x of big integers _a and _b. Use an integer type able to handle huge numbers.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:58:01.374503Z
10 | # Last modified on 2016-02-18T16:58:01.374503Z
11 | # Version 1
12 |
13 | from fractions import gcd
14 |
15 | x = (a * b) // gcd(a, b)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/076.1083-binary-digits-from-an-integer.py:
--------------------------------------------------------------------------------
1 | """Binary digits from an integer.
2 |
3 | Create the string _s of integer _x written in base _2.
4 |
5 | E.g. 13 -> "1101"
6 |
7 | Source: deleplace
8 | """
9 |
10 | # Implementation author: nickname
11 | # Created on 2016-02-18T16:58:01.42881Z
12 | # Last modified on 2016-02-18T16:58:01.42881Z
13 | # Version 1
14 |
15 | s = "{:b}".format(x)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/077.1093-complex-number.py:
--------------------------------------------------------------------------------
1 | """Complex number.
2 |
3 | Declare a complex _x and initialize it with value (_3i - _2). Then multiply it by _i.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:01.509788Z
10 | # Last modified on 2016-02-18T16:58:01.509788Z
11 | # Version 1
12 |
13 | x = 3j - 2
14 | y = x * 1j
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/078.1089-do-while-loop.py:
--------------------------------------------------------------------------------
1 | """"do while" loop.
2 |
3 | Execute a block once, then execute it again as long as boolean condition _c is true.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2015-11-30T12:37:31.03707Z
10 | # Last modified on 2015-11-30T12:37:31.03707Z
11 | # Version 1
12 |
13 | while True:
14 | do_something()
15 | if not c:
16 | break
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/079.1090-convert-integer-to-floating-point-number.py:
--------------------------------------------------------------------------------
1 | """Convert integer to floating point number.
2 |
3 | Declare floating point number _y and initialize it with the value of integer _x .
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:01.635422Z
10 | # Last modified on 2016-02-18T16:58:01.635422Z
11 | # Version 1
12 |
13 | y = float(x)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/080.1092-truncate-floating-point-number-to-integer.py:
--------------------------------------------------------------------------------
1 | """Truncate floating point number to integer.
2 |
3 | Declare integer _y and initialize it with the value of floating point number _x . Ignore non-integer digits of _x .
4 | Make sure to truncate towards zero: a negative _x must yield the closest greater integer (not lesser).
5 |
6 | Source: deleplace
7 | """
8 |
9 | # Implementation author: nickname
10 | # Created on 2016-02-18T16:58:01.720305Z
11 | # Last modified on 2016-02-18T16:58:01.720305Z
12 | # Version 1
13 |
14 | y = int(x)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/081.2270-round-floating-point-number-to-integer.py:
--------------------------------------------------------------------------------
1 | """Round floating point number to integer.
2 |
3 | Declare integer _y and initialize it with the rounded value of floating point number _x .
4 | Ties (when the fractional part of _x is exactly ._5) must be rounded up (to positive infinity).
5 |
6 | Source: deleplace
7 | """
8 |
9 | # Implementation author: bukzor
10 | # Created on 2018-04-08T06:49:12.434716Z
11 | # Last modified on 2018-04-08T06:49:45.658274Z
12 | # Version 2
13 |
14 | y = int(x + 0.5)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/082.1096-count-substring-occurrences.py:
--------------------------------------------------------------------------------
1 | """Count substring occurrences.
2 |
3 | Find how many times string _s contains substring _t.
4 | Specify if overlapping occurrences are counted.
5 |
6 | Source: deleplace
7 | """
8 |
9 | # Implementation author: nickname
10 | # Created on 2016-02-18T16:58:01.820664Z
11 | # Last modified on 2016-02-18T16:58:01.820664Z
12 | # Version 1
13 |
14 | # counts non-overlapping occurrences
15 |
16 | count = s.count(t)
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/083.1805-regex-with-character-repetition.py:
--------------------------------------------------------------------------------
1 | """Regex with character repetition.
2 |
3 | Declare regular expression _r matching strings "http", "htttp", "httttp", etc.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: iLoveTux
9 | # Created on 2016-08-24T02:53:23.462835Z
10 | # Last modified on 2016-08-24T02:53:23.462835Z
11 | # Version 1
12 |
13 | import re
14 |
15 | r = re.compile(r"htt+p")
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/084.1940-count-bits-set-in-integer-binary-representation.py:
--------------------------------------------------------------------------------
1 | """Count bits set in integer binary representation.
2 |
3 | Count number _c of 1s in the integer _i in base 2.
4 |
5 | E.g. _i=6 → _c=2
6 |
7 | Source: deleplace
8 | """
9 |
10 | # Implementation author: Maxlynch
11 | # Created on 2017-03-02T13:06:25.168698Z
12 | # Last modified on 2017-03-03T11:50:05.929281Z
13 | # Version 2
14 |
15 | c = bin(i).count("1")
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/085.1003-check-if-integer-addition-will-overflow.py:
--------------------------------------------------------------------------------
1 | """Check if integer addition will overflow.
2 |
3 | Write boolean function _addingWillOverflow which takes two integers _x, _y and return _true if (_x+_y) overflows.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: deleplace
9 | # Created on 2016-02-18T16:58:01.953081Z
10 | # Last modified on 2019-09-26T14:23:49.190417Z
11 | # Version 2
12 |
13 | # Python has arbitrary precision integers so you shouldn't worry about overflow.
14 | # Also, don't bother coding this constant function!
15 |
16 |
17 | def adding_will_overflow(x, y):
18 | return False
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/086.1004-check-if-integer-multiplication-will-overflow.py:
--------------------------------------------------------------------------------
1 | """Check if integer multiplication will overflow.
2 |
3 | Write boolean function _multiplyWillOverflow which takes two integers _x, _y and return _true if (_x*_y) overflows.
4 |
5 | Source: deleplace
6 | """
7 |
8 | # Implementation author: deleplace
9 | # Created on 2016-02-18T16:58:02.0026Z
10 | # Last modified on 2016-02-18T16:58:02.0026Z
11 | # Version 1
12 |
13 | # Python has arbitrary precision integers so you shouldn't worry about overflow.
14 | # Also, don't bother coding this constant function!
15 |
16 |
17 | def multiplyWillOverflow(x, y):
18 | return False
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/087.1139-stop-program.py:
--------------------------------------------------------------------------------
1 | """Stop program.
2 |
3 | Exit immediatly.
4 | If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
5 |
6 | Source: deleplace
7 | """
8 |
9 | # Implementation author: henkidefix
10 | # Created on 2016-02-18T16:58:02.06157Z
11 | # Last modified on 2016-02-18T16:58:02.06157Z
12 | # Version 1
13 |
14 | import sys
15 |
16 | sys.exit(1)
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/088.2143-allocate-1m-bytes.py:
--------------------------------------------------------------------------------
1 | """Allocate 1M bytes.
2 |
3 | Create a new bytes buffer _buf of size 1,000,000.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T10:29:47.767072Z
10 | # Last modified on 2017-10-28T10:29:47.767072Z
11 | # Version 1
12 |
13 | buf = bytearray(1000000)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/089.1097-handle-invalid-argument.py:
--------------------------------------------------------------------------------
1 | """Handle invalid argument.
2 |
3 | You've detected that the integer value of argument _x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:02.165631Z
10 | # Last modified on 2016-02-18T16:58:02.165631Z
11 | # Version 1
12 |
13 | raise ValueError("x is invalid")
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/090.1099-read-only-outside.py:
--------------------------------------------------------------------------------
1 | """Read-only outside.
2 |
3 | Expose a read-only integer _x to the outside world while being writable inside a structure or a class _Foo.
4 |
5 | Source: bbtemp
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:02.219893Z
10 | # Last modified on 2016-02-18T16:58:02.219893Z
11 | # Version 1
12 |
13 |
14 | class Foo(object):
15 | def __init__(self):
16 | self._x = 0
17 |
18 | @property
19 | def x(self):
20 | """
21 | Doc for x
22 | """
23 | return self._x
24 |
--------------------------------------------------------------------------------
/examples/idioms/programs/091.1098-load-json-file-into-struct.py:
--------------------------------------------------------------------------------
1 | """Load JSON file into struct.
2 |
3 | Read from file _data._json and write its content into object _x.
4 | Assume the JSON data is suitable for the type of _x.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: nickname
10 | # Created on 2016-02-18T16:58:02.260166Z
11 | # Last modified on 2016-02-18T16:58:02.260166Z
12 | # Version 1
13 |
14 | import json
15 |
16 | with open("data.json", "r") as input:
17 | x = json.load(input)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/092.1100-save-object-into-json-file.py:
--------------------------------------------------------------------------------
1 | """Save object into JSON file.
2 |
3 | Write content of object _x into file _data._json.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:02.298929Z
10 | # Last modified on 2016-02-18T16:58:02.298929Z
11 | # Version 1
12 |
13 | import json
14 |
15 | with open("data.json", "w") as output:
16 | json.dump(x, output)
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/093.1082-pass-a-runnable-procedure-as-parameter.py:
--------------------------------------------------------------------------------
1 | """Pass a runnable procedure as parameter.
2 |
3 | Implement procedure _control which receives one parameter _f, and runs _f.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:02.348116Z
10 | # Last modified on 2016-02-18T16:58:02.348116Z
11 | # Version 1
12 |
13 | from __future__ import print_function
14 |
15 |
16 | def control(f):
17 | return f()
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/094.1101-print-type-of-variable.py:
--------------------------------------------------------------------------------
1 | """Print type of variable.
2 |
3 | Print the name of the type of _x. Explain if it is a static type or dynamic type.
4 |
5 | This may not make sense in all languages.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: nickname
11 | # Created on 2016-02-18T16:58:02.394021Z
12 | # Last modified on 2016-10-26T12:12:01.566764Z
13 | # Version 2
14 |
15 | print(type(x))
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/094.1864-print-type-of-variable.py:
--------------------------------------------------------------------------------
1 | """Print type of variable.
2 |
3 | Print the name of the type of _x. Explain if it is a static type or dynamic type.
4 |
5 | This may not make sense in all languages.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: programming-idioms.org
11 | # Created on 2016-10-26T12:11:43.430534Z
12 | # Last modified on 2016-10-26T12:11:43.430534Z
13 | # Version 1
14 |
15 | print(x.__class__)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/095.2140-get-file-size.py:
--------------------------------------------------------------------------------
1 | """Get file size.
2 |
3 | Assign to variable _x the length (number of bytes) of the local file at _path.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T10:10:24.370986Z
10 | # Last modified on 2017-10-28T10:10:24.370986Z
11 | # Version 1
12 |
13 | import os
14 |
15 | x = os.path.getsize(path)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/096.1094-check-string-prefix.py:
--------------------------------------------------------------------------------
1 | """Check string prefix.
2 |
3 | Set boolean _b to _true if string _s starts with prefix _prefix, _false otherwise.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:02.501753Z
10 | # Last modified on 2016-02-18T16:58:02.501753Z
11 | # Version 1
12 |
13 | b = s.startswith(prefix)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/097.1095-check-string-suffix.py:
--------------------------------------------------------------------------------
1 | """Check string suffix.
2 |
3 | Set boolean _b to _true if string _s ends with string _suffix, _false otherwise.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: nickname
9 | # Created on 2016-02-18T16:58:02.566137Z
10 | # Last modified on 2016-02-18T16:58:02.566137Z
11 | # Version 1
12 |
13 | b = s.endswith(suffix)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/098.2142-epoch-seconds-to-date-object.py:
--------------------------------------------------------------------------------
1 | """Epoch seconds to date object.
2 |
3 | Convert a timestamp _ts (number of seconds in epoch-time) to a date with time _d. E.g. 0 -> 1970-01-01 00:00:00
4 |
5 | Source: elbrujohalcon
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T10:26:36.890877Z
10 | # Last modified on 2017-10-28T10:26:36.890877Z
11 | # Version 1
12 |
13 | import datetime
14 |
15 | d = datetime.date.fromtimestamp(ts)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/099.1429-format-date-yyyy-mm-dd.py:
--------------------------------------------------------------------------------
1 | """Format date YYYY-MM-DD.
2 |
3 | Assign to string _x the value of fields (year, month, day) of date _d, in format _YYYY-_MM-_DD.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T16:58:02.675046Z
10 | # Last modified on 2019-09-26T13:38:52.570471Z
11 | # Version 3
12 |
13 | from datetime import date
14 |
15 | d = date(2016, 9, 28)
16 | x = d.strftime("%Y-%m-%d")
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/099.2693-format-date-yyyy-mm-dd.py:
--------------------------------------------------------------------------------
1 | """Format date YYYY-MM-DD.
2 |
3 | Assign to string _x the value of fields (year, month, day) of date _d, in format _YYYY-_MM-_DD.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: jessedhillon
9 | # Created on 2019-09-26T13:46:18.91621Z
10 | # Last modified on 2019-09-26T13:46:18.91621Z
11 | # Version 1
12 |
13 | from datetime import date
14 |
15 | d = date.today()
16 | x = d.isoformat()
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/100.1142-sort-by-a-comparator.py:
--------------------------------------------------------------------------------
1 | """Sort by a comparator.
2 |
3 | Sort elements of array-like collection _items, using a comparator _c.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: benaryorg
9 | # Created on 2015-12-27T16:39:17.869168Z
10 | # Last modified on 2016-12-11T21:30:46.32397Z
11 | # Version 2
12 |
13 | items.sort(c)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/101.2172-load-from-http-get-request-into-a-string.py:
--------------------------------------------------------------------------------
1 | """Load from HTTP GET request into a string.
2 |
3 | Make an HTTP request with method GET to URL _u, then store the body of the response in string _s.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-29T09:59:08.181801Z
10 | # Last modified on 2017-10-29T10:10:54.980586Z
11 | # Version 2
12 |
13 | import urllib.request
14 |
15 | with urllib.request.urlopen(u) as f:
16 | s = f.read()
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/102.2173-load-from-http-get-request-into-a-file.py:
--------------------------------------------------------------------------------
1 | """Load from HTTP GET request into a file.
2 |
3 | Make an HTTP request with method GET to URL _u, then store the body of the response in file _result._txt. Try to save the data as it arrives if possible, without having all its content in memory at once.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-29T10:09:43.586786Z
10 | # Last modified on 2017-10-29T10:09:43.586786Z
11 | # Version 1
12 |
13 | import urllib
14 |
15 | filename, headers = urllib.request.urlretrieve(u, "result.txt")
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/103.2276-load-xml-file-into-struct.py:
--------------------------------------------------------------------------------
1 | """Load XML file into struct.
2 |
3 | Read from file _data._xml and write its content into object _x.
4 | Assume the XML data is suitable for the type of _x.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: bukzor
10 | # Created on 2018-04-08T07:25:34.222994Z
11 | # Last modified on 2018-04-08T07:25:34.222994Z
12 | # Version 1
13 |
14 | # Use "pip install" to get this third-party library. It's industry standard for python xml.
15 |
16 | import lxml.etree
17 |
18 | x = lxml.etree.parse("data.xml")
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/104.3264-save-object-into-xml-file.py:
--------------------------------------------------------------------------------
1 | """Save object into XML file.
2 |
3 | Write content of object _x into file _data._xml.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Fazel94
9 | # Created on 2019-09-27T14:19:13.327701Z
10 | # Last modified on 2019-09-27T14:19:13.327701Z
11 | # Version 1
12 |
13 | import pyxser as pyx
14 |
15 | # Python 2.5 to 2.7
16 | # Use pickle or marshall module
17 | class TestClass(object):
18 | a = None
19 | b = None
20 | c = None
21 |
22 | def __init__(self, a, b, c):
23 | self.a = a
24 | self.b = b
25 | self.c = c
26 |
27 |
28 | tst = TestClass("var_a", "var_b", "var_c")
29 | ser = pyx.serialize(obj=tst, enc="utf-8")
30 | print(ser)
31 |
--------------------------------------------------------------------------------
/examples/idioms/programs/105.1804-current-executable-name.py:
--------------------------------------------------------------------------------
1 | """Current executable name.
2 |
3 | Assign to string _s the name of the currently executing program (but not its full path).
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: iLoveTux
9 | # Created on 2016-08-24T02:50:46.124706Z
10 | # Last modified on 2016-08-24T02:50:46.124706Z
11 | # Version 1
12 |
13 | # sys.argv[0] holds the name of the currently running script, you might use ___file__, but if called from within a module you would then get the module's ___file__ attribute.
14 |
15 | import sys
16 |
17 | s = sys.argv[0]
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/106.2039-get-program-working-directory.py:
--------------------------------------------------------------------------------
1 | """Get program working directory.
2 |
3 | Assign to string _dir the path of the working directory.
4 | (This is not necessarily the folder containing the executable itself)
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Legron
10 | # Created on 2017-07-10T14:50:39.556494Z
11 | # Last modified on 2017-07-14T14:53:11.341848Z
12 | # Version 2
13 |
14 | # _getcwd stands for Get the Current Working Directory
15 |
16 | import os
17 |
18 | dir = os.getcwd()
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/107.2139-get-folder-containing-current-program.py:
--------------------------------------------------------------------------------
1 | """Get folder containing current program.
2 |
3 | Assign to string _dir the path of the folder containing the currently running executable.
4 | (This is not necessarily the working directory, though.)
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2017-10-28T09:56:04.557618Z
11 | # Last modified on 2017-10-28T09:56:04.557618Z
12 | # Version 1
13 |
14 | import os
15 |
16 | dir = os.path.dirname(os.path.abspath(__file__))
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/108.1291-determine-if-variable-name-is-defined.py:
--------------------------------------------------------------------------------
1 | """Determine if variable name is defined.
2 |
3 | Print the value of variable _x, but only if _x has been declared in this program.
4 | This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)
5 |
6 | Note that this is (almost?) always an anti pattern. If you think you need this, look into appropriate data structures like maps/hashes instead.
7 |
8 | Source: programming-idioms.org
9 | """
10 |
11 | # Implementation author: alfred.p.bankwartz
12 | # Created on 2016-02-18T16:58:03.13025Z
13 | # Last modified on 2016-02-18T16:58:03.13025Z
14 | # Version 1
15 |
16 | # variable name must be quoted.
17 |
18 | if "x" in locals():
19 | print(x)
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/109.2280-number-of-bytes-of-a-type.py:
--------------------------------------------------------------------------------
1 | """Number of bytes of a type.
2 |
3 | Set _n to the number of bytes of a variable _t (of type _T).
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T19:02:43.323249Z
10 | # Last modified on 2018-04-08T19:02:43.323249Z
11 | # Version 1
12 |
13 | # `pip install pympler` to get this third-party library. `sys.getsizeof` is built-in, but has many common failure modes.
14 |
15 | import pympler.asizeof
16 |
17 | n = pympler.asizeof.asizeof(t)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/110.1455-check-if-string-is-blank.py:
--------------------------------------------------------------------------------
1 | """Check if string is blank.
2 |
3 | Set boolean _blank to _true if string _s is empty, or null, or contains only whitespace ; _false otherwise.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T16:58:03.22685Z
10 | # Last modified on 2019-09-26T20:40:16.940019Z
11 | # Version 6
12 |
13 | blank = s.strip() == ""
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/111.2168-launch-other-program.py:
--------------------------------------------------------------------------------
1 | """Launch other program.
2 |
3 | From current process, run program _x with command-line parameters "a", "b".
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T13:48:41.476134Z
10 | # Last modified on 2017-10-28T13:48:41.476134Z
11 | # Version 1
12 |
13 | import subprocess
14 |
15 | subprocess.call(["x", "a", "b"])
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/112.2144-iterate-over-map-entries-ordered-by-keys.py:
--------------------------------------------------------------------------------
1 | """Iterate over map entries, ordered by keys.
2 |
3 | Print each key _k with its value _x from an associative array _mymap, in ascending order of _k.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T10:33:16.415371Z
10 | # Last modified on 2019-09-26T16:13:29.479393Z
11 | # Version 3
12 |
13 | # dictionaries iterate over their keys by default
14 |
15 | for k in sorted(mymap):
16 | print(mymap[k])
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/113.2157-iterate-over-map-entries-ordered-by-values.py:
--------------------------------------------------------------------------------
1 | """Iterate over map entries, ordered by values.
2 |
3 | Print each key _k with its value _x from an associative array _mymap, in ascending order of _x.
4 | Note that multiple entries may exist for the same value _x.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2017-10-28T12:30:49.249241Z
11 | # Last modified on 2017-10-28T12:30:49.249241Z
12 | # Version 1
13 |
14 | for x, k in sorted((x, k) for k, x in mymap.items()):
15 | print(k, x)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/114.2273-test-deep-equality.py:
--------------------------------------------------------------------------------
1 | """Test deep equality.
2 |
3 | Set boolean _b to true if objects _x and _y contain the same values, recursively comparing all referenced elements in _x and _y.
4 | Tell if the code correctly handles recursive types.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: bukzor
10 | # Created on 2018-04-08T07:01:32.293233Z
11 | # Last modified on 2018-04-08T20:07:29.581057Z
12 | # Version 2
13 |
14 | # The classes of _x and _y need to delegate to any contained objects' __eq__ implementation.
15 | # All objects in the standard library do so.
16 |
17 | b = x == y
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/115.2138-compare-dates.py:
--------------------------------------------------------------------------------
1 | """Compare dates.
2 |
3 | Set boolean _b to true if date _d1 is strictly before date _d2 ; false otherwise.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T09:29:14.884355Z
10 | # Last modified on 2017-10-28T09:29:14.884355Z
11 | # Version 1
12 |
13 | # _d1, _d2 have type _date
14 |
15 | import datetime
16 |
17 | b = d1 < d2
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/116.1257-remove-occurrences-of-word-from-string.py:
--------------------------------------------------------------------------------
1 | """Remove occurrences of word from string.
2 |
3 | Remove all occurrences of string _w from string _s1, and store the result in _s2.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cym13
9 | # Created on 2016-02-18T16:58:03.499908Z
10 | # Last modified on 2016-02-18T16:58:03.499908Z
11 | # Version 1
12 |
13 | s2 = s1.replace(w, "")
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/117.1297-get-list-size.py:
--------------------------------------------------------------------------------
1 | """Get list size.
2 |
3 | Set _n to the number of elements of list _x.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Sek
9 | # Created on 2016-02-16T15:06:30.778688Z
10 | # Last modified on 2016-02-16T15:06:30.778688Z
11 | # Version 1
12 |
13 | n = len(x)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/118.1254-list-to-set.py:
--------------------------------------------------------------------------------
1 | """List to set.
2 |
3 | Create set _y from list _x.
4 | _x may contain duplicates. _y is unordered and has no repeated values.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: cym13
10 | # Created on 2016-02-18T16:58:03.624481Z
11 | # Last modified on 2016-02-18T16:58:03.624481Z
12 | # Version 1
13 |
14 | y = set(x)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/118.3266-list-to-set.py:
--------------------------------------------------------------------------------
1 | """List to set.
2 |
3 | Create set _y from list _x.
4 | _x may contain duplicates. _y is unordered and has no repeated values.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: L3viathan
10 | # Created on 2019-09-27T14:27:31.718869Z
11 | # Last modified on 2019-09-27T14:27:31.718869Z
12 | # Version 1
13 |
14 | set(x)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/119.1253-deduplicate-list.py:
--------------------------------------------------------------------------------
1 | """Deduplicate list.
2 |
3 | Remove duplicates from list _x.
4 | Explain if original order is preserved.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: cym13
10 | # Created on 2016-02-18T16:58:03.699367Z
11 | # Last modified on 2016-02-18T16:58:03.699367Z
12 | # Version 1
13 |
14 | x = list(set(x))
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/119.3263-deduplicate-list.py:
--------------------------------------------------------------------------------
1 | """Deduplicate list.
2 |
3 | Remove duplicates from list _x.
4 | Explain if original order is preserved.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Fazel94
10 | # Created on 2019-09-27T14:12:17.335663Z
11 | # Last modified on 2019-09-27T14:12:17.335663Z
12 | # Version 1
13 |
14 | # This snippet preserves the original order of the list
15 | elements = ["b", "a", "b", "c"]
16 | unique_set = set()
17 | elements_unique = []
18 | for i in elements:
19 | if i not in unique_set:
20 | unique_set.add(i)
21 | elements_unique.append(i)
22 | print(elements_unique) # outputs ["b", "a", "c"]
23 |
--------------------------------------------------------------------------------
/examples/idioms/programs/120.1479-read-integer-from-stdin.py:
--------------------------------------------------------------------------------
1 | """Read integer from stdin.
2 |
3 | Read an integer value from the standard input into variable _n.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Trshant
9 | # Created on 2016-02-18T16:58:03.740088Z
10 | # Last modified on 2016-02-18T16:58:03.740088Z
11 | # Version 1
12 |
13 | input_var = int(raw_input("Input Prompting String: "))
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/121.3029-udp-listen-and-read.py:
--------------------------------------------------------------------------------
1 | """UDP listen and read.
2 |
3 | Listen UDP traffic on port _p and read 1024 bytes into buffer _b.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: awesmubarak
9 | # Created on 2019-09-26T19:14:27.532845Z
10 | # Last modified on 2019-09-26T19:28:59.877508Z
11 | # Version 2
12 |
13 | import socket
14 |
15 | UDP_IP = "127.0.0.1"
16 |
17 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
18 | sock.bind((UDP_IP, p))
19 | while True:
20 | data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
21 | print("received message:", data)
22 |
--------------------------------------------------------------------------------
/examples/idioms/programs/122.1453-declare-enumeration.py:
--------------------------------------------------------------------------------
1 | """Declare enumeration.
2 |
3 | Create an enumerated type _Suit with 4 possible values _SPADES, _HEARTS, _DIAMONDS, _CLUBS.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T16:58:03.828361Z
10 | # Last modified on 2016-02-18T16:58:03.828361Z
11 | # Version 1
12 |
13 | # Fake enum, works with any version of python.
14 |
15 |
16 | class Suit:
17 | SPADES, HEARTS, DIAMONDS, CLUBS = range(4)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/122.1454-declare-enumeration.py:
--------------------------------------------------------------------------------
1 | """Declare enumeration.
2 |
3 | Create an enumerated type _Suit with 4 possible values _SPADES, _HEARTS, _DIAMONDS, _CLUBS.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: TinyFawks
9 | # Created on 2016-02-18T16:58:03.828361Z
10 | # Last modified on 2016-11-06T23:13:31.574716Z
11 | # Version 2
12 |
13 | # New in Python 3.4
14 |
15 | from enum import Enum
16 |
17 |
18 | class Suit(Enum):
19 | SPADES = 1
20 | HEARTS = 2
21 | DIAMONDS = 3
22 | CLUBS = 4
23 |
--------------------------------------------------------------------------------
/examples/idioms/programs/123.2146-assert-condition.py:
--------------------------------------------------------------------------------
1 | """Assert condition.
2 |
3 | Verify that predicate _isConsistent returns true, otherwise report assertion violation.
4 | Explain if the assertion is executed even in production environment or not.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2017-10-28T10:54:23.223151Z
11 | # Last modified on 2017-10-28T10:54:23.223151Z
12 | # Version 1
13 |
14 | # raises _AssertionError Exception.
15 | #
16 | # Running Python with option _-O or with _PYTHONOPTIMZE
17 | # environment variable suppresses all asserts.
18 |
19 | assert isConsistent
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/124.2152-binary-search-for-a-value-in-sorted-array.py:
--------------------------------------------------------------------------------
1 | """Binary search for a value in sorted array.
2 |
3 | Write function _binarySearch which returns the index of an element having value _x in sorted array _a, or -1 if no such element.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T11:30:06.348956Z
10 | # Last modified on 2017-10-28T11:30:06.348956Z
11 | # Version 1
12 |
13 | import bisect
14 |
15 |
16 | def binarySearch(a, x):
17 | i = bisect.bisect_left(a, x)
18 | return i if i != len(a) and a[i] == x else -1
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/125.2167-measure-function-call-duration.py:
--------------------------------------------------------------------------------
1 | """Measure function call duration.
2 |
3 | measure the duration _t, in nano seconds, of a call to the function _foo. Print this duration.
4 |
5 | Source: JPSII
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T13:42:06.259364Z
10 | # Last modified on 2017-10-28T13:42:06.259364Z
11 | # Version 1
12 |
13 | # _t1 and _t2 are 64bit _float
14 |
15 | import time
16 |
17 | t1 = time.perf_counter()
18 | foo()
19 | t2 = time.perf_counter()
20 | print("Seconds:", t2 - t1)
21 |
--------------------------------------------------------------------------------
/examples/idioms/programs/126.2137-multiple-return-values.py:
--------------------------------------------------------------------------------
1 | """Multiple return values.
2 |
3 | Write a function _foo that returns a _string and a _boolean value.
4 |
5 | Source: MLKo
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T09:19:40.922778Z
10 | # Last modified on 2017-10-28T09:19:40.922778Z
11 | # Version 1
12 |
13 |
14 | def foo():
15 | return "string", True
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/127.2274-source-code-inclusion.py:
--------------------------------------------------------------------------------
1 | """Source code inclusion.
2 |
3 | Import the source code for the function _foo body from a file "foobody.txt" . The declaration must not reside in the external file.
4 |
5 | Source: MLKo
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T07:19:33.894869Z
10 | # Last modified on 2018-04-08T07:20:06.900516Z
11 | # Version 2
12 |
13 | # To remove all side-effects: del sys.modules['foobody']
14 |
15 | import imp
16 |
17 | foo = imp.load_module("foobody", "foobody.txt").foo
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/128.2085-breadth-first-traversing-of-a-tree.py:
--------------------------------------------------------------------------------
1 | """Breadth-first traversing of a tree.
2 |
3 | Call a function _f on every node of a tree, in breadth-first prefix order
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cpoulet_42
9 | # Created on 2017-08-09T09:52:02.728772Z
10 | # Last modified on 2017-08-09T22:27:55.685981Z
11 | # Version 2
12 |
13 |
14 | def BFS(f, root):
15 | Q = [root]
16 | while Q:
17 | n = Q.pop(0)
18 | f(n)
19 | for child in n:
20 | if not n.discovered:
21 | n.discovered = True
22 | Q.append(n)
23 |
--------------------------------------------------------------------------------
/examples/idioms/programs/129.2282-breadth-first-traversing-in-a-graph.py:
--------------------------------------------------------------------------------
1 | """Breadth-first traversing in a graph.
2 |
3 | Call a function _f on every vertex accessible from vertex _start, in breadth-first prefix order
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T19:15:40.73175Z
10 | # Last modified on 2018-04-08T19:15:40.73175Z
11 | # Version 1
12 |
13 | # It's best to not recurse in Python when the structure size is unknown, since we have a fixed, small stack size.
14 |
15 | from collections import deque
16 |
17 |
18 | def breadth_first(start, f):
19 | seen = set()
20 | q = deque([start])
21 | while q:
22 | vertex = q.popleft()
23 | f(vertex)
24 | seen.add(vertex)
25 | q.extend(v for v in vertex.adjacent if v not in seen)
26 |
--------------------------------------------------------------------------------
/examples/idioms/programs/130.2283-depth-first-traversing-in-a-graph.py:
--------------------------------------------------------------------------------
1 | """Depth-first traversing in a graph.
2 |
3 | Call a function _f on every vertex accessible for vertex _v, in depth-first prefix order
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T19:17:47.214988Z
10 | # Last modified on 2018-04-08T19:18:25.491984Z
11 | # Version 2
12 |
13 | # It's best to not recurse in Python when the structure size is unknown, since we have a fixed, small stack size.
14 |
15 |
16 | def depth_first(start, f):
17 | seen = set()
18 | stack = [start]
19 | while stack:
20 | vertex = stack.pop() # paroxython: -member_call_method:pop +member_call_method:list:pop
21 | f(vertex)
22 | seen.add(vertex)
23 | stack.extend(v for v in vertex.adjacent if v not in seen)
24 |
--------------------------------------------------------------------------------
/examples/idioms/programs/131.2083-successive-conditions.py:
--------------------------------------------------------------------------------
1 | """Successive conditions.
2 |
3 | Execute _f1 if condition _c1 is true, or else _f2 if condition _c2 is true, or else _f3 if condition _c3 is true.
4 | Don't evaluate a condition when a previous condition was true.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: cpoulet_42
10 | # Created on 2017-08-09T08:48:05.281879Z
11 | # Last modified on 2017-08-09T22:28:27.724165Z
12 | # Version 2
13 |
14 | f1 if c1 else f2 if c2 else f3 if c3 else None
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/131.2766-successive-conditions.py:
--------------------------------------------------------------------------------
1 | """Successive conditions.
2 |
3 | Execute _f1 if condition _c1 is true, or else _f2 if condition _c2 is true, or else _f3 if condition _c3 is true.
4 | Don't evaluate a condition when a previous condition was true.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: koltrast
10 | # Created on 2019-09-26T14:49:24.58635Z
11 | # Last modified on 2019-09-26T14:49:24.58635Z
12 | # Version 1
13 |
14 | if c1:
15 | f1()
16 | elif c2:
17 | f2()
18 | elif c3:
19 | f3()
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/132.2040-measure-duration-of-procedure-execution.py:
--------------------------------------------------------------------------------
1 | """Measure duration of procedure execution.
2 |
3 | Run procedure _f, and return the duration of the execution of _f.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Legron
9 | # Created on 2017-07-10T14:58:55.028109Z
10 | # Last modified on 2017-07-10T14:58:55.028109Z
11 | # Version 1
12 |
13 | # Setup makes the function _f accessible to timeit. Returned is the execution time in seconds
14 |
15 | import timeit
16 |
17 | duration = timeit.timeit("f()", setup="from __main__ import f")
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/133.2160-case-insensitive-string-contains.py:
--------------------------------------------------------------------------------
1 | """Case-insensitive string contains.
2 |
3 | Set boolean _ok to _true if string _word is contained in string _s as a substring, even if the case doesn't match, or to _false otherwise.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T12:37:36.700086Z
10 | # Last modified on 2017-10-28T12:37:36.700086Z
11 | # Version 1
12 |
13 | ok = word.lower() in s.lower()
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/134.1850-create-a-new-list.py:
--------------------------------------------------------------------------------
1 | """Create a new list.
2 |
3 | Declare and initialize a new list _items, containing 3 elements _a, _b, _c.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-10-20T11:54:59.397725Z
10 | # Last modified on 2016-10-20T11:54:59.397725Z
11 | # Version 1
12 |
13 | items = [a, b, c]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/135.2158-remove-item-from-list-by-its-value.py:
--------------------------------------------------------------------------------
1 | """Remove item from list, by its value.
2 |
3 | Remove at most 1 item from list _items, having value _x.
4 | This will alter the original list or return a new list, depending on which is more idiomatic. If there are several occurrences of _x in _items, remove only one of them.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2017-10-28T12:32:55.201435Z
11 | # Last modified on 2017-10-28T12:32:55.201435Z
12 | # Version 1
13 |
14 | items.remove(x)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/136.2141-remove-all-occurrences-of-a-value-from-a-list.py:
--------------------------------------------------------------------------------
1 | """ Remove all occurrences of a value from a list.
2 |
3 | Remove all occurrences of value _x from list _items.
4 | This will alter the original list or return a new list, depending on which is more idiomatic.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2017-10-28T10:22:48.548691Z
11 | # Last modified on 2017-10-28T10:22:48.548691Z
12 | # Version 1
13 |
14 | newlist = [item for item in items if item != x]
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/137.1823-check-if-string-contains-only-digits.py:
--------------------------------------------------------------------------------
1 | """Check if string contains only digits.
2 |
3 | Set boolean _b to _true if string _s contains only characters in range '0'..'9', _false otherwise.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cons0l3
9 | # Created on 2016-09-14T08:32:37.746156Z
10 | # Last modified on 2016-09-14T20:42:12.069228Z
11 | # Version 2
12 |
13 | b = s.isdigit()
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/138.2161-create-temp-file.py:
--------------------------------------------------------------------------------
1 | """Create temp file.
2 |
3 | Create a new temporary file on filesystem.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T12:51:14.76788Z
10 | # Last modified on 2017-11-18T23:26:36.830566Z
11 | # Version 2
12 |
13 | import tempfile
14 |
15 | file = tempfile.TemporaryFile()
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/139.2162-create-temp-directory.py:
--------------------------------------------------------------------------------
1 | """Create temp directory.
2 |
3 | Create a new temporary folder on filesystem, for writing.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T12:53:16.156619Z
10 | # Last modified on 2017-11-18T23:25:38.458057Z
11 | # Version 2
12 |
13 | # tempfile._TemporaryDirectory() was added in Python 3.2 .
14 | # It wraps lower-level function _mkdtemp() .
15 |
16 | import tempfile
17 |
18 | td = tempfile.TemporaryDirectory()
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/140.2156-delete-map-entry.py:
--------------------------------------------------------------------------------
1 | """Delete map entry.
2 |
3 | Delete from map _m the entry having key _k.
4 |
5 | Explain what happens if _k is not an existing key in _m.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: Oldboy
11 | # Created on 2017-10-28T12:10:35.967798Z
12 | # Last modified on 2017-10-28T12:13:29.517006Z
13 | # Version 2
14 |
15 | # A missing key will leave the map unchanged.
16 | #
17 | # If the second parameter is omitted, a missing key will raise the exception _KeyError
18 |
19 | m.pop(k, None)
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/141.2159-iterate-in-sequence-over-two-lists.py:
--------------------------------------------------------------------------------
1 | """Iterate in sequence over two lists.
2 |
3 | Iterate in sequence over the elements of the list _items1 then _items2. For each iteration print the element.
4 |
5 | Source: BBaz
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T12:34:37.289797Z
10 | # Last modified on 2017-10-28T12:34:37.289797Z
11 | # Version 1
12 |
13 | for x in items1 + items2:
14 | print(x)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/142.2151-hexadecimal-digits-of-an-integer.py:
--------------------------------------------------------------------------------
1 | """Hexadecimal digits of an integer.
2 |
3 | Assign to string _s the hexadecimal representation (base 16) of integer _x.
4 |
5 | E.g. 999 -> "3e7"
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: Oldboy
11 | # Created on 2017-10-28T11:11:15.149108Z
12 | # Last modified on 2019-09-26T18:30:31.797796Z
13 | # Version 2
14 |
15 | s = hex(x)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/143.2256-iterate-alternatively-over-two-lists.py:
--------------------------------------------------------------------------------
1 | """Iterate alternatively over two lists.
2 |
3 | Iterate alternatively over the elements of the list _items1 and _items2. For each iteration, print the element.
4 |
5 | Explain what happens if _items1 and _items2 have different size.
6 |
7 | Source: BBaz
8 | """
9 |
10 | # Implementation author: Xris
11 | # Created on 2018-03-27T11:45:39.203775Z
12 | # Last modified on 2018-03-27T11:56:30.155613Z
13 | # Version 2
14 |
15 | # This will print former min(len(item1), item(2)) pairs if len(item1) != len(item2).
16 |
17 | for pair in zip(item1, item2):
18 | print(pair)
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/144.2145-check-if-file-exists.py:
--------------------------------------------------------------------------------
1 | """Check if file exists.
2 |
3 | Set boolean _b to _true if file at path _fp exists on filesystem; _false otherwise.
4 |
5 | Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: Oldboy
11 | # Created on 2017-10-28T10:44:48.697654Z
12 | # Last modified on 2017-10-28T10:44:48.697654Z
13 | # Version 1
14 |
15 | import os
16 |
17 | b = os.path.exists(fp)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/144.2915-check-if-file-exists.py:
--------------------------------------------------------------------------------
1 | """Check if file exists.
2 |
3 | Set boolean _b to _true if file at path _fp exists on filesystem; _false otherwise.
4 |
5 | Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: ims
11 | # Created on 2019-09-26T17:01:46.595718Z
12 | # Last modified on 2019-09-26T17:02:43.549382Z
13 | # Version 3
14 |
15 | from pathlib import Path
16 |
17 | b = Path(fp).exists()
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/145.1822-print-log-line-with-datetime.py:
--------------------------------------------------------------------------------
1 | """Print log line with datetime.
2 |
3 | Print message _msg, prepended by current date and time.
4 |
5 | Explain what behavior is idiomatic: to _stdout or _stderr, and what the date format is.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: cons0l3
11 | # Created on 2016-09-14T08:27:08.139734Z
12 | # Last modified on 2016-09-17T21:34:16.405525Z
13 | # Version 5
14 |
15 | # Default output is stderr.
16 | #
17 | # Date format is ISO 8601.
18 |
19 | import sys, logging
20 |
21 | logging.basicConfig(
22 | stream=sys.stdout, level=logging.DEBUG, format="%(asctime)-15s %(message)s"
23 | )
24 | logger = logging.getLogger("NAME OF LOGGER")
25 |
26 | logger.info(msg)
27 |
--------------------------------------------------------------------------------
/examples/idioms/programs/146.1825-convert-string-to-floating-point-number.py:
--------------------------------------------------------------------------------
1 | """Convert string to floating point number.
2 |
3 | Extract floating point value _f from its string representation _s
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: cons0l3
9 | # Created on 2016-09-14T08:41:41.829008Z
10 | # Last modified on 2016-09-17T21:39:03.333125Z
11 | # Version 2
12 |
13 | # When working with different locale decimal and thousand separators you have to use _locale._atof
14 |
15 | import locale
16 |
17 | s = u"545,2222"
18 | locale.setlocale(locale.LC_ALL, "de")
19 | f = locale.atof(s)
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/146.1826-convert-string-to-floating-point-number.py:
--------------------------------------------------------------------------------
1 | """Convert string to floating point number.
2 |
3 | Extract floating point value _f from its string representation _s
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2016-09-17T21:38:36.556536Z
10 | # Last modified on 2016-09-17T21:38:36.556536Z
11 | # Version 1
12 |
13 | f = float(s)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/146.2739-convert-string-to-floating-point-number.py:
--------------------------------------------------------------------------------
1 | """Convert string to floating point number.
2 |
3 | Extract floating point value _f from its string representation _s
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: mk
9 | # Created on 2019-09-26T14:27:21.128091Z
10 | # Last modified on 2019-09-26T14:27:21.128091Z
11 | # Version 1
12 |
13 | float("1.3")
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/147.2171-remove-all-non-ascii-characters.py:
--------------------------------------------------------------------------------
1 | """Remove all non-ASCII characters.
2 |
3 | Create string _t from string _s, keeping only ASCII characters
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-29T09:50:15.686412Z
10 | # Last modified on 2017-10-29T09:50:15.686412Z
11 | # Version 1
12 |
13 | import re
14 |
15 | t = re.sub("[^\u0000-\u007f]", "", s)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/148.1829-read-list-of-integer-numbers-from-stdin.py:
--------------------------------------------------------------------------------
1 | """Read list of integer numbers from stdin.
2 |
3 |
4 | Source: psqq
5 | """
6 |
7 | # Implementation author: psqq
8 | # Created on 2016-10-02T08:32:13.212352Z
9 | # Last modified on 2016-10-02T08:32:13.212352Z
10 | # Version 1
11 |
12 | list(map(int, input().split()))
13 |
--------------------------------------------------------------------------------
/examples/idioms/programs/150.2154-remove-trailing-slash.py:
--------------------------------------------------------------------------------
1 | """Remove trailing slash.
2 |
3 | Remove last character from string _p, if this character is a slash /.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T11:49:04.31534Z
10 | # Last modified on 2019-09-26T20:20:55.019033Z
11 | # Version 2
12 |
13 | p = p.rstrip("/")
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/151.2166-remove-string-trailing-path-separator.py:
--------------------------------------------------------------------------------
1 | """Remove string trailing path separator.
2 |
3 | Remove last character from string _p, if this character is the file path separator of current platform.
4 |
5 | Note that this also transforms unix root path "/" into empty string!
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: Oldboy
11 | # Created on 2017-10-28T13:33:02.066456Z
12 | # Last modified on 2017-10-28T13:33:02.066456Z
13 | # Version 1
14 |
15 | import os
16 |
17 | if p.endswith(os.sep):
18 | p = p[:-1]
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/152.2153-turn-a-character-into-a-string.py:
--------------------------------------------------------------------------------
1 | """Turn a character into a string.
2 |
3 | Create string _s containing only the character _c.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T11:41:42.20071Z
10 | # Last modified on 2017-10-28T11:41:42.20071Z
11 | # Version 1
12 |
13 | # a character is a single character string, not a distinct datataype
14 |
15 | s = c
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/153.1980-concatenate-string-with-integer.py:
--------------------------------------------------------------------------------
1 | """Concatenate string with integer.
2 |
3 | Create string _t as the concatenation of string _s and integer _i.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Roming22
9 | # Created on 2017-04-27T17:56:43.707218Z
10 | # Last modified on 2017-04-27T17:56:43.707218Z
11 | # Version 1
12 |
13 | t = "{}{}".format(s, i)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/154.2155-halfway-between-two-hex-color-codes.py:
--------------------------------------------------------------------------------
1 | """Halfway between two hex color codes.
2 |
3 | Find color _c, the average between colors _c1, _c2.
4 |
5 | _c, _c1, _c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
6 | Assume linear computations, ignore gamma corrections.
7 |
8 | Source: programming-idioms.org
9 | """
10 |
11 | # Implementation author: Oldboy
12 | # Created on 2017-10-28T12:06:58.817755Z
13 | # Last modified on 2017-10-28T12:06:58.817755Z
14 | # Version 1
15 |
16 | r1, g1, b1 = [int(c1[p : p + 2], 16) for p in range(1, 6, 2)]
17 | r2, g2, b2 = [int(c2[p : p + 2], 16) for p in range(1, 6, 2)]
18 | c = "#{:02x}{:02x}{:02x}".format((r1 + r2) // 2, (g1 + g2) // 2, (b1 + b2) // 2)
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/154.2292-halfway-between-two-hex-color-codes.py:
--------------------------------------------------------------------------------
1 | """Halfway between two hex color codes.
2 |
3 | Find color _c, the average between colors _c1, _c2.
4 |
5 | _c, _c1, _c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
6 | Assume linear computations, ignore gamma corrections.
7 |
8 | Source: programming-idioms.org
9 | """
10 |
11 | # Implementation author: bukzor
12 | # Created on 2018-04-14T05:28:36.956894Z
13 | # Last modified on 2018-04-14T16:12:35.539002Z
14 | # Version 2
15 |
16 | # numpy is standard for array numerics, and works nicely for this problem. We can represent a RGB value as a special numpy array.
17 |
18 | import numpy
19 |
20 |
21 | class RGB(numpy.ndarray):
22 | @classmethod
23 | def from_str(cls, rgbstr):
24 | return numpy.array(
25 | [int(rgbstr[i : i + 2], 16) for i in range(1, len(rgbstr), 2)]
26 | ).view(cls)
27 |
28 | def __str__(self):
29 | self = self.astype(numpy.uint8)
30 | return "#" + "".join(format(n, "x") for n in self)
31 |
32 |
33 | c1 = RGB.from_str("#a1b1c1")
34 | print(c1)
35 | c2 = RGB.from_str("#1A1B1C")
36 | print(c2)
37 |
38 | print((c1 + c2) / 2)
39 |
--------------------------------------------------------------------------------
/examples/idioms/programs/155.2147-delete-file.py:
--------------------------------------------------------------------------------
1 | """Delete file.
2 |
3 | Delete from filesystem the file having path _filepath.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T10:56:11.056208Z
10 | # Last modified on 2019-09-26T15:16:25.002814Z
11 | # Version 2
12 |
13 | import pathlib
14 |
15 | path = pathlib.Path(_filepath)
16 | path.unlink()
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/156.2148-format-integer-with-zero-padding.py:
--------------------------------------------------------------------------------
1 | """Format integer with zero-padding.
2 |
3 | Assign to string _s the value of integer _i in 3 decimal digits. Pad with zeros if _i < _100. Keep all digits if _i ≥ _1000.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T10:59:52.748247Z
10 | # Last modified on 2017-10-28T10:59:52.748247Z
11 | # Version 1
12 |
13 | s = format("03d", i)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/157.2150-declare-constant-string.py:
--------------------------------------------------------------------------------
1 | """Declare constant string.
2 |
3 | Initialize a constant _planet with string value "Earth".
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T11:07:33.453323Z
10 | # Last modified on 2017-10-28T11:07:33.453323Z
11 | # Version 1
12 |
13 | # Names of constants are by convention written in uppercase
14 |
15 | PLANET = "Earth"
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/158.2163-random-sublist.py:
--------------------------------------------------------------------------------
1 | """Random sublist.
2 |
3 | Create a new list _y from randomly picking exactly _k elements from list _x.
4 |
5 | It is assumed that _x has at least _k elements.
6 | Each element must have same probability to be picked.
7 | Each element from _x must be picked _at _most _once.
8 | Explain if the original ordering is preserved or not.
9 |
10 | Source: programming-idioms.org
11 | """
12 |
13 | # Implementation author: Oldboy
14 | # Created on 2017-10-28T13:10:20.094421Z
15 | # Last modified on 2018-06-24T13:08:32.325774Z
16 | # Version 2
17 |
18 | # The original ordering is not preserved.
19 |
20 | import random
21 |
22 | y = random.sample(x, k)
23 |
--------------------------------------------------------------------------------
/examples/idioms/programs/159.2281-trie.py:
--------------------------------------------------------------------------------
1 | """Trie.
2 |
3 | Define a Trie data structure, where entries have an associated value.
4 | (Not all nodes are entries)
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: bukzor
10 | # Created on 2018-04-08T19:10:28.833888Z
11 | # Last modified on 2018-04-08T19:10:28.833888Z
12 | # Version 1
13 |
14 |
15 | class Trie:
16 | def __init__(self, prefix, value=None):
17 | self.prefix = prefix
18 | self.children = []
19 | self.value = value
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/160.2165-detect-if-32-bit-or-64-bit-architecture.py:
--------------------------------------------------------------------------------
1 | """Detect if 32-bit or 64-bit architecture.
2 |
3 | Execute _f32() if platform is 32-bit, or _f64() if platform is 64-bit.
4 | This can be either a compile-time condition (depending on target) or a runtime detection.
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2017-10-28T13:28:42.005738Z
11 | # Last modified on 2017-10-28T13:28:42.005738Z
12 | # Version 1
13 |
14 | # runtime check
15 |
16 | import sys
17 |
18 | if sys.maxsize > 2 ** 32:
19 | f64()
20 | else:
21 | f32()
22 |
--------------------------------------------------------------------------------
/examples/idioms/programs/161.2098-multiply-all-the-elements-of-a-list.py:
--------------------------------------------------------------------------------
1 | """Multiply all the elements of a list.
2 |
3 | Multiply all the elements of the list _elements by a constant _c
4 |
5 | Source: Bzzzzzzzzz
6 | """
7 |
8 | # Implementation author: npicca
9 | # Created on 2017-08-31T23:21:18.274771Z
10 | # Last modified on 2019-09-26T16:11:47.367428Z
11 | # Version 2
12 |
13 | # This maps the lambda function that multiplies a number by _c to the list _elements , and overwrites the old list
14 |
15 | elements = [c * x for x in elements]
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/162.2164-execute-procedures-depending-on-options.py:
--------------------------------------------------------------------------------
1 | """Execute procedures depending on options.
2 |
3 | execute _bat if _b is a program option and _fox if _f is a program option.
4 |
5 | Source: Bzzzzzzzzzz
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T13:18:02.415672Z
10 | # Last modified on 2017-10-28T13:18:02.415672Z
11 | # Version 1
12 |
13 | import sys
14 |
15 | if "b" in sys.argv[1:]:
16 | bat()
17 | if "f" in sys.argv[1:]:
18 | fox()
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/163.2170-print-list-elements-by-group-of-2.py:
--------------------------------------------------------------------------------
1 | """Print list elements by group of 2.
2 |
3 | Print all the _list elements, two by two, assuming _list length is even.
4 |
5 | Source: Bzzzzzzzzzz
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T14:00:36.671699Z
10 | # Last modified on 2017-11-18T23:17:29.372798Z
11 | # Version 2
12 |
13 | # original list is called _list
14 |
15 | for x in zip(list[::2], list[1::2]):
16 | print(x)
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/163.3177-print-list-elements-by-group-of-2.py:
--------------------------------------------------------------------------------
1 | """Print list elements by group of 2.
2 |
3 | Print all the _list elements, two by two, assuming _list length is even.
4 |
5 | Source: Bzzzzzzzzzz
6 | """
7 |
8 | # Implementation author: sgdpk
9 | # Created on 2019-09-27T04:00:54.357549Z
10 | # Last modified on 2019-09-27T04:00:54.357549Z
11 | # Version 1
12 |
13 | # Official documentation suggestion. Works for any iterable
14 |
15 | from itertools import tee
16 |
17 |
18 | def pairwise(iterable):
19 | "s -> (s0,s1), (s1,s2), (s2, s3), ..."
20 | a, b = tee(iterable)
21 | next(b, None)
22 | return zip(a, b)
23 |
24 |
25 | for a, b in pairwise(list):
26 | print(a, b)
27 |
--------------------------------------------------------------------------------
/examples/idioms/programs/164.2169-open-url-in-default-browser.py:
--------------------------------------------------------------------------------
1 | """Open URL in default browser.
2 |
3 | Open the URL _s in the default browser.
4 | Set boolean _b to indicate wether the operation was succesfull.
5 |
6 | Source: Bart
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2017-10-28T13:55:40.048963Z
11 | # Last modified on 2019-09-26T13:41:45.466068Z
12 | # Version 2
13 |
14 | # _b is not available
15 |
16 | import webbrowser
17 |
18 | webbrowser.open(s)
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/165.2149-last-element-of-list.py:
--------------------------------------------------------------------------------
1 | """Last element of list.
2 |
3 | Assign to variable _x the last element of list _items.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2017-10-28T11:02:52.087708Z
10 | # Last modified on 2017-10-28T11:02:52.087708Z
11 | # Version 1
12 |
13 | x = items[-1]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/166.2272-concatenate-two-lists.py:
--------------------------------------------------------------------------------
1 | """Concatenate two lists.
2 |
3 | Create list _ab containing all the elements of list _a, followed by all elements of list _b.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T06:59:30.796888Z
10 | # Last modified on 2018-04-08T06:59:30.796888Z
11 | # Version 1
12 |
13 | ab = a + b
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/167.2611-trim-prefix.py:
--------------------------------------------------------------------------------
1 | """Trim prefix.
2 |
3 | Create string _t consisting of string _s with its prefix _p removed (if _s starts with _p).
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Oldboy
9 | # Created on 2019-02-11T19:53:53.767084Z
10 | # Last modified on 2019-02-11T19:53:53.767084Z
11 | # Version 1
12 |
13 | t = s[s.startswith(p) and len(p) :]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/167.3175-trim-prefix.py:
--------------------------------------------------------------------------------
1 | """Trim prefix.
2 |
3 | Create string _t consisting of string _s with its prefix _p removed (if _s starts with _p).
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: sgdpk
9 | # Created on 2019-09-27T03:56:46.589873Z
10 | # Last modified on 2019-09-27T03:56:46.589873Z
11 | # Version 1
12 |
13 | t = s.lstrip(p)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/168.2277-trim-suffix.py:
--------------------------------------------------------------------------------
1 | """Trim suffix.
2 |
3 | Create string _t consisting of string _s with its suffix _w removed (if _s ends with _w).
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: bukzor
9 | # Created on 2018-04-08T07:26:47.248912Z
10 | # Last modified on 2018-04-08T07:26:47.248912Z
11 | # Version 1
12 |
13 | t = s.rsplit(w, 1)[0]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/168.3174-trim-suffix.py:
--------------------------------------------------------------------------------
1 | """Trim suffix.
2 |
3 | Create string _t consisting of string _s with its suffix _w removed (if _s ends with _w).
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: sgdpk
9 | # Created on 2019-09-27T03:54:34.623511Z
10 | # Last modified on 2019-09-27T03:54:34.623511Z
11 | # Version 1
12 |
13 | t = s.rstrip(w)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/169.2233-string-length.py:
--------------------------------------------------------------------------------
1 | """String length.
2 |
3 | Assign to integer _n the number of characters of string _s.
4 |
5 | This can be different from the number of bytes of _s.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: LucianoRamalho
11 | # Created on 2018-02-14T15:11:54.603668Z
12 | # Last modified on 2018-02-14T15:11:54.603668Z
13 | # Version 1
14 |
15 | # If _s is a Python 3 _str, or a Python 2 _unicode, _len(s) returns the number of characters. If _s is a Python 2 _str or a Python 3 _bytes, _len(s) returns the number of bytes.
16 |
17 | n = len(s)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/170.2275-get-map-size.py:
--------------------------------------------------------------------------------
1 | """Get map size.
2 |
3 | Set _n to the number of elements stored in _mymap.
4 |
5 | This is not always equal to the map capacity.
6 |
7 | Source: programming-idioms.org
8 | """
9 |
10 | # Implementation author: bukzor
11 | # Created on 2018-04-08T07:21:23.163901Z
12 | # Last modified on 2018-04-08T07:21:23.163901Z
13 | # Version 1
14 |
15 | n = len(mymap)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/171.2446-add-an-element-at-the-end-of-a-list.py:
--------------------------------------------------------------------------------
1 | """Add an element at the end of a list.
2 |
3 | Append element _x to the list _s.
4 |
5 | Source: programming-idioms
6 | """
7 |
8 | # Implementation author: Xanman
9 | # Created on 2018-10-09T21:27:12.797854Z
10 | # Last modified on 2018-10-09T21:27:12.797854Z
11 | # Version 1
12 |
13 | s.append(x)
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/172.2442-insert-entry-in-map.py:
--------------------------------------------------------------------------------
1 | """Insert entry in map.
2 |
3 | Insert value _v for key _k in map _m.
4 |
5 | Source: programming-idioms
6 | """
7 |
8 | # Implementation author: gustavotcabral
9 | # Created on 2018-09-24T18:17:34.508166Z
10 | # Last modified on 2018-09-24T18:17:34.508166Z
11 | # Version 1
12 |
13 | # If _m[_k] already exists, then it is overwritten.
14 |
15 | m[k] = v
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/173.2427-format-a-number-with-grouped-thousands.py:
--------------------------------------------------------------------------------
1 | """Format a number with grouped thousands.
2 |
3 | Number will be formatted with a comma separator between every group of thousands.
4 |
5 | Source: cup
6 | """
7 |
8 | # Implementation author: cup
9 | # Created on 2018-09-17T20:09:08.888749Z
10 | # Last modified on 2018-09-17T20:09:08.888749Z
11 | # Version 1
12 |
13 | print("f'{1000:,}'")
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/173.2428-format-a-number-with-grouped-thousands.py:
--------------------------------------------------------------------------------
1 | """Format a number with grouped thousands.
2 |
3 | Number will be formatted with a comma separator between every group of thousands.
4 |
5 | Source: cup
6 | """
7 |
8 | # Implementation author: cup
9 | # Created on 2018-09-17T20:09:55.503266Z
10 | # Last modified on 2018-09-17T20:09:55.503266Z
11 | # Version 1
12 |
13 | print("format(1000, ',')")
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/173.2429-format-a-number-with-grouped-thousands.py:
--------------------------------------------------------------------------------
1 | """Format a number with grouped thousands.
2 |
3 | Number will be formatted with a comma separator between every group of thousands.
4 |
5 | Source: cup
6 | """
7 |
8 | # Implementation author: cup
9 | # Created on 2018-09-17T20:10:23.485375Z
10 | # Last modified on 2018-09-17T20:10:23.485375Z
11 | # Version 1
12 |
13 | print("'{:,}'.format(1000)")
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/174.2687-make-http-post-request.py:
--------------------------------------------------------------------------------
1 | """Make HTTP POST request.
2 |
3 | Make a HTTP request with method POST to URL _u
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: random
9 | # Created on 2019-09-26T13:28:18.453487Z
10 | # Last modified on 2019-09-26T13:28:18.453487Z
11 | # Version 1
12 |
13 | # Explicit use of the "method" parameter, because "GET" is used when "data" is None
14 |
15 | from urllib import request, parse
16 |
17 | data = parse.urlencode("").encode()
18 | req = request.Request(u, data=data, method="POST")
19 | resp = request.urlopen(req)
20 |
--------------------------------------------------------------------------------
/examples/idioms/programs/175.2613-bytes-to-hex-string.py:
--------------------------------------------------------------------------------
1 | """Bytes to hex string.
2 |
3 | From array _a of _n bytes, build the equivalent hex string _s of _2n digits.
4 | Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit).
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2019-02-11T19:59:47.908514Z
11 | # Last modified on 2019-03-26T21:24:42.48353Z
12 | # Version 2
13 |
14 | s = a.hex()
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/176.2614-hex-string-to-byte-array.py:
--------------------------------------------------------------------------------
1 | """Hex string to byte array.
2 |
3 | From hex string _s of _2n digits, build the equivalent array _a of _n bytes.
4 | Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).
5 |
6 | Source: programming-idioms.org
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2019-02-11T20:01:36.48212Z
11 | # Last modified on 2019-03-26T21:23:37.827454Z
12 | # Version 2
13 |
14 | a = bytearray.fromhex(s)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/177.2709-find-files-with-a-given-list-of-filename-extensions.py:
--------------------------------------------------------------------------------
1 | """Find files with a given list of filename extensions.
2 |
3 | Construct a list _L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory _D and all it's subdirectories.
4 |
5 | Source: Bart
6 | """
7 |
8 | # Implementation author: citizenkong
9 | # Created on 2019-09-26T13:56:17.499124Z
10 | # Last modified on 2019-09-27T11:00:18.993182Z
11 | # Version 2
12 |
13 | # Doesn't look in subdirectories because I didn't read the question properly.
14 |
15 | import os
16 |
17 | extensions = [".jpg", ".jpeg", ".png"]
18 | L = [f for f in os.listdir(D) if os.path.splitext(f)[1] in extensions]
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/177.2725-find-files-with-a-given-list-of-filename-extensions.py:
--------------------------------------------------------------------------------
1 | """Find files with a given list of filename extensions.
2 |
3 | Construct a list _L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory _D and all it's subdirectories.
4 |
5 | Source: Bart
6 | """
7 |
8 | # Implementation author: âne O' nym
9 | # Created on 2019-09-26T14:12:32.0025Z
10 | # Last modified on 2019-09-26T14:13:11.52677Z
11 | # Version 2
12 |
13 | # * list comprehension
14 | # * iterate over all files and all directories in tree under _D (os module)
15 | # * iterate over all files found
16 | # * filter with regex matching the end of the filename (re module)
17 | # * regex is cached, but may be compiled beforehands
18 |
19 | import re
20 | import os
21 |
22 | filtered_files = [
23 | "{}/{}".format(dirpath, filename)
24 | for dirpath, _, filenames in os.walk(D)
25 | for filename in filenames
26 | if re.match(r"^.*\.(?:jpg|jpeg|png)$", filename)
27 | ]
28 |
--------------------------------------------------------------------------------
/examples/idioms/programs/177.3241-find-files-with-a-given-list-of-filename-extensions.py:
--------------------------------------------------------------------------------
1 | """Find files with a given list of filename extensions.
2 |
3 | Construct a list _L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory _D and all it's subdirectories.
4 |
5 | Source: Bart
6 | """
7 |
8 | # Implementation author: charlax
9 | # Created on 2019-09-27T11:33:27.420533Z
10 | # Last modified on 2019-09-27T11:33:27.420533Z
11 | # Version 1
12 |
13 | import glob
14 | import itertools
15 |
16 | list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"])))
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/178.2615-check-if-point-is-inside-rectangle.py:
--------------------------------------------------------------------------------
1 | """Check if point is inside rectangle.
2 |
3 | Set boolean _b to _true if if the point with coördinates (_x,_y) is inside the rectangle with coördinates (_x1,_y1,_x2,_y2) , or to _false otherwise.
4 | Describe if the edges are considered to be inside the rectangle.
5 |
6 | Source: Bart
7 | """
8 |
9 | # Implementation author: Oldboy
10 | # Created on 2019-02-11T20:04:55.444221Z
11 | # Last modified on 2019-02-11T20:04:55.444221Z
12 | # Version 1
13 |
14 | # Edges NOT considered to be inside.
15 |
16 | b = (x1 < x < x2) and (y1 < y < y2)
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/179.2688-get-center-of-a-rectangle.py:
--------------------------------------------------------------------------------
1 | """Get center of a rectangle.
2 |
3 | Return the center _c of the rectangle with coördinates(_x1,_y1,_x2,_y2)
4 |
5 | Source: Bart
6 | """
7 |
8 | # Implementation author: random
9 | # Created on 2019-09-26T13:33:57.518911Z
10 | # Last modified on 2019-09-26T13:33:57.518911Z
11 | # Version 1
12 |
13 | # center is a tuple that can be accessed using index 0 for x and 1 for y.
14 | #
15 | # e.g. center[0]
16 |
17 | center = ((x1 + x2) / 2, (y1 + y2) / 2)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/179.2689-get-center-of-a-rectangle.py:
--------------------------------------------------------------------------------
1 | """Get center of a rectangle.
2 |
3 | Return the center _c of the rectangle with coördinates(_x1,_y1,_x2,_y2)
4 |
5 | Source: Bart
6 | """
7 |
8 | # Implementation author: random
9 | # Created on 2019-09-26T13:37:07.573535Z
10 | # Last modified on 2019-09-26T13:37:07.573535Z
11 | # Version 1
12 |
13 | # center is a namedtuple, that can be accessed either using x and y or an index (0,1)
14 | #
15 | # e.g. center.x or center[0]
16 |
17 | from collections import namedtuple
18 |
19 | Point = namedtuple("Point", "x y")
20 | center = Point((x1 + x2) / 2, (y1 + y2) / 2)
21 |
--------------------------------------------------------------------------------
/examples/idioms/programs/180.2612-list-files-in-directory.py:
--------------------------------------------------------------------------------
1 | """List files in directory.
2 |
3 | Create list _x containing the contents of directory _d.
4 |
5 | _x may contain files and subfolders.
6 | No recursive subfolder listing.
7 |
8 | Source: programming-idioms.org
9 | """
10 |
11 | # Implementation author: Oldboy
12 | # Created on 2019-02-11T19:56:22.781171Z
13 | # Last modified on 2019-03-26T21:25:46.969143Z
14 | # Version 2
15 |
16 | import os
17 |
18 | x = os.listdir(d)
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/182.2658-quine-program.py:
--------------------------------------------------------------------------------
1 | """Quine program.
2 |
3 | Output the source of the program.
4 |
5 | Source: a
6 | """
7 |
8 | # Implementation author: a
9 | # Created on 2019-07-04T06:26:53.861091Z
10 | # Last modified on 2019-07-04T06:26:53.861091Z
11 | # Version 1
12 |
13 | s = "s = %r\nprint(s%%s)"
14 | print(s % s)
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/183.3025-make-http-put-request.py:
--------------------------------------------------------------------------------
1 | """Make HTTP PUT request.
2 |
3 | Make a HTTP request with method PUT to URL _u
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: awesmubarak
9 | # Created on 2019-09-26T19:06:19.150608Z
10 | # Last modified on 2019-09-27T19:11:23.885446Z
11 | # Version 2
12 |
13 | requests
14 |
15 | import requests
16 |
17 | content_type = "text/plain"
18 | headers = {"Content-Type": content_type}
19 | data = {}
20 |
21 | r = requests.put(url, headers=headers, data=data)
22 | status_code, content = r.status_code, r.content
23 |
--------------------------------------------------------------------------------
/examples/idioms/programs/184.2701-tomorrow.py:
--------------------------------------------------------------------------------
1 | """Tomorrow.
2 |
3 | Assign to variable _t a string representing the day, month and year of the day after the current date.
4 |
5 | Source: steenslag
6 | """
7 |
8 | # Implementation author: citizenkong
9 | # Created on 2019-09-26T13:50:47.638084Z
10 | # Last modified on 2019-09-26T13:50:47.638084Z
11 | # Version 1
12 |
13 | from datetime import date, timedelta
14 |
15 | date.today() + timedelta(days=1)
16 |
--------------------------------------------------------------------------------
/examples/idioms/programs/185.2820-execute-function-in-30-seconds.py:
--------------------------------------------------------------------------------
1 | """Execute function in 30 seconds.
2 |
3 | Schedule the execution of _f(42) in 30 seconds.
4 |
5 | Source: programming-idioms.org
6 | """
7 |
8 | # Implementation author: Baxter
9 | # Created on 2019-09-26T15:37:59.347514Z
10 | # Last modified on 2019-09-27T07:54:09.096921Z
11 | # Version 3
12 |
13 | import threading
14 |
15 | timer = threading.Timer(30.0, f, args=(42,))
16 | timer.start()
17 |
--------------------------------------------------------------------------------
/examples/idioms/programs/186.2699-exit-program-cleanly.py:
--------------------------------------------------------------------------------
1 | """Exit program cleanly.
2 |
3 | Exit a program cleanly indicating no error to OS
4 |
5 | Source: jazz
6 | """
7 |
8 | # Implementation author: random
9 | # Created on 2019-09-26T13:49:49.970567Z
10 | # Last modified on 2019-09-26T13:49:49.970567Z
11 | # Version 1
12 |
13 | # Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.
14 |
15 | import sys
16 |
17 | sys.exit(0)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/187.3261-disjoint-set.py:
--------------------------------------------------------------------------------
1 | """Disjoint Set.
2 |
3 | Disjoint Sets hold elements that are partitioned into a number of disjoint (non-overlapping) sets.
4 |
5 | Source: Shaftway
6 | """
7 |
8 | # Implementation author: Fazel94
9 | # Created on 2019-09-27T14:01:40.750605Z
10 | # Last modified on 2019-09-27T14:01:40.750605Z
11 | # Version 1
12 |
13 |
14 | class UnionFind:
15 | def __init__(self, size):
16 | self.rank = [0] * size
17 | self.p = [i for i in range(size)]
18 |
19 | def find_set(self, i):
20 | if self.p[i] == i:
21 | return i
22 | else:
23 | self.p[i] = self.find_set(self.p[i])
24 | return self.p[i]
25 |
26 | def is_same_set(self, i, j):
27 | return self.find_set(i) == self.find_set(j)
28 |
29 | def union_set(self, i, j):
30 | if not self.is_same_set(i, j):
31 | x, y = self.find_set(i), self.find_set(j)
32 |
--------------------------------------------------------------------------------
/examples/idioms/programs/188.3171-matrix-multiplication.py:
--------------------------------------------------------------------------------
1 | """Matrix multiplication.
2 |
3 | Perform matrix multiplication of a real matrix _a with _nx rows and _ny columns, a real matrix _b with _ny rows and _nz columns and assign the value to a real matrix _c with _nx rows and _nz columns.
4 |
5 | Source: tkoenig
6 | """
7 |
8 | # Implementation author: joshvm
9 | # Created on 2019-09-27T03:20:12.88986Z
10 | # Last modified on 2019-09-27T16:42:27.700845Z
11 | # Version 4
12 |
13 | # Python 3.5 (PEP465) introduced the @ operator for matrix multiplication.
14 | # You can also use _np._matrix instead of _np._array. Be careful when using _array, because the * operator performs elementwise multiplication.
15 |
16 | import numpy as np
17 |
18 | c = a @ b
19 |
--------------------------------------------------------------------------------
/examples/idioms/programs/188.3284-matrix-multiplication.py:
--------------------------------------------------------------------------------
1 | """Matrix multiplication.
2 |
3 | Perform matrix multiplication of a real matrix _a with _nx rows and _ny columns, a real matrix _b with _ny rows and _nz columns and assign the value to a real matrix _c with _nx rows and _nz columns.
4 |
5 | Source: tkoenig
6 | """
7 |
8 | # Implementation author: programming-idioms.org
9 | # Created on 2019-09-27T16:40:03.906529Z
10 | # Last modified on 2019-09-27T16:40:03.906529Z
11 | # Version 1
12 |
13 | # You can also use _np._matrix instead of _np._array. Be careful when using _array, because the * operator performs elementwise multiplication.
14 |
15 | import numpy as np
16 |
17 | c = np.matmul(a, b)
18 |
--------------------------------------------------------------------------------
/examples/idioms/programs/189.3236-filter-and-transform-list.py:
--------------------------------------------------------------------------------
1 | """Filter and transform list.
2 |
3 | Produce a new list _y containing the result of function _T applied to all elements _e of list _x that match the predicate _P.
4 |
5 | Source: beltiras
6 | """
7 |
8 | # Implementation author: beltiras
9 | # Created on 2019-09-27T11:23:50.196486Z
10 | # Last modified on 2019-09-27T13:26:07.008541Z
11 | # Version 3
12 |
13 | y = [T(e) for e in x if P(e)]
14 |
--------------------------------------------------------------------------------
/examples/idioms/programs/191.3403-check-if-any-value-in-a-list-is-larger-than-a-limit.py:
--------------------------------------------------------------------------------
1 | """Check if any value in a list is larger than a limit.
2 |
3 | Given a one-dimensional array _a, check if any value is larger than _x, and execute the procedure f if that is the case
4 |
5 | Source: tkoenig
6 | """
7 |
8 | # Implementation author: Grismar
9 | # Created on 2019-09-28T02:31:20.114991Z
10 | # Last modified on 2019-09-28T02:31:52.368863Z
11 | # Version 2
12 |
13 | if any(v > x for v in a):
14 | f()
15 |
--------------------------------------------------------------------------------
/examples/idioms/programs/197.3457-get-a-list-of-lines-from-a-file.py:
--------------------------------------------------------------------------------
1 | """Get a list of lines from a file.
2 |
3 | Retrieve the contents of file at _path into a list of strings _lines, in which each element is a line of the file.
4 |
5 | Source: Jadiker
6 | """
7 |
8 | # Implementation author: Jadiker
9 | # Created on 2019-09-28T17:00:28.690784Z
10 | # Last modified on 2019-09-28T20:49:36.126049Z
11 | # Version 3
12 |
13 | with open(path) as f:
14 | lines = f.readlines()
15 |
--------------------------------------------------------------------------------
/examples/idioms/read_me.md:
--------------------------------------------------------------------------------
1 | This collection of Python snippets originates from a snapshot of the CC BY-SA 3.0 Unported
2 | Licensed database of https://www.programming-idioms.org, provided by the author of the engine,
3 | Valentin Deleplace, in response to: https://github.com/Deleplace/programming-idioms/issues/98.
4 |
5 | The snapshot itself is not placed under version control on the present repository, but you can
6 | retrieve it yourself at https://gist.github.com/Deleplace/76e101f1b9a9e05f00b736a338929355.
7 |
8 | The contents of the present folder was generated by helpers/make_programming_idioms_folder.py on
9 | 2020-08-09 21:05:39.388475. All changes will be lost the next time this program is executed.
10 |
--------------------------------------------------------------------------------
/examples/mini/programs/assignment.py:
--------------------------------------------------------------------------------
1 | a = b
2 |
--------------------------------------------------------------------------------
/examples/mini/programs/collatz.py:
--------------------------------------------------------------------------------
1 | def print_collatz(n): # paroxython: added_block_label...
2 | while n != 1: # paroxython: suggest_constant_definition
3 | print(n)
4 | if n % 2 == 0: # paroxython: added_label_on_line_4
5 | n = n // 2 # paroxython: -literal:Num -binary_operator:FloorDiv
6 | else: # paroxython: unknown_label
7 | n = 3 * n + 1
8 | print(n) # paroxython: ...added_block_label
9 |
--------------------------------------------------------------------------------
/examples/mini/programs/fizzbuzz.py:
--------------------------------------------------------------------------------
1 | import collatz
2 |
3 | for i in range(1, 101):
4 | if i % 15 == 0:
5 | print("FizzBuzz")
6 | elif i % 3 == 0:
7 | print("Fizz")
8 | elif i % 5 == 0:
9 | print("Buzz")
10 | else:
11 | print(i)
12 |
--------------------------------------------------------------------------------
/examples/mini/programs/is_even.py:
--------------------------------------------------------------------------------
1 | import fizzbuzz
2 |
3 |
4 | def is_even(n):
5 | return n % 2 == 0
6 |
--------------------------------------------------------------------------------
/examples/mini/read_me.md:
--------------------------------------------------------------------------------
1 | This set of four minimal programs is used extensively during testing.
2 |
3 | - `assignment.py` is just `a = b`.
4 | - `collatz.py` is imported by `fizzbuzz.py`, which is imported by `is_even.py`. These importations are useful in the tests.
5 |
--------------------------------------------------------------------------------
/examples/mini/taxa.json:
--------------------------------------------------------------------------------
1 | {
2 | "assignment.py": {
3 | "meta/count/program/sloc/1": "1",
4 | "meta/count/variety/1": "1",
5 | "meta/program": "1",
6 | "style/imperative/flat": "1",
7 | "style/one_liner": "1",
8 | "var/assignment/explicit/single": "1",
9 | "var/scope/global": "1"
10 | },
11 | "collatz.py": {
12 | "call/subroutine/builtin/print": "3 8",
13 | "condition/divisibility/parity": "4",
14 | "condition/equality": "4",
15 | "condition/equality/not": "2",
16 | "def/subroutine/parameter/arg": "1",
17 | "def/subroutine/procedure": "1-8",
18 | "flow/conditional": "4-7",
19 | "flow/conditional/else": "7",
20 | "flow/loop/exit/late": "2-7",
21 | "flow/loop/while": "2-7",
22 | "meta/count/program/sloc/8": "1-8",
23 | "meta/count/subroutine/sloc/8": "1-8",
24 | "meta/count/variety/4": "1-8",
25 | "meta/program": "1-8",
26 | "operator/arithmetic/addition": "7",
27 | "operator/arithmetic/modulo": "4",
28 | "operator/arithmetic/multiplication": "7",
29 | "style/procedural": "1-8",
30 | "style/unpythonic/augmented_assignment": "5",
31 | "type/number/integer/literal": "2 4 5 7 7",
32 | "type/number/integer/literal/zero": "4",
33 | "type/number/magic": "7",
34 | "var/assignment/explicit/conditional/verbose": "4-7",
35 | "var/assignment/explicit/single": "5 7",
36 | "var/assignment/implicit/parameter": "1",
37 | "var/scope/local": "1-8"
38 | },
39 | "fizzbuzz.py": {
40 | "call/subroutine/builtin/print": "4 6 8 10",
41 | "call/subroutine/builtin/range": "2",
42 | "condition/equality": "3 5 7",
43 | "flow/conditional": "3-10 5-10 7-10",
44 | "flow/conditional/else": "10",
45 | "flow/conditional/else/if": "6 8",
46 | "flow/loop/exit/late": "2-10",
47 | "flow/loop/for/arithmetic/start": "2-10",
48 | "import/personal": "1",
49 | "meta/count/program/sloc/10": "1-10",
50 | "meta/count/variety/3": "1-10",
51 | "meta/program": "1-10",
52 | "operator/arithmetic/modulo": "3 5 7",
53 | "style/imperative": "1-10",
54 | "type/number/integer/literal": "2 2 3 5 7",
55 | "type/number/integer/literal/zero": "3 5 7",
56 | "type/number/magic": "2 3 5 7",
57 | "type/sequence/string/literal": "4 6 8",
58 | "var/assignment/implicit/iteration_variable": "2",
59 | "var/scope/global": "1-10"
60 | },
61 | "is_even.py": {
62 | "condition/divisibility/parity": "3",
63 | "condition/equality": "3",
64 | "def/subroutine/function/predicate": "2-3",
65 | "def/subroutine/function/pure": "2-3",
66 | "def/subroutine/parameter/arg": "2",
67 | "def/subroutine/return/something": "3",
68 | "import/personal": "1",
69 | "meta/count/program/sloc/3": "1-3",
70 | "meta/count/subroutine/sloc/2": "2-3",
71 | "meta/count/variety/2": "1-3",
72 | "meta/program": "1-3",
73 | "operator/arithmetic/modulo": "3",
74 | "style/functional": "1-3",
75 | "style/functional_trait/pure_function": "2-3",
76 | "style/one_liner": "1-3",
77 | "type/number/integer/literal": "3",
78 | "type/number/integer/literal/zero": "3",
79 | "var/assignment/implicit/parameter": "2",
80 | "var/scope/local": "2-3"
81 | }
82 | }
--------------------------------------------------------------------------------
/examples/mini/taxonomy.tsv:
--------------------------------------------------------------------------------
1 | Taxa (replacement patterns) Labels (search patterns)
2 | call/subroutine/builtin/casting/\1 free_call:(list|dict)
3 | call/subroutine/builtin/casting/set literal:Set
4 | condition/inequality comparison_operator:(Lt|LtE|Gt|GtE)
5 | flow/conditional if
6 | flow/conditional/else if_else
7 | type/non_sequence/set literal:Set
8 | type/non_sequence/set member_call_method:difference_update
9 | type/sequence/list free_call:list
10 |
--------------------------------------------------------------------------------
/examples/simple/programs/01_hello_world.py:
--------------------------------------------------------------------------------
1 | print("Hello, world!")
2 |
--------------------------------------------------------------------------------
/examples/simple/programs/02_input_name.py:
--------------------------------------------------------------------------------
1 | name = input("What is your name?\n")
2 | print("Hi, %s." % name)
3 |
--------------------------------------------------------------------------------
/examples/simple/programs/03_friends.py:
--------------------------------------------------------------------------------
1 | friends = ["john", "pat", "gary", "michael"]
2 | for i, name in enumerate(friends):
3 | print("iteration {iteration} is {name}".format(iteration=i, name=name))
4 |
--------------------------------------------------------------------------------
/examples/simple/programs/04_fibonacci.py:
--------------------------------------------------------------------------------
1 | parents, babies = (1, 1)
2 | while babies < 100:
3 | print("This generation has {} babies".format(babies))
4 | parents, babies = (babies, parents + babies)
5 |
--------------------------------------------------------------------------------
/examples/simple/programs/05_greet.py:
--------------------------------------------------------------------------------
1 | def greet(name):
2 | print("Hello", name)
3 |
4 |
5 | greet("Jack")
6 | greet("Jill")
7 | greet("Bob")
8 |
--------------------------------------------------------------------------------
/examples/simple/programs/06_regex.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | for test_string in ["555-1212", "ILL-EGAL"]:
4 | if re.match(r"^\d{3}-\d{4}$", test_string):
5 | print(test_string, "is a valid US local phone number")
6 | else:
7 | print(test_string, "rejected")
8 |
--------------------------------------------------------------------------------
/examples/simple/programs/07_grocery_bill.py:
--------------------------------------------------------------------------------
1 | prices = {"apple": 0.40, "banana": 0.50}
2 | my_purchase = {"apple": 1, "banana": 6}
3 | grocery_bill = sum(prices[fruit] * my_purchase[fruit] for fruit in my_purchase)
4 | print("I owe the grocer $%.2f" % grocery_bill)
5 |
--------------------------------------------------------------------------------
/examples/simple/programs/08_arguments.py:
--------------------------------------------------------------------------------
1 | # This program adds up integers that have been passed as arguments in the command line
2 | import sys
3 |
4 | try:
5 | total = sum(int(arg) for arg in sys.argv[1:])
6 | print("sum =", total)
7 | except ValueError:
8 | print("Please supply integer arguments")
9 |
--------------------------------------------------------------------------------
/examples/simple/programs/09_indent.py:
--------------------------------------------------------------------------------
1 | # indent your Python code to put into an email
2 | import glob
3 |
4 | # glob supports Unix style pathname extensions
5 | python_files = glob.glob("*.py")
6 | for file_name in sorted(python_files):
7 | print(" ------" + file_name)
8 |
9 | with open(file_name) as f:
10 | for line in f:
11 | print(" " + line.rstrip())
12 |
13 | print()
14 |
--------------------------------------------------------------------------------
/examples/simple/programs/10_time.py:
--------------------------------------------------------------------------------
1 | from time import localtime
2 |
3 | activities = {
4 | 8: "Sleeping",
5 | 9: "Commuting",
6 | 17: "Working",
7 | 18: "Commuting",
8 | 20: "Eating",
9 | 22: "Resting",
10 | }
11 |
12 | time_now = localtime()
13 | hour = time_now.tm_hour
14 |
15 | for activity_time in sorted(activities.keys()):
16 | if hour < activity_time:
17 | print(activities[activity_time])
18 | break
19 | else:
20 | print("Unknown, AFK or sleeping!")
21 |
--------------------------------------------------------------------------------
/examples/simple/programs/11_bottles.py:
--------------------------------------------------------------------------------
1 | REFRAIN = """
2 | %d bottles of beer on the wall,
3 | %d bottles of beer,
4 | take one down, pass it around,
5 | %d bottles of beer on the wall!
6 | """
7 | bottles_of_beer = 9
8 | while bottles_of_beer > 1:
9 | print(REFRAIN % (bottles_of_beer, bottles_of_beer, bottles_of_beer - 1))
10 | bottles_of_beer -= 1
11 |
--------------------------------------------------------------------------------
/examples/simple/programs/12_classes.py:
--------------------------------------------------------------------------------
1 | class BankAccount(object):
2 | def __init__(self, initial_balance=0):
3 | self.balance = initial_balance
4 |
5 | def deposit(self, amount):
6 | self.balance += amount
7 |
8 | def withdraw(self, amount):
9 | self.balance -= amount
10 |
11 | def overdrawn(self):
12 | return self.balance < 0
13 |
14 |
15 | my_account = BankAccount(15)
16 | my_account.withdraw(50)
17 | print(my_account.balance, my_account.overdrawn())
18 |
--------------------------------------------------------------------------------
/examples/simple/programs/13_unit_testing.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 |
4 | def median(pool):
5 | copy = sorted(pool)
6 | size = len(copy)
7 | if size % 2 == 1:
8 | return copy[int((size - 1) / 2)]
9 | else:
10 | return (copy[int(size / 2 - 1)] + copy[int(size / 2)]) / 2
11 |
12 |
13 | class TestMedian(unittest.TestCase):
14 | def testMedian(self):
15 | self.assertEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
16 |
17 |
18 | if __name__ == "__main__":
19 | unittest.main()
20 |
--------------------------------------------------------------------------------
/examples/simple/programs/14_median.py:
--------------------------------------------------------------------------------
1 | def median(pool):
2 | """Statistical median to demonstrate doctest.
3 | >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8])
4 | 6 #change to 7 in order to pass the test
5 | """
6 | copy = sorted(pool)
7 | size = len(copy)
8 | if size % 2 == 1:
9 | return copy[int((size - 1) / 2)]
10 | else:
11 | return (copy[int(size / 2 - 1)] + copy[int(size / 2)]) / 2
12 |
13 |
14 | if __name__ == "__main__":
15 | import doctest
16 |
17 | doctest.testmod()
18 |
--------------------------------------------------------------------------------
/examples/simple/programs/15_itertools_groupby.py:
--------------------------------------------------------------------------------
1 | from itertools import groupby
2 |
3 | lines = """
4 | This is the
5 | first paragraph.
6 |
7 | This is the second.
8 | """.splitlines()
9 | # Use itertools.groupby and bool to return groups of
10 | # consecutive lines that either have content or don't.
11 | for has_chars, frags in groupby(lines, bool):
12 | if has_chars:
13 | print(" ".join(frags))
14 | # PRINTS:
15 | # This is the first paragraph.
16 | # This is the second.
17 |
--------------------------------------------------------------------------------
/examples/simple/programs/16_csv.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 | # need to define cmp function in Python 3
4 | def cmp(a, b):
5 | return (a > b) - (a < b)
6 |
7 |
8 | # write stocks data as comma-separated values
9 | with open("stocks.csv", "w", newline="") as stocksFileW:
10 | writer = csv.writer(stocksFileW)
11 | writer.writerows(
12 | [
13 | ["GOOG", "Google, Inc.", 505.24, 0.47, 0.09],
14 | ["YHOO", "Yahoo! Inc.", 27.38, 0.33, 1.22],
15 | ["CNET", "CNET Networks, Inc.", 8.62, -0.13, -1.4901],
16 | ]
17 | )
18 |
19 | # read stocks data, print status messages
20 | with open("stocks.csv", "r") as stocksFile:
21 | stocks = csv.reader(stocksFile)
22 |
23 | status_labels = {-1: "down", 0: "unchanged", 1: "up"}
24 | for ticker, name, price, change, pct in stocks:
25 | status = status_labels[cmp(float(change), 0.0)]
26 | print("{} is {} ({:.2f})".format(name, status, float(pct)))
27 |
--------------------------------------------------------------------------------
/examples/simple/programs/18_queens.py:
--------------------------------------------------------------------------------
1 | BOARD_SIZE = 8
2 |
3 |
4 | def under_attack(col, queens):
5 | left = right = col
6 |
7 | for r, c in reversed(queens):
8 | left, right = left - 1, right + 1
9 |
10 | if c in (left, col, right):
11 | return True
12 | return False
13 |
14 |
15 | def solve(n):
16 | if n == 0:
17 | return [[]]
18 |
19 | smaller_solutions = solve(n - 1)
20 |
21 | return [
22 | solution + [(n, i + 1)]
23 | for i in range(BOARD_SIZE)
24 | for solution in smaller_solutions
25 | if not under_attack(i + 1, solution)
26 | ]
27 |
28 |
29 | for answer in solve(BOARD_SIZE):
30 | print(answer)
31 |
--------------------------------------------------------------------------------
/examples/simple/programs/20_prime_numbers.py:
--------------------------------------------------------------------------------
1 | import itertools
2 |
3 |
4 | def iter_primes():
5 | # an iterator of all numbers between 2 and +infinity
6 | numbers = itertools.count(2)
7 |
8 | # generate primes forever
9 | while True:
10 | # get the first number from the iterator (always a prime)
11 | prime = next(numbers)
12 | yield prime
13 |
14 | # this code iteratively builds up a chain of
15 | # filters...slightly tricky, but ponder it a bit
16 | numbers = filter(prime.__rmod__, numbers)
17 |
18 |
19 | for p in iter_primes():
20 | if p > 1000:
21 | break
22 | print(p)
23 |
--------------------------------------------------------------------------------
/examples/simple/programs/21_xml_html_parsing.py:
--------------------------------------------------------------------------------
1 | dinner_recipe = """
2 | amt | unit | item |
3 | 24 | slices | baguette |
4 | 2+ | tbsp | olive oil |
5 | 1 | cup | tomatoes |
6 | 1 | jar | pesto |
7 |
"""
8 |
9 | # From http://effbot.org/zone/element-index.htm
10 | import xml.etree.ElementTree as etree
11 |
12 | tree = etree.fromstring(dinner_recipe)
13 |
14 | # For invalid HTML use http://effbot.org/zone/element-soup.htm
15 | # import ElementSoup, StringIO
16 | # tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe))
17 |
18 | pantry = {"olive oil", "pesto"}
19 | for ingredient in tree.getiterator("tr"):
20 | amt, unit, item = ingredient
21 | if item.tag == "td" and item.text not in pantry:
22 | print("{}: {} {}".format(item.text, amt.text, unit.text))
23 |
--------------------------------------------------------------------------------
/examples/simple/programs/28_queens.py:
--------------------------------------------------------------------------------
1 | BOARD_SIZE = 8
2 |
3 |
4 | class BailOut(Exception):
5 | pass
6 |
7 |
8 | def validate(queens):
9 | left = right = col = queens[-1]
10 | for r in reversed(queens[:-1]):
11 | left, right = left - 1, right + 1
12 | if r in (left, col, right):
13 | raise BailOut
14 |
15 |
16 | def add_queen(queens):
17 | for i in range(BOARD_SIZE):
18 | test_queens = queens + [i]
19 | try:
20 | validate(test_queens)
21 | if len(test_queens) == BOARD_SIZE:
22 | return test_queens
23 | else:
24 | return add_queen(test_queens)
25 | except BailOut:
26 | pass
27 | raise BailOut
28 |
29 |
30 | queens = add_queen([])
31 | print(queens)
32 | print("\n".join(". " * q + "Q " + ". " * (BOARD_SIZE - q - 1) for q in queens))
33 |
--------------------------------------------------------------------------------
/examples/simple/programs/33_guess_the_number.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | guesses_made = 0
4 |
5 | name = input("Hello! What is your name?\n")
6 |
7 | number = random.randint(1, 20)
8 | print("Well, {}, I am thinking of a number between 1 and 20.".format(name))
9 |
10 | while guesses_made < 6:
11 |
12 | guess = int(input("Take a guess: "))
13 |
14 | guesses_made += 1
15 |
16 | if guess < number:
17 | print("Your guess is too low.")
18 |
19 | if guess > number:
20 | print("Your guess is too high.")
21 |
22 | if guess == number:
23 | break
24 |
25 | if guess == number:
26 | print("Good job, {}! You guessed my number in {} guesses!".format(name, guesses_made))
27 | else:
28 | print("Nope. The number I was thinking of was {}".format(number))
29 |
--------------------------------------------------------------------------------
/examples/simple/programs_pipe.py:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "operation": "impart",
4 | "data": [
5 | "01_hello_world.py",
6 | "02_input_name.py",
7 | "def/subroutine/procedure",
8 | "call/subroutine",
9 | "flow",
10 | ],
11 | },
12 | {
13 | "operation": "exclude",
14 | "data": [
15 | "03_friends.py",
16 | ],
17 | },
18 | {
19 | "operation": "exclude",
20 | "data": [
21 | "type/number/floating_point/literal",
22 | ("type/sequence/tuple", "is not", "var/assignment/explicit/parallel"),
23 | ],
24 | },
25 | {
26 | "operation": "include",
27 | "data": [
28 | "var/assignment/explicit",
29 | ],
30 | },
31 | {
32 | "operation": "hide",
33 | "data": [
34 | "call/subroutine/builtin/print",
35 | r".*test.*\.py",
36 | ],
37 | },
38 | ]
39 |
--------------------------------------------------------------------------------
/examples/simple/read_me.md:
--------------------------------------------------------------------------------
1 | Snapshot of [SimplePrograms](https://wiki.python.org/moin/SimplePrograms) (last edited 2019-11-09 23:29:53 by FrancesHocutt). GPL licensed.
2 |
--------------------------------------------------------------------------------
/helpers/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/laowantong/paroxython/44e14b17965c6b02871db4c9ed6acc8716c2740d/helpers/__init__.py
--------------------------------------------------------------------------------
/helpers/context.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | sys.path[0:0] = ["."]
4 |
--------------------------------------------------------------------------------
/helpers/draw_flow.py:
--------------------------------------------------------------------------------
1 | import os
2 | from pathlib import Path
3 |
4 | import regex
5 |
6 | paths = Path("paroxython").glob("*.py")
7 | paths = list(
8 | path
9 | for path in paths
10 | if not str(path).endswith(
11 | (
12 | "user_types.py",
13 | "goodies.py",
14 | "span.py",
15 | "analyze_one.py",
16 | "cli_collect.py",
17 | "cli_recommend.py",
18 | "cli.py",
19 | "cli_tag.py",
20 | )
21 | )
22 | )
23 | names = [str(path)[len("paroxython/") : -3] for path in paths]
24 | base = "docs/resources/flow"
25 | find_all = regex.compile(fr"(?m)^from \.({'|'.join(names)}) import").findall
26 |
27 | Path(f"{base}.dot").write_text(
28 | """digraph G {
29 | node [shape=box fontname=Menlo fontsize=16 style="rounded,filled" textcolor="#646464" fillcolor="#F5CA41" color="#B38D01" penwidth=2]
30 | edge [penwidth=2 color="#646464"]
31 | %s
32 | }
33 | """
34 | % "\n".join(
35 | [
36 | '"*_db.json" [shape=cylinder fillcolor="#c5f541" color="#435214" penwidth=1 height=1]',
37 | '"*_db.sqlite" [shape=cylinder fillcolor="#c5f541" color="#435214" penwidth=1 height=1]',
38 | '"spec.md" [shape=note fillcolor="#f57141" color="#662f17" penwidth=1]',
39 | '"*_pipe.py" [shape=note fillcolor="#f57141" color="#662f17" penwidth=1]',
40 | '"taxonomy.tsv" [shape=note fillcolor="#f57141" color="#662f17" penwidth=1]',
41 | '"source files" [shape=folder fillcolor="#f57141" color="#662f17" penwidth=1]',
42 | '"*_recommendations.md" [shape=note fillcolor="#c5f541" color="#435214" penwidth=1]',
43 | 'make_db -> "*_db.json"',
44 | 'make_db -> "*_db.sqlite"',
45 | '"*_db.json" -> filter_programs',
46 | '"spec.md" -> parse_program',
47 | '"source files" -> list_programs',
48 | '"taxonomy.tsv" -> map_taxonomy',
49 | '"*_pipe.py" -> recommend_programs',
50 | 'recommend_programs -> "*_recommendations.md"',
51 | # Add invisible edges to reshape the layout
52 | '"*_db.sqlite" -> "*_pipe.py" [style=invis]',
53 | '"list_programs" -> "flatten_ast" [style=invis]',
54 | ]
55 | + [
56 | f"{imported_name} -> {name}"
57 | for (name, path) in zip(names, paths)
58 | for imported_name in find_all(path.read_text())
59 | ]
60 | )
61 | )
62 | os.system(f"dot -Tpng {base}.dot > {base}.png; rm {base}.dot")
63 |
64 | base = "docs/resources/filter_flow"
65 | text = Path("paroxython/filter_programs.py").read_text()
66 | text = regex.search(r"(?s)(.+)", text)[1]
67 | text = text.replace("# ", " ")
68 |
69 | Path(f"{base}.dot").write_text(
70 | f"""digraph G {{
71 | node [shape=box fontname=Menlo fontsize=16 style="rounded,filled" textcolor="#646464" fillcolor="#F5CA41" color="#B38D01" penwidth=2]
72 | edge [penwidth=2 color="#646464"]
73 | rankdir=LR;
74 | {text}
75 | }}
76 | """
77 | )
78 | os.system(f"dot -Tpng {base}.dot > {base}.png; rm {base}.dot")
79 |
--------------------------------------------------------------------------------
/helpers/dump_flat_asts.py:
--------------------------------------------------------------------------------
1 | """Apply all AST-parsers on the regex-specified features, and dump the results for comparison."""
2 |
3 | from pathlib import Path
4 | import regex # type: ignore
5 |
6 | import context
7 |
8 | from paroxython.flatten_ast import select_ast_post_processing, flatten_ast
9 | from helpers.reformat_spec import reformat_spec
10 |
11 | SPEC_PATH = Path("paroxython/resources/spec.md")
12 |
13 | TEMPLATE = """
14 | #### Feature `{label_name}`
15 |
16 | ##### Specification
17 |
18 | ```re
19 | {spec}
20 | ```
21 |
22 | ##### Example
23 |
24 | ```python
25 | {source}
26 | ```
27 |
28 | #### Flat AST
29 |
30 | ```plain
31 | {flat_ast}```
32 | """
33 |
34 |
35 | def extract_specs(SPEC_PATH):
36 | text = SPEC_PATH.read_text()
37 | rex = r"""(?msx)
38 | ^\#{4}\s+Feature\s+`(.+?)` # capture the label's pattern
39 | .+?\#{5}\s+Specification # ensure the next code is in the Specification section
40 | .+?```(re|sql)\n+(.+?)\n``` # capture the language and the specification
41 | .+?\#{5}\s+Example # ensure the next code is in the Example section
42 | .+?```python\n+(.+?)\n``` # capture the source
43 | """
44 | return regex.finditer(rex, text)
45 |
46 |
47 | import ast
48 |
49 | reformat_spec(SPEC_PATH)
50 | select_ast_post_processing()
51 | specs = []
52 | for match in extract_specs(SPEC_PATH):
53 | (label_name, language, spec, source) = match.groups()
54 | if language == "sql":
55 | continue
56 | source = regex.sub(r"(?m)^.{1,4}", "", source)
57 | try:
58 | parsed_source = ast.parse(source)
59 | except SyntaxError:
60 | continue
61 | flat_ast = flatten_ast(parsed_source)
62 | specs.append(
63 | TEMPLATE.format(
64 | label_name=label_name,
65 | spec=spec,
66 | source=source,
67 | flat_ast=flat_ast,
68 | )
69 | )
70 | output_path = Path(f"sandbox/flat_asts.md")
71 | output_path.write_text("\n".join(specs))
72 | print(f"{len(specs)} ASTs dumped in '{output_path}'.")
73 |
--------------------------------------------------------------------------------
/helpers/example.sql:
--------------------------------------------------------------------------------
1 | -- SQLite
2 | SELECT name AS taxon, count(*) AS occurrences
3 | FROM taxon
4 | GROUP BY name
5 | ORDER BY occurrences DESC
6 | LIMIT 50
7 |
--------------------------------------------------------------------------------
/helpers/parse_source.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 |
3 | import regex # type: ignore
4 |
5 | import context
6 | from paroxython.goodies import couple_to_string
7 | from paroxython.parse_program import ProgramParser
8 | from paroxython.user_types import Program, Source
9 |
10 | path = Path("sandbox/source.py")
11 | source = path.read_text().strip()
12 | if source.startswith("1 "):
13 | source = regex.sub(r"(?m)^.{1,4}", "", source)
14 | for (i, line) in enumerate(source.split("\n"), 1):
15 | print(f"{i:<4}{line}")
16 | program = Program(source=Source(source), labels=[], taxa=[], addition={}, deletion={})
17 | print()
18 | parse = ProgramParser()
19 | acc = []
20 | for (name, spans) in sorted(parse(program, yield_failed_matches=False)):
21 | spans_as_string = ", ".join(map(couple_to_string, spans))
22 | acc.append(f"| `{name}` | {spans_as_string} |")
23 | # acc[-1] += " %s |" % ", ".join(f"{span.path}" for span in spans)
24 | print("\n".join(acc))
25 | Path("sandbox/flat_ast.txt").write_text(parse.flat_ast)
26 |
--------------------------------------------------------------------------------
/helpers/parse_syllabus.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from pathlib import Path
3 |
4 | import regex # type: ignore
5 |
6 | raw_text = Path(sys.argv[1]).read_text()
7 | useful_part = regex.search(r"(?sm)(.*)^ *# EOF\b", raw_text)[1]
8 | pattern = r"\+ *(?:\[.+?\] *)?(\w+(?
6 | :end-before: # Read them
7 |
8 |
9 |
10 | .. include:: ../docs/md/about.md
11 |
12 | *[AST]: Abstract Syntax Tree
13 | *[SQL]: Structured Query Language
14 | *[TSV]: Tab Separated Values
15 | *[JSON]: JavaScript Object Notation
16 | *[SLOC]: Source Lines Of Code
17 | """
18 |
19 | import sys
20 | from importlib.metadata import distribution, PackageNotFoundError
21 |
22 | try:
23 | PAROXYTHON_VERSION = distribution("paroxython").version
24 | except PackageNotFoundError:
25 | PAROXYTHON_VERSION = "(unknown version)" # For tests during CI
26 |
27 | if "ipykernel" in sys.modules:
28 | # Declare the magic stuff paroxython iff the module is loaded as an IPython extension.
29 |
30 | from IPython.core.magic import Magics, cell_magic, magics_class # type: ignore
31 | from IPython.display import Markdown, display # type: ignore
32 |
33 | from .cli_tag import main
34 |
35 | def load_ipython_extension(ipython):
36 | ipython.register_magics(ParoxythonMagics)
37 | print(f"Paroxython {PAROXYTHON_VERSION} loaded.")
38 |
39 | @magics_class
40 | class ParoxythonMagics(Magics):
41 | @staticmethod
42 | @cell_magic
43 | def paroxython(line, cell=""):
44 | """
45 | Tag a Python code cell and output the table of its taxa or labels.
46 |
47 | In cell mode:
48 | %%paroxython [labels] [raw]
49 | ... Python cell code ...
50 | """
51 | args = set(line.lower().split())
52 | tags = "Label" if args.intersection(["label", "labels"]) else "Taxon"
53 | cell = f"# Compensate the offset of the magic command.\n{cell}"
54 | try:
55 | result = main(cell, tags=tags)
56 | except ValueError as e:
57 | print(e, file=sys.stderr)
58 | else:
59 | if "raw" in args:
60 | print(result)
61 | else:
62 | display(Markdown(result))
63 |
--------------------------------------------------------------------------------
/paroxython/cli.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | """Command line interface for the main functionalities of Paroxython.
3 |
4 | USAGE:
5 | ```
6 | paroxython [--version] [--help] COMMAND [ARGS...]
7 | ```
8 |
9 | COMMANDS:
10 | ```plain
11 | tag Tag one Python file and output the table of its taxa or
12 | labels.
13 | collect Walk a directory, tag its Python files and make a JSON
14 | database of the results.
15 | recommend Read and execute a pipeline of commands and report the learning
16 | costs.
17 | ```
18 |
19 | Type `paroxython COMMAND --help` for more information on a specific command.
20 | """
21 | import sys
22 | from importlib import import_module
23 |
24 | import regex # type: ignore
25 | from docopt import docopt # type: ignore
26 |
27 | from . import PAROXYTHON_VERSION
28 | from .goodies import print_exit
29 |
30 | if sys.version_info < (3, 8): # pragma: no cover
31 | print_exit(f"Paroxython requires Python 3.8 or later to run.\nThis version is {sys.version}.")
32 |
33 |
34 | def main():
35 | doc = regex.sub(r"(?m)^ *```.*\n", "", __doc__) # suppress Markdown code delimiters
36 | args = docopt(doc, version=f"paroxython version {PAROXYTHON_VERSION}", options_first=True)
37 | if not args.get("COMMAND"): # pragma: no cover
38 | print_exit(doc)
39 | command_name = args["COMMAND"].lower()
40 | command_args = [command_name] + args["ARGS"]
41 | if command_name not in ("tag", "recommend", "collect"):
42 | print_exit(f"{command_name} is not a valid command. Type 'paroxython --help'.")
43 | command = import_module(f"paroxython.cli_{command_name}", "cli_wrapper")
44 | command.__doc__ = regex.sub(r"(?m)^ *```.*\n", "", command.__doc__)
45 | command.cli_wrapper(docopt(command.__doc__, argv=command_args))
46 |
47 |
48 | if __name__ == "__main__":
49 | main()
50 |
--------------------------------------------------------------------------------
/paroxython/cli_collect.py:
--------------------------------------------------------------------------------
1 | r"""Walk a directory, tag its Python files and make a database of the results.
2 |
3 | USAGE:
4 | ```
5 | paroxython collect [options] DIRECTORY
6 | ```
7 |
8 | OPTIONS:
9 | ```plain
10 | -c --cleanup=STR Transformation to apply to the source code before
11 | processing. [default: full]
12 | Currently available:
13 | • full: remove all blank lines, docstrings and
14 | comments (except Paroxython hints).
15 | • none: no transformation is applied.
16 | -e --skip=REGEX Filter out any file whose name fully matches this
17 | regular expression. NB: --glob precedes --skip.
18 | [default: (__init__|setup|.*[-_]tests?)\.py]
19 | -g --glob=PATTERN The names of the collected files must match this Unix-
20 | like glob pattern (not a regular expression). Special
21 | syntax: "**/" prefix means “this directory and all
22 | subdirectories, recursively”. [default: **/*.py]
23 | --log Print a detailed report of the labelling times.
24 | --no_timestamp Don't store programs' last modification date.
25 | -o --output=PATH The path of the resulting database. If not specified,
26 | create a JSON file under the name "DIRECTORY_db.json".
27 | Otherwise, use the extension (either ".json", ".sql"
28 | or ".sqlite") to decide the format of the tag database.
29 | [default: ]
30 | -t --taxonomy=PATH The path of a TSV file mapping labels onto taxa. If not
31 | specified, use the "taxonomy.tsv" present in DIRECTORY's
32 | parent. If absent, use the included default taxonomy:
33 | https://github.com/laowantong/paroxython/blob/0.7.0/paroxython/resources/taxonomy.tsv
34 | ```
35 | """
36 |
37 | from pathlib import Path
38 |
39 | from .goodies import print_exit
40 | from .make_db import TagDatabase
41 |
42 |
43 | def cli_wrapper(args):
44 | directory = Path(args["DIRECTORY"])
45 | if not directory.is_dir():
46 | print_exit(f"no directory at '{directory.absolute()}': aborted.")
47 | taxonomy = args.get("--taxonomy")
48 | if taxonomy:
49 | taxonomy_path = Path(taxonomy)
50 | else:
51 | taxonomy_path = directory.parent / "taxonomy.tsv"
52 | if not taxonomy_path.is_file():
53 | taxonomy_path = None
54 | db = TagDatabase(
55 | directory=directory,
56 | ignore_timestamps=args["--no_timestamp"],
57 | cleanup_strategy=args["--cleanup"], # -> list_programs
58 | skip_pattern=args["--skip"], # -> list_programs
59 | glob_pattern=args["--glob"], # -> list_programs
60 | print_performances=args["--log"], # -> labelled_programs
61 | taxonomy_path=taxonomy_path, # -> Taxonomy
62 | )
63 | if not args["--output"]:
64 | db.write_json()
65 | elif args["--output"].endswith(".json"):
66 | db.write_json(Path(args["--output"]))
67 | elif args["--output"].endswith((".sqlite", ".sql")):
68 | db.write_sqlite(Path(args["--output"]))
69 |
--------------------------------------------------------------------------------
/paroxython/cli_tag.py:
--------------------------------------------------------------------------------
1 | """Tag one Python file and output the table of its taxa or labels.
2 |
3 | USAGE:
4 | ```
5 | paroxython tag [options] FILENAME
6 | ```
7 |
8 | OPTIONS:
9 | ```plain
10 | -f --format=FORMAT Format of the output, either "md" (Markdown)
11 | or "tsv" (Tab Separated Values). [default: md]
12 | -l --labels Output the labels instead of the taxa.
13 | -t --taxonomy=PATH The path of a TSV file mapping labels onto taxa.
14 | If not specified, use the included default taxonomy:
15 | https://github.com/laowantong/paroxython/blob/0.7.0/paroxython/resources/taxonomy.tsv
16 | ```
17 | """
18 |
19 | from pathlib import Path
20 | from typing import List, Tuple, Optional
21 | from typing_extensions import Literal
22 |
23 | from .goodies import couple_to_string, print_exit
24 | from .parse_program import ProgramParser
25 | from .list_programs import get_program
26 | from .map_taxonomy import Taxonomy
27 | from .user_types import Source
28 |
29 |
30 | def main(
31 | source: Source,
32 | tags: Literal["Taxon", "Label"] = "Taxon",
33 | relative_path: Path = Path("."),
34 | output_format: Literal["md", "tsv"] = "md",
35 | taxonomy_path: Optional[Path] = None,
36 | ) -> str:
37 | program = get_program(source, relative_path)
38 | parse = ProgramParser()
39 | program.labels[:] = parse(program)
40 | couples: List[Tuple[str, str]] = [(tags, "Lines")]
41 | if tags == "Label":
42 | for (label_name, label_spans) in sorted(program.labels):
43 | s = ", ".join(map(couple_to_string, sorted(label_spans)))
44 | couples.append((label_name, s))
45 | else:
46 | taxonomy = Taxonomy(taxonomy_path)
47 | taxa = taxonomy.to_taxa(program.labels)
48 | for (taxon_name, taxon_spans) in sorted(taxa):
49 | s = ", ".join(map(couple_to_string, sorted(taxon_spans.elements())))
50 | couples.append((taxon_name, s))
51 | if output_format == "md":
52 | result = [f"| `{tag}` | {lines} |" for (tag, lines) in couples]
53 | result[0] = result[0].replace("`", "")
54 | result[1:1] = ["|:--|:--|"]
55 | else:
56 | result = [f"{tag}\t{lines}" for (tag, lines) in couples]
57 | return "\n".join(result)
58 |
59 |
60 | def cli_wrapper(args):
61 | path = Path(args["FILENAME"])
62 | try:
63 | source = path.read_text()
64 | except Exception as e:
65 | print_exit(str(e))
66 | result = main(
67 | source=Source(source),
68 | tags="Label" if args["--labels"] else "Taxon",
69 | relative_path=path.parent,
70 | output_format=args["--format"],
71 | taxonomy_path=Path(args["--taxonomy"]) if args["--taxonomy"] else None,
72 | )
73 | print(result)
74 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "paroxython"
3 | version = "0.7.2"
4 | description = "Search Python code for algorithmic features"
5 | authors = ["Aristide Grange"]
6 | license = "MIT"
7 | readme = "README.md"
8 | homepage = "https://github.com/laowantong/paroxython/"
9 | repository = "https://github.com/laowantong/paroxython/"
10 | keywords = ["education",
11 | "static-analysis",
12 | "algorithmic",
13 | "metaprogramming",
14 | "python",
15 | "taxonomic-classification",
16 | "knowledge-management"]
17 | classifiers = [
18 | "Development Status :: 5 - Production/Stable",
19 | "Environment :: Console",
20 | "Framework :: IPython",
21 | "Intended Audience :: Education",
22 | "License :: OSI Approved :: MIT License",
23 | "Natural Language :: English",
24 | "Operating System :: OS Independent",
25 | "Programming Language :: Python :: 3.8",
26 | "Programming Language :: Python :: 3.9",
27 | "Programming Language :: SQL",
28 | "Topic :: Database",
29 | "Topic :: Education",
30 | "Typing :: Typed",
31 | ]
32 |
33 | [tool.poetry.dependencies]
34 | docopt = "^0.6.2"
35 | python = "^3.8"
36 | regex = "^2022.8.17"
37 | typing-extensions = "^4.3.0"
38 |
39 | [tool.poetry.dev-dependencies]
40 | mypy = "^0.782"
41 | pdoc3 = "^0.9.1"
42 | pre-commit = "^2.20.0"
43 | pytest = "^7.1.3"
44 | sqlparse = "^0.4.2"
45 |
46 | [build-system]
47 | requires = ["poetry>=1.2.0"]
48 | build-backend = "poetry.masonry.api"
49 |
50 | [tool.poetry.urls]
51 | issues = "https://github.com/laowantong/paroxython/issues"
52 |
53 | [tool.poetry.scripts]
54 | paroxython = 'paroxython.cli:main'
55 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | docopt==0.6.2
2 | pytest==7.1.3
3 | regex==2022.9.13
4 | sqlparse==0.4.3
5 | typing-extensions==4.4.0
6 |
--------------------------------------------------------------------------------
/tests/context.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | sys.path[0:0] = ["."]
4 |
--------------------------------------------------------------------------------
/tests/make_snapshot.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 |
3 | import pytest
4 |
5 |
6 | def make_snapshot(path: Path, result: str, capsys):
7 | expected = path.exists() and path.read_text()
8 | if result != expected:
9 | with capsys.disabled():
10 | print(f"\nWARNING: Use version control to check the changes of snapshot '{path}'.")
11 | path.write_text(result)
12 |
13 |
14 | if __name__ == "__main__":
15 | pytest.main(["-qq", __import__("sys").argv[0]])
16 |
--------------------------------------------------------------------------------
/tests/test_assess_costs.py:
--------------------------------------------------------------------------------
1 | import json
2 | from pathlib import Path
3 |
4 | import pytest
5 |
6 | import context
7 | from paroxython.assess_costs import (
8 | LearningCostAssessor,
9 | range_to_cost_linear,
10 | range_to_cost_zeno,
11 | )
12 |
13 |
14 | def test_range_to_cost_zeno():
15 | assert range_to_cost_zeno(0, 0) == 0
16 | assert range_to_cost_zeno(42, 42) == 0
17 | assert range_to_cost_zeno(0, 1) == (1 / 2)
18 | assert range_to_cost_zeno(0, 2) == (1 / 2 + 1 / 4)
19 | assert range_to_cost_zeno(0, 3) == (1 / 2 + 1 / 4 + 1 / 8)
20 | assert range_to_cost_zeno(1, 4) == (1 / 4 + 1 / 8 + 1 / 16)
21 |
22 |
23 | def test_range_to_cost_linear():
24 | assert range_to_cost_linear(3, 5) == 2
25 |
26 |
27 | def test_taxon_cost():
28 | assess = LearningCostAssessor(None, "linear")
29 | imparted_knowledge = {"O", "O/J", "X", "X/S", "X/S/M", "X/S/M/L"}
30 | assess.set_imparted_knowledge(imparted_knowledge)
31 | assert assess.taxon_cost("O") == 0
32 | assert assess.taxon_cost("O/C") == 1
33 | assert assess.taxon_cost("O/C/F") == 2
34 | assert assess.taxon_cost("O/C/F/U") == 3
35 | assert assess.taxon_cost("O/J") == 0
36 | assert assess.taxon_cost("O/N") == 1
37 | assert assess.taxon_cost("O/N/P") == 2
38 | assert assess.taxon_cost("X") == 0
39 | assert assess.taxon_cost("X/S") == 0
40 | assert assess.taxon_cost("X/S/M") == 0
41 | assert assess.taxon_cost("X/S/M/L") == 0
42 | assert assess.taxon_cost("X/S/M/L/R") == 1
43 | assert assess.taxon_cost("X/S/M/L/R/D") == 2
44 | assert assess.taxon_cost("X/S/M/L/R/D/A") == 3
45 | assert assess.taxon_cost("Y") == 1
46 | assert assess.taxon_cost("Y/E") == 2
47 | assert assess.taxon_cost("Y/T") == 2
48 | assert assess.taxon_cost("Y/T/Q") == 3
49 | assert assess.taxon_cost("") == 1 # weird, but unspecified
50 |
51 |
52 | def test_get_sorted_recommandations():
53 | db = json.loads(Path("examples/dummy/programs_db.json").read_text())
54 | assess = LearningCostAssessor(db["programs"], "zeno")
55 | imparted_knowledge = {"O", "O/J", "X", "X/S", "X/S/M", "X/S/M/L"}
56 | assess.set_imparted_knowledge(imparted_knowledge)
57 | result = assess(db["programs"].keys())
58 | print(result)
59 | assert result == [
60 | (2.8671875, "prg5.py"),
61 | (3.1328125, "prg8.py"),
62 | (3.328125, "prg1.py"),
63 | (3.7578125, "prg4.py"),
64 | (3.9375, "prg3.py"),
65 | (4.015625, "prg2.py"),
66 | (4.296875, "prg7.py"),
67 | (4.7421875, "prg6.py"),
68 | (4.90625, "prg9.py"),
69 | ]
70 |
71 |
72 | if __name__ == "__main__":
73 | pytest.main(["-qq", __import__("sys").argv[0]])
74 |
--------------------------------------------------------------------------------
/tests/test_centrifugate_hints.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from pathlib import Path
3 |
4 | import regex # type: ignore
5 |
6 | import context
7 | from paroxython.preprocess_source import centrifugate_hints
8 |
9 | # This test suite is automatically injected into the docstring of `preprocess_source.py`.
10 |
11 | sources = r"""
12 | <<< Some isolated hints (`hint_3` and `hint_5` are centrifugated).
13 | foo = bar # paroxython: hint_1 hint_2
14 | # paroxython: hint_3
15 | fizz = [
16 | "foo",
17 | "bar", # paroxython: hint_4
18 | # paroxython: hint_5
19 | ]
20 | ---
21 | foo = bar # paroxython: hint_1 hint_2 hint_3... hint_5...
22 | fizz = [
23 | "foo",
24 | "bar", # paroxython: hint_4
25 | ] # paroxython: ...hint_3 ...hint_5
26 | >>>
27 |
28 | <<< Some trailing isolated hints (`hint_5` and `hint_6` are centrifugated).
29 | foo = bar # paroxython: hint_1 hint_2
30 | fizz = [
31 | "foo",
32 | "bar", # paroxython: hint_3
33 | ] # paroxython: hint_4
34 | # paroxython: hint_5
35 | # paroxython: hint_6
36 | ---
37 | foo = bar # paroxython: hint_1 hint_2 hint_5... hint_6...
38 | fizz = [
39 | "foo",
40 | "bar", # paroxython: hint_3
41 | ] # paroxython: hint_4 ...hint_5 ...hint_6
42 | >>>
43 |
44 | <<< No isolated hints (no centrifugation of the existing hints).
45 | foo = bar # paroxython: hint_1 hint_2
46 | fizz = [
47 | "foo",
48 | "bar", # paroxython: hint_4
49 | ]
50 | ---
51 | foo = bar # paroxython: hint_1 hint_2
52 | fizz = [
53 | "foo",
54 | "bar", # paroxython: hint_4
55 | ]
56 | >>>
57 | """
58 | source_rex = regex.compile(r"(?ms)^<<< ([^\n]+)\n(.+?)\n---\n(.+?)\n>>>")
59 | examples = [m for m in source_rex.findall(sources)]
60 |
61 |
62 | @pytest.mark.parametrize("title, original, expected", examples)
63 | def test_centrifugate_hints(title, original, expected):
64 | print(title)
65 | result = centrifugate_hints(original)
66 | print(result)
67 | assert result == expected
68 |
69 |
70 | def test_update_docstring():
71 | indent = "\n "
72 | result = []
73 | for (title, original, expected) in examples:
74 | original = original.replace("\n", indent)
75 | expected = expected.replace("\n", indent)
76 | result.append(f"- {title}")
77 | result.append(fr"```python{indent}{original}{indent}```")
78 | result.append(fr"```python{indent}{expected}{indent}```")
79 | result = indent.join(result)
80 | path = Path("paroxython/preprocess_source.py")
81 | source = path.read_text()
82 | (source, n) = regex.subn(
83 | r"(?sm)^(def centrifugate_hints.+?Examples:\n).+?^ *\n",
84 | fr"\1 {result}\n\n",
85 | source,
86 | )
87 | assert n == 1
88 | path.write_text(source)
89 |
90 |
91 | if __name__ == "__main__":
92 | pytest.main(["-qq", __import__("sys").argv[0]])
93 |
--------------------------------------------------------------------------------
/tests/test_label_programs.py:
--------------------------------------------------------------------------------
1 | import json
2 | from pathlib import Path
3 |
4 | import pytest
5 | import regex
6 |
7 | from make_snapshot import make_snapshot
8 |
9 | import context
10 | from paroxython.label_programs import labelled_programs, generate_labelled_sources
11 | from paroxython.user_types import Span, ProgramPath
12 |
13 |
14 | class ProgramEncoder(json.JSONEncoder):
15 | def default(self, obj):
16 | if isinstance(obj, type(ProgramPath)):
17 | return str(obj)
18 | if isinstance(obj, Span):
19 | return obj.to_couple()
20 | if isinstance(obj, set):
21 | return sorted(obj)
22 | return json.JSONEncoder.default(self, obj)
23 |
24 |
25 | programs = labelled_programs(Path("examples/mini/programs"))
26 |
27 |
28 | def test_label_programs(capsys):
29 | result = programs
30 | text = json.dumps(result, cls=ProgramEncoder, indent=2)
31 | text = regex.sub(r'\s*\[\s+(\d+),\s+(\d+),\s+(".*?")\s+\](,?)\s*', r"[\1,\2,\3]\4", text)
32 | make_snapshot(Path("examples/mini/labelled_programs.json"), text, capsys)
33 |
34 |
35 | def test_generate_labelled_sources(capsys):
36 | chunks = list(generate_labelled_sources(programs))
37 | result = []
38 | for chunk in chunks:
39 | if chunk.startswith("#"):
40 | result.append(chunk)
41 | else:
42 | for line in chunk.split("\n"):
43 | if not line:
44 | continue
45 | (source, _, comment) = line.partition(" # ")
46 | for label in comment.split(", "):
47 | result.append(f"{source} # {label}")
48 | source = " " * len(source)
49 | result.append("")
50 | make_snapshot(Path("examples/mini/labelled_sources.py"), "\n".join(result), capsys)
51 |
52 |
53 | def test_update_snapshots(capsys):
54 | directories = [
55 | "examples/idioms/programs",
56 | "examples/mini/programs",
57 | "examples/simple/programs",
58 | # "../algo/programs",
59 | ]
60 | for directory in directories:
61 | path = Path(directory)
62 | if not path.is_dir():
63 | continue
64 | acc = [result for result in generate_labelled_sources(labelled_programs(path))]
65 | output_path = Path(path.parent, path.parts[-1] + "_with_labels.py")
66 | make_snapshot(output_path, "\n".join(acc), capsys)
67 |
68 |
69 | if __name__ == "__main__":
70 | pytest.main(["-qq", __import__("sys").argv[0]])
71 |
--------------------------------------------------------------------------------
/tests/test_list_programs.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 | import pytest
3 |
4 | import context
5 | from paroxython.list_programs import list_programs
6 |
7 |
8 | def test_list_programs():
9 | result = iter(list_programs(Path("examples/mini/programs/")))
10 |
11 | program = next(result)
12 | assert program.path == "assignment.py"
13 | assert program.source == "a = b"
14 |
15 | program = next(result)
16 | assert program.path == "collatz.py"
17 | assert program.source.startswith("def print_collatz(n):")
18 |
19 | program = next(result)
20 | assert program.path == "fizzbuzz.py"
21 | assert program.source.startswith("import collatz")
22 |
23 | program = next(result)
24 | assert program.path == "is_even.py"
25 | assert program.source.__contains__("def is_even(n):\n return n % 2 == 0")
26 |
27 |
28 | if __name__ == "__main__":
29 | pytest.main(["-qq", __import__("sys").argv[0]])
30 |
--------------------------------------------------------------------------------
/tests/test_make_db.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 | from collections import Counter
3 |
4 | import pytest
5 |
6 | from make_snapshot import make_snapshot
7 |
8 | import context
9 | from paroxython.make_db import TagDatabase, prepared_labels, prepared_taxa
10 | from paroxython.user_types import Span
11 |
12 |
13 | def test_snapshot_mini_db(capsys):
14 | db = TagDatabase(Path("examples/mini/programs"), ignore_timestamps=True)
15 | make_snapshot(Path("examples/mini/programs_db.json"), db.get_json(), capsys)
16 | db.write_sqlite(Path("examples/mini/programs_db.sqlite"))
17 |
18 |
19 | def test_snapshot_programming_idioms_db(capsys):
20 | db = TagDatabase(Path("examples/idioms/programs"), ignore_timestamps=True)
21 | make_snapshot(Path("examples/idioms/programs_db.json"), db.get_json(), capsys)
22 |
23 |
24 | def test_prepared_labels():
25 | labels = [
26 | (
27 | "name_1",
28 | [
29 | Span(start=1, end=2, path="foo"),
30 | Span(start=1, end=2, path="foo"),
31 | Span(start=1, end=2, path="bar"),
32 | ],
33 | ),
34 | ("name_2", [Span(start=2, end=4, path="fizz"), Span(start=6, end=7, path="buzz")]),
35 | ("name_3", [Span(start=5, end=5, path="foobar")]),
36 | ]
37 | result = prepared_labels(labels)
38 | print(result)
39 | assert result == {
40 | "name_1": [(1, 2), (1, 2)],
41 | "name_2": [(2, 4), (6, 7)],
42 | "name_3": [(5, 5)],
43 | }
44 |
45 |
46 | def test_prepared_taxa():
47 | taxa = [
48 | (
49 | "name_1",
50 | Counter({Span(start=1, end=2, path="foo"): 2, Span(start=1, end=2, path="bar"): 1}),
51 | ),
52 | (
53 | "name_2",
54 | Counter({Span(start=2, end=4, path="fizz"): 1, Span(start=6, end=7, path="buzz"): 1}),
55 | ),
56 | ("name_3", Counter({Span(start=5, end=5, path="foobar"): 1})),
57 | ]
58 | result = prepared_taxa(taxa)
59 | print(result)
60 | assert result == {
61 | "name_1": [(1, 2), (1, 2)],
62 | "name_2": [(2, 4), (6, 7)],
63 | "name_3": [(5, 5)],
64 | }
65 |
66 |
67 | if __name__ == "__main__":
68 | pytest.main(["-qq", __import__("sys").argv[0]])
69 |
--------------------------------------------------------------------------------
/tests/test_normalize_predicate.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | import context
4 | from paroxython.normalize_predicate import normalize_predicate
5 | from paroxython.compare_spans import compare_spans
6 |
7 | NEGATED = True
8 | POSITIVE = False
9 |
10 | working_examples = [
11 | ("is after", "y≤y≤x≤x", POSITIVE),
12 | ("is after", "after", POSITIVE),
13 | ("!is after", "after", NEGATED),
14 | ("! is after", "after", NEGATED),
15 | ("not is after", "after", NEGATED),
16 | ("is not after", "after", NEGATED),
17 | ("is after not", "after", NEGATED),
18 | ("IS AFTER", "after", POSITIVE),
19 | (" IS AFTER ", "after", POSITIVE),
20 | ("is", "x=y≤x=y", POSITIVE),
21 | ("is not", "x=y≤x=y", NEGATED),
22 | ("x=y", "x=y≤x=y", POSITIVE),
23 | ("x=y≤y", "x≤x=y≤y", POSITIVE),
24 | ("x≤x=y", "x≤x=y≤y", POSITIVE),
25 | ("y≤x", "y≤y≤x≤x", POSITIVE),
26 | ("x<=x=y<=y", "x≤x=y≤y", POSITIVE),
27 | ("x≤x==y≤y", "x≤x=y≤y", POSITIVE),
28 | ("x<=x==y<=y", "x≤x=y≤y", POSITIVE),
29 | ("(x ≤ x) == (y ≤ y)", "x≤x=y≤y", POSITIVE),
30 | ("(x1 ≤ x2) == (y1 ≤ y2)", "x≤x=y≤y", POSITIVE),
31 | ("(x2 ≤ x1) == (y2 ≤ y1)", "x≤x=y≤y", POSITIVE),
32 | ]
33 |
34 |
35 | @pytest.mark.parametrize("original, normalized, negated", working_examples)
36 | def test_normalize_predicate(original, normalized, negated):
37 | assert normalize_predicate(original) == (compare_spans[normalized], negated)
38 |
39 |
40 | non_working_examples = [
41 | "is after",
42 | "notis after",
43 | "foobar",
44 | "is after_not",
45 | "x≤x≤x=y", # three x's
46 | "x>y", # write "x