├── .coverage
├── .flake8
├── .gitattributes
├── .github
├── CODEOWNERS
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── lain-lain.md
├── pull_request_template.md
└── workflows
│ ├── codeql.yml
│ ├── directory.yml
│ └── uv_test.yml
├── .gitignore
├── .gitpod.yml
├── .mergify.yml
├── .pre-commit-config.yaml
├── .python-version
├── Basic
├── 01_introduction
│ └── README.md
├── 02_tipe_data
│ ├── README.md
│ └── tipe_data.py
├── 03_variable
│ ├── README.md
│ ├── string_variable.py
│ └── variable.py
├── 04_operator
│ ├── README.md
│ ├── operator_aritmatika.py
│ ├── operator_bitwise.py
│ ├── operator_identitas.py
│ ├── operator_keanggotaan.py
│ ├── operator_logika.py
│ ├── operator_penugasan.py
│ ├── operator_penugasan_ekspresi.py
│ └── operator_perbandingan.py
├── 05_string
│ ├── README.md
│ └── string_python.py
├── 06_input_output
│ ├── README.md
│ └── input_output.py
├── 07_logika_percabangan
│ ├── README.md
│ └── logika_percabangan.py
├── 08_perulangan
│ ├── README.md
│ ├── for_loop.py
│ └── while_loop.py
├── 09_fungsi
│ ├── README.md
│ ├── fungsi.py
│ └── recursion_example.py
├── 10_list_tuple
│ ├── README.md
│ ├── list_python.py
│ └── tuple_python.py
├── 11_manipulasi_string
│ └── README.md
├── 12_exception
│ ├── README.md
│ └── exception.py
├── 13_module
│ ├── README.md
│ ├── kalkulator.py
│ ├── perhitungan1.py
│ └── perhitungan2.py
├── 14_python_datetime
│ ├── README.md
│ ├── module_datetime.py
│ └── perhitungan_umur.py
├── 15_python_math
│ ├── README.md
│ ├── math_eksponen_logaritma.py
│ ├── math_konstanta.py
│ ├── math_konversi_sudut.py
│ ├── math_pembulatan.py
│ └── math_trigonometri.py
├── 16_class
│ ├── README.md
│ ├── class.py
│ ├── const_desct.py
│ ├── dunder_method.py
│ └── methods.py
├── 17_inheritance
│ ├── README.md
│ └── inheritance_python.py
├── 18_akses_modifikasi
│ ├── 01_public
│ │ ├── README.md
│ │ └── public.py
│ ├── 02_private
│ │ ├── README.md
│ │ └── private.py
│ └── 03_protected
│ │ ├── README.md
│ │ └── protected.py
├── 19_iterator
│ ├── README.md
│ └── iterator.py
├── 20_lambda
│ ├── README.md
│ └── lambda.py
├── 21_regex
│ ├── README.md
│ └── regex_code.py
├── 22_scope
│ └── README.md
├── 23_kalkulator_dengan_fungsi
│ └── kalkulator_fungsi.py
├── 24_casting_tipe_data
│ └── casting_tipe_data.py
├── 25_list_and_dict_comprehension
│ ├── dict_comprehension.py
│ └── list_comprehension.py
├── 26_dekorator
│ ├── README.md
│ └── dekorator.py
├── Introduction.py
└── README.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── DIRECTORY.md
├── Dockerfile
├── LICENSE
├── README.md
├── SECURITY.md
├── algorithm
├── arithmetic_analysis
│ ├── README.md
│ ├── bisection.py
│ ├── gaussian_elimination.py
│ ├── in_static_equilibrium.py
│ ├── intersection.py
│ ├── jacobi_iteration_method.py
│ ├── lu_decomposition.py
│ ├── newton_forward_interpolation.py
│ ├── newton_method.py
│ ├── newton_raphson.py
│ ├── rootsearch.py
│ └── secant_method.py
├── backtracking
│ ├── README.md
│ ├── all_combinations.py
│ ├── cari_kata.py
│ ├── coloring.py
│ ├── combination.py
│ ├── hamilton_cycle.py
│ ├── knight_tour.py
│ ├── minimax.py
│ ├── n_queen_math.py
│ ├── n_queens.py
│ ├── permutation.py
│ ├── rat_in_maze.py
│ ├── subsequence.py
│ └── sudoku.py
├── boolean_algebra
│ ├── README.md
│ └── quinc_mc_cluskey.py
├── divide_and_conquer
│ ├── README.md
│ ├── closest_pair_of_points.py
│ ├── convex_hull.py
│ ├── heap_algorithm.py
│ ├── inversion.py
│ ├── kth_order_statistic.py
│ ├── max_difference_pair.py
│ └── max_subarray_sum.py
├── fuzzy_logic
│ ├── README.md
│ └── fuzzy_operation.py
├── genetic_algo
│ ├── README.md
│ └── basic_string.py
├── manipulasi_bit
│ ├── README.md
│ ├── binary_and_operator.py
│ ├── binary_count_trailing_zero.py
│ ├── binary_or_operator.py
│ ├── binary_setbits.py
│ ├── binary_shift.py
│ ├── binary_two_complement.py
│ ├── binary_xor_operator.py
│ ├── count_one_of_bit.py
│ └── reverse_bit.py
├── matrix
│ ├── README.md
│ ├── inverse_matrix.py
│ ├── matrix_class.py
│ ├── matrix_operation.py
│ ├── rotate_matrix.py
│ ├── searching_in_sorted_matrix.py
│ ├── sherman_morison.py
│ └── spiral_matrix.py
├── networking_flow
│ ├── README.md
│ ├── ford_fulkerson.py
│ └── minimum_cut.py
├── searching
│ ├── README.md
│ ├── _types.py
│ ├── binary_search.py
│ └── linear_search.py
└── sorting
│ ├── bead_sort.py
│ ├── bitonic_sorting.py
│ ├── bogo_sorting.py
│ ├── bubble_sort.py
│ ├── bubble_sort_ascii.py
│ ├── bucket_sort.py
│ ├── circle_sort.py
│ ├── gnome_sorting.py
│ ├── merge_sort.py
│ ├── pop_sort.py
│ └── quick_sorting.py
├── assets
└── logo.png
├── dev-requirements.txt
├── implementation
├── artificial_intelligence
│ ├── dataset_lstm.csv
│ ├── decision_tree.py
│ ├── fungsi_skoring.py
│ ├── gaussian_naive_bayes.py
│ ├── gradient_descent.py
│ ├── k_means_clutser.py
│ ├── k_nearest_neighbour.py
│ ├── lasso_regession.py
│ ├── linear_regression.py
│ ├── logistic_regression.py
│ ├── lstm.py
│ ├── normalization_data_tranform.py
│ ├── polynominal.py
│ ├── random_forest.py
│ ├── rigde_regession.py
│ └── similarity_searching.py
├── audio_filter
│ ├── audio_response.py
│ └── iir_filter.py
├── blockchain
│ ├── README.md
│ ├── chinese_remainder.py
│ ├── diophantine_equation.py
│ └── modular_division.py
├── celular_automata
│ ├── README.md
│ ├── game_of_life.py
│ ├── nagel_schrekenberg.py
│ └── one_dimensional.py
├── chiper
│ ├── README.md
│ ├── __init__.py
│ ├── affine.py
│ ├── atbash.py
│ ├── base16.py
│ ├── base32.py
│ ├── base64.py
│ ├── base85.py
│ ├── caesar.py
│ ├── cryptomath_module.py
│ ├── hill_chiper.py
│ ├── playfair.py
│ └── rot13.py
├── compression
│ ├── README.md
│ ├── burrows_wheeler.py
│ ├── huffman.py
│ └── lempel_ziv.py
├── computer_vision
│ ├── README.md
│ └── klasifikasi_cnn.py
├── electro
│ ├── README.md
│ ├── conversion
│ │ ├── binary_to_decimal.py
│ │ ├── binary_to_octal.py
│ │ ├── binary_to_string.py
│ │ └── temperature_conversion.py
│ └── ohm.py
├── file_transfer
│ ├── README.md
│ ├── __init__.py
│ ├── receive_file.py
│ ├── send_file.py
│ └── textfile.txt
├── finansial
│ └── angsuran.py
├── fractal
│ ├── README.md
│ ├── koch.py
│ ├── mandelbrot.py
│ └── sierpinski_triangle.py
├── fuzzy_logic
│ └── fuzzy_logic.py
├── geodesy_egineering
│ ├── README.md
│ ├── __init__.py
│ ├── ellipsodial_distance.py
│ └── haversine.py
├── graphic
│ └── bezier_curve.py
├── image_processing
│ ├── data_image
│ │ ├── README.txt
│ │ ├── __init__.py
│ │ └── example_image.jpg
│ └── gambar_sepia.py
├── linear_algebra
│ ├── README.md
│ ├── conjugate_gradient.py
│ ├── polynom_for_point.py
│ ├── rayleigh_quotient.py
│ └── transformation_2d.py
├── physics
│ ├── README.md
│ ├── n_body_simulation.py
│ └── percepatan.py
└── statistic
│ ├── LabelEncoding.py
│ ├── correlation.py
│ ├── covariance.py
│ ├── entropy.py
│ ├── factorAnalitic.py
│ ├── information_gain.py
│ ├── median.py
│ ├── modus.py
│ ├── multivariate_normal.py
│ ├── normalDistribution_multivariate.py
│ ├── rata_rata.py
│ ├── softmax.py
│ ├── standard_deviasi.py
│ └── variance.py
├── math
├── runge_kutta.py
├── README.md
├── aliquot_sum.py
├── angka_proth.py
├── bisection_math.py
├── convolution.py
├── counter.py
├── digit_sum.py
├── exponential_function.py
├── faktor_prima.py
├── fibonacci.py
├── fungsi_gamma.py
├── geometric_sum.py
├── intergration.py
├── is_prime.py
├── iteration_power.py
├── jumlah_deret_geomteri.py
├── midpoint.py
├── pascal_triangle.py
├── persamaan_kuadarat_bilangan_kompleks.py
├── prime_number_library.py
├── proth_number.py
├── qr_decomposition.py
├── r2_score.py
├── radian.py
├── random_generator.py
├── rectangle.py
├── recursion_power.py
├── relu.py
├── segmented_sieve.py
├── sieve_of_eratosthenes.py
├── sigmoid.py
├── simpson.py
├── sin.py
├── sock_merchant.py
├── softmax.py
├── sum_geometric_progression.py
├── sylvester_sequence.py
├── teorema_pytaghoras.py
├── trapezoid.py
├── triplet_sum.py
├── two_pointer.py
├── two_sum.py
├── ugly_number.py
├── variance.py
├── volume.py
└── zellers_congruence.py
├── matrix
├── median_matriks.py
└── pencarian_biner_matrix.py
├── object_oriented
├── README.md
├── advance
│ ├── .gitignore
│ ├── README.md
│ └── pycode
│ │ ├── argument
│ │ ├── README.md
│ │ └── args.py
│ │ ├── decorators
│ │ ├── README.md
│ │ ├── contoh_decorators1.py
│ │ ├── contoh_decorators2.py
│ │ ├── contoh_decorators3.py
│ │ ├── contoh_decoratos.md
│ │ ├── decorators.py
│ │ ├── decorators_chaining.py
│ │ └── decorators_return.py
│ │ ├── generators
│ │ ├── README.md
│ │ ├── generators_for.py
│ │ └── generators_while.py
│ │ ├── magic_methods
│ │ ├── Mmethod.py
│ │ └── README.md
│ │ ├── metaclass
│ │ ├── README.md
│ │ ├── composite.py
│ │ ├── docs
│ │ │ ├── composite.md
│ │ │ ├── factory.md
│ │ │ ├── proxy.md
│ │ │ └── singleton.md
│ │ ├── factory.py
│ │ ├── proxy.py
│ │ ├── singleton.py
│ │ └── src
│ │ │ └── __init__.py
│ │ └── type_hint
│ │ ├── README.md
│ │ └── hinter.py
├── basic_oop
│ ├── 00_definisi_kelas
│ │ └── README.md
│ ├── 01_atribut_kelas
│ │ ├── README.md
│ │ └── atribut_kelas.py
│ └── 02_mewarisi_kelas
│ │ └── README.md
└── intermediate
│ ├── README.md
│ ├── abstraksi
│ ├── README.md
│ └── abstraksi.py
│ ├── encapsulation
│ ├── README.md
│ ├── encapsulation.py
│ └── encapsulation2.py
│ ├── inheritance
│ ├── README.md
│ └── inheritance.py
│ └── polimorfis
│ ├── README.md
│ ├── polimorfisme_kelas.py
│ └── polimorfisme_sederhana.py
├── other
├── README.md
├── anagramCheck.py
├── date_to_weekday.py
├── doomsday_alg.py
├── hex_to_rgb.py
├── is_palindrom.py
├── power_dac.py
├── rgb_to_hex.py
├── strong_password_check.py
├── tower_of_hanoi.py
└── turtle
│ ├── README.md
│ └── logo_apple.py
├── pyproject.toml
├── pytest.ini
├── regular_expression
└── 00_pengenalan_regex
│ ├── README.md
│ └── contoh_regex.py
├── requirements.txt
├── scripts
└── build_directory_md.py
├── struktur_data
├── README.md
├── doubly_linked_list.py
├── singly_linked_list.py
├── stack
│ ├── README.md
│ └── stack_list.py
└── tree
│ ├── README.md
│ ├── avl_tree
│ ├── README.md
│ └── avl_tree.py
│ ├── binary_search_tree
│ ├── README.md
│ ├── basic_binary_tree.py
│ ├── binary_search_tree.py
│ ├── binary_search_tree_rekursif.py
│ ├── binary_tree_node_sum.py
│ ├── binary_tree_path_sum.py
│ └── img
│ │ ├── bst_example.png
│ │ ├── bst_insertion.png
│ │ ├── inorder.png
│ │ ├── postorder.png
│ │ └── preorder.png
│ ├── binary_tree_mirror.py
│ ├── fenwick_tree.py
│ └── img
│ ├── Ilustrasi_BST.png
│ ├── complete_bt.png
│ ├── degenerate_bt.png
│ ├── full_bt.png
│ ├── height_of_tree.png
│ └── perfect_bt.png
├── uv.lock
└── web_programming
├── README.md
├── breadcrumb_generator.py
├── covid_stat_xpath.py
├── emisi_co2.py
├── get_random_quote.py
├── pagination_helper.py
└── statik_corona.py
/.coverage:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/.coverage
--------------------------------------------------------------------------------
/.flake8:
--------------------------------------------------------------------------------
1 | [flake8]
2 | ignore = E203,W503,W504,E741
3 | max-complexity = 25
4 | show-source = true
5 | max-line-length = 88
6 | exclude = Basic
7 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 |
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 |
2 | # This is a comment.
3 | # Each line is a file pattern followed by one or more owners.
4 |
5 | # These owners will be the default owners for everything in
6 | # the repo. Unless a later match takes precedence,
7 | # @global-owner1 and @global-owner2 will be requested for
8 | # review when someone opens a pull request.
9 |
10 | # Commenting instead of deleting these users in the legacy file
11 | # to fix the current errors.
12 | # @KelvinMulyawan - since this user could not be found on GitHub
13 | # @hendri-27 - since this user didn't appear to have write access
14 | # according to the bellshade/Python contributions graphs
15 | * @athallahmaajid @slowy07
16 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: [slowy07, athallahmaajid]
2 | custom: ["https://saweria.co/bellshade"]
3 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: buat report untuk membantu kita dalam menyelesaikan masalah pada repository
4 | title: BUG
5 | labels: bug
6 | assignees: slowy07
7 |
8 | ---
9 |
10 | ## Masalah
11 |
12 |
13 | ## Screenshots atau contoh error
14 |
15 | ```
16 | pesan error
17 | ```
18 |
19 | ## Desktop (please complete the following information):
20 |
21 | - OS: ``linux/windows/macOS``
22 | - Python: ``version``
23 |
24 |
25 | terima kasih !
26 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/lain-lain.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Lain Lain
3 | about: buat report deskripsi untuk pull request
4 | title: Penambahan algoritma
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | ## Description
11 |
12 |
13 | ## Saya Menggunakan
14 |
15 | OS : ``Linux / Windows / MacOS``
16 | Python: ``version``
17 |
18 | ## tambahan lainnya
19 |
20 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ## Deskripsi (Description)
2 |
3 |
4 | ## Checklist:
5 | ### Umum:
6 |
7 | - [ ] Saya menambah algoritma terbaru.
8 | - [ ] Saya memperbaiki algoritma yang sudah ada.
9 | - [ ] Saya memperbaiki dokumentasi.
10 | - [ ] Saya menambah dokumentasi.
11 |
12 | ### Contributor Requirements (Syarat Kontributor) dan Lain-Lain:
13 |
14 | - [ ] Saya sudah membaca (I have read) [CONTRIBUTING](https://github.com/bellshade/PythonAlgorithm/blob/main/CONTRIBUTING.md) dan sudah menyetujui semua syarat.
15 | - [ ] Saya telah menambahkan docstring yang memberikan penjelasan maksud dari kode yang saya buat.
16 | - [ ] Saya menggunakan bahasa Indonesia untuk memberikan penjelasan dari kode yang saya buat.
17 |
18 | ### Unit Testing dan Linting:
19 |
20 | - [ ] pytest
21 | - [ ] flake8
22 |
23 | ## Environment
24 |
25 | Saya menggunakan (I'm using):
26 |
27 | - ``os`` = ``linux / windows / macOS``
28 | - ``python`` = ``python3 -V (unix) / py -3 -V (Windows-Python launcher)``
29 |
30 |
31 |
32 |
33 | linked issue #NOMOR_ISSUE
--------------------------------------------------------------------------------
/.github/workflows/codeql.yml:
--------------------------------------------------------------------------------
1 | name: "CodeQL"
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | pull_request:
7 | branches: [ "main" ]
8 | schedule:
9 | - cron: "7 14 * * 3"
10 |
11 | jobs:
12 | analyze:
13 | name: Analyze
14 | runs-on: ubuntu-latest
15 | permissions:
16 | actions: read
17 | contents: read
18 | security-events: write
19 |
20 | strategy:
21 | fail-fast: false
22 | matrix:
23 | language: [ python ]
24 |
25 | steps:
26 | - name: Checkout
27 | uses: actions/checkout@v3
28 |
29 | - name: Initialize CodeQL
30 | uses: github/codeql-action/init@v2
31 | with:
32 | languages: ${{ matrix.language }}
33 | queries: +security-and-quality
34 |
35 | - name: Autobuild
36 | uses: github/codeql-action/autobuild@v2
37 |
38 | - name: Perform CodeQL Analysis
39 | uses: github/codeql-action/analyze@v2
40 | with:
41 | category: "/language:${{ matrix.language }}"
42 |
--------------------------------------------------------------------------------
/.github/workflows/directory.yml:
--------------------------------------------------------------------------------
1 | name: directory_writer
2 | on: [push]
3 | jobs:
4 | build:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - uses: actions/checkout@v4
8 | - uses: actions/setup-python@v5
9 | - name: Write DIRECTORY.md
10 | run: |
11 | chmod +x scripts/build_directory_md.py
12 | scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
13 | git config --global user.name github-actions
14 | git config --global user.email 'bellshdae07@gmail.com'
15 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
16 | - name: Update DIRECTORY.md
17 | run: |
18 | git add DIRECTORY.md
19 | git commit -am "docs: update DIRECTORY.md" || true
20 | git push --force origin HEAD:$GITHUB_REF || true
21 |
--------------------------------------------------------------------------------
/.github/workflows/uv_test.yml:
--------------------------------------------------------------------------------
1 | name: uv python test
2 |
3 | on:
4 | pull_request:
5 | branches: [main]
6 |
7 | jobs:
8 | build:
9 | # menjalankan testing dengan 3 os yaitu
10 | # linux (ubuntu), windows, dan macOS
11 | runs-on: ${{ matrix.os }}
12 |
13 | strategy:
14 | matrix:
15 | os: [macos-latest, windows-latest, ubuntu-latest]
16 |
17 | steps:
18 | - name: Checkout Code
19 | uses: actions/checkout@v4
20 |
21 | - name: Install uv
22 | uses: astral-sh/setup-uv@v5
23 |
24 | - name: Setting python
25 | uses: actions/setup-python@v5
26 | with:
27 | python-version-file: ".python-version"
28 |
29 | - name: install depedencies
30 | run: uv add -r dev-requirements.txt
31 |
32 | - name: run testing
33 | run: |
34 | uv add pre-commit
35 | uv run pre-commit install
36 | uv run pre-commit run --all-files
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # direktori hasil cache testing
2 | # akan di ignore oleh git
3 | # agar tidak ikut dalam proses git push
4 | .vscode
5 | env/*
6 | __pycache__/
7 | .vscode/
8 | .mypy_chache/
9 | .pytest_cache/
10 | pip-log.txt
11 |
12 | # hasil coverage
13 | .coverage
14 |
--------------------------------------------------------------------------------
/.gitpod.yml:
--------------------------------------------------------------------------------
1 | tasks:
2 | - init: pip3 install -r requirements.txt
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/pre-commit/pre-commit-hooks
3 | rev: v4.6.0
4 | hooks:
5 | - id: check-executables-have-shebangs
6 | - id: check-yaml
7 | - id: end-of-file-fixer
8 | types: [python]
9 | - id: requirements-txt-fixer
10 |
11 | - repo: https://github.com/MarcoGorelli/auto-walrus
12 | rev: 0.3.4
13 | hooks:
14 | - id: auto-walrus
15 |
16 | - repo: https://github.com/psf/black
17 | rev: 24.4.2
18 | hooks:
19 | - id: black
20 |
21 | - repo: https://github.com/PyCQA/flake8
22 | rev: 7.1.0
23 | hooks:
24 | - id: flake8
25 | args:
26 | - --exclude=Basic
27 | - --ignore=E203,W503,F401,W504,F821,F841,E741,E721
28 | - --max-complexity=25
29 | - --max-line-length=100
30 |
31 |
--------------------------------------------------------------------------------
/.python-version:
--------------------------------------------------------------------------------
1 | 3.12
2 |
--------------------------------------------------------------------------------
/Basic/03_variable/string_variable.py:
--------------------------------------------------------------------------------
1 | # String dalam Python diidentifikasi
2 | # sebagai serangkaian karakter yang berdekatan
3 | # yang diwakili dalam tanda kutip.
4 |
5 | # Dalam membuat variabel string kita dapat
6 | # menggunakan petik dua ("") / petik satu ('')
7 | pesan = "saya pergi ke pasar"
8 |
9 | # s a y a p e r g i
10 | # 0 1 2 3 4 5 5 6 7 8 9
11 |
12 | # k e p a s a r
13 | # 10 11 12 13 14 15 16 17
14 |
15 | # Dalam tipe data string, value dari
16 | # variabel tersebut akan dianggap sebagai
17 | # list. Maka dari kita dapat memanggil
18 | # setiap karakter dengan urutan index
19 |
20 | # print secara keseluruhan
21 | print(pesan)
22 | # print karakter pertama pada pesan
23 | print(pesan[0])
24 | # print karakter dari karakter ke 3 sampai 5
25 | print(pesan[2:5])
26 | # print dimulai dari karakter ke 3
27 | print(pesan[2:])
28 | # print kata 2 kali
29 | print(pesan * 2)
30 |
31 |
32 | # gabung kata dengan kata baru
33 | # saya pergi kepasar dengan ibu saya
34 | print(pesan + " dengan ibu saya")
35 | print(pesan, " dengan ibu saya")
36 |
--------------------------------------------------------------------------------
/Basic/03_variable/variable.py:
--------------------------------------------------------------------------------
1 | nama = "Riskiy" # contoh tipe data string
2 | umur = 12 # contoh tipe data integer (int)
3 | nilai = 95.5 # nilai
4 |
5 | # tanda koma ',' pada print digunakan untuk
6 | # menambahkan nilai variabel ke perintah print
7 | print("Dia bernama ", nama)
8 | print("Dia baru berumur ", umur, " tahun")
9 | print("dan dia mendapatkan nilai ", nilai)
10 | print("dan itu sangat hebat sekali")
11 |
12 | # contoh penggunaan variabel yang dilarang
13 | # 1angka = 1 karena dimulai dari angka
14 |
15 | # contoh penggunaan variable yang baik
16 | # nama_lengkap = "jhon lenon"
17 | # nama_lengkap2 = "jhon lenin"
18 | # nama_lengkap_2 = "jhon lenan"
19 |
20 | # contoh inisiasi beberapa variable
21 | # dalam satu line
22 | a, b, c = 1, 2, 3
23 | print("a adalah nomor ", a) # 1
24 | print("b adalah nomor ", b) # 2
25 | print("c adalah nomor ", c) # 3
26 |
27 | # contoh penggunaan satu value dalam
28 | # beberapa variabel
29 | d = e = f = 1
30 | print("d adalah nomor ", d) # 1
31 | print("e adalah nomor ", e) # 1
32 | print("f adalah nomor ", f) # 1
33 |
--------------------------------------------------------------------------------
/Basic/04_operator/operator_aritmatika.py:
--------------------------------------------------------------------------------
1 | # operator digunakan untuk menjalankan operasi
2 | # antara kedua variabel atau value
3 | # contoh
4 |
5 |
6 | angka = 20
7 | angka_kedua = 50
8 |
9 | # operator penambahan
10 | print(30 + 20)
11 |
12 |
13 | # operator pengurangan
14 | print(angka_kedua - angka)
15 |
16 |
17 | # operator perkalian
18 | print(3 * 5)
19 |
20 | # operator pembagi
21 | print(20 * 5)
22 |
23 | # operator modulus
24 | # oeprator modulus menghitung nilai sisa bagi
25 | # dari suatu operasi matematika
26 | # sisa hasil bagi adalah bagian dari hasil
27 | # pembagian yang tidak menghasilkan bilangan
28 | # bulat
29 | # contoh
30 | # misalnya 7 / 2 = 3.5
31 | # berarti 3 sisa 1 krna sistem pembagian
32 | # dengan metode porogapit
33 | # contoh pembagian porogapit
34 | # https://id.wikihow.com/Melakukan-Pembagian-Bersusun-Panjang
35 | print(100 % 5)
36 |
37 | # operator perpangkatan
38 | print(4**2)
39 |
40 | # operator floor division
41 | # mengambil nilai utama dari suatu pembagian
42 | # sebagai contoh
43 | # 2 / 7 = 0.28
44 | # maka floor division hanya mengambil angka
45 | # angka utamanya yaitu 0
46 | print(30 // 2)
47 |
--------------------------------------------------------------------------------
/Basic/04_operator/operator_bitwise.py:
--------------------------------------------------------------------------------
1 | angka_saya = 30
2 | angka_saya1 = 6
3 |
4 | print("operator bitwise")
5 | print("angka_saya & angka =", angka_saya & angka_saya1)
6 | print("angka_saya | angka =", angka_saya | angka_saya1)
7 | print("angka_saya ^ angka =", angka_saya ^ angka_saya1)
8 | print("~angka_saya =", ~angka_saya)
9 |
10 |
11 | print("\noperator bitwise left and right")
12 | angka_lain = 30
13 | angka_lain1 = -30
14 | print("angka_lain = 30 >> 1 =", angka_lain >> 1)
15 | print("angka_lain1 = -30 >> 1 =", angka_lain1 >> 1)
16 |
17 | print("angka lain = 30 << 1 =", angka_lain << 1)
18 | print("angka_lain1 = -30 << 1 =", angka_lain1 << 1)
19 |
--------------------------------------------------------------------------------
/Basic/04_operator/operator_identitas.py:
--------------------------------------------------------------------------------
1 | # Operator Identitas adalah operator yang digunakan
2 | # untuk membandingkan suatu object. Jika object bernilai sama
3 | # dan memiliki memori yang sama, maka akan mengembalikan nilai True.
4 | # contoh:
5 |
6 |
7 | # variabel
8 | x = 3
9 | y = 7
10 |
11 | # cek apakah nilai dari variabel x dan y ada pada memori yang sama
12 | # jika x is y, maka cetak "Sama"
13 | # lain jika x is not y, maka cetak "Tidak sama"
14 |
15 | if x is y:
16 | print("Sama")
17 | elif x is not y:
18 | print("Tidak sama")
19 | print("\n")
20 |
21 |
22 | # jika tipe data y bukan integer, maka cetak "Ini bukan integer"
23 | # jika tidak, maka cetak "Ini adalah integer"
24 |
25 | if type(y) != int:
26 | print("Ini bukan integer")
27 | else:
28 | print("Ini adalah integer")
29 |
--------------------------------------------------------------------------------
/Basic/04_operator/operator_keanggotaan.py:
--------------------------------------------------------------------------------
1 | # Operator Keanggotaan (Membership Operator) adalah operator
2 | # yang memvalidasi anggota dari sebuah objek iterable
3 | # contoh:
4 |
5 |
6 | X = [1, 2, "3", 4, "lima"]
7 |
8 | # memvalidasi "3" didalam variable "X"
9 | print("3" in X) # True
10 |
11 | # memvalidasi 1 tidak didalam variable "X"
12 | print(1 not in X) # False
13 |
--------------------------------------------------------------------------------
/Basic/04_operator/operator_logika.py:
--------------------------------------------------------------------------------
1 | # operator logika (Logical Operator) digunakan untuk
2 | # menggabungkan pernyataan kondisional
3 | # bingung?
4 | # mari kita buat contohnya
5 |
6 |
7 | # variabel
8 | X = 5
9 |
10 | # operator "and" digunakan untuk mengecek
11 | # apakah kedua pernyataan yang diberikan bernilai True
12 |
13 | print("X < 6 and X > 1:", X < 6 and X > 1) # True
14 | print("X > 6 and X > 1:", X > 6 and X > 1) # False
15 |
16 | # operator "or" digunakan untuk mengecek
17 | # apakah salah satu dari dua pernyataan bernilai True
18 |
19 | print("X > 6 or X > 1:", X > 6 or X > 1) # True
20 | print("X > 6 or X < 1:", X > 6 or X < 1) # False
21 |
22 | # operator "not" digunakan untuk mengecek
23 | # apakah nilai tersebut bernilai False
24 |
25 | X_UNDER_6 = X < 6
26 | X_ABOVE_10 = X > 10
27 |
28 | print(not X_UNDER_6) # False
29 | print(not X_ABOVE_10) # True
30 |
--------------------------------------------------------------------------------
/Basic/04_operator/operator_penugasan.py:
--------------------------------------------------------------------------------
1 | # Operator penugasan (Assignment Operator) digunakan untuk
2 | # menetapkan nilai suatu variable
3 |
4 | """
5 | Operator Penugasan terdiri dari:
6 |
7 | | Operator | Example | Sama Dengan |
8 | |---------------|---------------|---------------|
9 | | = | x = 5 | x = 5 |
10 | | += | x += 3 | x = x + 3 |
11 | | -= | x -= 3 | x = x - 3 |
12 | | *= | x *= 3 | x = x * 3 |
13 | | /= | x /= 3 | x = x / 3 |
14 | | %= | x %= 3 | x = x % 3 |
15 | | //= | x //= 3 | x = x // 3 |
16 | | **= | x **= 3 | x = x ** 3 |
17 | | &= | x &= 3 | x = x & 3 |
18 | | |= | x |= 3 | x = x | 3 |
19 | | ^= | x ^= 3 | x = x ^ 3 |
20 | | <<= | x <<= 3 | x = x << 3 |
21 | | >>= | x >>= 3 | x = x >> 3 |
22 | """
23 |
24 | # contoh:
25 |
26 | # variable
27 | nilai = 5
28 |
29 |
30 | # menetapkan sekaligus menambahkan nilai ke variable nilai
31 | nilai += 3
32 | print("nilai += 3 adalah", nilai)
33 |
34 | # menetapkan sekaligus mengurangkan nilai ke variable nilai
35 | nilai -= 3
36 | print("nilai -= 3 adalah", nilai)
37 |
38 | # dan seterusnya
39 |
--------------------------------------------------------------------------------
/Basic/04_operator/operator_perbandingan.py:
--------------------------------------------------------------------------------
1 | # Operator Perbandingan (Comparison Operator) digunakan untuk
2 | # Membadingkan antara dua nilai
3 | # contoh
4 |
5 | # Variable
6 | a = 5
7 | b = 3
8 |
9 | # == (sama dengan) digunakan untuk membandingkan
10 | # apakah kedua nilai memiliki nilai yang sama
11 | print("a == b:", a == b) # False
12 |
13 | # != (tidak sama dengan) digunakan untuk membadingkan
14 | # apakah kedua nilai tidak memiliki nilai yang sama
15 | print("a != b:", a != b) # True
16 |
17 | # > (lebih besar dari) digunakan untuk membandingkan
18 | # apakah nilai kiri lebih besar dari nilai kanan
19 |
20 | print("a > b:", a > b) # True
21 |
22 | # < (lebih kecil dari) digunakan untuk membadingkan
23 | # apakah nilai kiri lebih kecil dari nilai kanan
24 | print("a < b:", a < b) # False
25 |
26 | # >= (lebih besar dari atau sama dengan) digunakan untuk membandingkan
27 | # apakah nilai kiri lebih besar dari atau sama dengan nilai kanan
28 | print("a >= b:", a >= b) # True
29 |
30 | # <= (lebih kecil dari atau sama dengan) digunakan untuk membadingkan
31 | # apakah nilai kiri lebih kecil dari atau sama dengan nilai kanan
32 | print("a <= b:", a <= b) # False
33 |
--------------------------------------------------------------------------------
/Basic/05_string/string_python.py:
--------------------------------------------------------------------------------
1 | # string di python bisa menggunakan
2 | # petik satu dan petik dua
3 | # contoh
4 | # "Hello World" sama dengan 'hello world'
5 | # 'hello world' sama dengan "hello world"
6 | # Namun disarankan menggunakan petik dua
7 | # dalam deklarasi python
8 |
9 |
10 | kata_pertama = "warung"
11 |
12 | # bisa juga menggunakan multi string
13 | # bisa menggunakan 3 tanda petik dua atau satu
14 | kata_saya = """Indonesia adalah negara yang indah
15 | berada di bawah garis khatulistiwa
16 | aku cinta Indonesia
17 | """
18 |
19 | # print(kata_pertama)
20 | print(kata_saya)
21 |
22 | # mengubah kata ke huruf besar
23 | print(kata_pertama.upper())
24 |
25 | # mengubah kata ke huruf kecil
26 | print(kata_pertama.lower())
27 |
28 | # mengambil salah satu karakter dari string
29 | # contoh
30 | print(kata_pertama[0])
31 |
32 | # menghitung jumlah karatker dari string
33 | # contoh
34 | print(len(kata_pertama))
35 |
36 | # kita juga dapat mengecek kata khusus dalam sebuah string
37 | # contoh
38 | print("Indonesia" in kata_saya)
39 | print("Indonesia" in "one") # lgtm [py/comparison-of-constants]
40 |
--------------------------------------------------------------------------------
/Basic/06_input_output/README.md:
--------------------------------------------------------------------------------
1 | # Input/Output Python
2 |
3 | Pada Python terdapat fungsi dimana kita bisa membuat sebuah inputan. Contohnya sebagai berikut:
4 |
5 | ```python
6 | nama = input("masukkan nama kamu ")
7 | print(nama)
8 | ```
9 |
10 | pada kode diatas jika dijalankan akan menampilkan:
11 |
12 | ```bash
13 | masukkan nama kamu
14 | ```
15 |
16 | Jika kita memasukkan nama maka program akan menampilkan nama yang sebelumnya kita ketik:
17 |
18 | ```bash
19 | masukkan nama kamu
20 | arfy
21 | arfy
22 | ```
23 |
24 | Contoh lain:
25 |
26 | ```python
27 | nama = input("masukkan nama ")
28 | print("selamat pagi ", nama)
29 | ```
30 |
31 | Maka akan menampilkan berupa ``selamat pagi nama_yang_diinputkan``. Contoh output:
32 |
33 | ```bash
34 | masukkan nama
35 | arfy
36 | selamat pagi arfy
37 | ```
38 |
39 | Kita juga bisa merubah value dari variabel yang sudah ada dengan menggunakan input.
40 |
41 | ```python
42 | nama = "arfy"
43 | # menampikan isi value dari nama terlebih dahulu
44 | print(nama)
45 | nama = input("masukkan nama ")
46 | print("di variabel nama sekarang adalah ", nama)
47 | ```
48 |
49 | Maka output yang keluar adalah:
50 |
51 | ```bash
52 | arfy
53 | masukkan nama
54 | jole
55 | di variabel nama sekarang adalah jole
56 | ```
57 |
58 | Video penjelasan tentang operator input output = [Belajar python dasar - mengambil input data dari user](https://www.youtube.com/watch?v=Ar1xxIsyuvI&list=PLZS-MHyEIRo59lUBwU-XHH7Ymmb04ffOY&index=8)
59 |
60 | [Materi Selanjutnya](../07_logika_percabangan)
--------------------------------------------------------------------------------
/Basic/06_input_output/input_output.py:
--------------------------------------------------------------------------------
1 | # input digunakan untuk
2 | # memasukkan variabel secara dinamis
3 | # output digunakan untuk
4 | # contoh
5 |
6 |
7 | nama = "joes"
8 | print(nama)
9 |
10 | # mengganti nama 'joes' menjadi sesuai user
11 | nama = input("masukkan nama :")
12 | print(nama)
13 |
14 | # menggunakan inputan sesuai tipe data
15 | # jika memasukkan inputan selain angka integer
16 | # akan terjadi error
17 | angka = int(input("masukkan angka :"))
18 | print(angka)
19 |
--------------------------------------------------------------------------------
/Basic/07_logika_percabangan/logika_percabangan.py:
--------------------------------------------------------------------------------
1 | # membuat variabel dari cuaca
2 | # dan membuat value "cerah"
3 |
4 |
5 | cuaca = "cerah"
6 | # logika jika cuaca hujan
7 | if cuaca == "hujan":
8 | print("gunakan payung")
9 | # menggunakan fungsi elif
10 | # jika cuaca cerah
11 | elif cuaca == "cerah":
12 | print("tidak menggunakan payung")
13 | # menggunakan else jika kedua fungsi tidak terpenhi
14 | # if dan elif
15 | else:
16 | print("gunakan pakaian renang")
17 |
--------------------------------------------------------------------------------
/Basic/08_perulangan/for_loop.py:
--------------------------------------------------------------------------------
1 | # penggunaan for loop pada string
2 | nama = "zoelfekre"
3 | for tampil_nama in nama:
4 | print(tampil_nama)
5 |
6 | # penggnaan for loop pada list
7 | print("\ntampil nama siswa dalam list")
8 | nama_siswa = ["zoelfekre", "dwi", "dian"]
9 | for tampil_siswa in nama_siswa:
10 | print(tampil_siswa)
11 |
12 | # penggunaan for loop pada tuple
13 | print("\ntampil nama siswa dalam tuple")
14 | nama_siswa_tuple = ("zoelfekre", "dwi", "dian")
15 | for tampil_siswa_tuple in nama_siswa:
16 | print(tampil_siswa_tuple)
17 |
18 |
19 | # penggunaan break pada looping
20 | angka_saya = 0
21 | for angka_saya in range(0, 10):
22 | print(angka_saya)
23 | if angka_saya == 5:
24 | break
25 |
26 | # penggunaan continue pada looping
27 | angka_saya1 = 0
28 | for angka_saya1 in range(0, 10):
29 | if angka_saya1 == 5:
30 | continue
31 | print(angka_saya1)
32 |
--------------------------------------------------------------------------------
/Basic/08_perulangan/while_loop.py:
--------------------------------------------------------------------------------
1 | a = 1
2 |
3 | while a <= 5:
4 | print(a)
5 | a += 1
6 |
7 | b = 5
8 |
9 | while b >= 1:
10 | print(b)
11 | b -= 1
12 |
13 | c = 1
14 |
15 | while c <= 5:
16 | print(c)
17 | if c == 3:
18 | break
19 | c += 1
20 |
21 | d = 0
22 |
23 | while d < 5:
24 | d += 1
25 | if d == 3:
26 | continue
27 | print(d)
28 |
29 | e = 0
30 |
31 | while e <= 5:
32 | print(e)
33 | e += 1
34 | break
35 | else:
36 | print("Selamat, looping anda telah selesai !!")
37 |
--------------------------------------------------------------------------------
/Basic/09_fungsi/fungsi.py:
--------------------------------------------------------------------------------
1 | # section 1
2 |
3 |
4 | def hello():
5 | print("Hello Bellshade !")
6 |
7 |
8 | hello() # Hello!
9 |
10 | # section 2
11 |
12 |
13 | def selamat(nama):
14 | print("Hello " + str(nama) + " !")
15 |
16 |
17 | selamat("Bellshade") # Hello Bellshade !
18 |
19 | # section 3
20 |
21 |
22 | def triangle(alas, tinggi):
23 | hasil = (alas * tinggi) / 2
24 | print(hasil)
25 |
26 |
27 | triangle(2, 3)
28 |
29 | # section 4
30 |
31 |
32 | def segitiga(alas, tinggi):
33 | hasil = (alas * tinggi) / 2
34 | return hasil
35 |
36 |
37 | print(segitiga(2, 3))
38 |
39 | # section 5
40 |
41 |
42 | def salam(waktu="Pagi"):
43 | greet = "Selamat " + str(waktu)
44 | return greet
45 |
46 |
47 | print(salam("Siang")) # Selamat Siang
48 | print(salam("Malam")) # Selamat Malam
49 | print(salam("Sore")) # Selamat Sore
50 | print(salam()) # Selamat Pagi
51 |
52 | # section 6
53 |
54 |
55 | def unlimited(*args):
56 | for item in args:
57 | print(item)
58 |
59 |
60 | unlimited(1, 2, 3, 4)
61 | unlimited([1, 2], [3, 4])
62 |
63 | # section 7
64 |
65 |
66 | def unlimitedkeyword(**infinite):
67 | for key, value in infinite.items():
68 | print(f"index {key} memiliki nilai {value}")
69 |
70 |
71 | unlimitedkeyword(a=2, b=1, c=3)
72 | unlimitedkeyword(fname="Harry", lname="Potter")
73 |
--------------------------------------------------------------------------------
/Basic/09_fungsi/recursion_example.py:
--------------------------------------------------------------------------------
1 | def fibo(n):
2 | """
3 | Deret fibonacci merupakan salah satu permasalahan yang diselesaikan
4 | menggunakan pendekatan rekursi. Pada beberapa literatur,
5 | deret fibonacci dimulai dengan 0,1,1,2,... namun ada
6 | literatur yang menjelaskan bahwa deret ini dimulai dengan 1,1,2,... .
7 | Fungsi fibo(n) memiliki parameter n yang akan mengembalikan nilai
8 | fibonacci pada urutan ke-n. Fungsi ini menggunakan deret 1,1,2,...
9 | """
10 |
11 | # base case
12 | if n == 1 or n == 2:
13 | return 1
14 | # proses rekursi
15 | else:
16 | return fibo(n - 1) + fibo(n - 2)
17 |
18 |
19 | n = 3
20 | result = fibo(n)
21 | # result menghasilkan 2
22 | print(result)
23 |
--------------------------------------------------------------------------------
/Basic/10_list_tuple/list_python.py:
--------------------------------------------------------------------------------
1 | nama_hewan = ["gajah", "sapi", "kuda", "buaya"]
2 |
3 | # menampilkan isi list
4 | print(nama_hewan)
5 |
6 | # menampilkan isi list dengan index
7 | print(nama_hewan[0])
8 | print(nama_hewan[1])
9 |
10 | # mengganti satu index list
11 | nama_hewan[0] = "kucing"
12 | print(nama_hewan)
13 |
14 | # menghitung jumlah list
15 | print(len(nama_hewan))
16 |
17 | # campur beberapa tipe data dalam satu list
18 | list_saya = ["gajah", 12, True, "makan"]
19 | print(list_saya)
20 |
21 | # menggunakan konstruktor pada pembuatan list
22 | list_hewan1 = list(("kijang", "sapi", "kucing", "ayam"))
23 | print(list_hewan1)
24 |
25 | # menggunakan looping untuk menampilkan list
26 | for jenis_hewan in list_hewan1:
27 | print(jenis_hewan)
28 |
--------------------------------------------------------------------------------
/Basic/10_list_tuple/tuple_python.py:
--------------------------------------------------------------------------------
1 | jenis_mobil = ("ferrari", "bmw", "jaguar", "lamborghini")
2 |
3 | # menampilkan isi dari tuple
4 | print(jenis_mobil)
5 |
6 | # menampilkan isi dari tuple dengan index
7 | print(jenis_mobil[0])
8 |
9 | # menduplikasi item pada list
10 | jenis_mobil_terbaru = ("ferrari", "bmw", "jaguar", "bmw")
11 | print(jenis_mobil_terbaru)
12 |
13 | # menghitung panjang tuple
14 | print(len(jenis_mobil))
15 |
16 | # membuat satu item dengan tuple
17 | jenis_makanan = ("seblak",)
18 | print(jenis_makanan)
19 |
20 | # membuat tipe data tuple
21 | tuple_campur = ("makan", 12, True, 12.0)
22 | print(tuple_campur)
23 |
24 | # menampilkan tuple dengan perulangan for
25 | for mobil in jenis_mobil:
26 | print(mobil)
27 |
--------------------------------------------------------------------------------
/Basic/12_exception/exception.py:
--------------------------------------------------------------------------------
1 | # menangani eksepsi sederhana
2 | try:
3 | # jalankan kode berikut jika berhasil
4 | # bilangan yang dibagi dengan nol merupakan kesalahan
5 | # maka tangani di dalam 'except'
6 | hasil = 5 / 0 # type: ignore
7 | print("Hasil pembagian adalah =", hasil)
8 | except ZeroDivisionError:
9 | # tangani kesalahan di sini
10 | print("Bilangan tidak dapat dibagi dengan nol")
11 |
12 |
13 | # menangani lebih dari satu eksepsi
14 | # Cara 1. menggunakan lebih dari satu blok 'except'
15 | try:
16 | hasil = 3 / "1" # type: ignore
17 | print("Hasil pembagian adalah =", hasil)
18 | except ZeroDivisionError:
19 | print("Bilangan tidak dapat dibagi dengan nol")
20 | except TypeError:
21 | print("Bilangan harus bertipe numerik")
22 |
23 | # Cara 2. menuliskannya di dalam tuple
24 | try:
25 | hasil = 3 / "1" # type: ignore
26 | print("Hasil pembagian adalah =", hasil)
27 | except (ZeroDivisionError, TypeError):
28 | print("Terdapat kesalahan ketika melakukan pembagian")
29 |
30 |
31 | # mencetak pesan kesalahan/eksepsi bawaan python
32 | # gunakan keyword 'as' untuk memberi nama alias eksepsi
33 | try:
34 | hasil = 5 / 0 # type: ignore
35 | print("Hasil pembagian adalah =", hasil)
36 | except ZeroDivisionError as err:
37 | print(err) # division by zero
38 | except TypeError as err:
39 | print(err) # unsupported operand type(s) for /: 'int' and 'str'
40 |
41 | try:
42 | hasil = 3 / "1" # type: ignore
43 | print("Hasil pembagian adalah =", hasil)
44 | except (ZeroDivisionError, TypeError) as err:
45 | # cetak pesan error tergantung jenis error yang ditangkap
46 | print(err)
47 |
--------------------------------------------------------------------------------
/Basic/13_module/kalkulator.py:
--------------------------------------------------------------------------------
1 | def tambah(angka1, angka2):
2 | return angka1 + angka2
3 |
4 |
5 | def kurang(angka1, angka2):
6 | return angka1 - angka2
7 |
8 |
9 | def kali(angka1, angka2):
10 | return angka1 * angka2
11 |
12 |
13 | def bagi(angka1, angka2):
14 | return angka1 / angka2
15 |
--------------------------------------------------------------------------------
/Basic/13_module/perhitungan1.py:
--------------------------------------------------------------------------------
1 | import kalkulator
2 |
3 | print(kalkulator.tambah(3, 2))
4 | print(kalkulator.kurang(4, 2))
5 | print(kalkulator.kali(3, 6))
6 | print(kalkulator.bagi(10, 2))
7 |
--------------------------------------------------------------------------------
/Basic/13_module/perhitungan2.py:
--------------------------------------------------------------------------------
1 | from kalkulator import bagi, kali, kurang, tambah
2 |
3 | print(tambah(2, 3))
4 | print(kurang(2, 3))
5 | print(kali(2, 3))
6 | print(bagi(10, 2))
7 |
--------------------------------------------------------------------------------
/Basic/14_python_datetime/module_datetime.py:
--------------------------------------------------------------------------------
1 | import datetime
2 |
3 | # mengetahui waktu sekarang
4 | sekarang = datetime.datetime.now()
5 | print(sekarang)
6 |
7 | # mengetahui tahun
8 | print(sekarang.year)
9 |
10 | # mengetahui bulan
11 | print(sekarang.month)
12 |
13 | # mengetahui hari
14 | print(sekarang.day)
15 |
16 | # format tanggal DD-MM-YYYY
17 | print(sekarang.strftime("%d-%m-%Y"))
18 |
19 | # mendefinisikan tanggal dan waktu
20 | hari_kemerdekaan = datetime.date(1945, 8, 17)
21 | print(hari_kemerdekaan)
22 |
--------------------------------------------------------------------------------
/Basic/14_python_datetime/perhitungan_umur.py:
--------------------------------------------------------------------------------
1 | import datetime
2 |
3 | # tentukan tanggal lahir, misalkan 29 Des 1997
4 | tanggal_lahir = datetime.datetime(1997, 12, 29)
5 |
6 | # ambil waktu sekarang
7 | tanggal_sekarang = datetime.datetime.now()
8 |
9 | # hitung umurnya
10 | umur_sekarang = tanggal_sekarang - tanggal_lahir
11 | print(umur_sekarang)
12 |
13 | # ambil jumlah hari
14 | jumlah_hari = umur_sekarang.days
15 |
16 | # hitung umur dalam tahun
17 | umur_tahun = jumlah_hari // 365
18 |
19 | # hitung sisa hari
20 | sisa_hari = jumlah_hari % 365
21 | print("Umur saya adalah %d tahun %d hari" % (umur_tahun, sisa_hari))
22 |
--------------------------------------------------------------------------------
/Basic/15_python_math/math_eksponen_logaritma.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | print(math.sqrt(25))
4 | print(math.pow(5, 3))
5 | print(math.log10(1000))
6 | print(math.log(125, 5))
7 |
--------------------------------------------------------------------------------
/Basic/15_python_math/math_konstanta.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | print(math.pi)
4 | print(math.e)
5 | print(math.tau)
6 | print(math.inf)
7 | print(-math.inf)
8 | print(math.nan)
9 |
--------------------------------------------------------------------------------
/Basic/15_python_math/math_konversi_sudut.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | print(math.degrees(2 * math.pi))
4 | print(math.radians(90))
5 |
--------------------------------------------------------------------------------
/Basic/15_python_math/math_pembulatan.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | print(math.floor(14.8))
4 | print(math.ceil(14.3))
5 |
--------------------------------------------------------------------------------
/Basic/15_python_math/math_trigonometri.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | sudut_30 = math.radians(30)
4 | print(math.sin(sudut_30))
5 | print(math.cos(sudut_30))
6 | print(math.tan(sudut_30))
7 |
--------------------------------------------------------------------------------
/Basic/16_class/class.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod, abstractproperty
2 |
3 |
4 | # Kelas abstrak hewan, tidak dapat di-inisialisasi dan hanya berupa instance
5 | class Hewan(ABC):
6 | # Properti abstrak
7 | @abstractproperty
8 | def suara(self):
9 | pass
10 |
11 | # Metode abstrak
12 | @abstractmethod
13 | def bersuara(self):
14 | pass
15 |
16 |
17 | # Menggunakan pewarisan dari kelas Hewan
18 | class Kucing(Hewan):
19 | # Mengimplementasikan properti suara
20 | @property
21 | def suara(self):
22 | return "MIAWW MIAWW"
23 |
24 | # Mengimplementasikan atribut bersuara
25 | def bersuara(self):
26 | print(self.suara)
27 |
28 |
29 | # contoh membuat objek
30 | tomcat = Kucing()
31 |
32 | # mengakses metode bersuara
33 | tomcat.bersuara()
34 | # output: "MIAWW MIAWW"
35 |
--------------------------------------------------------------------------------
/Basic/16_class/const_desct.py:
--------------------------------------------------------------------------------
1 | class Warung:
2 | def __init__(self, owner, alamat):
3 | self.owner = owner
4 | self.alamat = alamat
5 | self.menu = []
6 |
7 | def __del__(self):
8 | print("Warung dihapus, data terakhir warung:", self.data())
9 |
10 | def tambah_menu(self, makanan):
11 | """
12 | metode ini berfungsi untuk menambahkan data
13 | ke atribut menu_makanan
14 | makanan = string
15 | """
16 | self.menu.append(makanan)
17 |
18 | def data(self):
19 | """
20 | metode ini berfungsi untuk mengembalikan data
21 | seluruh atribut warung dalam bentuk dict.
22 | """
23 | return {"alamat warung": self.alamat, "owner": self.owner, "menu": self.menu}
24 |
25 |
26 | # membuat objek dan meng-inisialisasi-nya
27 | kedai_atuk = Warung(owner="Atuk Daka", alamat="Jl. Apel No. 23")
28 |
29 | # mengakses metode tambah_menu untuk menambahkan menu
30 | kedai_atuk.tambah_menu("kopi susu")
31 | kedai_atuk.tambah_menu("roti bakar")
32 |
33 | # mengakses metode data untuk melihat data warung
34 | data_kedai_atuk = kedai_atuk.data()
35 | print(data_kedai_atuk)
36 | # output: {'alamat warung': 'Jl. Apel No. 23',
37 | # 'owner': 'Atuk Daka',
38 | # 'menu': ['kopi susu', 'roti bakar']}
39 |
40 | # menghapus objek warung
41 | del kedai_atuk
42 | # output: Warung dihapus, data terakhir warung:
43 | # {'alamat warung': 'Jl. Apel No. 23',
44 | # 'owner': 'Atuk Daka',
45 | # 'menu': ['kopi susu', 'roti bakar']}
46 |
--------------------------------------------------------------------------------
/Basic/16_class/dunder_method.py:
--------------------------------------------------------------------------------
1 | class Hewan:
2 | def __init__(self, nama_hewan, suara):
3 | self.nama_hewan = nama_hewan
4 | self.suara = suara
5 |
6 | def __repr__(self):
7 | return f"kucing {self.nama_hewan} bersuara {self.suara}"
8 |
9 |
10 | if __name__ == "__main__":
11 | hewan = Hewan("sapi", "Mooo")
12 | print(f" {hewan.nama_hewan} bersuara :{hewan.suara}")
13 |
--------------------------------------------------------------------------------
/Basic/16_class/methods.py:
--------------------------------------------------------------------------------
1 | class SegiEmpat:
2 | def __init__(self, panjang, lebar):
3 | self.panjang = panjang
4 | self.lebar = lebar
5 |
6 | def hitung_luas(self):
7 | """
8 | metode ini akan mengembalikan luas bangun menggunakan
9 | hasil perkalian panjang dan lebar
10 | """
11 | return self.panjang * self.lebar
12 |
13 | @classmethod
14 | def kotak(cls, sisi):
15 | """
16 | metode ini akan mengembalikan suatu objek kotak
17 | """
18 | return cls(sisi, sisi)
19 |
20 | @staticmethod
21 | def jenis_bangun(panjang, lebar):
22 | """
23 | metode ini akan mengembalikan jenis segiempat, apakah
24 | persegi atau persegipanjang
25 | """
26 | return "persegi" if panjang == lebar else "persegi panjang"
27 |
28 |
29 | print(SegiEmpat.jenis_bangun(10, 5))
30 | # output: persegi panjang
31 |
32 | persegi_panjang = SegiEmpat(10, 5)
33 | print(persegi_panjang.hitung_luas())
34 | # output: 50
35 |
36 | print(SegiEmpat.jenis_bangun(3, 3))
37 | # output: persegi
38 |
39 | persegi = SegiEmpat.kotak(3)
40 | print(persegi.hitung_luas())
41 | # output: 9
42 |
--------------------------------------------------------------------------------
/Basic/17_inheritance/inheritance_python.py:
--------------------------------------------------------------------------------
1 | # kelas induk
2 | class Siswa:
3 | # __init__ sebagai constructor
4 | def __init__(self, nama, kelas, jenis_kelamin):
5 | self.nama = nama
6 | self.kelas = kelas
7 | self.jenis_kelamin = jenis_kelamin
8 |
9 |
10 | # child class atau kelas non induk
11 | # membuat kategori siswa berdasarkan dari
12 | # kelas induk
13 | class KategoriSiswa(Siswa):
14 | def __init__(self):
15 | # memanggil constructor dari kelas induk
16 | Siswa.__init__(self, "arfy", 12, "laki-laki")
17 |
18 | # mmenampilkan hasil dari kelas induk
19 | def tampilkan(self):
20 | print(self.nama)
21 | print(self.kelas)
22 | print(self.jenis_kelamin)
23 |
24 |
25 | # deklarasi objek
26 | data = KategoriSiswa()
27 | # memanggil objek
28 | data.tampilkan()
29 |
--------------------------------------------------------------------------------
/Basic/18_akses_modifikasi/01_public/README.md:
--------------------------------------------------------------------------------
1 | # public modifier
2 |
3 | Anggota kelas yang dideklarasikan publik mudah diakses dari bagian mana pun dari program. Semua anggota data dan fungsi anggota kelas bersifat publik secara default.
4 |
5 | ```python
6 | class NamaSaya:
7 | def __init__(self, nama, umur):
8 | self.nama_saya = name
9 | self.umur_saya = umur
10 |
11 | def tampil_nama(self):
12 | print(f"Apa kabar {self.nama_saya}")
13 |
14 | objek_kelas = NamaSaya("yoga", 31)
15 | objek_kelas.tampil_nama()
16 | print("Umur saya adalah ", objek_kelas.umur_saya)
17 | ```
18 |
19 | Dalam program di atas, ``nama_saya`` dan ``umur_saya`` adalah anggota data publik dan metode ``tampil_nama()`` adalah fungsi anggota publik dari kelas ``NamaSaya``. Data anggota kelas ``NamaSaya`` ini dapat diakses dari mana saja dalam program.
20 |
21 | [Materi Selanjutnya](../02_private)
--------------------------------------------------------------------------------
/Basic/18_akses_modifikasi/01_public/public.py:
--------------------------------------------------------------------------------
1 | class NamaSaya:
2 | def __init__(self, nama, umur):
3 | self.nama_saya = nama
4 | self.umur_saya = umur
5 |
6 | def tampil_nama(self):
7 | print(f"Apa kabar {self.nama_saya}")
8 |
9 |
10 | objek_kelas = NamaSaya("yoga", 31)
11 | objek_kelas.tampil_nama()
12 | print("Umur saya adalah ", objek_kelas.umur_saya)
13 |
--------------------------------------------------------------------------------
/Basic/18_akses_modifikasi/02_private/private.py:
--------------------------------------------------------------------------------
1 | class PekerjaTambang:
2 | # private variabel
3 | __nama = None
4 | __jabatan = None
5 |
6 | # konstruktor
7 | def __init__(self, nama, jabatan):
8 | self.__nama = nama
9 | self.__jabatan = jabatan
10 |
11 | # membuat fungsi yang bersifat private
12 |
13 | def __menampilkan(self):
14 | # memangakses private objek
15 | print("Nama: ", self.__nama)
16 | print("Jabatan: ", self.__jabatan)
17 |
18 | # fungsi yang bersifat publik
19 |
20 | def menampilkan_data(self):
21 | self.__menampilkan()
22 |
23 |
24 | # membuat objek dan menampilkannya
25 | pekerja1 = PekerjaTambang("James", "Research")
26 |
27 | # menampilkan objek yang dimana terdapat fungsi private
28 | pekerja1.menampilkan_data()
29 |
--------------------------------------------------------------------------------
/Basic/18_akses_modifikasi/03_protected/protected.py:
--------------------------------------------------------------------------------
1 | class PekerjaTambang:
2 | # protected variabel
3 | _nama = None
4 | _jabatan = None
5 |
6 | # membuat konstruktor
7 | def __init__(self, nama, jabatan):
8 | self._nama = nama
9 | self._jabatan = jabatan
10 |
11 | # membuat fungsi protected
12 | def _menampilkan(self):
13 | print("jabatan: ", self._jabatan)
14 |
15 |
16 | # kelas turunan dari pekerja tambang
17 | class Pekerja(PekerjaTambang):
18 | # membuat konstruktor
19 | def __init__(self, nama, jabatan):
20 | PekerjaTambang.__init__(self, nama, jabatan)
21 |
22 | # membuat fungsi publik
23 | def menampilkan(self):
24 | print("nama: ", self._nama)
25 | # menampilkan fungsi protected dari kelas Pekerja Tambang
26 | self._menampilkan()
27 |
28 |
29 | # membuat variabel yang membuat objek dari pekerja
30 | pekerja1 = Pekerja("james", "driller")
31 |
32 | # menampikan
33 | pekerja1.menampilkan()
34 |
--------------------------------------------------------------------------------
/Basic/19_iterator/README.md:
--------------------------------------------------------------------------------
1 | # Iterator
2 |
3 | Iterator adalah objek yang berisi sesuatu yang bisa dihitung atau *iterable*.
4 |
5 | Objek *iterable* adalah String, List, Tuple, Set, Dictionary.
6 |
7 | contoh dari penggunaan iterator:
8 | ```py
9 | nama_maintainer = ("majed", "permen", "kelvin", "hen")
10 | show = iter(nama_maintainer)
11 | print(next(show))
12 | print(next(show))
13 | print(next(show))
14 | print(next(show))
15 | ```
16 |
17 | menggunakan `__iter__()`
18 | ```py
19 | class AngkaSaya:
20 | def __iter__(self):
21 | self.angka = 1
22 | return self
23 |
24 | def __next__(self):
25 | nomor = self.angka
26 | self.angka += 1
27 | return nomor
28 |
29 | kelas_angka = AngkaSaya()
30 | test_iter = iter(kelas_angka)
31 |
32 | print(next(test_iter))
33 | print(next(test_iter))
34 | print(next(test_iter))
35 | ```
36 |
37 | untuk lebih jelasnya kamu bisa lihat [disini](iterator.py)
38 |
39 | [Materi Selanjutnya](../20_lambda)
--------------------------------------------------------------------------------
/Basic/19_iterator/iterator.py:
--------------------------------------------------------------------------------
1 | fruits = ("apple", "banana", "cherry")
2 |
3 | # fungsi iter() disini digunakan untuk membuat iterator
4 | fruits_iter = iter(fruits)
5 |
6 | # mengecek tipe data fruits_iter
7 | print("Tipe data dari fruits_iter:", fruits_iter)
8 |
9 | # Untuk mengakses isi dari iterator kita menggunakan fungsi next
10 | print(next(fruits_iter))
11 | print(next(fruits_iter))
12 | print(next(fruits_iter))
13 |
14 | # Kita juga dapat menggunakan for loop untuk mengulang suatu objek
15 |
16 | print("\nMenggunakan For Loop:")
17 |
18 | # hasil kode ini sama dengan yang diatas
19 | for fruit in fruits:
20 | print(fruit)
21 |
22 |
23 | # iterator juga bisa kita kustomisasi pada class
24 | class MyNumbers:
25 | # dunder method iter
26 | def __iter__(self):
27 | self.fruits = ["apple", "banana", "cherry"]
28 | self.counter = 0
29 | return self
30 |
31 | # dunder method next
32 | def __next__(self):
33 | if self.counter < len(self.fruits):
34 | x = self.fruits[self.counter]
35 | self.counter += 1
36 | return x
37 | else:
38 | # StopIteration digunakan untuk menghentikan iterator
39 | raise StopIteration
40 |
41 |
42 | myclass = MyNumbers()
43 | myiter = iter(myclass)
44 |
45 | print("\nMengulang menggunakan Class:")
46 | print(next(myiter))
47 | print(next(myiter))
48 | print(next(myiter))
49 |
--------------------------------------------------------------------------------
/Basic/20_lambda/README.md:
--------------------------------------------------------------------------------
1 | # Lambda function
2 |
3 | Lambda function atau dikenal juga dengan anonymous function
4 | adalah sebuah function yang bisa menerima multiple arguments
5 | tetapi hanya bisa melakukan satu ekspresi atau satu eksekusi.
6 |
7 | Pada contoh berikut, kita melakukan perhitungan luas persegi
8 | dengan satu argument yaitu sisi (s) dan satu ekspresi sisi*sisi.
9 |
10 | ```python
11 | luas_persegi = lambda s: s ** 2
12 | print(luas_persegi(4))
13 | ```
14 |
15 | Contoh dari lambda function yang bisa menerima multiple argument
16 | yaitu lambda function luas segitiga
17 |
18 | ```python
19 | luas_segitiga = lambda a, t: (a * t) / 2
20 | print(luas_segitiga(2, 3))
21 | ```
22 |
23 | Lambda sendiri bisa menerima argumen secara tak terbatas
24 | seperti pada contoh:
25 |
26 | ```python
27 | infinite = lambda *input: sum(input)
28 | print(infinite(1, 2, 3))
29 | print(infinite(1, 2, 3, 4))
30 | ```
31 |
32 | Bisa juga menerima argumen dengan keyword
33 | ```python
34 | key_inf = lambda **kwargs: sum(kwargs.values())
35 | print(key_inf(satu=1, dua=2, tiga=3)) # 6
36 | print(key_inf(seven=7, eight=8, nine=9, ten=10)) # 34
37 | ```
38 |
39 | Contoh penerapannya bisa kita lihat pada fungsi ```filter()```
40 | yaitu
41 | ```python
42 | li = [i for i in range(10)]
43 | beyond_five = list(filter(lambda x: (x > 5), li))
44 | print(beyond_five)
45 | ```
46 |
47 | [Materi Selanjutnya](../21_regex)
--------------------------------------------------------------------------------
/Basic/20_lambda/lambda.py:
--------------------------------------------------------------------------------
1 | # flake8: noqa
2 |
3 | # lambda function atau dikenal juga dengan anonymous function
4 | # adalah function yang bisa menerima multiple arguments
5 | # tapi hanya bisa melakukan 1 expression
6 |
7 | # seperti contoh pada lambda luas_persegi dibawah
8 | # hanya input s, dan satu expresi yaitu, s * s
9 |
10 | luas_persegi = lambda s: s**2
11 | print(luas_persegi(4)) # 16
12 |
13 | # bukti dari lambda bisa menerima multiple argument adalah
14 | # pada luas_segitiga, argument nya itu a dan t
15 |
16 | luas_segitiga = lambda a, t: (a * t) / 2
17 | print(luas_segitiga(2, 3)) # 3.0
18 |
19 | # disamping itu, lambda function juga bisa menerima
20 | # unlimited argument seperti contoh dibawah
21 |
22 | infinite = lambda *input: sum(input)
23 | print(infinite(1, 2, 3)) # 6
24 | print(infinite(1, 2, 3, 4)) # 10
25 |
26 | # dan bisa juga unlimited argument dengan keyword
27 |
28 | key_inf = lambda **kwargs: sum(kwargs.values())
29 | print(key_inf(satu=1, dua=2, tiga=3)) # 6
30 | print(key_inf(seven=7, eight=8, nine=9, ten=10)) # 34
31 |
32 | # contoh penerapan dari lambda function yaitu
33 | # melakukan proses filterisasi dimana yang ditampilkan hanya
34 | # bilangan yang lebih besar dari 5, memakai filter()
35 |
36 | li = [i for i in range(10)]
37 | beyond_five = list(filter(lambda x: (x > 5), li))
38 | print(beyond_five) # [6,7,8,9]
39 |
--------------------------------------------------------------------------------
/Basic/21_regex/regex_code.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | text = "@robot9 "
4 |
5 | print(re.findall(r"\d", text))
6 | print(re.findall(r"\w", text))
7 | print(re.findall(r"\s", text))
8 |
9 | angka = "1234"
10 |
11 | text = "Budi suka makan buah apel"
12 |
13 | print(re.findall(r"\d+", angka))
14 | print(re.findall(r"\w+", text))
15 |
16 | text = "Poseidon dan Zeus"
17 |
18 | print(re.findall(r"[aiueo]", text))
19 |
20 | text = "Air, api, tanah, udara"
21 |
22 | print(re.findall(r"Air|Water", text))
23 |
--------------------------------------------------------------------------------
/Basic/24_casting_tipe_data/casting_tipe_data.py:
--------------------------------------------------------------------------------
1 | # type casting adalah metode merubah tipe data dari
2 | # suatu variable atau value yang sudah dideklarasikan
3 | # contoh dibawah ini
4 | # kita bisa melihat dengan menggunakan fungsi "type()"
5 |
6 |
7 | # merubah ke bilangan koma ke bilangan bulat
8 | angka = int(30.12)
9 | print(type(angka))
10 |
11 | # merubah ke bilangan bulat ke bilangan koma
12 | angka_float = float(20)
13 | print(type(angka_float))
14 |
15 | # merubah dari bilangan bulat ke string
16 | angka_string = str(30)
17 | print(type(angka_string))
18 |
19 | # contoh lain (tipe data float)
20 | # float(1)
21 | # float("2")
22 | # float(3.14)
23 |
24 |
25 | # contoh lain (tipedata string)
26 | # str(1)
27 | # str("2")
28 | # str(3.14)
29 |
--------------------------------------------------------------------------------
/Basic/25_list_and_dict_comprehension/dict_comprehension.py:
--------------------------------------------------------------------------------
1 | # Dictionary comprehension adalah
2 | # Sebuah metode atau cara untuk membuat dictionary menggunakan for loop
3 |
4 | # Syntax Dictionary Comprehension
5 | # {key : value for vars in iterable}
6 |
7 | # Kelebihan menggunakan Dictionary Comprehension adalah
8 | # mampu menulis koding dengan elegan
9 |
10 | # Membuat Dictionary
11 | # contoh bisa dilakukan dengan membuat terlebih dahulu
12 | # dengan membuat variabel dengan fungsi ``dict()``
13 | # angka = dict()
14 |
15 | # Basic Dict Comprehension
16 | angka = {nilai: nilai * 2 for nilai in range(1, 6)}
17 | print("Angka : ", angka)
18 | # Output = Angka : {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
19 |
20 | # Contoh lainnya pada Dict Comprehension
21 | pangkat = {key * 2: value**2 for (key, value) in angka.items()}
22 | print("Pangkat Dua: ", pangkat)
23 | # Output = Pangkat Dua: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
24 |
25 | # Implementasi Dict Comprehension Dengan If Else
26 | ten_nums = {value: value * 2 for value in range(1, 11)}
27 | genap_only = {key: value for (key, value) in ten_nums.items() if key % 2 == 0}
28 | print("Genap Only : ", genap_only)
29 | # Output = Genap Only : {2: 4, 4: 8, 6: 12, 8: 16, 10: 20}
30 |
31 | # Implementasi Dict Comprehension Dengan If Else
32 | age_name = {"Ronaldo": 37, "Messi": 34, "Greenwood": 20, "Sancho": 21}
33 | status_umur = {
34 | nama: ("Tua" if umur > 30 else "Muda") for (nama, umur) in age_name.items()
35 | }
36 | print(status_umur)
37 | # Output = {'Ronaldo': 'Tua', 'Messi': 'Tua', 'Greenwood': 'Muda', 'Sancho': 'Muda'}
38 |
--------------------------------------------------------------------------------
/Basic/26_dekorator/dekorator.py:
--------------------------------------------------------------------------------
1 | def dekorator_huruf_kecil(kata):
2 | # membuat fungsi nested yang kita sebut 'wrapper'
3 | def wrapper():
4 | # memanggil yang diteruskan dekorator_huruf_kecil
5 | # dan kemudian dimasukkan ke dalam variabel
6 | # 'kata_message'
7 | kata_message = kata()
8 | # menggunakan fungsi 'lower()' untuk membuat
9 | # variabel dari kata_message menjadi kecil
10 | # dan kemudian ditugaskan dalam variabel
11 | # buat_kata_kecil
12 | buat_kata_kecil = kata_message.lower()
13 | # mengembalikan nilai dari 'wrapper'
14 | return buat_kata_kecil
15 |
16 | # mengembalikan fungsi dari wrapper
17 | return wrapper
18 |
19 |
20 | def kata_besar():
21 | return "BELLSHADE"
22 |
23 |
24 | dekorator = dekorator_huruf_kecil(kata_besar)
25 |
26 | print(dekorator() + "\n")
27 |
28 |
29 | @dekorator_huruf_kecil
30 | def kata_besar_():
31 | return "BELLSHADE"
32 |
33 |
34 | print(kata_besar_())
35 |
--------------------------------------------------------------------------------
/Basic/Introduction.py:
--------------------------------------------------------------------------------
1 | # Pada bahasa pemrograman Python, kita cukup
2 | # memakai perintah print untuk mendapatkan
3 | # output dari apa yang kita inginkan
4 | # Misalnya, output yang diinginkan adalah Turki,
5 | # maka kita mengetikkan Turki, seperti dibawah ini
6 | print("Negara Turki")
7 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/Dockerfile
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Bell shade community
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 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Use this section to tell people about which versions of your project are
6 | currently being supported with security updates.
7 |
8 | | Version | Supported |
9 | | ------- | ------------------ |
10 | | 5.1.x | :white_check_mark: |
11 | | 5.0.x | :x: |
12 | | 4.0.x | :white_check_mark: |
13 | | < 4.0 | :x: |
14 |
15 | ## Reporting a Vulnerability
16 |
17 | Use this section to tell people how to report a vulnerability.
18 |
19 | Tell them where to go, how often they can expect to get an update on a
20 | reported vulnerability, what to expect if the vulnerability is accepted or
21 | declined, etc.
22 |
--------------------------------------------------------------------------------
/algorithm/arithmetic_analysis/newton_forward_interpolation.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | # kalkulasi nilai u
4 |
5 |
6 | def ucal(u: float, p: int) -> float:
7 | """
8 | >>> ucal(1, 2)
9 | 0
10 | >>> ucal(1.1, 2)
11 | 0.11000000000000011
12 | >>> ucal(1.2, 2)
13 | 0.23999999999999994
14 | """
15 | temp = u
16 | for i in range(1, p):
17 | temp = temp * (u - i)
18 | return temp
19 |
20 |
21 | def setcal() -> None:
22 | n = int(input("masukkan jumlah nilai: "))
23 | y: list[list[float]] = []
24 | for i in range(n):
25 | y.append([])
26 | for i in range(n):
27 | for j in range(n):
28 | y[i].append(j)
29 | y[i][j] = 0
30 |
31 | print("masukkan nilai parameter dalam list: ")
32 | x = list(map(int, input().split()))
33 |
34 | print("masukkan nilai parameter yang sesuai: ")
35 | for i in range(n):
36 | y[i][0] = float(input())
37 |
38 | value = int(input("masukkan nilai untuk diinterpolasi :"))
39 | u = (value - x[0]) / (x[1] - x[0])
40 |
41 | for i in range(1, n):
42 | for j in range(n - i):
43 | y[j][i] = y[j + 1][i - 1] - y[j][i - 1]
44 |
45 | summ = y[0][0]
46 | for i in range(1, n):
47 | summ += (ucal(u, i) * y[0][i]) / math.factorial(i)
48 |
49 | print(f"Nilai di {value} adalah {summ}")
50 |
51 |
52 | if __name__ == "__main__":
53 | import doctest
54 |
55 | doctest.testmod()
56 |
--------------------------------------------------------------------------------
/algorithm/arithmetic_analysis/newton_raphson.py:
--------------------------------------------------------------------------------
1 | # Metode Newton-Raphson adalah metode pencarian akar suatu fungsi
2 | # f(x) dengan pendekatan satu titik,
3 | # dimana fungsi f(x) mempunyai turunan.
4 | # Metode ini dianggap lebih mudah dari Metode Bagi-Dua (Bisection Method),
5 | # karena metode ini menggunakan pendekatan satu titik sebagai titik awal.
6 |
7 | from __future__ import annotations
8 |
9 | from decimal import Decimal
10 | from math import * # noqa: F401, F403
11 |
12 | from sympy import diff
13 |
14 |
15 | def newton_raphson(func: str, a: float | Decimal, pres: float = 10**-10) -> float:
16 | """
17 | Menemukan akar dari titik 'a' dan seterusnya dengan metode Newton-Raphson
18 | >>> newton_raphson("sin(x)", 2)
19 | 3.1415926536808043
20 | >>> newton_raphson("x**2 - 5*x +2", 0.4)
21 | 0.4384471871911695
22 | >>> newton_raphson("x**2 - 5", 0.1)
23 | 2.23606797749979
24 | >>> newton_raphson("log(x)- 1", 2)
25 | 2.718281828458938
26 | """
27 | x = a
28 | while True:
29 | x = Decimal(x) - (Decimal(eval(func)) / Decimal(eval(str(diff(func)))))
30 | if abs(eval(func)) < pres:
31 | return float(x)
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/algorithm/arithmetic_analysis/secant_method.py:
--------------------------------------------------------------------------------
1 | # Pada Metode Newton-Raphson memerlukan syarat wajib yaitu
2 | # fungsi f(x) harus memiliki turunan f'(x).
3 | # Sehingga syarat wajib ini dianggap sulit,
4 | # karena tidak semua fungsi bisa dengan mudah mencari turunannya.
5 | # Oleh karena itu muncul ide dari yaitu mencari persamaan yang ekuivalen
6 | # dengan rumus turunan fungsi.
7 | # Ide ini lebih dikenal dengan nama Metode Secant.
8 |
9 | from math import exp
10 |
11 |
12 | def f(x: float) -> float:
13 | """
14 | >>> f(5)
15 | 39.98652410600183
16 | """
17 | return 8 * x - 2 * exp(-x)
18 |
19 |
20 | def secant_method(lower_bound: float, upper_bound: float, ulang: int) -> float:
21 | """
22 | >>> secant_method(1, 3, 2)
23 | 0.2139409276214589
24 | """
25 | x0 = lower_bound
26 | x1 = upper_bound
27 | for _ in range(0, ulang):
28 | x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
29 | return x1
30 |
31 |
32 | if __name__ == "__main__":
33 | import doctest
34 |
35 | doctest.testmod()
36 |
--------------------------------------------------------------------------------
/algorithm/backtracking/all_combinations.py:
--------------------------------------------------------------------------------
1 | # dalam soal contoh ini kita ingin menentukan semua
2 | # kemungkinan kombinasi dari k
3 | # angka dari 1 ... n. kita menggunakan algoritma
4 | # backtracking untuk memcahkan masalah
5 |
6 | from __future__ import annotations
7 |
8 |
9 | def generate_all_combinations(n: int, k: int) -> list[list[int]]:
10 | """
11 | >>> generate_all_combinations(n=4, k=2)
12 | [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
13 | """
14 | result: list[list[int]] = []
15 | create_all_state(1, n, k, [], result)
16 | return result
17 |
18 |
19 | def create_all_state(
20 | increment: int,
21 | total_number: int,
22 | level: int,
23 | current_list: list[int],
24 | total_list: list[list[int]],
25 | ) -> None:
26 | if level == 0:
27 | total_list.append(current_list[:])
28 | return
29 |
30 | for i in range(increment, total_number - level + 2):
31 | current_list.append(i)
32 | create_all_state(i + 1, total_number, level - 1, current_list, total_list)
33 | current_list.pop()
34 |
35 |
36 | def print_all_state(total_list: list[list[int]]) -> None:
37 | for i in total_list:
38 | print(*i)
39 |
40 |
41 | if __name__ == "__name__":
42 | import doctest
43 |
44 | doctest.testmod()
45 | n = 4
46 | k = 2
47 | total_list = generate_all_combinations(n, k)
48 | print_all_state(total_list)
49 |
--------------------------------------------------------------------------------
/algorithm/backtracking/combination.py:
--------------------------------------------------------------------------------
1 | # Dalam masalah ini, kami ingin menentukan semua kemungkinan kombinasi k
2 | # nomor dari 1 ... n. Kami menggunakan backtracking untuk memecahkan masalah ini.
3 | # Kompleksitas waktu: O(C(n,k)) yaitu O(n pilih k) = O((n!/(k! * (n - k)!)))
4 |
5 |
6 | def generate_combination(n: int, k: int) -> list[list[int]]:
7 | """
8 | >>> generate_combination(n=4, k=2)
9 | [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
10 | """
11 |
12 | result: list[list[int]] = []
13 |
14 | create_state(1, n, k, [], result)
15 |
16 | return result
17 |
18 |
19 | def create_state(
20 | increment: int,
21 | total_number: int,
22 | level: int,
23 | current_list: list[int],
24 | total_list: list[list[int]],
25 | ) -> None:
26 | if level == 0:
27 | total_list.append(current_list[:])
28 | return
29 | for i in range(increment, total_number - level + 2):
30 | current_list.append(i)
31 | create_state(i + 1, total_number, level - 1, current_list, total_list)
32 | current_list.pop()
33 |
34 |
35 | def print_state(total_list: list[list[int]]) -> None:
36 | for i in total_list:
37 | print(*i)
38 |
39 |
40 | if __name__ == "__main__":
41 | import doctest
42 |
43 | # n = 4
44 | # k = 2
45 | # total_list = generate_combination(n, k)
46 | # print_state(total_list)
47 | doctest.testmod()
48 |
--------------------------------------------------------------------------------
/algorithm/backtracking/permutation.py:
--------------------------------------------------------------------------------
1 | # Dalam masalah ini, kami ingin menentukan semua kemungkinan permutasi
2 | # dari urutan yang diberikan.
3 | # Kami menggunakan backtracking untuk memecahkan masalah ini.
4 | # Kompleksitas waktu: O(n! * n),
5 | # dimana n menyatakan panjang barisan yang diberikan.
6 | from __future__ import annotations
7 |
8 |
9 | def generate_all_permutaions(sequence: list[int | str]) -> None:
10 | create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
11 |
12 |
13 | def create_state_space_tree(
14 | sequence: list[int | str],
15 | current_sequence: list[int | str],
16 | index: int,
17 | index_used: list[int],
18 | ) -> None:
19 | """
20 | Membuat pohon ruang untuk iterasi melalui setiap cabang menggunakan DFS.
21 | Kita tahu bahwa setiap negara memiliki persis len (urutan) - anak-anak indeks.
22 | Ini berakhir ketika mencapai akhir urutan yang diberikan.
23 | """
24 | if index == len(sequence):
25 | print(current_sequence)
26 | return
27 |
28 | for i in range(len(sequence)):
29 | if not index_used[i]:
30 | current_sequence.append(sequence[i])
31 | index_used[i] = True
32 | create_state_space_tree(sequence, current_sequence, index + 1, index_used)
33 | current_sequence.pop()
34 | index_used[i] = False
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | # sequence: List[Union[int, str]] = [3, 1, 2,4]
41 | # generate_permutation(sequence)
42 | doctest.testmod()
43 |
--------------------------------------------------------------------------------
/algorithm/backtracking/subsequence.py:
--------------------------------------------------------------------------------
1 | # Dalam masalah ini, kami ingin menentukan semua kemungkinan turunan
2 | # dari urutan yang diberikan.
3 | # Kami menggunakan backtracking untuk memecahkan masalah ini.
4 | # Kompleksitas waktu: O(2^n),
5 | # dimana n menyatakan panjang barisan yang diberikan.
6 | from __future__ import annotations
7 |
8 | from typing import Any
9 |
10 |
11 | def generate_all_subsequences(sequence: list[Any]) -> None:
12 | create_state_space_tree(sequence, [], 0)
13 |
14 |
15 | def create_state_space_tree(
16 | sequence: list[Any], current_subsequence: list[Any], index: int
17 | ) -> None:
18 | """
19 | membuat state_space_tree untuk beralih melalui setiap
20 | cabang menggunakan DFS.
21 | Kita tahu bahwa setiap state bagian memiliki tepat dua anak.
22 | Ini berakhir ketika mencapai
23 | akhir dari urutan yang diberikan.
24 | """
25 |
26 | if index == len(sequence):
27 | print(current_subsequence)
28 | return
29 |
30 | create_state_space_tree(sequence, current_subsequence, index + 1)
31 | current_subsequence.append(sequence[index])
32 | create_state_space_tree(sequence, current_subsequence, index + 1)
33 | current_subsequence.pop()
34 |
35 |
36 | if __name__ == "__main__":
37 | import doctest
38 |
39 | seq: list[Any] = [3, 1, 2, 4]
40 | generate_all_subsequences(seq)
41 | seq.clear()
42 | seq.extend(["A", "B", "C"])
43 | generate_all_subsequences(seq)
44 | doctest.testmod()
45 |
--------------------------------------------------------------------------------
/algorithm/boolean_algebra/README.md:
--------------------------------------------------------------------------------
1 | ## Boolean Algebra
2 |
3 | Materi Selanjutnya: [Divide and Conquer](../divide_and_conquer)
--------------------------------------------------------------------------------
/algorithm/divide_and_conquer/README.md:
--------------------------------------------------------------------------------
1 | ## Divide and Conquer
2 |
3 | Materi Selanjutnya: [Fuzzy Logic](../fuzzy_logic)
--------------------------------------------------------------------------------
/algorithm/divide_and_conquer/kth_order_statistic.py:
--------------------------------------------------------------------------------
1 | # Temukan elemen terkecil ke-k dalam waktu
2 | # linier menggunakan metode divide and conquer.
3 | # Ingat kita bisa melakukan ini dengan
4 | # dalam waktu O(nlogn). Urutkan daftar dan
5 | # mengakses elemen ke-k dalam waktu yang konstan.
6 | # Ini adalah algoritma divide and conquer
7 | # yang dapat menemukan solusi dalam waktu O(n).
8 | # Untuk informasi lebih lanjut tentang algoritma ini:
9 | # https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf
10 |
11 |
12 | from __future__ import annotations
13 |
14 | from random import choice
15 |
16 |
17 | def random_pivot(lst):
18 | """
19 | Pilih pivot acak untuk list.
20 | Kita dapat menggunakan algoritma
21 | yang lebih canggih di sini, seperti median-of-medians
22 | algoritma.
23 | """
24 | return choice(lst)
25 |
26 |
27 | def kth_number(lst: list[int], k: int) -> int:
28 | """
29 | >>> kth_number([2, 1, 3, 4, 5], 3)
30 | 3
31 | >>> kth_number([2, 1, 3, 4, 5], 1)
32 | 1
33 | >>> kth_number([2, 1, 3, 4, 5], 5)
34 | 5
35 | """
36 | pivot = random_pivot(lst)
37 |
38 | small = [e for e in lst if e < pivot]
39 | big = [e for e in lst if e > pivot]
40 | if len(small) == k - 1:
41 | return pivot
42 |
43 | elif len(small) < k - 1:
44 | return kth_number(big, k - len(small) - 1)
45 | else:
46 | return kth_number(small, k)
47 |
48 |
49 | if __name__ == "__main__":
50 | import doctest
51 |
52 | doctest.testmod()
53 |
--------------------------------------------------------------------------------
/algorithm/divide_and_conquer/max_difference_pair.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 |
4 | def max_difference(a: list[int]) -> tuple[int, int]:
5 | """
6 | diberi array A[1..n] bilangan int, n >= 1. Kami ingin
7 | tentukan pasangan indeks (i,j) sedemikian rupa sehingga
8 | 1 <= i <= j <= n dan A[j] - A[i] sebesar mungkin.
9 | informasi lebih lanjut
10 | https://www.geeksforgeeks.org/maximum-difference-between-two-elements/
11 |
12 | >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7])
13 | (1, 9)
14 | """
15 | if len(a) == 1:
16 | return a[0], a[0]
17 | else:
18 | # membagi A menjadi setengah
19 | first = a[: len(a) // 2]
20 | second = a[len(a) // 2 :]
21 |
22 | # 2 sub masalah, 1/2 dari ukuran aslinya.
23 | small1, big1 = max_difference(first)
24 | small2, big2 = max_difference(second)
25 |
26 | min_first = min(first)
27 | max_second = max(second)
28 |
29 | if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1:
30 | return small2, big2
31 | elif big1 - small1 > max_second - min_first:
32 | return small1, big1
33 | else:
34 | return min_first, max_second
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | doctest.testmod()
41 |
--------------------------------------------------------------------------------
/algorithm/fuzzy_logic/README.md:
--------------------------------------------------------------------------------
1 | ## Fuzzy Logic
2 |
3 | Materi Selanjutnya: [Genetic Algo](../genetic_algo)
--------------------------------------------------------------------------------
/algorithm/genetic_algo/README.md:
--------------------------------------------------------------------------------
1 | ## Genetic Algo
2 |
3 | Materi Selanjutnya: [Manipulasi Bit](../manipulasi_bit)
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/README.md:
--------------------------------------------------------------------------------
1 | ## Manipulasi Bit
2 |
3 | manipulasi bit adalah tindakan manipulasi bit atau potongan data ain secaara algoritmik yang lebih pendek dari sebuah kata. manipulasi bit adalah suatu yang memiliki kompleksitas waktu yang konstan. manipulasi bit juga dalah proses penerapan operasi logis pada urutan bit untuk mencapai hasil yang diperlukan. tugas pemograman komputer yang memerlukan manipulasi bit meliputi:
4 |
5 | - kontrol perangkat tingkat rendah
6 | - deteksi kesalahan dan algoritma koreksi
7 | - kompresi data
8 | - algoritma enkripsi
9 | - optimaasi
10 |
11 | untuk sebagian besar tugs lainnya, bahasa pemograman modern memungkinkan pemrogram untuk bekerja secara langsung dengan abstraksi alih-alih bit yang mewakili abstraksi tersebut. manipulasi bit dapat meniadakan atau mengurangi kebutuhan untuk mengulang struktur data dan dapat mempercepat pengkodean karena manipulasi bit diproses secara paralel.
12 |
13 | Materi Selanjutnya: [Matrix](../matrix)
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/binary_and_operator.py:
--------------------------------------------------------------------------------
1 | # fungsi binary and operator
2 | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
3 |
4 |
5 | def binary_and(a: int, b: int) -> str:
6 | """
7 | Ambil 2 bilangan bulat, ubah menjadi biner,
8 | mengembalikan bilangan biner yaitu
9 | hasil dari binary_and operasi pada bilangan
10 | bulat yang disediakan.
11 | >>> binary_and(25, 32)
12 | '0b000000'
13 | >>> binary_and(37, 50)
14 | '0b100000'
15 | >>> binary_and(21, 30)
16 | '0b10100'
17 | >>> binary_and(58, 73)
18 | '0b0001000'
19 | >>> binary_and(0, 255)
20 | '0b00000000'
21 | >>> binary_and(256, 256)
22 | '0b100000000'
23 | >>> binary_and(0, -1)
24 | Traceback (most recent call last):
25 | ...
26 | ValueError: Kedua bilangan harus positif
27 | >>> binary_and(-1, 0)
28 | Traceback (most recent call last):
29 | ...
30 | ValueError: Kedua bilangan harus positif
31 | """
32 |
33 | if a < 0 or b < 0:
34 | raise ValueError("Kedua bilangan harus positif")
35 |
36 | a_binary = str(bin(a))[2:]
37 | b_binary = str(bin(b))[2:]
38 |
39 | max_binary = max(len(a_binary), len(b_binary))
40 |
41 | return "0b" + "".join(
42 | str(int(char_a == "1" and char_b == "1"))
43 | for char_a, char_b in zip(
44 | a_binary.zfill(max_binary), b_binary.zfill(max_binary)
45 | )
46 | )
47 |
48 |
49 | if __name__ == "__main__":
50 | import doctest
51 |
52 | doctest.testmod()
53 |
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/binary_count_trailing_zero.py:
--------------------------------------------------------------------------------
1 | from math import log2
2 |
3 |
4 | def binary_count_trailing_zero(a: int) -> int:
5 | """
6 | Ambil 1 integer,
7 | kembalikan angka yang merupakan jumlah nol trailing
8 | dalam representasi biner dari angka itu.
9 | contoh
10 | angka 25 = 11001 angka 0 akhir dari 1 tidak ada 0
11 | angka 36 = 100100 angka dari akhir 1 ada 0 mulai dibaca
12 | 100 < 1 100 < 2 = 2
13 | angka 16 = 10000 angka 0 akhir dari 1 ada 5
14 | 1 0 < 1 0 < 2 0 < 3 0 < 4 maka jumlah 4
15 | >>> binary_count_trailing_zero(25)
16 | 0
17 | >>> binary_count_trailing_zero(36)
18 | 2
19 | >>> binary_count_trailing_zero(16)
20 | 4
21 | >>> binary_count_trailing_zero(-10)
22 | Traceback (most recent call last):
23 | ...
24 | ValueError: Angka harus positif.
25 | >>> binary_count_trailing_zero(2.3)
26 | Traceback (most recent call last):
27 | ...
28 | TypeError: Angka harus integer.
29 | """
30 | if a < 0:
31 | raise ValueError("Angka harus positif.")
32 | elif isinstance(a, float):
33 | raise TypeError("Angka harus integer.")
34 | return 0 if (a == 0) else int(log2(a & -a))
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | doctest.testmod()
41 |
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/binary_or_operator.py:
--------------------------------------------------------------------------------
1 | # penjelasan tentang bit operator
2 | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
3 |
4 |
5 | def binary_or(a: int, b: int) -> str:
6 | """
7 | Ambil 2 bilangan integer,
8 | ubah menjadi biner,
9 | dan kembalikan angka biner yang merupakan hasil biner
10 | atau operasi pada bilangan bulat yang disediakan.
11 | >>> binary_or(1, 1)
12 | '0b1'
13 | >>> binary_or(0, 1)
14 | '0b1'
15 | >>> binary_or(1, 0)
16 | '0b1'
17 | >>> binary_or(0, 0)
18 | '0b0'
19 | >>> binary_or(58, 73)
20 | '0b1111011'
21 | >>> binary_or(-1, 2)
22 | Traceback (most recent call last):
23 | ...
24 | ValueError: Angka tidak boleh negatif
25 | >>> binary_or(3, -1)
26 | Traceback (most recent call last):
27 | ...
28 | ValueError: Angka tidak boleh negatif
29 | """
30 | if a < 0 or b < 0:
31 | raise ValueError("Angka tidak boleh negatif")
32 | a_binary = str(bin(a))[2:]
33 | b_binary = str(bin(b))[2:]
34 | max_binary = max(len(a_binary), len(b_binary))
35 | return "0b" + "".join(
36 | str(int("1" in (char_a, char_b)))
37 | for char_a, char_b in zip(
38 | a_binary.zfill(max_binary), b_binary.zfill(max_binary)
39 | )
40 | )
41 |
42 |
43 | if __name__ == "__main__":
44 | import doctest
45 |
46 | print(binary_or(1, 1))
47 | doctest.testmod()
48 |
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/binary_setbits.py:
--------------------------------------------------------------------------------
1 | def binary_count(a: int) -> int:
2 | """
3 | ambil 1 bilangan integer
4 | dan kemudian mengambil angka
5 | yaitu jumlah bit yang berisi 1
6 | dalam representasi biner
7 | dari nomor itu
8 | contoh bilangan biner dari 25
9 | 25 = 11001
10 | yang berarti 3 angka 1 dari 25
11 | >>> binary_count(25)
12 | 3
13 | >>> binary_count(36)
14 | 2
15 | >>> binary_count(16)
16 | 1
17 | >>> binary_count(58)
18 | 4
19 | >>> binary_count(4294967295)
20 | 32
21 | >>> binary_count(0)
22 | 0
23 | >>> binary_count(-10)
24 | Traceback (most recent call last):
25 | ...
26 | ValueError: Angka harus positif
27 | >>> binary_count(0.3)
28 | Traceback (most recent call last):
29 | ...
30 | TypeError: Input harus berupa tipe 'int'
31 | """
32 | if a < 0:
33 | raise ValueError("Angka harus positif")
34 | elif isinstance(a, float):
35 | raise TypeError("Input harus berupa tipe 'int'")
36 | return bin(a).count("1")
37 |
38 |
39 | if __name__ == "__main__":
40 | import doctest
41 |
42 | doctest.testmod()
43 |
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/binary_two_complement.py:
--------------------------------------------------------------------------------
1 | # informasi tentang two complemen
2 | # https://en.wikipedia.org/wiki/Two%27s_complement
3 |
4 |
5 | def two_complement(num: int) -> str:
6 | """
7 | ambil angka integer negatif
8 | kemudian mengembalikan
9 | representasi complement dari 'num'
10 | >>> two_complement(0)
11 | '0b0'
12 | >>> two_complement(-1)
13 | '0b11'
14 | >>> two_complement(-5)
15 | '0b1011'
16 | >>> two_complement(-17)
17 | '0b101111'
18 | >>> two_complement(-207)
19 | '0b100110001'
20 | >>> two_complement(1)
21 | Traceback (most recent call last):
22 | ...
23 | ValueError: Angka harus negatif
24 | """
25 | if num > 0:
26 | raise ValueError("Angka harus negatif")
27 | binary_num_len = len(bin(num)[3:])
28 | two_complement_num = bin(abs(num) - (1 << binary_num_len))[3:]
29 | two_complement_num = (
30 | ("1" + "0" * (binary_num_len - len(two_complement_num)) + two_complement_num)
31 | if num < 0
32 | else "0"
33 | )
34 | return "0b" + two_complement_num
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | doctest.testmod()
41 |
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/binary_xor_operator.py:
--------------------------------------------------------------------------------
1 | # informasi tentang binary xor
2 | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
3 |
4 |
5 | def binary_xor(a: int, b: int) -> str:
6 | """
7 | ambil 2 bilangan integer
8 | return bilangan biner
9 | yang merupakan hasil dari binary xor
10 | pada bilangan bulat yang sudah
11 | disediakan
12 | >>> binary_xor(25, 32)
13 | '0b111001'
14 | >>> binary_xor(37, 50)
15 | '0b010111'
16 | >>> binary_xor(21, 30)
17 | '0b01011'
18 | >>> binary_xor(58, 73)
19 | '0b1110011'
20 | >>> binary_xor(0, 255)
21 | '0b11111111'
22 | >>> binary_xor(256, 256)
23 | '0b000000000'
24 | >>> binary_xor(0, -1)
25 | Traceback (most recent call last):
26 | ...
27 | ValueError: Nilai keduanya harus bilangan positif
28 | """
29 | if a < 0 or b < 0:
30 | raise ValueError("Nilai keduanya harus bilangan positif")
31 |
32 | a_binary = str(bin(a))[2:]
33 | b_binary = str(bin(b))[2:]
34 |
35 | max_len = max(len(a_binary), len(b_binary))
36 |
37 | return "0b" + "".join(
38 | str(int(char_a != char_b))
39 | for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
40 | )
41 |
42 |
43 | if __name__ == "__main__":
44 | import doctest
45 |
46 | doctest.testmod()
47 |
--------------------------------------------------------------------------------
/algorithm/manipulasi_bit/count_one_of_bit.py:
--------------------------------------------------------------------------------
1 | def get_set_bits(number: int) -> int:
2 | """
3 | hitung jumlah bit angka 1
4 | >>> get_set_bits(25)
5 | 3
6 | >>> get_set_bits(52132)
7 | 8
8 | >>> get_set_bits(-2)
9 | Traceback (most recent call last):
10 | ...
11 | ValueError: Angka tidak boleh negatif
12 | """
13 | if number < 0:
14 | raise ValueError("Angka tidak boleh negatif")
15 | result = 0
16 |
17 | while number:
18 | if number % 2 == 1:
19 | result += 1
20 | number = number >> 1
21 | return result
22 |
23 |
24 | if __name__ == "__main__":
25 | import doctest
26 |
27 | doctest.testmod()
28 |
--------------------------------------------------------------------------------
/algorithm/matrix/README.md:
--------------------------------------------------------------------------------
1 | ## Matrix
2 |
3 | Materi Selanjutnya: [Networking Flow](../networking_flow)
--------------------------------------------------------------------------------
/algorithm/matrix/inverse_matrix.py:
--------------------------------------------------------------------------------
1 | # inverse matrix
2 | # https://www.mathsisfun.com/algebra/matrix-inverse.html
3 |
4 | from __future__ import annotations
5 |
6 | from decimal import Decimal
7 |
8 |
9 | def inverse_matrix(matrix: list[list[float]]) -> list[list[float]]:
10 | """
11 | Suatu matriks dikalikan dengan inversnya menghasilkan matriks identitas.
12 | Fungsi ini mencari invers dari matriks 2x2.
13 | Jika determinan suatu matriks adalah 0, inversnya tidak ada.
14 | >>> inverse_matrix([[2, 5], [2, 0]])
15 | [[0.0, 0.5], [0.2, -0.2]]
16 | """
17 | D = Decimal
18 | determinan = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1])
19 | if determinan == 0:
20 | raise ValueError("matrix ini no inverse")
21 |
22 | swapped_matrix = [[0.0, 0.0], [0.0, 0.0]]
23 | swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0]
24 | swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1]
25 |
26 | return [[float(D(n) / determinan) or 0.0 for n in row] for row in swapped_matrix]
27 |
28 |
29 | if __name__ == "__main__":
30 | import doctest
31 |
32 | doctest.testmod()
33 |
--------------------------------------------------------------------------------
/algorithm/matrix/searching_in_sorted_matrix.py:
--------------------------------------------------------------------------------
1 | # informasi lebih lanjut tentang searching sorted
2 | # matrix
3 | # https://www.geeksforgeeks.org/search-element-sorted-matrix/
4 |
5 | from __future__ import annotations
6 |
7 |
8 | def search_in_a_sorted_matrix(
9 | mat: list[list], m: int, n: int, key: int | float
10 | ) -> None:
11 | """
12 | >>> search_in_a_sorted_matrix(
13 | ... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 5)
14 | kunci 5 ditemukan pada row 1 kolom 2
15 | >>> search_in_a_sorted_matrix(
16 | ... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 21)
17 | kunci 21 tidak ditemukan
18 | >>> search_in_a_sorted_matrix(
19 | ... [[2.1, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 2.1)
20 | kunci 2.1 ditemukan pada row 1 kolom 1
21 | >>> search_in_a_sorted_matrix(
22 | ... [[2.1, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 2.2)
23 | kunci 2.2 tidak ditemukan
24 | """
25 | i, j = m - 1, 0
26 | while i >= 0 and j < n:
27 | if key == mat[i][j]:
28 | print(f"kunci {key} ditemukan pada row {i + 1} kolom {j + 1}")
29 | return
30 | if key < mat[i][j]:
31 | i -= 1
32 | else:
33 | j += 1
34 |
35 | print(f"kunci {key} tidak ditemukan")
36 |
37 |
38 | def main():
39 | mat = [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]]
40 | x = int(input("masukkan element yang ingin dicari:").strip())
41 | print(mat)
42 | search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), x)
43 |
44 |
45 | if __name__ == "__main__":
46 | import doctest
47 |
48 | doctest.testmod()
49 | main()
50 |
--------------------------------------------------------------------------------
/algorithm/networking_flow/README.md:
--------------------------------------------------------------------------------
1 | ## Networking Flow
2 |
3 | Materi Selanjutnya: [Searching](../searching)
--------------------------------------------------------------------------------
/algorithm/searching/README.md:
--------------------------------------------------------------------------------
1 | ## Searching
2 |
3 | Materi Selanjutnya: [Sorting](../sorting)
--------------------------------------------------------------------------------
/algorithm/searching/_types.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | from typing import Iterable, Protocol, TypeVar, overload, runtime_checkable
4 |
5 | T = TypeVar("T")
6 |
7 |
8 | @runtime_checkable
9 | class SizedIndexable(Iterable[T], Protocol[T]):
10 | @overload
11 | def __getitem__(self, key: slice) -> SizedIndexable[T]:
12 | """
13 | Hanya untuk suppress LGTM alert
14 | """
15 |
16 | def __len__(self) -> int:
17 | """
18 | hanya untuk supress LGTM alert
19 | """
20 |
--------------------------------------------------------------------------------
/algorithm/sorting/bead_sort.py:
--------------------------------------------------------------------------------
1 | # beard sort atau juga bisa disebut dengan gravity sort
2 | # algoritma sorting ini terinspirasi dari fenomena alam
3 | # dan dirancang dengan mengingat object yang jatuh dibawah
4 | # pengaruh gravitasi
5 |
6 | # beard sort hanya berfungsi untuk urutan bilangan
7 | # bilat non-negatif
8 |
9 |
10 | def bead_sort(sequence: list) -> list:
11 | """
12 | >>> bead_sort([6, 11, 12, 4, 1, 5])
13 | [1, 4, 5, 6, 11, 12]
14 |
15 | >>> bead_sort("coba string")
16 | Traceback (most recent call last):
17 | ...
18 | TypeError: Sequence harus berupa list dari non negatif
19 | """
20 | if any(not isinstance(x, int) or x < 0 for x in sequence):
21 | raise TypeError("Sequence harus berupa list dari non negatif")
22 | for _ in range(len(sequence)):
23 | for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])):
24 | if rod_upper > rod_lower:
25 | sequence[i] -= rod_upper - rod_lower
26 | sequence[i + 1] += rod_upper - rod_lower
27 | return sequence
28 |
29 |
30 | if __name__ == "__main__":
31 | assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
32 |
--------------------------------------------------------------------------------
/algorithm/sorting/bogo_sorting.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 |
4 | def bogo_sorting(arr: list[int]) -> list[int]:
5 | """
6 | algoritma bogo sorting adalah algoritma yang bekerja dengan
7 | mengurutkan elemen array secara acak kemudian memeriksa apakah array
8 | tersebut sudah diurutkan. jika tidak, maka akan mengacak kembali.
9 | proses tersebut dilanjutkan hingga semua array ter-urut.
10 | algoritma ini termasuk algoritma sorting yang paling tidak efisien
11 |
12 | >>> bogo_sorting([0, 2, 5, 1, 2])
13 | [0, 1, 2, 2, 5]
14 | """
15 |
16 | # membuat fungsi untuk mengecek apakah array
17 | # sudah disorting
18 | def sudah_disorting(data):
19 | for i in range(len(data) - 1):
20 | if data[i] > data[i + 1]:
21 | return False
22 | return True
23 |
24 | # jika array belum disorting maka lakukan
25 | # pengacakan hingga tersorting
26 | while not sudah_disorting(arr):
27 | random.shuffle(arr)
28 | return arr
29 |
30 |
31 | if __name__ == "__main__":
32 | import doctest
33 |
34 | doctest.testmod(verbose=True)
35 |
--------------------------------------------------------------------------------
/algorithm/sorting/bubble_sort.py:
--------------------------------------------------------------------------------
1 | # bubble sort adalah metode pengurutan algoritma
2 | # dengan cara penukaran data secara terus menerus
3 | # sampai bisa dipastikan dlam satu iterasi tertentu
4 | # tidak ada lagi perubahan / penukaran.
5 |
6 | # bandingkan nilai data ke 1 dan data ke 2
7 | # jika data ke 1 lebih besar, maka tukar posisi ke data 2
8 | # kemudian data yang lebih besar dibandingkan dengand data 3
9 |
10 |
11 | def bubble_sort(collection):
12 | """
13 | contoh
14 | >>> bubble_sort([0, 5, 2, 3, 2])
15 | [0, 2, 2, 3, 5]
16 | >>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
17 | True
18 | """
19 | panjang = len(collection)
20 |
21 | for i in range(panjang - 1):
22 | swap = False
23 | for j in range(panjang - 1 - i):
24 | if collection[j] > collection[j + 1]:
25 | swap = True
26 | collection[j], collection[j + 1] = collection[j + 1], collection[j]
27 | if not swap:
28 | # stop iterasi jika sudah ter sorting
29 | break
30 | return collection
31 |
32 |
33 | if __name__ == "__main__":
34 | import doctest
35 |
36 | doctest.testmod(verbose=True)
37 |
38 | data = [0, 3, 5, 4, 2, 7]
39 | unsorted = [int(item) for item in data]
40 | print(f"data yang belum di sorting adalah {unsorted}")
41 | print(f"data yang sudah di sorting {bubble_sort(unsorted)}")
42 |
--------------------------------------------------------------------------------
/algorithm/sorting/gnome_sorting.py:
--------------------------------------------------------------------------------
1 | def gnome_sorting(daftar: list) -> list:
2 | """
3 | Implementasi dari algoritma gnome sorting
4 |
5 | fungsi yang menerima daftar yang dapat nantinya diubah
6 | dan diurut dengan elemen heterogen yang bisa dibandingkan,
7 | lalu mengembalikan list tersebut dalam urutan menaik
8 |
9 | Parameter:
10 | daftar (list): data yang ingin diberikan
11 |
12 | Return:
13 | (list): hasil sorting gnome
14 |
15 | Contoh:
16 | >>> gnome_sorting([0, 5, 3, 2, 2])
17 | [0, 2, 2, 3, 5]
18 | """
19 | if len(daftar) <= 1:
20 | return daftar
21 |
22 | i = 1
23 | while i < len(daftar):
24 | if daftar[i - 1] <= daftar[i]:
25 | i += 1
26 | else:
27 | # tukar elemen jika tidak dalam urutan yang bener
28 | daftar[i - 1], daftar[i] = daftar[i], daftar[i - 1]
29 | i -= 1
30 | if i == 0:
31 | i = 1
32 | return daftar
33 |
34 |
35 | if __name__ == "__main__":
36 | import doctest
37 |
38 | doctest.testmod(verbose=True)
39 |
--------------------------------------------------------------------------------
/algorithm/sorting/merge_sort.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 |
4 | def merge_sort(data: list) -> list:
5 | """
6 | merge sort adalah algoritma sorting data yang yang bekerja
7 | dengan bekerja dengan membagi data menjadi dua bagian secara
8 | rekursif, megnrutukan kedua bagian secara terpisah, lalu
9 | menggabungkan kembali dua bagian tersebut dengan urutan
10 | yang benar
11 |
12 | referensi:
13 | https://en.wikipedia.org/wiki/Merge_sort
14 |
15 | Args:
16 | data (list): beberapa data yang bisa berubah sebanding dengan
17 | item yang sebanding di dalamnya
18 |
19 | Return:
20 | (list): data hasil yang berupa ascending
21 |
22 | Contoh:
23 | >>> merge_sort([0, 6, 3, 2, 1])
24 | [0, 1, 2, 3, 6]
25 | """
26 |
27 | def merge(kiri: list, kanan: list) -> list:
28 | """
29 | gabungkan data kiri dan kanan
30 |
31 | Args:
32 | kiri (list): data list kiri
33 | kanan (kanan): data list kanan
34 |
35 | Return:
36 | (list): data gabungan dari kiri dan kanan
37 | """
38 |
39 | def _gabung():
40 | while kiri and kanan:
41 | yield (kiri if kiri[0] <= kanan[0] else kanan).pop(0)
42 | yield from kiri
43 | yield from kanan
44 |
45 | return list(_gabung())
46 |
47 | if len(data) <= 1:
48 | return data
49 | mid = len(data) // 2
50 | return merge(merge_sort(data[:mid]), merge_sort(data[mid:]))
51 |
52 |
53 | if __name__ == "__main__":
54 | import doctest
55 |
56 | doctest.testmod()
57 |
--------------------------------------------------------------------------------
/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/assets/logo.png
--------------------------------------------------------------------------------
/dev-requirements.txt:
--------------------------------------------------------------------------------
1 | black==21.7b0
2 | coverage
3 | flake8
4 | isort
5 | mypy
6 | pytest
7 | pytest-cov
8 |
--------------------------------------------------------------------------------
/implementation/blockchain/README.md:
--------------------------------------------------------------------------------
1 | ## Apa itu Blockhain ?
2 | Blockchain adalah teknologi baru yang dikembangkan untuk sistem penyimpanan data digital. Teknologi ini terhubung melalui kriptografi dan penggunaannya sendiri tak bisa lepas dari mata uang Bitcoin dan *Cryptocurrency*.
3 |
4 | *Blockchain* terdiri dari gabungan dua kata, yakni *block* yang artinya kelompok dan *chain* yang berarti rantai. Penamaan tersebut mencerminkan bagaimana cara kerja *blockchain* yang menggunakan sumber daya komputer untuk menciptakan blok-blok yang terhubung satu sama lain dengan tujuan mengeksekusi transaksi.
5 |
6 | Jenis data yang digunakan pada teknologi ini bergantung pada tujuan *blockchain* itu sendiri. Contohnya, dalam bitcoin data blok berisikan seluruh detail transaksi, mulai dari jumlah koin, pengirim, hingga penerima.
7 |
(Sumber : https://www.akseleran.co.id/blog/blockchain-adalah/)
8 |
9 |
10 | Materi Selanjutnya: [Celular Automata](../celular_automata)
--------------------------------------------------------------------------------
/implementation/blockchain/chinese_remainder.py:
--------------------------------------------------------------------------------
1 | # chinese remainder theorem adalah salah satu teori algoritma yang berfungsi
2 | # untuk mempercepat dan meningkatkan efisiensi performa sistem kriptografi RSA
3 | # https://en.wikipedia.org/wiki/Chinese_remainder_theorem
4 |
5 |
6 | def extended_euclid(a: int, b: int) -> tuple[int, int]:
7 | """
8 | >>> extended_euclid(10, 6)
9 | (-1, 2)
10 | """
11 | if b == 0:
12 | return (1, 0)
13 | (x, y) = extended_euclid(b, a % b)
14 | k = a // b
15 | return (y, x - k * y)
16 |
17 |
18 | def chinese_remainder(n1: int, r1: int, n2: int, r2: int) -> int:
19 | """
20 | >>> chinese_remainder(5,1,7,3)
21 | 31
22 |
23 | penjelasan : 31 adalah nomor yang paling kecil
24 | ketika dibagi dengan 5 kita dapat hasil bagi 1
25 | ketika dibagi dengan 7 kita dapat hasil bagi 3
26 | """
27 | (x, y) = extended_euclid(n1, n2)
28 | m = n1 * n2
29 | n = r2 * x * n1 + r1 * y * n2
30 | return (n % m + m) % m
31 |
32 |
33 | if __name__ == "__main__":
34 | import doctest
35 |
36 | doctest.testmod()
37 |
--------------------------------------------------------------------------------
/implementation/celular_automata/README.md:
--------------------------------------------------------------------------------
1 | ## Celular Automata
2 | Celullar automata adalah cara untuk mensimulasikan perilaku "kehidupan", tidak peduli apakah itu robot atau sel. Mereka biasanya mengikuti aturan sederhana tetapi dapat mengarah pada penciptaan bentuk yang kompleks.
3 |
4 | - [game of life](game_of_life.py)
5 | - [one dimensional](one_dimensional.py)
6 |
--------------------------------------------------------------------------------
/implementation/chiper/README.md:
--------------------------------------------------------------------------------
1 | # Apa itu Kriptografi ?
2 | Kriptografi adalah ilmu tentang teknik enkripsi dimana sebuah “naskah/teks asli” (*plaintext*) diacak menggunakan suatu kunci enkripsi menjadi “naskah/teks acak" (*ciphertext*) yang akan sulit dibaca oleh seseorang yang tidak memiliki kunci dekripsi. Untuk mendapatkan kembali "naskah/teks asli", diperlukan sebuah kunci dekripsi.
3 |
4 | (Sumber : https://www.it-jurnal.com/pengertian-dan-sejarah-kriptografi/)
5 |
6 | Materi Selanjutnya: [Compression](../compression)
--------------------------------------------------------------------------------
/implementation/chiper/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/implementation/chiper/__init__.py
--------------------------------------------------------------------------------
/implementation/chiper/atbash.py:
--------------------------------------------------------------------------------
1 | import string
2 |
3 |
4 | def atbash(sequence: str) -> str:
5 | """
6 | >>> atbash("ABCDEFG")
7 | 'ZYXWVUT'
8 | """
9 | letters = string.ascii_letters
10 | letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
11 | return "".join(
12 | letters_reversed[letters.index(c)] if c in letters else c for c in sequence
13 | )
14 |
15 |
16 | if __name__ == "__main__":
17 | import doctest
18 |
19 | doctest.testmod()
20 |
--------------------------------------------------------------------------------
/implementation/chiper/base16.py:
--------------------------------------------------------------------------------
1 | import base64
2 |
3 |
4 | def encode_b16(msg: str) -> bytes:
5 | """
6 | >>> encode_b16('ini contoh')
7 | b'696E6920636F6E746F68'
8 | """
9 | encoded = msg.encode("utf-8")
10 | b16_encode = base64.b16encode(encoded)
11 |
12 | return b16_encode
13 |
14 |
15 | if __name__ == "__main__":
16 | import doctest
17 |
18 | doctest.testmod()
19 |
--------------------------------------------------------------------------------
/implementation/chiper/base32.py:
--------------------------------------------------------------------------------
1 | import base64
2 |
3 |
4 | def encode_b32(msg: str) -> bytes:
5 | """
6 | >>> encode_b32('ini contoh')
7 | b'NFXGSIDDN5XHI33I'
8 | """
9 | encoded = msg.encode("utf-8")
10 | b32_encode = base64.b32encode(encoded)
11 |
12 | return b32_encode
13 |
14 |
15 | if __name__ == "__main__":
16 | import doctest
17 |
18 | doctest.testmod()
19 |
--------------------------------------------------------------------------------
/implementation/chiper/base85.py:
--------------------------------------------------------------------------------
1 | import base64
2 |
3 |
4 | def base85(msg: str) -> bytes:
5 | """
6 | >>> base85("ini contoh")
7 | b'Bl7W-@rH7,DeK'
8 | """
9 | encoded = msg.encode("utf-8")
10 | encoded85 = base64.a85encode(encoded)
11 |
12 | return encoded85
13 |
14 |
15 | if __name__ == "__main__":
16 | import doctest
17 |
18 | doctest.testmod()
19 |
--------------------------------------------------------------------------------
/implementation/chiper/caesar.py:
--------------------------------------------------------------------------------
1 | from string import ascii_letters
2 |
3 |
4 | def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
5 | """
6 | Mengkodekan string yang diberikan dengan sandi caesar
7 | dan mengembalikan kode yang disandikan pesan
8 | >>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
9 | >>> encrypt('situasi pantai aman', 5, alphabet)
10 | 'xnyzfxn ufsyfn frfs'
11 | """
12 | alpha = alphabet or ascii_letters
13 | result = ""
14 |
15 | for character in input_string:
16 | if character not in alpha:
17 | # Tambahkan tanpa enkripsi jika karakter tidak ada dalam alfabet
18 | result += character
19 | else:
20 | # Dapatkan indeks kunci baru dan pastikan tidak terlalu besar
21 | new_key = (alpha.index(character) + key) % len(alpha)
22 |
23 | # tambahkan enskripsi karakter ke dalam alfabet
24 | result += alpha[new_key]
25 |
26 | return result
27 |
28 |
29 | def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
30 | """
31 | Mendekode string teks sandi yang diberikan
32 | dan mengembalikan teks biasa yang didekodekan
33 | >>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
34 | >>> decrypt('xnyzfxn ufsyfn frfs', 5, alphabet)
35 | 'situasi pantai aman'
36 | """
37 | key *= -1
38 | return encrypt(input_string, key, alphabet)
39 |
40 |
41 | if __name__ == "__main__":
42 | import doctest
43 |
44 | doctest.testmod()
45 |
--------------------------------------------------------------------------------
/implementation/chiper/cryptomath_module.py:
--------------------------------------------------------------------------------
1 | def gcd(a: int, b: int) -> int:
2 | """
3 | >>> gcd(10, 5)
4 | 5
5 | >>> gcd(5, 10)
6 | 5
7 | >>> gcd(0, 5)
8 | 5
9 | """
10 | while a != 0:
11 | a, b = b % a, a
12 | return b
13 |
14 |
15 | def find_mod_inverse(a: int, m: int) -> int:
16 | """
17 | >>> find_mod_inverse(2, 5)
18 | 3
19 | >>> find_mod_inverse(7, 26)
20 | 15
21 | >>> find_mod_inverse(1, 26)
22 | 1
23 | """
24 | if gcd(a, m) != 1:
25 | raise ValueError(f"mod kebalikan dari {a!r} dan {m!r} tidak ada")
26 | u1, u2, u3 = 1, 0, a
27 | v1, v2, v3 = 0, 1, m
28 | while v3 != 0:
29 | q = u3 // v3
30 | v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
31 | return u1 % m
32 |
--------------------------------------------------------------------------------
/implementation/chiper/rot13.py:
--------------------------------------------------------------------------------
1 | # program rot13
2 | # https://en.wikipedia.org/wiki/ROT13
3 |
4 |
5 | def decrypt(s: str, n: int = 13) -> str:
6 | """
7 | >>> msg = "keadaan pantai aman"
8 | >>> decrypt(msg)
9 | 'xrnqnna cnagnv nzna'
10 | """
11 | out = ""
12 | for c in s:
13 | if "A" <= c <= "Z":
14 | out += chr(ord("A") + (ord(c) - ord("A") + n) % 26)
15 | elif "a" <= c <= "z":
16 | out += chr(ord("a") + (ord(c) - ord("a") + n) % 26)
17 | else:
18 | out += c
19 |
20 | return out
21 |
22 |
23 | if __name__ == "__main__":
24 | import doctest
25 |
26 | doctest.testmod()
27 |
--------------------------------------------------------------------------------
/implementation/compression/README.md:
--------------------------------------------------------------------------------
1 | ## Compression
2 |
3 |
4 | Materi Selanjutnya: [Electro](../electro)
--------------------------------------------------------------------------------
/implementation/computer_vision/README.md:
--------------------------------------------------------------------------------
1 | # computer vision
2 |
3 | Computer vision adalah bagian dari ilmu komputer yang bekerja dengan melihat, mengidentifikasi serta memproses gambar yang bagaimana manusia lakukan dalam mengidentifikai gambar dan memberikan output yang diinginkan.
4 |
5 | computer vision memanfaatkan kecerdasan buatan dalam mengklasifikan sebuah gambar, memproses gambar.
6 |
7 | | Nama | File |
8 | | ------------- |:-----:|
9 | | klasifikasi CNN | [file](klasifikasi_cnn.py) |
10 |
--------------------------------------------------------------------------------
/implementation/electro/README.md:
--------------------------------------------------------------------------------
1 | ## Conversion
2 |
3 |
4 | Materi Selanjutnya: [File Transfer](../file_transfer)
--------------------------------------------------------------------------------
/implementation/electro/conversion/binary_to_decimal.py:
--------------------------------------------------------------------------------
1 | def binary_to_decimal(bin_string: str) -> int:
2 | """
3 | >>> binary_to_decimal("101")
4 | 5
5 | >>> binary_to_decimal(" 1010 ")
6 | 10
7 | >>> binary_to_decimal("-11101")
8 | -29
9 | >>> binary_to_decimal("0")
10 | 0
11 | >>> binary_to_decimal("a")
12 | Traceback (most recent call last):
13 | ...
14 | ValueError: bukan bilangan biner
15 | >>> binary_to_decimal("")
16 | Traceback (most recent call last):
17 | ...
18 | ValueError: Tidak ada yang diinputkan
19 | >>> binary_to_decimal("39")
20 | Traceback (most recent call last):
21 | ...
22 | ValueError: bukan bilangan biner
23 | """
24 | bin_string = str(bin_string).strip()
25 | if not bin_string:
26 | raise ValueError("Tidak ada yang diinputkan")
27 | is_negative = bin_string[0] == "-"
28 | if is_negative:
29 | bin_string = bin_string[1:]
30 | if not all(char in "01" for char in bin_string):
31 | raise ValueError("bukan bilangan biner")
32 | decimal_number = 0
33 | for char in bin_string:
34 | decimal_number = 2 * decimal_number + int(char)
35 | return -decimal_number if is_negative else decimal_number
36 |
37 |
38 | if __name__ == "__main__":
39 | import doctest
40 |
41 | doctest.testmod()
42 |
--------------------------------------------------------------------------------
/implementation/electro/conversion/binary_to_octal.py:
--------------------------------------------------------------------------------
1 | def binary_to_octal(binary: str) -> str:
2 | """
3 | implementasi biner ke oktal
4 | >>> binary_to_octal("1111")
5 | '17'
6 | """
7 | if not all(char in "01" for char in binary):
8 | raise ValueError("Nilai non-biner diteruskan ke fungsi")
9 | if not binary:
10 | raise ValueError("String kosong diteruskan ke fungsi")
11 |
12 | oct_string = ""
13 | while len(binary) % 3 != 0:
14 | binary = "0" + binary
15 |
16 | binary_string = [
17 | binary[index : index + 3] for index in range(len(binary)) if index % 3 == 0
18 | ]
19 | for bin_group in binary_string:
20 | oct_val = 0
21 | for index, val in enumerate(bin_group):
22 | oct_val += int(2 ** (2 - index) * int(val))
23 | oct_string += str(oct_val)
24 | return oct_string
25 |
26 |
27 | if __name__ == "__main__":
28 | import doctest
29 |
30 | # print(binary_to_octal("1111"))
31 | doctest.testmod()
32 |
--------------------------------------------------------------------------------
/implementation/electro/conversion/binary_to_string.py:
--------------------------------------------------------------------------------
1 | def binary_to_string(bin_string: str):
2 | """
3 | >>> binary_to_string("01100001")
4 | 'a'
5 | >>> binary_to_string("a")
6 | Traceback (most recent call last):
7 | ...
8 | ValueError: bukan bilangan biner
9 | >>> binary_to_string("")
10 | Traceback (most recent call last):
11 | ...
12 | ValueError: tidak ada yang diinputkan
13 | >>> binary_to_string("39")
14 | Traceback (most recent call last):
15 | ...
16 | ValueError: bukan bilangan biner
17 | >>> binary_to_string(1010)
18 | Traceback (most recent call last):
19 | ...
20 | TypeError: bukan string
21 | """
22 | if not isinstance(bin_string, str):
23 | raise TypeError("bukan string")
24 |
25 | if not bin_string:
26 | raise ValueError("tidak ada yang diinputkan")
27 |
28 | if not all(char in "01" for char in bin_string):
29 | raise ValueError("bukan bilangan biner")
30 |
31 | return "".join([chr(int(i, 2)) for i in bin_string.split()])
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/implementation/electro/ohm.py:
--------------------------------------------------------------------------------
1 | def ohm(voltage: float, current: float, resistance: float) -> dict[str, float]:
2 | """
3 | Terapkan Hukum Ohm, pada dua nilai listrik yang diberikan,
4 | yang dapat berupa tegangan, arus,
5 | dan resistensi, dan kemudian dalam Python dict return nama/nilai dari nilai nol.
6 | >>> ohm(voltage=10, resistance=5, current=0)
7 | {'current': 2.0}
8 | >>> ohm(voltage=0, current=0, resistance=10)
9 | Traceback (most recent call last):
10 | ...
11 | ValueError: Hanya satu argumen 0, yang bisa diisi.
12 | >>> ohm(voltage=0, current=1, resistance=-2)
13 | Traceback (most recent call last):
14 | ...
15 | ValueError: Resistan tidak boleh negatif.
16 | >>> ohm(resistance=0, voltage=-10, current=1)
17 | {'resistance': -10.0}
18 | >>> ohm(voltage=0, current=-1.5, resistance=2)
19 | {'voltage': -3.0}
20 | """
21 | if (voltage, current, resistance).count(0) != 1:
22 | raise ValueError("Hanya satu argumen 0, yang bisa diisi.")
23 | if resistance < 0:
24 | raise ValueError("Resistan tidak boleh negatif.")
25 | if voltage == 0:
26 | return {"voltage": float(current * resistance)}
27 | elif current == 0:
28 | return {"current": voltage / resistance}
29 | elif resistance == 0:
30 | return {"resistance": voltage / current}
31 | else:
32 | raise ValueError("Exactly one argument must be 0")
33 |
34 |
35 | if __name__ == "__main__":
36 | import doctest
37 |
38 | doctest.testmod()
39 |
--------------------------------------------------------------------------------
/implementation/file_transfer/README.md:
--------------------------------------------------------------------------------
1 | ## File Transfer
2 |
3 |
4 | Materi Selanjutnya: [Fractal](../fractal)
--------------------------------------------------------------------------------
/implementation/file_transfer/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/implementation/file_transfer/__init__.py
--------------------------------------------------------------------------------
/implementation/file_transfer/receive_file.py:
--------------------------------------------------------------------------------
1 | if __name__ == "__main__":
2 | import socket
3 |
4 | sock = socket.socket()
5 | host = socket.gethostname()
6 | port = 4412
7 |
8 | sock.connect((host, port))
9 | sock.send(b"hellotesting!")
10 |
11 | with open("Received_file", "wb") as out_file:
12 | print("file terbuka")
13 | print("menerima data")
14 | while True:
15 | data = sock.recv(1024)
16 | print(f"{data}")
17 | if not data:
18 | break
19 | out_file.write(data)
20 |
21 | print("data didapatkan")
22 | sock.close()
23 | print("tutup koneksi")
24 |
--------------------------------------------------------------------------------
/implementation/file_transfer/send_file.py:
--------------------------------------------------------------------------------
1 | import socket
2 |
3 |
4 | def send_file(filename: str = "textfile.txt", testing: bool = False) -> None:
5 | port = 4412
6 | sock = socket.socket()
7 | host = socket.gethostname()
8 | sock.bind((host, port))
9 | sock.listen(5)
10 |
11 | print("server jalan..!")
12 |
13 | while True:
14 | conn, addr = sock.accept()
15 | print(f"terkoneksi.. ke {addr}")
16 | data = conn.recv(1024)
17 | print(f"diterima .. {data}")
18 |
19 | with open(filename, "rb") as in_file:
20 | data = in_file.read(1024)
21 | while data:
22 | conn.send(data)
23 | data = in_file.read(1024)
24 |
25 | print("terkirim")
26 |
27 | conn.close()
28 | if testing:
29 | break
30 |
31 | sock.shutdown(1)
32 | sock.close()
33 |
34 |
35 | if __name__ == "__main__":
36 | send_file()
37 |
--------------------------------------------------------------------------------
/implementation/file_transfer/textfile.txt:
--------------------------------------------------------------------------------
1 | testing
2 | bellshade
3 | python indonesia
4 | piton
--------------------------------------------------------------------------------
/implementation/finansial/angsuran.py:
--------------------------------------------------------------------------------
1 | # program untuk menghitung jumlah
2 | # amortisasi perbulan, diberikan
3 | # - pinjaman utama
4 | # - tingkat bunga per tahun
5 | # - tahun untuk membayar kembali pinjaman
6 |
7 |
8 | def angsuran(pinjaman: float, bunga: float, bayar_kembali: int) -> float:
9 | """
10 | rumus
11 | A = p * r * (1 + r) ^n / ((1 + r)^n - 1)
12 | p = pinjaman
13 | r = bunga
14 | n = jumlah pembayaran
15 |
16 | >>> angsuran(25000, 0.12, 3)
17 | 830.3577453212793
18 | """
19 | if pinjaman <= 0:
20 | raise Exception("yang harus dipinjam > 0")
21 | if bunga < 0:
22 | raise Exception("bunga harus >= 0")
23 | if bayar_kembali <= 0 or not isinstance(bayar_kembali, int):
24 | raise Exception("tahun pembayaran harus integer > 0")
25 |
26 | pinjaman_bul = bunga / 12
27 | jumlah_pembayaran = bayar_kembali * 12
28 |
29 | return (
30 | pinjaman
31 | * pinjaman_bul
32 | * (1 + pinjaman_bul) ** jumlah_pembayaran
33 | / ((1 + pinjaman_bul) ** jumlah_pembayaran - 1)
34 | )
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | doctest.testmod()
41 |
--------------------------------------------------------------------------------
/implementation/fractal/README.md:
--------------------------------------------------------------------------------
1 | ## Fractal
2 |
3 | Fractal adalah pola yang tidak pernah berakhir. Fraktal adalah pola kompleks tak terhingga yang serup diri di seluruh skala yang berbeda. Mereka dibuat dengan mengulangi proses sederhana berulang-ulang dalam lingkaran umpan balik yang berkejelanjutan.
4 |
5 | Materi Selanjutnya: [Geodesy Engineering](../geodesy_engineering)
--------------------------------------------------------------------------------
/implementation/fractal/sierpinski_triangle.py:
--------------------------------------------------------------------------------
1 | # informasi tentang sierpinksi triangle
2 | # https://mathigon.org/course/fractals/sierpinski
3 |
4 | import turtle
5 |
6 | name = "sierpinksi triangle"
7 |
8 |
9 | points = [
10 | [
11 | -175,
12 | -125,
13 | ],
14 | [0, 175],
15 | [175, -125],
16 | ]
17 |
18 |
19 | def get_mid(p1, p2):
20 | return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
21 |
22 |
23 | def triangle(points, depth):
24 | drawing.up()
25 | drawing.goto(points[0][0], points[0][1])
26 | drawing.down()
27 | drawing.goto(points[1][0], points[1][1])
28 | drawing.goto(points[2][0], points[2][1])
29 | drawing.goto(points[0][0], points[0][1])
30 |
31 | if depth > 0:
32 | triangle(
33 | [points[0], get_mid(points[0], points[1]), get_mid(points[0], points[2])],
34 | depth - 1,
35 | )
36 | triangle(
37 | [points[1], get_mid(points[0], points[1]), get_mid(points[1], points[2])],
38 | depth - 1,
39 | )
40 | triangle(
41 | [points[2], get_mid(points[2], points[1]), get_mid(points[0], points[2])],
42 | depth - 1,
43 | )
44 |
45 |
46 | if __name__ == "__main__":
47 | drawing = turtle.Turtle()
48 | # drawing.ht()
49 | # drawing.speed(5)
50 | # drawing.pencolor("black")
51 | # triangle(points, 4)
52 |
--------------------------------------------------------------------------------
/implementation/geodesy_egineering/README.md:
--------------------------------------------------------------------------------
1 | ## Geodesy Engineering
2 |
3 |
4 | Materi Selanjutnya: [Linear Algebra](../linear_algebra)
--------------------------------------------------------------------------------
/implementation/geodesy_egineering/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/implementation/geodesy_egineering/__init__.py
--------------------------------------------------------------------------------
/implementation/image_processing/data_image/README.txt:
--------------------------------------------------------------------------------
1 | [INFORMASI]
2 |
3 | Sumber Gambar Dari Dylann Hendricks yang berjudul "a stone staircase leading up to a building"
4 |
5 | Source dari gambar dan pemilik gambar bisa dilihat dibawah ini
6 |
7 | Gambar: https://unsplash.com/photos/a-stone-staircase-leading-up-to-a-building-oaoZXg5GAm8
8 |
9 | User: https://unsplash.com/@dylanhendricks
10 |
--------------------------------------------------------------------------------
/implementation/image_processing/data_image/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/implementation/image_processing/data_image/__init__.py
--------------------------------------------------------------------------------
/implementation/image_processing/data_image/example_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/implementation/image_processing/data_image/example_image.jpg
--------------------------------------------------------------------------------
/implementation/linear_algebra/README.md:
--------------------------------------------------------------------------------
1 | ## Linear Algebra
2 |
3 | Linear algebra atau aljabar linear, adalah salah satu disiplin matematika yang berhubungan dengan vektor dan matriks, lebih umum, dengan ruang vektor dan transformasi linear. Tidak seperti bagian lain dari matematika yang sering disergakan oleh ide-ide baru dan masalah yang belum terpecahkan, aljabar linear sangat dipahami dengan baik. Nlainya terletka pada banyak aplikasinya, dari fisika matematika hingga aljabar modern dan teori pengkodean.
4 |
5 | Materi Selanjutnya: [Physics](../physics)
--------------------------------------------------------------------------------
/implementation/linear_algebra/rayleigh_quotient.py:
--------------------------------------------------------------------------------
1 | from typing import Any
2 |
3 | import numpy as np
4 |
5 |
6 | def is_hermitian(matrix: np.ndarray) -> bool:
7 | """
8 | Memeriksa apakah suatu matriks adalah Hermitian.
9 | >>> import numpy as np
10 | >>> A = np.array([
11 | ... [2, 2+1j, 4],
12 | ... [2-1j, 3, 1j],
13 | ... [4, -1j, 1]])
14 | >>> is_hermitian(A)
15 | True
16 | """
17 | return np.array_equal(matrix, matrix.conjugate().T)
18 |
19 |
20 | def rayleigh_quotient(A: np.ndarray, v: np.ndarray) -> Any:
21 | """
22 | Mengembalikan hasil bagi Rayleigh dari matriks Hermitian A dan
23 | vektor v
24 | >>> import numpy as np
25 | >>> A = np.array([
26 | ... [1, 2, 4],
27 | ... [2, 3, -1],
28 | ... [4, -1, 1]
29 | ... ])
30 | >>> v = np.array([
31 | ... [1],
32 | ... [2],
33 | ... [3]
34 | ... ])
35 | >>> rayleigh_quotient(A, v)
36 | array([[3.]])
37 | """
38 | v_star = v.conjugate().T
39 | v_star_dot = v_star.dot(A)
40 | assert isinstance(v_star_dot, np.ndarray)
41 | return (v_star_dot.dot(v)) / (v_star.dot(v))
42 |
43 |
44 | def testing() -> None:
45 | A = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]])
46 | v = np.array([[1], [2], [3]])
47 | assert is_hermitian(A), f"{A} tidak hermitian."
48 | print(rayleigh_quotient(A, v))
49 |
50 | A = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]])
51 | assert is_hermitian(A), f"{A} tidak hermitian"
52 | assert rayleigh_quotient(A, v) == float(3)
53 |
54 |
55 | if __name__ == "__main__":
56 | import doctest
57 |
58 | # testing()
59 | doctest.testmod()
60 |
--------------------------------------------------------------------------------
/implementation/linear_algebra/transformation_2d.py:
--------------------------------------------------------------------------------
1 | # Transformasi 2D secara teratur digunakan dalam Aljabar Linier
2 | # kode untuk matriks refleksi, proyeksi, penskalaan, dan rotasi 2D.
3 |
4 | from math import cos, sin
5 |
6 |
7 | def scaling(scaling_factor: float) -> list[list[float]]:
8 | """
9 | >>> scaling(5)
10 | [[5.0, 0.0], [0.0, 5.0]]
11 | """
12 | scaling_factor = float(scaling_factor)
13 | return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)]
14 |
15 |
16 | def rotation(angle: float) -> list[list[float]]:
17 | """
18 | >>> rotation(45) # doctest: +NORMALIZE_WHITESPACE
19 | [[0.5253219888177297, -0.8509035245341184],
20 | [0.8509035245341184, 0.5253219888177297]]
21 | """
22 | c, s = cos(angle), sin(angle)
23 | return [[c, -s], [s, c]]
24 |
25 |
26 | def projection(angle: float) -> list[list[float]]:
27 | """
28 | >>> projection(45) # doctest: +NORMALIZE_WHITESPACE
29 | [[0.27596319193541496, 0.446998331800279],
30 | [0.446998331800279, 0.7240368080645851]]
31 | """
32 | c, s = cos(angle), sin(angle)
33 | cs = c * s
34 | return [[c * c, cs], [cs, s * s]]
35 |
36 |
37 | def reflection(angle: float) -> list[list[float]]:
38 | """
39 | >>> reflection(45) # doctest: +NORMALIZE_WHITESPACE
40 | [[0.05064397763545947, 0.893996663600558],
41 | [0.893996663600558, 0.7018070490682369]]
42 | """
43 | c, s = cos(angle), sin(angle)
44 | cs = c * s
45 | return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]
46 |
47 |
48 | if __name__ == "__main__":
49 | import doctest
50 |
51 | doctest.testmod()
52 |
--------------------------------------------------------------------------------
/implementation/physics/README.md:
--------------------------------------------------------------------------------
1 | ## Physics
2 |
3 |
4 | Topik Selanjutnya: [Math](../../math)
--------------------------------------------------------------------------------
/implementation/statistic/LabelEncoding.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | import numpy as np
4 | import pandas as pd
5 |
6 |
7 | class LabelEncoding:
8 | """
9 | Deskripsi:
10 |
11 | ---
12 | Label Enconding adalah algoritma untuk tanda setiap value
13 | agar bisa di kategorikan
14 |
15 | Example:
16 |
17 | ----
18 |
19 | """
20 |
21 | def __init__(self):
22 | self.unique_values = []
23 | self.label_map = {}
24 |
25 | def fit(self, data: Union[np.array, pd.DataFrame]):
26 | if isinstance(data, pd.DataFrame):
27 | data = data.value
28 | self.unique_values = np.unique(data)
29 | return self
30 |
31 | def transform(self, data: np.array):
32 | labels = []
33 | for row in data:
34 | row_labels = []
35 | for value in row:
36 | if value not in self.label_map:
37 | self.label_map[value] = len(self.label_map)
38 | row_labels.append(self.label_map[value])
39 | labels.append(row_labels)
40 | return np.array(labels)
41 |
42 |
43 | if __name__ == "__main__":
44 | data = np.array([[1, 2, 1, 2], [1, 2, 2, 1]])
45 | # df = pd.DataFrame({"S": data[0], "B": data[1]})
46 | label = LabelEncoding()
47 | label.fit(data)
48 | print(label.transform(data))
49 |
--------------------------------------------------------------------------------
/implementation/statistic/correlation.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import requests
3 |
4 |
5 | def dataset() -> np.array:
6 | respon = requests.get(
7 | "https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/"
8 | "master/Week1/ADRvsRating.csv"
9 | )
10 | line = respon.text.splitlines()
11 | data = []
12 | for item in line:
13 | item = item.split(",")
14 | data.append(item)
15 | data.pop(0)
16 | dataset = np.matrix(data).astype(float)
17 | return dataset
18 |
19 |
20 | def correlation(matrix: np.array) -> np.array:
21 | """
22 | correlation merupakan hubungan dua variabel
23 | atau lebih baik variabel bersifat bebas atau
24 | terikat.
25 | Parama:
26 | -------
27 | params:matrix: merupakan bentuk array bersifat multivariat
28 | refence:
29 | https://en.wikipedia.org/wiki/Correlation
30 | """
31 | n = matrix.shape[0]
32 | mean_ = np.mean(matrix, axis=0)
33 | X = matrix - mean_
34 | cov = (X.T @ X) / (n)
35 | std_dev = np.sqrt(np.diag(cov))
36 | inv_std_dev = np.diag(1 / std_dev)
37 | return inv_std_dev @ cov @ inv_std_dev
38 |
39 |
40 | if __name__ == "__main__":
41 | import doctest
42 |
43 | doctest.testmod(verbose=True)
44 | matrix = dataset()
45 | print(dataset())
46 | print(correlation(matrix))
47 |
--------------------------------------------------------------------------------
/implementation/statistic/covariance.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import requests
3 |
4 |
5 | def dataset_collect():
6 | collect = requests.get(
7 | "https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/"
8 | "master/Week1/ADRvsRating.csv"
9 | )
10 | line = collect.text.splitlines()
11 | data = []
12 | for item in line:
13 | item = item.split(",")
14 | data.append(item)
15 | data.pop(0)
16 | dataset = np.matrix(data).astype(float)
17 | return dataset
18 |
19 |
20 | def cov(vector: np.array) -> np.array:
21 | """
22 | covariasi adalah pengukuran untuk hubungan dua variabel
23 | apabaila ada salah satu variabel meningkat maka variabel lain
24 | nya akan mengningkat pula
25 |
26 | Parameter:
27 |
28 | ----------
29 | vector: kumpulan data yang dimensi 2
30 |
31 | Return:
32 |
33 | --------
34 | vector: output ini berupa float di bungkus dgn vector
35 |
36 | refence:
37 | https://stats.stackexchange.com/questions/467306/how-calculate-variance-covariance-matrix-of-coefficients-for-multivariate-multi
38 | https://en.wikipedia.org/wiki/Covariance
39 | """
40 | n_sample = vector.shape[0] - 1
41 | mean_ = np.mean(vector, axis=0)
42 | X = vector - mean_
43 | return (X.T @ X) / n_sample
44 |
45 |
46 | if __name__ == "__main__":
47 | import doctest
48 |
49 | doctest.testmod(verbose=True)
50 | df = dataset_collect()
51 | covariance = cov(df)
52 | print(covariance)
53 |
--------------------------------------------------------------------------------
/implementation/statistic/entropy.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def entropy(labels, base=None) -> float:
5 | """
6 | menghitung entropy dari suatu fitur pada suatu dataset.
7 |
8 | Parameter:
9 |
10 | -----------
11 | labels:numpy.array
12 | Array 1-D yang berisi fitur yang akan dihitung entropynya
13 | base: int
14 | base ini merupakan basis log yang diingikan oleh pemakai
15 | refensi:
16 | https://www.youtube.com/watch?v=2s3aJfRr9gE (Video Tutorial)
17 | https://en.wikipedia.org/wiki/Entropy_(information_theory) (online reading)
18 | https://towardsdatascience.com/entropy-how-decision-trees-make-decisions-2946b9c18c8
19 | (Towards Data Science)
20 |
21 | example:
22 |
23 | --------
24 | >>> label=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
25 | >>> entropy(label,base=2)
26 | 0.9967916319816366
27 | """
28 | _, counts = np.unique(labels, return_counts=True)
29 | probs = counts / len(labels)
30 | logs = np.log(probs) if base is None else np.log(probs) / np.log(base)
31 | return np.sum(abs(probs * logs))
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod(verbose=True)
38 |
--------------------------------------------------------------------------------
/implementation/statistic/information_gain.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from entropy import entropy
3 |
4 |
5 | def informain_gain(feature_df, label_df, base=None) -> float:
6 | """
7 | Menghitung information gain dari suatu fitur pada suatu dataset.
8 |
9 | Parameter:
10 |
11 | -----------
12 | feature_arr: numpy.ndarray
13 | Array 1D yang berisi fitur yang akan dihitung information gain-nya.
14 | label_arr: numpy.ndarray
15 | Array 1D yang berisi label dari dataset.
16 | base:int
17 | base ini digunakan untuk basis log
18 |
19 | Return:
20 | -------
21 | float
22 | infomasi gain dari fitur
23 | refence:
24 | https://homes.cs.washington.edu/~shapiro/EE596/notes/InfoGain.pdf
25 | https://towardsdatascience.com/entropy-how-decision-trees-make-decisions-2946b9c18c8
26 | """
27 | # Menghitung entropy label
28 | parent_entropy = entropy(label_df, base)
29 |
30 | # Menghitung entropy setiap feature
31 | child_entropy = 0
32 | for value in np.unique(feature_df):
33 | group_entropy = entropy(label_df[feature_df == value], base) * np.sum(
34 | feature_df == value
35 | )
36 | child_entropy += group_entropy
37 |
38 | # Menghitung information gain
39 | information_gain = parent_entropy - child_entropy / len(feature_df)
40 |
41 | return information_gain
42 |
--------------------------------------------------------------------------------
/implementation/statistic/median.py:
--------------------------------------------------------------------------------
1 | def median(arr: list) -> int | float:
2 | """
3 | median adalah nilai yang dapat membagi data menjadi dua bagian yang sama.
4 | dengan kata lain bagaimana cara
5 |
6 | **Params**
7 |
8 | -----
9 | arr: tipe data ini adalah
10 |
11 | **Return**
12 |
13 | -----
14 | value : value ini tergantung pada ganjil atau genapnya jumlah panjang data
15 |
16 | **Contoh**
17 |
18 | ---
19 | >>> data=[1,2,3,4,5,6]
20 | >>> median(data)
21 | 3.5
22 | >>> data=[1,1,2,2,2,3,3]
23 | >>> median(data)
24 | 2
25 | """
26 |
27 | # mengurutkan dari terkecil ke besar
28 | arr.sort()
29 | panjang_data = len(arr)
30 |
31 | if panjang_data % 2 == 0:
32 | index = panjang_data - 1
33 | hasil = (arr[index // 2] + arr[(index // 2) + 1]) / 2
34 | else:
35 | index = panjang_data - 1
36 | hasil = arr[(index + 1) // 2]
37 | return hasil
38 |
39 |
40 | if __name__ == "__main__":
41 | import doctest
42 |
43 | doctest.testmod(verbose=True)
44 |
--------------------------------------------------------------------------------
/implementation/statistic/modus.py:
--------------------------------------------------------------------------------
1 | def mode(arr: list[int | float]) -> int | float:
2 | """
3 | mode atau dalam bahasa indonesia adalah modus
4 | modus dalam statiska merupaka nilai yang sering muncul
5 | dalam suatu kumpulan data.
6 |
7 | **Parameter**
8 |
9 | ---
10 | :param arr: parameter ini bertipe data list
11 |
12 | **Return**
13 | :param return: output ini muncul sebagai sesuai dengan item yang sering terjadi
14 |
15 | **Contoh**
16 | >>> data=[1,1,2,2,2,3,3]
17 | >>> mode(data)
18 | 2
19 | """
20 | count = []
21 | for value in arr:
22 | # kita hitung jumlah frekuensi pada setiap value di array tersebut
23 | count.append(arr.count(value))
24 | combine = dict(zip(arr, count))
25 | memo = [a for a, b in combine.items() if b == max(count)]
26 | min_value = memo[0]
27 | result = None
28 | for value in memo:
29 | if value < min_value:
30 | min_value = value
31 | result = min_value
32 | if result == 1:
33 | raise ValueError("nan")
34 | return result
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | doctest.testmod(verbose=True)
41 |
--------------------------------------------------------------------------------
/implementation/statistic/normalDistribution_multivariate.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import requests
3 |
4 |
5 | def dataset() -> np.array:
6 | respon = requests.get(
7 | "https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/"
8 | "master/Week1/ADRvsRating.csv"
9 | )
10 | line = respon.text.splitlines()
11 | data = []
12 | for item in line:
13 | item = item.split(",")
14 | data.append(item)
15 | data.pop(0)
16 | dataset = np.matrix(data).astype(float)
17 | dataset = dataset[:, [0, 1]]
18 | return dataset
19 |
20 |
21 | def gauss_distribution_multivariate(vector: np.array) -> np.array:
22 | """
23 | gauss distribusi normal adalah merupakan
24 | tipe peluang continues bertujuan menciptakan
25 | data random yang mirip value aslinya
26 |
27 | Param:
28 | ------
29 | vector:array dengan dimensi 2D
30 |
31 | Return:
32 | -----
33 | array: berisi number yang telah dilakukan normal distrbution
34 | """
35 | n, m = vector.shape
36 | mean_ = np.mean(vector, axis=0)
37 | X = vector - mean_
38 | cov = (X.T @ X) / (n - 1)
39 | formula = (
40 | 1.0
41 | / np.sqrt((2 * np.pi) ** m * np.linalg.det(cov))
42 | * (-0.5 * np.sum(X @ (np.linalg.inv(cov) @ X.T), axis=1))
43 | )
44 | return formula
45 |
46 |
47 | if __name__ == "__main__":
48 | data = np.random.normal(loc=0, scale=1, size=(100, 2))
49 | print(gauss_distribution_multivariate(dataset()))
50 | print(gauss_distribution_multivariate(data))
51 |
--------------------------------------------------------------------------------
/implementation/statistic/rata_rata.py:
--------------------------------------------------------------------------------
1 | def rata_rata(arr: list[int | float]) -> float:
2 | """
3 | rata-rata adalah menghitung seluruh nilai pada data dengan
4 | panjangnya data tersebut
5 |
6 | **Parameter**
7 |
8 | ----
9 | :param arr:parameter ini bertipe data list mengandung bisa berupa bulat dan desimal
10 |
11 | **Parameter**
12 |
13 | ----
14 | **Return**
15 | :param return: paramater ini beroutput angka desimal
16 | **Contoh**
17 | >>> data=[1,1,2,2,2,3,3]
18 | >>> rata_rata(data)
19 | 2.0
20 | """
21 | arr = arr.copy()
22 | panjang_data = 0
23 | perjumlahan = 0
24 | for value in arr:
25 | panjang_data += 1
26 | perjumlahan += value
27 | hasil = perjumlahan / panjang_data
28 | return hasil
29 |
30 |
31 | if __name__ == "__main__":
32 | import doctest
33 |
34 | doctest.testmod(verbose=True)
35 |
--------------------------------------------------------------------------------
/implementation/statistic/softmax.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def softmax(array: np.array) -> None:
5 | """
6 | Softmax adalah salah satu fungsi aktivasi yang sering
7 | digunakan pada jaringan saraf buatan untuk memetakan input ke
8 | dalam probabilitas keluaran yang sesuai dengan nilai target.
9 | """
10 | x = np.array(array)
11 | if x.ndim == 1:
12 | return np.exp(x) / np.sum(np.exp(x))
13 | elif x.ndim == 2:
14 | n, _ = x.shape
15 | return np.exp(x[:, n]) / np.sum(np.exp(x), axis=1)
16 |
17 |
18 | if __name__ == "__main__":
19 | data = np.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])
20 | softmax_result = softmax(data)
21 | print(softmax_result)
22 |
--------------------------------------------------------------------------------
/implementation/statistic/standard_deviasi.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def standard_dev(vector: np.array) -> float:
5 | x_sum = np.sum([(value - np.mean(vector)) ** 2 for value in vector])
6 | result = np.sqrt(x_sum / len(vector))
7 | return result
8 |
9 |
10 | data = [1, 2, 3, 1]
11 | print(standard_dev(data))
12 |
--------------------------------------------------------------------------------
/implementation/statistic/variance.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def variance(arr: np.array, ddof=0) -> float:
5 | """
6 | variance adalah untuk mengetahui keragaraman data terhadap selisih dari
7 | rata-rata tersebut
8 |
9 | **Params**
10 | ----------
11 | arr:parameter ini berfungsi untuk input data
12 |
13 | **Return**
14 |
15 | ----------
16 | float:hasil dari operasi ini berbentuk bilangan desimal
17 | """
18 | banyak_data = len(arr) - ddof
19 | formula = sum((arr - arr.mean()) ** 2) / banyak_data
20 |
21 | return formula
22 |
23 |
24 | if __name__ == "__main__":
25 | import doctest
26 |
27 | doctest.testmod(verbose=True)
28 |
--------------------------------------------------------------------------------
/math/ runge_kutta.py:
--------------------------------------------------------------------------------
1 | # https://en.wikipedia.org/wiki/Runge-Kutta_methods
2 | import numpy as np
3 |
4 |
5 | def runge_kutta(f, y0, x0, h, x_end):
6 | """
7 | Hitung solusi numerik pada
8 | setiap langkah ke ODE f(x, y) menggunakan RK4
9 |
10 | f = fungsi ODE dari x dan y
11 | y0 value awal untuk y
12 | x0 value awal untuk x
13 | h ukurang langkah
14 | x_end akhir dari value x
15 |
16 | >>> def f(x, y):
17 | ... return y
18 | >>> y0 = 1
19 | >>> y = runge_kutta(f, y0, 0.0, 0.01, 5)
20 | >>> y[-1]
21 | 148.41315904125113
22 | """
23 | N = int(np.ceil((x_end - x0) / h))
24 | y = np.zeros((N + 1,))
25 | y[0] = y0
26 | x = x0
27 |
28 | for k in range(N):
29 | k1 = f(x, y[k])
30 | k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1)
31 | k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2)
32 | k4 = f(x + h, y[k] + h * k3)
33 | y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4)
34 | x += h
35 |
36 | return y
37 |
38 |
39 | if __name__ == "__main__":
40 | import doctest
41 |
42 | doctest.testmod()
43 |
--------------------------------------------------------------------------------
/math/README.md:
--------------------------------------------------------------------------------
1 | ## Math
2 |
3 |
4 | Topik Selanjutnya: [Object Oriented Programming](../object_oriented_programming)
--------------------------------------------------------------------------------
/math/aliquot_sum.py:
--------------------------------------------------------------------------------
1 | def aliquot_sum(input_num: int) -> int:
2 | """
3 | Menemukan jumlah alikuot dari bilangan bulat input, di mana
4 | alikuot jumlah suatu bilangan n
5 | sebagai jumlah semua
6 | bilangan asli kurang dari n
7 | yang membagi n secara merata. Untuk
8 | contoh, jumlah alikuot dari 15 adalah 1 + 3 + 5 = 9. Ini adalah
9 | implementasi O(n) sederhana.
10 | param input_num:
11 | bilangan bulat positif yang jumlah alikuotnya dapat ditemukan
12 | return:
13 | jumlah alikuot dari input_num, jika input_num positif.
14 | Jika tidak, naikkan ValueError
15 | Penjelasan Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
16 |
17 | >>> aliquot_sum(19)
18 | 1
19 | """
20 | if not isinstance(input_num, int):
21 | raise ValueError("input harus integer")
22 | if input_num <= 0:
23 | raise ValueError("input harus positif")
24 |
25 | return sum(
26 | divisor for divisor in range(1, input_num // 2 + 1) if input_num % divisor == 0
27 | )
28 |
29 |
30 | if __name__ == "__main__":
31 | import doctest
32 |
33 | doctest.testmod()
34 |
--------------------------------------------------------------------------------
/math/angka_proth.py:
--------------------------------------------------------------------------------
1 | # kalkulasi nth dari angka proth
2 | # sumber wikipedia
3 | # https://handwiki.org/wiki/Proth_number
4 |
5 | import math
6 |
7 |
8 | def proth(number: int) -> int:
9 | """
10 | >>> proth(6)
11 | 25
12 | >>> proth(0)
13 | Traceback (most recent call last):
14 | ...
15 | ValueError: input value dari [number=0] harus lebih > 0
16 | """
17 | if not isinstance(number, int):
18 | raise TypeError(f"input value dari [number={number}] harus integer")
19 |
20 | if number < 1:
21 | raise ValueError(f"input value dari [number={number}] harus lebih > 0")
22 | elif number == 1:
23 | return 3
24 | elif number == 2:
25 | return 5
26 | else:
27 | # +1 untuk biner mulai dari 0 yaitu 2^0, 2^1, dll.
28 | # +1 untuk memulai urutan pada nomor Proth ke-3
29 | # Oleh karena itu, kami memiliki +2 dalam pernyataan di bawah ini
30 | block_index = int(math.log(number // 3, 2)) + 2
31 |
32 | proth_list = [3, 5]
33 | proth_index = 2
34 | increment = 3
35 | for block in range(1, block_index):
36 | for move in range(increment):
37 | proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])
38 | proth_index += 1
39 | increment *= 2
40 |
41 | return proth_list[number - 1]
42 |
43 |
44 | if __name__ == "__main__":
45 | import doctest
46 |
47 | doctest.testmod()
48 |
--------------------------------------------------------------------------------
/math/bisection_math.py:
--------------------------------------------------------------------------------
1 | # informasi tentang bisection
2 | # https://en.wikipedia.org/wiki/Bisection_method
3 |
4 | from __future__ import annotations
5 |
6 |
7 | def equation(x: float) -> float:
8 | """
9 | hasil dari pengurangan dan perkalian
10 | dari x
11 | parameter dan tipe:
12 | x: float
13 | return:
14 | hasil dari 10 - x * x
15 | tipe:
16 | float
17 | >>> equation(5)
18 | -15
19 | >>> equation(0.1)
20 | 9.99
21 | """
22 | return 10 - x * x
23 |
24 |
25 | def bisection(a: float, b: float) -> float:
26 | """
27 | Diberikan fungsi pada bilangan mengambang f(x) dan dua bilangan
28 | float 'a' dan 'b' sedemikian sehingga
29 | f(a) * f(b) < 0 dan f(x) kontinu di [a, b]self.
30 | Di sini f(x) mewakili persamaan aljabar atau transendentalself.
31 | Cari akar fungsi dalam interval [a, b]
32 | (Atau cari nilai x sehingga f(x) adalah 0)
33 |
34 | >>> bisection(-2, 5)
35 | 3.1611328125
36 | >>> bisection(0, 6)
37 | 3.158203125
38 | """
39 |
40 | # menggunakan teori bolzano
41 | if equation(a) * equation(b) >= 0:
42 | print("0")
43 |
44 | c = a
45 | while (b - a) >= 0.01:
46 | # mencari nilai tengahnya
47 | c = (a + b) / 2
48 | if equation(c) == 0.0:
49 | break
50 | if equation(c) * equation(a) < 0:
51 | b = c
52 | else:
53 | a = c
54 |
55 | return c
56 |
57 |
58 | if __name__ == "__main__":
59 | import doctest
60 |
61 | doctest.testmod()
62 |
--------------------------------------------------------------------------------
/math/convolution.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def simple_convolution(arr1: np.array, arr2: np.array):
5 | """
6 | fungsi merupakan calculasi dari rumus sederhana
7 | dari convolution
8 | Args:
9 | arr1 (np.array): Inputan berupa array 1 dimensi
10 | arr2 (np.array): Inputan berupa array 1 dimensi
11 | """
12 | m, n = arr1.shape[0], arr2.shape[0]
13 |
14 | # indenfikasi kalau ukuran array input harus sama
15 | if m != n:
16 | raise ValueError("Dimensi array harus sama")
17 |
18 | # kalkulasi tersebut
19 | result = np.zeros(m + n - 1)
20 | for i in range(m):
21 | for j in range(n):
22 | result[i + j] += arr1[i] * arr2[j]
23 | return result
24 |
--------------------------------------------------------------------------------
/math/exponential_function.py:
--------------------------------------------------------------------------------
1 | from math import factorial
2 |
3 |
4 | def exponent(x: int | float):
5 | """_summary_
6 |
7 | Args:
8 | x (_type_): _description_
9 |
10 | Returns:
11 | _type_: _description_
12 | Contoh:
13 | >>> exponent(2)
14 | 7.38905609893
15 | >>> exponent(1)
16 | 2.71828182846
17 | """
18 | n_term: int = 100
19 | result: float = 0.0
20 | for n in range(n_term):
21 | result += x**n / factorial(n)
22 |
23 | return round(result, 11)
24 |
25 |
26 | if __name__ == "__main__":
27 | import doctest
28 |
29 | doctest.testmod(verbose=True)
30 |
--------------------------------------------------------------------------------
/math/faktor_prima.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 |
4 | def faktor_prima(n: int) -> list[int]:
5 | """
6 | mengembalikan bilangan faktor prima
7 | dalam list
8 |
9 | >>> faktor_prima(0)
10 | []
11 | >>> faktor_prima(100)
12 | [2, 2, 5, 5]
13 | >>> faktor_prima(10**-2)
14 | []
15 | """
16 | i = 2
17 | faktor = []
18 | while i * i <= n:
19 | if n % i:
20 | i += 1
21 | else:
22 | n //= i
23 | faktor.append(i)
24 | if n > 1:
25 | faktor.append(n)
26 | return faktor
27 |
28 |
29 | if __name__ == "__main__":
30 | import doctest
31 |
32 | doctest.testmod()
33 |
--------------------------------------------------------------------------------
/math/fibonacci.py:
--------------------------------------------------------------------------------
1 | def fibonacci(n: int) -> list[int]:
2 | """
3 | fibbonacci adalah urutan angka dari jumlah dari dua bilangan sebelumnya,.
4 | kecuali dengan bilangan pertama dan kedua yang nilainya adalah 0 dan 1.
5 | >>> fibonacci(5)
6 | [0, 1, 1, 2, 3, 5]
7 | >>> fibonacci(10)
8 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
9 | """
10 | if n < 0:
11 | assert "Input integer value tidak boleh negatif"
12 |
13 | a = 0
14 | b = 1
15 | result = []
16 | for _ in range(n + 1):
17 | result.append(a)
18 |
19 | a, b = b, a + b
20 |
21 | return result
22 |
23 |
24 | if __name__ == "__main__":
25 | import doctest
26 |
27 | doctest.testmod(verbose=True)
28 |
--------------------------------------------------------------------------------
/math/geometric_sum.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 |
4 | def geoSum(suku_pertama: int, rasio: int, jumlah_deret: int) -> float:
5 | """
6 | Menghitung deret geometri berhingga dari n buah suku
7 | dengan suku pertama a dan rasio r. Rumus umum berlaku
8 | jika r tidak sama dengan 1 dan a tidak sama dengan 0
9 | Rumus = a * ((1 - pow(r, n)) / (1 - r))
10 | Mengembalikan nilai perhitungan rumus
11 |
12 | >>> geoSum(2, 2, 3)
13 | 14.0
14 |
15 | >>> geoSum(0, 0.5, 3)
16 | Traceback (most recent call last):
17 | ...
18 | ValueError: Suku pertama tidak boleh 0
19 |
20 | >>> geoSum(3, 1, 5)
21 | Traceback (most recent call last):
22 | ...
23 | ValueError: Rasio tidak boleh sama dengan 1
24 | """
25 | a = suku_pertama
26 | r = rasio
27 | n = jumlah_deret
28 |
29 | if a == 0:
30 | raise ValueError("Suku pertama tidak boleh 0")
31 | elif r == 1:
32 | raise ValueError("Rasio tidak boleh sama dengan 1")
33 | else:
34 | result = a * ((1 - pow(r, n)) / (1 - r))
35 | return result
36 |
37 |
38 | if __name__ == "__main__":
39 | import doctest
40 |
41 | doctest.testmod()
42 |
43 | # menampilkan 93.0
44 | # hasil1 = geoSum(3, 2, 5)
45 | # print(hasil1)
46 |
47 | # me-raise exception
48 | # hasil2 = geoSum(3, 1, 5)
49 | # print(hasil2)
50 |
--------------------------------------------------------------------------------
/math/intergration.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bellshade/Python/ce827e3977e132dd4a616506fe336b8e347f9d80/math/intergration.py
--------------------------------------------------------------------------------
/math/iteration_power.py:
--------------------------------------------------------------------------------
1 | def iteration_power(number: int, exp: int) -> int:
2 | """
3 | Perpangkatan dengan metode iteratif atau perulangan
4 | rumus matematika: number^exp
5 | >>> iteration_power(2, 5)
6 | 32
7 | >>> iteration_power(100, 0)
8 | 1
9 | >>> iteration_power(0, 100)
10 | 0
11 | >>> iteration_power(1, 100)
12 | 1
13 | """
14 | result = 1
15 | for _ in range(exp):
16 | result *= number
17 | return result
18 |
19 |
20 | if __name__ == "__main__":
21 | import doctest
22 |
23 | doctest.testmod()
24 |
25 | # Pangkat lebih dari 1
26 | print(iteration_power(number=2, exp=5))
27 |
28 | # Pangkat sama dengan 0
29 | print(iteration_power(number=100, exp=0))
30 |
31 | # Angka 0 dengan pangkat lebih dari 1
32 | print(iteration_power(number=0, exp=100))
33 |
34 | # Angka 1 dengan pangkat lebih dari 1
35 | print(iteration_power(number=1, exp=100))
36 |
--------------------------------------------------------------------------------
/math/jumlah_deret_geomteri.py:
--------------------------------------------------------------------------------
1 | # informasi tentang geometri progression
2 | # https://en.wikipedia.org/wiki/Geometric_progression
3 |
4 |
5 | def jumlah_deret_geometri(utama: int, rasio_umum: int, jumlah: int) -> int:
6 | """
7 | Menghitung jumlah deret geometri
8 | >>> jumlah_deret_geometri(1, 2, 10)
9 | 1023.0
10 | >>> jumlah_deret_geometri(1, 10, 5)
11 | 11111.0
12 | >>> jumlah_deret_geometri(0, 2, 10)
13 | 0.0
14 | """
15 | if rasio_umum == 1:
16 | # Rumus jumlah jika rasio umum adalah 1
17 | return jumlah * utama
18 |
19 | # Rumus untuk mencari jumlah n suku dari Progresi Geometris
20 | return (utama / (1 - rasio_umum)) * (1 - rasio_umum**jumlah)
21 |
22 |
23 | if __name__ == "__main__":
24 | import doctest
25 |
26 | doctest.testmod()
27 |
--------------------------------------------------------------------------------
/math/pascal_triangle.py:
--------------------------------------------------------------------------------
1 | def PascalTriangle(n: int) -> list[list[int]]:
2 | """Fungsi untuk mendapatkan segitiga pascal sebanyak n-baris
3 |
4 | Args:
5 | n (int): n baris bilangan yang diinginkan
6 |
7 | Returns:
8 | List[List[int]]: Kumpulan bilangan pascal
9 |
10 | >>> print(PascalTriangle(1))
11 | [[1]]
12 |
13 | >>> print(PascalTriangle(3))
14 | [[1], [1, 1], [1, 2, 1]]
15 |
16 | >>> print(PascalTriangle(5))
17 | [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
18 | """
19 | result = [[1] * (row + 1) for row in range(n)]
20 |
21 | for list_num in range(n):
22 | for position in range(1, list_num):
23 | result[list_num][position] = (
24 | result[list_num - 1][position - 1] + result[list_num - 1][position]
25 | )
26 | return result
27 |
28 |
29 | if __name__ == "__main__":
30 | import doctest
31 |
32 | doctest.testmod()
33 |
--------------------------------------------------------------------------------
/math/persamaan_kuadarat_bilangan_kompleks.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | from cmath import sqrt
4 |
5 |
6 | def akar_kuadrat(a: int, b: int, c: int) -> tuple[complex, complex]:
7 | """
8 | diberikan koefisien numerik a, b dan c,
9 | menghitung akar untuk setiap persamaan kuadrat dalam bentuk ax^2 + bx + c
10 |
11 | >>> akar_kuadrat(a = 1,b = 3,c = -4)
12 | (1.0, -4.0)
13 |
14 | >>> akar_kuadrat(5, 6, 1)
15 | (-0.2, -1.0)
16 |
17 | >>> akar_kuadrat(-1, 2, 3)
18 | (-1.0, 3.0)
19 |
20 | >>> akar_kuadrat(0, -2, 3)
21 | Traceback (most recent call last):
22 | ...
23 | ValueError: Koefisien a tidak boleh 0
24 | """
25 |
26 | if a == 0:
27 | raise ValueError("Koefisien a tidak boleh 0")
28 |
29 | delta = b * b - 4 * a * c
30 |
31 | if delta > 0:
32 | akar_1: complex = (-b + sqrt(delta)) / (2 * a)
33 | akar_2: complex = (-b - sqrt(delta)) / (2 * a)
34 |
35 | return akar_1, akar_2
36 |
37 | elif delta == 0:
38 | return 0
39 |
40 | else:
41 | msg: str = "persamaanya menjadi imajiner"
42 | return msg
43 |
44 |
45 | def main() -> None:
46 | solusi1, solusi2 = akar_kuadrat(a=1, b=3, c=4)
47 | print(f"solusi adalah {solusi1} dan {solusi2}")
48 |
49 |
50 | if __name__ == "__main__":
51 | import doctest
52 |
53 | doctest.testmod()
54 | main()
55 |
--------------------------------------------------------------------------------
/math/prime_number_library.py:
--------------------------------------------------------------------------------
1 | from sympy import isprime, nextprime, prevprime, prime, primepi, primerange, randprime
2 |
3 | # Mengecek apakah sebuah nilai adalah bilangan prima
4 | print("Apakah 10 angka prima?", isprime(10))
5 | print("Apakah 11 angka prima?", isprime(11))
6 |
7 | # Men-generate bilangan prima dalam batasan tertentu
8 | print("Tampilkan angka prima dari 1 sampai 10:")
9 | for i in primerange(1, 10):
10 | print(i)
11 |
12 | # Mengembalikan nilai random bilangan prima dalam batasan tertentu
13 | print("Angka prima acak antara 1 sampai 100:", randprime(1, 100))
14 |
15 | # Mengembalikan banyaknya bilangan prima kurang dari sama dengan nilai yang diinputkan
16 | print("Jumlah angka prima kurang dari sama dengan 10:", primepi(10))
17 |
18 | # Mengembalikan nilai ke n
19 | # misalkan bilangan prima pertama adalah 2
20 | # maka input yang diberikan adalah 1
21 | print("Angka prima ke 1:", prime(1))
22 |
23 | # Mengembalikan 1 angka prima sebelum angka input
24 | print("Angka prima sebelum angka 7:", prevprime(7))
25 |
26 | # Mengembalikan 1 angka prima setelah angka input
27 | print("Angka prima setelah angka 7:", nextprime(7))
28 |
--------------------------------------------------------------------------------
/math/proth_number.py:
--------------------------------------------------------------------------------
1 | # kalkulasi nth angka proth
2 | # https://handwiki.org/wiki/Proth_number
3 | import math
4 |
5 |
6 | def proth(angka: int) -> int:
7 | """
8 | >>> proth(-3)
9 | Traceback (most recent call last):
10 | ...
11 | ValueError: angka tidak boleh kurang dari 1
12 | >>> proth(6.0)
13 | Traceback (most recent call last):
14 | ...
15 | TypeError: Angka harus integer
16 | """
17 | if not isinstance(angka, int):
18 | raise TypeError("Angka harus integer")
19 |
20 | if angka < 1:
21 | raise ValueError("angka tidak boleh kurang dari 1")
22 |
23 | elif angka == 1:
24 | return 3
25 |
26 | elif angka == 2:
27 | return 5
28 |
29 | else:
30 | # +1 untuk biner yang dimulai pada 0 contoh 2 ^0, 2 ^1 dan lainnya
31 | block_index = int(math.log(angka // 3, 2)) + 2
32 | proth_list = [3, 5]
33 | proth_index = 2
34 | increment = 3
35 |
36 | for block in range(1, block_index):
37 | for _ in range(increment):
38 | proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])
39 | proth_index += 1
40 | increment *= 2
41 |
42 | return proth_list[angka - 1]
43 |
44 |
45 | if __name__ == "__main__":
46 | import doctest
47 |
48 | doctest.testmod(verbose=True)
49 |
50 | for angka in range(11):
51 | value = 0
52 | try:
53 | value = proth(angka)
54 | except ValueError:
55 | print(f"{angka}")
56 | continue
57 |
58 | print(f"{angka}, angka proth: {value}")
59 |
--------------------------------------------------------------------------------
/math/qr_decomposition.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def qr_householder(A):
5 | """
6 | Dekomposisi QR menguraikan matriks A berbentuk (m, n) menjadi an
7 | matriks ortogonal Q bentuk (m, m) dan matriks segitiga atas R dari
8 | bentuk (m, n). Perhatikan bahwa matriks A tidak harus persegi. Ini
9 | metode penguraian A menggunakan refleksi Householder, yaitu
10 | stabil secara numerik dan kompleksitas O(n^3).
11 |
12 | informasi lebih lanjut
13 | https://en.wikipedia.org/wiki/QR_decomposition#Using_Householder_reflections
14 |
15 | >>> A = np.array([[12, -51, 4], [6, 167, -68], [-5, 24, -14]], dtype=float)
16 | >>> Q, R = qr_householder(A)
17 |
18 | >>> # cek apabila dekomposisi benar
19 | >>> np.allclose(Q@R, A)
20 | True
21 | """
22 | m, n = A.shape
23 | t = min(m, n)
24 | Q = np.eye(m)
25 | R = A.copy()
26 |
27 | for k in range(t - 1):
28 | x = R[k:, [k]]
29 | e1 = np.zeros_like(x)
30 | e1[0] = 1.0
31 | alpha = np.linalg.norm(x)
32 | v = x + np.sign(x[0]) * alpha * e1
33 | v /= np.linalg.norm(v)
34 |
35 | Q_k = np.eye(m - k) - 2.0 * v @ v.T
36 | Q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), Q_k]])
37 |
38 | Q = Q @ Q_k.T
39 | R = Q_k @ R
40 |
41 | return Q, R
42 |
43 |
44 | if __name__ == "__main__":
45 | import doctest
46 |
47 | doctest.testmod()
48 |
--------------------------------------------------------------------------------
/math/r2_score.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def r2_score(y_predict, y_actual):
5 | """
6 | R2_score adalah ukuran yang digunakan dalam statistik untuk mengukur••
7 | seberapa baik model regresi cocok dengan data yang diamati••
8 | R2_score memberikan informasi seberapa dekat••
9 | titik data dengan garis regresi yang dihasilkan oleh model.
10 |
11 | >>> r2_score(np.array([12,34,12,23]),np.array([11,2,11,22]))
12 | -4.109452736318408
13 | >>> r2_score(np.array([12,34,12,23]),np.array([12,30,11,23]))
14 | 0.9319999999999999
15 | """
16 |
17 | sse = sum((y_actual - y_predict) ** 2)
18 | sst = sum((y_actual - np.mean(y_actual)) ** 2)
19 |
20 | return 1 - (sse / sst)
21 |
22 |
23 | if __name__ == "__main__":
24 | import doctest
25 |
26 | doctest.testmod(verbose=True)
27 |
--------------------------------------------------------------------------------
/math/radian.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | def radian_to_degree(radian: float) -> float:
5 | """
6 | Fungsi ini digunakan untuk mengonversi radian ke derajat.
7 | Rumus : radian * (180 derajat / pi)
8 |
9 | >>> radian_to_degree(5)
10 | 286.4788975654116
11 | """
12 | return radian * (180 / math.pi)
13 |
14 |
15 | def degree_to_radian(degree: float) -> float:
16 | """
17 | Fungsi ini digunakan untuk mengonversi derajat ke radian.
18 | Rumus : derajat * (pi / 180 derajat)
19 |
20 | >>> degree_to_radian(60)
21 | 1.0471975511965976
22 | """
23 | return degree * (math.pi / 180)
24 |
25 |
26 | def radian_to_gradian(radian: float) -> float:
27 | """
28 | Fungsi ini digunakan untuk mengonversi radian ke gradian.
29 | Rumus : radian * (200 gradian / pi)
30 |
31 | >>> radian_to_gradian(3)
32 | 190.9859317102744
33 | """
34 | return radian * (200 / math.pi)
35 |
36 |
37 | def gradian_to_radian(gradian: float) -> float:
38 | """
39 | Fungsi ini digunakan untuk mengonversi radian ke gradian.
40 | Rumus : gradian * (180 / (200 gradian)
41 |
42 | >>> gradian_to_radian(53)
43 | 0.8325220532012952
44 | """
45 | return gradian * (math.pi / 200)
46 |
47 |
48 | if __name__ == "__main__":
49 | import doctest
50 |
51 | doctest.testmod()
52 |
--------------------------------------------------------------------------------
/math/rectangle.py:
--------------------------------------------------------------------------------
1 | from typing import Callable
2 |
3 | import numpy as np
4 |
5 |
6 | def rectangle(
7 | func: Callable[..., float], a: float, b: float, eps: float = 0.0001, *args, **kwargs
8 | ) -> float:
9 | """
10 | Metode segi empat adalah metode integrasi paling sederhana.
11 | Metode ini membagi domain integrasi sebanyak n buah
12 | dan menjumlahkan seluruh luas segi empat dengan dimensi
13 | (a + b)/n * f(x), dimana x adalah sudut kiri segiempat
14 |
15 | Parameter:
16 | func = fungsi input
17 | a = batas bawah integrasi
18 | b = batas atas integrasi
19 | eps = error relatif maksimal
20 |
21 | >>> rectangle(lambda x: x**2, 0, 2)
22 | 2.6992751228325296
23 | >>> rectangle(lambda x: x**1, 0, 2)
24 | 2.0198019801980194
25 | """
26 | try:
27 | n = 100
28 | x = np.linspace(a, b, n)
29 | dx = x[1] - x[0]
30 | L0 = sum(dx * func(i, *args, **kwargs) for i in x)
31 | err = 1
32 | while err > eps:
33 | n += 1
34 | x = np.linspace(a, b, n)
35 | dx = x[1] - x[0]
36 | L1 = sum(dx * func(i, *args, **kwargs) for i in x)
37 | err = np.abs(L1 - L0) / np.abs(L1)
38 | L0 = L1
39 | except Exception:
40 | raise RuntimeError("Integrasi gagal, pastikan fungsi anda benar!")
41 | return L1
42 |
43 |
44 | if __name__ == "__main__":
45 |
46 | def f(x: float) -> float:
47 | """
48 | Test Function
49 | """
50 | return x**2
51 |
52 | print(rectangle(f, 0, 2))
53 |
54 | import doctest
55 |
56 | doctest.testmod()
57 |
--------------------------------------------------------------------------------
/math/recursion_power.py:
--------------------------------------------------------------------------------
1 | def recursion_power(number: int, exp: int, result: int = 1) -> int:
2 | """
3 | Perpangkatan dengan metode rekursif
4 | rumus matematika: number^exp
5 | >>> recursion_power(2, 5)
6 | 32
7 | >>> recursion_power(100, 0)
8 | 1
9 | >>> recursion_power(0, 100)
10 | 0
11 | >>> recursion_power(1, 100)
12 | 1
13 | """
14 | if exp < 1:
15 | return result
16 | else:
17 | return recursion_power(number, exp - 1, result * number)
18 |
19 |
20 | if __name__ == "__main__":
21 | import doctest
22 |
23 | doctest.testmod()
24 |
25 | # Pangkat lebih dari 1
26 | print(recursion_power(number=2, exp=5))
27 |
28 | # Pangkat sama dengan 0
29 | print(recursion_power(number=100, exp=0))
30 |
31 | # Angka 0 dengan pangkat lebih dari 1
32 | print(recursion_power(number=0, exp=100))
33 |
34 | # Angka 1 dengan pangkat lebih dari 1
35 | print(recursion_power(number=1, exp=100))
36 |
--------------------------------------------------------------------------------
/math/relu.py:
--------------------------------------------------------------------------------
1 | """
2 | Activation Function ReLU
3 |
4 | ReLU (Rectified Linear Unit) merupakan salah satu fungsi aktivasi
5 | yang biasa digunakan pada projek Machine Learning dan Deep Learning
6 | khususnya yang menggunakan Artificial Neural Network.
7 |
8 | Cara kerja ReLU sederhana, fungsi akan mengembalikan nilai 0 jika
9 | nilai input kurang dari 0. Jika fungsi diberi input nilai
10 | lebih dari 0 maka nilai yang dikembalikan adalah nilai input itu.
11 |
12 | >>> relu(1.0)
13 | 1.0
14 |
15 | >>> relu(0.0)
16 | 0.0
17 | """
18 |
19 |
20 | def relu(x: float):
21 | if x > 0.0:
22 | return x
23 | else:
24 | return 0.0
25 |
26 |
27 | if __name__ == "__main__":
28 | import doctest
29 |
30 | doctest.testmod()
31 |
32 | # Nilai input lebih dari 0
33 | print(relu(30.0))
34 |
35 | # Nilai input kurang dari 0
36 | print(relu(-30.0))
37 |
38 | # Nilai input sama dengan 0
39 | print(relu(0.0))
40 |
41 | # Nilai banyak sekali
42 | print(relu(193279812837917298371927.0))
43 |
--------------------------------------------------------------------------------
/math/segmented_sieve.py:
--------------------------------------------------------------------------------
1 | # segmented sieve
2 |
3 | from __future__ import annotations
4 |
5 | import math
6 |
7 |
8 | def sieve(n: int) -> tuple:
9 | """
10 | >>> sieve(2 **3)
11 | (2, 3, 5, 7)
12 |
13 | >>> sieve(3 ** 3)
14 | (2, 3, 5, 7, 11, 13, 17, 19, 23)
15 |
16 | >>> sieve(4)
17 | (2, 3)
18 | """
19 | in_prime = []
20 | start = 2
21 | end = int(math.sqrt(n))
22 | temp = [True] * (end + 1)
23 | prime = []
24 |
25 | while start <= end:
26 | if temp[start] is True:
27 | in_prime.append(start)
28 | for i in range(start * start, end + 1, start):
29 | if temp[i] is True:
30 | temp[i] = False
31 |
32 | start += 1
33 | prime += in_prime
34 |
35 | low = end + 1
36 | high = low + end - 1
37 | if high > n:
38 | high = n
39 |
40 | while low <= n:
41 | temp = [True] * (high - low + 1)
42 | for each in in_prime:
43 | t = math.floor(low / each) * each
44 | if t < low:
45 | t += each
46 |
47 | for j in range(t, high + 1, each):
48 | temp[j - low] = False
49 |
50 | for j in range(len(temp)):
51 | if temp[j] is True:
52 | prime.append(low + j)
53 |
54 | low = high + 1
55 | high = low + end - 1
56 |
57 | if high > n:
58 | high = n
59 |
60 | return tuple(prime)
61 |
62 |
63 | if __name__ == "__main__":
64 | import doctest
65 |
66 | doctest.testmod(verbose=True)
67 | # print(sieve(4))
68 |
--------------------------------------------------------------------------------
/math/sieve_of_eratosthenes.py:
--------------------------------------------------------------------------------
1 | # Saringan Eratosthenes adalah algoritma yang digunakan
2 | # untuk mencari bilangan prima, kurang dari atau
3 | # sama dengan nilai yang diberikan.
4 | # informasi lebih lanjut
5 | # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
6 |
7 | from __future__ import annotations
8 |
9 | import math
10 |
11 |
12 | def prime_sieve(angka: int) -> list[int]:
13 | """
14 | mengembalikan daftar dengan semua bilangan prima
15 | hingga ke n
16 | >>> prime_sieve(25)
17 | [2, 3, 5, 7, 11, 13, 17, 19, 23]
18 | >>> prime_sieve(10)
19 | [2, 3, 5, 7]
20 | >>> prime_sieve(2)
21 | [2]
22 | >>> prime_sieve(1)
23 | []
24 | """
25 | if angka <= 0:
26 | raise ValueError("angka harus positif atau tidak boleh 0")
27 |
28 | sieve = [True] * (angka + 1)
29 | prime = []
30 | start = 2
31 | end = int(math.sqrt(angka))
32 |
33 | while start <= end:
34 | if sieve[start] is True:
35 | prime.append(start)
36 |
37 | # atur kelipatan awal menjadi false
38 | for i in range(start * start, angka + 1, start):
39 | if sieve[i] is True:
40 | sieve[i] = False
41 |
42 | start += 1
43 |
44 | for j in range(end + 1, angka + 1):
45 | if sieve[j] is True:
46 | prime.append(j)
47 |
48 | return prime
49 |
50 |
51 | if __name__ == "__main__":
52 | import doctest
53 |
54 | doctest.testmod(verbose=True)
55 |
--------------------------------------------------------------------------------
/math/sigmoid.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def sigmoid(vector: np.array) -> np.array:
5 | """fungsi sigmoid digunakan untuk mendapatkan output berupa non-linear
6 |
7 | Args:
8 | vector (np.array): Nilai input berupa vektor
9 |
10 | Returns:
11 | np.array: Nilai sigmoid dari vektor yang diinputkan
12 |
13 | >>> sigmoid(np.array([-1.0, 1.0, 2.0]))
14 | array([0.26894142, 0.73105858, 0.88079708])
15 | >>> sigmoid(np.array([0.0]))
16 | array([0.5])
17 | """
18 | return 1 / (1 + np.exp(-vector))
19 |
--------------------------------------------------------------------------------
/math/sin.py:
--------------------------------------------------------------------------------
1 | from math import pi, e
2 |
3 |
4 | def factorial(n: int) -> int:
5 | if n < 0:
6 | raise ValueError("angkanya harus bilangan real")
7 | if n == 0 or n == 1:
8 | return 1
9 | else:
10 | return n * factorial(n - 1)
11 |
12 |
13 | def sinus(x: float | int, iterable: int = 4):
14 | """
15 | Sinus ini merupakan perhitungan dasar yang ada pada
16 | teori pythagoras
17 | Args:
18 | x (float | int): input ini merupakan value dari sudut yang kita
19 | inputkan
20 | iterable (int, optional): paramater ini untuk jumlah data yang kuta sum kan
21 | Defaults to 4.
22 | Returns:
23 | complex: hasil dari pembagian numerator (complex) dengan denominator
24 | """
25 | result = 0
26 | for n in range(iterable):
27 | numerator = (e ** (complex(0, pi / 180) * x)) - (
28 | e ** (-complex(0, pi / 180) * x)
29 | )
30 | denominator = factorial(2 * n + 1)
31 | result += numerator / denominator
32 | return result
33 |
34 |
35 | if __name__ == "__main__":
36 | list_sudut = [0, pi / 2, pi * 3 / 4, pi]
37 | for sudut in list_sudut:
38 | print("Sudut:", sudut, "Sin:", sinus(sudut))
39 |
--------------------------------------------------------------------------------
/math/sock_merchant.py:
--------------------------------------------------------------------------------
1 | # solusi dari problem maths hackerrank sockmerchank
2 |
3 | from __future__ import annotations
4 |
5 | from collections import Counter
6 |
7 |
8 | def sock_merchant(colors: list[int]) -> int:
9 | """
10 | >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
11 | 3
12 | >>> sock_merchant([1, 2, 1, 2, 1, 3, 2])
13 | 2
14 | """
15 | return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values())
16 |
17 |
18 | if __name__ == "__main__":
19 | import doctest
20 |
21 | doctest.testmod(verbose=True)
22 |
--------------------------------------------------------------------------------
/math/softmax.py:
--------------------------------------------------------------------------------
1 | # demonstrasi darii implementasi fungsi softmax
2 |
3 | # Ini adalah fungsi yang mengambil vektor dari K
4 | # bilangan real sebagai input, dan menormalkan
5 | # ke dalam distribusi probabilitas yang terdiri
6 | # dari K probabilitas proporsional
7 | # ke eksponensial dari angka input.
8 | # Setelah softmax, elemen dari
9 | # vektor selalu berjumlah 1.
10 |
11 | # referensi
12 | # https://en.wikipedia.org/wiki/Softmax_function
13 |
14 | import numpy as np
15 |
16 |
17 | def softmax(vector):
18 | """
19 | Menerapkan fungsi softmax
20 | Parameter:
21 | vector (np.array,list,tuple): Array berbentuk numpy (1,n)
22 | terdiri dari nilai-nilai nyata atau daftar serupa,tuple
23 | Pengembalian:
24 | softmax_vec (np.array):
25 | Input array numpy setelah diterapkan
26 | softmax.
27 | Vektor softmax menambahkan hingga satu.
28 | Kita perlu membatasi untuk
29 | presisi
30 |
31 | >>> vec = np.array([5, 5])
32 | >>> softmax(vec)
33 | array([0.5, 0.5])
34 |
35 | >>> softmax([0])
36 | array([1.])
37 | """
38 | exponent_vector = np.exp(vector)
39 |
40 | # Jumlahkan semua eksponensialnya
41 | sum_exponent = np.sum(exponent_vector)
42 |
43 | # bagi setiap eksponen dengan jumlah
44 | # semua eksponen
45 | softmax_vector = exponent_vector / sum_exponent
46 |
47 | return softmax_vector
48 |
49 |
50 | if __name__ == "__main__":
51 | import doctest
52 |
53 | doctest.testmod(verbose=True)
54 |
--------------------------------------------------------------------------------
/math/sum_geometric_progression.py:
--------------------------------------------------------------------------------
1 | # penjelasan tentang sum of geometric progression
2 | # https://www.cuemath.com/algebra/sum-of-a-gp/
3 |
4 |
5 | def sum_geometric_progression(
6 | ist_pertama: int, rasio_umum: int, ist_bilangan: int
7 | ) -> float:
8 | """
9 | mengembalikan jumlah n suku dalam
10 | deret geometric
11 | >>> sum_geometric_progression(1, 2, 10)
12 | 1023.0
13 | >>> sum_geometric_progression(1, 10, 5)
14 | 11111.0
15 | >>> sum_geometric_progression(0, 2, 10)
16 | 0.0
17 | """
18 | if rasio_umum == 1:
19 | # rumus untuk hasil jika rasio umum adalah 1
20 | return ist_bilangan * ist_pertama
21 |
22 | # rumus untuk menemukan hasil dari suku ke n dari
23 | # geometric progression
24 | return (ist_pertama / (1 - rasio_umum)) * (1 - rasio_umum**ist_bilangan)
25 |
--------------------------------------------------------------------------------
/math/sylvester_sequence.py:
--------------------------------------------------------------------------------
1 | # Menghitung angka ke-n dalam deret Sylvester
2 | # https://en.wikipedia.org/wiki/Sylvester%27s_sequence
3 |
4 |
5 | def sylvester(number: int) -> int:
6 | """
7 | >>> sylvester(8)
8 | 113423713055421844361000443
9 |
10 | >>> sylvester(-1)
11 | Traceback (most recent call last):
12 | ...
13 | ValueError: angka tidak boleh negatif
14 | """
15 | assert isinstance(number, int), f"nomor {number} tidak integer"
16 |
17 | if number == 1:
18 | return 2
19 | elif number < 1:
20 | raise ValueError("angka tidak boleh negatif")
21 | else:
22 | num = sylvester(number - 1)
23 | lower = num - 1
24 | upper = num
25 | return lower * upper + 1
26 |
27 |
28 | if __name__ == "__main__":
29 | print(f"nomor ke 8 dalam deret sylvester {sylvester(8)}")
30 |
--------------------------------------------------------------------------------
/math/teorema_pytaghoras.py:
--------------------------------------------------------------------------------
1 | # menghitung 2 point menggunakan teorema pythagoras
2 | # https://www.statmat.net/teorema-pythagoras/
3 |
4 | import math
5 |
6 |
7 | class Poin:
8 | def __init__(self, x, y, z):
9 | self.x = x
10 | self.y = y
11 | self.z = z
12 |
13 | def __repr__(self) -> str:
14 | return f"Poin({self.x}, {self.y}, {self.z})"
15 |
16 |
17 | def jarak(a: Poin, b: Poin) -> float:
18 | return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2))
19 |
20 |
21 | def tes_hitung() -> None:
22 | """
23 | >>> poin1 = Poin(2, -1, 7)
24 | >>> poin2 = Poin(1, -3, 5)
25 | >>> print(f"jarak dari {poin1} ke {poin2} adalah {jarak(poin1, poin2)}")
26 | jarak dari Poin(2, -1, 7) ke Poin(1, -3, 5) adalah 3.0
27 | """
28 | pass
29 |
30 |
31 | if __name__ == "__main__":
32 | import doctest
33 |
34 | doctest.testmod()
35 |
--------------------------------------------------------------------------------
/math/two_pointer.py:
--------------------------------------------------------------------------------
1 | # Diberikan array bilangan bulat yang diurutkan,
2 | # kembalikan indeks dari dua angka seperti
3 | # bahwa mereka menambahkan hingga target tertentu menggunakan teknik dua pointer.
4 | # Anda dapat berasumsi bahwa setiap input
5 | # akan memiliki tepat satu solusi, dan Anda
6 | # tidak boleh menggunakan elemen yang sama dua kali.
7 | # Ini adalah solusi alternatif dari
8 | # masalah dua jumlah, yang menggunakan
9 | # peta untuk memecahkan masalah.
10 | # Oleh karena itu tidak dapat menyelesaikan masalah jika ada
11 | # kendala tidak menggunakan indeks yang sama dua kali.
12 | # contoh
13 | # diberikan arr = [2, 7, 11, 15] target = 9
14 | # jadi karena arr[0] + arr[1] = 2 + 7 = 9
15 | # maka mengembalikan nilai [0, 1]
16 |
17 |
18 | from __future__ import annotations
19 |
20 |
21 | def two_pointer(nums: list[int], target: int) -> list[int]:
22 | """
23 | >>> two_pointer([2, 7, 11, 15], 9)
24 | [0, 1]
25 | >>> two_pointer([2, 7, 11, 15], 18)
26 | [1, 2]
27 | >>> two_pointer([2, 7, 11, 15], 13)
28 | [0, 2]
29 | """
30 | i = 0
31 | j = len(nums) - 1
32 | while i < j:
33 | if nums[i] + nums[j] == target:
34 | return [i, j]
35 | elif nums[i] + nums[j] < target:
36 | i = i + 1
37 | else:
38 | j = j - 1
39 |
40 | return []
41 |
42 |
43 | if __name__ == "__main__":
44 | import doctest
45 |
46 | doctest.testmod()
47 |
--------------------------------------------------------------------------------
/math/two_sum.py:
--------------------------------------------------------------------------------
1 | # Diberikan array bilangan bulat, kembalikan indeks dari
2 | # dua angka sedemikian rupa sehingga jumlahnya menjadi
3 | # target tertentu.
4 | # Anda mungkin berasumsi bahwa setiap input
5 | # akan memiliki tepat satu solusi,
6 | # dan Anda tidak boleh menggunakan
7 | # elemen yang sama dua kali. informasi tentang two sum
8 | # https://leetcode.com/problems/two-sum/
9 |
10 | from __future__ import annotations
11 |
12 |
13 | def two_sum(nums: list[int], target: int) -> list[int]:
14 | """
15 | >>> two_sum([2, 7, 11, 15], 9)
16 | [0, 1]
17 | >>> two_sum([15, 2, 11, 7], 13)
18 | [1, 2]
19 | """
20 | chk_map: dict[int, int] = {}
21 | for index, val in enumerate(nums):
22 | compl = target - val
23 | if compl in chk_map:
24 | return [chk_map[compl], index]
25 | chk_map[val] = index
26 |
27 | return []
28 |
29 |
30 | if __name__ == "__main__":
31 | import doctest
32 |
33 | doctest.testmod()
34 | print(f"{two_sum([2, 7, 11, 15], 9)}")
35 |
--------------------------------------------------------------------------------
/math/ugly_number.py:
--------------------------------------------------------------------------------
1 | # bilangan aneh adalah bilangan
2 | # yang faktor primanya hanya 2, 3, 5
3 | # urutannya
4 | # 1, 2, 3, 4 ,5 ,6, 8, 9, 10, 12, 15, ...
5 | # menunjukkan angka aneh pertama.
6 | # dengan perjanjian
7 | # 1 disertakan. deiberikan bilangan bilan n,
8 | # kita harus menemukan bilangan aneh ke-n
9 |
10 |
11 | def ugly_number(n: int) -> int:
12 | """
13 | return bilangan aneh
14 | >>> ugly_number(100)
15 | 1536
16 | >>> ugly_number(0)
17 | 1
18 | >>> ugly_number(20)
19 | 36
20 | """
21 | ugly_num = [1]
22 | i2, i3, i5 = 0, 0, 0
23 | next_2 = ugly_num[i2] * 2
24 | next_3 = ugly_num[i3] * 3
25 | next_5 = ugly_num[i5] * 5
26 |
27 | for i in range(1, n):
28 | next_num = min(next_2, next_3, next_5)
29 | ugly_num.append(next_num)
30 | if next_num == next_2:
31 | i2 += 1
32 | next_2 = ugly_num[i2] * 2
33 | if next_num == next_3:
34 | i3 += 1
35 | next_3 = ugly_num[i3] * 3
36 | if next_num == next_5:
37 | i5 += 1
38 | next_5 = ugly_num[i5] * 5
39 | return ugly_num[-1]
40 |
41 |
42 | if __name__ == "__main__":
43 | import doctest
44 |
45 | doctest.testmod(verbose=True)
46 | print(f"{ugly_number(100)}")
47 |
--------------------------------------------------------------------------------
/math/variance.py:
--------------------------------------------------------------------------------
1 | def rata_rata(data: list[int | float]) -> float:
2 | """
3 | rata-rata merupakan model matematika untuk mengetahui
4 | jumlah seluruh nilai data dibagi banyak data
5 | contoh input:
6 | >>> rata_rata([20,12,12])
7 | 14.666666666666666
8 | >>> rata_rata([-20,3,12])
9 | -1.6666666666666667
10 | """
11 | jumlah = 0
12 | panjang_data = 0
13 | for number in data:
14 | panjang_data += 1
15 | jumlah += number
16 | result = jumlah / panjang_data
17 | return result
18 |
19 |
20 | def variance(data: list[int | float]) -> float:
21 | """
22 | variansi atau dalam bahasa inggris disebut juga disebut variance.
23 | variansi ini berfungsi untuk menghitung ukuran nilai data agar,
24 | mengetahui sifat-sifat serta semua titik data dalam kumpulan data.
25 | >>> variance([10,20,20])
26 | 33.33
27 | >>> variance([-20,1,2])
28 | 154.33
29 | """
30 | n = len(data)
31 | jumlah = 0
32 | for value in data:
33 | hitung = (value - rata_rata(data)) ** 2
34 | jumlah += hitung
35 | result = jumlah / (n - 1)
36 | return round(result, 2)
37 |
38 |
39 | if __name__ == "__main__":
40 | import doctest
41 |
42 | doctest.testmod()
43 |
--------------------------------------------------------------------------------
/matrix/median_matriks.py:
--------------------------------------------------------------------------------
1 | def median(matriks: list[list[int]]) -> int:
2 | """
3 | menghitung nilai dari median dari sebuah matriks
4 | yang sudah diurutkan
5 |
6 | Parameter:
7 | matriks(list[list[int]]): matriks 2D yang berisi bilangan
8 | bulat
9 |
10 | Contoh:
11 | >>> matriks = [[1, 3, 5], [2, 6, 9], [3, 6, 9]]
12 | >>> median(matriks)
13 | 5
14 | >>> matriks = [[1, 2, 3], [4, 5, 6]]
15 | >>> median(matriks)
16 | 3
17 | """
18 | # flatten matriks 2D jadi list 1D yang terurut
19 | linear = sorted(angka for baris in matriks for angka in baris)
20 |
21 | # hitung indeks tengah untuk menemukan median
22 | tengah = (len(linear) - 1) // 2
23 |
24 | # return hasil dari nilai median
25 | return linear[tengah]
26 |
27 |
28 | if __name__ == "__main__":
29 | import doctest
30 |
31 | # jalankan doctesting
32 | doctest.testmod()
33 |
--------------------------------------------------------------------------------
/object_oriented/advance/.gitignore:
--------------------------------------------------------------------------------
1 | env/*
2 | /.mypy_cache
--------------------------------------------------------------------------------
/object_oriented/advance/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Catatan: bagi kamu yang belum mempelajari tentang dasaran dari object oriented programming di python, sangat di sarankan untuk mempelajari syntax berorientasi object pada python.
-------------------------------------------------------------------------------- /object_oriented/advance/pycode/argument/args.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from getopt import getopt, GetoptError 3 | from typing import List 4 | 5 | 6 | try: 7 | argv: List[str] = sys.argv[1:] 8 | opts, args = getopt(argv, "c:", ["create="]) 9 | 10 | except GetoptError as e: 11 | raise e 12 | 13 | for opt, arg in opts: 14 | if opt in ["-c", "--create"]: 15 | with open(arg, "w") as file: 16 | res = file.write("Berhasil membuat berkas dengan CLI...") 17 | file.close() 18 | else: 19 | ... 20 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/decorators/contoh_decorators1.py: -------------------------------------------------------------------------------- 1 | # Contoh Decorator 1 2 | def menyapa(nama: str) -> str: 3 | """Contoh pada decorator yang satu ini, kita hanya cukup satu fungsi 4 | yang mengembalikan nilai Uppercase 5 | :param nama: masukan bellshade pada parameter nama 6 | >>> nama = "bellshade" 7 | >>> salam = menyapa 8 | >>> salam(nama) 9 | 'BELLSHADE' 10 | """ 11 | return nama.upper() 12 | 13 | 14 | def test_menyapa(): 15 | assert "BELLSHADE" == menyapa("bellshade") 16 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/decorators/contoh_decorators2.py: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | 3 | 4 | # Contoh Decorator 2 5 | def wpu(str1: str) -> str: 6 | # Fungsi wpu yang mengembalikan nilai string upper 7 | return str1.upper() 8 | 9 | 10 | def terbuka(str2: str) -> str: 11 | # Fungsi terbuka yang mengembalikan nilai string lower 12 | return str2.lower() 13 | 14 | 15 | def bellshade(func: Callable) -> str: 16 | """ 17 | Fungsi ini akan menampung fungsi dari luar fungsi bellshade 18 | :param func: parameter fungsi yang akan menampung fungsi lainnya 19 | >>> mhs1 = wpu 20 | >>> mhs2 = terbuka 21 | >>> bellshade(mhs1) 22 | 'HALO SOBAT BELLSHADE!!!' 23 | >>> bellshade(mhs2) 24 | 'halo sobat bellshade!!!' 25 | """ 26 | return func("Halo Sobat bellshade!!!") 27 | 28 | 29 | def test_func_upper(): 30 | assert "HALO SOBAT BELLSHADE!!!" == bellshade(wpu) 31 | 32 | 33 | def test_func_lower(): 34 | assert "halo sobat bellshade!!!" == bellshade(terbuka) 35 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/decorators/contoh_decorators3.py: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | 3 | 4 | # Contoh Decorator 3 5 | def users(nama: str) -> Callable: 6 | """ 7 | Fungsi ini hanya mengembalikan sebuah fungsi 8 | :param name: Parameter nama dari fungsi users 9 | >>> nama = 'Udin' 10 | >>> belajar = users(nama) 11 | >>> belajar('Python') 12 | 'Udin sedang belajar: Python' 13 | """ 14 | 15 | def belajar(str1: Callable) -> str: 16 | """ 17 | Fungsi ini akan membungkus parameter dari users 18 | """ 19 | 20 | # Return ini mengembalikan nilai untuk fungsi (belajar) 21 | return f"{nama} sedang belajar: {str1}" 22 | 23 | # Di return terluar, kita akan mengembalikan nilai berupa fungsi (belajar) 24 | return belajar 25 | 26 | 27 | def test_input_user(): 28 | name = "Udin" 29 | belajar = users(name) 30 | assert "Udin sedang belajar: Python" == belajar("Python") 31 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/decorators/decorators.py: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | 3 | 4 | # Decorators 5 | def bellshade(func: Callable) -> Callable: 6 | """ 7 | Fungsi ini akan kita jadikan sebagai decoratord decorators (@) 8 | Saat Mengeksekusi, kita cukup panggil Fungsi wpu 9 | >>> wpu('Bellshade') 10 | 'Selamat datang Bellshade' 11 | """ 12 | 13 | def wrap(str1: str) -> str: 14 | return f"Selamat datang {str1}" 15 | 16 | return wrap # <- Mengembalikan fungsi (wrap) sebagai fungsi terdalam (bellshade) 17 | 18 | 19 | @bellshade 20 | def wpu(str1: str) -> str: 21 | return str1 22 | 23 | 24 | # ----------| Cara Penggunaan Decorators |---------- # 25 | def test_decorators(): 26 | @bellshade 27 | def wpu(str1): 28 | return str1 29 | assert str1 == "Bellshade" 30 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/decorators/decorators_chaining.py: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | 3 | 4 | # DECORATORS CHAINING 5 | def add(func: Callable) -> Callable: 6 | """ 7 | Fungsi ini akan memanggil fungsi lain dan mengembalikan fungsi 8 | >>> num1() 9 | 1250 10 | """ 11 | 12 | def wrap() -> int: 13 | x = func() 14 | return x + x 15 | 16 | return wrap 17 | 18 | 19 | def add_quadrat(func: Callable) -> Callable: 20 | """ 21 | Fungsi ini akan memanggil fungsi lain dan mengembalikan fungsi 22 | >>> num2() 23 | 2500 24 | """ 25 | 26 | def wrap() -> int: 27 | x = func() 28 | return x**2 29 | 30 | return wrap 31 | 32 | 33 | # Cara menggunakan rantai decorators 34 | @add 35 | @add_quadrat 36 | def num1() -> int: 37 | return 25 38 | 39 | 40 | @add_quadrat 41 | @add 42 | def num2() -> int: 43 | return 25 44 | 45 | 46 | def test_add(): 47 | assert num1() == 1250 48 | 49 | 50 | def test_add_quadrat(): 51 | assert num2() == 2500 52 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/decorators/decorators_return.py: -------------------------------------------------------------------------------- 1 | from typing import Union, Callable 2 | 3 | 4 | def openseries(func: Callable) -> Callable: 5 | """ 6 | Fungsi openseries akan di jadikan sebagai decorators yang mengembalikan fungsi 7 | Sekarang coba jalankan fungsi add yang di decorators fungsi openseries 8 | >>> a = 5 9 | >>> b = 9 10 | >>> add(a, b) 11 | '(5 + 9): 14' 12 | """ 13 | 14 | def wrap(*args: Union[int, float]) -> Union[int, float]: 15 | return_val = func(*args) 16 | return return_val 17 | 18 | return wrap 19 | 20 | 21 | @openseries 22 | def add(a: Union[int, float], b: Union[int, float]) -> Union[int, str]: 23 | return f"({a} + {b}): {a + b}" 24 | 25 | 26 | def test_openseries_add_func(): 27 | assert add(5, 9) == "(5 + 9): 14" 28 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/generators/generators_for.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | from typing import Callable 3 | 4 | 5 | # GENERATORS 6 | def Generators(func: Callable) -> Callable: 7 | """ 8 | Fungsi ini akan menerima parameter dari user untuk melakukan generate 9 | ubah bagian range function menjadi [for i in range(random.randint(5,35))] 10 | hapus [return i] jika ingin generate berlanjut 11 | 12 | :param func: Tipe parameter diharuskan object_func 13 | :return: Hasil Generators 14 | >>> coba1() 15 | 49 16 | """ 17 | 18 | @wraps(func) 19 | def start() -> int: 20 | i: int = 1 21 | for i in range(13, 50): 22 | i ** func() 23 | return i 24 | 25 | return start 26 | 27 | 28 | def test_generators(): 29 | 30 | @Generators 31 | def coba1(): 32 | return 7 33 | 34 | assert coba1() == 49 35 | 36 | 37 | @Generators 38 | def coba1(): 39 | return 7 40 | 41 | 42 | if __name__ == "__main__": 43 | print(coba1()) 44 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/generators/generators_while.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | 4 | # GENERATORS WHILE 5 | class Generators: 6 | """ 7 | Kelas ini secara default hanya akan menghasilkan 1x generate 8 | :param target_int: Untuk menentukan jumlah hasil generate 9 | :param max_repeat: Untuk membatas perulangan agar berhenti dan tidak overloop 10 | Jika kamu ingin mendapatkan hasil generate secara berkala hapus [return selft.res] 11 | 12 | >>> app = Generators(7) 13 | >>> app() 14 | 2187 15 | """ 16 | 17 | def __init__(self, target_int: Union[int, float], max_repeat: int = 5) -> None: 18 | self.tar_mul = target_int 19 | self.target_repeat_max = max_repeat 20 | 21 | def __call__(self): 22 | self.start_generate() 23 | 24 | def start_generate(self) -> None: 25 | self.indeks = 2 26 | 27 | try: 28 | while True: 29 | self.indeks += 1 30 | self.res = self.indeks**self.tar_mul 31 | print(self.res) 32 | 33 | if self.indeks == self.target_repeat_max: 34 | break 35 | 36 | return self.res 37 | except Exception: 38 | ... 39 | 40 | 41 | def test_generate_dengan_attribute(): 42 | app = Generators(7) 43 | assert app.start_generate() == 2187 44 | 45 | 46 | app = Generators(7) 47 | 48 | if __name__ == "__main__": 49 | app() 50 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/magic_methods/Mmethod.py: -------------------------------------------------------------------------------- 1 | class Pastikom: 2 | 3 | def __init__(self, yourname: str, email: str) -> None: 4 | """Magic Method 5 | Kelas Pastikom memiliki 2 parameter dan/atau argumen 6 | :param yourname: tuliskan nama mu di parameter pertama 7 | :param email: tuliskan email mu di parameter ke dua 8 | nama = 'Bellshade' 9 | email = bellshade@pastikom.id 10 | >>> Pastikom(nama, email) 11 | Nama: Bellshade 12 | Email: bellshade@pastikom.id 13 | """ 14 | self.name = yourname 15 | self.email = email 16 | 17 | def __repr__(self) -> str: 18 | """Fungsi representasi nilai parameter dan/atau argumen""" 19 | return f"Nama: {self.name}\nEmail: {self.email}" 20 | 21 | def __del__(self) -> str: 22 | """Fungsi informasi jika ada nilai parameter dan/atau argumen yang terhapus""" 23 | return "Oh tidaaaak! Data sudah terhapus :'(" 24 | 25 | 26 | nama: str = "Bellshade" 27 | email: str = "bellshade@pastikom.id" 28 | if __name__ == "__main__": 29 | Pastikom(nama, email) 30 | -------------------------------------------------------------------------------- /object_oriented/advance/pycode/metaclass/README.md: -------------------------------------------------------------------------------- 1 |
2 |
3 |