repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is used to convert the currency using the Amdoren Currency API https://www.amdoren.com """ import os import requests URL_BASE = "https://www.amdoren.com/api/currency.php" TESTING = os.getenv("CI", False) API_KEY = os.getenv("AMDOREN_API_KEY", "") if not API_KEY and not TESTING: raise KeyError( "API key must be provided in the 'AMDOREN_API_KEY' environment variable." ) # Currency and their description list_of_currencies = """ AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Netherlands Antillean Guilder AOA Angolan Kwanza ARS Argentine Peso AUD Australian Dollar AWG Aruban Florin AZN Azerbaijani Manat BAM Bosnia & Herzegovina Convertible Mark BBD Barbadian Dollar BDT Bangladeshi Taka BGN Bulgarian Lev BHD Bahraini Dinar BIF Burundian Franc BMD Bermudian Dollar BND Brunei Dollar BOB Bolivian Boliviano BRL Brazilian Real BSD Bahamian Dollar BTN Bhutanese Ngultrum BWP Botswana Pula BYN Belarus Ruble BZD Belize Dollar CAD Canadian Dollar CDF Congolese Franc CHF Swiss Franc CLP Chilean Peso CNY Chinese Yuan COP Colombian Peso CRC Costa Rican Colon CUC Cuban Convertible Peso CVE Cape Verdean Escudo CZK Czech Republic Koruna DJF Djiboutian Franc DKK Danish Krone DOP Dominican Peso DZD Algerian Dinar EGP Egyptian Pound ERN Eritrean Nakfa ETB Ethiopian Birr EUR Euro FJD Fiji Dollar GBP British Pound Sterling GEL Georgian Lari GHS Ghanaian Cedi GIP Gibraltar Pound GMD Gambian Dalasi GNF Guinea Franc GTQ Guatemalan Quetzal GYD Guyanaese Dollar HKD Hong Kong Dollar HNL Honduran Lempira HRK Croatian Kuna HTG Haiti Gourde HUF Hungarian Forint IDR Indonesian Rupiah ILS Israeli Shekel INR Indian Rupee IQD Iraqi Dinar IRR Iranian Rial ISK Icelandic Krona JMD Jamaican Dollar JOD Jordanian Dinar JPY Japanese Yen KES Kenyan Shilling KGS Kyrgystani Som KHR Cambodian Riel KMF Comorian Franc KPW North Korean Won KRW South Korean Won KWD Kuwaiti Dinar KYD Cayman Islands Dollar KZT Kazakhstan Tenge LAK Laotian Kip LBP Lebanese Pound LKR Sri Lankan Rupee LRD Liberian Dollar LSL Lesotho Loti LYD Libyan Dinar MAD Moroccan Dirham MDL Moldovan Leu MGA Malagasy Ariary MKD Macedonian Denar MMK Myanma Kyat MNT Mongolian Tugrik MOP Macau Pataca MRO Mauritanian Ouguiya MUR Mauritian Rupee MVR Maldivian Rufiyaa MWK Malawi Kwacha MXN Mexican Peso MYR Malaysian Ringgit MZN Mozambican Metical NAD Namibian Dollar NGN Nigerian Naira NIO Nicaragua Cordoba NOK Norwegian Krone NPR Nepalese Rupee NZD New Zealand Dollar OMR Omani Rial PAB Panamanian Balboa PEN Peruvian Nuevo Sol PGK Papua New Guinean Kina PHP Philippine Peso PKR Pakistani Rupee PLN Polish Zloty PYG Paraguayan Guarani QAR Qatari Riyal RON Romanian Leu RSD Serbian Dinar RUB Russian Ruble RWF Rwanda Franc SAR Saudi Riyal SBD Solomon Islands Dollar SCR Seychellois Rupee SDG Sudanese Pound SEK Swedish Krona SGD Singapore Dollar SHP Saint Helena Pound SLL Sierra Leonean Leone SOS Somali Shilling SRD Surinamese Dollar SSP South Sudanese Pound STD Sao Tome and Principe Dobra SYP Syrian Pound SZL Swazi Lilangeni THB Thai Baht TJS Tajikistan Somoni TMT Turkmenistani Manat TND Tunisian Dinar TOP Tonga Paanga TRY Turkish Lira TTD Trinidad and Tobago Dollar TWD New Taiwan Dollar TZS Tanzanian Shilling UAH Ukrainian Hryvnia UGX Ugandan Shilling USD United States Dollar UYU Uruguayan Peso UZS Uzbekistan Som VEF Venezuelan Bolivar VND Vietnamese Dong VUV Vanuatu Vatu WST Samoan Tala XAF Central African CFA franc XCD East Caribbean Dollar XOF West African CFA franc XPF CFP Franc YER Yemeni Rial ZAR South African Rand ZMW Zambian Kwacha """ def convert_currency( from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = API_KEY ) -> str: """https://www.amdoren.com/currency-api/""" params = locals() params["from"] = params.pop("from_") res = requests.get(URL_BASE, params=params).json() return str(res["amount"]) if res["error"] == 0 else res["error_message"] if __name__ == "__main__": print( convert_currency( input("Enter from currency: ").strip(), input("Enter to currency: ").strip(), float(input("Enter the amount: ").strip()), ) )
""" This is used to convert the currency using the Amdoren Currency API https://www.amdoren.com """ import os import requests URL_BASE = "https://www.amdoren.com/api/currency.php" TESTING = os.getenv("CI", "") API_KEY = os.getenv("AMDOREN_API_KEY", "") if not API_KEY and not TESTING: raise KeyError( "API key must be provided in the 'AMDOREN_API_KEY' environment variable." ) # Currency and their description list_of_currencies = """ AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Netherlands Antillean Guilder AOA Angolan Kwanza ARS Argentine Peso AUD Australian Dollar AWG Aruban Florin AZN Azerbaijani Manat BAM Bosnia & Herzegovina Convertible Mark BBD Barbadian Dollar BDT Bangladeshi Taka BGN Bulgarian Lev BHD Bahraini Dinar BIF Burundian Franc BMD Bermudian Dollar BND Brunei Dollar BOB Bolivian Boliviano BRL Brazilian Real BSD Bahamian Dollar BTN Bhutanese Ngultrum BWP Botswana Pula BYN Belarus Ruble BZD Belize Dollar CAD Canadian Dollar CDF Congolese Franc CHF Swiss Franc CLP Chilean Peso CNY Chinese Yuan COP Colombian Peso CRC Costa Rican Colon CUC Cuban Convertible Peso CVE Cape Verdean Escudo CZK Czech Republic Koruna DJF Djiboutian Franc DKK Danish Krone DOP Dominican Peso DZD Algerian Dinar EGP Egyptian Pound ERN Eritrean Nakfa ETB Ethiopian Birr EUR Euro FJD Fiji Dollar GBP British Pound Sterling GEL Georgian Lari GHS Ghanaian Cedi GIP Gibraltar Pound GMD Gambian Dalasi GNF Guinea Franc GTQ Guatemalan Quetzal GYD Guyanaese Dollar HKD Hong Kong Dollar HNL Honduran Lempira HRK Croatian Kuna HTG Haiti Gourde HUF Hungarian Forint IDR Indonesian Rupiah ILS Israeli Shekel INR Indian Rupee IQD Iraqi Dinar IRR Iranian Rial ISK Icelandic Krona JMD Jamaican Dollar JOD Jordanian Dinar JPY Japanese Yen KES Kenyan Shilling KGS Kyrgystani Som KHR Cambodian Riel KMF Comorian Franc KPW North Korean Won KRW South Korean Won KWD Kuwaiti Dinar KYD Cayman Islands Dollar KZT Kazakhstan Tenge LAK Laotian Kip LBP Lebanese Pound LKR Sri Lankan Rupee LRD Liberian Dollar LSL Lesotho Loti LYD Libyan Dinar MAD Moroccan Dirham MDL Moldovan Leu MGA Malagasy Ariary MKD Macedonian Denar MMK Myanma Kyat MNT Mongolian Tugrik MOP Macau Pataca MRO Mauritanian Ouguiya MUR Mauritian Rupee MVR Maldivian Rufiyaa MWK Malawi Kwacha MXN Mexican Peso MYR Malaysian Ringgit MZN Mozambican Metical NAD Namibian Dollar NGN Nigerian Naira NIO Nicaragua Cordoba NOK Norwegian Krone NPR Nepalese Rupee NZD New Zealand Dollar OMR Omani Rial PAB Panamanian Balboa PEN Peruvian Nuevo Sol PGK Papua New Guinean Kina PHP Philippine Peso PKR Pakistani Rupee PLN Polish Zloty PYG Paraguayan Guarani QAR Qatari Riyal RON Romanian Leu RSD Serbian Dinar RUB Russian Ruble RWF Rwanda Franc SAR Saudi Riyal SBD Solomon Islands Dollar SCR Seychellois Rupee SDG Sudanese Pound SEK Swedish Krona SGD Singapore Dollar SHP Saint Helena Pound SLL Sierra Leonean Leone SOS Somali Shilling SRD Surinamese Dollar SSP South Sudanese Pound STD Sao Tome and Principe Dobra SYP Syrian Pound SZL Swazi Lilangeni THB Thai Baht TJS Tajikistan Somoni TMT Turkmenistani Manat TND Tunisian Dinar TOP Tonga Paanga TRY Turkish Lira TTD Trinidad and Tobago Dollar TWD New Taiwan Dollar TZS Tanzanian Shilling UAH Ukrainian Hryvnia UGX Ugandan Shilling USD United States Dollar UYU Uruguayan Peso UZS Uzbekistan Som VEF Venezuelan Bolivar VND Vietnamese Dong VUV Vanuatu Vatu WST Samoan Tala XAF Central African CFA franc XCD East Caribbean Dollar XOF West African CFA franc XPF CFP Franc YER Yemeni Rial ZAR South African Rand ZMW Zambian Kwacha """ def convert_currency( from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = API_KEY ) -> str: """https://www.amdoren.com/currency-api/""" params = locals() params["from"] = params.pop("from_") res = requests.get(URL_BASE, params=params).json() return str(res["amount"]) if res["error"] == 0 else res["error_message"] if __name__ == "__main__": print( convert_currency( input("Enter from currency: ").strip(), input("Enter to currency: ").strip(), float(input("Enter the amount: ").strip()), ) )
1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Find the kinetic energy of an object, given its mass and velocity. Description : In physics, the kinetic energy of an object is the energy that it possesses due to its motion.It is defined as the work needed to accelerate a body of a given mass from rest to its stated velocity.Having gained this energy during its acceleration, the body maintains this kinetic energy unless its speed changes.The same amount of work is done by the body when decelerating from its current speed to a state of rest.Formally, a kinetic energy is any term in a system's Lagrangian which includes a derivative with respect to time. In classical mechanics, the kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv².In relativistic mechanics, this is a good approximation only when v is much less than the speed of light.The standard unit of kinetic energy is the joule, while the English unit of kinetic energy is the foot-pound. Reference : https://en.m.wikipedia.org/wiki/Kinetic_energy """ def kinetic_energy(mass: float, velocity: float) -> float: """ Calculate kinetic energy. The kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv² >>> kinetic_energy(10,10) 500.0 >>> kinetic_energy(0,10) 0.0 >>> kinetic_energy(10,0) 0.0 >>> kinetic_energy(20,-20) 4000.0 >>> kinetic_energy(0,0) 0.0 >>> kinetic_energy(2,2) 4.0 >>> kinetic_energy(100,100) 500000.0 """ if mass < 0: raise ValueError("The mass of a body cannot be negative") return 0.5 * mass * abs(velocity) * abs(velocity) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
""" Find the kinetic energy of an object, given its mass and velocity. Description : In physics, the kinetic energy of an object is the energy that it possesses due to its motion.It is defined as the work needed to accelerate a body of a given mass from rest to its stated velocity.Having gained this energy during its acceleration, the body maintains this kinetic energy unless its speed changes.The same amount of work is done by the body when decelerating from its current speed to a state of rest.Formally, a kinetic energy is any term in a system's Lagrangian which includes a derivative with respect to time. In classical mechanics, the kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv².In relativistic mechanics, this is a good approximation only when v is much less than the speed of light.The standard unit of kinetic energy is the joule, while the English unit of kinetic energy is the foot-pound. Reference : https://en.m.wikipedia.org/wiki/Kinetic_energy """ def kinetic_energy(mass: float, velocity: float) -> float: """ Calculate kinetic energy. The kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv² >>> kinetic_energy(10,10) 500.0 >>> kinetic_energy(0,10) 0.0 >>> kinetic_energy(10,0) 0.0 >>> kinetic_energy(20,-20) 4000.0 >>> kinetic_energy(0,0) 0.0 >>> kinetic_energy(2,2) 4.0 >>> kinetic_energy(100,100) 500000.0 """ if mass < 0: raise ValueError("The mass of a body cannot be negative") return 0.5 * mass * abs(velocity) * abs(velocity) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 131: https://projecteuler.net/problem=131 There are some prime values, p, for which there exists a positive integer, n, such that the expression n^3 + n^2p is a perfect cube. For example, when p = 19, 8^3 + 8^2 x 19 = 12^3. What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred. How many primes below one million have this remarkable property? """ from math import isqrt def is_prime(number: int) -> bool: """ Determines whether number is prime >>> is_prime(3) True >>> is_prime(4) False """ for divisor in range(2, isqrt(number) + 1): if number % divisor == 0: return False return True def solution(max_prime: int = 10**6) -> int: """ Returns number of primes below max_prime with the property >>> solution(100) 4 """ primes_count = 0 cube_index = 1 prime_candidate = 7 while prime_candidate < max_prime: primes_count += is_prime(prime_candidate) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 131: https://projecteuler.net/problem=131 There are some prime values, p, for which there exists a positive integer, n, such that the expression n^3 + n^2p is a perfect cube. For example, when p = 19, 8^3 + 8^2 x 19 = 12^3. What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred. How many primes below one million have this remarkable property? """ from math import isqrt def is_prime(number: int) -> bool: """ Determines whether number is prime >>> is_prime(3) True >>> is_prime(4) False """ for divisor in range(2, isqrt(number) + 1): if number % divisor == 0: return False return True def solution(max_prime: int = 10**6) -> int: """ Returns number of primes below max_prime with the property >>> solution(100) 4 """ primes_count = 0 cube_index = 1 prime_candidate = 7 while prime_candidate < max_prime: primes_count += is_prime(prime_candidate) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implemented an algorithm using opencv to convert a colored image into its negative """ from cv2 import destroyAllWindows, imread, imshow, waitKey def convert_to_negative(img): # getting number of pixels in the image pixel_h, pixel_v = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(pixel_h): for j in range(pixel_v): img[i][j] = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image img = imread("image_data/lena.jpg", 1) # convert to its negative neg = convert_to_negative(img) # show result image imshow("negative of original image", img) waitKey(0) destroyAllWindows()
""" Implemented an algorithm using opencv to convert a colored image into its negative """ from cv2 import destroyAllWindows, imread, imshow, waitKey def convert_to_negative(img): # getting number of pixels in the image pixel_h, pixel_v = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(pixel_h): for j in range(pixel_v): img[i][j] = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image img = imread("image_data/lena.jpg", 1) # convert to its negative neg = convert_to_negative(img) # show result image imshow("negative of original image", img) waitKey(0) destroyAllWindows()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Autokey_cipher An autokey cipher (also known as the autoclave cipher) is a cipher that incorporates the message (the plaintext) into the key. The key is generated from the message in some automated fashion, sometimes by selecting certain letters from the text or, more commonly, by adding a short primer key to the front of the message. """ def encrypt(plaintext: str, key: str) -> str: """ Encrypt a given plaintext (string) and key (string), returning the encrypted ciphertext. >>> encrypt("hello world", "coffee") 'jsqqs avvwo' >>> encrypt("coffee is good as python", "TheAlgorithms") 'vvjfpk wj ohvp su ddylsv' >>> encrypt("coffee is good as python", 2) Traceback (most recent call last): ... TypeError: key must be a string >>> encrypt("", "TheAlgorithms") Traceback (most recent call last): ... ValueError: plaintext is empty """ if not isinstance(plaintext, str): raise TypeError("plaintext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not plaintext: raise ValueError("plaintext is empty") if not key: raise ValueError("key is empty") key += plaintext plaintext = plaintext.lower() key = key.lower() plaintext_iterator = 0 key_iterator = 0 ciphertext = "" while plaintext_iterator < len(plaintext): if ( ord(plaintext[plaintext_iterator]) < 97 or ord(plaintext[plaintext_iterator]) > 122 ): ciphertext += plaintext[plaintext_iterator] plaintext_iterator += 1 elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122: key_iterator += 1 else: ciphertext += chr( ( (ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator])) - 97 ) % 26 + 97 ) key_iterator += 1 plaintext_iterator += 1 return ciphertext def decrypt(ciphertext: str, key: str) -> str: """ Decrypt a given ciphertext (string) and key (string), returning the decrypted ciphertext. >>> decrypt("jsqqs avvwo", "coffee") 'hello world' >>> decrypt("vvjfpk wj ohvp su ddylsv", "TheAlgorithms") 'coffee is good as python' >>> decrypt("vvjfpk wj ohvp su ddylsv", "") Traceback (most recent call last): ... ValueError: key is empty >>> decrypt(527.26, "TheAlgorithms") Traceback (most recent call last): ... TypeError: ciphertext must be a string """ if not isinstance(ciphertext, str): raise TypeError("ciphertext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not ciphertext: raise ValueError("ciphertext is empty") if not key: raise ValueError("key is empty") key = key.lower() ciphertext_iterator = 0 key_iterator = 0 plaintext = "" while ciphertext_iterator < len(ciphertext): if ( ord(ciphertext[ciphertext_iterator]) < 97 or ord(ciphertext[ciphertext_iterator]) > 122 ): plaintext += ciphertext[ciphertext_iterator] else: plaintext += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key_iterator += 1 ciphertext_iterator += 1 return plaintext if __name__ == "__main__": import doctest doctest.testmod() operation = int(input("Type 1 to encrypt or 2 to decrypt:")) if operation == 1: plaintext = input("Typeplaintext to be encrypted:\n") key = input("Type the key:\n") print(encrypt(plaintext, key)) elif operation == 2: ciphertext = input("Type the ciphertext to be decrypted:\n") key = input("Type the key:\n") print(decrypt(ciphertext, key)) decrypt("jsqqs avvwo", "coffee")
""" https://en.wikipedia.org/wiki/Autokey_cipher An autokey cipher (also known as the autoclave cipher) is a cipher that incorporates the message (the plaintext) into the key. The key is generated from the message in some automated fashion, sometimes by selecting certain letters from the text or, more commonly, by adding a short primer key to the front of the message. """ def encrypt(plaintext: str, key: str) -> str: """ Encrypt a given plaintext (string) and key (string), returning the encrypted ciphertext. >>> encrypt("hello world", "coffee") 'jsqqs avvwo' >>> encrypt("coffee is good as python", "TheAlgorithms") 'vvjfpk wj ohvp su ddylsv' >>> encrypt("coffee is good as python", 2) Traceback (most recent call last): ... TypeError: key must be a string >>> encrypt("", "TheAlgorithms") Traceback (most recent call last): ... ValueError: plaintext is empty """ if not isinstance(plaintext, str): raise TypeError("plaintext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not plaintext: raise ValueError("plaintext is empty") if not key: raise ValueError("key is empty") key += plaintext plaintext = plaintext.lower() key = key.lower() plaintext_iterator = 0 key_iterator = 0 ciphertext = "" while plaintext_iterator < len(plaintext): if ( ord(plaintext[plaintext_iterator]) < 97 or ord(plaintext[plaintext_iterator]) > 122 ): ciphertext += plaintext[plaintext_iterator] plaintext_iterator += 1 elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122: key_iterator += 1 else: ciphertext += chr( ( (ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator])) - 97 ) % 26 + 97 ) key_iterator += 1 plaintext_iterator += 1 return ciphertext def decrypt(ciphertext: str, key: str) -> str: """ Decrypt a given ciphertext (string) and key (string), returning the decrypted ciphertext. >>> decrypt("jsqqs avvwo", "coffee") 'hello world' >>> decrypt("vvjfpk wj ohvp su ddylsv", "TheAlgorithms") 'coffee is good as python' >>> decrypt("vvjfpk wj ohvp su ddylsv", "") Traceback (most recent call last): ... ValueError: key is empty >>> decrypt(527.26, "TheAlgorithms") Traceback (most recent call last): ... TypeError: ciphertext must be a string """ if not isinstance(ciphertext, str): raise TypeError("ciphertext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not ciphertext: raise ValueError("ciphertext is empty") if not key: raise ValueError("key is empty") key = key.lower() ciphertext_iterator = 0 key_iterator = 0 plaintext = "" while ciphertext_iterator < len(ciphertext): if ( ord(ciphertext[ciphertext_iterator]) < 97 or ord(ciphertext[ciphertext_iterator]) > 122 ): plaintext += ciphertext[ciphertext_iterator] else: plaintext += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key_iterator += 1 ciphertext_iterator += 1 return plaintext if __name__ == "__main__": import doctest doctest.testmod() operation = int(input("Type 1 to encrypt or 2 to decrypt:")) if operation == 1: plaintext = input("Typeplaintext to be encrypted:\n") key = input("Type the key:\n") print(encrypt(plaintext, key)) elif operation == 2: ciphertext = input("Type the ciphertext to be decrypted:\n") key = input("Type the key:\n") print(decrypt(ciphertext, key)) decrypt("jsqqs avvwo", "coffee")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py or python3 -m doctest -v sentinel_linear_search.py For manual testing run: python sentinel_linear_search.py """ def sentinel_linear_search(sequence, target): """Pure implementation of sentinel linear search algorithm in Python :param sequence: some sequence with comparable items :param target: item value to search :return: index of found item or None if item is not found Examples: >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) 0 >>> sentinel_linear_search([0, 5, 7, 10, 15], 15) 4 >>> sentinel_linear_search([0, 5, 7, 10, 15], 5) 1 >>> sentinel_linear_search([0, 5, 7, 10, 15], 6) """ sequence.append(target) index = 0 while sequence[index] != target: index += 1 sequence.pop() if index == len(sequence): return None return index if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item) for item in user_input.split(",")] target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
""" This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py or python3 -m doctest -v sentinel_linear_search.py For manual testing run: python sentinel_linear_search.py """ def sentinel_linear_search(sequence, target): """Pure implementation of sentinel linear search algorithm in Python :param sequence: some sequence with comparable items :param target: item value to search :return: index of found item or None if item is not found Examples: >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) 0 >>> sentinel_linear_search([0, 5, 7, 10, 15], 15) 4 >>> sentinel_linear_search([0, 5, 7, 10, 15], 5) 1 >>> sentinel_linear_search([0, 5, 7, 10, 15], 6) """ sequence.append(target) index = 0 while sequence[index] != target: index += 1 sequence.pop() if index == len(sequence): return None return index if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item) for item in user_input.split(",")] target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Boolean Algebra Boolean algebra is used to do arithmetic with bits of values True (1) or False (0). There are three basic operations: 'and', 'or' and 'not'. * <https://en.wikipedia.org/wiki/Boolean_algebra> * <https://plato.stanford.edu/entries/boolalg-math/>
# Boolean Algebra Boolean algebra is used to do arithmetic with bits of values True (1) or False (0). There are three basic operations: 'and', 'or' and 'not'. * <https://en.wikipedia.org/wiki/Boolean_algebra> * <https://plato.stanford.edu/entries/boolalg-math/>
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Hash map with open addressing. https://en.wikipedia.org/wiki/Hash_table Another hash map implementation, with a good explanation. Modern Dictionaries by Raymond Hettinger https://www.youtube.com/watch?v=p33CVV29OG8 """ from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar KEY = TypeVar("KEY") VAL = TypeVar("VAL") @dataclass(frozen=True, slots=True) class _Item(Generic[KEY, VAL]): key: KEY val: VAL class _DeletedItem(_Item): def __init__(self) -> None: super().__init__(None, None) def __bool__(self) -> bool: return False _deleted = _DeletedItem() class HashMap(MutableMapping[KEY, VAL]): """ Hash map with open addressing. """ def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 ) -> None: self._initial_block_size = initial_block_size self._buckets: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 self._capacity_factor = capacity_factor self._len = 0 def _get_bucket_index(self, key: KEY) -> int: return hash(key) % len(self._buckets) def _get_next_ind(self, ind: int) -> int: """ Get next index. Implements linear open addressing. """ return (ind + 1) % len(self._buckets) def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: """ Try to add value to the bucket. If bucket is empty or key is the same, does insert and return True. If bucket has another key or deleted placeholder, that means that we need to check next bucket. """ stored = self._buckets[ind] if not stored: self._buckets[ind] = _Item(key, val) self._len += 1 return True elif stored.key == key: self._buckets[ind] = _Item(key, val) return True else: return False def _is_full(self) -> bool: """ Return true if we have reached safe capacity. So we need to increase the number of buckets to avoid collisions. """ limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit) def _is_sparse(self) -> bool: """Return true if we need twice fewer buckets when we have now.""" if len(self._buckets) <= self._initial_block_size: return False limit = len(self._buckets) * self._capacity_factor / 2 return len(self) < limit def _resize(self, new_size: int) -> None: old_buckets = self._buckets self._buckets = [None] * new_size self._len = 0 for item in old_buckets: if item: self._add_item(item.key, item.val) def _size_up(self) -> None: self._resize(len(self._buckets) * 2) def _size_down(self) -> None: self._resize(len(self._buckets) // 2) def _iterate_buckets(self, key: KEY) -> Iterator[int]: ind = self._get_bucket_index(key) for _ in range(len(self._buckets)): yield ind ind = self._get_next_ind(ind) def _add_item(self, key: KEY, val: VAL) -> None: for ind in self._iterate_buckets(key): if self._try_set(ind, key, val): break def __setitem__(self, key: KEY, val: VAL) -> None: if self._is_full(): self._size_up() self._add_item(key, val) def __delitem__(self, key: KEY) -> None: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: raise KeyError(key) if item is _deleted: continue if item.key == key: self._buckets[ind] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__(self, key: KEY) -> VAL: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(key) def __len__(self) -> int: return self._len def __iter__(self) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__(self) -> str: val_string = " ,".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})"
""" Hash map with open addressing. https://en.wikipedia.org/wiki/Hash_table Another hash map implementation, with a good explanation. Modern Dictionaries by Raymond Hettinger https://www.youtube.com/watch?v=p33CVV29OG8 """ from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar KEY = TypeVar("KEY") VAL = TypeVar("VAL") @dataclass(frozen=True, slots=True) class _Item(Generic[KEY, VAL]): key: KEY val: VAL class _DeletedItem(_Item): def __init__(self) -> None: super().__init__(None, None) def __bool__(self) -> bool: return False _deleted = _DeletedItem() class HashMap(MutableMapping[KEY, VAL]): """ Hash map with open addressing. """ def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 ) -> None: self._initial_block_size = initial_block_size self._buckets: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 self._capacity_factor = capacity_factor self._len = 0 def _get_bucket_index(self, key: KEY) -> int: return hash(key) % len(self._buckets) def _get_next_ind(self, ind: int) -> int: """ Get next index. Implements linear open addressing. """ return (ind + 1) % len(self._buckets) def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: """ Try to add value to the bucket. If bucket is empty or key is the same, does insert and return True. If bucket has another key or deleted placeholder, that means that we need to check next bucket. """ stored = self._buckets[ind] if not stored: self._buckets[ind] = _Item(key, val) self._len += 1 return True elif stored.key == key: self._buckets[ind] = _Item(key, val) return True else: return False def _is_full(self) -> bool: """ Return true if we have reached safe capacity. So we need to increase the number of buckets to avoid collisions. """ limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit) def _is_sparse(self) -> bool: """Return true if we need twice fewer buckets when we have now.""" if len(self._buckets) <= self._initial_block_size: return False limit = len(self._buckets) * self._capacity_factor / 2 return len(self) < limit def _resize(self, new_size: int) -> None: old_buckets = self._buckets self._buckets = [None] * new_size self._len = 0 for item in old_buckets: if item: self._add_item(item.key, item.val) def _size_up(self) -> None: self._resize(len(self._buckets) * 2) def _size_down(self) -> None: self._resize(len(self._buckets) // 2) def _iterate_buckets(self, key: KEY) -> Iterator[int]: ind = self._get_bucket_index(key) for _ in range(len(self._buckets)): yield ind ind = self._get_next_ind(ind) def _add_item(self, key: KEY, val: VAL) -> None: for ind in self._iterate_buckets(key): if self._try_set(ind, key, val): break def __setitem__(self, key: KEY, val: VAL) -> None: if self._is_full(): self._size_up() self._add_item(key, val) def __delitem__(self, key: KEY) -> None: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: raise KeyError(key) if item is _deleted: continue if item.key == key: self._buckets[ind] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__(self, key: KEY) -> VAL: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(key) def __len__(self) -> int: return self._len def __iter__(self) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__(self) -> str: val_string = " ,".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})"
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Atbash """ import string def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def atbash(sequence: str) -> str: """ >>> atbash("ABCDEFG") 'ZYXWVUT' >>> atbash("aW;;123BX") 'zD;;123YC' """ letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: """Let's benchmark our functions side-by-side...""" from timeit import timeit print("Running performance benchmarks...") setup = "from string import printable ; from __main__ import atbash, atbash_slow" print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds") print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds") if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
""" https://en.wikipedia.org/wiki/Atbash """ import string def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def atbash(sequence: str) -> str: """ >>> atbash("ABCDEFG") 'ZYXWVUT' >>> atbash("aW;;123BX") 'zD;;123YC' """ letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: """Let's benchmark our functions side-by-side...""" from timeit import timeit print("Running performance benchmarks...") setup = "from string import printable ; from __main__ import atbash, atbash_slow" print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds") print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds") if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison. For doctests run following command: python3 -m doctest -v insertion_sort.py For manual testing run: python3 insertion_sort.py """ def insertion_sort(collection: list) -> list: """A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> insertion_sort([]) == sorted([]) True >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) True >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> insertion_sort(collection) == sorted(collection) True """ for insert_index, insert_value in enumerate(collection[1:]): temp_index = insert_index while insert_index >= 0 and insert_value < collection[insert_index]: collection[insert_index + 1] = collection[insert_index] insert_index -= 1 if insert_index != temp_index: collection[insert_index + 1] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 1, and 1 (True) otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def nand_gate(input_1: int, input_2: int) -> int: """ Calculate NAND of the input values >>> nand_gate(0, 0) 1 >>> nand_gate(0, 1) 1 >>> nand_gate(1, 0) 1 >>> nand_gate(1, 1) 0 """ return int((input_1, input_2).count(0) != 0) def test_nand_gate() -> None: """ Tests the nand_gate function """ assert nand_gate(0, 0) == 1 assert nand_gate(0, 1) == 1 assert nand_gate(1, 0) == 1 assert nand_gate(1, 1) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
""" A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 1, and 1 (True) otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def nand_gate(input_1: int, input_2: int) -> int: """ Calculate NAND of the input values >>> nand_gate(0, 0) 1 >>> nand_gate(0, 1) 1 >>> nand_gate(1, 0) 1 >>> nand_gate(1, 1) 0 """ return int((input_1, input_2).count(0) != 0) def test_nand_gate() -> None: """ Tests the nand_gate function """ assert nand_gate(0, 0) == 1 assert nand_gate(0, 1) == 1 assert nand_gate(1, 0) == 1 assert nand_gate(1, 1) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 092: https://projecteuler.net/problem=92 Square digit chains A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? """ DIGITS_SQUARED = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100000)] def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit to form a new number. For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 >>> next_number(10) 1 >>> next_number(32) 13 """ sum_of_digits_squared = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution CHAINS: list[bool | None] = [None] * 10000000 CHAINS[0] = True CHAINS[57] = False def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. For example, if starting number is 44, then the function generates the following chain of numbers: 44 → 32 → 13 → 10 → 1 → 1. Once the next number generated is 1 or 89, the function returns whether or not the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) False >>> chain(1) True """ if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore number_chain = chain(next_number(number)) CHAINS[number - 1] = number_chain while number < 10000000: CHAINS[number - 1] = number_chain number *= 10 return number_chain def solution(number: int = 10000000) -> int: """ The function returns the number of integers that end up being 89 in each chain. The function accepts a range number and the function checks all the values under value number. >>> solution(100) 80 >>> solution(10000000) 8581146 """ for i in range(1, number): if CHAINS[i] is None: chain(i + 1) return CHAINS[:number].count(False) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
""" Project Euler Problem 092: https://projecteuler.net/problem=92 Square digit chains A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? """ DIGITS_SQUARED = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100000)] def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit to form a new number. For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 >>> next_number(10) 1 >>> next_number(32) 13 """ sum_of_digits_squared = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution CHAINS: list[bool | None] = [None] * 10000000 CHAINS[0] = True CHAINS[57] = False def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. For example, if starting number is 44, then the function generates the following chain of numbers: 44 → 32 → 13 → 10 → 1 → 1. Once the next number generated is 1 or 89, the function returns whether or not the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) False >>> chain(1) True """ if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore number_chain = chain(next_number(number)) CHAINS[number - 1] = number_chain while number < 10000000: CHAINS[number - 1] = number_chain number *= 10 return number_chain def solution(number: int = 10000000) -> int: """ The function returns the number of integers that end up being 89 in each chain. The function accepts a range number and the function checks all the values under value number. >>> solution(100) 80 >>> solution(10000000) 8581146 """ for i in range(1, number): if CHAINS[i] is None: chain(i + 1) return CHAINS[:number].count(False) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ import itertools def is_combination_valid(combination): """ Checks if a combination (a tuple of 9 digits) is a valid product equation. >>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4')) True >>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9')) False """ return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) ) def solution(): """ Finds the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital >>> solution() 45228 """ return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } ) if __name__ == "__main__": print(solution())
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ import itertools def is_combination_valid(combination): """ Checks if a combination (a tuple of 9 digits) is a valid product equation. >>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4')) True >>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9')) False """ return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) ) def solution(): """ Finds the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital >>> solution() 45228 """ return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } ) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the greedy-merge-sort algorithm reference: https://www.geeksforgeeks.org/optimal-file-merge-patterns/ For doctests run following command: python3 -m doctest -v greedy_merge_sort.py Objective Merge a set of sorted files of different length into a single sorted file. We need to find an optimal solution, where the resultant file will be generated in minimum time. Approach If the number of sorted files are given, there are many ways to merge them into a single sorted file. This merge can be performed pair wise. To merge a m-record file and a n-record file requires possibly m+n record moves the optimal choice being, merge the two smallest files together at each step (greedy approach). """ def optimal_merge_pattern(files: list) -> float: """Function to merge all the files with optimum cost Args: files [list]: A list of sizes of different files to be merged Returns: optimal_merge_cost [int]: Optimal cost to merge all those files Examples: >>> optimal_merge_pattern([2, 3, 4]) 14 >>> optimal_merge_pattern([5, 10, 20, 30, 30]) 205 >>> optimal_merge_pattern([8, 8, 8, 8, 8]) 96 """ optimal_merge_cost = 0 while len(files) > 1: temp = 0 # Consider two files with minimum cost to be merged for _ in range(2): min_index = files.index(min(files)) temp += files[min_index] files.pop(min_index) files.append(temp) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
""" This is a pure Python implementation of the greedy-merge-sort algorithm reference: https://www.geeksforgeeks.org/optimal-file-merge-patterns/ For doctests run following command: python3 -m doctest -v greedy_merge_sort.py Objective Merge a set of sorted files of different length into a single sorted file. We need to find an optimal solution, where the resultant file will be generated in minimum time. Approach If the number of sorted files are given, there are many ways to merge them into a single sorted file. This merge can be performed pair wise. To merge a m-record file and a n-record file requires possibly m+n record moves the optimal choice being, merge the two smallest files together at each step (greedy approach). """ def optimal_merge_pattern(files: list) -> float: """Function to merge all the files with optimum cost Args: files [list]: A list of sizes of different files to be merged Returns: optimal_merge_cost [int]: Optimal cost to merge all those files Examples: >>> optimal_merge_pattern([2, 3, 4]) 14 >>> optimal_merge_pattern([5, 10, 20, 30, 30]) 205 >>> optimal_merge_pattern([8, 8, 8, 8, 8]) 96 """ optimal_merge_cost = 0 while len(files) > 1: temp = 0 # Consider two files with minimum cost to be merged for _ in range(2): min_index = files.index(min(files)) temp += files[min_index] files.pop(min_index) files.append(temp) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Pure Python implementation of a binary search algorithm. For doctests run following command: python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: """ >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> binary_search(test_list, 3) False >>> binary_search(test_list, 13) True >>> binary_search([4, 4, 5, 6, 7], 4) True >>> binary_search([4, 4, 5, 6, 7], -10) False >>> binary_search([-18, 2], -18) True >>> binary_search([5], 5) True >>> binary_search(['a', 'c', 'd'], 'c') True >>> binary_search(['a', 'c', 'd'], 'f') False >>> binary_search([], 1) False >>> binary_search([-.1, .1 , .8], .1) True >>> binary_search(range(-5000, 5000, 10), 80) True >>> binary_search(range(-5000, 5000, 10), 1255) False >>> binary_search(range(0, 10000, 5), 2) False """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " print(f"{target} was {not_str}found in {sequence}")
""" Pure Python implementation of a binary search algorithm. For doctests run following command: python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: """ >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> binary_search(test_list, 3) False >>> binary_search(test_list, 13) True >>> binary_search([4, 4, 5, 6, 7], 4) True >>> binary_search([4, 4, 5, 6, 7], -10) False >>> binary_search([-18, 2], -18) True >>> binary_search([5], 5) True >>> binary_search(['a', 'c', 'd'], 'c') True >>> binary_search(['a', 'c', 'd'], 'f') False >>> binary_search([], 1) False >>> binary_search([-.1, .1 , .8], .1) True >>> binary_search(range(-5000, 5000, 10), 80) True >>> binary_search(range(-5000, 5000, 10), 1255) False >>> binary_search(range(0, 10000, 5), 2) False """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " print(f"{target} was {not_str}found in {sequence}")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def find_primitive(n: int) -> int | None: for r in range(1, n): li = [] for x in range(n - 1): val = pow(r, x, n) if val in li: break li.append(val) else: return r return None if __name__ == "__main__": q = int(input("Enter a prime number q: ")) a = find_primitive(q) if a is None: print(f"Cannot find the primitive for the value: {a!r}") else: a_private = int(input("Enter private key of A: ")) a_public = pow(a, a_private, q) b_private = int(input("Enter private key of B: ")) b_public = pow(a, b_private, q) a_secret = pow(b_public, a_private, q) b_secret = pow(a_public, b_private, q) print("The key value generated by A is: ", a_secret) print("The key value generated by B is: ", b_secret)
from __future__ import annotations def find_primitive(n: int) -> int | None: for r in range(1, n): li = [] for x in range(n - 1): val = pow(r, x, n) if val in li: break li.append(val) else: return r return None if __name__ == "__main__": q = int(input("Enter a prime number q: ")) a = find_primitive(q) if a is None: print(f"Cannot find the primitive for the value: {a!r}") else: a_private = int(input("Enter private key of A: ")) a_public = pow(a, a_private, q) b_private = int(input("Enter private key of B: ")) b_public = pow(a, b_private, q) a_secret = pow(b_public, a_private, q) b_secret = pow(a_public, b_private, q) print("The key value generated by A is: ", a_secret) print("The key value generated by B is: ", b_secret)
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the heap sort algorithm. For doctests run following command: python -m doctest -v heap_sort.py or python3 -m doctest -v heap_sort.py For manual testing run: python heap_sort.py """ def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) def heap_sort(unsorted): """ Pure implementation of the heap sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> heap_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> heap_sort([]) [] >>> heap_sort([-2, -5, -45]) [-45, -5, -2] """ n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(heap_sort(unsorted))
""" This is a pure Python implementation of the heap sort algorithm. For doctests run following command: python -m doctest -v heap_sort.py or python3 -m doctest -v heap_sort.py For manual testing run: python heap_sort.py """ def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) def heap_sort(unsorted): """ Pure implementation of the heap sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> heap_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> heap_sort([]) [] >>> heap_sort([-2, -5, -45]) [-45, -5, -2] """ n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(heap_sort(unsorted))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def binomial_coefficient(n, r): """ Find binomial coefficient using pascals triangle. >>> binomial_coefficient(10, 5) 252 """ c = [0 for i in range(r + 1)] # nc0 = 1 c[0] = 1 for i in range(1, n + 1): # to compute current row from previous row. j = min(i, r) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
def binomial_coefficient(n, r): """ Find binomial coefficient using pascals triangle. >>> binomial_coefficient(10, 5) 252 """ c = [0 for i in range(r + 1)] # nc0 = 1 c[0] = 1 for i in range(1, n + 1): # to compute current row from previous row. j = min(i, r) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:] if __name__ == "__main__": print(solution())
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def get_reverse_bit_string(number: int) -> str: """ return the bit string of an integer >>> get_reverse_bit_string(9) '10010000000000000000000000000000' >>> get_reverse_bit_string(43) '11010100000000000000000000000000' >>> get_reverse_bit_string(2873) '10011100110100000000000000000000' >>> get_reverse_bit_string("this is not a number") Traceback (most recent call last): ... TypeError: operation can not be conducted on a object of type str """ if not isinstance(number, int): raise TypeError( "operation can not be conducted on a object of type " f"{type(number).__name__}" ) bit_string = "" for _ in range(0, 32): bit_string += str(number % 2) number = number >> 1 return bit_string def reverse_bit(number: int) -> str: """ Take in an 32 bit integer, reverse its bits, return a string of reverse bits result of a reverse_bit and operation on the integer provided. >>> reverse_bit(25) '00000000000000000000000000011001' >>> reverse_bit(37) '00000000000000000000000000100101' >>> reverse_bit(21) '00000000000000000000000000010101' >>> reverse_bit(58) '00000000000000000000000000111010' >>> reverse_bit(0) '00000000000000000000000000000000' >>> reverse_bit(256) '00000000000000000000000100000000' >>> reverse_bit(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive >>> reverse_bit(1.1) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> reverse_bit("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if number < 0: raise ValueError("the value of input must be positive") elif isinstance(number, float): raise TypeError("Input value must be a 'int' type") elif isinstance(number, str): raise TypeError("'<' not supported between instances of 'str' and 'int'") result = 0 # iterator over [1 to 32],since we are dealing with 32 bit integer for _ in range(1, 33): # left shift the bits by unity result = result << 1 # get the end bit end_bit = number % 2 # right shift the bits by unity number = number >> 1 # add that bit to our ans result = result | end_bit return get_reverse_bit_string(result) if __name__ == "__main__": import doctest doctest.testmod()
def get_reverse_bit_string(number: int) -> str: """ return the bit string of an integer >>> get_reverse_bit_string(9) '10010000000000000000000000000000' >>> get_reverse_bit_string(43) '11010100000000000000000000000000' >>> get_reverse_bit_string(2873) '10011100110100000000000000000000' >>> get_reverse_bit_string("this is not a number") Traceback (most recent call last): ... TypeError: operation can not be conducted on a object of type str """ if not isinstance(number, int): raise TypeError( "operation can not be conducted on a object of type " f"{type(number).__name__}" ) bit_string = "" for _ in range(0, 32): bit_string += str(number % 2) number = number >> 1 return bit_string def reverse_bit(number: int) -> str: """ Take in an 32 bit integer, reverse its bits, return a string of reverse bits result of a reverse_bit and operation on the integer provided. >>> reverse_bit(25) '00000000000000000000000000011001' >>> reverse_bit(37) '00000000000000000000000000100101' >>> reverse_bit(21) '00000000000000000000000000010101' >>> reverse_bit(58) '00000000000000000000000000111010' >>> reverse_bit(0) '00000000000000000000000000000000' >>> reverse_bit(256) '00000000000000000000000100000000' >>> reverse_bit(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive >>> reverse_bit(1.1) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> reverse_bit("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if number < 0: raise ValueError("the value of input must be positive") elif isinstance(number, float): raise TypeError("Input value must be a 'int' type") elif isinstance(number, str): raise TypeError("'<' not supported between instances of 'str' and 'int'") result = 0 # iterator over [1 to 32],since we are dealing with 32 bit integer for _ in range(1, 33): # left shift the bits by unity result = result << 1 # get the end bit end_bit = number % 2 # right shift the bits by unity number = number >> 1 # add that bit to our ans result = result | end_bit return get_reverse_bit_string(result) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm def longest_distance(graph): indegree = [0] * len(graph) queue = [] long_dist = [1] * len(graph) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: long_dist[x] = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(x) print(max(long_dist)) # Adjacency list of Graph graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm def longest_distance(graph): indegree = [0] * len(graph) queue = [] long_dist = [1] * len(graph) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: long_dist[x] = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(x) print(max(long_dist)) # Adjacency list of Graph graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" == Liouville Lambda Function == The Liouville Lambda function, denoted by λ(n) and λ(n) is 1 if n is the product of an even number of prime numbers, and -1 if it is the product of an odd number of primes. https://en.wikipedia.org/wiki/Liouville_function """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_factors import prime_factors def liouville_lambda(number: int) -> int: """ This functions takes an integer number as input. returns 1 if n has even number of prime factors and -1 otherwise. >>> liouville_lambda(10) 1 >>> liouville_lambda(11) -1 >>> liouville_lambda(0) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> liouville_lambda(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> liouville_lambda(11.0) Traceback (most recent call last): ... TypeError: Input value of [number=11.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError("Input must be a positive integer") return -1 if len(prime_factors(number)) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
""" == Liouville Lambda Function == The Liouville Lambda function, denoted by λ(n) and λ(n) is 1 if n is the product of an even number of prime numbers, and -1 if it is the product of an odd number of primes. https://en.wikipedia.org/wiki/Liouville_function """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_factors import prime_factors def liouville_lambda(number: int) -> int: """ This functions takes an integer number as input. returns 1 if n has even number of prime factors and -1 otherwise. >>> liouville_lambda(10) 1 >>> liouville_lambda(11) -1 >>> liouville_lambda(0) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> liouville_lambda(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> liouville_lambda(11.0) Traceback (most recent call last): ... TypeError: Input value of [number=11.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError("Input must be a positive integer") return -1 if len(prime_factors(number)) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np def qr_householder(a): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity O(n^3). https://en.wikipedia.org/wiki/QR_decomposition#Using_Householder_reflections Arguments: A -- a numpy.ndarray of shape (m, n) Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. >>> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=float) >>> Q, R = qr_householder(A) >>> # check that the decomposition is correct >>> np.allclose(Q@R, A) True >>> # check that Q is orthogonal >>> np.allclose([email protected], np.eye(A.shape[0])) True >>> np.allclose(Q.T@Q, np.eye(A.shape[0])) True >>> # check that R is upper triangular >>> np.allclose(np.triu(R), R) True """ m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): # select a column of modified matrix A': x = r[k:, [k]] # construct first basis vector e1 = np.zeros_like(x) e1[0] = 1.0 # determine scaling factor alpha = np.linalg.norm(x) # construct vector v for Householder reflection v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) # construct the Householder matrix q_k = np.eye(m - k) - 2.0 * v @ v.T # pad with ones and zeros as necessary q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]]) q = q @ q_k.T r = q_k @ r return q, r if __name__ == "__main__": import doctest doctest.testmod()
import numpy as np def qr_householder(a): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity O(n^3). https://en.wikipedia.org/wiki/QR_decomposition#Using_Householder_reflections Arguments: A -- a numpy.ndarray of shape (m, n) Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. >>> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=float) >>> Q, R = qr_householder(A) >>> # check that the decomposition is correct >>> np.allclose(Q@R, A) True >>> # check that Q is orthogonal >>> np.allclose([email protected], np.eye(A.shape[0])) True >>> np.allclose(Q.T@Q, np.eye(A.shape[0])) True >>> # check that R is upper triangular >>> np.allclose(np.triu(R), R) True """ m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): # select a column of modified matrix A': x = r[k:, [k]] # construct first basis vector e1 = np.zeros_like(x) e1[0] = 1.0 # determine scaling factor alpha = np.linalg.norm(x) # construct vector v for Householder reflection v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) # construct the Householder matrix q_k = np.eye(m - k) - 2.0 * v @ v.T # pad with ones and zeros as necessary q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]]) q = q @ q_k.T r = q_k @ r return q, r if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import os from string import ascii_letters LETTERS_AND_SPACE = ascii_letters + " \t\n" def load_dictionary() -> dict[str, None]: path = os.path.split(os.path.realpath(__file__)) english_words: dict[str, None] = {} with open(path[0] + "/dictionary.txt") as dictionary_file: for word in dictionary_file.read().split("\n"): english_words[word] = None return english_words ENGLISH_WORDS = load_dictionary() def get_english_count(message: str) -> float: message = message.upper() message = remove_non_letters(message) possible_words = message.split() matches = len([word for word in possible_words if word in ENGLISH_WORDS]) return float(matches) / len(possible_words) def remove_non_letters(message: str) -> str: return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE) def is_english( message: str, word_percentage: int = 20, letter_percentage: int = 85 ) -> bool: """ >>> is_english('Hello World') True >>> is_english('llold HorWd') False """ words_match = get_english_count(message) * 100 >= word_percentage num_letters = len(remove_non_letters(message)) message_letters_percentage = (float(num_letters) / len(message)) * 100 letters_match = message_letters_percentage >= letter_percentage return words_match and letters_match if __name__ == "__main__": import doctest doctest.testmod()
import os from string import ascii_letters LETTERS_AND_SPACE = ascii_letters + " \t\n" def load_dictionary() -> dict[str, None]: path = os.path.split(os.path.realpath(__file__)) english_words: dict[str, None] = {} with open(path[0] + "/dictionary.txt") as dictionary_file: for word in dictionary_file.read().split("\n"): english_words[word] = None return english_words ENGLISH_WORDS = load_dictionary() def get_english_count(message: str) -> float: message = message.upper() message = remove_non_letters(message) possible_words = message.split() matches = len([word for word in possible_words if word in ENGLISH_WORDS]) return float(matches) / len(possible_words) def remove_non_letters(message: str) -> str: return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE) def is_english( message: str, word_percentage: int = 20, letter_percentage: int = 85 ) -> bool: """ >>> is_english('Hello World') True >>> is_english('llold HorWd') False """ words_match = get_english_count(message) * 100 >= word_percentage num_letters = len(remove_non_letters(message)) message_letters_percentage = (float(num_letters) / len(message)) * 100 letters_match = message_letters_percentage >= letter_percentage return words_match and letters_match if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.wikipedia.org/wiki/Ohm%27s_law from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Ohm%27s_law from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def collatz_sequence(n: int) -> list[int]: """ Collatz conjecture: start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is: n / 2 . If n is odd, the next term is: 3 * n + 1. The conjecture states the sequence will always reach 1 for any starting value n. Example: >>> collatz_sequence(2.1) Traceback (most recent call last): ... Exception: Sequence only defined for natural numbers >>> collatz_sequence(0) Traceback (most recent call last): ... Exception: Sequence only defined for natural numbers >>> collatz_sequence(43) # doctest: +NORMALIZE_WHITESPACE [43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] """ if not isinstance(n, int) or n < 1: raise Exception("Sequence only defined for natural numbers") sequence = [n] while n != 1: n = 3 * n + 1 if n & 1 else n // 2 sequence.append(n) return sequence def main(): n = 43 sequence = collatz_sequence(n) print(sequence) print(f"collatz sequence from {n} took {len(sequence)} steps.") if __name__ == "__main__": main()
from __future__ import annotations def collatz_sequence(n: int) -> list[int]: """ Collatz conjecture: start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is: n / 2 . If n is odd, the next term is: 3 * n + 1. The conjecture states the sequence will always reach 1 for any starting value n. Example: >>> collatz_sequence(2.1) Traceback (most recent call last): ... Exception: Sequence only defined for natural numbers >>> collatz_sequence(0) Traceback (most recent call last): ... Exception: Sequence only defined for natural numbers >>> collatz_sequence(43) # doctest: +NORMALIZE_WHITESPACE [43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] """ if not isinstance(n, int) or n < 1: raise Exception("Sequence only defined for natural numbers") sequence = [n] while n != 1: n = 3 * n + 1 if n & 1 else n // 2 sequence.append(n) return sequence def main(): n = 43 sequence = collatz_sequence(n) print(sequence) print(f"collatz sequence from {n} took {len(sequence)} steps.") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ from math import factorial def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ return sum(int(x) for x in str(factorial(num))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
""" Problem 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ from math import factorial def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ return sum(int(x) for x in str(factorial(num))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Normalization. Wikipedia: https://en.wikipedia.org/wiki/Normalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between [0, 1] or [-1, 1]. The equation for normalization is x_norm = (x - x_min)/(x_max - x_min) where x_norm is the normalized value, x is the value, x_min is the minimum value within the column or list of data, and x_max is the maximum value within the column or list of data. Normalization is used to speed up the training of data and put all of the data on a similar scale. This is useful because variance in the range of values of a dataset can heavily impact optimization (particularly Gradient Descent). Standardization Wikipedia: https://en.wikipedia.org/wiki/Standardization Standardization is the process of converting numerical data to a normally distributed range of values. This range will have a mean of 0 and standard deviation of 1. This is also known as z-score normalization. The equation for standardization is x_std = (x - mu)/(sigma) where mu is the mean of the column or list of values and sigma is the standard deviation of the column or list of values. Choosing between Normalization & Standardization is more of an art of a science, but it is often recommended to run experiments with both to see which performs better. Additionally, a few rules of thumb are: 1. gaussian (normal) distributions work better with standardization 2. non-gaussian (non-normal) distributions work better with normalization 3. If a column or list of values has extreme values / outliers, use standardization """ from statistics import mean, stdev def normalization(data: list, ndigits: int = 3) -> list: """ Return a normalized list of values. @params: data, a list of values to normalize @returns: a list of normalized values (rounded to ndigits decimal places) @examples: >>> normalization([2, 7, 10, 20, 30, 50]) [0.0, 0.104, 0.167, 0.375, 0.583, 1.0] >>> normalization([5, 10, 15, 20, 25]) [0.0, 0.25, 0.5, 0.75, 1.0] """ # variables for calculation x_min = min(data) x_max = max(data) # normalize data return [round((x - x_min) / (x_max - x_min), ndigits) for x in data] def standardization(data: list, ndigits: int = 3) -> list: """ Return a standardized list of values. @params: data, a list of values to standardize @returns: a list of standardized values (rounded to ndigits decimal places) @examples: >>> standardization([2, 7, 10, 20, 30, 50]) [-0.999, -0.719, -0.551, 0.009, 0.57, 1.69] >>> standardization([5, 10, 15, 20, 25]) [-1.265, -0.632, 0.0, 0.632, 1.265] """ # variables for calculation mu = mean(data) sigma = stdev(data) # standardize data return [round((x - mu) / (sigma), ndigits) for x in data]
""" Normalization. Wikipedia: https://en.wikipedia.org/wiki/Normalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between [0, 1] or [-1, 1]. The equation for normalization is x_norm = (x - x_min)/(x_max - x_min) where x_norm is the normalized value, x is the value, x_min is the minimum value within the column or list of data, and x_max is the maximum value within the column or list of data. Normalization is used to speed up the training of data and put all of the data on a similar scale. This is useful because variance in the range of values of a dataset can heavily impact optimization (particularly Gradient Descent). Standardization Wikipedia: https://en.wikipedia.org/wiki/Standardization Standardization is the process of converting numerical data to a normally distributed range of values. This range will have a mean of 0 and standard deviation of 1. This is also known as z-score normalization. The equation for standardization is x_std = (x - mu)/(sigma) where mu is the mean of the column or list of values and sigma is the standard deviation of the column or list of values. Choosing between Normalization & Standardization is more of an art of a science, but it is often recommended to run experiments with both to see which performs better. Additionally, a few rules of thumb are: 1. gaussian (normal) distributions work better with standardization 2. non-gaussian (non-normal) distributions work better with normalization 3. If a column or list of values has extreme values / outliers, use standardization """ from statistics import mean, stdev def normalization(data: list, ndigits: int = 3) -> list: """ Return a normalized list of values. @params: data, a list of values to normalize @returns: a list of normalized values (rounded to ndigits decimal places) @examples: >>> normalization([2, 7, 10, 20, 30, 50]) [0.0, 0.104, 0.167, 0.375, 0.583, 1.0] >>> normalization([5, 10, 15, 20, 25]) [0.0, 0.25, 0.5, 0.75, 1.0] """ # variables for calculation x_min = min(data) x_max = max(data) # normalize data return [round((x - x_min) / (x_max - x_min), ndigits) for x in data] def standardization(data: list, ndigits: int = 3) -> list: """ Return a standardized list of values. @params: data, a list of values to standardize @returns: a list of standardized values (rounded to ndigits decimal places) @examples: >>> standardization([2, 7, 10, 20, 30, 50]) [-0.999, -0.719, -0.551, 0.009, 0.57, 1.69] >>> standardization([5, 10, 15, 20, 25]) [-1.265, -0.632, 0.0, 0.632, 1.265] """ # variables for calculation mu = mean(data) sigma = stdev(data) # standardize data return [round((x - mu) / (sigma), ndigits) for x in data]
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ from __future__ import annotations def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]: result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, index + 1, [*path, nums[index]], result, remaining_nums_sum - nums[index], ) """ remove the comment to take an input from the user print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) """ nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
""" The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ from __future__ import annotations def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]: result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, index + 1, [*path, nums[index]], result, remaining_nums_sum - nums[index], ) """ remove the comment to take an input from the user print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) """ nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def multiplication_table(number: int, number_of_terms: int) -> str: """ Prints the multiplication table of a given number till the given number of terms >>> print(multiplication_table(3, 5)) 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 >>> print(multiplication_table(-4, 6)) -4 * 1 = -4 -4 * 2 = -8 -4 * 3 = -12 -4 * 4 = -16 -4 * 5 = -20 -4 * 6 = -24 """ return "\n".join( f"{number} * {i} = {number * i}" for i in range(1, number_of_terms + 1) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
def multiplication_table(number: int, number_of_terms: int) -> str: """ Prints the multiplication table of a given number till the given number of terms >>> print(multiplication_table(3, 5)) 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 >>> print(multiplication_table(-4, 6)) -4 * 1 = -4 -4 * 2 = -8 -4 * 3 = -12 -4 * 4 = -16 -4 * 5 = -20 -4 * 6 = -24 """ return "\n".join( f"{number} * {i} = {number * i}" for i in range(1, number_of_terms + 1) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Check whether Graph is Bipartite or Not using DFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def check_bipartite_dfs(graph): visited = [False] * len(graph) color = [-1] * len(graph) def dfs(v, c): visited[v] = True color[v] = c for u in graph[v]: if not visited[u]: dfs(u, 1 - c) for i in range(len(graph)): if not visited[i]: dfs(i, 0) for i in range(len(graph)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
# Check whether Graph is Bipartite or Not using DFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def check_bipartite_dfs(graph): visited = [False] * len(graph) color = [-1] * len(graph) def dfs(v, c): visited[v] = True color[v] = c for u in graph[v]: if not visited[u]: dfs(u, 1 - c) for i in range(len(graph)): if not visited[i]: dfs(i, 0) for i in range(len(graph)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? """ def solution(n: int = 100) -> int: """Returns the number of distinct terms in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100. >>> solution(100) 9183 >>> solution(50) 2184 >>> solution(20) 324 >>> solution(5) 15 >>> solution(2) 1 >>> solution(1) 0 """ collect_powers = set() current_pow = 0 n = n + 1 # maximum limit for a in range(2, n): for b in range(2, n): current_pow = a**b # calculates the current power collect_powers.add(current_pow) # adds the result to the set return len(collect_powers) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
""" Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? """ def solution(n: int = 100) -> int: """Returns the number of distinct terms in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100. >>> solution(100) 9183 >>> solution(50) 2184 >>> solution(20) 324 >>> solution(5) 15 >>> solution(2) 1 >>> solution(1) 0 """ collect_powers = set() current_pow = 0 n = n + 1 # maximum limit for a in range(2, n): for b in range(2, n): current_pow = a**b # calculates the current power collect_powers.add(current_pow) # adds the result to the set return len(collect_powers) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Primality Testing with the Rabin-Miller Algorithm import random def rabin_miller(num: int) -> bool: s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + 1 v = (v**2) % num return True def is_prime_low_num(num: int) -> bool: if num < 2: return False low_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(num) def generate_large_prime(keysize: int = 1024) -> int: while True: num = random.randrange(2 ** (keysize - 1), 2 ** (keysize)) if is_prime_low_num(num): return num if __name__ == "__main__": num = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
# Primality Testing with the Rabin-Miller Algorithm import random def rabin_miller(num: int) -> bool: s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + 1 v = (v**2) % num return True def is_prime_low_num(num: int) -> bool: if num < 2: return False low_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(num) def generate_large_prime(keysize: int = 1024) -> int: while True: num = random.randrange(2 ** (keysize - 1), 2 ** (keysize)) if is_prime_low_num(num): return num if __name__ == "__main__": num = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible """ def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 >>> solution(3.4) 6 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i return None if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible """ def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 >>> solution(3.4) 6 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i return None if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))) """ from __future__ import annotations def generate_all_combinations(n: int, k: int) -> list[list[int]]: """ >>> generate_all_combinations(n=4, k=2) [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] """ result: list[list[int]] = [] create_all_state(1, n, k, [], result) return result def create_all_state( increment: int, total_number: int, level: int, current_list: list[int], total_list: list[list[int]], ) -> None: if level == 0: total_list.append(current_list[:]) return for i in range(increment, total_number - level + 2): current_list.append(i) create_all_state(i + 1, total_number, level - 1, current_list, total_list) current_list.pop() def print_all_state(total_list: list[list[int]]) -> None: for i in total_list: print(*i) if __name__ == "__main__": n = 4 k = 2 total_list = generate_all_combinations(n, k) print_all_state(total_list)
""" In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))) """ from __future__ import annotations def generate_all_combinations(n: int, k: int) -> list[list[int]]: """ >>> generate_all_combinations(n=4, k=2) [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] """ result: list[list[int]] = [] create_all_state(1, n, k, [], result) return result def create_all_state( increment: int, total_number: int, level: int, current_list: list[int], total_list: list[list[int]], ) -> None: if level == 0: total_list.append(current_list[:]) return for i in range(increment, total_number - level + 2): current_list.append(i) create_all_state(i + 1, total_number, level - 1, current_list, total_list) current_list.pop() def print_all_state(total_list: list[list[int]]) -> None: for i in total_list: print(*i) if __name__ == "__main__": n = 4 k = 2 total_list = generate_all_combinations(n, k) print_all_state(total_list)
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley ([email protected]), [email protected]", # "Date": 28-10-2018 # } """ The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. [Source] Wikipedia [Credit] Rosetta Code C implementation helped very much. (https://rosettacode.org/wiki/Banker%27s_algorithm) """ from __future__ import annotations import time import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: """ :param claim_vector: A nxn/nxm list depicting the amount of each resources (eg. memory, interface, semaphores, etc.) available. :param allocated_resources_table: A nxn/nxm list depicting the amount of each resource each process is currently holding :param maximum_claim_table: A nxn/nxm list depicting how much of each resource the system currently has available """ self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: """ Check for allocated resources in line with each resource in the claim vector """ return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: """ Check for available resources in line with each resource in the claim vector """ return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: """ Implement safety checker that calculates the needs by ensuring that max_claim[i][j] - alloc_table[i][j] <= avail[j] """ return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: """ This function builds an index control dictionary to track original ids/indices of processes when altered during execution of method "main" Return: {0: [a: int, b: int], 1: [c: int, d: int]} >>> (BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table)._BankersAlgorithm__need_index_manager() ... ) # doctest: +NORMALIZE_WHITESPACE {0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0], 4: [2, 0, 0, 3]} """ return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: """ Utilize various methods in this class to simulate the Banker's algorithm Return: None >>> BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table).main(describe=True) Allocated Resource Table P1 2 0 1 1 <BLANKLINE> P2 0 1 2 1 <BLANKLINE> P3 4 0 0 3 <BLANKLINE> P4 0 2 1 0 <BLANKLINE> P5 1 0 3 0 <BLANKLINE> System Resource Table P1 3 2 1 4 <BLANKLINE> P2 0 2 5 2 <BLANKLINE> P3 5 1 0 5 <BLANKLINE> P4 1 5 3 0 <BLANKLINE> P5 3 0 3 3 <BLANKLINE> Current Usage by Active Processes: 8 5 9 7 Initial Available Resources: 1 2 2 2 __________________________________________________ <BLANKLINE> Process 3 is executing. Updated available resource stack for processes: 5 2 2 5 The process is in a safe state. <BLANKLINE> Process 1 is executing. Updated available resource stack for processes: 7 2 3 6 The process is in a safe state. <BLANKLINE> Process 2 is executing. Updated available resource stack for processes: 7 3 5 7 The process is in a safe state. <BLANKLINE> Process 4 is executing. Updated available resource stack for processes: 7 5 6 7 The process is in a safe state. <BLANKLINE> Process 5 is executing. Updated available resource stack for processes: 8 5 9 7 The process is in a safe state. <BLANKLINE> """ need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): """ Properly align display of the algorithm's solution """ print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley ([email protected]), [email protected]", # "Date": 28-10-2018 # } """ The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. [Source] Wikipedia [Credit] Rosetta Code C implementation helped very much. (https://rosettacode.org/wiki/Banker%27s_algorithm) """ from __future__ import annotations import time import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: """ :param claim_vector: A nxn/nxm list depicting the amount of each resources (eg. memory, interface, semaphores, etc.) available. :param allocated_resources_table: A nxn/nxm list depicting the amount of each resource each process is currently holding :param maximum_claim_table: A nxn/nxm list depicting how much of each resource the system currently has available """ self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: """ Check for allocated resources in line with each resource in the claim vector """ return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: """ Check for available resources in line with each resource in the claim vector """ return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: """ Implement safety checker that calculates the needs by ensuring that max_claim[i][j] - alloc_table[i][j] <= avail[j] """ return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: """ This function builds an index control dictionary to track original ids/indices of processes when altered during execution of method "main" Return: {0: [a: int, b: int], 1: [c: int, d: int]} >>> (BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table)._BankersAlgorithm__need_index_manager() ... ) # doctest: +NORMALIZE_WHITESPACE {0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0], 4: [2, 0, 0, 3]} """ return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: """ Utilize various methods in this class to simulate the Banker's algorithm Return: None >>> BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table).main(describe=True) Allocated Resource Table P1 2 0 1 1 <BLANKLINE> P2 0 1 2 1 <BLANKLINE> P3 4 0 0 3 <BLANKLINE> P4 0 2 1 0 <BLANKLINE> P5 1 0 3 0 <BLANKLINE> System Resource Table P1 3 2 1 4 <BLANKLINE> P2 0 2 5 2 <BLANKLINE> P3 5 1 0 5 <BLANKLINE> P4 1 5 3 0 <BLANKLINE> P5 3 0 3 3 <BLANKLINE> Current Usage by Active Processes: 8 5 9 7 Initial Available Resources: 1 2 2 2 __________________________________________________ <BLANKLINE> Process 3 is executing. Updated available resource stack for processes: 5 2 2 5 The process is in a safe state. <BLANKLINE> Process 1 is executing. Updated available resource stack for processes: 7 2 3 6 The process is in a safe state. <BLANKLINE> Process 2 is executing. Updated available resource stack for processes: 7 3 5 7 The process is in a safe state. <BLANKLINE> Process 4 is executing. Updated available resource stack for processes: 7 5 6 7 The process is in a safe state. <BLANKLINE> Process 5 is executing. Updated available resource stack for processes: 8 5 9 7 The process is in a safe state. <BLANKLINE> """ need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): """ Properly align display of the algorithm's solution """ print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Amicable Numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ from math import sqrt def sum_of_divisors(n: int) -> int: total = 0 for i in range(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): total += i return total - n def solution(n: int = 10000) -> int: """Returns the sum of all the amicable numbers under n. >>> solution(10000) 31626 >>> solution(5000) 8442 >>> solution(1000) 504 >>> solution(100) 0 >>> solution(50) 0 """ total = sum( i for i in range(1, n) if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" Amicable Numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ from math import sqrt def sum_of_divisors(n: int) -> int: total = 0 for i in range(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): total += i return total - n def solution(n: int = 10000) -> int: """Returns the sum of all the amicable numbers under n. >>> solution(10000) 31626 >>> solution(5000) 8442 >>> solution(1000) 504 >>> solution(100) 0 >>> solution(50) 0 """ total = sum( i for i in range(1, n) if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. """ chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: """ Run through the list of Letters and build the min heap for the Huffman Tree. """ response: list[Letter | TreeNode] = letters # type: ignore while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda x: x.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: """ Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters """ if isinstance(root, Letter): root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root # type: ignore letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: """ Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. """ chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: """ Run through the list of Letters and build the min heap for the Huffman Tree. """ response: list[Letter | TreeNode] = letters # type: ignore while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda x: x.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: """ Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters """ if isinstance(root, Letter): root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root # type: ignore letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: """ Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Question: You are given an array of distinct integers and you have to tell how many different ways of selecting the elements from the array are there such that the sum of chosen elements is equal to the target number tar. Example Input: N = 3 target = 5 array = [1, 2, 5] Output: 9 Approach: The basic idea is to go over recursively to find the way such that the sum of chosen elements is “tar”. For every element, we have two choices 1. Include the element in our set of chosen elements. 2. Don’t include the element in our set of chosen elements. """ def combination_sum_iv(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations, and returns the count of possible combination in exponential Time Complexity. >>> combination_sum_iv(3, [1,2,5], 5) 9 """ def count_of_possible_combinations(target: int) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item) for item in array) return count_of_possible_combinations(target) def combination_sum_iv_dp_array(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations, and returns the count of possible combination in O(N^2) Time Complexity as we are using Dynamic programming array here. >>> combination_sum_iv_dp_array(3, [1,2,5], 5) 9 """ def count_of_possible_combinations_with_dp_array( target: int, dp_array: list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] answer = sum( count_of_possible_combinations_with_dp_array(target - item, dp_array) for item in array ) dp_array[target] = answer return answer dp_array = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(target, dp_array) def combination_sum_iv_bottom_up(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations with using bottom up approach, and returns the count of possible combination in O(N^2) Time Complexity as we are using Dynamic programming array here. >>> combination_sum_iv_bottom_up(3, [1,2,5], 5) 9 """ dp_array = [0] * (target + 1) dp_array[0] = 1 for i in range(1, target + 1): for j in range(n): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() n = 3 target = 5 array = [1, 2, 5] print(combination_sum_iv(n, array, target))
""" Question: You are given an array of distinct integers and you have to tell how many different ways of selecting the elements from the array are there such that the sum of chosen elements is equal to the target number tar. Example Input: N = 3 target = 5 array = [1, 2, 5] Output: 9 Approach: The basic idea is to go over recursively to find the way such that the sum of chosen elements is “tar”. For every element, we have two choices 1. Include the element in our set of chosen elements. 2. Don’t include the element in our set of chosen elements. """ def combination_sum_iv(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations, and returns the count of possible combination in exponential Time Complexity. >>> combination_sum_iv(3, [1,2,5], 5) 9 """ def count_of_possible_combinations(target: int) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item) for item in array) return count_of_possible_combinations(target) def combination_sum_iv_dp_array(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations, and returns the count of possible combination in O(N^2) Time Complexity as we are using Dynamic programming array here. >>> combination_sum_iv_dp_array(3, [1,2,5], 5) 9 """ def count_of_possible_combinations_with_dp_array( target: int, dp_array: list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] answer = sum( count_of_possible_combinations_with_dp_array(target - item, dp_array) for item in array ) dp_array[target] = answer return answer dp_array = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(target, dp_array) def combination_sum_iv_bottom_up(n: int, array: list[int], target: int) -> int: """ Function checks the all possible combinations with using bottom up approach, and returns the count of possible combination in O(N^2) Time Complexity as we are using Dynamic programming array here. >>> combination_sum_iv_bottom_up(3, [1,2,5], 5) 9 """ dp_array = [0] * (target + 1) dp_array[0] = 1 for i in range(1, target + 1): for j in range(n): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() n = 3 target = 5 array = [1, 2, 5] print(combination_sum_iv(n, array, target))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import unittest from knapsack import greedy_knapsack as kp class TestClass(unittest.TestCase): """ Test cases for knapsack """ def test_sorted(self): """ kp.calc_profit takes the required argument (profit, weight, max_weight) and returns whether the answer matches to the expected ones """ profit = [10, 20, 30, 40, 50, 60] weight = [2, 4, 6, 8, 10, 12] max_weight = 100 self.assertEqual(kp.calc_profit(profit, weight, max_weight), 210) def test_negative_max_weight(self): """ Returns ValueError for any negative max_weight value :return: ValueError """ # profit = [10, 20, 30, 40, 50, 60] # weight = [2, 4, 6, 8, 10, 12] # max_weight = -15 self.assertRaisesRegex(ValueError, "max_weight must greater than zero.") def test_negative_profit_value(self): """ Returns ValueError for any negative profit value in the list :return: ValueError """ # profit = [10, -20, 30, 40, 50, 60] # weight = [2, 4, 6, 8, 10, 12] # max_weight = 15 self.assertRaisesRegex(ValueError, "Weight can not be negative.") def test_negative_weight_value(self): """ Returns ValueError for any negative weight value in the list :return: ValueError """ # profit = [10, 20, 30, 40, 50, 60] # weight = [2, -4, 6, -8, 10, 12] # max_weight = 15 self.assertRaisesRegex(ValueError, "Profit can not be negative.") def test_null_max_weight(self): """ Returns ValueError for any zero max_weight value :return: ValueError """ # profit = [10, 20, 30, 40, 50, 60] # weight = [2, 4, 6, 8, 10, 12] # max_weight = null self.assertRaisesRegex(ValueError, "max_weight must greater than zero.") def test_unequal_list_length(self): """ Returns IndexError if length of lists (profit and weight) are unequal. :return: IndexError """ # profit = [10, 20, 30, 40, 50] # weight = [2, 4, 6, 8, 10, 12] # max_weight = 100 self.assertRaisesRegex( IndexError, "The length of profit and weight must be same." ) if __name__ == "__main__": unittest.main()
import unittest from knapsack import greedy_knapsack as kp class TestClass(unittest.TestCase): """ Test cases for knapsack """ def test_sorted(self): """ kp.calc_profit takes the required argument (profit, weight, max_weight) and returns whether the answer matches to the expected ones """ profit = [10, 20, 30, 40, 50, 60] weight = [2, 4, 6, 8, 10, 12] max_weight = 100 self.assertEqual(kp.calc_profit(profit, weight, max_weight), 210) def test_negative_max_weight(self): """ Returns ValueError for any negative max_weight value :return: ValueError """ # profit = [10, 20, 30, 40, 50, 60] # weight = [2, 4, 6, 8, 10, 12] # max_weight = -15 self.assertRaisesRegex(ValueError, "max_weight must greater than zero.") def test_negative_profit_value(self): """ Returns ValueError for any negative profit value in the list :return: ValueError """ # profit = [10, -20, 30, 40, 50, 60] # weight = [2, 4, 6, 8, 10, 12] # max_weight = 15 self.assertRaisesRegex(ValueError, "Weight can not be negative.") def test_negative_weight_value(self): """ Returns ValueError for any negative weight value in the list :return: ValueError """ # profit = [10, 20, 30, 40, 50, 60] # weight = [2, -4, 6, -8, 10, 12] # max_weight = 15 self.assertRaisesRegex(ValueError, "Profit can not be negative.") def test_null_max_weight(self): """ Returns ValueError for any zero max_weight value :return: ValueError """ # profit = [10, 20, 30, 40, 50, 60] # weight = [2, 4, 6, 8, 10, 12] # max_weight = null self.assertRaisesRegex(ValueError, "max_weight must greater than zero.") def test_unequal_list_length(self): """ Returns IndexError if length of lists (profit and weight) are unequal. :return: IndexError """ # profit = [10, 20, 30, 40, 50] # weight = [2, 4, 6, 8, 10, 12] # max_weight = 100 self.assertRaisesRegex( IndexError, "The length of profit and weight must be same." ) if __name__ == "__main__": unittest.main()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import re def dna(dna: str) -> str: """ https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand >>> dna("GCTA") 'CGAT' >>> dna("ATGC") 'TACG' >>> dna("CTGA") 'GACT' >>> dna("GFGG") Traceback (most recent call last): ... ValueError: Invalid Strand """ if len(re.findall("[ATCG]", dna)) != len(dna): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG", "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
import re def dna(dna: str) -> str: """ https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand >>> dna("GCTA") 'CGAT' >>> dna("ATGC") 'TACG' >>> dna("CTGA") 'GACT' >>> dna("GFGG") Traceback (most recent call last): ... ValueError: Invalid Strand """ if len(re.findall("[ATCG]", dna)) != len(dna): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG", "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Program to list all the ways a target string can be constructed from the given list of substrings """ from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: """ returns the list containing all the possible combinations a string(target) can be constructed from the given list of substrings(word_bank) >>> all_construct("hello", ["he", "l", "o"]) [['he', 'l', 'l', 'o']] >>> all_construct("purple",["purp","p","ur","le","purpl"]) [['purp', 'le'], ['p', 'ur', 'p', 'le']] """ word_bank = word_bank or [] # create a table table_size: int = len(target) + 1 table: list[list[list[str]]] = [] for _ in range(table_size): table.append([]) # seed value table[0] = [[]] # because empty string has empty combination # iterate through the indices for i in range(table_size): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(word)] == word: new_combinations: list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(word)] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(target)]: combination.reverse() return table[len(target)] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
""" Program to list all the ways a target string can be constructed from the given list of substrings """ from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: """ returns the list containing all the possible combinations a string(target) can be constructed from the given list of substrings(word_bank) >>> all_construct("hello", ["he", "l", "o"]) [['he', 'l', 'l', 'o']] >>> all_construct("purple",["purp","p","ur","le","purpl"]) [['purp', 'le'], ['p', 'ur', 'p', 'le']] """ word_bank = word_bank or [] # create a table table_size: int = len(target) + 1 table: list[list[list[str]]] = [] for _ in range(table_size): table.append([]) # seed value table[0] = [[]] # because empty string has empty combination # iterate through the indices for i in range(table_size): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(word)] == word: new_combinations: list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(word)] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(target)]: combination.reverse() return table[len(target)] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.  The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively. At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points. There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust". When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). There are exactly eleven distinct ways to checkout on a score of 6: D3 D1 D2 S2 D2 D2 D1 S4 D1 S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. Incredibly there are 42336 distinct ways of checking out in total. How many distinct ways can a player checkout with a score less than 100? Solution: We first construct a list of the possible dart values, separated by type. We then iterate through the doubles, followed by the possible 2 following throws. If the total of these three darts is less than the given limit, we increment the counter. """ from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: """ Count the number of distinct ways a player can checkout with a score less than limit. >>> solution(171) 42336 >>> solution(50) 12577 """ singles: list[int] = [*list(range(1, 21)), 25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] num_checkouts: int = 0 double: int throw1: int throw2: int checkout_total: int for double in doubles: for throw1, throw2 in combinations_with_replacement(all_values, 2): checkout_total = double + throw1 + throw2 if checkout_total < limit: num_checkouts += 1 return num_checkouts if __name__ == "__main__": print(f"{solution() = }")
""" In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.  The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively. At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points. There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust". When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). There are exactly eleven distinct ways to checkout on a score of 6: D3 D1 D2 S2 D2 D2 D1 S4 D1 S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. Incredibly there are 42336 distinct ways of checking out in total. How many distinct ways can a player checkout with a score less than 100? Solution: We first construct a list of the possible dart values, separated by type. We then iterate through the doubles, followed by the possible 2 following throws. If the total of these three darts is less than the given limit, we increment the counter. """ from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: """ Count the number of distinct ways a player can checkout with a score less than limit. >>> solution(171) 42336 >>> solution(50) 12577 """ singles: list[int] = [*list(range(1, 21)), 25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] num_checkouts: int = 0 double: int throw1: int throw2: int checkout_total: int for double in doubles: for throw1, throw2 in combinations_with_replacement(all_values, 2): checkout_total = double + throw1 + throw2 if checkout_total < limit: num_checkouts += 1 return num_checkouts if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration >>> molarity_to_normality(2, 3.1, 0.31) 20 >>> molarity_to_normality(4, 11.4, 5.7) 8 """ return round(float(moles / volume) * nfactor) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_pressure(0.82, 3, 300) 90 >>> moles_to_pressure(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: """ Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_volume(0.82, 3, 300) 90 >>> moles_to_volume(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> pressure_and_volume_to_temperature(0.82, 1, 2) 20 >>> pressure_and_volume_to_temperature(8.2, 5, 3) 60 """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration >>> molarity_to_normality(2, 3.1, 0.31) 20 >>> molarity_to_normality(4, 11.4, 5.7) 8 """ return round(float(moles / volume) * nfactor) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_pressure(0.82, 3, 300) 90 >>> moles_to_pressure(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: """ Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_volume(0.82, 3, 300) 90 >>> moles_to_volume(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> pressure_and_volume_to_temperature(0.82, 1, 2) 20 >>> pressure_and_volume_to_temperature(8.2, 5, 3) 60 """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected]) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_o_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_nama <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size: int) -> list[list[bool]]: canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas: list[list[bool]]) -> list[list[bool]]: """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) current_canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return_canvas: list[list[bool]] = current_canvas.tolist() return return_canvas def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive == 2 or alive == 3: state = True elif alive > 3: state = False else: if alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
"""Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected]) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_o_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_nama <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size: int) -> list[list[bool]]: canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas: list[list[bool]]) -> list[list[bool]]: """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) current_canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return_canvas: list[list[bool]] = current_canvas.tolist() return return_canvas def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive == 2 or alive == 3: state = True elif alive > 3: state = False else: if alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" == Automorphic Numbers == A number n is said to be a Automorphic number if the square of n "ends" in the same digits as n itself. Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... https://en.wikipedia.org/wiki/Automorphic_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. >>> is_automorphic_number(-1) False >>> is_automorphic_number(0) True >>> is_automorphic_number(5) True >>> is_automorphic_number(6) True >>> is_automorphic_number(7) False >>> is_automorphic_number(25) True >>> is_automorphic_number(259918212890625) True >>> is_automorphic_number(259918212890636) False >>> is_automorphic_number(740081787109376) True >>> is_automorphic_number(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 0: return False number_square = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
""" == Automorphic Numbers == A number n is said to be a Automorphic number if the square of n "ends" in the same digits as n itself. Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... https://en.wikipedia.org/wiki/Automorphic_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. >>> is_automorphic_number(-1) False >>> is_automorphic_number(0) True >>> is_automorphic_number(5) True >>> is_automorphic_number(6) True >>> is_automorphic_number(7) False >>> is_automorphic_number(25) True >>> is_automorphic_number(259918212890625) True >>> is_automorphic_number(259918212890636) False >>> is_automorphic_number(740081787109376) True >>> is_automorphic_number(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 0: return False number_square = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Any class Node: def __init__(self, data: Any): """ Create and initialize Node class instance. >>> Node(20) Node(20) >>> Node("Hello, world!") Node(Hello, world!) >>> Node(None) Node(None) >>> Node(True) Node(True) """ self.data = data self.next = None def __repr__(self) -> str: """ Get the string representation of this node. >>> Node(10).__repr__() 'Node(10)' """ return f"Node({self.data})" class LinkedList: def __init__(self): """ Create and initialize LinkedList class instance. >>> linked_list = LinkedList() """ self.head = None def __iter__(self) -> Any: """ This function is intended for iterators to access and iterate through data inside linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list.insert_tail("tail_1") >>> linked_list.insert_tail("tail_2") >>> for node in linked_list: # __iter__ used here. ... node 'tail' 'tail_1' 'tail_2' """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("tail") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self) -> str: """ String representation/visualization of a Linked Lists >>> linked_list = LinkedList() >>> linked_list.insert_tail(1) >>> linked_list.insert_tail(3) >>> linked_list.__repr__() '1->3' """ return "->".join([str(item) for item in self]) def __getitem__(self, index: int) -> Any: """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node return None # Used to change the data of a particular node def __setitem__(self, index: int, data: Any) -> None: """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for _ in range(index): current = current.next current.data = data def insert_tail(self, data: Any) -> None: """ Insert data to the end of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list tail >>> linked_list.insert_tail("tail_2") >>> linked_list tail->tail_2 >>> linked_list.insert_tail("tail_3") >>> linked_list tail->tail_2->tail_3 """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert data to the beginning of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_head("head") >>> linked_list head >>> linked_list.insert_head("head_2") >>> linked_list head_2->head >>> linked_list.insert_head("head_3") >>> linked_list head_3->head_2->head """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert data at given index. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.insert_nth(1, "fourth") >>> linked_list first->fourth->second->third >>> linked_list.insert_nth(3, "fifth") >>> linked_list first->fourth->second->fifth->third """ if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data """ This method prints every node data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third """ print(self) def delete_head(self) -> Any: """ Delete the first node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_head() 'first' >>> linked_list second->third >>> linked_list.delete_head() 'second' >>> linked_list third >>> linked_list.delete_head() 'third' >>> linked_list.delete_head() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(0) def delete_tail(self) -> Any: # delete from tail """ Delete the tail end node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_tail() 'third' >>> linked_list first->second >>> linked_list.delete_tail() 'second' >>> linked_list first >>> linked_list.delete_tail() 'first' >>> linked_list.delete_tail() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete node at given index and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_nth(1) # delete middle 'second' >>> linked_list first->third >>> linked_list.delete_nth(5) # this raises error Traceback (most recent call last): ... IndexError: List index out of range. >>> linked_list.delete_nth(-1) # this also raises error Traceback (most recent call last): ... IndexError: List index out of range. """ if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: """ Check if linked list is empty. >>> linked_list = LinkedList() >>> linked_list.is_empty() True >>> linked_list.insert_head("first") >>> linked_list.is_empty() False """ return self.head is None def reverse(self) -> None: """ This reverses the linked list order. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.reverse() >>> linked_list third->second->first """ prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True linked_list.reverse() assert str(linked_list) == "->".join(str(i) for i in range(-8, 1)) def test_singly_linked_list_2() -> None: """ This section of the test used varying data types for input. >>> test_singly_linked_list_2() """ test_input = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] linked_list = LinkedList() for i in test_input: linked_list.insert_tail(i) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(linked_list) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head result = linked_list.delete_head() assert result == -9 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail result = linked_list.delete_tail() assert result == 12.2 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list result = linked_list.delete_nth(10) assert result is None assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(None) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(linked_list) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
from typing import Any class Node: def __init__(self, data: Any): """ Create and initialize Node class instance. >>> Node(20) Node(20) >>> Node("Hello, world!") Node(Hello, world!) >>> Node(None) Node(None) >>> Node(True) Node(True) """ self.data = data self.next = None def __repr__(self) -> str: """ Get the string representation of this node. >>> Node(10).__repr__() 'Node(10)' """ return f"Node({self.data})" class LinkedList: def __init__(self): """ Create and initialize LinkedList class instance. >>> linked_list = LinkedList() """ self.head = None def __iter__(self) -> Any: """ This function is intended for iterators to access and iterate through data inside linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list.insert_tail("tail_1") >>> linked_list.insert_tail("tail_2") >>> for node in linked_list: # __iter__ used here. ... node 'tail' 'tail_1' 'tail_2' """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("tail") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self) -> str: """ String representation/visualization of a Linked Lists >>> linked_list = LinkedList() >>> linked_list.insert_tail(1) >>> linked_list.insert_tail(3) >>> linked_list.__repr__() '1->3' """ return "->".join([str(item) for item in self]) def __getitem__(self, index: int) -> Any: """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node return None # Used to change the data of a particular node def __setitem__(self, index: int, data: Any) -> None: """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for _ in range(index): current = current.next current.data = data def insert_tail(self, data: Any) -> None: """ Insert data to the end of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list tail >>> linked_list.insert_tail("tail_2") >>> linked_list tail->tail_2 >>> linked_list.insert_tail("tail_3") >>> linked_list tail->tail_2->tail_3 """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert data to the beginning of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_head("head") >>> linked_list head >>> linked_list.insert_head("head_2") >>> linked_list head_2->head >>> linked_list.insert_head("head_3") >>> linked_list head_3->head_2->head """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert data at given index. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.insert_nth(1, "fourth") >>> linked_list first->fourth->second->third >>> linked_list.insert_nth(3, "fifth") >>> linked_list first->fourth->second->fifth->third """ if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data """ This method prints every node data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third """ print(self) def delete_head(self) -> Any: """ Delete the first node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_head() 'first' >>> linked_list second->third >>> linked_list.delete_head() 'second' >>> linked_list third >>> linked_list.delete_head() 'third' >>> linked_list.delete_head() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(0) def delete_tail(self) -> Any: # delete from tail """ Delete the tail end node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_tail() 'third' >>> linked_list first->second >>> linked_list.delete_tail() 'second' >>> linked_list first >>> linked_list.delete_tail() 'first' >>> linked_list.delete_tail() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete node at given index and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_nth(1) # delete middle 'second' >>> linked_list first->third >>> linked_list.delete_nth(5) # this raises error Traceback (most recent call last): ... IndexError: List index out of range. >>> linked_list.delete_nth(-1) # this also raises error Traceback (most recent call last): ... IndexError: List index out of range. """ if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: """ Check if linked list is empty. >>> linked_list = LinkedList() >>> linked_list.is_empty() True >>> linked_list.insert_head("first") >>> linked_list.is_empty() False """ return self.head is None def reverse(self) -> None: """ This reverses the linked list order. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.reverse() >>> linked_list third->second->first """ prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True linked_list.reverse() assert str(linked_list) == "->".join(str(i) for i in range(-8, 1)) def test_singly_linked_list_2() -> None: """ This section of the test used varying data types for input. >>> test_singly_linked_list_2() """ test_input = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] linked_list = LinkedList() for i in test_input: linked_list.insert_tail(i) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(linked_list) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head result = linked_list.delete_head() assert result == -9 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail result = linked_list.delete_tail() assert result == 12.2 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list result = linked_list.delete_nth(10) assert result is None assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(None) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(linked_list) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class BinaryHeap: """ A max-heap implementation in Python >>> binary_heap = BinaryHeap() >>> binary_heap.insert(6) >>> binary_heap.insert(10) >>> binary_heap.insert(15) >>> binary_heap.insert(12) >>> binary_heap.pop() 15 >>> binary_heap.pop() 12 >>> binary_heap.get_list [10, 6] >>> len(binary_heap) 2 """ def __init__(self): self.__heap = [0] self.__size = 0 def __swap_up(self, i: int) -> None: """Swap the element up""" temporary = self.__heap[i] while i // 2 > 0: if self.__heap[i] > self.__heap[i // 2]: self.__heap[i] = self.__heap[i // 2] self.__heap[i // 2] = temporary i //= 2 def insert(self, value: int) -> None: """Insert new element""" self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size) def __swap_down(self, i: int) -> None: """Swap the element down""" while self.__size >= 2 * i: if 2 * i + 1 > self.__size: bigger_child = 2 * i else: if self.__heap[2 * i] > self.__heap[2 * i + 1]: bigger_child = 2 * i else: bigger_child = 2 * i + 1 temporary = self.__heap[i] if self.__heap[i] < self.__heap[bigger_child]: self.__heap[i] = self.__heap[bigger_child] self.__heap[bigger_child] = temporary i = bigger_child def pop(self) -> int: """Pop the root element""" max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value @property def get_list(self): return self.__heap[1:] def __len__(self): """Length of the array""" return self.__size if __name__ == "__main__": import doctest doctest.testmod() # create an instance of BinaryHeap binary_heap = BinaryHeap() binary_heap.insert(6) binary_heap.insert(10) binary_heap.insert(15) binary_heap.insert(12) # pop root(max-values because it is max heap) print(binary_heap.pop()) # 15 print(binary_heap.pop()) # 12 # get the list and size after operations print(binary_heap.get_list) print(len(binary_heap))
class BinaryHeap: """ A max-heap implementation in Python >>> binary_heap = BinaryHeap() >>> binary_heap.insert(6) >>> binary_heap.insert(10) >>> binary_heap.insert(15) >>> binary_heap.insert(12) >>> binary_heap.pop() 15 >>> binary_heap.pop() 12 >>> binary_heap.get_list [10, 6] >>> len(binary_heap) 2 """ def __init__(self): self.__heap = [0] self.__size = 0 def __swap_up(self, i: int) -> None: """Swap the element up""" temporary = self.__heap[i] while i // 2 > 0: if self.__heap[i] > self.__heap[i // 2]: self.__heap[i] = self.__heap[i // 2] self.__heap[i // 2] = temporary i //= 2 def insert(self, value: int) -> None: """Insert new element""" self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size) def __swap_down(self, i: int) -> None: """Swap the element down""" while self.__size >= 2 * i: if 2 * i + 1 > self.__size: bigger_child = 2 * i else: if self.__heap[2 * i] > self.__heap[2 * i + 1]: bigger_child = 2 * i else: bigger_child = 2 * i + 1 temporary = self.__heap[i] if self.__heap[i] < self.__heap[bigger_child]: self.__heap[i] = self.__heap[bigger_child] self.__heap[bigger_child] = temporary i = bigger_child def pop(self) -> int: """Pop the root element""" max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value @property def get_list(self): return self.__heap[1:] def __len__(self): """Length of the array""" return self.__size if __name__ == "__main__": import doctest doctest.testmod() # create an instance of BinaryHeap binary_heap = BinaryHeap() binary_heap.insert(6) binary_heap.insert(10) binary_heap.insert(15) binary_heap.insert(12) # pop root(max-values because it is max heap) print(binary_heap.pop()) # 15 print(binary_heap.pop()) # 12 # get the list and size after operations print(binary_heap.get_list) print(len(binary_heap))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Program to join a list of strings with a given separator """ def join(separator: str, separated: list[str]) -> str: """ >>> join("", ["a", "b", "c", "d"]) 'abcd' >>> join("#", ["a", "b", "c", "d"]) 'a#b#c#d' >>> join("#", "a") 'a' >>> join(" ", ["You", "are", "amazing!"]) 'You are amazing!' >>> join("#", ["a", "b", "c", 1]) Traceback (most recent call last): ... Exception: join() accepts only strings to be joined """ joined = "" for word_or_phrase in separated: if not isinstance(word_or_phrase, str): raise Exception("join() accepts only strings to be joined") joined += word_or_phrase + separator return joined.strip(separator) if __name__ == "__main__": from doctest import testmod testmod()
""" Program to join a list of strings with a given separator """ def join(separator: str, separated: list[str]) -> str: """ >>> join("", ["a", "b", "c", "d"]) 'abcd' >>> join("#", ["a", "b", "c", "d"]) 'a#b#c#d' >>> join("#", "a") 'a' >>> join(" ", ["You", "are", "amazing!"]) 'You are amazing!' >>> join("#", ["a", "b", "c", 1]) Traceback (most recent call last): ... Exception: join() accepts only strings to be joined """ joined = "" for word_or_phrase in separated: if not isinstance(word_or_phrase, str): raise Exception("join() accepts only strings to be joined") joined += word_or_phrase + separator return joined.strip(separator) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Conversion of pressure units. Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), inHg(in mercury column),torr,atm USAGE : -> Import this file into their respective project. -> Use the function pressure_conversion() for conversion of pressure units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit) -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury -> Wikipedia reference: https://en.wikipedia.org/wiki/Torr -> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) -> https://msestudent.com/what-are-the-units-of-pressure/ -> https://www.unitconverters.net/pressure-converter.html """ from collections import namedtuple from_to = namedtuple("from_to", "from_ to") PRESSURE_CONVERSION = { "atm": from_to(1, 1), "pascal": from_to(0.0000098, 101325), "bar": from_to(0.986923, 1.01325), "kilopascal": from_to(0.00986923, 101.325), "megapascal": from_to(9.86923, 0.101325), "psi": from_to(0.068046, 14.6959), "inHg": from_to(0.0334211, 29.9213), "torr": from_to(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between pressure units. >>> pressure_conversion(4, "atm", "pascal") 405300 >>> pressure_conversion(1, "pascal", "psi") 0.00014401981999999998 >>> pressure_conversion(1, "bar", "atm") 0.986923 >>> pressure_conversion(3, "kilopascal", "bar") 0.029999991892499998 >>> pressure_conversion(2, "megapascal", "psi") 290.074434314 >>> pressure_conversion(4, "psi", "torr") 206.85984 >>> pressure_conversion(1, "inHg", "atm") 0.0334211 >>> pressure_conversion(1, "torr", "psi") 0.019336718261000002 >>> pressure_conversion(4, "wrongUnit", "atm") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr """ if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to ) if __name__ == "__main__": import doctest doctest.testmod()
""" Conversion of pressure units. Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), inHg(in mercury column),torr,atm USAGE : -> Import this file into their respective project. -> Use the function pressure_conversion() for conversion of pressure units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit) -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury -> Wikipedia reference: https://en.wikipedia.org/wiki/Torr -> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) -> https://msestudent.com/what-are-the-units-of-pressure/ -> https://www.unitconverters.net/pressure-converter.html """ from collections import namedtuple from_to = namedtuple("from_to", "from_ to") PRESSURE_CONVERSION = { "atm": from_to(1, 1), "pascal": from_to(0.0000098, 101325), "bar": from_to(0.986923, 1.01325), "kilopascal": from_to(0.00986923, 101.325), "megapascal": from_to(9.86923, 0.101325), "psi": from_to(0.068046, 14.6959), "inHg": from_to(0.0334211, 29.9213), "torr": from_to(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between pressure units. >>> pressure_conversion(4, "atm", "pascal") 405300 >>> pressure_conversion(1, "pascal", "psi") 0.00014401981999999998 >>> pressure_conversion(1, "bar", "atm") 0.986923 >>> pressure_conversion(3, "kilopascal", "bar") 0.029999991892499998 >>> pressure_conversion(2, "megapascal", "psi") 290.074434314 >>> pressure_conversion(4, "psi", "torr") 206.85984 >>> pressure_conversion(1, "inHg", "atm") 0.0334211 >>> pressure_conversion(1, "torr", "psi") 0.019336718261000002 >>> pressure_conversion(4, "wrongUnit", "atm") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr """ if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A NOR Gate is a logic gate in boolean algebra which results to false(0) if any of the input is 1, and True(1) if both the inputs are 0. Following is the truth table of a NOR Gate: | Input 1 | Input 2 | Output | | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 0 | Following is the code implementation of the NOR Gate """ def nor_gate(input_1: int, input_2: int) -> int: """ >>> nor_gate(0, 0) 1 >>> nor_gate(0, 1) 0 >>> nor_gate(1, 0) 0 >>> nor_gate(1, 1) 0 >>> nor_gate(0.0, 0.0) 1 >>> nor_gate(0, -7) 0 """ return int(input_1 == input_2 == 0) def main() -> None: print("Truth Table of NOR Gate:") print("| Input 1 | Input 2 | Output |") print(f"| 0 | 0 | {nor_gate(0, 0)} |") print(f"| 0 | 1 | {nor_gate(0, 1)} |") print(f"| 1 | 0 | {nor_gate(1, 0)} |") print(f"| 1 | 1 | {nor_gate(1, 1)} |") if __name__ == "__main__": import doctest doctest.testmod() main() """Code provided by Akshaj Vishwanathan""" """Reference: https://www.geeksforgeeks.org/logic-gates-in-python/"""
""" A NOR Gate is a logic gate in boolean algebra which results to false(0) if any of the input is 1, and True(1) if both the inputs are 0. Following is the truth table of a NOR Gate: | Input 1 | Input 2 | Output | | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 0 | Following is the code implementation of the NOR Gate """ def nor_gate(input_1: int, input_2: int) -> int: """ >>> nor_gate(0, 0) 1 >>> nor_gate(0, 1) 0 >>> nor_gate(1, 0) 0 >>> nor_gate(1, 1) 0 >>> nor_gate(0.0, 0.0) 1 >>> nor_gate(0, -7) 0 """ return int(input_1 == input_2 == 0) def main() -> None: print("Truth Table of NOR Gate:") print("| Input 1 | Input 2 | Output |") print(f"| 0 | 0 | {nor_gate(0, 0)} |") print(f"| 0 | 1 | {nor_gate(0, 1)} |") print(f"| 1 | 0 | {nor_gate(1, 0)} |") print(f"| 1 | 1 | {nor_gate(1, 1)} |") if __name__ == "__main__": import doctest doctest.testmod() main() """Code provided by Akshaj Vishwanathan""" """Reference: https://www.geeksforgeeks.org/logic-gates-in-python/"""
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Gaussian elimination method for solving a system of linear equations. Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination """ import numpy as np from numpy import float64 from numpy.typing import NDArray def retroactive_resolution( coefficients: NDArray[float64], vector: NDArray[float64] ) -> NDArray[float64]: """ This function performs a retroactive linear system resolution for triangular matrix Examples: 2x1 + 2x2 - 1x3 = 5 2x1 + 2x2 = -1 0x1 - 2x2 - 1x3 = -7 0x1 - 2x2 = -1 0x1 + 0x2 + 5x3 = 15 >>> gaussian_elimination([[2, 2, -1], [0, -2, -1], [0, 0, 5]], [[5], [-7], [15]]) array([[2.], [2.], [3.]]) >>> gaussian_elimination([[2, 2], [0, -2]], [[-1], [-1]]) array([[-1. ], [ 0.5]]) """ rows, columns = np.shape(coefficients) x: NDArray[float64] = np.zeros((rows, 1), dtype=float) for row in reversed(range(rows)): total = 0 for col in range(row + 1, columns): total += coefficients[row, col] * x[col] x[row, 0] = (vector[row] - total) / coefficients[row, row] return x def gaussian_elimination( coefficients: NDArray[float64], vector: NDArray[float64] ) -> NDArray[float64]: """ This function performs Gaussian elimination method Examples: 1x1 - 4x2 - 2x3 = -2 1x1 + 2x2 = 5 5x1 + 2x2 - 2x3 = -3 5x1 + 2x2 = 5 1x1 - 1x2 + 0x3 = 4 >>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]]) array([[ 2.3 ], [-1.7 ], [ 5.55]]) >>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]]) array([[0. ], [2.5]]) """ # coefficients must to be a square matrix so we need to check first rows, columns = np.shape(coefficients) if rows != columns: return np.array((), dtype=float) # augmented matrix augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1) augmented_mat = augmented_mat.astype("float64") # scale the matrix leaving it triangular for row in range(rows - 1): pivot = augmented_mat[row, row] for col in range(row + 1, columns): factor = augmented_mat[col, row] / pivot augmented_mat[col, :] -= factor * augmented_mat[row, :] x = retroactive_resolution( augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1] ) return x if __name__ == "__main__": import doctest doctest.testmod()
""" Gaussian elimination method for solving a system of linear equations. Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination """ import numpy as np from numpy import float64 from numpy.typing import NDArray def retroactive_resolution( coefficients: NDArray[float64], vector: NDArray[float64] ) -> NDArray[float64]: """ This function performs a retroactive linear system resolution for triangular matrix Examples: 2x1 + 2x2 - 1x3 = 5 2x1 + 2x2 = -1 0x1 - 2x2 - 1x3 = -7 0x1 - 2x2 = -1 0x1 + 0x2 + 5x3 = 15 >>> gaussian_elimination([[2, 2, -1], [0, -2, -1], [0, 0, 5]], [[5], [-7], [15]]) array([[2.], [2.], [3.]]) >>> gaussian_elimination([[2, 2], [0, -2]], [[-1], [-1]]) array([[-1. ], [ 0.5]]) """ rows, columns = np.shape(coefficients) x: NDArray[float64] = np.zeros((rows, 1), dtype=float) for row in reversed(range(rows)): total = 0 for col in range(row + 1, columns): total += coefficients[row, col] * x[col] x[row, 0] = (vector[row] - total) / coefficients[row, row] return x def gaussian_elimination( coefficients: NDArray[float64], vector: NDArray[float64] ) -> NDArray[float64]: """ This function performs Gaussian elimination method Examples: 1x1 - 4x2 - 2x3 = -2 1x1 + 2x2 = 5 5x1 + 2x2 - 2x3 = -3 5x1 + 2x2 = 5 1x1 - 1x2 + 0x3 = 4 >>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]]) array([[ 2.3 ], [-1.7 ], [ 5.55]]) >>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]]) array([[0. ], [2.5]]) """ # coefficients must to be a square matrix so we need to check first rows, columns = np.shape(coefficients) if rows != columns: return np.array((), dtype=float) # augmented matrix augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1) augmented_mat = augmented_mat.astype("float64") # scale the matrix leaving it triangular for row in range(rows - 1): pivot = augmented_mat[row, row] for col in range(row + 1, columns): factor = augmented_mat[col, row] / pivot augmented_mat[col, :] -= factor * augmented_mat[row, :] x = retroactive_resolution( augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1] ) return x if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A pure implementation of Dutch national flag (DNF) sort algorithm in Python. Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra. It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can sort a sequence of n size with [0 <= a[i] <= 2] at guaranteed O(n) complexity in a single pass. The flag of the Netherlands consists of three colors: white, red, and blue. The task is to randomly arrange balls of white, red, and blue in such a way that balls of the same color are placed together. DNF sorts a sequence of 0, 1, and 2's in linear time that does not consume any extra space. This algorithm can be implemented only on a sequence that contains three unique elements. 1) Time complexity is O(n). 2) Space complexity is O(1). More info on: https://en.wikipedia.org/wiki/Dutch_national_flag_problem For doctests run following command: python3 -m doctest -v dutch_national_flag_sort.py For manual testing run: python dnf_sort.py """ # Python program to sort a sequence containing only 0, 1 and 2 in a single pass. red = 0 # The first color of the flag. white = 1 # The second color of the flag. blue = 2 # The third color of the flag. colors = (red, white, blue) def dutch_national_flag_sort(sequence: list) -> list: """ A pure Python implementation of Dutch National Flag sort algorithm. :param data: 3 unique integer values (e.g., 0, 1, 2) in an sequence :return: The same collection in ascending order >>> dutch_national_flag_sort([]) [] >>> dutch_national_flag_sort([0]) [0] >>> dutch_national_flag_sort([2, 1, 0, 0, 1, 2]) [0, 0, 1, 1, 2, 2] >>> dutch_national_flag_sort([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2] >>> dutch_national_flag_sort("abacab") Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort("Abacab") Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([3, 2, 3, 1, 3, 0, 3]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([-1, 2, -1, 1, -1, 0, -1]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([1.1, 2, 1.1, 1, 1.1, 0, 1.1]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values """ if not sequence: return [] if len(sequence) == 1: return list(sequence) low = 0 high = len(sequence) - 1 mid = 0 while mid <= high: if sequence[mid] == colors[0]: sequence[low], sequence[mid] = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: sequence[mid], sequence[high] = sequence[high], sequence[mid] high -= 1 else: raise ValueError( f"The elements inside the sequence must contains only {colors} values" ) return sequence if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by commas:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] print(f"{dutch_national_flag_sort(unsorted)}")
""" A pure implementation of Dutch national flag (DNF) sort algorithm in Python. Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra. It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can sort a sequence of n size with [0 <= a[i] <= 2] at guaranteed O(n) complexity in a single pass. The flag of the Netherlands consists of three colors: white, red, and blue. The task is to randomly arrange balls of white, red, and blue in such a way that balls of the same color are placed together. DNF sorts a sequence of 0, 1, and 2's in linear time that does not consume any extra space. This algorithm can be implemented only on a sequence that contains three unique elements. 1) Time complexity is O(n). 2) Space complexity is O(1). More info on: https://en.wikipedia.org/wiki/Dutch_national_flag_problem For doctests run following command: python3 -m doctest -v dutch_national_flag_sort.py For manual testing run: python dnf_sort.py """ # Python program to sort a sequence containing only 0, 1 and 2 in a single pass. red = 0 # The first color of the flag. white = 1 # The second color of the flag. blue = 2 # The third color of the flag. colors = (red, white, blue) def dutch_national_flag_sort(sequence: list) -> list: """ A pure Python implementation of Dutch National Flag sort algorithm. :param data: 3 unique integer values (e.g., 0, 1, 2) in an sequence :return: The same collection in ascending order >>> dutch_national_flag_sort([]) [] >>> dutch_national_flag_sort([0]) [0] >>> dutch_national_flag_sort([2, 1, 0, 0, 1, 2]) [0, 0, 1, 1, 2, 2] >>> dutch_national_flag_sort([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2] >>> dutch_national_flag_sort("abacab") Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort("Abacab") Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([3, 2, 3, 1, 3, 0, 3]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([-1, 2, -1, 1, -1, 0, -1]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values >>> dutch_national_flag_sort([1.1, 2, 1.1, 1, 1.1, 0, 1.1]) Traceback (most recent call last): ... ValueError: The elements inside the sequence must contains only (0, 1, 2) values """ if not sequence: return [] if len(sequence) == 1: return list(sequence) low = 0 high = len(sequence) - 1 mid = 0 while mid <= high: if sequence[mid] == colors[0]: sequence[low], sequence[mid] = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: sequence[mid], sequence[high] = sequence[high], sequence[mid] high -= 1 else: raise ValueError( f"The elements inside the sequence must contains only {colors} values" ) return sequence if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by commas:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] print(f"{dutch_national_flag_sort(unsorted)}")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 117: https://projecteuler.net/problem=117 Using a combination of grey square tiles and oblong tiles chosen from: red tiles (measuring two units), green tiles (measuring three units), and blue tiles (measuring four units), it is possible to tile a row measuring five units in length in exactly fifteen different ways. |grey|grey|grey|grey|grey| |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| |red,red|green,green,green| |green,green,green|red,red| |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| How many ways can a row measuring fifty units in length be tiled? NOTE: This is related to Problem 116 (https://projecteuler.net/problem=116). """ def solution(length: int = 50) -> int: """ Returns the number of ways can a row of the given length be tiled >>> solution(5) 15 """ ways_number = [1] * (length + 1) for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 117: https://projecteuler.net/problem=117 Using a combination of grey square tiles and oblong tiles chosen from: red tiles (measuring two units), green tiles (measuring three units), and blue tiles (measuring four units), it is possible to tile a row measuring five units in length in exactly fifteen different ways. |grey|grey|grey|grey|grey| |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| |red,red|green,green,green| |green,green,green|red,red| |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| How many ways can a row measuring fifty units in length be tiled? NOTE: This is related to Problem 116 (https://projecteuler.net/problem=116). """ def solution(length: int = 50) -> int: """ Returns the number of ways can a row of the given length be tiled >>> solution(5) 15 """ ways_number = [1] * (length + 1) for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Any def mode(input_list: list) -> list[Any]: """This function returns the mode(Mode as in the measures of central tendency) of the input data. The input list may contain any Datastructure or any Datatype. >>> mode([2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2]) [2] >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2]) [2] >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2]) [2, 4] >>> mode(["x", "y", "y", "z"]) ['y'] >>> mode(["x", "x" , "y", "y", "z"]) ['x', 'y'] """ if not input_list: return [] result = [input_list.count(value) for value in input_list] y = max(result) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(result) if value == y}) if __name__ == "__main__": import doctest doctest.testmod()
from typing import Any def mode(input_list: list) -> list[Any]: """This function returns the mode(Mode as in the measures of central tendency) of the input data. The input list may contain any Datastructure or any Datatype. >>> mode([2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2]) [2] >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2]) [2] >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2]) [2, 4] >>> mode(["x", "y", "y", "z"]) ['y'] >>> mode(["x", "x" , "y", "y", "z"]) ['x', 'y'] """ if not input_list: return [] result = [input_list.count(value) for value in input_list] y = max(result) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(result) if value == y}) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Bi-directional Dijkstra's algorithm. A bi-directional approach is an efficient and less time consuming optimization for Dijkstra's searching algorithm Reference: shorturl.at/exHM7 """ # Author: Swayam Singh (https://github.com/practice404) from queue import PriorityQueue from typing import Any import numpy as np def bidirectional_dij( source: str, destination: str, graph_forward: dict, graph_backward: dict ) -> int: """ Bi-directional Dijkstra's algorithm. Returns: shortest_path_distance (int): length of the shortest path. Warnings: If the destination is not reachable, function returns -1 >>> bidirectional_dij("E", "F", graph_fwd, graph_bwd) 3 """ shortest_path_distance = -1 visited_forward = set() visited_backward = set() cst_fwd = {source: 0} cst_bwd = {destination: 0} parent_forward = {source: None} parent_backward = {destination: None} queue_forward: PriorityQueue[Any] = PriorityQueue() queue_backward: PriorityQueue[Any] = PriorityQueue() shortest_distance = np.inf queue_forward.put((0, source)) queue_backward.put((0, destination)) if source == destination: return 0 while queue_forward and queue_backward: while not queue_forward.empty(): _, v_fwd = queue_forward.get() if v_fwd not in visited_forward: break else: break visited_forward.add(v_fwd) while not queue_backward.empty(): _, v_bwd = queue_backward.get() if v_bwd not in visited_backward: break else: break visited_backward.add(v_bwd) # forward pass and relaxation for nxt_fwd, d_forward in graph_forward[v_fwd]: if nxt_fwd in visited_forward: continue old_cost_f = cst_fwd.get(nxt_fwd, np.inf) new_cost_f = cst_fwd[v_fwd] + d_forward if new_cost_f < old_cost_f: queue_forward.put((new_cost_f, nxt_fwd)) cst_fwd[nxt_fwd] = new_cost_f parent_forward[nxt_fwd] = v_fwd if nxt_fwd in visited_backward: if cst_fwd[v_fwd] + d_forward + cst_bwd[nxt_fwd] < shortest_distance: shortest_distance = cst_fwd[v_fwd] + d_forward + cst_bwd[nxt_fwd] # backward pass and relaxation for nxt_bwd, d_backward in graph_backward[v_bwd]: if nxt_bwd in visited_backward: continue old_cost_b = cst_bwd.get(nxt_bwd, np.inf) new_cost_b = cst_bwd[v_bwd] + d_backward if new_cost_b < old_cost_b: queue_backward.put((new_cost_b, nxt_bwd)) cst_bwd[nxt_bwd] = new_cost_b parent_backward[nxt_bwd] = v_bwd if nxt_bwd in visited_forward: if cst_bwd[v_bwd] + d_backward + cst_fwd[nxt_bwd] < shortest_distance: shortest_distance = cst_bwd[v_bwd] + d_backward + cst_fwd[nxt_bwd] if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: shortest_path_distance = shortest_distance return shortest_path_distance graph_fwd = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } graph_bwd = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
""" Bi-directional Dijkstra's algorithm. A bi-directional approach is an efficient and less time consuming optimization for Dijkstra's searching algorithm Reference: shorturl.at/exHM7 """ # Author: Swayam Singh (https://github.com/practice404) from queue import PriorityQueue from typing import Any import numpy as np def bidirectional_dij( source: str, destination: str, graph_forward: dict, graph_backward: dict ) -> int: """ Bi-directional Dijkstra's algorithm. Returns: shortest_path_distance (int): length of the shortest path. Warnings: If the destination is not reachable, function returns -1 >>> bidirectional_dij("E", "F", graph_fwd, graph_bwd) 3 """ shortest_path_distance = -1 visited_forward = set() visited_backward = set() cst_fwd = {source: 0} cst_bwd = {destination: 0} parent_forward = {source: None} parent_backward = {destination: None} queue_forward: PriorityQueue[Any] = PriorityQueue() queue_backward: PriorityQueue[Any] = PriorityQueue() shortest_distance = np.inf queue_forward.put((0, source)) queue_backward.put((0, destination)) if source == destination: return 0 while queue_forward and queue_backward: while not queue_forward.empty(): _, v_fwd = queue_forward.get() if v_fwd not in visited_forward: break else: break visited_forward.add(v_fwd) while not queue_backward.empty(): _, v_bwd = queue_backward.get() if v_bwd not in visited_backward: break else: break visited_backward.add(v_bwd) # forward pass and relaxation for nxt_fwd, d_forward in graph_forward[v_fwd]: if nxt_fwd in visited_forward: continue old_cost_f = cst_fwd.get(nxt_fwd, np.inf) new_cost_f = cst_fwd[v_fwd] + d_forward if new_cost_f < old_cost_f: queue_forward.put((new_cost_f, nxt_fwd)) cst_fwd[nxt_fwd] = new_cost_f parent_forward[nxt_fwd] = v_fwd if nxt_fwd in visited_backward: if cst_fwd[v_fwd] + d_forward + cst_bwd[nxt_fwd] < shortest_distance: shortest_distance = cst_fwd[v_fwd] + d_forward + cst_bwd[nxt_fwd] # backward pass and relaxation for nxt_bwd, d_backward in graph_backward[v_bwd]: if nxt_bwd in visited_backward: continue old_cost_b = cst_bwd.get(nxt_bwd, np.inf) new_cost_b = cst_bwd[v_bwd] + d_backward if new_cost_b < old_cost_b: queue_backward.put((new_cost_b, nxt_bwd)) cst_bwd[nxt_bwd] = new_cost_b parent_backward[nxt_bwd] = v_bwd if nxt_bwd in visited_forward: if cst_bwd[v_bwd] + d_backward + cst_fwd[nxt_bwd] < shortest_distance: shortest_distance = cst_bwd[v_bwd] + d_backward + cst_fwd[nxt_bwd] if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: shortest_path_distance = shortest_distance return shortest_path_distance graph_fwd = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } graph_bwd = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance""" def jaro_winkler(str1: str, str2: str) -> float: """ Jaro–Winkler distance is a string metric measuring an edit distance between two sequences. Output value is between 0.0 and 1.0. >>> jaro_winkler("martha", "marhta") 0.9611111111111111 >>> jaro_winkler("CRATE", "TRACE") 0.7333333333333334 >>> jaro_winkler("test", "dbdbdbdb") 0.0 >>> jaro_winkler("test", "test") 1.0 >>> jaro_winkler("hello world", "HeLLo W0rlD") 0.6363636363636364 >>> jaro_winkler("test", "") 0.0 >>> jaro_winkler("hello", "world") 0.4666666666666666 >>> jaro_winkler("hell**o", "*world") 0.4365079365079365 """ def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, l in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2))) if l in _str2[left:right]: matched.append(l) _str2 = f"{_str2[0:_str2.index(l)]} {_str2[_str2.index(l) + 1:]}" return "".join(matched) # matching characters matching_1 = get_matched_characters(str1, str2) matching_2 = get_matched_characters(str2, str1) match_count = len(matching_1) # transposition transpositions = ( len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2 ) if not match_count: jaro = 0.0 else: jaro = ( 1 / 3 * ( match_count / len(str1) + match_count / len(str2) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters prefix_len = 0 for c1, c2 in zip(str1[:4], str2[:4]): if c1 == c2: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
"""https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance""" def jaro_winkler(str1: str, str2: str) -> float: """ Jaro–Winkler distance is a string metric measuring an edit distance between two sequences. Output value is between 0.0 and 1.0. >>> jaro_winkler("martha", "marhta") 0.9611111111111111 >>> jaro_winkler("CRATE", "TRACE") 0.7333333333333334 >>> jaro_winkler("test", "dbdbdbdb") 0.0 >>> jaro_winkler("test", "test") 1.0 >>> jaro_winkler("hello world", "HeLLo W0rlD") 0.6363636363636364 >>> jaro_winkler("test", "") 0.0 >>> jaro_winkler("hello", "world") 0.4666666666666666 >>> jaro_winkler("hell**o", "*world") 0.4365079365079365 """ def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, l in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2))) if l in _str2[left:right]: matched.append(l) _str2 = f"{_str2[0:_str2.index(l)]} {_str2[_str2.index(l) + 1:]}" return "".join(matched) # matching characters matching_1 = get_matched_characters(str1, str2) matching_2 = get_matched_characters(str2, str1) match_count = len(matching_1) # transposition transpositions = ( len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2 ) if not match_count: jaro = 0.0 else: jaro = ( 1 / 3 * ( match_count / len(str1) + match_count / len(str2) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters prefix_len = 0 for c1, c2 in zip(str1[:4], str2[:4]): if c1 == c2: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def max_subarray_sum(nums: list) -> int: """ >>> max_subarray_sum([6 , 9, -1, 3, -7, -5, 10]) 17 """ if not nums: return 0 n = len(nums) res, s, s_pre = nums[0], nums[0], nums[0] for i in range(1, n): s = max(nums[i], s_pre + nums[i]) s_pre = s res = max(res, s) return res if __name__ == "__main__": nums = [6, 9, -1, 3, -7, -5, 10] print(max_subarray_sum(nums))
def max_subarray_sum(nums: list) -> int: """ >>> max_subarray_sum([6 , 9, -1, 3, -7, -5, 10]) 17 """ if not nums: return 0 n = len(nums) res, s, s_pre = nums[0], nums[0], nums[0] for i in range(1, n): s = max(nums[i], s_pre + nums[i]) s_pre = s res = max(res, s) return res if __name__ == "__main__": nums = [6, 9, -1, 3, -7, -5, 10] print(max_subarray_sum(nums))
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 57: https://projecteuler.net/problem=57 It is possible to show that the square root of two can be expressed as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...))) By expanding this for the first four iterations, we get: 1 + 1 / 2 = 3 / 2 = 1.5 1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666... 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator? """ def solution(n: int = 1000) -> int: """ returns number of fractions containing a numerator with more digits than the denominator in the first n expansions. >>> solution(14) 2 >>> solution(100) 15 >>> solution(10000) 1508 """ prev_numerator, prev_denominator = 1, 1 result = [] for i in range(1, n + 1): numerator = prev_numerator + 2 * prev_denominator denominator = prev_numerator + prev_denominator if len(str(numerator)) > len(str(denominator)): result.append(i) prev_numerator = numerator prev_denominator = denominator return len(result) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 57: https://projecteuler.net/problem=57 It is possible to show that the square root of two can be expressed as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...))) By expanding this for the first four iterations, we get: 1 + 1 / 2 = 3 / 2 = 1.5 1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666... 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator? """ def solution(n: int = 1000) -> int: """ returns number of fractions containing a numerator with more digits than the denominator in the first n expansions. >>> solution(14) 2 >>> solution(100) 15 >>> solution(10000) 1508 """ prev_numerator, prev_denominator = 1, 1 result = [] for i in range(1, n + 1): numerator = prev_numerator + 2 * prev_denominator denominator = prev_numerator + prev_denominator if len(str(numerator)) > len(str(denominator)): result.append(i) prev_numerator = numerator prev_denominator = denominator return len(result) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def print_dist(dist, v): print("\nVertex Distance") for i in range(v): if dist[i] != float("inf"): print(i, "\t", int(dist[i]), end="\t") else: print(i, "\t", "INF", end="\t") print() def min_dist(mdist, vset, v): min_val = float("inf") min_ind = -1 for i in range(v): if (not vset[i]) and mdist[i] < min_val: min_ind = i min_val = mdist[i] return min_ind def dijkstra(graph, v, src): mdist = [float("inf") for _ in range(v)] vset = [False for _ in range(v)] mdist[src] = 0.0 for _ in range(v - 1): u = min_dist(mdist, vset, v) vset[u] = True for i in range(v): if ( (not vset[i]) and graph[u][i] != float("inf") and mdist[u] + graph[u][i] < mdist[i] ): mdist[i] = mdist[u] + graph[u][i] print_dist(mdist, i) if __name__ == "__main__": V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph = [[float("inf") for i in range(V)] for j in range(V)] for i in range(V): graph[i][i] = 0.0 for i in range(E): print("\nEdge ", i + 1) src = int(input("Enter source:").strip()) dst = int(input("Enter destination:").strip()) weight = float(input("Enter weight:").strip()) graph[src][dst] = weight gsrc = int(input("\nEnter shortest path source:").strip()) dijkstra(graph, V, gsrc)
def print_dist(dist, v): print("\nVertex Distance") for i in range(v): if dist[i] != float("inf"): print(i, "\t", int(dist[i]), end="\t") else: print(i, "\t", "INF", end="\t") print() def min_dist(mdist, vset, v): min_val = float("inf") min_ind = -1 for i in range(v): if (not vset[i]) and mdist[i] < min_val: min_ind = i min_val = mdist[i] return min_ind def dijkstra(graph, v, src): mdist = [float("inf") for _ in range(v)] vset = [False for _ in range(v)] mdist[src] = 0.0 for _ in range(v - 1): u = min_dist(mdist, vset, v) vset[u] = True for i in range(v): if ( (not vset[i]) and graph[u][i] != float("inf") and mdist[u] + graph[u][i] < mdist[i] ): mdist[i] = mdist[u] + graph[u][i] print_dist(mdist, i) if __name__ == "__main__": V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph = [[float("inf") for i in range(V)] for j in range(V)] for i in range(V): graph[i][i] = 0.0 for i in range(E): print("\nEdge ", i + 1) src = int(input("Enter source:").strip()) dst = int(input("Enter destination:").strip()) weight = float(input("Enter weight:").strip()) graph[src][dst] = weight gsrc = int(input("\nEnter shortest path source:").strip()) dijkstra(graph, V, gsrc)
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=15), SegmentTreeNode(start=0, end=2, val=8), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=3), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=1)) >>> >>> num_arr.update(1, 5) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=19), SegmentTreeNode(start=0, end=2, val=12), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=7), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=5)) >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=5) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=1) SegmentTreeNode(start=0, end=2, val=1) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=1) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=2) SegmentTreeNode(start=0, end=2, val=2) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=15), SegmentTreeNode(start=0, end=2, val=8), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=3), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=1)) >>> >>> num_arr.update(1, 5) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=19), SegmentTreeNode(start=0, end=2, val=12), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=7), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=5)) >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=5) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=1) SegmentTreeNode(start=0, end=2, val=1) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=1) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=2) SegmentTreeNode(start=0, end=2, val=2) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(ratio: float = 0.1) -> int: """ Returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(ratio: float = 0.1) -> int: """ Returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Electrical impedance is the measure of the opposition that a circuit presents to a current when a voltage is applied. Impedance extends the concept of resistance to alternating current (AC) circuits. Source: https://en.wikipedia.org/wiki/Electrical_impedance """ from __future__ import annotations from math import pow, sqrt def electrical_impedance( resistance: float, reactance: float, impedance: float ) -> dict[str, float]: """ Apply Electrical Impedance formula, on any two given electrical values, which can be resistance, reactance, and impedance, and then in a Python dict return name/value pair of the zero value. >>> electrical_impedance(3,4,0) {'impedance': 5.0} >>> electrical_impedance(0,4,5) {'resistance': 3.0} >>> electrical_impedance(3,0,5) {'reactance': 4.0} >>> electrical_impedance(3,4,5) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 """ if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance == 0: return {"resistance": sqrt(pow(impedance, 2) - pow(reactance, 2))} elif reactance == 0: return {"reactance": sqrt(pow(impedance, 2) - pow(resistance, 2))} elif impedance == 0: return {"impedance": sqrt(pow(resistance, 2) + pow(reactance, 2))} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
"""Electrical impedance is the measure of the opposition that a circuit presents to a current when a voltage is applied. Impedance extends the concept of resistance to alternating current (AC) circuits. Source: https://en.wikipedia.org/wiki/Electrical_impedance """ from __future__ import annotations from math import pow, sqrt def electrical_impedance( resistance: float, reactance: float, impedance: float ) -> dict[str, float]: """ Apply Electrical Impedance formula, on any two given electrical values, which can be resistance, reactance, and impedance, and then in a Python dict return name/value pair of the zero value. >>> electrical_impedance(3,4,0) {'impedance': 5.0} >>> electrical_impedance(0,4,5) {'resistance': 3.0} >>> electrical_impedance(3,0,5) {'reactance': 4.0} >>> electrical_impedance(3,4,5) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 """ if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance == 0: return {"resistance": sqrt(pow(impedance, 2) - pow(reactance, 2))} elif reactance == 0: return {"reactance": sqrt(pow(impedance, 2) - pow(resistance, 2))} elif impedance == 0: return {"impedance": sqrt(pow(resistance, 2) + pow(reactance, 2))} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: List of waiting times. >>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4) [0, 3, 5, 0] >>> calculate_waitingtime([1,2,3],[2,5,1],3) [0, 2, 0] >>> calculate_waitingtime([2,3],[5,1],2) [1, 0] """ remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False # Process until all processes are completed while complete != no_of_processes: for j in range(no_of_processes): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False # Find finish time of current process finish_time = increment_time + 1 # Calculate waiting time finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] if waiting_time[short] < 0: waiting_time[short] = 0 # Increment time increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turn around time of each Processes Return: list of turn around times. >>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0]) [3, 6, 10, 1] >>> calculate_turnaroundtime([3,3], 2, [0,3]) [3, 6] >>> calculate_turnaroundtime([8,10,1], 3, [1,0,3]) [9, 10, 4] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: """ This function calculates the average of the waiting & turnaround times Prints: Average Waiting time & Average Turn Around Time >>> calculate_average_times([0,3,5,0],[3,6,10,1],4) Average waiting time = 2.00000 Average turn around time = 5.0 >>> calculate_average_times([2,3],[3,6],2) Average waiting time = 2.50000 Average turn around time = 4.5 >>> calculate_average_times([10,4,3],[2,7,6],3) Average waiting time = 5.66667 Average turn around time = 5.0 """ total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}") print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: List of waiting times. >>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4) [0, 3, 5, 0] >>> calculate_waitingtime([1,2,3],[2,5,1],3) [0, 2, 0] >>> calculate_waitingtime([2,3],[5,1],2) [1, 0] """ remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False # Process until all processes are completed while complete != no_of_processes: for j in range(no_of_processes): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False # Find finish time of current process finish_time = increment_time + 1 # Calculate waiting time finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] if waiting_time[short] < 0: waiting_time[short] = 0 # Increment time increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turn around time of each Processes Return: list of turn around times. >>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0]) [3, 6, 10, 1] >>> calculate_turnaroundtime([3,3], 2, [0,3]) [3, 6] >>> calculate_turnaroundtime([8,10,1], 3, [1,0,3]) [9, 10, 4] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: """ This function calculates the average of the waiting & turnaround times Prints: Average Waiting time & Average Turn Around Time >>> calculate_average_times([0,3,5,0],[3,6,10,1],4) Average waiting time = 2.00000 Average turn around time = 5.0 >>> calculate_average_times([2,3],[3,6],2) Average waiting time = 2.50000 Average turn around time = 4.5 >>> calculate_average_times([10,4,3],[2,7,6],3) Average waiting time = 5.66667 Average turn around time = 5.0 """ total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}") print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem Description: Given a binary tree, return its mirror. """ def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_dictionary[root] = [right_child, left_child] binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: """ >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) Traceback (most recent call last): ... ValueError: root 5 is not present in the binary_tree >>> binary_tree_mirror({}, 5) Traceback (most recent call last): ... ValueError: binary tree cannot be empty """ if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: raise ValueError(f"root {root} is not present in the binary_tree") binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
""" Problem Description: Given a binary tree, return its mirror. """ def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_dictionary[root] = [right_child, left_child] binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: """ >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) Traceback (most recent call last): ... ValueError: root 5 is not present in the binary_tree >>> binary_tree_mirror({}, 5) Traceback (most recent call last): ... ValueError: binary tree cannot be empty """ if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: raise ValueError(f"root {root} is not present in the binary_tree") binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Approximates the area under the curve using the trapezoidal rule """ from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[int | float], int | float], x_start: int | float, x_end: int | float, steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000) '10.000' >>> def f(x): ... return 9*x**2 >>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000) '192.0000' >>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000) '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x**3 print("f(x) = x^3") print("The area between the curve, x = -10, x = 10 and the x axis is:") i = 10 while i <= 100000: area = trapezoidal_area(f, -5, 5, i) print(f"with {i} steps: {area}") i *= 10
""" Approximates the area under the curve using the trapezoidal rule """ from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[int | float], int | float], x_start: int | float, x_end: int | float, steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000) '10.000' >>> def f(x): ... return 9*x**2 >>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000) '192.0000' >>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000) '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x**3 print("f(x) = x^3") print("The area between the curve, x = -10, x = 10 and the x axis is:") i = 10 while i <= 100000: area = trapezoidal_area(f, -5, 5, i) print(f"with {i} steps: {area}") i *= 10
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations class Node: """ A Node has data variable and pointers to Nodes to its left and right. """ def __init__(self, data: int) -> None: self.data = data self.left: Node | None = None self.right: Node | None = None def display(tree: Node | None) -> None: # In Order traversal of the tree """ >>> root = Node(1) >>> root.left = Node(0) >>> root.right = Node(2) >>> display(root) 0 1 2 >>> display(root.right) 2 """ if tree: display(tree.left) print(tree.data) display(tree.right) def depth_of_tree(tree: Node | None) -> int: """ Recursive function that returns the depth of a binary tree. >>> root = Node(0) >>> depth_of_tree(root) 1 >>> root.left = Node(0) >>> depth_of_tree(root) 2 >>> root.right = Node(0) >>> depth_of_tree(root) 2 >>> root.left.right = Node(0) >>> depth_of_tree(root) 3 >>> depth_of_tree(root.left) 2 """ return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right)) if tree else 0 def is_full_binary_tree(tree: Node) -> bool: """ Returns True if this is a full binary tree >>> root = Node(0) >>> is_full_binary_tree(root) True >>> root.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right = Node(0) >>> is_full_binary_tree(root) True >>> root.left.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right.right = Node(0) >>> is_full_binary_tree(root) False """ if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right) else: return not tree.left and not tree.right def main() -> None: # Main function for testing. tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.left.right.left = Node(6) tree.right.left = Node(7) tree.right.left.left = Node(8) tree.right.left.left.right = Node(9) print(is_full_binary_tree(tree)) print(depth_of_tree(tree)) print("Tree is: ") display(tree) if __name__ == "__main__": main()
from __future__ import annotations class Node: """ A Node has data variable and pointers to Nodes to its left and right. """ def __init__(self, data: int) -> None: self.data = data self.left: Node | None = None self.right: Node | None = None def display(tree: Node | None) -> None: # In Order traversal of the tree """ >>> root = Node(1) >>> root.left = Node(0) >>> root.right = Node(2) >>> display(root) 0 1 2 >>> display(root.right) 2 """ if tree: display(tree.left) print(tree.data) display(tree.right) def depth_of_tree(tree: Node | None) -> int: """ Recursive function that returns the depth of a binary tree. >>> root = Node(0) >>> depth_of_tree(root) 1 >>> root.left = Node(0) >>> depth_of_tree(root) 2 >>> root.right = Node(0) >>> depth_of_tree(root) 2 >>> root.left.right = Node(0) >>> depth_of_tree(root) 3 >>> depth_of_tree(root.left) 2 """ return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right)) if tree else 0 def is_full_binary_tree(tree: Node) -> bool: """ Returns True if this is a full binary tree >>> root = Node(0) >>> is_full_binary_tree(root) True >>> root.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right = Node(0) >>> is_full_binary_tree(root) True >>> root.left.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right.right = Node(0) >>> is_full_binary_tree(root) False """ if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right) else: return not tree.left and not tree.right def main() -> None: # Main function for testing. tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.left.right.left = Node(6) tree.right.left = Node(7) tree.right.left.left = Node(8) tree.right.left.left.right = Node(9) print(is_full_binary_tree(tree)) print(depth_of_tree(tree)) print("Tree is: ") display(tree) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import csv import tweepy # Twitter API credentials consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" def get_all_tweets(screen_name: str) -> None: # authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) # initialize a list to hold all the tweepy Tweets alltweets = [] # make initial request for most recent tweets (200 is the maximum allowed count) new_tweets = api.user_timeline(screen_name=screen_name, count=200) # save most recent tweets alltweets.extend(new_tweets) # save the id of the oldest tweet less one oldest = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(new_tweets) > 0: print(f"getting tweets before {oldest}") # all subsequent requests use the max_id param to prevent duplicates new_tweets = api.user_timeline( screen_name=screen_name, count=200, max_id=oldest ) # save most recent tweets alltweets.extend(new_tweets) # update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print(f"...{len(alltweets)} tweets downloaded so far") # transform the tweepy tweets into a 2D array that will populate the csv outtweets = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(f"new_{screen_name}_tweets.csv", "w") as f: writer = csv.writer(f) writer.writerow(["id", "created_at", "text"]) writer.writerows(outtweets) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("FirePing32")
import csv import tweepy # Twitter API credentials consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" def get_all_tweets(screen_name: str) -> None: # authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) # initialize a list to hold all the tweepy Tweets alltweets = [] # make initial request for most recent tweets (200 is the maximum allowed count) new_tweets = api.user_timeline(screen_name=screen_name, count=200) # save most recent tweets alltweets.extend(new_tweets) # save the id of the oldest tweet less one oldest = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(new_tweets) > 0: print(f"getting tweets before {oldest}") # all subsequent requests use the max_id param to prevent duplicates new_tweets = api.user_timeline( screen_name=screen_name, count=200, max_id=oldest ) # save most recent tweets alltweets.extend(new_tweets) # update the id of the oldest tweet less one oldest = alltweets[-1].id - 1 print(f"...{len(alltweets)} tweets downloaded so far") # transform the tweepy tweets into a 2D array that will populate the csv outtweets = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(f"new_{screen_name}_tweets.csv", "w") as f: writer = csv.writer(f) writer.writerow(["id", "created_at", "text"]) writer.writerows(outtweets) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("FirePing32")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Find the volume of various shapes. * https://en.wikipedia.org/wiki/Volume * https://en.wikipedia.org/wiki/Spherical_cap """ from __future__ import annotations from math import pi, pow def vol_cube(side_length: int | float) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1.0 >>> vol_cube(3) 27.0 >>> vol_cube(0) 0.0 >>> vol_cube(1.6) 4.096000000000001 >>> vol_cube(-1) Traceback (most recent call last): ... ValueError: vol_cube() only accepts non-negative values """ if side_length < 0: raise ValueError("vol_cube() only accepts non-negative values") return pow(side_length, 3) def vol_spherical_cap(height: float, radius: float) -> float: """ Calculate the volume of the spherical cap. >>> vol_spherical_cap(1, 2) 5.235987755982988 >>> vol_spherical_cap(1.6, 2.6) 16.621119532592402 >>> vol_spherical_cap(0, 0) 0.0 >>> vol_spherical_cap(-1, 2) Traceback (most recent call last): ... ValueError: vol_spherical_cap() only accepts non-negative values >>> vol_spherical_cap(1, -2) Traceback (most recent call last): ... ValueError: vol_spherical_cap() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_spherical_cap() only accepts non-negative values") # Volume is 1/3 pi * height squared * (3 * radius - height) return 1 / 3 * pi * pow(height, 2) * (3 * radius - height) def vol_spheres_intersect( radius_1: float, radius_2: float, centers_distance: float ) -> float: """ Calculate the volume of the intersection of two spheres. The intersection is composed by two spherical caps and therefore its volume is the sum of the volumes of the spherical caps. First, it calculates the heights (h1, h2) of the spherical caps, then the two volumes and it returns the sum. The height formulas are h1 = (radius_1 - radius_2 + centers_distance) * (radius_1 + radius_2 - centers_distance) / (2 * centers_distance) h2 = (radius_2 - radius_1 + centers_distance) * (radius_2 + radius_1 - centers_distance) / (2 * centers_distance) if centers_distance is 0 then it returns the volume of the smallers sphere :return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1) >>> vol_spheres_intersect(2, 2, 1) 21.205750411731103 >>> vol_spheres_intersect(2.6, 2.6, 1.6) 40.71504079052372 >>> vol_spheres_intersect(0, 0, 0) 0.0 >>> vol_spheres_intersect(-2, 2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values >>> vol_spheres_intersect(2, -2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values >>> vol_spheres_intersect(2, 2, -1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values """ if radius_1 < 0 or radius_2 < 0 or centers_distance < 0: raise ValueError("vol_spheres_intersect() only accepts non-negative values") if centers_distance == 0: return vol_sphere(min(radius_1, radius_2)) h1 = ( (radius_1 - radius_2 + centers_distance) * (radius_1 + radius_2 - centers_distance) / (2 * centers_distance) ) h2 = ( (radius_2 - radius_1 + centers_distance) * (radius_2 + radius_1 - centers_distance) / (2 * centers_distance) ) return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1) def vol_spheres_union( radius_1: float, radius_2: float, centers_distance: float ) -> float: """ Calculate the volume of the union of two spheres that possibly intersect. It is the sum of sphere A and sphere B minus their intersection. First, it calculates the volumes (v1, v2) of the spheres, then the volume of the intersection (i) and it returns the sum v1+v2-i. If centers_distance is 0 then it returns the volume of the larger sphere :return vol_sphere(radius_1) + vol_sphere(radius_2) - vol_spheres_intersect(radius_1, radius_2, centers_distance) >>> vol_spheres_union(2, 2, 1) 45.814892864851146 >>> vol_spheres_union(1.56, 2.2, 1.4) 48.77802773671288 >>> vol_spheres_union(0, 2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_union() only accepts non-negative values, non-zero radius >>> vol_spheres_union('1.56', '2.2', '1.4') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'str' and 'int' >>> vol_spheres_union(1, None, 1) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'NoneType' and 'int' """ if radius_1 <= 0 or radius_2 <= 0 or centers_distance < 0: raise ValueError( "vol_spheres_union() only accepts non-negative values, non-zero radius" ) if centers_distance == 0: return vol_sphere(max(radius_1, radius_2)) return ( vol_sphere(radius_1) + vol_sphere(radius_2) - vol_spheres_intersect(radius_1, radius_2, centers_distance) ) def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return multiple of width, length and height >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 >>> vol_cuboid(1.6, 2.6, 3.6) 14.976 >>> vol_cuboid(0, 0, 0) 0.0 >>> vol_cuboid(-1, 2, 3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values >>> vol_cuboid(1, -2, 3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values >>> vol_cuboid(1, 2, -3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values """ if width < 0 or height < 0 or length < 0: raise ValueError("vol_cuboid() only accepts non-negative values") return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * area_of_base * height >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 >>> vol_cone(1.6, 1.6) 0.8533333333333335 >>> vol_cone(0, 0) 0.0 >>> vol_cone(-1, 1) Traceback (most recent call last): ... ValueError: vol_cone() only accepts non-negative values >>> vol_cone(1, -1) Traceback (most recent call last): ... ValueError: vol_cone() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_cone() only accepts non-negative values") return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: """ Calculate the Volume of a Right Circular Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * pi * radius^2 * height >>> vol_right_circ_cone(2, 3) 12.566370614359172 >>> vol_right_circ_cone(0, 0) 0.0 >>> vol_right_circ_cone(1.6, 1.6) 4.289321169701265 >>> vol_right_circ_cone(-1, 1) Traceback (most recent call last): ... ValueError: vol_right_circ_cone() only accepts non-negative values >>> vol_right_circ_cone(1, -1) Traceback (most recent call last): ... ValueError: vol_right_circ_cone() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_right_circ_cone() only accepts non-negative values") return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Prism. Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) :return V = Bh >>> vol_prism(10, 2) 20.0 >>> vol_prism(11, 1) 11.0 >>> vol_prism(1.6, 1.6) 2.5600000000000005 >>> vol_prism(0, 0) 0.0 >>> vol_prism(-1, 1) Traceback (most recent call last): ... ValueError: vol_prism() only accepts non-negative values >>> vol_prism(1, -1) Traceback (most recent call last): ... ValueError: vol_prism() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_prism() only accepts non-negative values") return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 >>> vol_pyramid(1.6, 1.6) 0.8533333333333335 >>> vol_pyramid(0, 0) 0.0 >>> vol_pyramid(-1, 1) Traceback (most recent call last): ... ValueError: vol_pyramid() only accepts non-negative values >>> vol_pyramid(1, -1) Traceback (most recent call last): ... ValueError: vol_pyramid() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_pyramid() only accepts non-negative values") return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: """ Calculate the Volume of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere :return (4/3) * pi * r^3 >>> vol_sphere(5) 523.5987755982989 >>> vol_sphere(1) 4.1887902047863905 >>> vol_sphere(1.6) 17.15728467880506 >>> vol_sphere(0) 0.0 >>> vol_sphere(-1) Traceback (most recent call last): ... ValueError: vol_sphere() only accepts non-negative values """ if radius < 0: raise ValueError("vol_sphere() only accepts non-negative values") # Volume is 4/3 * pi * radius cubed return 4 / 3 * pi * pow(radius, 3) def vol_hemisphere(radius: float) -> float: """Calculate the volume of a hemisphere Wikipedia reference: https://en.wikipedia.org/wiki/Hemisphere Other references: https://www.cuemath.com/geometry/hemisphere :return 2/3 * pi * radius^3 >>> vol_hemisphere(1) 2.0943951023931953 >>> vol_hemisphere(7) 718.377520120866 >>> vol_hemisphere(1.6) 8.57864233940253 >>> vol_hemisphere(0) 0.0 >>> vol_hemisphere(-1) Traceback (most recent call last): ... ValueError: vol_hemisphere() only accepts non-negative values """ if radius < 0: raise ValueError("vol_hemisphere() only accepts non-negative values") # Volume is radius cubed * pi * 2/3 return pow(radius, 3) * pi * 2 / 3 def vol_circular_cylinder(radius: float, height: float) -> float: """Calculate the Volume of a Circular Cylinder. Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder :return pi * radius^2 * height >>> vol_circular_cylinder(1, 1) 3.141592653589793 >>> vol_circular_cylinder(4, 3) 150.79644737231007 >>> vol_circular_cylinder(1.6, 1.6) 12.867963509103795 >>> vol_circular_cylinder(0, 0) 0.0 >>> vol_circular_cylinder(-1, 1) Traceback (most recent call last): ... ValueError: vol_circular_cylinder() only accepts non-negative values >>> vol_circular_cylinder(1, -1) Traceback (most recent call last): ... ValueError: vol_circular_cylinder() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_circular_cylinder() only accepts non-negative values") # Volume is radius squared * height * pi return pow(radius, 2) * height * pi def vol_hollow_circular_cylinder( inner_radius: float, outer_radius: float, height: float ) -> float: """Calculate the Volume of a Hollow Circular Cylinder. >>> vol_hollow_circular_cylinder(1, 2, 3) 28.274333882308138 >>> vol_hollow_circular_cylinder(1.6, 2.6, 3.6) 47.50088092227767 >>> vol_hollow_circular_cylinder(-1, 2, 3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(1, -2, 3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(1, 2, -3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(2, 1, 3) Traceback (most recent call last): ... ValueError: outer_radius must be greater than inner_radius >>> vol_hollow_circular_cylinder(0, 0, 0) Traceback (most recent call last): ... ValueError: outer_radius must be greater than inner_radius """ # Volume - (outer_radius squared - inner_radius squared) * pi * height if inner_radius < 0 or outer_radius < 0 or height < 0: raise ValueError( "vol_hollow_circular_cylinder() only accepts non-negative values" ) if outer_radius <= inner_radius: raise ValueError("outer_radius must be greater than inner_radius") return pi * (pow(outer_radius, 2) - pow(inner_radius, 2)) * height def vol_conical_frustum(height: float, radius_1: float, radius_2: float) -> float: """Calculate the Volume of a Conical Frustum. Wikipedia reference: https://en.wikipedia.org/wiki/Frustum >>> vol_conical_frustum(45, 7, 28) 48490.482608158454 >>> vol_conical_frustum(1, 1, 2) 7.330382858376184 >>> vol_conical_frustum(1.6, 2.6, 3.6) 48.7240076620753 >>> vol_conical_frustum(0, 0, 0) 0.0 >>> vol_conical_frustum(-2, 2, 1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values >>> vol_conical_frustum(2, -2, 1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values >>> vol_conical_frustum(2, 2, -1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values """ # Volume is 1/3 * pi * height * # (radius_1 squared + radius_2 squared + radius_1 * radius_2) if radius_1 < 0 or radius_2 < 0 or height < 0: raise ValueError("vol_conical_frustum() only accepts non-negative values") return ( 1 / 3 * pi * height * (pow(radius_1, 2) + pow(radius_2, 2) + radius_1 * radius_2) ) def vol_torus(torus_radius: float, tube_radius: float) -> float: """Calculate the Volume of a Torus. Wikipedia reference: https://en.wikipedia.org/wiki/Torus :return 2pi^2 * torus_radius * tube_radius^2 >>> vol_torus(1, 1) 19.739208802178716 >>> vol_torus(4, 3) 710.6115168784338 >>> vol_torus(3, 4) 947.4820225045784 >>> vol_torus(1.6, 1.6) 80.85179925372404 >>> vol_torus(0, 0) 0.0 >>> vol_torus(-1, 1) Traceback (most recent call last): ... ValueError: vol_torus() only accepts non-negative values >>> vol_torus(1, -1) Traceback (most recent call last): ... ValueError: vol_torus() only accepts non-negative values """ if torus_radius < 0 or tube_radius < 0: raise ValueError("vol_torus() only accepts non-negative values") return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2) def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print(f"Cube: {vol_cube(2) = }") # = 8 print(f"Cuboid: {vol_cuboid(2, 2, 2) = }") # = 8 print(f"Cone: {vol_cone(2, 2) = }") # ~= 1.33 print(f"Right Circular Cone: {vol_right_circ_cone(2, 2) = }") # ~= 8.38 print(f"Prism: {vol_prism(2, 2) = }") # = 4 print(f"Pyramid: {vol_pyramid(2, 2) = }") # ~= 1.33 print(f"Sphere: {vol_sphere(2) = }") # ~= 33.5 print(f"Hemisphere: {vol_hemisphere(2) = }") # ~= 16.75 print(f"Circular Cylinder: {vol_circular_cylinder(2, 2) = }") # ~= 25.1 print(f"Torus: {vol_torus(2, 2) = }") # ~= 157.9 print(f"Conical Frustum: {vol_conical_frustum(2, 2, 4) = }") # ~= 58.6 print(f"Spherical cap: {vol_spherical_cap(1, 2) = }") # ~= 5.24 print(f"Spheres intersetion: {vol_spheres_intersect(2, 2, 1) = }") # ~= 21.21 print(f"Spheres union: {vol_spheres_union(2, 2, 1) = }") # ~= 45.81 print( f"Hollow Circular Cylinder: {vol_hollow_circular_cylinder(1, 2, 3) = }" ) # ~= 28.3 if __name__ == "__main__": main()
""" Find the volume of various shapes. * https://en.wikipedia.org/wiki/Volume * https://en.wikipedia.org/wiki/Spherical_cap """ from __future__ import annotations from math import pi, pow def vol_cube(side_length: int | float) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1.0 >>> vol_cube(3) 27.0 >>> vol_cube(0) 0.0 >>> vol_cube(1.6) 4.096000000000001 >>> vol_cube(-1) Traceback (most recent call last): ... ValueError: vol_cube() only accepts non-negative values """ if side_length < 0: raise ValueError("vol_cube() only accepts non-negative values") return pow(side_length, 3) def vol_spherical_cap(height: float, radius: float) -> float: """ Calculate the volume of the spherical cap. >>> vol_spherical_cap(1, 2) 5.235987755982988 >>> vol_spherical_cap(1.6, 2.6) 16.621119532592402 >>> vol_spherical_cap(0, 0) 0.0 >>> vol_spherical_cap(-1, 2) Traceback (most recent call last): ... ValueError: vol_spherical_cap() only accepts non-negative values >>> vol_spherical_cap(1, -2) Traceback (most recent call last): ... ValueError: vol_spherical_cap() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_spherical_cap() only accepts non-negative values") # Volume is 1/3 pi * height squared * (3 * radius - height) return 1 / 3 * pi * pow(height, 2) * (3 * radius - height) def vol_spheres_intersect( radius_1: float, radius_2: float, centers_distance: float ) -> float: """ Calculate the volume of the intersection of two spheres. The intersection is composed by two spherical caps and therefore its volume is the sum of the volumes of the spherical caps. First, it calculates the heights (h1, h2) of the spherical caps, then the two volumes and it returns the sum. The height formulas are h1 = (radius_1 - radius_2 + centers_distance) * (radius_1 + radius_2 - centers_distance) / (2 * centers_distance) h2 = (radius_2 - radius_1 + centers_distance) * (radius_2 + radius_1 - centers_distance) / (2 * centers_distance) if centers_distance is 0 then it returns the volume of the smallers sphere :return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1) >>> vol_spheres_intersect(2, 2, 1) 21.205750411731103 >>> vol_spheres_intersect(2.6, 2.6, 1.6) 40.71504079052372 >>> vol_spheres_intersect(0, 0, 0) 0.0 >>> vol_spheres_intersect(-2, 2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values >>> vol_spheres_intersect(2, -2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values >>> vol_spheres_intersect(2, 2, -1) Traceback (most recent call last): ... ValueError: vol_spheres_intersect() only accepts non-negative values """ if radius_1 < 0 or radius_2 < 0 or centers_distance < 0: raise ValueError("vol_spheres_intersect() only accepts non-negative values") if centers_distance == 0: return vol_sphere(min(radius_1, radius_2)) h1 = ( (radius_1 - radius_2 + centers_distance) * (radius_1 + radius_2 - centers_distance) / (2 * centers_distance) ) h2 = ( (radius_2 - radius_1 + centers_distance) * (radius_2 + radius_1 - centers_distance) / (2 * centers_distance) ) return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1) def vol_spheres_union( radius_1: float, radius_2: float, centers_distance: float ) -> float: """ Calculate the volume of the union of two spheres that possibly intersect. It is the sum of sphere A and sphere B minus their intersection. First, it calculates the volumes (v1, v2) of the spheres, then the volume of the intersection (i) and it returns the sum v1+v2-i. If centers_distance is 0 then it returns the volume of the larger sphere :return vol_sphere(radius_1) + vol_sphere(radius_2) - vol_spheres_intersect(radius_1, radius_2, centers_distance) >>> vol_spheres_union(2, 2, 1) 45.814892864851146 >>> vol_spheres_union(1.56, 2.2, 1.4) 48.77802773671288 >>> vol_spheres_union(0, 2, 1) Traceback (most recent call last): ... ValueError: vol_spheres_union() only accepts non-negative values, non-zero radius >>> vol_spheres_union('1.56', '2.2', '1.4') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'str' and 'int' >>> vol_spheres_union(1, None, 1) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'NoneType' and 'int' """ if radius_1 <= 0 or radius_2 <= 0 or centers_distance < 0: raise ValueError( "vol_spheres_union() only accepts non-negative values, non-zero radius" ) if centers_distance == 0: return vol_sphere(max(radius_1, radius_2)) return ( vol_sphere(radius_1) + vol_sphere(radius_2) - vol_spheres_intersect(radius_1, radius_2, centers_distance) ) def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return multiple of width, length and height >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 >>> vol_cuboid(1.6, 2.6, 3.6) 14.976 >>> vol_cuboid(0, 0, 0) 0.0 >>> vol_cuboid(-1, 2, 3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values >>> vol_cuboid(1, -2, 3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values >>> vol_cuboid(1, 2, -3) Traceback (most recent call last): ... ValueError: vol_cuboid() only accepts non-negative values """ if width < 0 or height < 0 or length < 0: raise ValueError("vol_cuboid() only accepts non-negative values") return float(width * height * length) def vol_cone(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * area_of_base * height >>> vol_cone(10, 3) 10.0 >>> vol_cone(1, 1) 0.3333333333333333 >>> vol_cone(1.6, 1.6) 0.8533333333333335 >>> vol_cone(0, 0) 0.0 >>> vol_cone(-1, 1) Traceback (most recent call last): ... ValueError: vol_cone() only accepts non-negative values >>> vol_cone(1, -1) Traceback (most recent call last): ... ValueError: vol_cone() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_cone() only accepts non-negative values") return area_of_base * height / 3.0 def vol_right_circ_cone(radius: float, height: float) -> float: """ Calculate the Volume of a Right Circular Cone. Wikipedia reference: https://en.wikipedia.org/wiki/Cone :return (1/3) * pi * radius^2 * height >>> vol_right_circ_cone(2, 3) 12.566370614359172 >>> vol_right_circ_cone(0, 0) 0.0 >>> vol_right_circ_cone(1.6, 1.6) 4.289321169701265 >>> vol_right_circ_cone(-1, 1) Traceback (most recent call last): ... ValueError: vol_right_circ_cone() only accepts non-negative values >>> vol_right_circ_cone(1, -1) Traceback (most recent call last): ... ValueError: vol_right_circ_cone() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_right_circ_cone() only accepts non-negative values") return pi * pow(radius, 2) * height / 3.0 def vol_prism(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Prism. Wikipedia reference: https://en.wikipedia.org/wiki/Prism_(geometry) :return V = Bh >>> vol_prism(10, 2) 20.0 >>> vol_prism(11, 1) 11.0 >>> vol_prism(1.6, 1.6) 2.5600000000000005 >>> vol_prism(0, 0) 0.0 >>> vol_prism(-1, 1) Traceback (most recent call last): ... ValueError: vol_prism() only accepts non-negative values >>> vol_prism(1, -1) Traceback (most recent call last): ... ValueError: vol_prism() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_prism() only accepts non-negative values") return float(area_of_base * height) def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 >>> vol_pyramid(1.6, 1.6) 0.8533333333333335 >>> vol_pyramid(0, 0) 0.0 >>> vol_pyramid(-1, 1) Traceback (most recent call last): ... ValueError: vol_pyramid() only accepts non-negative values >>> vol_pyramid(1, -1) Traceback (most recent call last): ... ValueError: vol_pyramid() only accepts non-negative values """ if height < 0 or area_of_base < 0: raise ValueError("vol_pyramid() only accepts non-negative values") return area_of_base * height / 3.0 def vol_sphere(radius: float) -> float: """ Calculate the Volume of a Sphere. Wikipedia reference: https://en.wikipedia.org/wiki/Sphere :return (4/3) * pi * r^3 >>> vol_sphere(5) 523.5987755982989 >>> vol_sphere(1) 4.1887902047863905 >>> vol_sphere(1.6) 17.15728467880506 >>> vol_sphere(0) 0.0 >>> vol_sphere(-1) Traceback (most recent call last): ... ValueError: vol_sphere() only accepts non-negative values """ if radius < 0: raise ValueError("vol_sphere() only accepts non-negative values") # Volume is 4/3 * pi * radius cubed return 4 / 3 * pi * pow(radius, 3) def vol_hemisphere(radius: float) -> float: """Calculate the volume of a hemisphere Wikipedia reference: https://en.wikipedia.org/wiki/Hemisphere Other references: https://www.cuemath.com/geometry/hemisphere :return 2/3 * pi * radius^3 >>> vol_hemisphere(1) 2.0943951023931953 >>> vol_hemisphere(7) 718.377520120866 >>> vol_hemisphere(1.6) 8.57864233940253 >>> vol_hemisphere(0) 0.0 >>> vol_hemisphere(-1) Traceback (most recent call last): ... ValueError: vol_hemisphere() only accepts non-negative values """ if radius < 0: raise ValueError("vol_hemisphere() only accepts non-negative values") # Volume is radius cubed * pi * 2/3 return pow(radius, 3) * pi * 2 / 3 def vol_circular_cylinder(radius: float, height: float) -> float: """Calculate the Volume of a Circular Cylinder. Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder :return pi * radius^2 * height >>> vol_circular_cylinder(1, 1) 3.141592653589793 >>> vol_circular_cylinder(4, 3) 150.79644737231007 >>> vol_circular_cylinder(1.6, 1.6) 12.867963509103795 >>> vol_circular_cylinder(0, 0) 0.0 >>> vol_circular_cylinder(-1, 1) Traceback (most recent call last): ... ValueError: vol_circular_cylinder() only accepts non-negative values >>> vol_circular_cylinder(1, -1) Traceback (most recent call last): ... ValueError: vol_circular_cylinder() only accepts non-negative values """ if height < 0 or radius < 0: raise ValueError("vol_circular_cylinder() only accepts non-negative values") # Volume is radius squared * height * pi return pow(radius, 2) * height * pi def vol_hollow_circular_cylinder( inner_radius: float, outer_radius: float, height: float ) -> float: """Calculate the Volume of a Hollow Circular Cylinder. >>> vol_hollow_circular_cylinder(1, 2, 3) 28.274333882308138 >>> vol_hollow_circular_cylinder(1.6, 2.6, 3.6) 47.50088092227767 >>> vol_hollow_circular_cylinder(-1, 2, 3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(1, -2, 3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(1, 2, -3) Traceback (most recent call last): ... ValueError: vol_hollow_circular_cylinder() only accepts non-negative values >>> vol_hollow_circular_cylinder(2, 1, 3) Traceback (most recent call last): ... ValueError: outer_radius must be greater than inner_radius >>> vol_hollow_circular_cylinder(0, 0, 0) Traceback (most recent call last): ... ValueError: outer_radius must be greater than inner_radius """ # Volume - (outer_radius squared - inner_radius squared) * pi * height if inner_radius < 0 or outer_radius < 0 or height < 0: raise ValueError( "vol_hollow_circular_cylinder() only accepts non-negative values" ) if outer_radius <= inner_radius: raise ValueError("outer_radius must be greater than inner_radius") return pi * (pow(outer_radius, 2) - pow(inner_radius, 2)) * height def vol_conical_frustum(height: float, radius_1: float, radius_2: float) -> float: """Calculate the Volume of a Conical Frustum. Wikipedia reference: https://en.wikipedia.org/wiki/Frustum >>> vol_conical_frustum(45, 7, 28) 48490.482608158454 >>> vol_conical_frustum(1, 1, 2) 7.330382858376184 >>> vol_conical_frustum(1.6, 2.6, 3.6) 48.7240076620753 >>> vol_conical_frustum(0, 0, 0) 0.0 >>> vol_conical_frustum(-2, 2, 1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values >>> vol_conical_frustum(2, -2, 1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values >>> vol_conical_frustum(2, 2, -1) Traceback (most recent call last): ... ValueError: vol_conical_frustum() only accepts non-negative values """ # Volume is 1/3 * pi * height * # (radius_1 squared + radius_2 squared + radius_1 * radius_2) if radius_1 < 0 or radius_2 < 0 or height < 0: raise ValueError("vol_conical_frustum() only accepts non-negative values") return ( 1 / 3 * pi * height * (pow(radius_1, 2) + pow(radius_2, 2) + radius_1 * radius_2) ) def vol_torus(torus_radius: float, tube_radius: float) -> float: """Calculate the Volume of a Torus. Wikipedia reference: https://en.wikipedia.org/wiki/Torus :return 2pi^2 * torus_radius * tube_radius^2 >>> vol_torus(1, 1) 19.739208802178716 >>> vol_torus(4, 3) 710.6115168784338 >>> vol_torus(3, 4) 947.4820225045784 >>> vol_torus(1.6, 1.6) 80.85179925372404 >>> vol_torus(0, 0) 0.0 >>> vol_torus(-1, 1) Traceback (most recent call last): ... ValueError: vol_torus() only accepts non-negative values >>> vol_torus(1, -1) Traceback (most recent call last): ... ValueError: vol_torus() only accepts non-negative values """ if torus_radius < 0 or tube_radius < 0: raise ValueError("vol_torus() only accepts non-negative values") return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2) def main(): """Print the Results of Various Volume Calculations.""" print("Volumes:") print(f"Cube: {vol_cube(2) = }") # = 8 print(f"Cuboid: {vol_cuboid(2, 2, 2) = }") # = 8 print(f"Cone: {vol_cone(2, 2) = }") # ~= 1.33 print(f"Right Circular Cone: {vol_right_circ_cone(2, 2) = }") # ~= 8.38 print(f"Prism: {vol_prism(2, 2) = }") # = 4 print(f"Pyramid: {vol_pyramid(2, 2) = }") # ~= 1.33 print(f"Sphere: {vol_sphere(2) = }") # ~= 33.5 print(f"Hemisphere: {vol_hemisphere(2) = }") # ~= 16.75 print(f"Circular Cylinder: {vol_circular_cylinder(2, 2) = }") # ~= 25.1 print(f"Torus: {vol_torus(2, 2) = }") # ~= 157.9 print(f"Conical Frustum: {vol_conical_frustum(2, 2, 4) = }") # ~= 58.6 print(f"Spherical cap: {vol_spherical_cap(1, 2) = }") # ~= 5.24 print(f"Spheres intersetion: {vol_spheres_intersect(2, 2, 1) = }") # ~= 21.21 print(f"Spheres union: {vol_spheres_union(2, 2, 1) = }") # ~= 45.81 print( f"Hollow Circular Cylinder: {vol_hollow_circular_cylinder(1, 2, 3) = }" ) # ~= 28.3 if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. """ try: nth = int(nth) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") primes: list[int] = [] num = 2 while len(primes) < nth: if is_prime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter nth must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter nth must be int or castable to int. """ try: nth = int(nth) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") primes: list[int] = [] num = 2 while len(primes) < nth: if is_prime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ i = 1 j = 2 total = 0 while j <= n: if j % 2 == 0: total += j i, j = j, i + j return total if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ i = 1 j = 2 total = 0 while j <= n: if j % 2 == 0: total += j i, j = j, i + j return total if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Program to calculate the amortization amount per month, given - Principal borrowed - Rate of interest per annum - Years to repay the loan Wikipedia Reference: https://en.wikipedia.org/wiki/Equated_monthly_installment """ def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: int ) -> float: """ Formula for amortization amount per month: A = p * r * (1 + r)^n / ((1 + r)^n - 1) where p is the principal, r is the rate of interest per month and n is the number of payments >>> equated_monthly_installments(25000, 0.12, 3) 830.3577453212793 >>> equated_monthly_installments(25000, 0.12, 10) 358.67737100646826 >>> equated_monthly_installments(0, 0.12, 3) Traceback (most recent call last): ... Exception: Principal borrowed must be > 0 >>> equated_monthly_installments(25000, -1, 3) Traceback (most recent call last): ... Exception: Rate of interest must be >= 0 >>> equated_monthly_installments(25000, 0.12, 0) Traceback (most recent call last): ... Exception: Years to repay must be an integer > 0 """ if principal <= 0: raise Exception("Principal borrowed must be > 0") if rate_per_annum < 0: raise Exception("Rate of interest must be >= 0") if years_to_repay <= 0 or not isinstance(years_to_repay, int): raise Exception("Years to repay must be an integer > 0") # Yearly rate is divided by 12 to get monthly rate rate_per_month = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly number_of_payments = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
""" Program to calculate the amortization amount per month, given - Principal borrowed - Rate of interest per annum - Years to repay the loan Wikipedia Reference: https://en.wikipedia.org/wiki/Equated_monthly_installment """ def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: int ) -> float: """ Formula for amortization amount per month: A = p * r * (1 + r)^n / ((1 + r)^n - 1) where p is the principal, r is the rate of interest per month and n is the number of payments >>> equated_monthly_installments(25000, 0.12, 3) 830.3577453212793 >>> equated_monthly_installments(25000, 0.12, 10) 358.67737100646826 >>> equated_monthly_installments(0, 0.12, 3) Traceback (most recent call last): ... Exception: Principal borrowed must be > 0 >>> equated_monthly_installments(25000, -1, 3) Traceback (most recent call last): ... Exception: Rate of interest must be >= 0 >>> equated_monthly_installments(25000, 0.12, 0) Traceback (most recent call last): ... Exception: Years to repay must be an integer > 0 """ if principal <= 0: raise Exception("Principal borrowed must be > 0") if rate_per_annum < 0: raise Exception("Rate of interest must be >= 0") if years_to_repay <= 0 or not isinstance(years_to_repay, int): raise Exception("Years to repay must be an integer > 0") # Yearly rate is divided by 12 to get monthly rate rate_per_month = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly number_of_payments = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,178
Replace bandit, flake8, isort, and pyupgrade with ruff
### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2023-03-14T00:17:59Z"
"2023-03-15T12:58:26Z"
adc3ccdabede375df5cff62c3c8f06d8a191a803
c96241b5a5052af466894ef90c7a7c749ba872eb
Replace bandit, flake8, isort, and pyupgrade with ruff. ### Describe your change: [Ruff](https://beta.ruff.rs/) supports [over 500 lint rules](https://beta.ruff.rs/docs/rules) including bandit, isort, pylint, pyupgrade, and flake8 plus its plugins, and is written in Rust for speed. The `ruff` Action uses minimal steps to run in ~10 seconds, rapidly providing intuitive GitHub Annotations to contributors. ![image](https://user-images.githubusercontent.com/3709715/223758136-afc386d2-70aa-4eff-953a-2c2d82ceea23.png) * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Improve testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: """ Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param x_coordinate: x-coordinate of the pixel :param y_coordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. """ try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: """ It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param x_coordinate: x coordinate of the pixel :param y_coordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. """ center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] # skip get_neighbors_pixel if center is null if center is None: return 0 # Starting from the top right, assigning value to pixels clockwise binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] # Converting the binary value to decimal. return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the # local binary pattern value for each pixel. for i in range(0, image.shape[0]): for j in range(0, image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: """ Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param x_coordinate: x-coordinate of the pixel :param y_coordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. """ try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: """ It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param x_coordinate: x coordinate of the pixel :param y_coordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. """ center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] # skip get_neighbors_pixel if center is null if center is None: return 0 # Starting from the top right, assigning value to pixels clockwise binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] # Converting the binary value to decimal. return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the # local binary pattern value for each pixel. for i in range(0, image.shape[0]): for j in range(0, image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
-1