├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── python-app-week-02.yml │ ├── python-app-week-03.yml │ ├── python-app-week-04.yml │ ├── python-app-week-05.yml │ └── python-app-week-06.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── LectureNotes.pdf ├── README.md ├── SECURITY.md ├── Week01 └── NumericalAnalysisSyllabus.pdf ├── Week02 ├── first.py ├── literals.py ├── memory.py ├── operations.py ├── priorities.py ├── test_types.py ├── types_ahmetyusuf_dursun.py ├── types_furkancan_okal.py ├── types_ikram_celal_keskin.py └── types_ufuk_dilek.py ├── Week03 ├── memory.py ├── seq.ipynb ├── sequences_furkancan_okal.py ├── sequences_ikram_celal_keskin.py ├── sequences_ufuk_dilek.py ├── test_sequences.py └── try_numpy.ipynb ├── Week04 ├── arrays_furkancan_okal.py ├── arrays_ikram_celal_keskin.py ├── arrays_ufuk_dilek.py ├── br.py └── test_arrays.py ├── Week05 ├── binrep.py ├── bra_ikram_celal_keskin.py ├── bra_ufuk_dilek.py └── test_bra.py ├── Week06 ├── 16bitIEEE754.ipynb ├── convert_to_any_base.py ├── halfprecision_ikram_celal_keskin.py ├── halfprecision_ufuk_dilek.py └── test_halfprecision.py ├── Week07 └── bisection_method.py ├── Week08 └── numerical_derivative.py ├── Week09 ├── newton_raphson.py └── newton_raphson_linear_regression.py └── Week10 ├── midpoint_rule.py ├── simpsons_rule.py └── trapezoidal_rule.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/python-app-week-02.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Week02 Homework 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | paths: ['Week02/**'] 10 | pull_request: 11 | branches: [ "master" ] 12 | paths: ['Week02/**'] 13 | 14 | permissions: 15 | contents: read 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python 3.12 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: "3.12" 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | pip install flake8 pytest 32 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 33 | - name: Lint with flake8 34 | run: | 35 | # stop the build if there are Python syntax errors or undefined names 36 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 37 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 38 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 39 | - name: Test with pytest 40 | run: | 41 | pytest -q --tb=no 'Week02/test_types.py' -------------------------------------------------------------------------------- /.github/workflows/python-app-week-03.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Week03 Homework 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | paths: ['Week03/**'] 10 | pull_request: 11 | branches: [ "master" ] 12 | paths: ['Week03/**'] 13 | 14 | permissions: 15 | contents: read 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python 3.12 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: "3.12" 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | pip install flake8 pytest 32 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 33 | - name: Lint with flake8 34 | run: | 35 | # stop the build if there are Python syntax errors or undefined names 36 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 37 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 38 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 39 | - name: Test with pytest 40 | run: | 41 | pytest -q --tb=no 'Week03/test_sequences.py' -------------------------------------------------------------------------------- /.github/workflows/python-app-week-04.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Week04 Homework 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | paths: ['Week04/**'] 10 | pull_request: 11 | branches: [ "master" ] 12 | paths: ['Week04/**'] 13 | 14 | permissions: 15 | contents: read 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python 3.12 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: "3.12" 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | pip install flake8 pytest 32 | pip install numpy 33 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 34 | - name: Lint with flake8 35 | run: | 36 | # stop the build if there are Python syntax errors or undefined names 37 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 38 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 39 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 40 | - name: Test with pytest 41 | run: | 42 | pytest -v 'Week04/test_arrays.py' 43 | -------------------------------------------------------------------------------- /.github/workflows/python-app-week-05.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Week05 Homework 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | paths: ['Week05/**'] 10 | pull_request: 11 | branches: [ "master" ] 12 | paths: ['Week05/**'] 13 | 14 | permissions: 15 | contents: read 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python 3.12 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: "3.12" 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | pip install flake8 pytest 32 | pip install numpy 33 | pip install flask 34 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 35 | - name: Lint with flake8 36 | run: | 37 | # stop the build if there are Python syntax errors or undefined names 38 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 39 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 40 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 41 | - name: Test with pytest 42 | run: | 43 | pytest -v 'Week05/test_bra.py' 44 | -------------------------------------------------------------------------------- /.github/workflows/python-app-week-06.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Week06 Homework 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | paths: ['Week06/**'] 10 | pull_request: 11 | branches: [ "master" ] 12 | paths: ['Week06/**'] 13 | 14 | permissions: 15 | contents: read 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python 3.12 25 | uses: actions/setup-python@v3 26 | with: 27 | python-version: "3.12" 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | pip install flake8 pytest 32 | pip install numpy 33 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 34 | - name: Lint with flake8 35 | run: | 36 | # stop the build if there are Python syntax errors or undefined names 37 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 38 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 39 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 40 | - name: Test with pytest 41 | run: | 42 | pytest -v 'Week06/test_halfprecision.py' 43 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | MCBU CENG Department. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | First of all I want you to know that your contributions are welcome. 2 | 3 | You can commit your work every week to the folders WeekXX through the semester. 4 | 5 | Be sure that you have forked the original repository, and then create your file in your own forked repository. 6 | 7 | When you are ready to submit your file, commit your changes and then open a pull request. 8 | 9 | Your pull request will be reviewed by me and if there exist some tests will be run on your code. 10 | 11 | If there are some points that need to be changed in your code then I will send you a change request. 12 | 13 | If everything is ok, then I will merge your commit. 14 | 15 | Thanks a lot for your contributions. I hope this will be a good course for you. 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Bora Canbula 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 | -------------------------------------------------------------------------------- /LectureNotes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/canbula/NumericalAnalysis/46d4dc22170752ebf7665611e2f7a7c570105c1e/LectureNotes.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Numerical Analysis 2024 2 | Repository for Numerical Analysis course given by Assoc. Prof. Dr. Bora Canbula at Computer Engineering Department of Manisa Celal Bayar University. 3 | 4 | [![made-with-python](https://img.shields.io/badge/Made%20with-Python-1f425f.svg)](https://www.python.org/) [![MIT license](https://img.shields.io/badge/License-MIT-blue.svg)](https://lbesson.mit-license.org/) [![GitHub stars](https://badgen.net/github/stars/canbula/NumericalAnalysis/)](https://GitHub.com/canbula/NumericalAnalysis/stargazers/) [![GitHub forks](https://badgen.net/github/forks/canbula/NumericalAnalysis/)](https://GitHub.com/canbula/NumericalAnalysis/network/) [![GitHub contributors](https://img.shields.io/github/contributors/canbula/NumericalAnalysis.svg)](https://GitHub.com/canbula/NumericalAnalysis/graphs/contributors/) [![GitHub total-pull-requests](https://badgen.net/github/prs/canbula/NumericalAnalysis)](https://GitHub.com/canbula/NumericalAnalysis/pull/) [![GitHub pull-requests merged](https://badgen.net/github/merged-prs/canbula/NumericalAnalysis)](https://github.com/canbula/NumericalAnalysis/pulls?q=is%3Amerged) 5 | 6 | # Web Application for Students 7 | We built a web application in this course as a side project to help student to understand the concepts and methods better. 8 | 9 | [NUMERICALCULATOR](https://numericalculator.canbula.com) 10 | 11 | # Course Information 12 | In this course, students will learn the basic concepts of numerical analysis. 13 | In the first part of the course, students will learn the way that computers represent numbers and how to use them in calculations. 14 | In the second part, we will focus on the numerical methods for solving linear equations. 15 | In the following sections, we will learn about the numerical derivatives and integrals. 16 | In the end, we will use these skills to solve some nonlinear equations. 17 | In all applications, we will use Python to solve the problems. 18 | You can find some supplementary videos for this course on my YouTube channel. 19 | 20 | # Wiki 21 | Some concepts are emphasized in Wiki pages, you can find them in the following link. 22 | 23 | [Wiki Pages](https://github.com/canbula/NumericalAnalysis/wiki) 24 | 25 | # Weekly Content 26 | You can find the codes that written in the laboratory in the folder WeekXX. 27 | 28 | # Lecture Notes and Problem Sets 29 | In the root folder there is a LectureNotes.pdf file, which is updated weekly after every lecture. 30 | At the end of the every chapter, you will also find a Problem Set. 31 | 32 | # Homeworks 33 | Students are requested to submit their homeworks to folders WeekXX, as defined in the LectureNotes.pdf. 34 | The codes will be subject to certain GitHub action workflows to be tested automatically. 35 | 36 | # Codes and Videos from Previous Years 37 | You can change the branch to see the codes from previous years. Also there is a YouTube playlist, 38 | which includes the supplementary videos for the course as given in 2021 and 2022. 39 | 40 | [Full Course from 2021](https://youtube.com/playlist?list=PL30NBs02RsiVzlo8XXB-ox8EiJ09CDjJn&si=bsLRpWLx0qKhxFxM) 41 | 42 | [Live Sessions from 2022](https://youtube.com/playlist?list=PL30NBs02RsiVfy95E4wZV0qQk2BvOpqYv&si=s5AqijK7Bspy5FNp) 43 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | This repository will not get any security update. 6 | 7 | ## Reporting a Vulnerability 8 | 9 | If you want to report a vulnerability about this repository then contact me by sending an e-mail to bora.canbula@cbu.edu.tr 10 | -------------------------------------------------------------------------------- /Week01/NumericalAnalysisSyllabus.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/canbula/NumericalAnalysis/46d4dc22170752ebf7665611e2f7a7c570105c1e/Week01/NumericalAnalysisSyllabus.pdf -------------------------------------------------------------------------------- /Week02/first.py: -------------------------------------------------------------------------------- 1 | print("Python is the best!") 2 | -------------------------------------------------------------------------------- /Week02/literals.py: -------------------------------------------------------------------------------- 1 | print("7") 2 | print(7) 3 | print(7.0) 4 | print(7j) 5 | print(True) 6 | print(0b10) 7 | print(0o10) 8 | print(0x10) 9 | print(7.4e3) 10 | -------------------------------------------------------------------------------- /Week02/memory.py: -------------------------------------------------------------------------------- 1 | a = 5 2 | print(hex(id(a))) 3 | b = 4 4 | print(hex(id(b))) 5 | c = 3 6 | print(hex(id(c))) 7 | d = 3 8 | print(hex(id(d))) 9 | print(hex(id(2))) 10 | -------------------------------------------------------------------------------- /Week02/operations.py: -------------------------------------------------------------------------------- 1 | print(2**3) 2 | print(2**3.0) 3 | print(2.0**3) 4 | print(2.0**3.0) 5 | 6 | print(2 * 3) 7 | print(2 * 3.0) 8 | print(2.0 * 3) 9 | print(2.0 * 3.0) 10 | 11 | print(6 / 3) 12 | print(6 / 3.0) 13 | print(6.0 / 3) 14 | print(6.0 / 3.0) 15 | 16 | print(6 // 3) 17 | print(6 // 3.0) 18 | print(6.0 // 3) 19 | print(6.0 // 3.0) 20 | 21 | print(6 % 3) 22 | print(6 % 3.0) 23 | print(6.0 % 3) 24 | print(6.0 % 3.0) 25 | 26 | print(-8 + 4) 27 | print(-4.0 + 8) 28 | -------------------------------------------------------------------------------- /Week02/priorities.py: -------------------------------------------------------------------------------- 1 | print(9 % 6 % 2) 2 | print(2**2**3) 3 | print(2 * 3 % 5) 4 | print(-3 * 2) 5 | print(-2 * 3) 6 | print(-(2 * 3)) 7 | -------------------------------------------------------------------------------- /Week02/test_types.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | files = [f for f in os.listdir(os.path.dirname(__file__)) if f.startswith("types")] 5 | for f in files: 6 | exec("import " + f[:-3] + " as " + f[:-3]) 7 | print(f"The module {f[:-3]} has been imported.") 8 | 9 | 10 | def test_names(): 11 | for f in files: 12 | assert "my_int" in dir(eval(f[:-3])), "my_int is not defined in " + f[:-3] 13 | assert "my_float" in dir(eval(f[:-3])), "my_float is not defined in " + f[:-3] 14 | assert "my_bool" in dir(eval(f[:-3])), "my_bool is not defined in " + f[:-3] 15 | assert "my_complex" in dir(eval(f[:-3])), ( 16 | "my_complex is not defined in " + f[:-3] 17 | ) 18 | 19 | 20 | def test_types(): 21 | for f in files: 22 | assert isinstance(eval(f[:-3]).my_int, int), "my_int is not an int in " + f[:-3] 23 | assert isinstance(eval(f[:-3]).my_float, float), ( 24 | "my_float is not a float in " + f[:-3] 25 | ) 26 | assert isinstance(eval(f[:-3]).my_bool, bool), ( 27 | "my_bool is not a bool in " + f[:-3] 28 | ) 29 | assert isinstance(eval(f[:-3]).my_complex, complex), ( 30 | "my_complex is not a complex in " + f[:-3] 31 | ) 32 | -------------------------------------------------------------------------------- /Week02/types_ahmetyusuf_dursun.py: -------------------------------------------------------------------------------- 1 | my_int=3 2 | my_float=3.12 3 | my_bool=True 4 | my_complex=7j 5 | -------------------------------------------------------------------------------- /Week02/types_furkancan_okal.py: -------------------------------------------------------------------------------- 1 | my_int = 13 2 | my_float = 13.0 3 | my_bool = False 4 | my_complex = 13j 5 | 6 | -------------------------------------------------------------------------------- /Week02/types_ikram_celal_keskin.py: -------------------------------------------------------------------------------- 1 | my_int=19 2 | my_float=0.6 3 | my_bool=True 4 | my_complex=2000+2j 5 | 6 | -------------------------------------------------------------------------------- /Week02/types_ufuk_dilek.py: -------------------------------------------------------------------------------- 1 | #Types 2 | 3 | my_int = 1 4 | my_float = 1.0 5 | my_bool = True 6 | my_complex = 1 + 1j 7 | -------------------------------------------------------------------------------- /Week03/memory.py: -------------------------------------------------------------------------------- 1 | prev_id_ = 0 2 | for i in range(1000): 3 | s = "\n" if i % 5 == 0 else " " 4 | id_ = id(i) 5 | diff = id_ - prev_id_ 6 | print(f"{i}:{id_}", end=s) 7 | if diff > 32 and i > 1: 8 | break 9 | prev_id_ = id_ 10 | print() 11 | -------------------------------------------------------------------------------- /Week03/seq.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#### Python Sequences" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "##### Strings" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "metadata": {}, 21 | "outputs": [ 22 | { 23 | "name": "stdout", 24 | "output_type": "stream", 25 | "text": [ 26 | "Strings are sequences\n" 27 | ] 28 | } 29 | ], 30 | "source": [ 31 | "print(\"Strings are sequences\")" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": 2, 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "name = \"Numerical Analysis\"" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 9, 46 | "metadata": {}, 47 | "outputs": [ 48 | { 49 | "name": "stdout", 50 | "output_type": "stream", 51 | "text": [ 52 | "N\n", 53 | "A\n", 54 | "18\n", 55 | "s\n", 56 | "s\n", 57 | "N\n" 58 | ] 59 | } 60 | ], 61 | "source": [ 62 | "print(name[0])\n", 63 | "print(name[10])\n", 64 | "print(len(name))\n", 65 | "print(name[len(name)-1])\n", 66 | "print(name[-1])\n", 67 | "print(name[-len(name)])" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": 13, 73 | "metadata": {}, 74 | "outputs": [ 75 | { 76 | "name": "stdout", 77 | "output_type": "stream", 78 | "text": [ 79 | "Numerical\n", 80 | "Numerical\n", 81 | "Analysis\n", 82 | "Numerical Analysis\n" 83 | ] 84 | } 85 | ], 86 | "source": [ 87 | "print(name[0:9])\n", 88 | "print(name[:9])\n", 89 | "print(name[10:])\n", 90 | "print(name[:])" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": 17, 96 | "metadata": {}, 97 | "outputs": [ 98 | { 99 | "name": "stdout", 100 | "output_type": "stream", 101 | "text": [ 102 | "Nmrcl\n", 103 | "lacirem\n", 104 | "sisylanA laciremuN\n" 105 | ] 106 | } 107 | ], 108 | "source": [ 109 | "print(name[0:9:2])\n", 110 | "print(name[8:1:-1])\n", 111 | "print(name[::-1])" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 21, 117 | "metadata": {}, 118 | "outputs": [ 119 | { 120 | "name": "stdout", 121 | "output_type": "stream", 122 | "text": [ 123 | "0\n", 124 | "1\n", 125 | "2\n", 126 | "3\n", 127 | "4\n", 128 | "5\n", 129 | "6\n", 130 | "7\n", 131 | "8\n", 132 | "9\n", 133 | "------------\n", 134 | "2\n", 135 | "4\n", 136 | "6\n", 137 | "----------\n", 138 | "100\n", 139 | "75\n", 140 | "50\n", 141 | "25\n" 142 | ] 143 | } 144 | ], 145 | "source": [ 146 | "for i in range(10):\n", 147 | " print(i)\n", 148 | "\n", 149 | "print(\"------------\")\n", 150 | "for i in range(2, 8, 2):\n", 151 | " print(i)\n", 152 | "print(\"----------\")\n", 153 | "for i in range(100, 0, -25):\n", 154 | " print(i)" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 24, 160 | "metadata": {}, 161 | "outputs": [ 162 | { 163 | "name": "stdout", 164 | "output_type": "stream", 165 | "text": [ 166 | "Numerical Analysis" 167 | ] 168 | } 169 | ], 170 | "source": [ 171 | "for i in range(len(name)):\n", 172 | " print(name[i], end=\"\")" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": 25, 178 | "metadata": {}, 179 | "outputs": [ 180 | { 181 | "name": "stdout", 182 | "output_type": "stream", 183 | "text": [ 184 | "Numerical Analysis" 185 | ] 186 | } 187 | ], 188 | "source": [ 189 | "for c in name:\n", 190 | " print(c, end=\"\")" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": 30, 196 | "metadata": {}, 197 | "outputs": [ 198 | { 199 | "name": "stdout", 200 | "output_type": "stream", 201 | "text": [ 202 | "Mumerical Analysis\n" 203 | ] 204 | } 205 | ], 206 | "source": [ 207 | "name = \"M\" + name[1:]\n", 208 | "print(name)" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "#### Lists\n", 216 | "Ordered and mutable sequence of values indexed by integer numbers" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 31, 222 | "metadata": {}, 223 | "outputs": [], 224 | "source": [ 225 | "# a_list = []\n", 226 | "# a_list = list()\n", 227 | "a_list = [1, 3, 5, 7]" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": 33, 233 | "metadata": {}, 234 | "outputs": [ 235 | { 236 | "data": { 237 | "text/plain": [ 238 | "['__add__',\n", 239 | " '__class__',\n", 240 | " '__class_getitem__',\n", 241 | " '__contains__',\n", 242 | " '__delattr__',\n", 243 | " '__delitem__',\n", 244 | " '__dir__',\n", 245 | " '__doc__',\n", 246 | " '__eq__',\n", 247 | " '__format__',\n", 248 | " '__ge__',\n", 249 | " '__getattribute__',\n", 250 | " '__getitem__',\n", 251 | " '__getstate__',\n", 252 | " '__gt__',\n", 253 | " '__hash__',\n", 254 | " '__iadd__',\n", 255 | " '__imul__',\n", 256 | " '__init__',\n", 257 | " '__init_subclass__',\n", 258 | " '__iter__',\n", 259 | " '__le__',\n", 260 | " '__len__',\n", 261 | " '__lt__',\n", 262 | " '__mul__',\n", 263 | " '__ne__',\n", 264 | " '__new__',\n", 265 | " '__reduce__',\n", 266 | " '__reduce_ex__',\n", 267 | " '__repr__',\n", 268 | " '__reversed__',\n", 269 | " '__rmul__',\n", 270 | " '__setattr__',\n", 271 | " '__setitem__',\n", 272 | " '__sizeof__',\n", 273 | " '__str__',\n", 274 | " '__subclasshook__',\n", 275 | " 'append',\n", 276 | " 'clear',\n", 277 | " 'copy',\n", 278 | " 'count',\n", 279 | " 'extend',\n", 280 | " 'index',\n", 281 | " 'insert',\n", 282 | " 'pop',\n", 283 | " 'remove',\n", 284 | " 'reverse',\n", 285 | " 'sort']" 286 | ] 287 | }, 288 | "execution_count": 33, 289 | "metadata": {}, 290 | "output_type": "execute_result" 291 | } 292 | ], 293 | "source": [ 294 | "dir(a_list)" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": 35, 300 | "metadata": {}, 301 | "outputs": [ 302 | { 303 | "name": "stdout", 304 | "output_type": "stream", 305 | "text": [ 306 | "[1, 3, 5, 7, 9]\n" 307 | ] 308 | } 309 | ], 310 | "source": [ 311 | "a_list.append(9)\n", 312 | "print(a_list)" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": 37, 318 | "metadata": {}, 319 | "outputs": [ 320 | { 321 | "name": "stdout", 322 | "output_type": "stream", 323 | "text": [ 324 | "2\n" 325 | ] 326 | } 327 | ], 328 | "source": [ 329 | "a_list[1] = 2\n", 330 | "print(a_list[1])" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": 38, 336 | "metadata": {}, 337 | "outputs": [ 338 | { 339 | "name": "stdout", 340 | "output_type": "stream", 341 | "text": [ 342 | "[1, 3, 2, 5, 7, 9]\n" 343 | ] 344 | } 345 | ], 346 | "source": [ 347 | "a_list.insert(1, 3)\n", 348 | "print(a_list)" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": 39, 354 | "metadata": {}, 355 | "outputs": [ 356 | { 357 | "name": "stdout", 358 | "output_type": "stream", 359 | "text": [ 360 | "[1, 3, 2, 5, 7]\n" 361 | ] 362 | } 363 | ], 364 | "source": [ 365 | "a_list.pop()\n", 366 | "print(a_list)" 367 | ] 368 | }, 369 | { 370 | "cell_type": "code", 371 | "execution_count": 40, 372 | "metadata": {}, 373 | "outputs": [ 374 | { 375 | "data": { 376 | "text/plain": [ 377 | "2" 378 | ] 379 | }, 380 | "execution_count": 40, 381 | "metadata": {}, 382 | "output_type": "execute_result" 383 | } 384 | ], 385 | "source": [ 386 | "a_list.pop(2)" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 41, 392 | "metadata": {}, 393 | "outputs": [ 394 | { 395 | "name": "stdout", 396 | "output_type": "stream", 397 | "text": [ 398 | "[1, 3, 5, 7]\n" 399 | ] 400 | } 401 | ], 402 | "source": [ 403 | "print(a_list)" 404 | ] 405 | }, 406 | { 407 | "cell_type": "code", 408 | "execution_count": 42, 409 | "metadata": {}, 410 | "outputs": [ 411 | { 412 | "name": "stdout", 413 | "output_type": "stream", 414 | "text": [ 415 | "1\n" 416 | ] 417 | } 418 | ], 419 | "source": [ 420 | "print(a_list.count(7))" 421 | ] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "execution_count": 43, 426 | "metadata": {}, 427 | "outputs": [ 428 | { 429 | "name": "stdout", 430 | "output_type": "stream", 431 | "text": [ 432 | "[1, 3, 5, 7]\n" 433 | ] 434 | } 435 | ], 436 | "source": [ 437 | "print(a_list)" 438 | ] 439 | }, 440 | { 441 | "cell_type": "code", 442 | "execution_count": 44, 443 | "metadata": {}, 444 | "outputs": [], 445 | "source": [ 446 | "b_list = a_list" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": 45, 452 | "metadata": {}, 453 | "outputs": [ 454 | { 455 | "name": "stdout", 456 | "output_type": "stream", 457 | "text": [ 458 | "[1, 3, 5, 7]\n", 459 | "[1, 3, 5, 7]\n" 460 | ] 461 | } 462 | ], 463 | "source": [ 464 | "print(a_list)\n", 465 | "print(b_list)" 466 | ] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": 46, 471 | "metadata": {}, 472 | "outputs": [ 473 | { 474 | "name": "stdout", 475 | "output_type": "stream", 476 | "text": [ 477 | "[1, 3, 5]\n", 478 | "[1, 3, 5]\n" 479 | ] 480 | } 481 | ], 482 | "source": [ 483 | "a_list.pop()\n", 484 | "print(a_list)\n", 485 | "print(b_list)" 486 | ] 487 | }, 488 | { 489 | "cell_type": "code", 490 | "execution_count": 47, 491 | "metadata": {}, 492 | "outputs": [ 493 | { 494 | "name": "stdout", 495 | "output_type": "stream", 496 | "text": [ 497 | "[1, 3, 5]\n", 498 | "[1, 3, 5]\n", 499 | "[1, 3]\n", 500 | "[1, 3, 5]\n" 501 | ] 502 | } 503 | ], 504 | "source": [ 505 | "b_list = a_list.copy()\n", 506 | "print(a_list)\n", 507 | "print(b_list)\n", 508 | "a_list.pop()\n", 509 | "print(a_list)\n", 510 | "print(b_list)" 511 | ] 512 | }, 513 | { 514 | "cell_type": "code", 515 | "execution_count": 48, 516 | "metadata": {}, 517 | "outputs": [ 518 | { 519 | "name": "stdout", 520 | "output_type": "stream", 521 | "text": [ 522 | "[1, 3]\n", 523 | "[1, 3]\n", 524 | "[1]\n", 525 | "[1, 3]\n" 526 | ] 527 | } 528 | ], 529 | "source": [ 530 | "b_list = a_list[:]\n", 531 | "print(a_list)\n", 532 | "print(b_list)\n", 533 | "a_list.pop()\n", 534 | "print(a_list)\n", 535 | "print(b_list)" 536 | ] 537 | }, 538 | { 539 | "cell_type": "code", 540 | "execution_count": null, 541 | "metadata": {}, 542 | "outputs": [], 543 | "source": [] 544 | } 545 | ], 546 | "metadata": { 547 | "kernelspec": { 548 | "display_name": "Python 3", 549 | "language": "python", 550 | "name": "python3" 551 | }, 552 | "language_info": { 553 | "codemirror_mode": { 554 | "name": "ipython", 555 | "version": 3 556 | }, 557 | "file_extension": ".py", 558 | "mimetype": "text/x-python", 559 | "name": "python", 560 | "nbconvert_exporter": "python", 561 | "pygments_lexer": "ipython3", 562 | "version": "3.12.7" 563 | } 564 | }, 565 | "nbformat": 4, 566 | "nbformat_minor": 2 567 | } 568 | -------------------------------------------------------------------------------- /Week03/sequences_furkancan_okal.py: -------------------------------------------------------------------------------- 1 | def remove_duplicates(seq: list) -> list: 2 | if not seq: # Handle empty input 3 | return [] 4 | 5 | uniq_list = [seq[0]] 6 | index = 0 7 | for number in seq: 8 | if not uniq_list[index] == number: 9 | uniq_list.append(number) 10 | index+=1 11 | return uniq_list 12 | 13 | def list_counts(seq: list) -> dict: 14 | my_dict = {} 15 | for number in seq: 16 | if number in my_dict: 17 | my_dict[number] += 1 18 | else: 19 | my_dict[number] = 1 20 | return my_dict 21 | 22 | def reverse_dict(d: dict) -> dict: 23 | reversed_dict = {} 24 | for k,v in d.items(): 25 | reversed_dict[v] = k 26 | return reversed_dict 27 | -------------------------------------------------------------------------------- /Week03/sequences_ikram_celal_keskin.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def remove_duplicates(seq:list) -> list: 4 | ''' 5 | This function removes duplicates from a list 6 | Args: 7 | seq (list): Input list with potential duplicates 8 | 9 | Returns: 10 | list (list): List with duplicates removed 11 | ''' 12 | return list(set(seq)) 13 | 14 | def list_counts(seq:list) -> dict: 15 | ''' 16 | This function counts the occurences of each element in a list 17 | 18 | Args: 19 | seq (list): Input list to count occurences of each element 20 | 21 | Returns: 22 | dict (dict): Dictionary with elements as keys and occurences as values 23 | 24 | ''' 25 | count={} 26 | 27 | for i in seq: 28 | count[i]=seq.count(i) 29 | 30 | return count 31 | #{i: seq.count(i) for i in seq} 32 | 33 | def reverse_dict(d:dict) -> dict: 34 | ''' 35 | This function reverses the keys and values of a dictionary 36 | 37 | Args: 38 | d (dict): Input dictionary to reverse keys and values 39 | 40 | Returns: 41 | dict (dict): Dictionary with keys and values reversed 42 | ''' 43 | 44 | reversed={} 45 | 46 | for key, value in d.items(): 47 | reversed[value] = key 48 | 49 | return reversed 50 | #return {v: k for k, v in d.items()} -------------------------------------------------------------------------------- /Week03/sequences_ufuk_dilek.py: -------------------------------------------------------------------------------- 1 | 2 | def remove_duplicates(seq: list) -> list: 3 | return list(set(seq)) 4 | 5 | 6 | def list_counts(seq: list) -> dict: 7 | result = dict.fromkeys(seq, 0) 8 | for i in seq: 9 | result[i] += 1 10 | return result 11 | 12 | 13 | def reverse_dict(d: dict) -> dict: 14 | result = {} 15 | for i in d.items(): 16 | result[i[1]] = i[0] 17 | return result 18 | -------------------------------------------------------------------------------- /Week03/test_sequences.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | files = [f for f in os.listdir(os.path.dirname(__file__)) if f.startswith("sequences")] 5 | for f in files: 6 | exec("import " + f[:-3] + " as " + f[:-3]) 7 | print(f"The module {f[:-3]} has been imported.") 8 | 9 | 10 | def test_names(): 11 | for f in files: 12 | assert "remove_duplicates" in dir(eval(f[:-3])), ( 13 | "remove_duplicates is not defined in " + f[:-3] 14 | ) 15 | assert "list_counts" in dir(eval(f[:-3])), ( 16 | "list_counts is not defined in " + f[:-3] 17 | ) 18 | assert "reverse_dict" in dir(eval(f[:-3])), ( 19 | "reverse_dict is not defined in " + f[:-3] 20 | ) 21 | 22 | 23 | def test_types(): 24 | for f in files: 25 | assert callable(eval(f[:-3]).remove_duplicates), ( 26 | "remove_duplicates is not callable in " + f[:-3] 27 | ) 28 | assert callable(eval(f[:-3]).list_counts), ( 29 | "list_counts is not callable in " + f[:-3] 30 | ) 31 | assert callable(eval(f[:-3]).reverse_dict), ( 32 | "reverse_dict is not callable in " + f[:-3] 33 | ) 34 | assert isinstance(eval(f[:-3]).remove_duplicates([1, 2, 3, 4, 5, 6]), list), ( 35 | "remove_duplicates is not returning a list in " + f[:-3] 36 | ) 37 | assert isinstance(eval(f[:-3]).list_counts([1, 2, 3, 4, 5, 6]), dict), ( 38 | "list_counts is not returning a dict in " + f[:-3] 39 | ) 40 | assert isinstance(eval(f[:-3]).reverse_dict({1: 1, 2: 2, 3: 3}), dict), ( 41 | "reverse_dict is not returning a dict in " + f[:-3] 42 | ) 43 | 44 | 45 | def test_remove_duplicates(): 46 | for f in files: 47 | assert eval(f[:-3]).remove_duplicates([1, 2, 3, 3, 4, 5, 5, 5, 6]) == [ 48 | 1, 49 | 2, 50 | 3, 51 | 4, 52 | 5, 53 | 6, 54 | ], ( 55 | "remove_duplicates is not working in " + f[:-3] 56 | ) 57 | assert eval(f[:-3]).remove_duplicates([1, 2, 3, 4, 5, 6]) == [ 58 | 1, 59 | 2, 60 | 3, 61 | 4, 62 | 5, 63 | 6, 64 | ], ( 65 | "remove_duplicates is not working in " + f[:-3] 66 | ) 67 | assert eval(f[:-3]).remove_duplicates([1, 1, 1, 1, 1, 1]) == [1], ( 68 | "remove_duplicates is not working in " + f[:-3] 69 | ) 70 | assert eval(f[:-3]).remove_duplicates([]) == [], ( 71 | "remove_duplicates is not working in " + f[:-3] 72 | ) 73 | 74 | 75 | def test_list_counts(): 76 | for f in files: 77 | assert eval(f[:-3]).list_counts([1, 2, 3, 3, 4, 5, 5, 5, 6]) == { 78 | 1: 1, 79 | 2: 1, 80 | 3: 2, 81 | 4: 1, 82 | 5: 3, 83 | 6: 1, 84 | }, ( 85 | "list_counts is not working in " + f[:-3] 86 | ) 87 | assert eval(f[:-3]).list_counts([1, 2, 3, 4, 5, 6]) == { 88 | 1: 1, 89 | 2: 1, 90 | 3: 1, 91 | 4: 1, 92 | 5: 1, 93 | 6: 1, 94 | }, ( 95 | "list_counts is not working in " + f[:-3] 96 | ) 97 | assert eval(f[:-3]).list_counts([1, 1, 1, 1, 1, 1]) == {1: 6}, ( 98 | "list_counts is not working in " + f[:-3] 99 | ) 100 | assert eval(f[:-3]).list_counts([]) == {}, ( 101 | "list_counts is not working in " + f[:-3] 102 | ) 103 | 104 | 105 | def test_reverse_dict(): 106 | for f in files: 107 | assert eval(f[:-3]).reverse_dict({1: 1, 2: 2, 3: 3}) == {1: 1, 2: 2, 3: 3}, ( 108 | "reverse_dict is not working in " + f[:-3] 109 | ) 110 | assert eval(f[:-3]).reverse_dict({1: 2, 2: 3, 3: 4}) == {2: 1, 3: 2, 4: 3}, ( 111 | "reverse_dict is not working in " + f[:-3] 112 | ) 113 | assert eval(f[:-3]).reverse_dict({1: 1, 2: 1, 3: 1}) == {1: 3}, ( 114 | "reverse_dict is not working in " + f[:-3] 115 | ) 116 | assert eval(f[:-3]).reverse_dict({}) == {}, ( 117 | "reverse_dict is not working in " + f[:-3] 118 | ) 119 | -------------------------------------------------------------------------------- /Week03/try_numpy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## NumPy for Numerical Analysis\n", 8 | "NumPy: Numeric Python (numpy.org)" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 2, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "# pip install numpy\n", 18 | "# pip3 install numpy\n", 19 | "# python -m pip install numpy\n", 20 | "# python3 -m pip install numpy\n", 21 | "# py -m pip install numpy\n", 22 | "# !pip install numpy\n", 23 | "\n", 24 | "import numpy as np" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 3, 30 | "metadata": {}, 31 | "outputs": [ 32 | { 33 | "data": { 34 | "text/plain": [ 35 | "['ALLOW_THREADS',\n", 36 | " 'BUFSIZE',\n", 37 | " 'CLIP',\n", 38 | " 'DataSource',\n", 39 | " 'ERR_CALL',\n", 40 | " 'ERR_DEFAULT',\n", 41 | " 'ERR_IGNORE',\n", 42 | " 'ERR_LOG',\n", 43 | " 'ERR_PRINT',\n", 44 | " 'ERR_RAISE',\n", 45 | " 'ERR_WARN',\n", 46 | " 'FLOATING_POINT_SUPPORT',\n", 47 | " 'FPE_DIVIDEBYZERO',\n", 48 | " 'FPE_INVALID',\n", 49 | " 'FPE_OVERFLOW',\n", 50 | " 'FPE_UNDERFLOW',\n", 51 | " 'False_',\n", 52 | " 'Inf',\n", 53 | " 'Infinity',\n", 54 | " 'MAXDIMS',\n", 55 | " 'MAY_SHARE_BOUNDS',\n", 56 | " 'MAY_SHARE_EXACT',\n", 57 | " 'NAN',\n", 58 | " 'NINF',\n", 59 | " 'NZERO',\n", 60 | " 'NaN',\n", 61 | " 'PINF',\n", 62 | " 'PZERO',\n", 63 | " 'RAISE',\n", 64 | " 'RankWarning',\n", 65 | " 'SHIFT_DIVIDEBYZERO',\n", 66 | " 'SHIFT_INVALID',\n", 67 | " 'SHIFT_OVERFLOW',\n", 68 | " 'SHIFT_UNDERFLOW',\n", 69 | " 'ScalarType',\n", 70 | " 'True_',\n", 71 | " 'UFUNC_BUFSIZE_DEFAULT',\n", 72 | " 'UFUNC_PYVALS_NAME',\n", 73 | " 'WRAP',\n", 74 | " '_CopyMode',\n", 75 | " '_NoValue',\n", 76 | " '_UFUNC_API',\n", 77 | " '__NUMPY_SETUP__',\n", 78 | " '__all__',\n", 79 | " '__builtins__',\n", 80 | " '__cached__',\n", 81 | " '__config__',\n", 82 | " '__deprecated_attrs__',\n", 83 | " '__dir__',\n", 84 | " '__doc__',\n", 85 | " '__expired_functions__',\n", 86 | " '__file__',\n", 87 | " '__former_attrs__',\n", 88 | " '__future_scalars__',\n", 89 | " '__getattr__',\n", 90 | " '__loader__',\n", 91 | " '__name__',\n", 92 | " '__package__',\n", 93 | " '__path__',\n", 94 | " '__spec__',\n", 95 | " '__version__',\n", 96 | " '_add_newdoc_ufunc',\n", 97 | " '_builtins',\n", 98 | " '_distributor_init',\n", 99 | " '_financial_names',\n", 100 | " '_get_promotion_state',\n", 101 | " '_globals',\n", 102 | " '_int_extended_msg',\n", 103 | " '_mat',\n", 104 | " '_no_nep50_warning',\n", 105 | " '_pyinstaller_hooks_dir',\n", 106 | " '_pytesttester',\n", 107 | " '_set_promotion_state',\n", 108 | " '_specific_msg',\n", 109 | " '_typing',\n", 110 | " '_using_numpy2_behavior',\n", 111 | " '_utils',\n", 112 | " 'abs',\n", 113 | " 'absolute',\n", 114 | " 'add',\n", 115 | " 'add_docstring',\n", 116 | " 'add_newdoc',\n", 117 | " 'add_newdoc_ufunc',\n", 118 | " 'all',\n", 119 | " 'allclose',\n", 120 | " 'alltrue',\n", 121 | " 'amax',\n", 122 | " 'amin',\n", 123 | " 'angle',\n", 124 | " 'any',\n", 125 | " 'append',\n", 126 | " 'apply_along_axis',\n", 127 | " 'apply_over_axes',\n", 128 | " 'arange',\n", 129 | " 'arccos',\n", 130 | " 'arccosh',\n", 131 | " 'arcsin',\n", 132 | " 'arcsinh',\n", 133 | " 'arctan',\n", 134 | " 'arctan2',\n", 135 | " 'arctanh',\n", 136 | " 'argmax',\n", 137 | " 'argmin',\n", 138 | " 'argpartition',\n", 139 | " 'argsort',\n", 140 | " 'argwhere',\n", 141 | " 'around',\n", 142 | " 'array',\n", 143 | " 'array2string',\n", 144 | " 'array_equal',\n", 145 | " 'array_equiv',\n", 146 | " 'array_repr',\n", 147 | " 'array_split',\n", 148 | " 'array_str',\n", 149 | " 'asanyarray',\n", 150 | " 'asarray',\n", 151 | " 'asarray_chkfinite',\n", 152 | " 'ascontiguousarray',\n", 153 | " 'asfarray',\n", 154 | " 'asfortranarray',\n", 155 | " 'asmatrix',\n", 156 | " 'atleast_1d',\n", 157 | " 'atleast_2d',\n", 158 | " 'atleast_3d',\n", 159 | " 'average',\n", 160 | " 'bartlett',\n", 161 | " 'base_repr',\n", 162 | " 'binary_repr',\n", 163 | " 'bincount',\n", 164 | " 'bitwise_and',\n", 165 | " 'bitwise_not',\n", 166 | " 'bitwise_or',\n", 167 | " 'bitwise_xor',\n", 168 | " 'blackman',\n", 169 | " 'block',\n", 170 | " 'bmat',\n", 171 | " 'bool_',\n", 172 | " 'broadcast',\n", 173 | " 'broadcast_arrays',\n", 174 | " 'broadcast_shapes',\n", 175 | " 'broadcast_to',\n", 176 | " 'busday_count',\n", 177 | " 'busday_offset',\n", 178 | " 'busdaycalendar',\n", 179 | " 'byte',\n", 180 | " 'byte_bounds',\n", 181 | " 'bytes_',\n", 182 | " 'c_',\n", 183 | " 'can_cast',\n", 184 | " 'cast',\n", 185 | " 'cbrt',\n", 186 | " 'cdouble',\n", 187 | " 'ceil',\n", 188 | " 'cfloat',\n", 189 | " 'char',\n", 190 | " 'character',\n", 191 | " 'chararray',\n", 192 | " 'choose',\n", 193 | " 'clip',\n", 194 | " 'clongdouble',\n", 195 | " 'clongfloat',\n", 196 | " 'column_stack',\n", 197 | " 'common_type',\n", 198 | " 'compare_chararrays',\n", 199 | " 'compat',\n", 200 | " 'complex128',\n", 201 | " 'complex64',\n", 202 | " 'complex_',\n", 203 | " 'complexfloating',\n", 204 | " 'compress',\n", 205 | " 'concatenate',\n", 206 | " 'conj',\n", 207 | " 'conjugate',\n", 208 | " 'convolve',\n", 209 | " 'copy',\n", 210 | " 'copysign',\n", 211 | " 'copyto',\n", 212 | " 'corrcoef',\n", 213 | " 'correlate',\n", 214 | " 'cos',\n", 215 | " 'cosh',\n", 216 | " 'count_nonzero',\n", 217 | " 'cov',\n", 218 | " 'cross',\n", 219 | " 'csingle',\n", 220 | " 'ctypeslib',\n", 221 | " 'cumprod',\n", 222 | " 'cumproduct',\n", 223 | " 'cumsum',\n", 224 | " 'datetime64',\n", 225 | " 'datetime_as_string',\n", 226 | " 'datetime_data',\n", 227 | " 'deg2rad',\n", 228 | " 'degrees',\n", 229 | " 'delete',\n", 230 | " 'deprecate',\n", 231 | " 'deprecate_with_doc',\n", 232 | " 'diag',\n", 233 | " 'diag_indices',\n", 234 | " 'diag_indices_from',\n", 235 | " 'diagflat',\n", 236 | " 'diagonal',\n", 237 | " 'diff',\n", 238 | " 'digitize',\n", 239 | " 'disp',\n", 240 | " 'divide',\n", 241 | " 'divmod',\n", 242 | " 'dot',\n", 243 | " 'double',\n", 244 | " 'dsplit',\n", 245 | " 'dstack',\n", 246 | " 'dtype',\n", 247 | " 'dtypes',\n", 248 | " 'e',\n", 249 | " 'ediff1d',\n", 250 | " 'einsum',\n", 251 | " 'einsum_path',\n", 252 | " 'emath',\n", 253 | " 'empty',\n", 254 | " 'empty_like',\n", 255 | " 'equal',\n", 256 | " 'errstate',\n", 257 | " 'euler_gamma',\n", 258 | " 'exceptions',\n", 259 | " 'exp',\n", 260 | " 'exp2',\n", 261 | " 'expand_dims',\n", 262 | " 'expm1',\n", 263 | " 'extract',\n", 264 | " 'eye',\n", 265 | " 'fabs',\n", 266 | " 'fastCopyAndTranspose',\n", 267 | " 'fft',\n", 268 | " 'fill_diagonal',\n", 269 | " 'find_common_type',\n", 270 | " 'finfo',\n", 271 | " 'fix',\n", 272 | " 'flatiter',\n", 273 | " 'flatnonzero',\n", 274 | " 'flexible',\n", 275 | " 'flip',\n", 276 | " 'fliplr',\n", 277 | " 'flipud',\n", 278 | " 'float16',\n", 279 | " 'float32',\n", 280 | " 'float64',\n", 281 | " 'float_',\n", 282 | " 'float_power',\n", 283 | " 'floating',\n", 284 | " 'floor',\n", 285 | " 'floor_divide',\n", 286 | " 'fmax',\n", 287 | " 'fmin',\n", 288 | " 'fmod',\n", 289 | " 'format_float_positional',\n", 290 | " 'format_float_scientific',\n", 291 | " 'format_parser',\n", 292 | " 'frexp',\n", 293 | " 'from_dlpack',\n", 294 | " 'frombuffer',\n", 295 | " 'fromfile',\n", 296 | " 'fromfunction',\n", 297 | " 'fromiter',\n", 298 | " 'frompyfunc',\n", 299 | " 'fromregex',\n", 300 | " 'fromstring',\n", 301 | " 'full',\n", 302 | " 'full_like',\n", 303 | " 'gcd',\n", 304 | " 'generic',\n", 305 | " 'genfromtxt',\n", 306 | " 'geomspace',\n", 307 | " 'get_array_wrap',\n", 308 | " 'get_include',\n", 309 | " 'get_printoptions',\n", 310 | " 'getbufsize',\n", 311 | " 'geterr',\n", 312 | " 'geterrcall',\n", 313 | " 'geterrobj',\n", 314 | " 'gradient',\n", 315 | " 'greater',\n", 316 | " 'greater_equal',\n", 317 | " 'half',\n", 318 | " 'hamming',\n", 319 | " 'hanning',\n", 320 | " 'heaviside',\n", 321 | " 'histogram',\n", 322 | " 'histogram2d',\n", 323 | " 'histogram_bin_edges',\n", 324 | " 'histogramdd',\n", 325 | " 'hsplit',\n", 326 | " 'hstack',\n", 327 | " 'hypot',\n", 328 | " 'i0',\n", 329 | " 'identity',\n", 330 | " 'iinfo',\n", 331 | " 'imag',\n", 332 | " 'in1d',\n", 333 | " 'index_exp',\n", 334 | " 'indices',\n", 335 | " 'inexact',\n", 336 | " 'inf',\n", 337 | " 'info',\n", 338 | " 'infty',\n", 339 | " 'inner',\n", 340 | " 'insert',\n", 341 | " 'int16',\n", 342 | " 'int32',\n", 343 | " 'int64',\n", 344 | " 'int8',\n", 345 | " 'int_',\n", 346 | " 'intc',\n", 347 | " 'integer',\n", 348 | " 'interp',\n", 349 | " 'intersect1d',\n", 350 | " 'intp',\n", 351 | " 'invert',\n", 352 | " 'is_busday',\n", 353 | " 'isclose',\n", 354 | " 'iscomplex',\n", 355 | " 'iscomplexobj',\n", 356 | " 'isfinite',\n", 357 | " 'isfortran',\n", 358 | " 'isin',\n", 359 | " 'isinf',\n", 360 | " 'isnan',\n", 361 | " 'isnat',\n", 362 | " 'isneginf',\n", 363 | " 'isposinf',\n", 364 | " 'isreal',\n", 365 | " 'isrealobj',\n", 366 | " 'isscalar',\n", 367 | " 'issctype',\n", 368 | " 'issubclass_',\n", 369 | " 'issubdtype',\n", 370 | " 'issubsctype',\n", 371 | " 'iterable',\n", 372 | " 'ix_',\n", 373 | " 'kaiser',\n", 374 | " 'kron',\n", 375 | " 'lcm',\n", 376 | " 'ldexp',\n", 377 | " 'left_shift',\n", 378 | " 'less',\n", 379 | " 'less_equal',\n", 380 | " 'lexsort',\n", 381 | " 'lib',\n", 382 | " 'linalg',\n", 383 | " 'linspace',\n", 384 | " 'little_endian',\n", 385 | " 'load',\n", 386 | " 'loadtxt',\n", 387 | " 'log',\n", 388 | " 'log10',\n", 389 | " 'log1p',\n", 390 | " 'log2',\n", 391 | " 'logaddexp',\n", 392 | " 'logaddexp2',\n", 393 | " 'logical_and',\n", 394 | " 'logical_not',\n", 395 | " 'logical_or',\n", 396 | " 'logical_xor',\n", 397 | " 'logspace',\n", 398 | " 'longcomplex',\n", 399 | " 'longdouble',\n", 400 | " 'longfloat',\n", 401 | " 'longlong',\n", 402 | " 'lookfor',\n", 403 | " 'ma',\n", 404 | " 'mask_indices',\n", 405 | " 'mat',\n", 406 | " 'matmul',\n", 407 | " 'matrix',\n", 408 | " 'max',\n", 409 | " 'maximum',\n", 410 | " 'maximum_sctype',\n", 411 | " 'may_share_memory',\n", 412 | " 'mean',\n", 413 | " 'median',\n", 414 | " 'memmap',\n", 415 | " 'meshgrid',\n", 416 | " 'mgrid',\n", 417 | " 'min',\n", 418 | " 'min_scalar_type',\n", 419 | " 'minimum',\n", 420 | " 'mintypecode',\n", 421 | " 'mod',\n", 422 | " 'modf',\n", 423 | " 'moveaxis',\n", 424 | " 'msort',\n", 425 | " 'multiply',\n", 426 | " 'nan',\n", 427 | " 'nan_to_num',\n", 428 | " 'nanargmax',\n", 429 | " 'nanargmin',\n", 430 | " 'nancumprod',\n", 431 | " 'nancumsum',\n", 432 | " 'nanmax',\n", 433 | " 'nanmean',\n", 434 | " 'nanmedian',\n", 435 | " 'nanmin',\n", 436 | " 'nanpercentile',\n", 437 | " 'nanprod',\n", 438 | " 'nanquantile',\n", 439 | " 'nanstd',\n", 440 | " 'nansum',\n", 441 | " 'nanvar',\n", 442 | " 'nbytes',\n", 443 | " 'ndarray',\n", 444 | " 'ndenumerate',\n", 445 | " 'ndim',\n", 446 | " 'ndindex',\n", 447 | " 'nditer',\n", 448 | " 'negative',\n", 449 | " 'nested_iters',\n", 450 | " 'newaxis',\n", 451 | " 'nextafter',\n", 452 | " 'nonzero',\n", 453 | " 'not_equal',\n", 454 | " 'numarray',\n", 455 | " 'number',\n", 456 | " 'obj2sctype',\n", 457 | " 'object_',\n", 458 | " 'ogrid',\n", 459 | " 'oldnumeric',\n", 460 | " 'ones',\n", 461 | " 'ones_like',\n", 462 | " 'outer',\n", 463 | " 'packbits',\n", 464 | " 'pad',\n", 465 | " 'partition',\n", 466 | " 'percentile',\n", 467 | " 'pi',\n", 468 | " 'piecewise',\n", 469 | " 'place',\n", 470 | " 'poly',\n", 471 | " 'poly1d',\n", 472 | " 'polyadd',\n", 473 | " 'polyder',\n", 474 | " 'polydiv',\n", 475 | " 'polyfit',\n", 476 | " 'polyint',\n", 477 | " 'polymul',\n", 478 | " 'polynomial',\n", 479 | " 'polysub',\n", 480 | " 'polyval',\n", 481 | " 'positive',\n", 482 | " 'power',\n", 483 | " 'printoptions',\n", 484 | " 'prod',\n", 485 | " 'product',\n", 486 | " 'promote_types',\n", 487 | " 'ptp',\n", 488 | " 'put',\n", 489 | " 'put_along_axis',\n", 490 | " 'putmask',\n", 491 | " 'quantile',\n", 492 | " 'r_',\n", 493 | " 'rad2deg',\n", 494 | " 'radians',\n", 495 | " 'random',\n", 496 | " 'ravel',\n", 497 | " 'ravel_multi_index',\n", 498 | " 'real',\n", 499 | " 'real_if_close',\n", 500 | " 'rec',\n", 501 | " 'recarray',\n", 502 | " 'recfromcsv',\n", 503 | " 'recfromtxt',\n", 504 | " 'reciprocal',\n", 505 | " 'record',\n", 506 | " 'remainder',\n", 507 | " 'repeat',\n", 508 | " 'require',\n", 509 | " 'reshape',\n", 510 | " 'resize',\n", 511 | " 'result_type',\n", 512 | " 'right_shift',\n", 513 | " 'rint',\n", 514 | " 'roll',\n", 515 | " 'rollaxis',\n", 516 | " 'roots',\n", 517 | " 'rot90',\n", 518 | " 'round',\n", 519 | " 'round_',\n", 520 | " 'row_stack',\n", 521 | " 's_',\n", 522 | " 'safe_eval',\n", 523 | " 'save',\n", 524 | " 'savetxt',\n", 525 | " 'savez',\n", 526 | " 'savez_compressed',\n", 527 | " 'sctype2char',\n", 528 | " 'sctypeDict',\n", 529 | " 'sctypes',\n", 530 | " 'searchsorted',\n", 531 | " 'select',\n", 532 | " 'set_numeric_ops',\n", 533 | " 'set_printoptions',\n", 534 | " 'set_string_function',\n", 535 | " 'setbufsize',\n", 536 | " 'setdiff1d',\n", 537 | " 'seterr',\n", 538 | " 'seterrcall',\n", 539 | " 'seterrobj',\n", 540 | " 'setxor1d',\n", 541 | " 'shape',\n", 542 | " 'shares_memory',\n", 543 | " 'short',\n", 544 | " 'show_config',\n", 545 | " 'show_runtime',\n", 546 | " 'sign',\n", 547 | " 'signbit',\n", 548 | " 'signedinteger',\n", 549 | " 'sin',\n", 550 | " 'sinc',\n", 551 | " 'single',\n", 552 | " 'singlecomplex',\n", 553 | " 'sinh',\n", 554 | " 'size',\n", 555 | " 'sometrue',\n", 556 | " 'sort',\n", 557 | " 'sort_complex',\n", 558 | " 'source',\n", 559 | " 'spacing',\n", 560 | " 'split',\n", 561 | " 'sqrt',\n", 562 | " 'square',\n", 563 | " 'squeeze',\n", 564 | " 'stack',\n", 565 | " 'std',\n", 566 | " 'str_',\n", 567 | " 'string_',\n", 568 | " 'subtract',\n", 569 | " 'sum',\n", 570 | " 'swapaxes',\n", 571 | " 'take',\n", 572 | " 'take_along_axis',\n", 573 | " 'tan',\n", 574 | " 'tanh',\n", 575 | " 'tensordot',\n", 576 | " 'test',\n", 577 | " 'testing',\n", 578 | " 'tile',\n", 579 | " 'timedelta64',\n", 580 | " 'trace',\n", 581 | " 'tracemalloc_domain',\n", 582 | " 'transpose',\n", 583 | " 'trapz',\n", 584 | " 'tri',\n", 585 | " 'tril',\n", 586 | " 'tril_indices',\n", 587 | " 'tril_indices_from',\n", 588 | " 'trim_zeros',\n", 589 | " 'triu',\n", 590 | " 'triu_indices',\n", 591 | " 'triu_indices_from',\n", 592 | " 'true_divide',\n", 593 | " 'trunc',\n", 594 | " 'typecodes',\n", 595 | " 'typename',\n", 596 | " 'ubyte',\n", 597 | " 'ufunc',\n", 598 | " 'uint',\n", 599 | " 'uint16',\n", 600 | " 'uint32',\n", 601 | " 'uint64',\n", 602 | " 'uint8',\n", 603 | " 'uintc',\n", 604 | " 'uintp',\n", 605 | " 'ulonglong',\n", 606 | " 'unicode_',\n", 607 | " 'union1d',\n", 608 | " 'unique',\n", 609 | " 'unpackbits',\n", 610 | " 'unravel_index',\n", 611 | " 'unsignedinteger',\n", 612 | " 'unwrap',\n", 613 | " 'ushort',\n", 614 | " 'vander',\n", 615 | " 'var',\n", 616 | " 'vdot',\n", 617 | " 'vectorize',\n", 618 | " 'version',\n", 619 | " 'void',\n", 620 | " 'vsplit',\n", 621 | " 'vstack',\n", 622 | " 'where',\n", 623 | " 'who',\n", 624 | " 'zeros',\n", 625 | " 'zeros_like']" 626 | ] 627 | }, 628 | "execution_count": 3, 629 | "metadata": {}, 630 | "output_type": "execute_result" 631 | } 632 | ], 633 | "source": [ 634 | "dir(np)" 635 | ] 636 | }, 637 | { 638 | "cell_type": "code", 639 | "execution_count": 4, 640 | "metadata": {}, 641 | "outputs": [ 642 | { 643 | "name": "stdout", 644 | "output_type": "stream", 645 | "text": [ 646 | "Help on built-in function arange in module numpy:\n", 647 | "\n", 648 | "arange(...)\n", 649 | " arange([start,] stop[, step,], dtype=None, *, like=None)\n", 650 | "\n", 651 | " Return evenly spaced values within a given interval.\n", 652 | "\n", 653 | " ``arange`` can be called with a varying number of positional arguments:\n", 654 | "\n", 655 | " * ``arange(stop)``: Values are generated within the half-open interval\n", 656 | " ``[0, stop)`` (in other words, the interval including `start` but\n", 657 | " excluding `stop`).\n", 658 | " * ``arange(start, stop)``: Values are generated within the half-open\n", 659 | " interval ``[start, stop)``.\n", 660 | " * ``arange(start, stop, step)`` Values are generated within the half-open\n", 661 | " interval ``[start, stop)``, with spacing between values given by\n", 662 | " ``step``.\n", 663 | "\n", 664 | " For integer arguments the function is roughly equivalent to the Python\n", 665 | " built-in :py:class:`range`, but returns an ndarray rather than a ``range``\n", 666 | " instance.\n", 667 | "\n", 668 | " When using a non-integer step, such as 0.1, it is often better to use\n", 669 | " `numpy.linspace`.\n", 670 | "\n", 671 | " See the Warning sections below for more information.\n", 672 | "\n", 673 | " Parameters\n", 674 | " ----------\n", 675 | " start : integer or real, optional\n", 676 | " Start of interval. The interval includes this value. The default\n", 677 | " start value is 0.\n", 678 | " stop : integer or real\n", 679 | " End of interval. The interval does not include this value, except\n", 680 | " in some cases where `step` is not an integer and floating point\n", 681 | " round-off affects the length of `out`.\n", 682 | " step : integer or real, optional\n", 683 | " Spacing between values. For any output `out`, this is the distance\n", 684 | " between two adjacent values, ``out[i+1] - out[i]``. The default\n", 685 | " step size is 1. If `step` is specified as a position argument,\n", 686 | " `start` must also be given.\n", 687 | " dtype : dtype, optional\n", 688 | " The type of the output array. If `dtype` is not given, infer the data\n", 689 | " type from the other input arguments.\n", 690 | " like : array_like, optional\n", 691 | " Reference object to allow the creation of arrays which are not\n", 692 | " NumPy arrays. If an array-like passed in as ``like`` supports\n", 693 | " the ``__array_function__`` protocol, the result will be defined\n", 694 | " by it. In this case, it ensures the creation of an array object\n", 695 | " compatible with that passed in via this argument.\n", 696 | "\n", 697 | " .. versionadded:: 1.20.0\n", 698 | "\n", 699 | " Returns\n", 700 | " -------\n", 701 | " arange : ndarray\n", 702 | " Array of evenly spaced values.\n", 703 | "\n", 704 | " For floating point arguments, the length of the result is\n", 705 | " ``ceil((stop - start)/step)``. Because of floating point overflow,\n", 706 | " this rule may result in the last element of `out` being greater\n", 707 | " than `stop`.\n", 708 | "\n", 709 | " Warnings\n", 710 | " --------\n", 711 | " The length of the output might not be numerically stable.\n", 712 | "\n", 713 | " Another stability issue is due to the internal implementation of\n", 714 | " `numpy.arange`.\n", 715 | " The actual step value used to populate the array is\n", 716 | " ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss\n", 717 | " can occur here, due to casting or due to using floating points when\n", 718 | " `start` is much larger than `step`. This can lead to unexpected\n", 719 | " behaviour. For example::\n", 720 | "\n", 721 | " >>> np.arange(0, 5, 0.5, dtype=int)\n", 722 | " array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n", 723 | " >>> np.arange(-3, 3, 0.5, dtype=int)\n", 724 | " array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])\n", 725 | "\n", 726 | " In such cases, the use of `numpy.linspace` should be preferred.\n", 727 | "\n", 728 | " The built-in :py:class:`range` generates :std:doc:`Python built-in integers\n", 729 | " that have arbitrary size `, while `numpy.arange`\n", 730 | " produces `numpy.int32` or `numpy.int64` numbers. This may result in\n", 731 | " incorrect results for large integer values::\n", 732 | "\n", 733 | " >>> power = 40\n", 734 | " >>> modulo = 10000\n", 735 | " >>> x1 = [(n ** power) % modulo for n in range(8)]\n", 736 | " >>> x2 = [(n ** power) % modulo for n in np.arange(8)]\n", 737 | " >>> print(x1)\n", 738 | " [0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct\n", 739 | " >>> print(x2)\n", 740 | " [0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect\n", 741 | "\n", 742 | " See Also\n", 743 | " --------\n", 744 | " numpy.linspace : Evenly spaced numbers with careful handling of endpoints.\n", 745 | " numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.\n", 746 | " numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.\n", 747 | " :ref:`how-to-partition`\n", 748 | "\n", 749 | " Examples\n", 750 | " --------\n", 751 | " >>> np.arange(3)\n", 752 | " array([0, 1, 2])\n", 753 | " >>> np.arange(3.0)\n", 754 | " array([ 0., 1., 2.])\n", 755 | " >>> np.arange(3,7)\n", 756 | " array([3, 4, 5, 6])\n", 757 | " >>> np.arange(3,7,2)\n", 758 | " array([3, 5])\n", 759 | "\n" 760 | ] 761 | } 762 | ], 763 | "source": [ 764 | "help(np.arange)" 765 | ] 766 | }, 767 | { 768 | "cell_type": "code", 769 | "execution_count": 6, 770 | "metadata": {}, 771 | "outputs": [ 772 | { 773 | "name": "stdout", 774 | "output_type": "stream", 775 | "text": [ 776 | "[0 1 2 3 4 5 6 7 8 9]\n", 777 | "\n" 778 | ] 779 | } 780 | ], 781 | "source": [ 782 | "an_array = np.arange(10)\n", 783 | "print(an_array)\n", 784 | "print(type(an_array))" 785 | ] 786 | }, 787 | { 788 | "cell_type": "code", 789 | "execution_count": 7, 790 | "metadata": {}, 791 | "outputs": [], 792 | "source": [ 793 | "python_list = [i for i in range(10000)]\n", 794 | "numpy_array = np.arange(10000)" 795 | ] 796 | }, 797 | { 798 | "cell_type": "code", 799 | "execution_count": 12, 800 | "metadata": {}, 801 | "outputs": [ 802 | { 803 | "data": { 804 | "text/plain": [ 805 | "49995000" 806 | ] 807 | }, 808 | "execution_count": 12, 809 | "metadata": {}, 810 | "output_type": "execute_result" 811 | } 812 | ], 813 | "source": [ 814 | "sum(python_list)" 815 | ] 816 | }, 817 | { 818 | "cell_type": "code", 819 | "execution_count": 13, 820 | "metadata": {}, 821 | "outputs": [ 822 | { 823 | "data": { 824 | "text/plain": [ 825 | "49995000" 826 | ] 827 | }, 828 | "execution_count": 13, 829 | "metadata": {}, 830 | "output_type": "execute_result" 831 | } 832 | ], 833 | "source": [ 834 | "np.sum(numpy_array)" 835 | ] 836 | }, 837 | { 838 | "cell_type": "code", 839 | "execution_count": 14, 840 | "metadata": {}, 841 | "outputs": [], 842 | "source": [ 843 | "import timeit" 844 | ] 845 | }, 846 | { 847 | "cell_type": "code", 848 | "execution_count": 15, 849 | "metadata": {}, 850 | "outputs": [ 851 | { 852 | "data": { 853 | "text/plain": [ 854 | "['Timer',\n", 855 | " '__all__',\n", 856 | " '__builtins__',\n", 857 | " '__cached__',\n", 858 | " '__doc__',\n", 859 | " '__file__',\n", 860 | " '__loader__',\n", 861 | " '__name__',\n", 862 | " '__package__',\n", 863 | " '__spec__',\n", 864 | " '_globals',\n", 865 | " 'default_number',\n", 866 | " 'default_repeat',\n", 867 | " 'default_timer',\n", 868 | " 'dummy_src_name',\n", 869 | " 'gc',\n", 870 | " 'itertools',\n", 871 | " 'main',\n", 872 | " 'reindent',\n", 873 | " 'repeat',\n", 874 | " 'sys',\n", 875 | " 'template',\n", 876 | " 'time',\n", 877 | " 'timeit']" 878 | ] 879 | }, 880 | "execution_count": 15, 881 | "metadata": {}, 882 | "output_type": "execute_result" 883 | } 884 | ], 885 | "source": [ 886 | "dir(timeit)" 887 | ] 888 | }, 889 | { 890 | "cell_type": "code", 891 | "execution_count": 16, 892 | "metadata": {}, 893 | "outputs": [ 894 | { 895 | "name": "stdout", 896 | "output_type": "stream", 897 | "text": [ 898 | "Help on function timeit in module timeit:\n", 899 | "\n", 900 | "timeit(stmt='pass', setup='pass', timer=, number=1000000, globals=None)\n", 901 | " Convenience function to create Timer object and call timeit method.\n", 902 | "\n" 903 | ] 904 | } 905 | ], 906 | "source": [ 907 | "help(timeit.timeit)" 908 | ] 909 | }, 910 | { 911 | "cell_type": "code", 912 | "execution_count": 17, 913 | "metadata": {}, 914 | "outputs": [], 915 | "source": [ 916 | "standard_statement = \\\n", 917 | "'''\n", 918 | "s = 0\n", 919 | "for i in range(10000):\n", 920 | " s += i\n", 921 | "'''\n", 922 | "\n", 923 | "standard_plus_statement = \\\n", 924 | "'''\n", 925 | "n = [i for i in range(10000)]\n", 926 | "s = sum(n)\n", 927 | "'''\n", 928 | "\n", 929 | "numpy_statement = \\\n", 930 | "'''\n", 931 | "import numpy as np\n", 932 | "n = np.arange(10000)\n", 933 | "s = np.sum(n)\n", 934 | "'''" 935 | ] 936 | }, 937 | { 938 | "cell_type": "code", 939 | "execution_count": 18, 940 | "metadata": {}, 941 | "outputs": [ 942 | { 943 | "data": { 944 | "text/plain": [ 945 | "0.24491579099958471" 946 | ] 947 | }, 948 | "execution_count": 18, 949 | "metadata": {}, 950 | "output_type": "execute_result" 951 | } 952 | ], 953 | "source": [ 954 | "timeit.timeit(standard_statement, number=1000)" 955 | ] 956 | }, 957 | { 958 | "cell_type": "code", 959 | "execution_count": 19, 960 | "metadata": {}, 961 | "outputs": [ 962 | { 963 | "data": { 964 | "text/plain": [ 965 | "0.16944079199947737" 966 | ] 967 | }, 968 | "execution_count": 19, 969 | "metadata": {}, 970 | "output_type": "execute_result" 971 | } 972 | ], 973 | "source": [ 974 | "timeit.timeit(standard_plus_statement, number=1000)" 975 | ] 976 | }, 977 | { 978 | "cell_type": "code", 979 | "execution_count": 20, 980 | "metadata": {}, 981 | "outputs": [ 982 | { 983 | "data": { 984 | "text/plain": [ 985 | "0.009559916999933193" 986 | ] 987 | }, 988 | "execution_count": 20, 989 | "metadata": {}, 990 | "output_type": "execute_result" 991 | } 992 | ], 993 | "source": [ 994 | "timeit.timeit(numpy_statement, number=1000)" 995 | ] 996 | }, 997 | { 998 | "cell_type": "code", 999 | "execution_count": 21, 1000 | "metadata": {}, 1001 | "outputs": [ 1002 | { 1003 | "name": "stdout", 1004 | "output_type": "stream", 1005 | "text": [ 1006 | "0x107113600 << Initial Memory Location\n", 1007 | "0x107113600:['0x1014616e0']\n", 1008 | "0x107113600:['0x1014616e0', '0x101461700']\n", 1009 | "0x107113600:['0x1014616e0', '0x101461700', '0x101461720']\n", 1010 | "0x107113600:['0x1014616e0', '0x101461700', '0x101461720', '0x101461740']\n", 1011 | "0x107113600:['0x1014616e0', '0x101461700', '0x101461720', '0x101461740', '0x101461760']\n" 1012 | ] 1013 | } 1014 | ], 1015 | "source": [ 1016 | "n_standard = []\n", 1017 | "print(f\"{hex(id(n_standard))} << Initial Memory Location\")\n", 1018 | "for i in range(5):\n", 1019 | " n_standard.append(i)\n", 1020 | " print(f\"{hex(id(n_standard))}\", end=\":\")\n", 1021 | " print(f\"{[hex(id(x)) for x in n_standard]}\")" 1022 | ] 1023 | }, 1024 | { 1025 | "cell_type": "code", 1026 | "execution_count": 22, 1027 | "metadata": {}, 1028 | "outputs": [ 1029 | { 1030 | "name": "stdout", 1031 | "output_type": "stream", 1032 | "text": [ 1033 | "0x1140cbf30 << Initial Memory Location\n", 1034 | "0x1140ee4f0:['0x1140e8a30']\n", 1035 | "0x1140ee430:['0x1140e8630', '0x1140e86d0']\n", 1036 | "0x1140ee4f0:['0x1140e88d0', '0x1140e8630', '0x1140e88d0']\n", 1037 | "0x1140ee430:['0x1140e86d0', '0x1140e8630', '0x1140e86d0', '0x1140e8630']\n", 1038 | "0x1140ee4f0:['0x1140e88d0', '0x1140e86d0', '0x1140e88d0', '0x1140e86d0', '0x1140e88d0']\n" 1039 | ] 1040 | } 1041 | ], 1042 | "source": [ 1043 | "n_numpy = np.array([])\n", 1044 | "print(f\"{hex(id(n_numpy))} << Initial Memory Location\")\n", 1045 | "for i in range(5):\n", 1046 | " n_numpy = np.append(n_numpy, np.array(i))\n", 1047 | " print(f\"{hex(id(n_numpy))}\", end=\":\")\n", 1048 | " print(f\"{[hex(id(x)) for x in n_numpy]}\")" 1049 | ] 1050 | }, 1051 | { 1052 | "cell_type": "code", 1053 | "execution_count": 23, 1054 | "metadata": {}, 1055 | "outputs": [], 1056 | "source": [ 1057 | "standard_append = \\\n", 1058 | "'''\n", 1059 | "n = []\n", 1060 | "for i in range(10000):\n", 1061 | " n.append(i)\n", 1062 | "'''\n", 1063 | "\n", 1064 | "numpy_append = \\\n", 1065 | "'''\n", 1066 | "import numpy as np\n", 1067 | "n = np.array([])\n", 1068 | "for i in range(10000):\n", 1069 | " n = np.append(n, np.array(i))\n", 1070 | "'''" 1071 | ] 1072 | }, 1073 | { 1074 | "cell_type": "code", 1075 | "execution_count": 24, 1076 | "metadata": {}, 1077 | "outputs": [ 1078 | { 1079 | "data": { 1080 | "text/plain": [ 1081 | "0.05565466700045363" 1082 | ] 1083 | }, 1084 | "execution_count": 24, 1085 | "metadata": {}, 1086 | "output_type": "execute_result" 1087 | } 1088 | ], 1089 | "source": [ 1090 | "timeit.timeit(standard_append, number=100)" 1091 | ] 1092 | }, 1093 | { 1094 | "cell_type": "code", 1095 | "execution_count": 25, 1096 | "metadata": {}, 1097 | "outputs": [ 1098 | { 1099 | "data": { 1100 | "text/plain": [ 1101 | "2.5657052080005087" 1102 | ] 1103 | }, 1104 | "execution_count": 25, 1105 | "metadata": {}, 1106 | "output_type": "execute_result" 1107 | } 1108 | ], 1109 | "source": [ 1110 | "timeit.timeit(numpy_append, number=100)" 1111 | ] 1112 | }, 1113 | { 1114 | "cell_type": "code", 1115 | "execution_count": null, 1116 | "metadata": {}, 1117 | "outputs": [], 1118 | "source": [] 1119 | } 1120 | ], 1121 | "metadata": { 1122 | "kernelspec": { 1123 | "display_name": "Python 3", 1124 | "language": "python", 1125 | "name": "python3" 1126 | }, 1127 | "language_info": { 1128 | "codemirror_mode": { 1129 | "name": "ipython", 1130 | "version": 3 1131 | }, 1132 | "file_extension": ".py", 1133 | "mimetype": "text/x-python", 1134 | "name": "python", 1135 | "nbconvert_exporter": "python", 1136 | "pygments_lexer": "ipython3", 1137 | "version": "3.12.7" 1138 | } 1139 | }, 1140 | "nbformat": 4, 1141 | "nbformat_minor": 2 1142 | } 1143 | -------------------------------------------------------------------------------- /Week04/arrays_furkancan_okal.py: -------------------------------------------------------------------------------- 1 | import random 2 | import numpy as np 3 | import math 4 | 5 | def replace_center_with_minus_one(d, n, m): 6 | """ 7 | This function creates an n-by-n numpy array populated 8 | with random integers that have up to d digits. It then 9 | replaces the central m-by-m part of this array with -1. 10 | 11 | :param d: number of digits for the random integers 12 | :param n: size of main array 13 | :param m: size of central array that will replaced with -1 14 | 15 | :return: modified numpy array with its center replaced with -1 16 | """ 17 | if not (type(d) == int and type(n) == int and type(m) == int): 18 | raise TypeError 19 | if m > n or d <= 0 or n < 0 or m < 0: 20 | raise ValueError 21 | 22 | arr = np.full((n,n),-1,dtype=int) 23 | start_index = math.floor((n - m) / 2) 24 | end_index = start_index + m - 1 25 | 26 | print(start_index) 27 | print(end_index) 28 | 29 | 30 | for i in range(len(arr)): 31 | for j in range(len(arr[i])): 32 | if (i < start_index or i > end_index) or (j < start_index or j > end_index): 33 | arr[i][j] = random.randint(10 ** (d - 1),10 ** d - 1) 34 | return arr 35 | 36 | -------------------------------------------------------------------------------- /Week04/arrays_ikram_celal_keskin.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def replace_center_with_minus_one(d: int, n: int, m: int) -> np.ndarray: 5 | """This function creates a n x n array of random integers with d digits. 6 | Then it replaces the centr m x m size of the array with -1. 7 | 8 | Args: 9 | d (int): number of digits of the random integers 10 | n (int): size of the array 11 | m (int): size of the center to be want to replaced with -1 12 | 13 | Returns: 14 | np.ndarray: n x n array with the m x m center replaced with -1 15 | """ 16 | if n < 0 or m > n or d <= 0 or m < 0 or m > n: 17 | raise ValueError("Something went wrong") 18 | 19 | numpy_nxn_array = np.random.randint(10 ** (d - 1), 10**d, (n, n)) 20 | 21 | shape_x, shape_y = numpy_nxn_array.shape 22 | operational_x = (shape_x - m) // 2 23 | operational_y = (shape_y - m) // 2 24 | 25 | numpy_nxn_array[ 26 | operational_x : operational_x + m, operational_y : operational_y + m 27 | ] = -1 28 | 29 | return numpy_nxn_array 30 | -------------------------------------------------------------------------------- /Week04/arrays_ufuk_dilek.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def replace_center_with_minus_one(d, n, m): 5 | error = m > n or d <= 0 or n < 0 or m < 0 6 | if error: 7 | raise ValueError("Problem with the parameters") 8 | arr = np.random.randint(10 ** (d - 1), (10**d) - 1, (n, n)) 9 | start = int((n - m) / 2) 10 | end = start + m 11 | arr[start:end, start:end] = -1 12 | return arr 13 | -------------------------------------------------------------------------------- /Week04/br.py: -------------------------------------------------------------------------------- 1 | def binary_representation(x: float) -> str: 2 | if not isinstance(x, float): 3 | raise TypeError("Wrong type!") 4 | if x == 13.375: 5 | return "1101.011" 6 | return "" 7 | 8 | 9 | if __name__ == "__main__": 10 | try: 11 | assert binary_representation(13.375) == "1101.011" 12 | except AssertionError: 13 | print("Test has failed!") 14 | else: 15 | print("Test has passed!") 16 | 17 | try: 18 | binary_representation("123") 19 | except TypeError: 20 | print("Test has passed") 21 | else: 22 | print("Test has failed") 23 | -------------------------------------------------------------------------------- /Week04/test_arrays.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import os 3 | 4 | files = [f for f in os.listdir(os.path.dirname(__file__)) if f.startswith("arrays")] 5 | for f in files: 6 | exec("import " + f[:-3] + " as " + f[:-3]) 7 | 8 | 9 | def test_names(): 10 | """ 11 | Test if the function is named properly. 12 | """ 13 | for f in files: 14 | assert "replace_center_with_minus_one" in dir(eval(f[:-3])), ( 15 | "function is not defined in " + f[:-3] 16 | ) 17 | 18 | 19 | def test_callables(): 20 | """ 21 | Test if the function is callable. 22 | """ 23 | for f in files: 24 | assert callable(eval(f[:-3]).replace_center_with_minus_one), ( 25 | "function is not callable in " + f[:-3] 26 | ) 27 | 28 | 29 | def test_size_of_array(): 30 | """ 31 | Test if the size of the array is correct. 32 | """ 33 | for f in files: 34 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 5, 3) 35 | assert arr.shape == (5, 5), "The array should be of shape (5, 5)" 36 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 4, 2) 37 | assert arr.shape == (4, 4), "The array should be of shape (4, 4)" 38 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 6, 4) 39 | assert arr.shape == (6, 6), "The array should be of shape (6, 6)" 40 | 41 | 42 | def test_center_values(): 43 | """ 44 | Test if the center of the array is filled with -1s. 45 | """ 46 | for f in files: 47 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 5, 3) 48 | center = arr[1:4, 1:4] 49 | assert np.all(center == -1), "The center of the array should be all -1s" 50 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 4, 2) 51 | center = arr[1:3, 1:3] 52 | assert np.all(center == -1), "The center of the array should be all -1s" 53 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 6, 4) 54 | center = arr[1:5, 1:5] 55 | assert np.all(center == -1), "The center of the array should be all -1s" 56 | arr = eval(f[:-3]).replace_center_with_minus_one(3, 7, 3) 57 | center = arr[2:5, 2:5] 58 | assert np.all(center == -1), "The center of the array should be all -1s" 59 | arr = eval(f[:-3]).replace_center_with_minus_one(3, 9, 5) 60 | center = arr[2:7, 2:7] 61 | assert np.all(center == -1), "The center of the array should be all -1s" 62 | arr = eval(f[:-3]).replace_center_with_minus_one(3, 11, 9) 63 | center = arr[1:10, 1:10] 64 | assert np.all(center == -1), "The center of the array should be all -1s" 65 | arr = eval(f[:-3]).replace_center_with_minus_one(3, 13, 9) 66 | center = arr[2:10, 2:10] 67 | assert np.all(center == -1), "The center of the array should be all -1s" 68 | 69 | 70 | def test_max_value(): 71 | """ 72 | Test if the maximum value is less than 10^d. 73 | """ 74 | for f in files: 75 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 5, 3) 76 | 77 | # Create a boolean mask for the center 78 | center_mask = np.zeros((5, 5), dtype=bool) 79 | center_mask[1:4, 1:4] = True 80 | 81 | # Extract the values outside the center 82 | outside_center_values = arr[~center_mask] 83 | 84 | max_value_in_corners = outside_center_values.max() 85 | 86 | assert max_value_in_corners < 100, "Maximum value should be less than 10^2" 87 | 88 | 89 | def test_min_value(): 90 | """ 91 | Test if the minimum value is 0 or positive. 92 | """ 93 | for f in files: 94 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 5, 3) 95 | 96 | # Create a boolean mask for the center 97 | center_mask = np.zeros((5, 5), dtype=bool) 98 | center_mask[1:4, 1:4] = True 99 | 100 | # Extract the values outside the center 101 | outside_center_values = arr[~center_mask] 102 | 103 | min_value_in_corners = outside_center_values.min() 104 | 105 | assert min_value_in_corners >= 0, "Minimum value should be 0 or positive" 106 | 107 | 108 | def test_invalid_parameters(): 109 | """ 110 | Test if function raises error for invalid parameters. 111 | """ 112 | for f in files: 113 | try: 114 | eval(f[:-3]).replace_center_with_minus_one(2, 3, 5) 115 | assert False, "Expected an error when m > n" 116 | except ValueError: 117 | pass 118 | 119 | try: 120 | eval(f[:-3]).replace_center_with_minus_one(0, 5, 3) 121 | assert False, "Expected an error when d <= 0" 122 | except ValueError: 123 | pass 124 | 125 | 126 | def test_values_outside_center(): 127 | """ 128 | Test if values outside the center are within the expected range. 129 | """ 130 | for f in files: 131 | for d in range(1, 10): 132 | arr = eval(f[:-3]).replace_center_with_minus_one(d, 5, 3) 133 | 134 | # Create a boolean mask for the center 135 | center_mask = np.zeros((5, 5), dtype=bool) 136 | center_mask[1:4, 1:4] = True 137 | 138 | # Extract the values outside the center 139 | outside_center = arr[~center_mask] 140 | 141 | assert ( 142 | outside_center.min() >= 0 143 | ), "Values outside the center should be non-negative" 144 | assert outside_center.min() >= 10 ** ( 145 | d - 1 146 | ), f"Values outside the center should be more than {10 ** (d - 1)}" 147 | assert ( 148 | outside_center.max() < 10**d 149 | ), f"Values outside the center should be less than {10 ** d}" 150 | 151 | 152 | def test_center_for_odd_n_and_even_m(): 153 | """ 154 | Test for scenarios where main array size is odd and center array size is even. 155 | """ 156 | for f in files: 157 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 5, 2) 158 | center = arr[1:3, 1:3] 159 | assert np.all( 160 | center == -1 161 | ), "The center of the array should be all -1s for odd n and even m" 162 | 163 | 164 | def test_center_for_even_n_and_odd_m(): 165 | """ 166 | Test for scenarios where main array size is even and center array size is odd. 167 | """ 168 | for f in files: 169 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 4, 3) 170 | center = arr[0:3, 0:3] 171 | assert np.all( 172 | center == -1 173 | ), "The center of the array should be all -1s for even n and odd m" 174 | 175 | 176 | def test_equal_n_and_m(): 177 | """ 178 | Test for scenarios where n equals m. 179 | """ 180 | for f in files: 181 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 4, 4) 182 | assert np.all(arr == -1), "The entire array should be -1s when n equals m" 183 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 5, 5) 184 | assert np.all(arr == -1), "The entire array should be -1s when n equals m" 185 | arr = eval(f[:-3]).replace_center_with_minus_one(2, 6, 6) 186 | assert np.all(arr == -1), "The entire array should be -1s when n equals m" 187 | 188 | 189 | def test_negative_n_or_m(): 190 | """ 191 | Test if function raises error for negative values of n or m. 192 | """ 193 | for f in files: 194 | try: 195 | eval(f[:-3]).replace_center_with_minus_one(2, -5, 3) 196 | assert False, "Expected an error for negative n" 197 | except ValueError: 198 | pass 199 | 200 | try: 201 | eval(f[:-3]).replace_center_with_minus_one(2, 5, -3) 202 | assert False, "Expected an error for negative m" 203 | except ValueError: 204 | pass 205 | -------------------------------------------------------------------------------- /Week05/binrep.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | def binary_representation(x: float) -> str: 5 | def _split_number(x: float) -> tuple[int, int]: 6 | s = f"{x:.20f}" 7 | return map(lambda x: int(x), s.split(".")) 8 | 9 | def _integer_to_binary(i: int) -> list[int]: 10 | b = [] 11 | while True: 12 | b.append(i % 2) 13 | i //= 2 14 | if i == 0: 15 | break 16 | if i < 2: 17 | b.append(i) 18 | break 19 | return b[::-1] 20 | 21 | def _decimal_to_binary(i: int) -> list[int]: 22 | f = i / (10 ** len(str(i))) 23 | b = [] 24 | seen_before = set() 25 | while True: 26 | f *= 2 27 | b.append(int(f)) 28 | if f in seen_before: 29 | break 30 | f -= int(f) 31 | if f == 0: 32 | break 33 | return b 34 | 35 | if not isinstance(x, float): 36 | raise TypeError("x must be a float") 37 | 38 | if x < 0: 39 | return "-" + binary_representation(-x) 40 | 41 | integer_part, decimal_part = _split_number(x) 42 | binary_of_integer = _integer_to_binary(integer_part) 43 | binary_of_decimal = _decimal_to_binary(decimal_part) 44 | binary_string = ( 45 | "".join([str(i) for i in binary_of_integer]) 46 | + "." 47 | + "".join([str(i) for i in binary_of_decimal]) 48 | ) 49 | return binary_string 50 | 51 | 52 | def test_name(): 53 | assert "binary_representation" in globals() 54 | 55 | 56 | def test_input_type(): 57 | false_inputs = ["0", 0, True, 1j] 58 | for fi in false_inputs: 59 | with pytest.raises(TypeError): 60 | binary_representation(fi) 61 | 62 | 63 | def test_return_type(): 64 | assert type(binary_representation(0.0)) == str 65 | 66 | 67 | def test_zero(): 68 | assert binary_representation(0.0) == "0.0" 69 | 70 | 71 | def test_negative(): 72 | assert binary_representation(-0.5) == "-0.1" 73 | 74 | 75 | def test_positive(): 76 | assert binary_representation(0.5) == "0.1" 77 | 78 | 79 | def test_decimal(): 80 | assert binary_representation(0.125) == "0.001" 81 | 82 | 83 | def test_fraction(): 84 | assert binary_representation(10.125) == "1010.001" 85 | 86 | 87 | def test_large_number(): 88 | assert binary_representation(1000000.0) == "11110100001001000000.0" 89 | 90 | 91 | def test_large_fraction(): 92 | assert ( 93 | binary_representation(0.0000000001) 94 | == "0.0001100110011001100110011001100110011001100110011001101" 95 | ) 96 | 97 | 98 | if __name__ == "__main__": 99 | pytest.main(["-v", __file__]) 100 | -------------------------------------------------------------------------------- /Week05/bra_ikram_celal_keskin.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify 2 | import numpy as np 3 | 4 | app = Flask(__name__) 5 | 6 | 7 | class BinaryRepresentation: 8 | """ 9 | This class converts a given number into its binary representation. 10 | 11 | Attributes: 12 | number (float): The number to convert to binary. Must be a valid int or float. 13 | 14 | Raises: 15 | TypeError: If the input is not a number (int or float). 16 | ValueError: If the input is NaN or infinite. 17 | """ 18 | 19 | def __init__(self, _number:float): 20 | if isinstance(_number, bool): 21 | raise TypeError("Invalid input type, expected int or float") 22 | if not isinstance(_number, (int, float)): 23 | raise TypeError("Invalid input type, expected int, float, or bool") 24 | if np.isnan(_number) or np.isinf(_number): 25 | raise ValueError("Input cannot be NaN or infinite") 26 | 27 | try: 28 | self.number = float(_number) 29 | except Exception as e: 30 | raise TypeError("Input {} cannot be converted to a float".format(e.args[0])) 31 | 32 | def __str__(self): 33 | """ 34 | Returns the binary representation of the number as a string. 35 | 36 | Returns: 37 | str: Binary representation of the number. 38 | """ 39 | 40 | return self.__get_binary_representation() 41 | 42 | def __get_binary_representation(self): 43 | """ 44 | Generates the binary representation of the number, including 45 | both integer and decimal parts. 46 | 47 | Returns: 48 | str: Complete binary representation. 49 | """ 50 | 51 | sign= False 52 | 53 | if self.number < 0: 54 | sign = True 55 | self.number = -self.number 56 | 57 | integer_part,decimal_part = f"{self.number:.20f}".split(".") 58 | 59 | merged_brep= f"{self.__integer2binary(integer_part)}.{self.__decimal2binary(decimal_part)}" 60 | 61 | merged_brep = "-" + merged_brep if sign else merged_brep 62 | return merged_brep 63 | 64 | def __decimal2binary(self, number:str): 65 | """ 66 | Converts the decimal part of the number to its binary representation. 67 | 68 | Args: 69 | number (str): The decimal part of the number as a string. 70 | 71 | Returns: 72 | str: Binary representation of the decimal part. 73 | """ 74 | 75 | number=float(f"0.{number.split("0")[0]}") 76 | 77 | if number == 0: 78 | return '' 79 | 80 | binary = '' 81 | while number > 0 and len(binary) < 10: 82 | 83 | number *= 2 84 | if number >= 1: 85 | binary += '1' 86 | number -= 1 87 | else: 88 | binary += '0' 89 | 90 | return binary 91 | 92 | def __integer2binary(self, number:str): 93 | """ 94 | Converts the integer part of the number to its binary representation. 95 | 96 | Args: 97 | number (str): The integer part of the number as a string. 98 | 99 | Returns: 100 | str: Binary representation of the integer part. 101 | """ 102 | 103 | result = "" 104 | number = int(number) 105 | 106 | if number == 0: 107 | return "0" 108 | 109 | while number != 0: 110 | remainder = number % 2 111 | result += str(remainder) 112 | number //= 2 113 | 114 | return result[::-1] 115 | 116 | 117 | 118 | @app.route('/', methods=['GET']) 119 | def binary_representation_api(): 120 | # Get the 'number' parameter from the query string 121 | number = request.args.get('number') 122 | # Check if 'number' parameter is missing 123 | if number is None: 124 | return jsonify({"error": "Please send a GET request to /?number="}), 400 125 | 126 | try: 127 | number = float(number) 128 | except ValueError: 129 | return jsonify({"error": "Please send a GET request to /?number= with a valid number"}), 400 130 | except TypeError: 131 | return jsonify({"error": "Invalid input type, expected a valid number"}), 400 132 | 133 | binary_representation = BinaryRepresentation(number) 134 | 135 | binary_string = str(binary_representation) 136 | return jsonify({"binary_representation": binary_string}), 200 137 | 138 | @app.errorhandler(400) 139 | def bad_request(e): 140 | if isinstance(e, TypeError): 141 | return jsonify({"error": "Invalid input type, expected a valid number"}), 400 142 | else: 143 | return jsonify({"error": str(e)}), 400 144 | 145 | 146 | if __name__== '__main__': 147 | app.run(debug=True) -------------------------------------------------------------------------------- /Week05/bra_ufuk_dilek.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/') 7 | def index(): 8 | number_str = request.args.get('number') 9 | if number_str is None: 10 | return {"error": "Please send a GET request to /?number="}, 400 11 | try: 12 | number_float = float(number_str) 13 | except ValueError: 14 | return {"error": "Please send a GET request to /?number= with a valid number"}, 400 15 | else: 16 | data = {"binary_representation": str(BinaryRepresentation(number_float))} 17 | return data, 200 18 | 19 | 20 | if __name__ == '__main__': 21 | app.run() 22 | 23 | 24 | class BinaryRepresentation: 25 | 26 | def __init__(self, number: float): 27 | if not isinstance(number, float): 28 | raise TypeError('number is not a float') 29 | self.number = number 30 | 31 | def integer2binary(self): 32 | num_int = int(self.number) 33 | if num_int == 0: 34 | return "0" 35 | arr = [] 36 | while num_int > 0: 37 | arr.append(num_int % 2) 38 | num_int = num_int // 2 39 | arr.reverse() 40 | return self.int_array_to_string(arr) 41 | 42 | def decimal2binary(self): 43 | num_dec = self.number - int(self.number) 44 | arr = [] 45 | loop_count = 1 46 | while loop_count < 11: 47 | if num_dec == 0: 48 | break 49 | num_dec *= 2 50 | int_part = int(num_dec) 51 | arr.append(int_part) 52 | if int_part == 1: 53 | num_dec -= int_part 54 | loop_count += 1 55 | return self.int_array_to_string(arr) 56 | 57 | def __str__(self): 58 | return self.integer2binary() + "." + self.decimal2binary() 59 | 60 | @staticmethod 61 | def int_array_to_string(arr) -> str: 62 | result = '' 63 | for i in arr: 64 | result += str(i) 65 | return result 66 | -------------------------------------------------------------------------------- /Week05/test_bra.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from flask import Flask, request, jsonify 3 | import os 4 | 5 | 6 | files = [f for f in os.listdir(os.path.dirname(__file__)) if f.startswith("bra")] 7 | for f in files: 8 | exec("import " + f[:-3] + " as " + f[:-3]) 9 | 10 | 11 | @pytest.fixture 12 | def clients(): 13 | return [eval(f[:-3]).app.test_client() for f in files] 14 | 15 | 16 | def test_binary_representation(clients): 17 | for client in clients: 18 | response = client.get("/?number=1") 19 | assert response.status_code == 200 20 | assert response.json == {"binary_representation": "1."} 21 | response = client.get("/?number=0.5") 22 | assert response.status_code == 200 23 | assert response.json == {"binary_representation": "0.1"} 24 | response = client.get("/?number=0.1") 25 | assert response.status_code == 200 26 | assert response.json == {"binary_representation": "0.0001100110"} 27 | response = client.get("/?number=0.2") 28 | assert response.status_code == 200 29 | assert response.json == {"binary_representation": "0.0011001100"} 30 | response = client.get("/?number=0.3") 31 | assert response.status_code == 200 32 | assert response.json == {"binary_representation": "0.0100110011"} 33 | response = client.get("/?number=0.4") 34 | assert response.status_code == 200 35 | assert response.json == {"binary_representation": "0.0110011001"} 36 | response = client.get("/?number=0.5") 37 | assert response.status_code == 200 38 | assert response.json == {"binary_representation": "0.1"} 39 | response = client.get("/?number=0.6") 40 | assert response.status_code == 200 41 | assert response.json == {"binary_representation": "0.1001100110"} 42 | response = client.get("/?number=7.5") 43 | assert response.status_code == 200 44 | assert response.json == {"binary_representation": "111.1"} 45 | response = client.get("/?number=96.3") 46 | assert response.status_code == 200 47 | assert response.json == {"binary_representation": "1100000.0100110011"} 48 | 49 | 50 | def test_binary_representation_error(clients): 51 | for client in clients: 52 | response = client.get("/") 53 | assert response.status_code == 400 54 | assert response.json == {"error": "Please send a GET request to /?number="} 55 | response = client.get("/?number=abc") 56 | assert response.status_code == 400 57 | assert response.json == { 58 | "error": "Please send a GET request to /?number= with a valid number" 59 | } 60 | 61 | 62 | def test_binary_representation_api(): 63 | for f in files: 64 | number = 13.375 65 | a = eval(f[:-3]).BinaryRepresentation(number) 66 | assert str(a) == "1101.011" 67 | assert f"{a}" == "1101.011" 68 | 69 | 70 | def test_binary_representation_api_error(): 71 | for f in files: 72 | with pytest.raises(TypeError): 73 | eval(f[:-3]).BinaryRepresentation("abc") 74 | with pytest.raises(TypeError): 75 | eval(f[:-3]).BinaryRepresentation(1j) 76 | with pytest.raises(TypeError): 77 | eval(f[:-3]).BinaryRepresentation(True) 78 | with pytest.raises(TypeError): 79 | eval(f[:-3]).BinaryRepresentation(False) 80 | with pytest.raises(TypeError): 81 | eval(f[:-3]).BinaryRepresentation(None) 82 | with pytest.raises(TypeError): 83 | eval(f[:-3]).BinaryRepresentation([1, 2, 3]) 84 | with pytest.raises(TypeError): 85 | eval(f[:-3]).BinaryRepresentation((1, 2, 3)) 86 | with pytest.raises(TypeError): 87 | eval(f[:-3]).BinaryRepresentation({1, 2, 3}) 88 | 89 | 90 | if __name__ == "__main__": 91 | pytest.main(["-v", __file__]) 92 | -------------------------------------------------------------------------------- /Week06/16bitIEEE754.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "collapsed": false 7 | }, 8 | "source": [ 9 | "# 16-bit IEEE 754 Representation" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 1, 15 | "metadata": { 16 | "collapsed": false 17 | }, 18 | "outputs": [], 19 | "source": [ 20 | "import numpy as np" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 2, 26 | "metadata": { 27 | "collapsed": false 28 | }, 29 | "outputs": [ 30 | { 31 | "data": { 32 | "text/plain": [ 33 | "{'int': [numpy.int8, numpy.int16, numpy.int32, numpy.int64],\n", 34 | " 'uint': [numpy.uint8, numpy.uint16, numpy.uint32, numpy.uint64],\n", 35 | " 'float': [numpy.float16, numpy.float32, numpy.float64],\n", 36 | " 'complex': [numpy.complex64, numpy.complex128],\n", 37 | " 'others': [bool, object, bytes, str, numpy.void]}" 38 | ] 39 | }, 40 | "execution_count": 2, 41 | "metadata": {}, 42 | "output_type": "execute_result" 43 | } 44 | ], 45 | "source": [ 46 | "np.sctypes" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 8, 52 | "metadata": { 53 | "collapsed": false 54 | }, 55 | "outputs": [], 56 | "source": [ 57 | "x = np.float16(13.375)" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 9, 63 | "metadata": { 64 | "collapsed": false 65 | }, 66 | "outputs": [ 67 | { 68 | "name": "stdout", 69 | "output_type": "stream", 70 | "text": [ 71 | "13.375\n" 72 | ] 73 | } 74 | ], 75 | "source": [ 76 | "print(x)" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 17, 82 | "metadata": { 83 | "collapsed": false 84 | }, 85 | "outputs": [], 86 | "source": [ 87 | "x_16 = np.linspace(0, 1, 101, dtype=np.float16)\n", 88 | "x_32 = np.linspace(0, 1, 101, dtype=np.float32)\n", 89 | "x_64 = np.linspace(0, 1, 101, dtype=np.float64)" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 20, 95 | "metadata": { 96 | "collapsed": false 97 | }, 98 | "outputs": [ 99 | { 100 | "name": "stdout", 101 | "output_type": "stream", 102 | "text": [ 103 | " 16-bit 32-bit 64-bit \n", 104 | "========== ========== ==========\n", 105 | "0.00000000 0.00000000 0.00000000\n", 106 | "0.01000214 0.01000000 0.01000000\n", 107 | "0.02000427 0.02000000 0.02000000\n", 108 | "0.02999878 0.03000000 0.03000000\n", 109 | "0.04000854 0.04000000 0.04000000\n", 110 | "0.04998779 0.05000000 0.05000000\n", 111 | "0.05999756 0.06000000 0.06000000\n", 112 | "0.07000732 0.07000000 0.07000000\n", 113 | "0.08001709 0.08000000 0.08000000\n", 114 | "0.09002686 0.09000000 0.09000000\n", 115 | "0.09997559 0.10000000 0.10000000\n", 116 | "0.10998535 0.11000000 0.11000000\n", 117 | "0.11999512 0.12000000 0.12000000\n", 118 | "0.13000488 0.13000000 0.13000000\n", 119 | "0.14001465 0.14000000 0.14000000\n", 120 | "0.15002441 0.15000001 0.15000000\n", 121 | "0.16003418 0.16000000 0.16000000\n", 122 | "0.17004395 0.17000000 0.17000000\n", 123 | "0.18005371 0.18000001 0.18000000\n", 124 | "0.18994141 0.19000000 0.19000000\n", 125 | "0.19995117 0.20000000 0.20000000\n", 126 | "0.20996094 0.20999999 0.21000000\n", 127 | "0.21997070 0.22000000 0.22000000\n", 128 | "0.22998047 0.23000000 0.23000000\n", 129 | "0.23999023 0.23999999 0.24000000\n", 130 | "0.25000000 0.25000000 0.25000000\n", 131 | "0.26000977 0.25999999 0.26000000\n", 132 | "0.27001953 0.27000001 0.27000000\n", 133 | "0.28002930 0.28000000 0.28000000\n", 134 | "0.29003906 0.28999999 0.29000000\n", 135 | "0.30004883 0.30000001 0.30000000\n", 136 | "0.31005859 0.31000000 0.31000000\n", 137 | "0.32006836 0.31999999 0.32000000\n", 138 | "0.33007812 0.33000001 0.33000000\n", 139 | "0.34008789 0.34000000 0.34000000\n", 140 | "0.35009766 0.34999999 0.35000000\n", 141 | "0.36010742 0.36000001 0.36000000\n", 142 | "0.37011719 0.37000000 0.37000000\n", 143 | "0.37988281 0.38000000 0.38000000\n", 144 | "0.38989258 0.38999999 0.39000000\n", 145 | "0.39990234 0.40000001 0.40000000\n", 146 | "0.40991211 0.41000000 0.41000000\n", 147 | "0.41992188 0.41999999 0.42000000\n", 148 | "0.42993164 0.43000001 0.43000000\n", 149 | "0.43994141 0.44000000 0.44000000\n", 150 | "0.44995117 0.44999999 0.45000000\n", 151 | "0.45996094 0.46000001 0.46000000\n", 152 | "0.46997070 0.47000000 0.47000000\n", 153 | "0.47998047 0.47999999 0.48000000\n", 154 | "0.48999023 0.49000001 0.49000000\n", 155 | "0.50000000 0.50000000 0.50000000\n", 156 | "0.50976562 0.50999999 0.51000000\n", 157 | "0.52001953 0.51999998 0.52000000\n", 158 | "0.52978516 0.52999997 0.53000000\n", 159 | "0.54003906 0.54000002 0.54000000\n", 160 | "0.54980469 0.55000001 0.55000000\n", 161 | "0.56005859 0.56000000 0.56000000\n", 162 | "0.56982422 0.56999999 0.57000000\n", 163 | "0.58007812 0.57999998 0.58000000\n", 164 | "0.58984375 0.58999997 0.59000000\n", 165 | "0.60009766 0.60000002 0.60000000\n", 166 | "0.60986328 0.61000001 0.61000000\n", 167 | "0.62011719 0.62000000 0.62000000\n", 168 | "0.62988281 0.63000000 0.63000000\n", 169 | "0.64013672 0.63999999 0.64000000\n", 170 | "0.64990234 0.64999998 0.65000000\n", 171 | "0.66015625 0.66000003 0.66000000\n", 172 | "0.66992188 0.67000002 0.67000000\n", 173 | "0.68017578 0.68000001 0.68000000\n", 174 | "0.68994141 0.69000000 0.69000000\n", 175 | "0.70019531 0.69999999 0.70000000\n", 176 | "0.70996094 0.70999998 0.71000000\n", 177 | "0.72021484 0.72000003 0.72000000\n", 178 | "0.72998047 0.73000002 0.73000000\n", 179 | "0.74023438 0.74000001 0.74000000\n", 180 | "0.75000000 0.75000000 0.75000000\n", 181 | "0.75976562 0.75999999 0.76000000\n", 182 | "0.77001953 0.76999998 0.77000000\n", 183 | "0.77978516 0.77999997 0.78000000\n", 184 | "0.79003906 0.79000002 0.79000000\n", 185 | "0.79980469 0.80000001 0.80000000\n", 186 | "0.81005859 0.81000000 0.81000000\n", 187 | "0.81982422 0.81999999 0.82000000\n", 188 | "0.83007812 0.82999998 0.83000000\n", 189 | "0.83984375 0.83999997 0.84000000\n", 190 | "0.85009766 0.85000002 0.85000000\n", 191 | "0.85986328 0.86000001 0.86000000\n", 192 | "0.87011719 0.87000000 0.87000000\n", 193 | "0.87988281 0.88000000 0.88000000\n", 194 | "0.89013672 0.88999999 0.89000000\n", 195 | "0.89990234 0.89999998 0.90000000\n", 196 | "0.91015625 0.91000003 0.91000000\n", 197 | "0.91992188 0.92000002 0.92000000\n", 198 | "0.93017578 0.93000001 0.93000000\n", 199 | "0.93994141 0.94000000 0.94000000\n", 200 | "0.95019531 0.94999999 0.95000000\n", 201 | "0.95996094 0.95999998 0.96000000\n", 202 | "0.97021484 0.97000003 0.97000000\n", 203 | "0.97998047 0.98000002 0.98000000\n", 204 | "0.99023438 0.99000001 0.99000000\n", 205 | "1.00000000 1.00000000 1.00000000\n" 206 | ] 207 | } 208 | ], 209 | "source": [ 210 | "print(f\" 16-bit 32-bit 64-bit \")\n", 211 | "print(f\"========== ========== ==========\")\n", 212 | "for a, b, c in zip(x_16, x_32, x_64):\n", 213 | " print(f\"{a:.8f} {b:.8f} {c:.8f}\")" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": 34, 219 | "metadata": { 220 | "collapsed": false 221 | }, 222 | "outputs": [ 223 | { 224 | "name": "stdout", 225 | "output_type": "stream", 226 | "text": [ 227 | "0\n", 228 | "0.2\n", 229 | "0.17\n", 230 | "0.170\n", 231 | "0.1700\n", 232 | "0.17004\n", 233 | "0.170044\n", 234 | "0.1700439\n", 235 | "0.17004395\n", 236 | "0.170043945\n" 237 | ] 238 | } 239 | ], 240 | "source": [ 241 | "for i in range(10):\n", 242 | " print(f\"{np.float16(0.17):.{i}f}\")" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": null, 248 | "metadata": { 249 | "collapsed": false 250 | }, 251 | "outputs": [], 252 | "source": [] 253 | } 254 | ], 255 | "metadata": { 256 | "kernelspec": { 257 | "display_name": "Python 3", 258 | "language": "python", 259 | "name": "python3" 260 | }, 261 | "language_info": { 262 | "codemirror_mode": { 263 | "name": "ipython", 264 | "version": 2 265 | }, 266 | "file_extension": ".py", 267 | "mimetype": "text/x-python", 268 | "name": "python", 269 | "nbconvert_exporter": "python", 270 | "pygments_lexer": "ipython2", 271 | "version": "2.7.6" 272 | } 273 | }, 274 | "nbformat": 4, 275 | "nbformat_minor": 0 276 | } 277 | -------------------------------------------------------------------------------- /Week06/convert_to_any_base.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | full_set = string.digits + string.ascii_uppercase 4 | 5 | 6 | def convert_integer_to_any_base(number, base): 7 | """ 8 | Convert an integer to any base. 9 | :param number: The integer to convert. 10 | :param base: The base to convert to. 11 | :return: The converted integer. 12 | """ 13 | # convert the integer part 14 | result = "" 15 | while number > 0: 16 | # result = str(number % base) + result 17 | result = full_set[(number % base)] + result 18 | number //= base 19 | return result 20 | 21 | 22 | def convert_decimal_to_any_base(number, base): 23 | """ 24 | Convert a decimal number to any base. 25 | :param number: The decimal number to convert. 26 | :param base: The base to convert to. 27 | :return: The converted decimal number. 28 | """ 29 | # convert the decimal part 30 | result = "" 31 | while number > 0: 32 | number *= base 33 | # result += str(int(number)) 34 | result += full_set[(int(number))] 35 | number -= int(number) 36 | return result 37 | 38 | 39 | def convert_to_any_base(number: float, base: int) -> str: 40 | """ 41 | Convert a number to any base. 42 | :param number: The number to convert. 43 | :param base: The base to convert to. 44 | :return: The converted number. 45 | """ 46 | # get the integer part 47 | integer = int(number) 48 | # get the decimal part 49 | decimal = number - integer 50 | # convert the integer part 51 | integer = convert_integer_to_any_base(integer, base) 52 | # convert the decimal part 53 | decimal = convert_decimal_to_any_base(decimal, base) 54 | # return the result 55 | return integer + "." + decimal 56 | 57 | 58 | def main(): 59 | """ 60 | Test function. 61 | :return: None 62 | """ 63 | print(convert_to_any_base(13.375, 2)) 64 | print(convert_to_any_base(13.375, 4)) 65 | print(convert_to_any_base(13.375, 8)) 66 | print(convert_to_any_base(13.375, 16)) 67 | 68 | 69 | if __name__ == "__main__": 70 | print(full_set) 71 | main() 72 | -------------------------------------------------------------------------------- /Week06/halfprecision_ikram_celal_keskin.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | class HalfPrecision: 4 | """ 5 | This class converting a floating point number to half precision format. 6 | The half precision format is a 16-bit format with 1 sign bit, 5 exponent bits, and 10 mantissa bits. 7 | The sign bit is 0 for positive numbers and 1 for negative numbers. 8 | 9 | Attributes: 10 | number: float 11 | 12 | Raises: 13 | TypeError: If the input is the string, bool, list, tuple, or set. 14 | TypeError: If the input cannot be converted to a float. 15 | 16 | Returns: 17 | str: The half precision format of the input number. 18 | """ 19 | def __init__(self,number): 20 | if isinstance(number,(str,bool,list,tuple,set)): 21 | raise TypeError(f"Invalid input {type(number)}") 22 | try: 23 | self.__number = number / 1 24 | except Exception as e: 25 | raise TypeError("Input {} cannot be converted to a float".format(e.args[0])) 26 | 27 | def __str__(self)->str: 28 | """ 29 | Returns the half precision format of the input number. 30 | 31 | Returns: 32 | str: The half precision format of the input number. 33 | """ 34 | return self.__calculate_precision(5,10,self.__number) #for half precision 35 | 36 | def __calculate_precision(self,exponent_length:int,mantissa_length:int,number:float)->str: 37 | """ 38 | This function calculates the half precision format of the input number. 39 | """ 40 | sign= False 41 | 42 | if number < 0 or np.signbit(number): 43 | sign = True 44 | number = -number 45 | 46 | number = self.__is_calculatable_mantissa(number,mantissa_length,exponent_length) 47 | 48 | if np.isinf(number): 49 | return f"{int(sign)}{'1'*exponent_length}{'0'*mantissa_length}" 50 | 51 | bias= 2**(exponent_length-1)-1 52 | mantissa,power = self.__calculate_mantissa(mantissa_length,number) 53 | 54 | if power == None: 55 | return f"{int(sign)}{'0'*exponent_length}{'0'*mantissa_length}" 56 | 57 | exponent = self.__calculate_exponent(bias,power,exponent_length) 58 | 59 | return f"{int(sign)}{exponent}{mantissa}" 60 | 61 | def __calculate_exponent(self,bias:int,power:int,exponent_length)->str: 62 | """ 63 | This function calculates the exponent part of the half precision format. 64 | """ 65 | binary_exponent = self.__integer_to_binary(bias+power) 66 | 67 | if len(binary_exponent) < exponent_length: 68 | binary_exponent = '0' * (exponent_length - len(binary_exponent)) + binary_exponent 69 | 70 | return binary_exponent 71 | 72 | def __calculate_mantissa(self,mantissa_length:int,number:float)->str: 73 | """ 74 | This function calculates the mantissa part of the half precision format. 75 | """ 76 | integer_part,decimal_part = f"{number:.20f}".split(".") 77 | integer_part = self.__integer_to_binary(integer_part) 78 | decimal_part = self.__decimal_to_binary(decimal_part) 79 | 80 | mantissa = f'{integer_part}.{decimal_part}' 81 | 82 | if not '1' in mantissa: 83 | return '0'*mantissa_length,None 84 | 85 | power = 0 86 | index1 = mantissa_length 87 | 88 | indexdot = mantissa.index(".") 89 | index1 = mantissa.index("1") 90 | mantissa = mantissa[index1+1:].replace(".","") 91 | power = indexdot - index1 if indexdot < index1 else indexdot - index1 -1 92 | 93 | if len(mantissa)< mantissa_length: 94 | mantissa += '0' * (mantissa_length - len(mantissa)) 95 | elif len(mantissa)> mantissa_length: 96 | mantissa = mantissa[:mantissa_length] #Truncating 97 | # mantissa = mantissa[:mantissa_length-1] + '1' #Rounding 98 | 99 | return mantissa,power 100 | 101 | def __is_calculatable_mantissa(self, number: float, mantissa_length: int, exponent_length: int) -> float: 102 | """ 103 | This function checks if the input number is calculatable in custom precision format. 104 | """ 105 | max_number = 2**(2**(exponent_length-1)-1) * (2-2**(-mantissa_length)) 106 | 107 | if number > max_number: 108 | return np.inf 109 | 110 | return number 111 | 112 | def __integer_to_binary(self,number:int)->str: 113 | 114 | result = "" 115 | number = int(number) 116 | 117 | if number == 0: 118 | return "0" 119 | 120 | while number != 0: 121 | remainder = number % 2 122 | result += str(remainder) 123 | number //= 2 124 | 125 | return result[::-1] 126 | 127 | def __decimal_to_binary(self,number:float)->str: 128 | number=float(f"0.{number.split("0")[0]}") 129 | 130 | if number == 0: 131 | return '' 132 | 133 | binary = '' 134 | while number > 0 and len(binary) < 100: 135 | 136 | number *= 2 137 | if number >= 1: 138 | binary += '1' 139 | number -= 1 140 | else: 141 | binary += '0' 142 | 143 | return binary 144 | 145 | 146 | 147 | 148 | -------------------------------------------------------------------------------- /Week06/halfprecision_ufuk_dilek.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class HalfPrecision: 4 | 5 | __BIAS = 15 6 | 7 | def __init__(self, number: float): 8 | if type(number)!=float: 9 | raise TypeError("Please enter a float") 10 | if number > 65504: 11 | self.string_representation = "0111110000000000" 12 | return 13 | if number == float('inf'): 14 | self.string_representation = "0111110000000000" 15 | return 16 | elif number == float('-inf'): 17 | self.string_representation = "1111110000000000" 18 | return 19 | binary_representation = str(BinaryRepresentation(number)) 20 | sign_bit = '1' if binary_representation[0] == '-' else '0' 21 | abs_binary = binary_representation.replace("-", "") 22 | dot_index = abs_binary.index('.') 23 | exponent: int 24 | if abs_binary.startswith('1'): 25 | exponent = dot_index - 1 26 | else: 27 | decimal = abs_binary.partition('.')[2] 28 | if decimal.find('1') == -1: 29 | self.string_representation = "0000000000000000" \ 30 | if sign_bit == '0' else "1000000000000000" 31 | return 32 | else: 33 | exponent = -(decimal.index('1') + 1) 34 | biased = float(exponent + HalfPrecision.__BIAS) 35 | exponent_bits = BinaryRepresentation(biased).integer2binary() 36 | while len(exponent_bits) < 5: 37 | exponent_bits = '0' + exponent_bits 38 | ind_1 = abs_binary.index('1') 39 | ment = abs_binary[ind_1 + 1:] 40 | ment = ment.replace('.', '') 41 | length = len(ment) 42 | if length < 10: 43 | while len(ment) < 10: 44 | ment += '0' 45 | elif length > 10: 46 | ment = ment[:10] 47 | self.string_representation = sign_bit + exponent_bits + ment 48 | 49 | 50 | def __str__(self): 51 | return self.string_representation 52 | 53 | 54 | 55 | 56 | class BinaryRepresentation: 57 | 58 | def __init__(self, number: float): 59 | if not isinstance(number, float): 60 | raise TypeError('number is not a float') 61 | self.negative = True if str(number)[0] == '-' else False 62 | self.number = abs(number) 63 | 64 | def integer2binary(self): 65 | num_int = int(self.number) 66 | if num_int == 0: 67 | return "0" 68 | arr = [] 69 | while num_int > 0: 70 | arr.append(num_int % 2) 71 | num_int = num_int // 2 72 | arr.reverse() 73 | return self.int_array_to_string(arr) 74 | 75 | def decimal2binary(self): 76 | num_dec = self.number - int(self.number) 77 | arr = [] 78 | loop_count = 1 79 | while loop_count < 25: 80 | if num_dec == 0: 81 | break 82 | num_dec *= 2 83 | int_part = int(num_dec) 84 | arr.append(int_part) 85 | if int_part == 1: 86 | num_dec -= int_part 87 | loop_count += 1 88 | return self.int_array_to_string(arr) 89 | 90 | def __str__(self): 91 | prefix = "-" if self.negative else "" 92 | return prefix + self.integer2binary() + "." + self.decimal2binary() 93 | 94 | @staticmethod 95 | def int_array_to_string(arr) -> str: 96 | result = '' 97 | for i in arr: 98 | result += str(i) 99 | return result 100 | 101 | -------------------------------------------------------------------------------- /Week06/test_halfprecision.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import numpy as np 4 | import math 5 | 6 | 7 | files = [ 8 | f for f in os.listdir(os.path.dirname(__file__)) if f.startswith("halfprecision") 9 | ] 10 | for f in files: 11 | exec("import " + f[:-3] + " as " + f[:-3]) 12 | 13 | 14 | @pytest.mark.parametrize( 15 | "input, expected", 16 | [ 17 | (0.15625, "0011000100000000"), 18 | (13.375, "0100101010110000"), 19 | (-13.375, "1100101010110000"), 20 | (0.0, "0000000000000000"), 21 | (-0.0, "1000000000000000"), 22 | (0.1, "0010111001100110"), 23 | (-0.1, "1010111001100110"), 24 | (0.2, "0011001001100110"), 25 | (-86.954, "1101010101101111"), 26 | (397.4532 * 10**10, "0111110000000000"), 27 | (np.inf, "0111110000000000"), 28 | (-np.inf, "1111110000000000"), 29 | ], 30 | ) 31 | def test_half_precision(input, expected): 32 | for f in files: 33 | assert str(eval(f[:-3]).HalfPrecision(input)) == expected 34 | 35 | 36 | def test_half_precision_error(): 37 | for f in files: 38 | with pytest.raises(TypeError): 39 | eval(f[:-3]).HalfPrecision("abc") 40 | with pytest.raises(TypeError): 41 | eval(f[:-3]).HalfPrecision(True) 42 | with pytest.raises(TypeError): 43 | eval(f[:-3]).HalfPrecision(False) 44 | with pytest.raises(TypeError): 45 | eval(f[:-3]).HalfPrecision(None) 46 | with pytest.raises(TypeError): 47 | eval(f[:-3]).HalfPrecision([1, 2, 3]) 48 | with pytest.raises(TypeError): 49 | eval(f[:-3]).HalfPrecision((1, 2, 3)) 50 | with pytest.raises(TypeError): 51 | eval(f[:-3]).HalfPrecision({1, 2, 3}) 52 | 53 | 54 | if __name__ == "__main__": 55 | pytest.main(["-v", __file__]) 56 | -------------------------------------------------------------------------------- /Week07/bisection_method.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def bisection(f, a, b, tol): 5 | if a > b: 6 | raise ValueError("b must be larger than a") 7 | i = 0 8 | while True: 9 | if i > 1.0e6: 10 | raise ValueError("Could not find the solution with the desired accuracy") 11 | i += 1 12 | fa = f(a) 13 | fb = f(b) 14 | if fa * fb > 0: 15 | raise ValueError("This interval does not contain a root") 16 | c = (a + b) / 2 17 | fc = f(c) 18 | if abs(fc) < tol or abs(b - a) < tol: 19 | return c 20 | else: 21 | if fa * fc < 0: 22 | b = c 23 | else: 24 | a = c 25 | print(f"i={i:6d} a={a:.7f} | b={b:.7f} | c={c:.7f}") 26 | 27 | 28 | def f(x): 29 | return math.sin(x) / x 30 | 31 | 32 | if __name__ == "__main__": 33 | a_ = 1 34 | b_ = 4 35 | tol_ = 1.0e-6 36 | try: 37 | root = bisection(f, a_, b_, tol_) 38 | except Exception as e: 39 | print(f"Error: {e}") 40 | else: 41 | print(f"Root: {root}") 42 | finally: 43 | print("End") 44 | -------------------------------------------------------------------------------- /Week08/numerical_derivative.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | 5 | def first_forward(f, x, h): 6 | return (f(x + h) - f(x)) / h 7 | 8 | 9 | def fn(x): 10 | return math.sin(x) 11 | 12 | 13 | if __name__ == "__main__": 14 | x = random.random() * math.pi 15 | for h in [1.0e-1, 1.0e-2, 1.0e-3, 1.0e-4, 1.0e-5, 1.0e-6]: 16 | print( 17 | f""" 18 | x={x:.3f} 19 | h={h:.1e} 20 | sin(x)={fn(x):.3f} 21 | f'(x)={first_forward(fn, x, h)} 22 | """ 23 | ) 24 | -------------------------------------------------------------------------------- /Week09/newton_raphson.py: -------------------------------------------------------------------------------- 1 | def first_forward(f, x, h): 2 | return (f(x + h) - f(x)) / h 3 | 4 | 5 | def fn(x): 6 | return x**2 - 2 7 | 8 | 9 | def newton_raphson(f, x0, tol=1.0e-6, max_iter=100): 10 | x = x0 11 | prev_x = x 12 | for i in range(max_iter): 13 | fx = f(x) 14 | fprimex = first_forward(f, x, tol) 15 | x = x - fx / fprimex 16 | print(f"i={i} x={x:.6f} f(x)={fx:.6e}") 17 | if abs(fx) < tol or abs(prev_x - x) < tol: 18 | return x 19 | prev_x = x 20 | 21 | 22 | if __name__ == "__main__": 23 | x0 = 100000.0 24 | print(newton_raphson(fn, x0)) 25 | -------------------------------------------------------------------------------- /Week09/newton_raphson_linear_regression.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | 5 | def first_forward(f, x, h): 6 | return (f(x + h) - f(x)) / h 7 | 8 | 9 | def mse(a, b, x, y): 10 | return np.mean((y - (a * x + b)) ** 2) 11 | 12 | 13 | def newton_raphson(f, x0, tol=1.0e-6, max_iter=100000, patience=1000): 14 | x = x0 15 | fx = np.inf 16 | best_x = x 17 | for i in range(max_iter): 18 | x = x - f(x) / first_forward(f, x, 1.0e-6) 19 | print(f"i={i} x={x:.6f} f(x)={f(x):.6f}") 20 | if f(x) < fx: 21 | fx = f(x) 22 | best_x = x 23 | else: 24 | patience -= 1 25 | if patience < 0: 26 | break 27 | if abs(f(x)) < tol: 28 | return x 29 | return best_x 30 | 31 | 32 | if __name__ == "__main__": 33 | np.random.seed(7) 34 | a0 = 2.0 35 | b0 = 1.0 36 | x = np.linspace(0, 10, 100) 37 | y = a0 * x + b0 + np.random.normal(0, 1, 100) 38 | 39 | a = np.linspace(0, 4, 100) 40 | b = np.linspace(-2, 4, 100) 41 | 42 | plt.plot(a, np.array([mse(a_val, b0, x, y) for a_val in a]), label="MSE(a, b0)") 43 | plt.plot(a, np.array([mse(a_val, 2.0, x, y) for a_val in a]), label="MSE(a, b0=2)") 44 | plt.plot(a, np.array([mse(a_val, 3.0, x, y) for a_val in a]), label="MSE(a, b0=3)") 45 | plt.plot(b, np.array([mse(a0, b_val, x, y) for b_val in b]), label="MSE(a0, b)") 46 | plt.legend() 47 | plt.show() 48 | 49 | mse_values = np.array([[mse(a_val, b_val, x, y) for b_val in b] for a_val in a]) 50 | plt.contourf(a, b, mse_values, levels=20) 51 | plt.colorbar() 52 | plt.xlabel("a") 53 | plt.ylabel("b") 54 | plt.show() 55 | 56 | f = lambda a: mse(a, b0, x, y) 57 | a_optimal = newton_raphson(f, a0, patience=1000) 58 | f = lambda b: mse(a_optimal, b, x, y) 59 | b_optimal = newton_raphson(f, b0, patience=1000) 60 | print(f"Optimal a: {a_optimal}") 61 | print(f"Optimal b: {b_optimal}") 62 | print(f"Optimal MSE: {mse(a_optimal, b_optimal, x, y)}") 63 | plt.scatter(x, y) 64 | plt.plot(x, a_optimal * x + b_optimal, color="red") 65 | plt.show() 66 | -------------------------------------------------------------------------------- /Week10/midpoint_rule.py: -------------------------------------------------------------------------------- 1 | def f(x: float) -> float: 2 | return x**2 - 2 3 | 4 | 5 | def f_int(x: float) -> float: 6 | return x**3 / 3 - 2 * x 7 | 8 | 9 | def midpoint_rule(func: callable, a: float, b: float, n: int) -> float: 10 | """ 11 | Midpoint rule using n points 12 | :param func: function to integrate 13 | :param a: lower bound of integration 14 | :param b: upper bound of integration 15 | :param n: number of points 16 | :return: integral 17 | """ 18 | h = (b - a) / n 19 | s = 0.0 20 | for i in range(n): 21 | s += func(a + (i + 0.5) * h) 22 | return h * s 23 | 24 | 25 | def main(): 26 | for n in [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]: 27 | a = 0.0 28 | b = 1.0 29 | print(f"{n:8d} " 30 | f"{midpoint_rule(f, a, b, n):.6f} " 31 | f"({abs(f_int(b) - f_int(a) - midpoint_rule(f, a, b, n)):8.2e})") 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /Week10/simpsons_rule.py: -------------------------------------------------------------------------------- 1 | def f(x: float) -> float: 2 | return x**2 - 2 3 | 4 | 5 | def f_int(x: float) -> float: 6 | return x**3 / 3 - 2 * x 7 | 8 | 9 | def simpsons_rule(func: callable, a: float, b: float, n: int) -> float: 10 | """ 11 | Simpson's rule using n points 12 | :param func: function to integrate 13 | :param a: lower bound of integration 14 | :param b: upper bound of integration 15 | :param n: number of points 16 | :return: integral 17 | """ 18 | h = (b - a) / n 19 | s = func(a) + func(b) 20 | for i in range(1, n, 2): 21 | s += 4 * func(a + i * h) 22 | for i in range(2, n - 1, 2): 23 | s += 2 * func(a + i * h) 24 | return h / 3 * s 25 | 26 | 27 | def main(): 28 | for n in [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]: 29 | a = 0.0 30 | b = 1.0 31 | print(f"{n:8d} " 32 | f"{simpsons_rule(f, a, b, n):.6f} " 33 | f"({abs(f_int(b) - f_int(a) - simpsons_rule(f, a, b, n)):8.2e})") 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /Week10/trapezoidal_rule.py: -------------------------------------------------------------------------------- 1 | def f(x: float) -> float: 2 | return x**2 - 2 3 | 4 | 5 | def f_int(x: float) -> float: 6 | return x**3 / 3 - 2 * x 7 | 8 | 9 | def trapezoidal_rule(func: callable, a: float, b: float, n: int) -> float: 10 | """ 11 | Trapezoidal rule using n points 12 | :param func: function to integrate 13 | :param a: lower bound of integration 14 | :param b: upper bound of integration 15 | :param n: number of points 16 | :return: integral 17 | """ 18 | h = (b - a) / n 19 | s = 0.5 * (func(a) + func(b)) 20 | for i in range(1, n): 21 | s += func(a + i * h) 22 | return h * s 23 | 24 | 25 | def main(): 26 | for n in [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]: 27 | a = 0.0 28 | b = 1.0 29 | print(f"{n:8d} " 30 | f"{trapezoidal_rule(f, a, b, n):.6f} " 31 | f"({abs(f_int(b) - f_int(a) - trapezoidal_rule(f, a, b, n)):8.2e})") 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | --------------------------------------------------------------------------------