[
  {
    "path": ".github/workflows/check.yml",
    "content": "name: check\n\non: [push, pull_request]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    strategy:\n      max-parallel: 4\n      matrix:\n        python-version: [\"3.10\", \"3.12\"]\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n      - name: Set up Python ${{ matrix.python-version }}\n        uses: actions/setup-python@v5\n        with:\n          python-version: ${{ matrix.python-version }}\n      - name: Install\n        run: |\n          pip install --upgrade -e .[dev]\n      - name: Test\n        run: |\n          pytest --cov-report term-missing --cov itu.algs4\n      - name: Lint\n        run: |\n          flake8 examples tests itu\n          isort -c --diff examples tests itu\n      - name: Typecheck\n        run: |\n          mypy\n        continue-on-error: true\n      - name: Documentation\n        run: |\n          pip install sphinx\n          cd docs\n          mkdir _target && mkdir _static\n          sphinx-build . _target/\n"
  },
  {
    "path": ".github/workflows/python_publish.yml",
    "content": "name: Upload Python Package to PyPi\n\non:\n  push:\n    tags:\n      - \"v*\" # Push events matching v*, i.e. v1.0, v20.15.10\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - name: Set up Python\n        uses: actions/setup-python@v5\n        with:\n          python-version: \"3.10\"\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip\n          pip install setuptools wheel twine\n      - name: Build and publish\n        env:\n          TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}\n          TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}\n        run: |\n          python setup.py sdist bdist_wheel\n          twine upload dist/*\n"
  },
  {
    "path": ".gitignore",
    "content": "*.pyc\n.vs/\nalgs4-data/\n.mypy_cache\n.pytest_cache\n.ruff_cache\nitu.algs4.egg-info\n__pycache__"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Development\n\n## Testing\n\nBefore you can run tests, you should clone the repository, and install the\npackage in \"editable\" mode, including its development dependencies:\n```bash\npip install --upgrade -e '.[dev]'\n```\nRun all tests as follows:\n```bash\npytest\n```\nTo additionally display code coverage statistics, use this:\n```bash\npytest --cov\n```\nTo run individual tests, you can also do this:\n```\npython3 -m unittest tests/test_bst.py\npytest tests/test_stack.py\n```\n\n## Linter   \n\nRun `flake8` to lint all code. Run `black .` to automatically fix some linting error.\nMoreover, run\n```\nisort -y\n```\nto sort import statements.\nWe enforce linting on [examples/](examples), [tests/](tests), and [itu/](itu).\n\n## Types\n\nWeak type checking is currently enforced only on [examples/](examples) and [tests/](tests). To run the type checker, try:\n```\nmypy\n```\nIdeally, we want every module to strictly type check. For example, the binary search trees strictly type check:\n```\nmypy --strict itu/algs4/searching/bst.py itu/algs4/searching/red_black_bst.py itu/algs4/fundamentals/queue.py\n```\n\n\n## Examples\n\nClient code should be migrated to [examples/](examples).\n\n## Uploading to PyPi\n\nCreate package and upload it:\n```bash\npython3 setup.py sdist bdist_wheel\npython3 -m twine upload dist/*\n```\n\n## Useful Resources\n\n- the book https://algs4.cs.princeton.edu/home/\n- a python version of a similar book https://introcs.cs.princeton.edu/python/home/\n- all java code -- good list, includes what needs to be done https://algs4.cs.princeton.edu/code/ https://github.com/kevin-wayne/algs4\n\n## Coding style \n\nhttps://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions\n\n- we have subdirectories for the code, one for each chapter\n\n- if java relies on having different implementations depending on the type:\nUse somehting like\n```\nclass DirectedDFS:\n\tdef __init__(self, G, *s):\n```\nlike in `graphs/directed_dfs.py`\n\nOtherwise we use static factory methods where the name indicates the expected type.\nIf appropriate we use `isinstance()` and its variants, for example to distinguish undirected and directed graphs. \n\n- things like 'node' are inside classes, no leading underscore\n\n- file names, variables, methods are file_name (and not CamelCase, adjustting from algs4), only classes are CamelCase (PascalCase)\n\n- there is one file per version of an algorithm / data structure (like in algs4), the name, and importantly the docstring, reflects which version it is\n\n- java main becomes `__main__` stuff; follow what is there; adjust the initial comment\n\n- don't replicate imports unless \n\n- lower case letter with underscore\n  - like in the book\n  - private variables become _variable_name\n\n- if java has `toString()`, then we have `__repr__()`\n\n- keep the comments from the java code \n\n- if in doubt, we go with the book, not the code on the book web site (keep it simple)\n\n- docstring without formatting\n\n## ideas\n- should we include generators (additionally to iterators) everywhere?\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Algs4 library for Python 3\n\n`itu.algs4` is a Python 3 port of the Java code in [Algorithms, 4th Edition](https://algs4.cs.princeton.edu/home/).\n\n[![Build Status](https://github.com/itu-algorithms/itu.algs4/workflows/check/badge.svg)](https://github.com/itu-algorithms/itu.algs4/actions)\n[![Documentation Status](https://readthedocs.org/projects/itualgs4/badge/?version=latest)](https://itualgs4.readthedocs.io/en/latest/?badge=latest)\n\n## Target audience\n\n`itu.algs4` is intended for instructors and students who wish to follow the textbook [Algorithms, 4th Edition](https://algs4.cs.princeton.edu/home/) by Sedgewick and Wayne.\nIt was first created in 2018 by teaching assistants and instructors at [ITU Copenhagen](https://algorithms.itu.dk), where the introductory course on Algorithms and Data Structures is taught bilingually in Java and Python 3.\n\n## Installation\n\nThis library requires a functioning Python 3 environment; for example, the one provided by [Miniconda](https://www.anaconda.com/docs/getting-started/miniconda/main) or [Anaconda](https://www.anaconda.com/docs/getting-started/anaconda/main).\n\nSome optional visual and auditory features depend on the [numpy](http://numpy.org) and [pygame](https://pygame.org) packages. These features are not used in the ITU course, and you shouldn't spend extra time on installing those packages unless you already have them or want to play around with the those parts on your own.\n\n### With pip\n\nIf you have previously installed this package under its old name, we recommend you remove it with\n\n```bash\npip uninstall algs4 algs4_python\n```\n\nThen you can install `itu.algs4` simply with\n\n```bash\npip install itu.algs4\n```\n\nIf you have already installed `itu.algs4` and want to upgrade to a new version, run:\n\n```bash\npip install itu.algs4 --upgrade\n```\n\nTo test that you have installed the library correctly, run this command:\n\n```bash\npython -c 'from itu.algs4.stdlib import stdio; stdio.write(\"Hello World!\")'\n```\n\nIt should greet you. If an error message appears instead, the library is not installed correctly.\n\n### Alternative: With pip and git\n\nIf git is available, the following command will install the library in your Python environment:\n\n```bash\npip install git+https://github.com/itu-algorithms/itu.algs4\n```\n\n### Alternative: With pip and zip\n\nTo install this library without git:\n\n1. Download and unzip the repository.\n2. Open a command prompt or terminal and navigate to the downloaded folder. There should be the file `setup.py`.\n3. Use the command `pip3 install .` to install the package (this will also work for updating the package, when a newer version is available). If your Python installation is system-wide, use `sudo pip3 install .`\n\n### Alternative: Step-by-step guide for Windows\n\nTo install the Python package `itu.algs4`:\n\n- Download the repository by pressing the green \"Clone or download\" button, and pressing \"Download ZIP\".\n- Extract the content of the zip to your Desktop (you can delete the folder after installing the package).\n- Open the \"Command Prompt\" by pressing \"Windows + R\", type \"cmd\" in the window that appears, and press \"OK\".\n- If you saved the folder on the Desktop you should be able to navigate to the folder by typing \"cd Desktop\\itu.algs4-master\".\n\n```\nC:\\Users\\user>cd Desktop\\itu.algs4-master\n```\n\n- When in the correct folder, type `pip install .` to install the package.\n\n```\nC:\\Users\\user\\Desktop\\itu.algs4-master>pip install .\n```\n\n- After this, the package should be installed correctly and you can delete the folder from your Desktop.\n\n## Package structure\n\nThe Python package `itu.algs4` has a hierarchical structure with seven sub-packages:\n\n- [itu.algs4.fundamentals](itu/algs4/fundamentals)\n- [itu.algs4.sorting](itu/algs4/sorting)\n- [itu.algs4.searching](itu/algs4/searching)\n- [itu.algs4.graphs](itu/algs4/graphs)\n- [itu.algs4.strings](itu/algs4/strings)\n- [itu.algs4.stdlib](itu/algs4/stdlib)\n- [itu.algs4.errors](itu/algs4/errors)\n\nWhile deep nesting of packages is normally [discouraged](https://peps.python.org/pep-0423/#avoid-deep-nesting) in Python, an important design goal of `itu.algs4` was to mirror the structure of the original Java code.\nThe first five packages correspond to the first five chapters of [Algorithms, 4th Edition](https://algs4.cs.princeton.edu/home/). The `stdlib` package is based on the one from the related book [Introduction to Programming in Python](https://introcs.cs.princeton.edu/python/). The package `errors` contains some exception classes.\n\nAll filenames and package names have been written in lower_case style with underscores instead of the CamelCase style of the Java version. For example `EdgeWeightedDigraph.java` has been renamed to `edge_weighted_digraph.py`. Class names still use CamelCase though, which is consistent with naming conventions in Python.\n\n## Examples\n\nThe directory [examples/](examples) contains examples, some of which are\ndescribed here.\n\n### Hello World\n\nA simple program, stored as a file [hello_world.py](examples/hello_world.py), looks like this:\n\n```python\nfrom itu.algs4.stdlib import stdio\n\nstdio.write(\"Hello World!\\n\")\n```\n\nIt can be run with the command `python hello_world.py`.\n\n### Sort numbers\n\nA slightly more interesting example is\n[sort-numbers.py](examples/sort-numbers.py):\n\n```python\nfrom itu.algs4.sorting import merge\nfrom itu.algs4.stdlib import stdio\n\n\"\"\"\nReads a list of integers from standard input.\nThen prints it in sorted order.\n\"\"\"\nL = stdio.readAllInts()\n\nmerge.sort(L)\n\nif len(L) > 0:\n    stdio.write(L[0])\nfor i in range(1, len(L)):\n    stdio.write(\" \")\n    stdio.write(L[i])\nstdio.writeln()\n```\n\nThis code uses the convenient function `stdio.readAllInts()` to read the\nintegers (separated by whitespaces) from the standard input and put them in the\narray `L`. It then sorts the elements of the array. Finally, it outputs the\nsorted list -- the code to do so is somewhat less elegant to get the whitespace\nexactly right. (Of course, advanced Python users know more concise ways to\nproduce the same output: `print(\" \".join(map(str, L)))`)\n\n### Import classes\n\nYou can import classes, such as the class EdgeWeightedDigraph, with\n\n```python\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\n```\n\n## Documentation\n\nThe documentation can be found [here](https://itualgs4.readthedocs.io/en/latest/).\n\nYou can use Python's built-in `help` function on any package, sub-package, public class, or function to get a description of what it contains or does. This documentation should also show up in your IDE of choice.\nFor example `help(itu.algs4)` yields the following:\n\n```\nHelp on package itu.algs4 in itu:\n\nNAME\n    itu.algs4\n\nPACKAGE CONTENTS\n    errors (package)\n    fundamentals (package)\n    graphs (package)\n    searching (package)\n    sorting (package)\n    stdlib (package)\n    strings (package)\n\nFILE\n    (built-in)\n```\n\n## Development\n\n`itu.algs4` has known bugs and has not been tested systematically. We are open to pull requests, and in particular, we appreciate the contribution of high-quality test cases, bug-fixes, and coding style improvements. For more information, see the [CONTRIBUTING.md](CONTRIBUTING.md) file.\n\n## Contributors\n\n- Andreas Holck Høeg-Petersen\n- Anton Mølbjerg Eskildsen\n- Frederik Haagensen\n- Holger Dell\n- Martino Secchi\n- Morten Keller Grøftehauge\n- Morten Tychsen Clausen\n- Nina Mesing Stausholm Nielsen\n- Otto Stadel Clausen\n- Riko Jacob\n- Thore Husfeldt\n- Viktor Shamal Andersen\n\n## License\n\nThis project is licensed under the GPLv3 License - see the [LICENSE](LICENSE) file for details\n\n## Links to other projects\n\n- [algs4](https://github.com/kevin-wayne/algs4/) is the original Java implementation by Sedgewick and Wayne.\n- The textbook [Introduction to Programming in Python](https://introcs.cs.princeton.edu/python/) by Sedgewick, Wayne, and Dondero has a somewhat different approach from [Algorithms, 4th Edition](https://algs4.cs.princeton.edu/home/), and is therefore not suitable for a bilingual course. Nevertheless, our code in [itu/algs4/stdlib/](itu/algs4/stdlib/) is largely based on the [source code](https://introcs.cs.princeton.edu/python/code/) associated with that book.\n- [pyalgs](https://github.com/chen0040/pyalgs) is a Python port of `algs4` that uses a more idiomatic Python coding style. In contrast, our port tries to stay as close to the original Java library and the course book’s Java implementations as possible, so that it can be used with less friction in a bilingual course.\n- [Scala-Algorithms](https://github.com/garyaiki/Scala-Algorithms) is a Scala port of `algs4`.\n- [Algs4Net](https://github.com/nguyenqthai/Algs4Net) is a .NET port of `algs4`.\n"
  },
  {
    "path": "create_html_doc.sh",
    "content": "DIR=~/WorkSpace/bads-code/AlgorithmsInPython/algs4/\nDEST=/home/rikj/WorkSpace/riko/html_templ_tum/itu_dest/AlgorithmsInPython\n\nDIR=algs4\nDEST=DOC\nmkdir DOC\n\nFILES=`cd $DIR; find . -type d -or -name \\*.py`\n\ncd $DEST\n\nfor f in $FILES\ndo\n    p=${f#./}\n    b=${p%.py}\n    if [ ! $b == ${b%datafiles} ]\n    then\n        continue\n    fi\n    if [ ! $b == ${b#test} ]\n    then\n        continue\n    fi\n    arg=algs4.`echo ${b} | tr / .`\n    res=`pydoc3 -w $arg | grep -v '^wrote'`\n    if [ ! -z \"$res\" ]\n    then\n        echo $arg $res\n    fi\n    \n    #    pydoc3 -w algs4.`echo ${b} | tr / .` > /dev/null\ndone\n\ncd ../..\n#rsync -va  itu_dest/ ssh.itu.dk:public_html/\n"
  },
  {
    "path": "docs/conf.py",
    "content": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(\"../\"))\n\n\n# -- Project information -----------------------------------------------------\n\nproject = \"itu.algs4\"\ncopyright = \"2020, ITU Algorithms Group\"\nauthor = \"ITU Algorithms Group\"\nmaster_doc = \"index\"\n\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\"sphinx.ext.autodoc\"]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = \"alabaster\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n"
  },
  {
    "path": "docs/index.rst",
    "content": ".. itu.algs4 documentation master file, created by\n   sphinx-quickstart on Mon Jul  6 13:50:43 2020.\n   You can adapt this file completely to your liking, but it should at least\n   contain the root `toctree` directive.\n\nWelcome to itu.algs4's documentation!\n=====================================\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Contents:\n\n   source/itu.algs4.fundamentals.rst\n   source/itu.algs4.graphs.rst\n   source/itu.algs4.searching.rst\n   source/itu.algs4.sorting.rst\n   source/itu.algs4.stdlib.rst\n   source/itu.algs4.strings.rst\n\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n"
  },
  {
    "path": "docs/requirements.txt",
    "content": "pygame\ntyping_extensions\ncolor\n"
  },
  {
    "path": "docs/source/itu.algs4.errors.rst",
    "content": "itu.algs4.errors package\n========================\n\nSubmodules\n----------\n\nitu.algs4.errors.errors module\n------------------------------\n\n.. automodule:: itu.algs4.errors.errors\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4.errors\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/itu.algs4.fundamentals.rst",
    "content": "itu.algs4.fundamentals package\n==============================\n\nSubmodules\n----------\n\nitu.algs4.fundamentals.bag module\n---------------------------------\n\n.. automodule:: itu.algs4.fundamentals.bag\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.binary\\_search module\n--------------------------------------------\n\n.. automodule:: itu.algs4.fundamentals.binary_search\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.evaluate module\n--------------------------------------\n\n.. automodule:: itu.algs4.fundamentals.evaluate\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.java\\_helper module\n------------------------------------------\n\n.. automodule:: itu.algs4.fundamentals.java_helper\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.queue module\n-----------------------------------\n\n.. automodule:: itu.algs4.fundamentals.queue\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.stack module\n-----------------------------------\n\n.. automodule:: itu.algs4.fundamentals.stack\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.three\\_sum module\n----------------------------------------\n\n.. automodule:: itu.algs4.fundamentals.three_sum\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.three\\_sum\\_fast module\n----------------------------------------------\n\n.. automodule:: itu.algs4.fundamentals.three_sum_fast\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.two\\_sum\\_fast module\n--------------------------------------------\n\n.. automodule:: itu.algs4.fundamentals.two_sum_fast\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.fundamentals.uf module\n--------------------------------\n\n.. automodule:: itu.algs4.fundamentals.uf\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4.fundamentals\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/itu.algs4.graphs.rst",
    "content": "itu.algs4.graphs package\n========================\n\nSubmodules\n----------\n\nitu.algs4.graphs.Arbitrage module\n---------------------------------\n\n.. automodule:: itu.algs4.graphs.Arbitrage\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.CPM module\n---------------------------\n\n.. automodule:: itu.algs4.graphs.CPM\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.acyclic\\_lp module\n-----------------------------------\n\n.. automodule:: itu.algs4.graphs.acyclic_lp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.acyclic\\_sp module\n-----------------------------------\n\n.. automodule:: itu.algs4.graphs.acyclic_sp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.bellman\\_ford\\_sp module\n-----------------------------------------\n\n.. automodule:: itu.algs4.graphs.bellman_ford_sp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.bipartite module\n---------------------------------\n\n.. automodule:: itu.algs4.graphs.bipartite\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.breadth\\_first\\_paths module\n---------------------------------------------\n\n.. automodule:: itu.algs4.graphs.breadth_first_paths\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.cc module\n--------------------------\n\n.. automodule:: itu.algs4.graphs.cc\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.cycle module\n-----------------------------\n\n.. automodule:: itu.algs4.graphs.cycle\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.degrees\\_of\\_separation module\n-----------------------------------------------\n\n.. automodule:: itu.algs4.graphs.degrees_of_separation\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.depth\\_first\\_order module\n-------------------------------------------\n\n.. automodule:: itu.algs4.graphs.depth_first_order\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.depth\\_first\\_paths module\n-------------------------------------------\n\n.. automodule:: itu.algs4.graphs.depth_first_paths\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.depth\\_first\\_search module\n--------------------------------------------\n\n.. automodule:: itu.algs4.graphs.depth_first_search\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.digraph module\n-------------------------------\n\n.. automodule:: itu.algs4.graphs.digraph\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.dijkstra\\_all\\_pairs\\_sp module\n------------------------------------------------\n\n.. automodule:: itu.algs4.graphs.dijkstra_all_pairs_sp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.dijkstra\\_sp module\n------------------------------------\n\n.. automodule:: itu.algs4.graphs.dijkstra_sp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.dijkstra\\_undirected\\_sp module\n------------------------------------------------\n\n.. automodule:: itu.algs4.graphs.dijkstra_undirected_sp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.directed\\_cycle module\n---------------------------------------\n\n.. automodule:: itu.algs4.graphs.directed_cycle\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.directed\\_dfs module\n-------------------------------------\n\n.. automodule:: itu.algs4.graphs.directed_dfs\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.directed\\_edge module\n--------------------------------------\n\n.. automodule:: itu.algs4.graphs.directed_edge\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.edge module\n----------------------------\n\n.. automodule:: itu.algs4.graphs.edge\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.edge\\_weighted\\_digraph module\n-----------------------------------------------\n\n.. automodule:: itu.algs4.graphs.edge_weighted_digraph\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.edge\\_weighted\\_directed\\_cycle module\n-------------------------------------------------------\n\n.. automodule:: itu.algs4.graphs.edge_weighted_directed_cycle\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.edge\\_weighted\\_directed\\_cycle\\_anton module\n--------------------------------------------------------------\n\n.. automodule:: itu.algs4.graphs.edge_weighted_directed_cycle_anton\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.edge\\_weighted\\_graph module\n---------------------------------------------\n\n.. automodule:: itu.algs4.graphs.edge_weighted_graph\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.graph module\n-----------------------------\n\n.. automodule:: itu.algs4.graphs.graph\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.kosaraju\\_sharir\\_scc module\n---------------------------------------------\n\n.. automodule:: itu.algs4.graphs.kosaraju_sharir_scc\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.kruskal\\_mst module\n------------------------------------\n\n.. automodule:: itu.algs4.graphs.kruskal_mst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.lazy\\_prim\\_mst module\n---------------------------------------\n\n.. automodule:: itu.algs4.graphs.lazy_prim_mst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.prim\\_mst module\n---------------------------------\n\n.. automodule:: itu.algs4.graphs.prim_mst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.symbol\\_digraph module\n---------------------------------------\n\n.. automodule:: itu.algs4.graphs.symbol_digraph\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.symbol\\_graph module\n-------------------------------------\n\n.. automodule:: itu.algs4.graphs.symbol_graph\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.topological module\n-----------------------------------\n\n.. automodule:: itu.algs4.graphs.topological\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.graphs.transitive\\_closure module\n-------------------------------------------\n\n.. automodule:: itu.algs4.graphs.transitive_closure\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4.graphs\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/itu.algs4.rst",
    "content": "itu.algs4 package\n=================\n\nSubpackages\n-----------\n\n.. toctree::\n   :maxdepth: 4\n\n   itu.algs4.errors\n   itu.algs4.fundamentals\n   itu.algs4.graphs\n   itu.algs4.searching\n   itu.algs4.sorting\n   itu.algs4.stdlib\n   itu.algs4.strings\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/itu.algs4.searching.rst",
    "content": "itu.algs4.searching package\n===========================\n\nSubmodules\n----------\n\nitu.algs4.searching.binary\\_search\\_st module\n---------------------------------------------\n\n.. automodule:: itu.algs4.searching.binary_search_st\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.bst module\n------------------------------\n\n.. automodule:: itu.algs4.searching.bst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.file\\_index module\n--------------------------------------\n\n.. automodule:: itu.algs4.searching.file_index\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.frequency\\_counter module\n---------------------------------------------\n\n.. automodule:: itu.algs4.searching.frequency_counter\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.linear\\_probing\\_hst module\n-----------------------------------------------\n\n.. automodule:: itu.algs4.searching.linear_probing_hst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.lookup\\_csv module\n--------------------------------------\n\n.. automodule:: itu.algs4.searching.lookup_csv\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.lookup\\_index module\n----------------------------------------\n\n.. automodule:: itu.algs4.searching.lookup_index\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.red\\_black\\_bst module\n------------------------------------------\n\n.. automodule:: itu.algs4.searching.red_black_bst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.seperate\\_chaining\\_hst module\n--------------------------------------------------\n\n.. automodule:: itu.algs4.searching.seperate_chaining_hst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.sequential\\_search\\_st module\n-------------------------------------------------\n\n.. automodule:: itu.algs4.searching.sequential_search_st\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.set module\n------------------------------\n\n.. automodule:: itu.algs4.searching.set\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.sparse\\_vector module\n-----------------------------------------\n\n.. automodule:: itu.algs4.searching.sparse_vector\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.searching.st module\n-----------------------------\n\n.. automodule:: itu.algs4.searching.st\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4.searching\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/itu.algs4.sorting.rst",
    "content": "itu.algs4.sorting package\n=========================\n\nSubmodules\n----------\n\nitu.algs4.sorting.heap module\n-----------------------------\n\n.. automodule:: itu.algs4.sorting.heap\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.index\\_min\\_pq module\n---------------------------------------\n\n.. automodule:: itu.algs4.sorting.index_min_pq\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.insertion\\_sort module\n----------------------------------------\n\n.. automodule:: itu.algs4.sorting.insertion_sort\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.max\\_pq module\n--------------------------------\n\n.. automodule:: itu.algs4.sorting.max_pq\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.merge module\n------------------------------\n\n.. automodule:: itu.algs4.sorting.merge\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.merge\\_bu module\n----------------------------------\n\n.. automodule:: itu.algs4.sorting.merge_bu\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.min\\_pq module\n--------------------------------\n\n.. automodule:: itu.algs4.sorting.min_pq\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.quick3way module\n----------------------------------\n\n.. automodule:: itu.algs4.sorting.quick3way\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.quicksort module\n----------------------------------\n\n.. automodule:: itu.algs4.sorting.quicksort\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.selection module\n----------------------------------\n\n.. automodule:: itu.algs4.sorting.selection\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.sorting.shellsort module\n----------------------------------\n\n.. automodule:: itu.algs4.sorting.shellsort\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4.sorting\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/itu.algs4.stdlib.rst",
    "content": "itu.algs4.stdlib package\n========================\n\nSubmodules\n----------\n\nitu.algs4.stdlib.binary\\_out module\n-----------------------------------\n\n.. automodule:: itu.algs4.stdlib.binary_out\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.binary\\_stdin module\n-------------------------------------\n\n.. automodule:: itu.algs4.stdlib.binary_stdin\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.binary\\_stdout module\n--------------------------------------\n\n.. automodule:: itu.algs4.stdlib.binary_stdout\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.color module\n-----------------------------\n\n.. automodule:: itu.algs4.stdlib.color\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.instream module\n--------------------------------\n\n.. automodule:: itu.algs4.stdlib.instream\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.outstream module\n---------------------------------\n\n.. automodule:: itu.algs4.stdlib.outstream\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.picture module\n-------------------------------\n\n.. automodule:: itu.algs4.stdlib.picture\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.stdarray module\n--------------------------------\n\n.. automodule:: itu.algs4.stdlib.stdarray\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.stdaudio module\n--------------------------------\n\n.. automodule:: itu.algs4.stdlib.stdaudio\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.stddraw module\n-------------------------------\n\n.. automodule:: itu.algs4.stdlib.stddraw\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.stdio module\n-----------------------------\n\n.. automodule:: itu.algs4.stdlib.stdio\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.stdrandom module\n---------------------------------\n\n.. automodule:: itu.algs4.stdlib.stdrandom\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.stdlib.stdstats module\n--------------------------------\n\n.. automodule:: itu.algs4.stdlib.stdstats\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4.stdlib\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/itu.algs4.strings.rst",
    "content": "itu.algs4.strings package\n=========================\n\nSubmodules\n----------\n\nitu.algs4.strings.boyer\\_moore module\n-------------------------------------\n\n.. automodule:: itu.algs4.strings.boyer_moore\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.huffman\\_compression module\n---------------------------------------------\n\n.. automodule:: itu.algs4.strings.huffman_compression\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.kmp module\n----------------------------\n\n.. automodule:: itu.algs4.strings.kmp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.lsd module\n----------------------------\n\n.. automodule:: itu.algs4.strings.lsd\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.lzw module\n----------------------------\n\n.. automodule:: itu.algs4.strings.lzw\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.msd module\n----------------------------\n\n.. automodule:: itu.algs4.strings.msd\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.nfa module\n----------------------------\n\n.. automodule:: itu.algs4.strings.nfa\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.quick3string module\n-------------------------------------\n\n.. automodule:: itu.algs4.strings.quick3string\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.rabin\\_karp module\n------------------------------------\n\n.. automodule:: itu.algs4.strings.rabin_karp\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.trie\\_st module\n---------------------------------\n\n.. automodule:: itu.algs4.strings.trie_st\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\nitu.algs4.strings.tst module\n----------------------------\n\n.. automodule:: itu.algs4.strings.tst\n   :members:\n   :undoc-members:\n   :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: itu.algs4.strings\n   :members:\n   :undoc-members:\n   :show-inheritance:\n"
  },
  {
    "path": "examples/bst.py",
    "content": "#!/usr/bin/env python3\nimport sys\n\nfrom itu.algs4.searching.bst import BST\nfrom itu.algs4.stdlib import stdio\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    data = stdio.readAllStrings()\n    st: BST[str, int] = BST()\n    i = 0\n    for key in data:\n        st.put(key, i)\n        i += 1\n\n    print(\"LEVELORDER:\")\n    for key in st.level_order():\n        print(str(key) + \" \" + str(st.get(key)))\n\n    print()\n\n    print(\"KEYS:\")\n    for key in st.keys():\n        print(str(key) + \" \" + str(st.get(key)))\n"
  },
  {
    "path": "examples/hello_world.py",
    "content": "#!/usr/bin/env python3\nfrom itu.algs4.stdlib import stdio\n\nstdio.write(\"Hello World!\\n\")\n"
  },
  {
    "path": "examples/queue.py",
    "content": "#!/usr/bin/env python3\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.stdlib import stdio\n\n\"\"\"\nReads strings from an stdin and adds them to a queue.\nWhen reading a '-' it removes the least recently added item and prints it.\nPrints the amount of items left on the queue.\n\"\"\"\nqueue: Queue[str] = Queue()\nwhile not stdio.isEmpty():\n    input_item = stdio.readString()\n    if input_item != \"-\":\n        queue.enqueue(input_item)\n    elif not queue.is_empty():\n        print(queue.dequeue())\nprint(\"({} left on queue)\".format(queue.size()))\n"
  },
  {
    "path": "examples/sort-numbers.py",
    "content": "#!/usr/bin/env python3\nfrom itu.algs4.sorting import merge\nfrom itu.algs4.stdlib import stdio\n\n\"\"\"\nReads a list of integers from standard input.\nThen prints it in sorted order.\n\"\"\"\nL = stdio.readAllInts()\n\nmerge.sort(L)\n\nif len(L) > 0:\n    stdio.write(L[0])\nfor i in range(1, len(L)):\n    stdio.write(\" \")\n    stdio.write(L[i])\nstdio.writeln()\n"
  },
  {
    "path": "examples/stack.py",
    "content": "#!/usr/bin/env python3\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.stdlib import stdio\n\nif len(sys.argv) > 1:\n    try:\n        sys.stdin = open(sys.argv[1])\n    except IOError:\n        print(\"File not found, using standard input instead\")\n\nstack: Stack[str] = Stack()\nwhile not stdio.isEmpty():\n    item = stdio.readString()\n    if not item == \"-\":\n        stack.push(item)\n    elif not stack.is_empty():\n        stdio.write(stack.pop() + \" \")\n\nstdio.writef(\"(%i left on stack)\\n\", stack.size())\n"
  },
  {
    "path": "itu/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/errors/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/errors/errors.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass NoSuchElementException(Exception):\n    pass\n\n\nclass IllegalArgumentException(Exception):\n    pass\n\n\nclass UnsupportedOperationException(Exception):\n    pass\n"
  },
  {
    "path": "itu/algs4/fundamentals/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/fundamentals/bag.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\n#     See ResizingArrayBag for a version that uses a resizing array.\n\nfrom typing import Generic, Iterator, Optional, TypeVar\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n\nclass Bag(Generic[T]):\n    \"\"\"The Bag class represents a bag (or multiset) of generic items. It\n    supports insertion and iterating over the items in arbitrary order.\n\n    This implementation uses a singly linked list with a static nested class Node.\n    See LinkedBag for the version from the\n    textbook that uses a non-static nested class.\n\n    The add, is_empty, and size operations\n    take constant time. Iteration takes time proportional to the number of items.\n\n    \"\"\"\n\n    class Node(Generic[S]):\n        # helper linked list class\n        def __init__(self):\n            self.next: Optional[Bag.Node[T]] = None\n            self.item: Optional[S] = None\n\n    def __init__(self) -> None:\n        \"\"\"Initializes an empty bag.\"\"\"\n        self._first: Optional[Bag.Node[T]] = None  # beginning of bag\n        self._n = 0  # number of elements in bag\n\n    def is_empty(self) -> bool:\n        \"\"\"Returns true if this bag is empty.\n\n        :returns: true if this bag is empty\n                  false otherwise\n\n        \"\"\"\n        return self._first is None\n\n    def size(self) -> int:\n        \"\"\"Returns the number of items in this bag.\n\n        :returns: the number of items in this bag\n\n        \"\"\"\n        return self._n\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def add(self, item: T) -> None:\n        \"\"\"Adds the item to this bag.\n\n        :param item: the item to add to this bag\n\n        \"\"\"\n        oldfirst = self._first\n        self._first = Bag.Node()\n        self._first.item = item\n        self._first.next = oldfirst\n        self._n += 1\n\n    def __iter__(self) -> Iterator[T]:\n        \"\"\"Returns an iterator that iterates over the items in this bag in\n        arbitrary order.\n\n        :returns: an iterator that iterates over the items in this bag in arbitrary order\n\n        \"\"\"\n        current = self._first\n        while current is not None:\n            assert current.item is not None\n            yield current.item\n            current = current.next\n\n    def __repr__(self) -> str:\n        out = \"{\"\n        for elem in self:\n            out += \"{}, \".format(elem)\n        return out + \"}\"\n\n\n# start of the script itself\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.stdlib import stdio\n\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    bag: Bag[str] = Bag()\n    while not stdio.isEmpty():\n        item = stdio.readString()\n        bag.add(item)\n\n    stdio.writef(\"size of bag = %i\\n\", bag.size())\n\n    for s in bag:\n        stdio.writeln(s)\n"
  },
  {
    "path": "itu/algs4/fundamentals/binary_search.py",
    "content": "import sys\nfrom typing import List, TypeVar\n\nfrom itu.algs4.stdlib import stdio\n\nT = TypeVar(\"T\")\n\n# Created for BADS 2018\n# See README.md for details\n# This is python3\n\n\"\"\"\nThe binary_search module provides a method for binary\nsearching for an item in a sorted array.\nThe index_of operation takes logarithmic time in the worst case.\n\"\"\"\n\n\ndef index_of(a: List[T], key: T):\n    \"\"\"Returns the index of the specified key in the specified array.\n\n    :param a: the array of items, must be sorted in ascending order\n    :param key: the search key\n    :return: index of key in array if present -1 otherwise\n\n    \"\"\"\n    lo = 0\n    hi = len(a) - 1\n    while hi >= lo:\n        mid = lo + (hi - lo) // 2\n        if a[mid] < key:\n            lo = mid + 1\n        elif a[mid] > key:\n            hi = mid - 1\n        else:\n            return mid\n    return -1\n\n\ndef main():\n    \"\"\"Reads strings from first input file and sorts them Reads strings from\n    second input file and prints every string not in first input file.\"\"\"\n    if len(sys.argv) == 3:\n        sys.stdin = open(sys.argv[1])\n        arr = stdio.readAllStrings()\n        arr.sort()\n        sys.stdin = open(sys.argv[2])\n        while not stdio.isEmpty():\n            key = stdio.readString()\n            if index_of(arr, key) == -1:\n                print(key)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/fundamentals/evaluate.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport math\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.stdlib import stdio\n\n\ndef evaluate():\n    ops = Stack()\n    vals = Stack()\n\n    while not stdio.isEmpty():\n        # Read token, push if operator\n        s = stdio.readString()\n        if s == \"(\":\n            pass\n        elif s == \"+\":\n            ops.push(s)\n        elif s == \"-\":\n            ops.push(s)\n        elif s == \"*\":\n            ops.push(s)\n        elif s == \"/\":\n            ops.push(s)\n        elif s == \"sqrt\":\n            ops.push(s)\n        elif s == \")\":\n            # Pop, evaluate and push result if token is \")\"\n            op = ops.pop()\n            v = vals.pop()\n            if op == \"+\":\n                v = vals.pop() + v\n            elif op == \"-\":\n                v = vals.pop() - v\n            elif op == \"*\":\n                v = vals.pop() * v\n            elif op == \"/\":\n                v = vals.pop() / v\n            elif op == \"sqrt\":\n                v = math.sqrt(v)\n            vals.push(v)\n        else:\n            vals.push(float(s))\n    stdio.writeln(vals.pop())\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    evaluate()\n"
  },
  {
    "path": "itu/algs4/fundamentals/java_helper.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# this one is not inspired by algorithms from the book, but useful for running java and python in parallel\n# Python 3\n\n\ndef java_string_hash(key):\n    \"\"\"If key is a string, compute its java .hash() code.\n\n    Taken from http://garage.pimentech.net/libcommonPython_src_python_libcommon_javastringhashcode/\n\n    \"\"\"\n    h = 0\n    for c in key:\n        h = (31 * h + ord(c)) & 0xFFFFFFFF\n    return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000\n\n\ndef trailing_zeros(i):\n    zeros = 0\n    while i & 1 == 0 and zeros < 32:\n        zeros += 1\n        i = i >> 1\n    return zeros\n"
  },
  {
    "path": "itu/algs4/fundamentals/queue.py",
    "content": "from typing import Generic, Iterator, Optional, TypeVar\n\nfrom ..errors.errors import NoSuchElementException\n\n# Created for BADS 2018\n# See README.md for details\n# This is python3\n\n\nT = TypeVar(\"T\")\n\n\nclass Node(Generic[T]):\n    def __init__(self, item: T, next: Optional[\"Node[T]\"]) -> None:\n        \"\"\"Initializes a new node.\n\n        :param item: the item to be stored in the node\n        :param next: the next node in the queue\n\n        \"\"\"\n        self.item: T = item\n        self.next: Optional[Node[T]] = next\n\n\nclass Queue(Generic[T]):\n    \"\"\"The Queue class represents a first-in-first-out (FIFO) queue of generic\n    items.\n\n    It supports the usual enqueue and dequeue operations, along with\n    methods for peeking at the first item, testing if the queue is\n    empty, and iterating through the items in FIFO order This\n    implementation uses a singly linked list of linked-list nodes The\n    enqueue, dequeue, peek, size, and is_empty operations all take\n    constant time in the worst case\n\n    \"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Initializes an empty queue.\"\"\"\n        self._first: Optional[Node[T]] = None\n        self._last: Optional[Node[T]] = None\n        self._n: int = 0\n\n    def enqueue(self, item: T) -> None:\n        \"\"\"Adds the item to this queue.\n\n        :param item: the item to add\n\n        \"\"\"\n        old_last: Optional[Node[T]] = self._last\n        self._last = Node(item, None)\n        if self.is_empty():\n            self._first = self._last\n        else:\n            assert old_last is not None\n            old_last.next = self._last\n        self._n += 1\n\n    def dequeue(self) -> T:\n        \"\"\"\n        Removes and returns the item on this queue that was least recently added.\n        :return: the item on this queue that was least recently added.\n        :raises NoSuchElementException: if this queue is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"Queue underflow\")\n\n        assert self._first is not None\n        item = self._first.item\n        self._first = self._first.next\n        self._n -= 1\n        if self.is_empty():\n            self._last = None\n        return item\n\n    def is_empty(self) -> bool:\n        \"\"\"Returns true if this queue is empty.\n\n        :return: True if this queue is empty otherwise False\n        :rtype: bool\n\n        \"\"\"\n        return self._first is None\n\n    def size(self) -> int:\n        \"\"\"Returns the number of items in this queue.\n\n        :return: the number of items in this queue\n        :rtype: int\n\n        \"\"\"\n        return self._n\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def peek(self) -> T:\n        \"\"\"\n        Returns the item least recently added to this queue.\n        :return: the item least recently added to this queue\n        :raises NoSuchElementException: if this queue is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"Queue underflow\")\n\n        assert self._first is not None\n        return self._first.item\n\n    def __iter__(self) -> Iterator[T]:\n        \"\"\"Iterates over all the items in this queue in FIFO order.\"\"\"\n        curr = self._first\n        while curr is not None:\n            yield curr.item\n            curr = curr.next\n\n    def __repr__(self) -> str:\n        \"\"\"Returns a string representation of this queue.\n\n        :return: the sequence of items in FIFO order, separated by spaces\n\n        \"\"\"\n        s = []\n        for item in self:\n            s.append(\"{} \".format(item))\n        return \"\".join(s)\n"
  },
  {
    "path": "itu/algs4/fundamentals/stack.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom typing import Generic, Iterator, List, Optional, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass Node(Generic[T]):\n    # helper linked list class\n    def __init__(self):\n        self.item: T = None\n        self.next: Optional[Node] = None\n\n\nclass Stack(Generic[T]):\n    \"\"\"The Stack class represents a last-in-first-out (LIFO) stack of generic\n    items. It supports the usual push and pop operations, along with methods\n    for peeking at the top item, testing if the stack is empty, and iterating\n    through the items in LIFO order.\n\n    This implementation uses a singly linked list with a static nested\n    class for linked-list nodes. See LinkedStack for the version from\n    the textbook that uses a non-static nested class. See\n    ResizingArrayStack for a version that uses a resizing array. The\n    push, pop, peek, size, and is-empty operations all take constant\n    time in the worst case.\n\n    \"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Initializes an empty stack.\"\"\"\n        self._first: Optional[Node[T]] = None\n        self._n: int = 0\n\n    def is_empty(self) -> bool:\n        \"\"\"Returns true if this stack is empty.\n\n        :returns: true if this stack is empty false otherwise\n\n        \"\"\"\n        return self._n == 0\n\n    def size(self) -> int:\n        \"\"\"Returns the number of items in this stack.\n\n        :returns: the number of items in this stack\n\n        \"\"\"\n        return self._n\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def push(self, item: T) -> None:\n        \"\"\"Adds the item to this stack.\n\n        :param item: the item to add\n\n        \"\"\"\n        oldfirst = self._first\n        self._first = Node()\n        self._first.item = item\n        self._first.next = oldfirst\n        self._n += 1\n\n    def pop(self) -> T:\n        \"\"\"Removes and returns the item most recently added to this stack.\n\n        :returns: the item most recently added\n        :raises ValueError: if this stack is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise ValueError(\"Stack underflow\")\n        assert self._first is not None\n        item = self._first.item\n        assert item is not None\n        self._first = self._first.next\n        self._n -= 1\n        return item\n\n    def peek(self) -> T:\n        \"\"\"Returns (but does not remove) the item most recently added to this\n        stack.\n\n        :returns: the item most recently added to this stack\n        :raises ValueError: if this stack is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise ValueError(\"Stack underflow\")\n        assert self._first is not None\n        item = self._first.item\n        assert item is not None\n        return item\n\n    def __repr__(self) -> str:\n        \"\"\"Returns a string representation of this stack.\n\n        :returns: the sequence of items in this stack in LIFO order, separated by spaces\n\n        \"\"\"\n        s = []\n        for item in self:\n            s.append(item.__repr__())\n        return \" \".join(s)\n\n    def __iter__(self) -> Iterator[T]:\n        \"\"\"Returns an iterator to this stack that iterates through the items in\n        LIFO order.\n\n        :return: an iterator to this stack that iterates through the items in LIFO order\n\n        \"\"\"\n        current = self._first\n        while current is not None:\n            item = current.item\n            assert item is not None\n            yield item\n            current = current.next\n\n\nclass FixedCapacityStack(Generic[T]):\n    def __init__(self, capacity: int):\n        self.a: List[Optional[T]] = [None] * capacity\n        self.n: int = 0\n\n    def is_empty(self) -> bool:\n        return self.n == 0\n\n    def size(self) -> int:\n        return self.n\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def push(self, item: T):\n        self.a[self.n] = item\n        self.n += 1\n\n    def pop(self) -> T:\n        self.n -= 1\n        item = self.a[self.n]\n        assert item is not None\n        return item\n\n\nclass ResizingArrayStack(Generic[T]):\n    def __init__(self) -> None:\n        self.a: List[Optional[T]] = [None]\n        self.n: int = 0\n\n    def is_empty(self) -> bool:\n        return self.n == 0\n\n    def size(self) -> int:\n        return self.n\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def resize(self, capacity: int) -> None:\n        temp: List[Optional[T]] = [None] * capacity\n        for i in range(self.n):\n            temp[i] = self.a[i]\n        self.a = temp\n\n    def push(self, item: T) -> None:\n        if self.n == len(self.a):\n            self.resize(2 * len(self.a))\n        self.a[self.n] = item\n        self.n += 1\n\n    def pop(self) -> T:\n        self.n -= 1\n        item = self.a[self.n]\n        self.a[self.n] = None\n        if self.n > 0 and self.n <= len(self.a) // 4:\n            self.resize(len(self.a) // 2)\n        assert item is not None\n        return item\n\n    def __iter__(self) -> Iterator[T]:\n        i = self.n - 1\n        while i >= 0:\n            item = self.a[i]\n            assert item is not None\n            yield item\n            i -= 1\n"
  },
  {
    "path": "itu/algs4/fundamentals/three_sum.py",
    "content": "class ThreeSum:\n    @staticmethod\n    def count(a):\n        # Count triples that sum to 0\n        n = len(a)\n        count = 0\n        for i in range(n):\n            for j in range(i + 1, n):\n                for k in range(j + 1, n):\n                    if a[i] + a[j] + a[k] == 0:\n                        count += 1\n        return count\n"
  },
  {
    "path": "itu/algs4/fundamentals/three_sum_fast.py",
    "content": "from itu.algs4.fundamentals import binary_search\n\n\nclass ThreeSumFast:\n    @staticmethod\n    def count(a):\n        # Count triples that sum to 0\n        a.sort()\n        n = len(a)\n        count = 0\n        for i in range(n):\n            for j in range(i + 1, n):\n                if binary_search.index_of(a, -a[i] - a[j]) > j:\n                    count += 1\n        return count\n"
  },
  {
    "path": "itu/algs4/fundamentals/two_sum_fast.py",
    "content": "from itu.algs4.fundamentals import binary_search\n\n\nclass TwoSumFast:\n    @staticmethod\n    def count(a):\n        # Count pairs that sum to 0\n        a = sorted(a)\n        n = len(a)\n        count = 0\n        for i in range(n):\n            if binary_search.index_of(a, -a[i]) > i:\n                count += 1\n        return count\n"
  },
  {
    "path": "itu/algs4/fundamentals/uf.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"The UF module implements several versions of the union-find data structure\n(also known as the disjoint-sets data type). It supports the union and find\noperations, along with a connected operation for determining whether two sites\nare in the same component and a count operation that returns the total number\nof components.\n\nThe union-find data type models connectivity among a set of n sites, named 0\nthrough n-1. The is-connected-to relation must be an equivalence relation:\n    * Reflexive: p is connected to p.\n    * Symmetric: If p is connected to q, then q is connected to p.\n    * Transitive: If p is connected to q and q is connected to r, then\n                       p is connected to r.\n\n\"\"\"\nimport sys\n\nfrom itu.algs4.stdlib import stdio\n\n\nclass UF:\n    \"\"\"\n    This is an implementation of the union-find data structure - see module documentation for\n    more info.\n\n    This implementation uses weighted quick union by rank with path compression by\n    halving. Initializing a data structure with n sites takes linear time. Afterwards,\n    the union, find, and connected operations take logarithmic time (in the worst case)\n    and the count operation takes constant time. Moreover, the amortized time per union,\n    find, and connected operation has inverse Ackermann complexity.\n\n    For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n    \"\"\"\n\n    def __init__(self, n: int) -> None:\n        \"\"\"Initializes an empty union-find data structure with n sites, 0\n        through n-1. Each site is initially in its own component.\n\n        :param n: the number of sites\n\n        \"\"\"\n        self._count = n\n        self._parent = list(range(n))\n        self._rank = [0] * n\n\n    def _validate(self, p: int) -> None:\n        # validate that p is a valid index\n        n = len(self._parent)\n        if p < 0 or p >= n:\n            raise ValueError(\"index {} is not between 0 and {}\".format(p, n - 1))\n\n    def union(self, p: int, q: int) -> None:\n        \"\"\"Merges the component containing site p with the component containing\n        site q.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n\n        \"\"\"\n        root_p = self.find(p)\n        root_q = self.find(q)\n        if root_p == root_q:\n            return\n\n        # make root of smaller rank point to root of larger rank\n        if self._rank[root_p] < self._rank[root_q]:\n            self._parent[root_p] = root_q\n        elif self._rank[root_p] > self._rank[root_q]:\n            self._parent[root_q] = root_p\n        else:\n            self._parent[root_q] = root_p\n            self._rank[root_p] += 1\n\n        self._count -= 1\n\n    def find(self, p: int) -> int:\n        \"\"\"Returns the component identifier for the component containing site\n        p.\n\n        :param p: the integer representing one site\n        :return: the component identifier for the component containing site p\n\n        \"\"\"\n        self._validate(p)\n        while p != self._parent[p]:\n            self._parent[p] = self._parent[\n                self._parent[p]\n            ]  # path compression by halving\n            p = self._parent[p]\n        return p\n\n    def connected(self, p: int, q: int) -> bool:\n        \"\"\"Returns true if the two sites are in the same component.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n        :return: true if the two sites p and q are in the same component; false otherwise\n\n        \"\"\"\n        return self.find(p) == self.find(q)\n\n    def count(self) -> int:\n        return self._count\n\n\nclass QuickUnionUF:\n    \"\"\"\n    This is an implementation of the union-find data structure - see module documentation for\n    more info.\n\n    This implementation uses quick union. Initializing a data structure with n sites takes\n    linear time. Afterwards, the union, find, and connected operations take linear time\n    (in the worst case) and the count operation takes constant time. For alternate implementations\n    of the same API, see UF, QuickFindUF, and WeightedQuickUnionUF.\n\n    For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n    \"\"\"\n\n    def __init__(self, n: int) -> None:\n        \"\"\"Initializes an empty union-find data structure with n sites, 0\n        through n-1. Each site is initially in its own component.\n\n        :param n: the number of sites\n\n        \"\"\"\n        self._count = n\n        self._parent = list(range(n))\n\n    def _validate(self, p: int) -> None:\n        # validate that p is a valid index\n        n = len(self._parent)\n        if p < 0 or p >= n:\n            raise ValueError(\"index {} is not between 0 and {}\".format(p, n - 1))\n\n    def union(self, p: int, q: int) -> None:\n        \"\"\"Merges the component containing site p with the component containing\n        site q.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n\n        \"\"\"\n        root_p = self.find(p)\n        root_q = self.find(q)\n        if root_p == root_q:\n            return\n\n        self._parent[root_p] = root_q\n\n        self._count -= 1\n\n    def find(self, p: int) -> int:\n        \"\"\"Returns the component identifier for the component containing site\n        p.\n\n        :param p: the integer representing one site\n        :return: the component identifier for the component containing site p\n\n        \"\"\"\n        self._validate(p)\n        while p != self._parent[p]:\n            p = self._parent[p]\n        return p\n\n    def connected(self, p: int, q: int) -> bool:\n        \"\"\"Returns true if the two sites are in the same component.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n        :return: true if the two sites p and q are in the same component; false otherwise\n\n        \"\"\"\n        return self.find(p) == self.find(q)\n\n    def count(self) -> int:\n        return self._count\n\n\nclass WeightedQuickUnionUF:\n    \"\"\"\n    This is an implementation of the union-find data structure - see module documentation for\n    more info.\n\n    This implementation uses weighted quick union by size (without path compression).\n    Initializing a data structure with n sites takes linear time. Afterwards, the union, find,\n    and connected operations take logarithmic time (in the worst case) and the count operation\n    takes constant time. For alternate implementations of the same API, see UF, QuickFindUF,\n    and QuickUnionUF.\n\n    For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n    \"\"\"\n\n    def __init__(self, n: int) -> None:\n        \"\"\"Initializes an empty union-find data structure with n sites, 0\n        through n-1. Each site is initially in its own component.\n\n        :param n: the number of sites\n\n        \"\"\"\n        self._count = n\n        self._parent = list(range(n))\n        self._size = [1] * n\n\n    def _validate(self, p: int) -> None:\n        # validate that p is a valid index\n        n = len(self._parent)\n        if p < 0 or p >= n:\n            raise ValueError(\"index {} is not between 0 and {}\".format(p, n - 1))\n\n    def union(self, p: int, q: int) -> None:\n        \"\"\"Merges the component containing site p with the component containing\n        site q.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n\n        \"\"\"\n        root_p = self.find(p)\n        root_q = self.find(q)\n        if root_p == root_q:\n            return\n\n        # make root of smaller rank point to root of larger rank\n        if self._size[root_p] < self._size[root_q]:\n            small, large = root_p, root_q\n        else:\n            small, large = root_q, root_p\n\n        self._parent[small] = large\n        self._size[large] += self._size[small]\n\n        self._count -= 1\n\n    def find(self, p: int) -> int:\n        \"\"\"Returns the component identifier for the component containing site\n        p.\n\n        :param p: the integer representing one site\n        :return: the component identifier for the component containing site p\n\n        \"\"\"\n        self._validate(p)\n        while p != self._parent[p]:\n            p = self._parent[p]\n        return p\n\n    def connected(self, p: int, q: int) -> bool:\n        \"\"\"Returns true if the two sites are in the same component.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n        :return: true if the two sites p and q are in the same component; false otherwise\n\n        \"\"\"\n        return self.find(p) == self.find(q)\n\n    def count(self) -> int:\n        return self._count\n\n\nclass QuickFindUF:\n    \"\"\"\n    This is an implementation of the union-find data structure - see module documentation for\n    more info.\n\n    This implementation uses quick find. Initializing a data structure with n sites takes linear time.\n    Afterwards, the find, connected, and count operations take constant time but the union operation\n    takes linear time.\n\n    For additional documentation, see Section 1.5 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n    \"\"\"\n\n    def __init__(self, n: int) -> None:\n        \"\"\"Initializes an empty union-find data structure with n sites, 0\n        through n-1. Each site is initially in its own component.\n\n        :param n: the number of sites\n\n        \"\"\"\n        self._count = n\n        self._id = list(range(n))\n\n    def _validate(self, p: int) -> None:\n        # validate that p is a valid index\n        n = len(self._id)\n        if p < 0 or p >= n:\n            raise ValueError(\"index {} is not between 0 and {}\".format(p, n - 1))\n\n    def union(self, p: int, q: int) -> None:\n        \"\"\"Merges the component containing site p with the component containing\n        site q.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n\n        \"\"\"\n        self._validate(p)\n        self._validate(q)\n\n        p_id = self._id[p]  # needed for correctness\n        q_id = self._id[q]  # to reduce the number of array accesses\n\n        # p and q are already in the same component\n        if p_id == q_id:\n            return\n\n        for i in range(len(self._id)):\n            if self._id[i] == p_id:\n                self._id[i] = q_id\n        self._count -= 1\n\n    def find(self, p: int) -> int:\n        \"\"\"Returns the component identifier for the component containing site\n        p.\n\n        :param p: the integer representing one site\n        :return: the component identifier for the component containing site p\n\n        \"\"\"\n        self._validate(p)\n        return self._id[p]\n\n    def connected(self, p: int, q: int) -> bool:\n        \"\"\"Returns true if the two sites are in the same component.\n\n        :param p: the integer representing one site\n        :param q: the integer representing the other site\n        :return: true if the two sites p and q are in the same component; false otherwise\n\n        \"\"\"\n        self._validate(p)\n        self._validate(q)\n        return self._id[p] == self._id[q]\n\n    def count(self):\n        return self._count\n\n\n# Reads in a an integer n and a sequence of pairs of integers\n# (between 0 and n-1) from standard input or a file\n# supplied as argument to the program, where each integer\n# in the pair represents some site; if the sites are in different\n# components, merge the two components and print the pair to standard output.\nif __name__ == \"__main__\":\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n    n = stdio.readInt()\n    uf = UF(n)\n    while not stdio.isEmpty():\n        p = stdio.readInt()\n        q = stdio.readInt()\n        if uf.connected(p, q):\n            continue\n        uf.union(p, q)\n        print(\"{} {}\".format(p, q))\n    print(\"number of components: {}\".format(uf.count()))\n"
  },
  {
    "path": "itu/algs4/graphs/Arbitrage.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport math\nimport sys\n\nfrom itu.algs4.graphs.bellman_ford_sp import BellmanFordSP\nfrom itu.algs4.graphs.directed_edge import DirectedEdge\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\nfrom itu.algs4.stdlib import stdio\n\nif __name__ == \"__main__\":\n    \"\"\"The Arbitrage function provides a client that finds an arbitrage\n    opportunity in a currency exchange table by constructing a complete-digraph\n    representation of the exchange table and then finding a negative cycle in\n    the digraph.\n\n    This implementation uses the Bellman-Ford algorithm to find a negative cycle in\n    the complete digraph. The running time is proportional to V3 in the worst case,\n    where V is the number of currencies.\n\n    For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    # V currencies\n    V = stdio.readInt()\n    name = [None] * V\n\n    # Create complete network\n    graph = EdgeWeightedDigraph(V)\n    for v in range(V):\n        name[v] = stdio.readString()\n        for w in range(V):\n            rate = stdio.readFloat()\n            edge = DirectedEdge(v, w, -math.log(rate))\n            graph.add_edge(edge)\n\n    # find negative cycle\n    spt = BellmanFordSP(graph, 0)\n    if spt.has_negative_cycle():\n        stake = 1000.0\n        for edge in spt.negative_cycle():\n            print(\"{} {}\", stake, name[edge.from_vertex()])\n            stake *= math.exp(-edge.weight())\n            print(\"{} {}\")\n"
  },
  {
    "path": "itu/algs4/graphs/CPM.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.graphs.acyclic_lp import AcyclicLp\nfrom itu.algs4.graphs.directed_edge import DirectedEdge\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\nfrom itu.algs4.stdlib import instream\n\n\"\"\"\nThe cpm module is an example of using graphs to solve the parallel precedence-constrained\njob scheduling problem via the critical path method. It reduces the problem to the longest-paths\nproblem in edge-weighted DAGs. It builds an edge-weighted digraph (which must be a DAG) from the\njob-scheduling problem specification, finds the longest-paths tree, and computes the longest-paths\nlengths (which are precisely the start times for each job).\n\nThis implementation uses AcyclicLP to find a longest path in a DAG. The running time is proportional\nto V + E, where V is the number of jobs and E is the number of precedence constraints.\n\nFor additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\"\"\"\n\n\n# Try this with the jobsPC.txt data file\nif __name__ == \"__main__\":\n    # Create stream from file or the standard input,\n    # depending on whether a file name was passed.\n    file = sys.argv[1] if len(sys.argv) > 1 else None\n    stream = instream.InStream(file)\n\n    # Number of jobs\n    N = stream.readInt()\n\n    # Source and sink\n    source, sink = 2 * N, 2 * N + 1\n\n    # Construct the network\n    G = EdgeWeightedDigraph(2 * N + 2)\n    for i in range(N):\n        duration = stream.readFloat()\n        G.add_edge(DirectedEdge(i, i + N, duration))\n        G.add_edge(DirectedEdge(source, i, 0.0))\n        G.add_edge(DirectedEdge(i + N, sink, 0.0))\n\n        # Precedence constraints\n        m = stream.readInt()\n        for _ in range(m):\n            successor = stream.readInt()\n            G.add_edge(DirectedEdge(i + N, successor, 0.0))\n\n    # Compute longest path\n    lp = AcyclicLp(G, source)\n\n    # Print results\n    print(\"Start times:\")\n    for i in range(N):\n        print(\"{:4d}: {:5.1f}\".format(i, lp.dist_to(i)))\n    print(\"Finish time: {:5.1f}\".format(lp.dist_to(i)))\n"
  },
  {
    "path": "itu/algs4/graphs/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/graphs/acyclic_lp.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\nfrom itu.algs4.graphs.topological import Topological\nfrom itu.algs4.stdlib import instream\n\n\"\"\"\nThis module implements a class for solving the single-source Longest\npaths problem in edge-weighted directed acyclic graphs (DAGs), described in\nAlgorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\nFor more information, see chapter 4.2 of the book.\n\"\"\"\n\n\nclass AcyclicLp:\n    \"\"\"The AcyclicLP class represents a data type for solving the single-source\n    longest paths problem in edge-weighted directed acyclic graphs (DAGs). The\n    edge weights can be positive, negative, or zero.\n\n    This implementation uses a topological-sort based algorithm. The constructor takes\n    time proportional to V + E, where V is the number of vertices and E is the number of edges.\n    Each call to distTo(int) and hasPathTo(int) takes constant time; each call to pathTo(int)\n    takes time proportional to the number of edges in the shortest path returned.\n\n    For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, edge_weighted_digraph, s):\n        \"\"\"Computes a longest paths tree from s to every other vertex in the\n        directed acyclic graph G.\n\n        :param edge_weighted_digraph: the acyclic digraph\n        :param s: the source vertex\n\n        \"\"\"\n        graph = edge_weighted_digraph\n        self._dist_to = [float(\"-inf\")] * graph.V()\n        self._edge_to = [None] * graph.V()\n\n        self._validate_vertex(s)\n\n        self._dist_to[s] = 0.0\n\n        # relax vertices in topological order\n        topological = Topological(graph)\n        if not topological.has_order():\n            print(graph)\n            raise ValueError(\"Digraph is not acyclic.\")\n\n        for v in topological.order():\n            for edge in graph.adj(v):\n                self._relax(edge)\n\n    def dist_to(self, v):\n        \"\"\"Returns the length of a longest path from the source vertex s to\n        vertex v.\n\n        :param v: the destination vertex\n\n        :returns: the length of a longest path from the source vertex s to vertex v;\n                  negative infinity if no such path exists\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._dist_to[v]\n\n    def has_path_to(self, v):\n        \"\"\"Is there a path from the source vertex s to vertex v?\"\"\"\n        return self.dist_to(v) > float(\"-inf\")\n\n    def path_to(self, v):\n        \"\"\"Returns a longest path from the source vertex s to vertex v.\n\n        :param: the destination vertex\n        :returns: a longest path from the source vertex s to vertex v as an iterable of edges, and None if no such path\n\n        \"\"\"\n        self._validate_vertex(v)\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        edge = self._edge_to[v]\n        while edge is not None:\n            path.push(edge)\n            edge = self._edge_to[edge.from_vertex()]\n        return path\n\n    # relax edge e, but update if you find a *longer* path\n    def _relax(self, edge):\n        v, w = edge.from_vertex(), edge.to_vertex()\n        if self._dist_to[w] < self._dist_to[v] + edge.weight():\n            self._dist_to[w] = self._dist_to[v] + edge.weight()\n            self._edge_to[w] = edge\n\n    # throw an IllegalArgumentException unless 0 <= v < V\n    def _validate_vertex(self, v):\n        V = len(self._dist_to)\n        if not (0 <= v < V):\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nif __name__ == \"__main__\":\n    # Create stream from file or the standard input,\n    # depending on whether a file name was passed.\n    stream = sys.argv[1] if len(sys.argv) > 1 else None\n    d = EdgeWeightedDigraph.from_stream(instream.InStream(stream))\n    a = AcyclicLp(d, 3)\n\n    # print longest paths to all other vertices\n    for i in range(d.V()):\n        print(\"{} to {}\".format(i, a.path_to(i)))\n"
  },
  {
    "path": "itu/algs4/graphs/acyclic_sp.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nimport math\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.topological import Topological\n\n\nclass AcyclicSP:\n    \"\"\"The AcyclicSP class represents a data type for solving the single-source\n    shortest paths problem in edge-weighted directed acyclic graphs (DAGs). The\n    edge weights can be positive, negative, or zero.\n\n    This implementation uses a topological-sort based algorithm. The\n    constructor takes time proportional to V + E, where V is the number\n    of vertices and E is the number of edges. Each call to distTo(int)\n    and has_path_to(int) takes constant time each call to pathTo(int)\n    takes time proportional to the number of edges in the shortest path\n    returned.\n\n    \"\"\"\n\n    def __init__(self, G, s):\n        \"\"\"Computes a shortest paths tree from s to every other vertex in the\n        directed acyclic graph G.\n\n        :param G: the acyclic digraph\n        :param s: the source vertex\n        :raises ValueError: if the digraph is not acyclic\n        :raises ValueError: unless 0 <= s < V\n\n        \"\"\"\n        self._dist_to = [0] * G.V()  # _dist_to[v] = distance  of shortest s->v path\n        self._edge_to = [None] * G.V()  # _edge_to[v] = last edge on shortest s->v path\n\n        self._validate_vertex(s)\n\n        for v in range(G.V()):\n            self._dist_to[v] = math.inf\n        self._dist_to[s] = 0.0\n\n        # visit vertices in toplogical order\n        topological = Topological(G)\n        if not topological.has_order():\n            raise ValueError(\"Digraph is not acyclic.\")\n\n        for v in topological.order():\n            for e in G.adj(v):\n                self._relax(e)\n\n    def _relax(self, e):\n        v = e.from_vertex()\n        w = e.to_vertex()\n\n        if self._dist_to[w] > self._dist_to[v] + e.weight():\n            self._dist_to[w] = self._dist_to[v] + e.weight()\n            self._edge_to[w] = e\n\n    def dist_to(self, v):\n        \"\"\"Returns the length of a shortest path from the source vertex s to\n        vertex v.\n\n        :param v: the destination vertex\n        :returns: the length of a shortest path from the source vertex s to vertex v\n                math.inf if no such path\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._dist_to[v]\n\n    def has_path_to(self, v):\n        \"\"\"Is there a path from the source vertex s to vertex v?\n\n        :param v: the destination vertex\n        :returns: true if there is a path from the source vertex\n                s to vertex v, and false otherwise\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._dist_to[v] < math.inf\n\n    def path_to(self, v):\n        \"\"\"Returns a shortest path from the source vertex s to vertex v.\n\n        :param v: the destination vertex\n        :returns: a shortest path from the source vertex s to vertex v\n                as an iterable of edges, and None if no such path\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        e = self._edge_to[v]\n        while e is not None:\n            path.push(e)\n            e = self._edge_to[e.from_vertex()]\n        return path\n\n    def _validate_vertex(self, v):\n        # raise an ValueError unless 0 <= v < V\n        V = len(self._dist_to)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    s = int(sys.argv[2])\n    G = EdgeWeightedDigraph.from_stream(In)\n\n    # find shortest path from s to each other vertex in DAG\n    sp = AcyclicSP(G, s)\n    for v in range(G.V()):\n        if sp.has_path_to(v):\n            stdio.writef(\"%d to %d (%.2f)  \", s, v, sp.dist_to(v))\n            for e in sp.path_to(v):\n                stdio.writef(\"%s\\t\", e.__repr__())\n            stdio.writeln()\n        else:\n            stdio.writef(\"%d to %d no path\\n\", s, v)\n"
  },
  {
    "path": "itu/algs4/graphs/bellman_ford_sp.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.errors.errors import (\n    IllegalArgumentException,\n    UnsupportedOperationException,\n)\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\nfrom itu.algs4.graphs.edge_weighted_directed_cycle import EdgeWeightedDirectedCycle\nfrom itu.algs4.stdlib.instream import InStream\n\ntry:\n    q = Queue()\n    q.enqueue(1)\nexcept AttributeError:\n    print(\"ERROR - Could not import itu.algs4 queue\")\n    sys.exit(1)\n\n#  Execution:    python BellmanFordSP.py filename.txt s\n#  Data files:   https://algs4.cs.princeton.edu/44sp/tinyEWDn.txt\n#                https://algs4.cs.princeton.edu/44sp/mediumEWDnc.txt\n#\n#  Bellman-Ford shortest path algorithm. Computes the shortest path tree in\n#  edge-weighted digraph G from vertex s, or finds a negative cost cycle\n#  reachable from s.\n\n\"\"\"\n The BellmanFordSP class represents a data type for solving the\n single-source shortest paths problem in edge-weighted digraphs with\n no negative cycles.\n The edge weights can be positive, negative, or zero.\n This class finds either a shortest path from the source vertex s\n to every other vertex or a negative cycle reachable from the source vertex.\n This implementation uses the Bellman-Ford-Moore algorithm.\n The constructor takes time proportional to V (V + E)\n in the worst case, where V is the number of vertices and E\n is the number of edges.\n Each call to distTo(int) and hasPathTo(int),\n hasNegativeCycle takes constant time;\n each call to pathTo(int) and negativeCycle()\n takes time proportional to length of the path returned.\n\"\"\"\n\n\nclass BellmanFordSP:\n    # Computes a shortest paths tree from s to every other vertex in\n    # the edge-weighted digraph G.\n    # @param G the acyclic digraph\n    # @param s the source vertex\n    # @throws IllegalArgumentException unless 0 <= s < V\n    def __init__(self, G, s):\n        self._distTo = [\n            sys.float_info.max\n        ] * G.V()  # distTo[v] = distance  of shortest s->v path\n        self._edgeTo = [None] * G.V()  # edgeTo[v] = last edge on shortest s->v path\n        self._onQueue = [False] * G.V()  # onQueue[v] = is v currently on the queue?\n        self._queue = Queue()  # queue of vertices to relax\n        self._cost = 0  # number of calls to relax()\n        self._cycle = None  # negative cycle (or None if no such cycle)\n\n        # Bellman-Ford algorithm\n        self._distTo[s] = 0.0\n        self._queue.enqueue(s)\n        self._onQueue[s] = True\n        while not self._queue.is_empty() and not self.has_negative_cycle():\n            v = self._queue.dequeue()\n            self._onQueue[v] = False\n            self._relax(G, v)\n        assert self._check(G, s)\n\n    # relax vertex v and put other endpoints on queue if changed\n    def _relax(self, G, v):\n        for e in G.adj(v):\n            w = e.to_vertex()\n            if self._distTo[w] > self._distTo[v] + e.weight():\n                self._distTo[w] = self._distTo[v] + e.weight()\n                self._edgeTo[w] = e\n                if not self._onQueue[w]:\n                    self._queue.enqueue(w)\n                    self._onQueue[w] = True\n            if self._cost % G.V() == 0:\n                self._find_negative_cycle()\n                if self.has_negative_cycle():\n                    return  # found a negative cycle\n            self._cost += 1\n\n    # Is there a negative cycle reachable from the source vertex s?\n    # @return true if there is a negative cycle reachable from the\n    #    source vertex s, and false otherwise\n    def has_negative_cycle(self):\n        return self._cycle is not None\n\n    # Returns a negative cycle reachable from the source vertex s, or None\n    # if there is no such cycle.\n    # @return a negative cycle reachable from the soruce vertex s\n    #    as an iterable of edges, and None if there is no such cycle\n    def negative_cycle(self):\n        return self._cycle\n\n    # by finding a cycle in predecessor graph\n    def _find_negative_cycle(self):\n        V = len(self._edgeTo)\n        spt = EdgeWeightedDigraph(V)\n        for v in range(V):\n            if self._edgeTo[v] is not None:\n                spt.add_edge(self._edgeTo[v])\n\n        finder = EdgeWeightedDirectedCycle(spt)\n        self._cycle = finder.cycle()\n\n    # Returns the length of a shortest path from the source vertex s to vertex v.\n    # @param  v the destination vertex\n    # @return the length of a shortest path from the source vertex s to vertex v;\n    #         sys.float_info.max if no such path\n    # @throws UnsupportedOperationException if there is a negative cost cycle reachable\n    #         from the source vertex s\n    # @throws IllegalArgumentException unless 0 <= v < V\n    def dist_to(self, v):\n        self._validate_vertex(v)\n        if self.has_negative_cycle():\n            raise UnsupportedOperationException(\"Negative cost cycle exists\")\n        return self._distTo[v]\n\n    # Is there a path from the source s to vertex v?\n    # @param  v the destination vertex\n    # @return true if there is a path from the source vertex\n    #         s to vertex v, and false otherwise\n    # @throws IllegalArgumentException unless 0 <= v < V\n    def has_path_to(self, v):\n        self._validate_vertex(v)\n        return self._distTo[v] < sys.float_info.max\n\n    # Returns a shortest path from the source s to vertex v.\n    # @param  v the destination vertex\n    # @return a shortest path from the source s to vertex v\n    #         as an iterable of edges, and None if no such path\n    # @throws UnsupportedOperationException if there is a negative cost cycle reachable\n    #         from the source vertex s\n    # @throws IllegalArgumentException unless 0 <= v < V\n    def path_to(self, v):\n        self._validate_vertex(v)\n        if self.has_negative_cycle():\n            raise UnsupportedOperationException(\"Negative cost cycle exists\")\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        e = self._edgeTo[v]\n        while e is not None:\n            path.push(e)\n            e = self._edgeTo[e.from_vertex()]\n        return path\n\n    # check optimality conditions: either\n    # (i) there exists a negative cycle reacheable from s\n    #    or\n    # (ii)  for all edges e = v->w:            distTo[w] <= distTo[v] + e.weight()\n    # (ii') for all edges e = v->w on the SPT: distTo[w] == distTo[v] + e.weight()\n    def _check(self, G, s):\n\n        # has a negative cycle\n        if self.has_negative_cycle():\n            weight = 0.0\n            for e in self.negative_cycle():\n                weight += e.weight()\n            if weight >= 0.0:\n                print(\"error: weight of negative cycle = {}\".format(weight))\n                return False\n\n        # no negative cycle reachable from source\n        else:\n\n            # check that distTo[v] and edgeTo[v] are consistent\n            if self._distTo[s] != 0.0 or self._edgeTo[s] is not None:\n                print(\"distanceTo[s] and edgeTo[s] inconsistent\")\n                return False\n\n            for v in range(G.V()):\n                if v == s:\n                    continue\n                if self._edgeTo[v] is None and self._distTo[v] != sys.float_info.max:\n                    print(\"distTo[] and edgeTo[] inconsistent\")\n                    return False\n\n            # check that all edges e = v->w satisfy distTo[w] <= distTo[v] + e.weight()\n            for v in range(G.V()):\n                for e in G.adj(v):\n                    w = e.to_vertex()\n                    if self._distTo[v] + e.weight() < self._distTo[w]:\n                        print(\"edge {} not relaxed\".format(e))\n                        return False\n\n            # check that all edges e = v->w on SPT satisfy distTo[w] == distTo[v] + e.weight()\n            for w in range(G.V()):\n                if self._edgeTo[w] is None:\n                    continue\n                e = self._edgeTo[w]\n                v = e.from_vertex()\n                if w != e.to_vertex():\n                    return False\n                if self._distTo[v] + e.weight() != self._distTo[w]:\n                    print(\"edge {} on shortest path not tight\".format(e))\n                    return False\n\n        print(\"Satisfies optimality conditions\")\n        print()\n        return True\n\n    # raise an IllegalArgumentException unless 0 <= v < V\n    def _validate_vertex(self, v):\n        V = len(self._distTo)\n        if v < 0 or v >= V:\n            raise IllegalArgumentException(\n                \"vertex {} is not between 0 and {}\".format(v, V - 1)\n            )\n\n\ndef main(args):\n    stream = InStream(args[0])\n    s = int(args[1])\n    G = EdgeWeightedDigraph.from_stream(stream)\n    sp = BellmanFordSP(G, s)\n\n    # print negative cycle\n    if sp.has_negative_cycle():\n        for e in sp.negative_cycle():\n            print(e)\n    # print shortest paths\n    else:\n        for v in range(G.V()):\n            if sp.has_path_to(v):\n                print(\"{} to {} ({})  \".format(s, v, sp.dist_to(v)))\n                for e in sp.path_to(v):\n                    print(\"{}\\t\".format(e), end=\"\")\n                print()\n            else:\n                print(\"{} to {} no path\".format(s, v))\n\n\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n\n# *  % python BellmanFordSP.py tinyEWDn.txt 0\n# *  0 to 0 ( 0.00)\n# *  0 to 1 ( 0.93)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52   6->4 -1.25   4->5  0.35   5->1  0.32\n# *  0 to 2 ( 0.26)  0->2  0.26\n# *  0 to 3 ( 0.99)  0->2  0.26   2->7  0.34   7->3  0.39\n# *  0 to 4 ( 0.26)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52   6->4 -1.25\n# *  0 to 5 ( 0.61)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52   6->4 -1.25   4->5  0.35\n# *  0 to 6 ( 1.51)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52\n# *  0 to 7 ( 0.60)  0->2  0.26   2->7  0.34\n# *\n# *  % python BellmanFordSP.py tinyEWDnc.txt 0\n# *  4->5  0.35\n# *  5->4 -0.66\n# *\n"
  },
  {
    "path": "itu/algs4/graphs/bipartite.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.graph import Graph\n\n\nclass Bipartite:\n    \"\"\"The Bipartite class represents a data type for determining whether an\n    undirected graph is bipartite or whether it has an odd-length cycle. The\n    isBipartite operation determines whether the graph is bipartite. If so, the\n    color operation determines a bipartition if not, the oddCycle operation\n    determines a cycle with an odd number of edges.\n\n    This implementation uses depth-first search. The constructor takes\n    time proportional to V + E (in the worst case), where V is the\n    number of vertices and E is the number of edges. Afterwards, the\n    isBipartite and color operations take constant time the oddCycle\n    operation takes time proportional to the length of the cycle. See\n    BipartiteX for a nonrecursive version that uses breadth-first\n    search.\n\n    \"\"\"\n\n    class UnsupportedOperationException(Exception):\n        pass\n\n    def __init__(self, G):\n        \"\"\"Determines whether an undirected graph is bipartite and finds either\n        a bipartition or an odd-length cycle.\n\n        :param G: the graph\n\n        \"\"\"\n        self._is_bipartite = True  # is the graph bipartite?\n        self._color = [\n            False\n        ] * G.V()  # color[v] gives vertices on one side of bipartition\n        self._marked = [False] * G.V()  # marked[v] = True if v has been visited in DFS\n        self._edge_to = [0] * G.V()  # edgeTo[v] = last edge on path to v\n        self._cycle = None  # odd-length cycle\n\n        for v in range(G.V()):\n            if not self._marked[v]:\n                self._dfs(G, v)\n\n        assert self._check(G)\n\n    def _dfs(self, G, v):\n        self._marked[v] = True\n\n        for w in G.adj(v):\n            # short circuit if odd-length cycle found\n            if self._cycle is not None:\n                return\n\n            # found uncolored vertex, so recur\n            if not self._marked[w]:\n                self._edge_to[w] = v\n                self._color[w] = not self._color[v]\n                self._dfs(G, w)\n\n            # if v-w create an odd-length cycle, find it\n            elif self._color[w] == self._color[v]:\n                self._is_bipartite = False\n                self._cycle = Stack()\n                self._cycle.push(\n                    w\n                )  # don't need this unless you want to include start vertex twice\n                x = v\n                while x != w:\n                    self._cycle.push(x)\n                    x = self._edge_to[x]\n\n                self._cycle.push(w)\n\n    def is_bipartite(self):\n        \"\"\"Returns True if the graph is bipartite.\n\n        :returns: True if the graph is bipartite False otherwise\n\n        \"\"\"\n        return self._is_bipartite\n\n    def color(self, v):\n        \"\"\"Returns the side of the bipartite that vertex v is on.\n\n        :param v: the vertex\n        :returns: the side of the bipartition that vertex v is on two vertices\n                are in the same side of the bipartition if and only if they have the\n                same color\n        :raises IllegalArgumentException: unless 0 <= v < V\n        :raises UnsupportedOperationException: if this method is called when the graph\n                is not bipartite\n\n        \"\"\"\n        self._validateVertex(v)\n        if not self._is_bipartite:\n            raise Bipartite.UnsupportedOperationException(\"graph is not bipartite\")\n        return self._color[v]\n\n    def odd_cycle(self):\n        \"\"\"Returns an odd-length cycle if the graph is not bipartite, and None\n        otherwise.\n\n        :returns: an odd-length cycle if the graph is not bipartite\n                (and hence has an odd-length cycle), and None otherwise\n\n        \"\"\"\n        return self._cycle\n\n    def _check(self, G):\n        # graph is bipartite\n        if self._is_bipartite:\n            for v in range(G.V()):\n                for w in G.adj(v):\n                    if self._color[v] == self._color[w]:\n                        error = \"edge {}-{} with {} and {} in same side of bipartition\\n\".format(\n                            v, w, v, w\n                        )\n                        print(error, file=sys.stderr)\n                        return False\n        # graph has an odd-length cycle\n        else:\n            # verify cycle\n            first = -1\n            last = -1\n            for v in self.odd_cycle():\n                if first == -1:\n                    first = v\n                last = v\n\n            if first != last:\n                error = \"cycle begins with {} and ends with {}\\n\".format(first, last)\n                print(error, file=sys.stderr)\n                return False\n        return True\n\n    def _validateVertex(self, v):\n        # raise an ValueError unless 0 <= v < V\n        V = len(self._marked)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = Graph.from_stream(In)\n    stdio.writeln(G)\n\n    b = Bipartite(G)\n    if b.is_bipartite():\n        stdio.writeln(\"Graph is bipartite\")\n        for v in range(G.V()):\n            stdio.writef(\"%i: %i\\n\", v, b.color(v))\n    else:\n        stdio.writeln(\"Graph has an odd-length cycle: \")\n        for x in b.odd_cycle():\n            stdio.writef(\"%i \", x)\n        stdio.writeln()\n"
  },
  {
    "path": "itu/algs4/graphs/breadth_first_paths.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nimport math\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.stack import Stack\n\n\nclass BreadthFirstPaths:\n    \"\"\"The BreadthFirstPaths class represents a data type for finding shortest\n    paths (number of edges) from a source vertex s (or a set of source\n    vertices) to every other vertex in a directed or undirected graph.\n\n    This implementation uses breadth-first search. The constructor takes\n    time proportional to V + E, where V is the number of vertices and E\n    is the number of edges. Each call to distTo(int) and hasPathTo(int)\n    takes constant time each call to pathTo(int) takes time proportional\n    to the length of the path. It uses extra space (not including the\n    graph) proportional to V.\n\n    \"\"\"\n\n    def __init__(self, G, s):\n        \"\"\"Computes the shortest path between the source vertex s and every\n        other vertex in the graph G.\n\n        :param G: the graph\n        :param s: the source vertex\n        :raises ValueError: unless 0 <= s < V\n\n        \"\"\"\n        self._marked = [False] * G.V()  # Is a shortest path to this vertex known?\n        self._dist_to = [math.inf] * G.V()\n        self._edgeTo = [0] * G.V()  # last vertex on known path to this vertex\n        self._validateVertex(s)\n        self._bfs(G, s)\n\n        assert self._check(G, s)\n\n    # @staticmethod\n    # def from_multiple_sources(G, sources):\n    #     \"\"\"\n    #     Computes the shortest path between any one of the source vertices in sources\n    #     and every other vertex in graph G.\n\n    #     :param G the graph\n    #     :param sources the source vertices\n    #     :raises ValueError: unless 0 <= s < V for each vertex\n    #                         s in sources\n    #     \"\"\"\n    #     pass\n\n    def _bfs(self, G, s):\n        # breadth-first search from a single source\n        queue = Queue()\n        self._dist_to[s] = 0\n        self._marked[s] = True  # Mark the source\n        queue.enqueue(s)  # and put it on the queue.\n\n        while not queue.is_empty():\n            v = queue.dequeue()  # Remove next vertex from the queue.\n            for w in G.adj(v):\n                if not self._marked[w]:\n                    self._edgeTo[w] = v  # For every unmarked adjacent vertex,\n                    self._dist_to[w] = self._dist_to[v] + 1\n                    self._marked[w] = True  # mark it because path is known,\n                    queue.enqueue(w)  # and add it to the queue.\n\n    # def _bfs_multiple_sources(self, G, sources):\n    #     # breadth-first search from multiple sources\n    #     pass\n\n    def has_path_to(self, v):\n        \"\"\"Is there a path between the source vertex s (or sources) and vertex\n        v?\n\n        :param v: the vertex\n        :returns: true if there is a path, and False otherwise\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        return self._marked[v]\n\n    def dist_to(self, v):\n        \"\"\"Returns the number of edges in a shortest path between the source\n        vertex s (or sources) and vertex v?\n\n        :param v: the vertex\n        :returns: the number of edges in a shortest path\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._dist_to[v]\n\n    def path_to(self, v):\n        \"\"\"Returns a shortest path between the source vertex s (or sources) and\n        v, or null if no such path.\n\n        :param v: the vertex\n        :returns: the sequence of vertices on a shortest path, as an Iterable\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        x = v\n        while self._dist_to[x] != 0:\n            path.push(x)\n            x = self._edgeTo[x]\n        path.push(x)\n        return path\n\n    def _check(self, G, s):\n        # check optimality conditions for singe source\n        # check that the distance of s = 0\n        if self._dist_to[s] != 0:\n            stdio.writef(\"distance of source %i to itself = %i\\n\", s, self._dist_to[s])\n            return False\n\n        # check that for each edge v-w dist[w] <= dist[v] + 1\n        # provided v is reachable from s\n        for v in range(G.V()):\n            for w in G.adj(v):\n                # if self.has_path_to(v) != self.has_path_to(w):\n                # modified for directed graphs\n                if self.has_path_to(v) and not self.has_path_to(w):\n                    stdio.writef(\"edge %i-%i\\n\", v, w)\n                    stdio.writef(\"has_path_to(%i) = %s\\n\", v, self.has_path_to(v))\n                    stdio.writef(\"has_path_to(%i) = %s\\n\", w, self.has_path_to(w))\n                    return False\n                if self.has_path_to(v) and (self._dist_to[w] > self._dist_to[v] + 1):\n                    stdio.writef(\"edge %i-%i\\n\", v, w)\n                    stdio.writef(\"dist_to[%i] = %i\\n\", v, self._dist_to[v])\n                    stdio.writef(\"dist_to[%i] = %i\\n\", v, self._dist_to[w])\n                    return False\n\n        # check that v = edgeTo[w] satisfies distTo[w] = distTo[v] + 1\n        # provided v is reachable from s\n        for w in range(G.V()):\n            if not self.has_path_to(w) or w == s:\n                continue\n            v = self._edgeTo[w]\n            if self._dist_to[w] != self._dist_to[v] + 1:\n                stdio.writef(\"shortest path edge %i-%i\\n\", v, w)\n                stdio.writef(\"dist_to[%i] = %i\\n\", v, self._dist_to[v])\n                stdio.writef(\"dist_to[%i] = %i\\n\", w, self._dist_to[w])\n                return False\n\n        return True\n\n    def _validateVertex(self, v):\n        # throw an ValueError unless 0 <= v < V\n        V = len(self._marked)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n    # def _validateVertices(self, vertices):\n    #     # throw an ValueError unless 0 <= v < V\n    #     pass\n\n\nclass BreadthFirstPathsBook:\n    def __init__(self, G, s):\n        self._marked = [False] * G.V()  # Is a shortest path to this vertex known?\n        self._edgeTo = [0] * G.V()  # last vertex on known path to this vertex\n        self._s = s  # source\n        self._bfs(G, s)\n\n    def _bfs(self, G, s):\n        # breadth-first search from a single source\n        queue = Queue()\n        self._marked[s] = True  # Mark the source\n        queue.enqueue(s)  # and put it on the queue.\n        while not queue.is_empty():\n            v = queue.dequeue()  # Remove next vertex from the queue.\n            for w in G.adj(v):\n                if not self._marked[w]:\n                    self._edgeTo[w] = v  # For every unmarked adjacent vertex,\n                    self._marked[w] = True  # mark it because path is known,\n                    queue.enqueue(w)  # and add it to the queue.\n\n    def has_path_to(self, v):\n        return self._marked[v]\n\n    def path_to(self, v):\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        x = v\n        while x != self._s:\n            path.push(x)\n            x = self._edgeTo[x]\n        path.push(self._s)\n        return path\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.graphs.graph import Graph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = Graph.from_stream(In)\n    s = int(sys.argv[2])\n    bfs = BreadthFirstPaths(G, s)\n\n    for v in range(G.V()):\n        if bfs.has_path_to(v):\n            stdio.writef(\"%d to %d (%d):  \", s, v, bfs.dist_to(v))\n            for x in bfs.path_to(v):\n                if x == s:\n                    stdio.write(x)\n                else:\n                    stdio.writef(\"-%i\", x)\n            stdio.writeln()\n        else:\n            stdio.writef(\"%d to %d (-):  not connected\\n\", s, v)\n"
  },
  {
    "path": "itu/algs4/graphs/cc.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\n\nclass CC:\n    \"\"\"The CC class represents a data type for determining the connected\n    components in an undirected graph. The id operation determines in which\n    connected component a given vertex lies the connected operation determines\n    whether two vertices are in the same connected component the count\n    operation determines the number of connected components and the size\n    operation determines the number of vertices in the connect component\n    containing a given vertex.\n\n    The component identifier of a connected component is one of the\n    vertices in the connected component: two vertices have the same component\n    identifier if and only if they are in the same connected component.\n\n    This implementation uses depth-first search.\n    The constructor takes time proportional to V + E\n    (in the worst case),\n    where V is the number of vertices and E is the number of edges.\n    Afterwards, the id, count, connected,\n    and size operations take constant time.\n\n    \"\"\"\n\n    def __init__(self, G):\n        \"\"\"Computes the connected components of the undirected graph G.\n\n        :param G: the undirected graph\n\n        \"\"\"\n        self._marked = [False] * G.V()  # marked[v] = has vertex v been marked?\n        self._id = [None] * G.V()  # id[v] = id of connected component containing v\n        self._size = [0] * G.V()  # size[id] = number of vertices in given component\n        self._count = 0  # number of connected components\n\n        for v in range(G.V()):\n            if not self._marked[v]:\n                self._dfs(G, v)\n                self._count += 1\n\n    def _dfs(self, G, v):\n        # depth-first search for a Graph\n        self._marked[v] = True\n        self._id[v] = self._count\n        self._size[self._count] += 1\n        for w in G.adj(v):\n            if not self._marked[w]:\n                self._dfs(G, w)\n\n    def id(self, v):\n        \"\"\"Returns the component id of the connected component containing\n        vertex v.\n\n        :param v: the vertex\n        :returns: the component id of the connected component containing vertex v\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._id[v]\n\n    def size(self, v):\n        \"\"\"Returns the number of vertices in the connected component containing\n        vertex v.\n\n        :param v: the vertex\n        :returns: the number of vertices in the connected component containing vertex v\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._size[self._id[v]]\n\n    def count(self):\n        \"\"\"Returns the number of connected components in the graph G.\n\n        :returns: the number of connected components in the graph G\n\n        \"\"\"\n        return self._count\n\n    def connected(self, v, w):\n        \"\"\"Returns true if vertices v and w are in the same connected\n        component.\n\n        :param v: one vertex\n        :param w: the other vertex\n        :returns: True if vertices v and w are in the same connected component;\n                    False otherwise\n        :raises ValueError: unless 0 <= v < V\n        :raises ValueError: unless 0 <= w < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        self._validate_vertex(w)\n        return self.id(v) == self.id(w)\n\n    def _validate_vertex(self, v):\n        # Raises a ValueError n unless 0 <= v < V\n        V = len(self._marked)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nclass CCBook:\n    def __init__(self, G):\n        self._marked = [False] * G.V()  # marked[v] = has vertex v been marked?\n        self._id = [None] * G.V()  # id[v] = id of connected component containing v\n        self._count = 0  # number of connected components\n\n        for s in range(G.V()):\n            if not self._marked[s]:\n                self._dfs(G, s)\n                self._count += 1\n\n    def _dfs(self, G, v):\n        self._marked[v] = True\n        self._id[v] = self._count\n        for w in G.adj(v):\n            if not self._marked[w]:\n                self._dfs(G, w)\n\n    def connected(self, v, w):\n        return self._id[v] == self._id[w]\n\n    def id(self, v):\n        return self._id[v]\n\n    def count(self):\n        return self._count\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.fundamentals.queue import Queue\n    from itu.algs4.graphs.graph import Graph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = Graph.from_stream(In)\n    cc = CC(G)\n\n    # number of connected components\n    m = cc.count()\n    stdio.writef(\"%i components\\n\", m)\n\n    # compute list of vertices in each connected component\n    components = [Queue() for _ in range(m)]\n    for v in range(G.V()):\n        components[cc.id(v)].enqueue(v)\n\n    # print results\n    for i in range(m):\n        for v in components[i]:\n            stdio.writef(\"%i \", v)\n        stdio.writeln()\n"
  },
  {
    "path": "itu/algs4/graphs/cycle.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.stack import Stack\n\n\nclass Cycle:\n    \"\"\"The Cycle class represents a data type for determining whether an\n    undirected graph has a cycle. The hasCycle operation determines whether the\n    graph has a cycle and, if so, the cycle operation returns one.\n\n    This implementation uses depth-first search. The constructor takes\n    time proportional to V + E (in the worst case), where V is the\n    number of vertices and E is the number of edges. Afterwards, the\n    hasCycle operation takes constant time the cycle operation takes\n    time proportional to the length of the cycle.\n\n    \"\"\"\n\n    def __init__(self, G):\n        \"\"\"Determines whether the undirected graph G has a cycle and, if so,\n        finds such a cycle.\n\n        :param G: the undirected graph\n\n        \"\"\"\n        if self._has_self_loop(G):\n            return\n        if self._has_parallel_edges(G):\n            return\n        self._marked = [False] * G.V()\n        self._edgeTo = [0] * G.V()\n        self._cycle = None\n        for v in range(G.V()):\n            if not self._marked[v]:\n                self._dfs(G, -1, v)\n\n    def _has_self_loop(self, G):\n        # does this graph have a self loop?\n        # side effect: initialize cycle to be self loop\n        for v in range(G.V()):\n            for w in G.adj(v):\n                if v == w:\n                    self._cycle = Stack()\n                    self._cycle.push(v)\n                    self._cycle.push(w)\n                    return True\n        return False\n\n    def _has_parallel_edges(self, G):\n        # does this graph have two parallel edges?\n        # side effect: initialize cycle to be two parallel edges\n        self._marked = [False] * G.V()\n        for v in range(G.V()):\n            # check for parallel edges incident to v\n            for w in G.adj(v):\n                if self._marked[w]:\n                    self._cycle = Stack()\n                    self._cycle.push(v)\n                    self._cycle.push(w)\n                    self._cycle.push(v)\n                    return True\n                self._marked[w] = True\n\n            for w in G.adj(v):\n                self._marked[w] = False\n        return False\n\n    def has_cycle(self):\n        \"\"\"Returns true if the graph G has a cycle.\n\n        :returns: true if the graph has a cycle false otherwise\n\n        \"\"\"\n        return self._cycle is not None\n\n    def cycle(self):\n        \"\"\"Returns a cycle in the graph G.\n\n        :returns: a cycle if the graph G has a cycle,\n            and null otherwise\n\n        \"\"\"\n        return self._cycle\n\n    def _dfs(self, G, u, v):\n        self._marked[v] = True\n        for w in G.adj(v):\n            # short circuit if cycle already found\n            if self._cycle is not None:\n                return\n            if not self._marked[w]:\n                self._edgeTo[w] = v\n                self._dfs(G, v, w)\n            elif w != u:\n                self._cycle = Stack()\n                x = v\n                while x != w:\n                    self._cycle.push(x)\n                    x = self._edgeTo[x]\n                self._cycle.push(w)\n                self._cycle.push(v)\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.graphs.graph import Graph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = Graph.from_stream(In)\n    finder = Cycle(G)\n    if finder.has_cycle():\n        for v in finder.cycle():\n            stdio.writef(\"%i \", v)\n        stdio.writeln()\n    else:\n        stdio.writeln(\"Graph is acyclic\")\n"
  },
  {
    "path": "itu/algs4/graphs/degrees_of_separation.py",
    "content": "from itu.algs4.graphs.breadth_first_paths import BreadthFirstPaths\nfrom itu.algs4.graphs.symbol_graph import SymbolGraph\nfrom itu.algs4.stdlib import stdio\n\n\nclass DegreesOfSeparation:\n    \"\"\"The DegreesOfSeparation class provides a client for finding the degree\n    of separation between one distinguished individual and every other\n    individual in a social network. As an example, if the social network\n    consists of actors in which two actors are connected by a link if they\n    appeared in the same movie, and Kevin Bacon is the distinguished\n    individual, then the client computes the Kevin Bacon number of every actor\n    in the network.\n\n    The running time is proportional to the number of individuals and\n    connections in the network. If the connections are given implicitly,\n    as in the movie network example (where every two actors are\n    connected if they appear in the same movie), the efficiency of the\n    algorithm is improved by allowing both movie and actor vertices and\n    connecting each movie to all of the actors that appear in that\n    movie.\n\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"this class shouldn't be instantiated.\"\"\"\n        pass\n\n    @staticmethod\n    def main(args):\n        \"\"\"Reads in a social network from a file, and then repeatedly reads in\n        individuals from standard input and prints out their degrees of\n        separation. Takes three command-line arguments: the name of a file, a\n        delimiter, and the name of the distinguished individual. Each line in\n        the file contains the name of a vertex, followed by a list of the names\n        of the vertices adjacent to that vertex, separated by the delimiter.\n\n        :param args: the command-line arguments\n\n        \"\"\"\n        filename = args[1]\n        delimiter = args[2]\n        source = args[3]\n\n        sg = SymbolGraph(filename, delimiter)\n        G = sg.graph()\n        if not sg.contains(source):\n            stdio.writeln(\"{} not in database\".format(source))\n            return\n\n        s = sg.index_of(source)\n        bfs = BreadthFirstPaths(G, s)\n\n        while not stdio.isEmpty():\n            sink = stdio.readLine()\n            if sg.contains(sink):\n                t = sg.index_of(sink)\n                if bfs.has_path_to(t):\n                    for v in bfs.path_to(t):\n                        stdio.writef(\"\\t%s\\n\", sg.name_of(v))\n                else:\n                    stdio.writeln(\"\\tNot connected\")\n            else:\n                stdio.writeln(\"\\tNot in database.\")\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    DegreesOfSeparation.main(sys.argv)\n"
  },
  {
    "path": "itu/algs4/graphs/depth_first_order.py",
    "content": "from itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.digraph import Digraph\n\n\nclass DepthFirstOrder:\n    \"\"\"The DepthFirstOrder class represents a data type for determining depth-\n    first search ordering of the vertices in a digraph or edge-weighted\n    digraph, including preorder, postorder, and reverse postorder.\n\n    This implementation uses depth-first search. The constructor takes time proportional\n    to V + E (in the worst case), where V is the number of vertices and E is the number\n    of edges. Afterwards, the preorder, postorder, and reverse postorder operation takes\n    take time proportional to V.\n\n    For additional documentation, see Section 4.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, digraph):\n        \"\"\"Determines a depth-first order for the digraph.\n\n        :param digraph: the digraph to check\n\n        \"\"\"\n        self._pre = [0] * digraph.V()\n        self._post = [0] * digraph.V()\n        self._preorder = Queue()\n        self._postorder = Queue()\n        self._marked = [False] * digraph.V()\n\n        self._pre_counter = 0\n        self._post_counter = 0\n\n        if isinstance(digraph, Digraph):\n            dfs = self._dfs\n        else:\n            dfs = self._dfs_edge_weighted\n\n        for v in range(digraph.V()):\n            if not self._marked[v]:\n                dfs(digraph, v)\n\n    def post(self, v=None):\n        \"\"\"Either returns the postorder number of vertex v or, if v is None,\n        returns the vertices in postorder.\n\n        :param v: None, or the vertex to return the postorder number of\n        :return: if v is None, the vertices in postorder, otherwise the postorder\n        number of v\n\n        \"\"\"\n        if v is None:\n            return self._postorder\n        else:\n            self._validate_vertex(v)\n            return self._post[v]\n\n    def pre(self, v=None):\n        \"\"\"Either returns the preorder number of vertex v or, if v is None,\n        returns the vertices in preorder.\n\n        :param v: None, or the vertex to return the preorder number of\n        :return: if v is None, the vertices in preorder, otherwise the preorder\n                number of v\n\n        \"\"\"\n        if v is None:\n            return self._preorder\n        else:\n            self._validate_vertex(v)\n            return self._pre[v]\n\n    def reverse_post(self):\n        \"\"\"Returns the vertices in reverse postorder.\n\n        :return: the vertices in reverse postorder, as an iterable of vertices\n\n        \"\"\"\n        reverse = Stack()\n        for v in self._postorder:\n            reverse.push(v)\n        return reverse\n\n    # run DFS in digraph G from vertex v and compute preorder/postorder\n    def _dfs(self, digraph, v):\n        self._marked[v] = True\n        self._pre[v] = self._pre_counter\n        self._pre_counter += 1\n        self._preorder.enqueue(v)\n        for w in digraph.adj(v):\n            if not self._marked[w]:\n                self._dfs(digraph, w)\n        self._postorder.enqueue(v)\n        self._post[v] = self._post_counter\n        self._post_counter += 1\n\n    # run DFS in edge-weighted digraph G from vertex v and compute preorder/postorder\n    def _dfs_edge_weighted(self, graph, v):\n        self._marked[v] = True\n        self._pre[v] = self._pre_counter\n        self._pre_counter += 1\n        self._preorder.enqueue(v)\n        for edge in graph.adj(v):\n            w = edge.to_vertex()\n            if not self._marked[w]:\n                self._dfs_edge_weighted(graph, w)\n        self._postorder.enqueue(v)\n        self._post[v] = self._post_counter\n        self._post_counter += 1\n\n    # throw an IllegalArgumentException unless 0 <= v < V\n    def _validate_vertex(self, v):\n        V = len(self._marked)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\", v, V - 1)\n\n    # check that pre() and post() are consistent with pre(v) and post(v)\n    def _check(self):\n        # check that post(v) is consistent with post()\n        r = 0\n        for v in self.post():\n            if self.post(v) != r:\n                print(\"post(v) and post() inconsistent\")\n                return False\n            r += 1\n\n        # check that pre(v) is consistent with pre()\n        r = 0\n        for v in self.pre():\n            if self.pre(v) != r:\n                print(\"pre(v) and pre() inconsistent\")\n                return False\n            r += 1\n\n        return True\n"
  },
  {
    "path": "itu/algs4/graphs/depth_first_paths.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.stack import Stack\n\n\nclass DepthFirstPaths:\n    \"\"\"The  DepthFirstPaths class represents a data type for finding paths from\n    a source vertex s to every other vertex in an undirected graph.\n\n    This implementation uses depth-first search. The constructor takes\n    time proportional to V + E, where V is the number of vertices and E\n    is the number of edges. Each call to hasPathTo(int) takes constant\n    time each call to pathTo(int) takes time proportional to the length\n    of the path. It uses extra space (not including the graph)\n    proportional to V.\n\n    \"\"\"\n\n    def __init__(self, G, s):\n        \"\"\"Computes a path between s and every other vertex in graph G.\n\n        :param G: the graph\n        :param s: the source vertex\n        :raises ValueError: unless 0 <= s < V\n\n        \"\"\"\n        self._marked = [False] * G.V()  # Has dfs been called for this vertex?\n        self._edgeTo = [0] * G.V()  # last vertex on known path to this vertex\n        self._s = s  # source\n        self._validateVertex(s)\n        self._dfs(G, s)\n\n    def _dfs(self, G, v):\n        # depth first search from v\n        self._marked[v] = True\n        for w in G.adj(v):\n            if not self._marked[w]:\n                self._edgeTo[w] = v\n                self._dfs(G, w)\n\n    def has_path_to(self, v):\n        \"\"\"Is there a path between the source vertex s and vertex v?\n\n        :param v: the vertex\n        :returns: true if there is a path, false otherwise\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._marked[v]\n\n    def path_to(self, v):\n        \"\"\"Returns a path between the source vertex s and vertex v, or None if\n        no such path.\n\n        :param v: the vertex\n        :returns: the sequence of vertices on a path between the source vertex\n                   s and vertex v, as an Iterable\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        w = v\n        while w != self._s:\n            path.push(w)\n            w = self._edgeTo[w]\n        path.push(self._s)\n\n        return path\n\n    def _validateVertex(self, v):\n        # throw an ValueError unless 0 <= v < V\n        V = len(self._marked)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.graphs.graph import Graph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = Graph.from_stream(In)\n    s = int(sys.argv[2])\n    dfs = DepthFirstPaths(G, s)\n\n    for v in range(G.V()):\n        if dfs.has_path_to(v):\n            stdio.writef(\"%d to %d:  \", s, v)\n            for x in dfs.path_to(v):\n                if x == s:\n                    stdio.write(x)\n                else:\n                    stdio.writef(\"-%i\", x)\n            stdio.writeln()\n        else:\n            stdio.writef(\"%d to %d:  not connected\\n\", s, v)\n"
  },
  {
    "path": "itu/algs4/graphs/depth_first_search.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\n\nclass DepthFirstSearch:\n    \"\"\"The DepthFirstSearch class represents a data type for determining the\n    vertices connected to a given source vertex s in an undirected graph. For\n    versions that find the paths, see DepthFirstPaths and BreadthFirstPaths.\n\n    This implementation uses depth-first search. The constructor takes\n    time proportional to V + E (in the worst case), where V is the\n    number of vertices and E is the number of edges. It uses extra space\n    (not including the graph) proportional to V.\n\n    \"\"\"\n\n    def __init__(self, G, s):\n        \"\"\"Computes the vertices in graph G that are connected to the source\n        vertex s.\n\n        :param G: the graph\n        :param s: the source vertex\n        :throws ValueError: unless 0 <= s < V\n\n        \"\"\"\n        self._marked = [False] * G.V()  # marked[v] = is there an s-v path?\n        self._count = 0  # number of vertices connected to s\n        self._validateVertex(s)\n        self._dfs(G, s)\n\n    def _dfs(self, G, v):\n        # depth first search from v\n        self._marked[v] = True\n        self._count += 1\n        for w in G.adj(v):\n            if not self._marked[w]:\n                self._dfs(G, w)\n\n    def marked(self, v):\n        \"\"\"Is there a path between the source vertex s and vertex v?\n\n        :param v: the vertex\n        :returns: true if there is a path, false otherwise\n        :raises ValueError: unless 0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._marked[v]\n\n    def count(self):\n        \"\"\"Returns the number of vertices connected to the source vertex s.\n\n        :returns: the number of vertices connected to the source vertex s\n\n        \"\"\"\n        return self._count\n\n    def _validateVertex(self, v):\n        # throw an ValueError unless 0 <= v < V\n        V = len(self._marked)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.graphs.graph import Graph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = Graph.from_stream(In)\n    s = int(sys.argv[2])\n    search = DepthFirstSearch(G, s)\n    for v in range(G.V()):\n        if search.marked(v):\n            stdio.writef(\"%i \", v)\n    stdio.writeln()\n\n    if search.count() != G.V():\n        stdio.writeln(\"NOT connected\")\n    else:\n        stdio.writeln(\"connected\")\n"
  },
  {
    "path": "itu/algs4/graphs/digraph.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module implements the directed graph data structure described in\nAlgorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\nFor more information, see chapter 4.2 of the book.\n\n\"\"\"\n\nimport sys\n\nfrom itu.algs4.fundamentals.bag import Bag\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.graph import Graph\nfrom itu.algs4.stdlib.instream import InStream\n\n\nclass Digraph:\n    \"\"\"The Graph class represents an undirected graph of vertices.\n\n    named 0 through V - 1.\n    It supports the following two primary operations: add an edge to the graph,\n    iterate over all of the vertices adjacent to a vertex. It also provides\n    methods for returning the number of vertices V and the number\n    of edges E. Parallel edges and self-loops are permitted.\n    By convention, a self-loop v-v appears in the\n    adjacency list of v twice and contributes two to the degree\n    of v.\n\n    This implementation uses an adjacency-lists representation, which\n    is a vertex-indexed array of Bag objects.\n    All operations take constant time (in the worst case) except\n    iterating over the vertices adjacent to a given vertex, which takes\n    time proportional to the number of such vertices.\n\n    \"\"\"\n\n    def __init__(self, V):\n        \"\"\"Initializes an empty graph with V vertices and 0 edges. param V the\n        number of vertices.\n\n        :param V: number of vertices\n        :raises: ValueError if V < 0\n\n        \"\"\"\n        if V < 0:\n            raise ValueError(\"Number of vertices must be nonnegative\")\n        self._V = V  # number of vertices\n        self._E = 0  # number of edges\n        self._adj = []  # adjacency lists\n\n        for _ in range(V):\n            self._adj.append(Bag())  # Initialize all lists to empty bags.\n\n    @staticmethod\n    def from_stream(stream):\n        \"\"\"Initializes a graph from the specified input stream. The format is\n        the number of vertices V, followed by the number of edges E, followed\n        by E pairs of vertices, with each entry separated by whitespace.\n\n        :param stream: the input stream\n        :returns: new graph from stream\n        :raises ValueError: if the endpoints of any edge are not in prescribed range\n        :raises ValueError: if the number of vertices or edges is negative\n        :raises ValueError: if the input stream is in the wrong format\n\n        \"\"\"\n        V = stream.readInt()  # read V\n        if V < 0:\n            raise ValueError(\"Number of vertices must be nonnegative\")\n        g = Digraph(V)  # construct this graph\n        E = stream.readInt()  # read E\n        if E < 0:\n            raise ValueError(\"Number of edges in a Graph must be nonnegative\")\n        for _ in range(E):\n            # Add an edge\n            v = stream.readInt()  # read a vertex,\n            w = stream.readInt()  # read another vertex,\n            g._validateVertex(v)\n            g._validateVertex(w)\n            g.add_edge(v, w)  # and add edge connecting them.\n        return g\n\n    @staticmethod\n    def from_graph(G):\n        \"\"\"Initializes a new graph that is a deep copy of G.\n\n        :param G: the graph to copy\n        :returns: copy of G\n\n        \"\"\"\n        g = Graph(G.V())\n        g._E = G.E()\n        for v in range(G.V()):\n            # reverse so that adjacency list is in same order as original\n            reverse = Stack()\n            for w in G._adj[v]:\n                reverse.push(w)\n            for w in reverse:\n                g._adj[v].add(w)\n\n    def V(self):\n        \"\"\"Returns the number of vertices in this graph.\n\n        :returns: the number of vertices in this graph.\n\n        \"\"\"\n        return self._V\n\n    def E(self):\n        \"\"\"Returns the number of edges in this graph.\n\n        :returns: the number of edges in this graph.\n\n        \"\"\"\n        return self._E\n\n    def _validateVertex(self, v):\n        # throw a ValueError unless 0 <= v < V\n        if v < 0 or v >= self._V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, self._V))\n\n    def add_edge(self, v, w):\n        \"\"\"Adds the undirected edge v-w to this graph.\n\n        :param v: one vertex in the edge\n        :param w: the other vertex in the edge\n        :raises ValueError: unless both 0 <= v < V and 0 <= w < V\n\n        \"\"\"\n        self._adj[v].add(w)  # add w to v's list\n        self._E += 1\n\n    def adj(self, v):\n        \"\"\"Returns the vertices adjacent to vertex v.\n\n        :param v: the vertex\n        :returns: the vertices adjacent to vertex v, as an iterable\n        :raises ValueError: unless  0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._adj[v]\n\n    def degree(self, v):\n        \"\"\"Returns the degree of vertex v.\n\n        :param v: the vertex\n        :returns: the degree of vertex v\n        :raises ValueError:  unless 0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._adj[v].size()\n\n    def reverse(self):\n        \"\"\"Returns the reverse of the digraph.\n\n        :returns: the reverse of the digraph\n\n        \"\"\"\n        rev = Digraph(self._V)\n        for v in range(self._V):\n            for w in self.adj(v):\n                rev.add_edge(w, v)\n        return rev\n\n    def __repr__(self):\n        \"\"\"Returns a string representation of this graph.\n\n        :returns: the number of vertices V, followed by the number of edges E,\n                    followed by the V adjacency lists\n\n        \"\"\"\n        s = [\"{} vertices, {} edges\\n\".format(self._V, self._E)]\n        for v in range(self._V):\n            s.append(\"%d : \" % (v))\n            for w in self._adj[v]:\n                s.append(\"%d \" % (w))\n            s.append(\"\\n\")\n\n        return \"\".join(s)\n\n\nif __name__ == \"__main__\":\n    # Create stream from file or the standard input,\n    # depending on whether a file name was passed.\n    stream = sys.argv[1] if len(sys.argv) > 1 else None\n\n    d = Digraph.from_stream(InStream(stream))\n    print(d)\n"
  },
  {
    "path": "itu/algs4/graphs/dijkstra_all_pairs_sp.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\n\"\"\"This module implements a data type for solving the all-pairs shortest paths\nproblem in edge-weighted digraphs where the edge weights are nonnegative.\"\"\"\n\nimport sys\n\nfrom itu.algs4.graphs.dijkstra_sp import DijkstraSP\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\nfrom itu.algs4.stdlib import instream\n\n\nclass DijkstraAllPairsSP:\n    \"\"\"This implementation runs Dijkstra's algorithm from each vertex. The\n    constructor takes time proportional to V (E log V) and uses space\n    proprtional to V2, where V is the number of vertices and E is the number of\n    edges. Afterwards, the dist() and hasPath() methods take constant time and\n    the path() method takes time proportional to the number of edges in the\n    shortest path returned.\n\n    For additional documentation, see Section 4.4 of Algorithms, 4th\n    Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, edge_weighted_digraph):\n        \"\"\"Computes a shortest paths tree from each vertex to to every other\n        vertex in the edge-weighted digraph G.\n\n        :param edge_weighted_digraph: the edge-weighted digraph\n\n        \"\"\"\n        self._all = []\n        for v in range(edge_weighted_digraph.V()):\n            self._all.append(DijkstraSP(edge_weighted_digraph, v))\n\n    def path(self, source, target):\n        \"\"\"Returns a shortest path from source vertex to the target vertex.\n\n        :param source: the source vertex\n        :param target: the destination vertex\n\n        :returns: a shortest path from the source vertex to the target vertex as an iterable of edges,\n                  and None if no such path\n\n        \"\"\"\n        self._validateVertex(source)\n        self._validateVertex(target)\n\n        return self._all[source].path_to(target)\n\n    def has_path(self, source, target):\n        \"\"\"Is there a path from the source vertex to the target vertex?\n\n        :param source: the source vertex\n        :param target: the target vertex\n\n        :returns: True if there is a path from the source to the target, and False otherwise\n\n        \"\"\"\n        return self.dist(source, target) < float(\"inf\")\n\n    def dist(self, source, target):\n        \"\"\"Returns the length of a shortest path from the source vertex to the\n        target vertex.\n\n        :param source: the source vertex\n        :param target: the target vertex\n\n        :returns: the length of a shortest path from the source vertex to the target vertex;\n                  float('inf') if no such path\n\n        \"\"\"\n        self._validateVertex(source)\n        self._validateVertex(target)\n\n        return self._all[source].dist_to(target)\n\n    # throw a ValueError unless 0 <= v < V\n    def _validateVertex(self, v):\n        V = len(self._all)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, (V - 1)))\n\n\nif __name__ == \"__main__\":\n    # Create stream from file or the standard input,\n    # depending on whether a file name was passed.\n    stream = sys.argv[1] if len(sys.argv) > 1 else None\n\n    # Create a DijkstraAllPairsSP data structure\n    g = EdgeWeightedDigraph.from_stream(instream.InStream(stream))\n    dijkstra_all = DijkstraAllPairsSP(g)\n\n    # Print the shortest path distances between all possible pairs of vertices.\n    for source in range(g.V()):\n        for target in range(g.V()):\n            print(dijkstra_all.dist(source, target))\n"
  },
  {
    "path": "itu/algs4/graphs/dijkstra_sp.py",
    "content": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\nfrom itu.algs4.sorting.index_min_pq import IndexMinPQ\nfrom itu.algs4.stdlib.instream import InStream\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass DijkstraSP:\n    \"\"\"The DijkstraSP class represents a data type for solving the single-\n    source shortest paths problem in edge-weighted digraphs where the edge\n    weights are nonnegative.\n\n    This implementation uses Dijkstra's algorithm with a binary heap.\n    The constructor takes time proportional to E log V, where V is the\n    number of vertices and E is the number of edges. Each call to\n    dist_to() and has_path_to() takes constant time. Each call to\n    path_to() takes time proportional to the number of edges in the\n    shortest path returned.\n\n    \"\"\"\n\n    def __init__(self, G, s):\n        \"\"\"Computes a shortest-paths tree from the source vertex s to every\n        other vertex in the edge-weighted digraph G.\n\n        :param G: The edge-weighted digraph\n        :param s: The source vertex\n        :raises IllegalArgumentException: if an edge weight is negative\n        :raises IllegalArgumentException: unless 0 <= s < V\n\n        \"\"\"\n        for e in G.edges():\n            if e.weight() < 0:\n                raise IllegalArgumentException(\"edge {} has negative weight\".format(e))\n        self._dist_to = [float(\"inf\")] * G.V()\n        self._edge_to = [None] * G.V()\n        self._validate_vertex(s)\n        self._dist_to[s] = 0.0\n        self._pq = IndexMinPQ(G.V())\n        self._pq.insert(s, 0.0)\n        while not self._pq.is_empty():\n            v = self._pq.del_min()\n            for e in G.adj(v):\n                self._relax(e)\n\n    def dist_to(self, v):\n        \"\"\"Returns the length of a shortest path from the source vertex s to\n        vertex v.\n\n        :param v: the destination vertex\n        :return: the length of a shortest path from the source vertex s to vertex v\n        :rtype: float\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._dist_to[v]\n\n    def has_path_to(self, v):\n        \"\"\"Returns True if there is a ath from the source vertex s to vertex v.\n\n        :param v: the destination vertex\n        :return: True if there is a path from the source vertex\n        s to vertex v. Otherwise returns False\n        :rtype: bool\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._dist_to[v] < float(\"inf\")\n\n    def path_to(self, v):\n        \"\"\"Returns a shortest path from the source vertex s to vertex v.\n\n        :param v: the destination vertex\n        :return: a shortest path from the source vertex s to vertex v\n        :rtype: collections.iterable[DirectedEdge]\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        e = self._edge_to[v]\n        while e is not None:\n            path.push(e)\n            e = self._edge_to[e.from_vertex()]\n        return path\n\n    def _relax(self, e):\n        \"\"\"Relaxes the edge e and updates the pq if changed.\n\n        :param e: the edge to relax\n\n        \"\"\"\n        v = e.from_vertex()\n        w = e.to_vertex()\n        if self._dist_to[w] > self._dist_to[v] + e.weight():\n            self._dist_to[w] = self._dist_to[v] + e.weight()\n            self._edge_to[w] = e\n            if self._pq.contains(w):\n                self._pq.decrease_key(w, self._dist_to[w])\n            else:\n                self._pq.insert(w, self._dist_to[w])\n\n    def _validate_vertex(self, v):\n        \"\"\"Raises an IllegalArgumentException unless 0 <= v < V.\n\n        :param v: the vertex to be validated\n\n        \"\"\"\n        V = len(self._dist_to)\n        if v < 0 or v >= V:\n            raise IllegalArgumentException(\n                \"vertex {} is not between 0 and {}\".format(v, V - 1)\n            )\n\n\ndef main():\n    \"\"\"Creates an EdgeWeightedDigraph from input file.\n\n    Runs DijkstraSP on the graph with the given source vertex. Prints\n    the shortest path from the source vertex to all other vertices.\n\n    \"\"\"\n    if len(sys.argv) == 3:\n        stream = InStream(sys.argv[1])\n        G = EdgeWeightedDigraph.from_stream(stream)\n        s = int(sys.argv[2])\n        sp = DijkstraSP(G, s)\n        for t in range(G.V()):\n            if sp.has_path_to(t):\n                print(\"{} to {} ({:.2f})  \".format(s, t, sp.dist_to(t)), end=\"\")\n                for e in sp.path_to(t):\n                    print(e, end=\"   \")\n                print()\n            else:\n                print(\"{} to {}         no path\\n\".format(s, t))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/dijkstra_undirected_sp.py",
    "content": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.edge_weighted_graph import EdgeWeightedGraph\nfrom itu.algs4.sorting.index_min_pq import IndexMinPQ\nfrom itu.algs4.stdlib.instream import InStream\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass DijkstraUndirectedSP:\n    \"\"\"The DijkstraSP class represents a data type for solving the single-\n    source shortest paths problem in edge-weighted diagraphs where the edge\n    weights are nonnegative.\n\n    This implementation uses Dijkstra's algorithm with a binary heap.\n    The constructor takes time proportional to E log V, where V is the\n    number of vertices and E is the number of edges. Each call to\n    dist_to() and has_path_to() takes constant time each call to\n    path_to() takes time proportional to the number of edges in the\n    shortest path returned.\n\n    \"\"\"\n\n    def __init__(self, G, s):\n        \"\"\"Computes a shortest-paths tree from the source vertex s to every\n        other vertex in the edge-weighted graph G.\n\n        :param G: the edge-weighted graph\n        :param s: the source vertex\n        :raises IllegalArgumentException: if an edge weight is negative\n        :raises IllegalArgumentException: unless 0 <= s < V\n\n        \"\"\"\n        for e in G.edges():\n            if e.weight() < 0:\n                raise IllegalArgumentException(\"edge {} has negative weight\".format(e))\n\n        self._dist_to = [float(\"inf\")] * G.V()\n        self._edge_to = [None] * G.V()\n        self._dist_to[s] = 0.0\n        self._validate_vertex(s)\n        self._pq = IndexMinPQ(G.V())\n        self._pq.insert(s, 0)\n\n        while not self._pq.is_empty():\n            v = self._pq.del_min()\n            for e in G.adj(v):\n                self._relax(e, v)\n\n    def dist_to(self, v):\n        \"\"\"Returns the length of a shortest path between the source vertex s\n        and vertex v.\n\n        :param v: the destination vertex\n        :return: the length of a shortest path between the source vertex s and\n        the vertex v. float('inf') is not such path\n        :rtype: float\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        return self._dist_to[v]\n\n    def has_path_to(self, v):\n        \"\"\"Returns true if there is a path between the source vertex s and\n        vertex v.\n\n        :param v: the destination vertex\n        :return: True if there is a path between the source vertex\n        s to vertex v. False otherwise\n        :rtype: bool\n\n        \"\"\"\n        return self._dist_to[v] < float(\"inf\")\n\n    def path_to(self, v):\n        \"\"\"Returns a shortest path between the source vertex s and vertex v.\n\n        :param v: the destination vertex\n        :return: a shortest path between the source vertex s and vertex v.\n        None if no such path\n        :rtype: collections.iterable[Edge]\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        if not self.has_path_to(v):\n            return None\n        path = Stack()\n        x = v\n        e = self._edge_to[v]\n        while e is not None:\n            edge = self._edge_to[x]\n            path.push(edge)\n            x = e.other(x)\n            e = self._edge_to[x]\n        return path\n\n    def _validate_vertex(self, v):\n        \"\"\"Raises an IllegalArgumentException unless 0 <= v < V.\n\n        :param v: the vertex to validate\n\n        \"\"\"\n        V = len(self._dist_to)\n        if v < 0 or v >= V:\n            raise IllegalArgumentException(\n                \"vertex {} is not between 0 and {}\".format(v, V - 1)\n            )\n\n    def _relax(self, e, v):\n        \"\"\"Relax edge e and update pq if changed.\n\n        :param e: the edge to relax\n        :param v: the vertex e goes out from\n\n        \"\"\"\n        w = e.other(v)\n        if self._dist_to[v] + e.weight() < self._dist_to[w]:\n            self._dist_to[w] = self._dist_to[v] + e.weight()\n            self._edge_to[w] = e\n            if self._pq.contains(w):\n                self._pq.decrease_key(w, self._dist_to[w])\n            else:\n                self._pq.insert(w, self._dist_to[w])\n\n\ndef main():\n    if len(sys.argv) == 3:\n        stream = InStream(sys.argv[1])\n        G = EdgeWeightedGraph.from_stream(stream)\n        s = int(sys.argv[2])\n        sp = DijkstraUndirectedSP(G, s)\n\n        for t in range(G.V()):\n            if sp.has_path_to(t):\n                print(\"{} to {} ({:.2f})  \".format(s, t, sp.dist_to(t)), end=\"\")\n                for e in sp.path_to(t):\n                    print(e, end=\"   \")\n                print()\n            else:\n                print(\"{} to {}         no path\\n\".format(s, t))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/directed_cycle.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module implements the directed cycle algorithm described in Algorithms,\n4th Edition by Robert Sedgewick and Kevin Wayne. This version works for both\nweighted and unweighted directed graphs, due to Python's duck-typing.\n\nFor more information, see chapter 4.2 of the book.\n\n\"\"\"\n\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.digraph import Digraph\nfrom itu.algs4.stdlib.instream import InStream\n\n\nclass DirectedCycle:\n    \"\"\"The DirectedCycle class represents a data type for determining whether a\n    digraph has a directed cycle. The hasCycle operation determines whether the\n    digraph has a directed cycle and, and of so, the cycle operation returns\n    one.\n\n    This implementation uses depth-first search. The constructor takes time proportional\n    to V + E (in the worst case), where V is the number of vertices and E is the\n    number of edges. Afterwards, the hasCycle operation takes constant time; the\n    cycle operation takes time proportional to the length of the cycle.\n\n    See Topological to compute a topological order if the digraph is acyclic.\n\n    For additional documentation, see Section 4.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, digraph):\n        \"\"\"Determines whether the digraph has a directed cycle and, if so,\n        finds such a cycle.\n\n        :digraph: the digraph\n\n        \"\"\"\n        self._cycle = None\n        self._on_stack = [False] * digraph.V()\n        self._edge_to = [0] * digraph.V()\n        self._marked = [False] * digraph.V()\n        for v in range(digraph.V()):\n            if not self._marked[v]:\n                self._dfs(digraph, v)\n\n    # check that algorithm computes either the topological order or finds a directed cycle\n    def _dfs(self, digraph, v):\n        self._on_stack[v] = True\n        self._marked[v] = True\n        for w in digraph.adj(v):\n            # short circuit if directed cycle found\n            if self.has_cycle():\n                return\n            # found new vertex, so recur\n            elif not self._marked[w]:\n                self._edge_to[w] = v\n                self._dfs(digraph, w)\n            # trace back directed cycle\n            elif self._on_stack[w]:\n                self._cycle = Stack()\n                x = v\n                while x != w:\n                    self._cycle.push(x)\n                    x = self._edge_to[x]\n                self._cycle.push(w)\n                self._cycle.push(v)\n\n        self._on_stack[v] = False\n\n    def has_cycle(self):\n        \"\"\"Does the digraph have a directed cycle?\n\n        :returns: true if there is a cycle, false otherwise\n\n        \"\"\"\n        return self._cycle is not None\n\n    def cycle(self):\n        \"\"\"Returns a directed cycle if the digraph has a directed cycle, and\n        null otherwise.\n\n        :returns: a directed cycle (as an iterable) if the digraph has a directed cycle, and null otherwise\n\n        \"\"\"\n        return self._cycle\n\n\nif __name__ == \"__main__\":\n    # Create stream from file or the standard input,\n    # depending on whether a file name was passed.\n    stream = sys.argv[1] if len(sys.argv) > 1 else None\n\n    d = Digraph.from_stream(InStream(stream))\n\n    cyc = DirectedCycle(d)\n    print(cyc.cycle())\n"
  },
  {
    "path": "itu/algs4/graphs/directed_dfs.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport sys\n\nfrom itu.algs4.fundamentals.bag import Bag\nfrom itu.algs4.graphs.digraph import Digraph\nfrom itu.algs4.stdlib.instream import InStream\n\n\nclass DirectedDFS:\n    \"\"\"The DirectedDFS class represents a data type for determining the vertices\n    reachable from a given source vertex s (or a set of source vertices) in a\n    digraph. For versions that find the paths, see DepthFirstDirectedPaths and\n    BreadthFirstDirectedPaths.\n\n    This implementation uses depth-first search.\n    The constructor takes time proportional to V + E (in the worst case),\n    where V is the number of vertices and E is the number of edges.\n\n    For additional documentation, see Section 4.2 of Algorithms,\n    4th Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, G, *s):\n        \"\"\"Computes the vertices in digraph G that are reachable from the source\n        vertex s.\n\n        :param G: the digraph\n        :param s: the source vertex/vertices\n        :raises ValueError: unless 0 <= s_ < V for every s_ in s\n\n        \"\"\"\n        self.marked = [False for i in range(0, G.V())]\n        self.reachables = 0\n        for s_ in s:\n            self._validate_vertex(s_)\n            self._dfs(G, s_)\n\n    def _dfs(self, G, v):\n        self.reachables += 1\n        self.marked[v] = True\n        for w in G.adj(v):\n            if not self.marked[w]:\n                self._dfs(G, w)\n\n    def is_marked(self, v):\n        \"\"\"Is there a directed path from the source vertex and vertex v?\n\n        :param v: the vertex\n        :returns: True if there is a directed\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self.marked[v]\n\n    def count(self):\n        \"\"\"\n        Returns the number of vertices reachable from the source vertex\n        (or source vertices)\n        :returns: the number of vertices reachable from the source vertex\n        (or source vertices)\n        \"\"\"\n        return self.reachables\n\n    def _validate_vertex(self, v):\n        # Raise a ValueError unless 0 <= v < V\n        V = len(self.marked)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\ndef main():\n    \"\"\"Unit tests the DirectedDFS data type.\"\"\"\n    G = Digraph.from_stream(InStream(None))\n    sources = Bag()\n    for i in range(1, len(sys.argv)):\n        s = int(sys.argv[i])\n        sources.add(s)\n\n    dfs = DirectedDFS(G, *sources)\n    print(\"Reachable vertices:\")\n    for v in range(0, G.V()):\n        if dfs.is_marked(v):\n            print(v, end=\" \")\n    print()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/directed_edge.py",
    "content": "import math\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass DirectedEdge:\n    \"\"\"The DirectedEdge class represents a weighted edge in an\n    EdgeWeightedDigraph.\n\n    Each edge consists of two integers (naming the two vertices) and a\n    real-value weight. The data type provides methods for accessing the\n    two endpoints of the directed edge and the weight.\n\n    \"\"\"\n\n    def __init__(self, v, w, weight):\n        \"\"\"Initializes a directed edge from vertex v to vertex w with the given\n        weight.\n\n        :param v: the tail vertex\n        :param w: the head vertex\n        :param weight: the weight of the directed edge\n        :raises IllegalArgumentException: if either v or w is a negative integer\n        :raises IllegalArgumentException: if weight is NaN\n\n        \"\"\"\n        if v < 0:\n            raise IllegalArgumentException(\"Vertex names must be nonnegative integers\")\n        if w < 0:\n            raise IllegalArgumentException(\"Vertex names must be nonnegative integers\")\n        if math.isnan(weight):\n            raise IllegalArgumentException(\"Weight is NaN\")\n        self._v = v\n        self._w = w\n        self._weight = weight\n\n    def from_vertex(self):\n        \"\"\"Returns the tail vertex of the directed edge.\n\n        :return: the tail vertex of the directed edge\n        :rtype: int\n\n        \"\"\"\n        return self._v\n\n    def to_vertex(self):\n        \"\"\"Returns the head vertex of the directed edge.\n\n        :return: the head vertex of the directed edge\n        :rtype: int\n\n        \"\"\"\n        return self._w\n\n    def weight(self):\n        \"\"\"Returns the weight of the directed edge.\n\n        :return: the weight of the directed edge\n        :rtype: float\n\n        \"\"\"\n        return self._weight\n\n    def __repr__(self):\n        \"\"\"Returns a string representation of the directed edge.\n\n        :return: a string representation of the directed edge\n        :rtype: str\n\n        \"\"\"\n        return \"{}->{} {:5.2f}\".format(self._v, self._w, self._weight)\n\n\ndef main():\n    \"\"\"Creates a directed edge and prints it.\n\n    :return:\n\n    \"\"\"\n    e = DirectedEdge(12, 34, 5.67)\n    print(e)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/edge.py",
    "content": "import math\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass Edge:\n    \"\"\"The Edge class represents a weighted edge in an EdgeWeightedGraph.\n\n    Each edge consists of two integers (naming the two vertices) and a\n    real-value weight. The data type provides methods for accessing the\n    two endpoints of the edge and the weight. The natural order for this\n    data type is by ascending order of weight.\n\n    \"\"\"\n\n    def __init__(self, v, w, weight):\n        \"\"\"Initializes an edge between vertices v and w of the given weight.\n\n        :param v: one vertex\n        :param w: the other vertex\n        :param weight: the weight of this edge\n        :raises IllegalArgumentException: if either v or w is a negative integer\n        :raises IllegalArgumentException: if weight is NaN\n\n        \"\"\"\n        if v < 0:\n            raise IllegalArgumentException(\"vertex index must be a nonnegative integer\")\n        if w < 0:\n            raise IllegalArgumentException(\"vertex index must be a nonnegative integer\")\n        if math.isnan(weight):\n            raise IllegalArgumentException(\"Weight is NaN\")\n        self._v = v\n        self._w = w\n        self._weight = weight\n\n    def weight(self):\n        \"\"\"Returns the weight of this edge.\n\n        :return: the weight of this edge\n        :rtype: float\n\n        \"\"\"\n        return self._weight\n\n    def either(self):\n        \"\"\"Returns either endpoint of this edge.\n\n        :return: either endpoint of this edge\n        :rtype: int\n\n        \"\"\"\n        return self._v\n\n    def other(self, vertex):\n        \"\"\"Returns the endpoint of this edge that is different from the given\n        vertex.\n\n        :param vertex: one endpoint of this edge\n        :return: the other endpoint of this edge\n        :rtype: int\n        :raises IllegalArgumentException: if the vertex is not one of the endpoints of this edge\n\n        \"\"\"\n        if vertex == self._v:\n            return self._w\n        elif vertex == self._w:\n            return self._v\n        else:\n            raise IllegalArgumentException(\"Illegal endpoint\")\n\n    def __lt__(self, other):\n        \"\"\"Checks if this edge has smaller weight than other edge.\n\n        :param other: the edge to compare with\n        :return: True if weight of this edge is less than weight of other edge otherwise returns False\n\n        \"\"\"\n        return self.weight() < other.weight()\n\n    def __gt__(self, other):\n        \"\"\"Checks if this edge has greater weight than other edge.\n\n        :param other: the edge to compare with\n        :return: True if weight of this edge is greater than weight of other edge otherwise returns False\n\n        \"\"\"\n        return self.weight() > other.weight()\n\n    def __repr__(self):\n        \"\"\"Returns a string representation of this edge.\n\n        :return: a string representation of this edge\n\n        \"\"\"\n        return \"{}-{} {:.5f}\".format(self._v, self._w, self._weight)\n\n\ndef main():\n    \"\"\"Creates an edge and prints it.\"\"\"\n    e = Edge(12, 34, 5.67)\n    print(e)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/edge_weighted_digraph.py",
    "content": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.bag import Bag\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.directed_edge import DirectedEdge\nfrom itu.algs4.stdlib.instream import InStream\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass EdgeWeightedDigraph:\n    \"\"\"The EdgeWeightedDigraph class represents an edge-weighted digraph of\n    vertices named 0 through V-1, where each directed edge is of type\n    DirectedEdge and has a real-valued weight.\n\n    It supports the following two primary operations: add a directed\n    edge to the digraph and iterate over all edges incident from a given\n    vertex. it also provides methods for returning the number of\n    vertices V and the number of edges E. Parallel edges and self-loops\n    are permitted. This implementation uses an adjacency-lists\n    representation, which is a vertex-indexed array of Bag objects. All\n    operations take constant time (in the worst case) except iterating\n    over the edges incident from a given vertex, which takes time\n    proportional to the number of such edges.\n\n    \"\"\"\n\n    def __init__(self, V):\n        \"\"\"Initializes an empty edge-weighted digraph with V vertices and 0\n        edges.\n\n        :param V: the number of vertices\n        :raises IllegalArgumentException: if V < 0\n\n        \"\"\"\n        if V < 0:\n            raise IllegalArgumentException(\n                \"Number of vertices in a Digraph must be nonnegative\"\n            )\n        self._V = V\n        self._E = 0\n        self._indegree = [0] * V\n        self._adj = [None] * V\n        for v in range(V):\n            self._adj[v] = Bag()\n\n    @staticmethod\n    def from_graph(G):\n        \"\"\"Initializes a new edge-weighted digraph that is a deep copy of G.\n\n        :param G: the edge-weighted digraph to copy\n        :return: a copy of graph G\n        :rtype: EdgeWeightedDigraph\n\n        \"\"\"\n        g = EdgeWeightedDigraph(G.V())\n        g._E = G.E()\n        for v in range(G.V()):\n            g._indegree[v] = G.indegree(v)\n            reverse = Stack()\n            for e in G.adj(v):\n                reverse.push(e)\n            for e in reverse:\n                g._adj[v].add(e)\n        return g\n\n    @staticmethod\n    def from_stream(stream):\n        \"\"\"Initializes an edge-weighted digraph from the specified input\n        stream. The format is the number of vertices V, followed by the number\n        of edges E, followed by E pairs of vertices and edge weights, with each\n        entry seperated by whitespace.\n\n        :param stream: the input stream\n\n        :raises IllegalArgumentException: if the endpoints of any edge are not in prescribed range\n        :raises IllegalArgumentException: if the number of vertices or edges is negative\n        :return: the edge-weighted digraph\n        :rtype: EdgeWeightedDigraph\n\n        \"\"\"\n        g = EdgeWeightedDigraph(stream.readInt())\n        E = stream.readInt()\n        if g._E < 0:\n            raise IllegalArgumentException(\"Number of edges must be nonnegative\")\n        for _ in range(E):\n            v = stream.readInt()\n            w = stream.readInt()\n            g._validate_vertex(v)\n            g._validate_vertex(w)\n            weight = stream.readFloat()\n            g.add_edge(DirectedEdge(v, w, weight))\n        return g\n\n    def V(self):\n        \"\"\"Returns the number of vertices in this edge-weighted digraph.\n\n        :return: the number of vertices in this edge-weighted digraph\n        :rtype: int\n\n        \"\"\"\n        return self._V\n\n    def E(self):\n        \"\"\"Returns the number of edges in this edge-weighted digraph.\n\n        :return: the number of edges in this edge-weighted digraph\n        :rtype: int\n\n        \"\"\"\n        return self._E\n\n    def _validate_vertex(self, v):\n        \"\"\"Raises an IllegalArgumentException unluess 0 <= v < V.\n\n        :param v: the vertex to validate\n\n        \"\"\"\n        if v < 0 or v >= self._V:\n            raise IllegalArgumentException(\n                \"vertex {} is not between 0 and {}\".format(v, self._V - 1)\n            )\n\n    def add_edge(self, e):\n        \"\"\"Adds the directed edge e to this edge-weighted digraph.\n\n        :param e: the edge\n        :raises IllegalArgumentException: unless endpoints of edge are between 0 and V-1\n\n        \"\"\"\n        v = e.from_vertex()\n        w = e.to_vertex()\n        self._validate_vertex(v)\n        self._validate_vertex(w)\n        self._adj[v].add(e)\n        self._indegree[w] += 1\n        self._E += 1\n\n    def adj(self, v):\n        \"\"\"Returns the directed edges incident from vertex v.\n\n        :param v: the vertex\n        :return: the directed edges incident from vertex v.\n        :rtype: collections.iterable[DirectedEdge]\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._adj[v]\n\n    def outdegree(self, v):\n        \"\"\"Returns the number of directed edges incident from vertex v. This is\n        known as the outdegree of vertex v.\n\n        :param v: the vertex\n        :return: the outdegree of vertex v\n        :rtype: int\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._adj[v].size()\n\n    def indegree(self, v):\n        \"\"\"Returns the number of directed edges incident to vertex v. This is\n        known as the indegree of vertex v.\n\n        :param v: the vertex\n        :return: the indegree of vertex v\n        :rtype: int\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._indegree[v]\n\n    def edges(self):\n        \"\"\"Returns all directed edges in this edge-weighted digraph.\n\n        :return: all edges in this edge-weighted digraph\n        :rtype: collections.iterable[DirectedEdge]\n\n        \"\"\"\n        edges = Bag()\n        for v in range(self._V):\n            for e in self._adj[v]:\n                edges.add(e)\n        return edges\n\n    def __repr__(self):\n        \"\"\"Returns a string representation of this edge-weighted digraph.\n\n        :return: the number of vertices V, followed by the number of edges E,\n        followed by the V adjacency lists of edges.\n        :rtype: str\n\n        \"\"\"\n        s = [\"{} {} \\n\".format(self._V, self._E)]\n        for v in range(self._V):\n            s.append(\"{}: \".format(v))\n            for e in self._adj[v]:\n                s.append(\"{}  \".format(e))\n            s.append(\"\\n\")\n        return \"\".join(s)\n\n\ndef main():\n    \"\"\"Creates an edge-weighted digraph from the given input file and prints\n    it.\"\"\"\n    if len(sys.argv) > 1:\n        stream = InStream(sys.argv[1])\n        G = EdgeWeightedDigraph.from_stream(stream)\n        print(G)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/edge_weighted_directed_cycle.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.directed_edge import DirectedEdge\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\n\n# Execution:    python edge_weighted_directed_cycle V E F\n# Finds a directed cycle in an edge-weighted digraph.\n# Runs in O(E + V) time.\n\n\"\"\"\n    The EdgeWeightedDirectedCycle class represents a data type for\n    determining whether an edge-weighted digraph has a directed cycle.\n    The hasCycle operation determines whether the edge-weighted\n    digraph has a directed cycle and, if so, the cycle operation\n    returns one.\n    This implementation uses depth-first search.\n    The constructor takes time proportional to V + E\n    (in the worst case),\n    where V is the number of vertices and E is the number of edges.\n    Afterwards, the hasCycle operation takes constant time;\n    the cycle operation takes time proportional\n    to the length of the cycle.\n\"\"\"\n\n\nclass EdgeWeightedDirectedCycle:\n    \"\"\"Determines whether the edge-weighted digraph G has a directed cycle and,\n    if so, finds such a cycle.\n\n    :param G the edge-weighted digraph\n\n    \"\"\"\n\n    def __init__(self, G):\n        self._marked = [False] * G.V()  # marked[v] = has vertex v been marked?\n        self._edgeTo = [None] * G.V()  # edgeTo[v] = previous DirectedEdge on path to v\n        self._onStack = [False] * G.V()  # onStack[v] = is vertex on the stack?\n        self._cycle = None  # directed cycle (or None if no such cycle)\n\n        for v in range(G.V()):\n            if not self._marked[v]:\n                self._dfs(G, v)\n\n        # check that digraph has a cycle\n        assert self._check()\n\n    # check that algorithm computes either the topological order or finds a directed cycle\n    def _dfs(self, G, v):\n        self._onStack[v] = True\n        self._marked[v] = True\n        for e in G.adj(v):\n            w = e.to_vertex()\n\n            # short circuit if directed cycle found\n            if self._cycle is not None:\n                return\n\n            # found new vertex, so recur\n            elif not self._marked[w]:\n                self._edgeTo[w] = e\n                self._dfs(G, w)\n\n            # trace back directed cycle\n            elif self._onStack[w]:\n                self._cycle = Stack()\n                f = e\n                while f.from_vertex() != w:\n                    self._cycle.push(f)\n                    f = self._edgeTo[f.from_vertex()]\n\n                self._cycle.push(f)\n                return\n        self._onStack[v] = False\n\n    # Does the edge-weighted digraph have a directed cycle?\n    # @return True if the edge-weighted digraph has a directed cycle,\n    # False otherwise\n    def has_cycle(self):\n        return self._cycle is not None\n\n    # Returns a directed cycle if the edge-weighted digraph has a directed cycle,\n    # and None otherwise.\n    # @return a directed cycle (as an iterable) if the edge-weighted digraph\n    #    has a directed cycle, and None otherwise\n    def cycle(self):\n        return self._cycle\n\n    # certify that digraph is either acyclic or has a directed cycle\n    def _check(self):\n\n        # edge-weighted digraph is cyclic\n        if self.has_cycle():\n            # verify cycle\n            first = None\n            last = None\n            for e in self.cycle():\n                if first is None:\n                    first = e\n                if last is not None:\n                    if last.to_vertex() != e.from_vertex():\n                        print(\"cycle edges {} and {} not incident\".format(last, e))\n                        return False\n                last = e\n\n            if last.to_vertex() != first.from_vertex():\n                print(\"cycle edges {} and {} not incident\".format(last, first))\n                return False\n\n        return True\n\n\ndef main(args):\n    from itu.algs4.stdlib import stdrandom as stdrandom\n\n    # create random DAG with V vertices and E edges; then add F random edges\n    V = int(args[0])\n    E = int(args[1])\n    F = int(args[2])\n    G = EdgeWeightedDigraph(V)\n    vertices = [i for i in range(V)]\n    stdrandom.shuffle(vertices)\n    for _ in range(E):\n        while True:\n            v = stdrandom.uniformInt(0, V)\n            w = stdrandom.uniformInt(0, V)\n            if v >= w:\n                break\n        weight = stdrandom.uniformFloat(0.0, 1.0)\n        G.add_edge(DirectedEdge(v, w, weight))\n\n    # add F extra edges\n    for _ in range(F):\n        v = stdrandom.uniformInt(0, V)\n        w = stdrandom.uniformInt(0, V)\n        weight = stdrandom.uniformFloat(0.0, 1.0)\n        G.add_edge(DirectedEdge(v, w, weight))\n\n    print(G)\n\n    # find a directed cycle\n    finder = EdgeWeightedDirectedCycle(G)\n    if finder.has_cycle():\n        print(\"Cycle: \")\n        for e in finder.cycle():\n            print(\"{}  \".format(e), end=\"\")\n        print()\n    # or give topologial sort\n    else:\n        print(\"No directed cycle\")\n\n\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n"
  },
  {
    "path": "itu/algs4/graphs/edge_weighted_directed_cycle_anton.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module implements the directed cycle algorithm for EdgeWeightedDigraphs\ndescribed in Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. This\nversion works for both weighted and unweighted directed graphs, due to Python's\nduck-typing.\n\nFor more information, see chapter 4.2 of the book.\n\n\"\"\"\n\nimport sys\n\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.edge_weighted_digraph import EdgeWeightedDigraph\nfrom itu.algs4.stdlib import instream\n\n\nclass EdgeWeightedDirectedCycle:\n    \"\"\"The EdgeWeightedDirectedCycle class represents a data type for\n    determining whether edge-weighted digraph has a directed cycle. The\n    hasCycle operation determines whether the edge-weighted digraph has a\n    directed cycle and, if so, the cycle operation returns one.\n\n    This implementation uses depth-first search. The constructor takes time proportional to\n    V + E (in the worst case), where V is the number of vertices and E is the number of edges.\n    Afterwards, the hasCycle operation takes constant time; the cycle operation takes time\n    proportional to the length of the cycle.\n\n    See Topological to compute a topological order if the edge-weighted digraph is acyclic.\n\n    For additional documentation, see Section 4.4 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, edge_weighted_digraph):\n        \"\"\"Determines whether the edge weighted digraph has a directed cycle\n        and, if so, finds such a cycle.\n\n        :digraph: the digraph\n\n        \"\"\"\n        self._cycle = None\n        self._on_stack = [False] * edge_weighted_digraph.V()\n        self._edge_to = [None] * edge_weighted_digraph.V()\n        self._marked = [False] * edge_weighted_digraph.V()\n        for v in range(edge_weighted_digraph.V()):\n            if not self._marked[v]:\n                self._dfs(edge_weighted_digraph, v)\n\n    # check that algorithm computes either the topological order or finds a directed cycle\n    def _dfs(self, graph, v):\n        self._on_stack[v] = True\n        self._marked[v] = True\n        for edge in graph.adj(v):\n            w = edge.to_vertex()\n\n            # short circuit if directed cycle found\n            if self.has_cycle():\n                return\n            # found new vertex, so recur\n            elif not self._marked[w]:\n                self._edge_to[w] = edge\n                self._dfs(graph, w)\n            # trace back directed cycle\n            elif self._on_stack[w]:\n                self._cycle = Stack()\n                f = edge\n                while f.from_vertex() != w:\n                    self._cycle.push(f)\n                    f = self._edge_to[f.from_vertex()]\n                self._cycle.push(f)\n\n        self._on_stack[v] = False\n\n    def has_cycle(self):\n        \"\"\"Does the edge weighted digraph have a directed cycle?\n\n        :returns: true if there is a cycle, false otherwise\n\n        \"\"\"\n        return self._cycle is not None\n\n    def cycle(self):\n        \"\"\"Returns a directed cycle if the edge weighted digraph has a directed\n        cycle, and null otherwise.\n\n        :returns: a directed cycle (as an iterable) if the digraph has a directed cycle, and null otherwise\n\n        \"\"\"\n        return self._cycle\n\n\nif __name__ == \"__main__\":\n    # Create stream from file or the standard input,\n    # depending on whether a file name was passed.\n    stream = sys.argv[1] if len(sys.argv) > 1 else None\n\n    d = EdgeWeightedDigraph.from_stream(instream.InStream(stream))\n\n    cyc = EdgeWeightedDirectedCycle(d)\n    print(cyc.cycle())\n"
  },
  {
    "path": "itu/algs4/graphs/edge_weighted_graph.py",
    "content": "import sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.bag import Bag\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.edge import Edge\nfrom itu.algs4.stdlib.instream import InStream\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass EdgeWeightedGraph:\n    \"\"\"The EdgeWeightedGraph class represents an edge-weighted graph of\n    vertices named 0 through V-1, where each undirected edge is of type Edge\n    and has a real-valued weight.\n\n    It supports the following two primary operations: add an edge to the\n    graph, iterate over all of the edges incident to a vertex. It also\n    provides methods for returning the number of vertices V and the\n    number of edges E. Parallel edges and self-loops are permitted. By\n    convention, a self-loop v-v appears in the adjacency list of v twice\n    and contributes two to the degree of v. This implementation uses an\n    adjacency-list representation, which is a vertex-indexed array of\n    Bag objects. All operations take constant time (in the worst case)\n    except iterating over the edges incident to a given vertex, which\n    takes time proportional to the number of such edges.\n\n    \"\"\"\n\n    def __init__(self, V):\n        \"\"\"Initializes an empty edge-weighted graph with V vertices and 0\n        edges.\n\n        :param V: the number of vertices\n        :raises IllegalArgumentException: if V < 0\n\n        \"\"\"\n        if V < 0:\n            raise IllegalArgumentException(\"Number of vertices must be nonnegative\")\n        self._V = V\n        self._E = 0\n        self._adj = [None] * V\n        for v in range(V):\n            self._adj[v] = Bag()\n\n    @staticmethod\n    def from_graph(G):\n        \"\"\"Initializes a new edge-weighted graph that is a deep copy of G.\n\n        :param G: the edge-weighted graph to copy\n        :return: the copy of the graph edge-weighted graph G\n        :rtype: EdgeWeightedGraph\n\n        \"\"\"\n        g = EdgeWeightedGraph(G.V())\n        g._E = G.E()\n        for v in range(G.V()):\n            reverse = Stack()\n            for e in G.adj(v):\n                reverse.push(e)\n            for e in reverse:\n                g._adj[v].add(e)\n        return g\n\n    @staticmethod\n    def from_stream(stream):\n        \"\"\"Initializes an edge-weighted graph from an input stream. The format\n        is the number of vertices V, followed by the number of edges E,\n        followed by E pairs of vertices and edge weights, with each entry\n        separated by whitespace.\n\n        :param stream: the input stream\n        :raises IllegalArgumentException: if the endpoints of any edge are not in prescribed range\n        :raises IllegalArgumentException: if the number of vertices or edges is negative\n        :return: the edge-weighted graph\n        :rtype: EdgeWeightedGraph\n\n        \"\"\"\n        g = EdgeWeightedGraph(stream.readInt())\n        E = stream.readInt()\n        if E < 0:\n            raise IllegalArgumentException(\"Number of edges must be nonnegative\")\n        for _ in range(E):\n            v = stream.readInt()\n            w = stream.readInt()\n            g._validate_vertex(v)\n            g._validate_vertex(w)\n            weight = stream.readFloat()\n            e = Edge(v, w, weight)\n            g.add_edge(e)\n        return g\n\n    def add_edge(self, e):\n        \"\"\"Adds the undirected edge e to this edge-weighted graph.\n\n        :param e: the edge\n\n        \"\"\"\n        v = e.either()\n        w = e.other(v)\n        self._validate_vertex(v)\n        self._validate_vertex(w)\n        self._adj[v].add(e)\n        self._adj[w].add(e)\n        self._E += 1\n\n    def adj(self, v):\n        \"\"\"Returns the edges incident on vertex v.\n\n        :param v: the vertex\n        :return: the edges incident on vertex v\n        :rtype: collections.iterable[Edge]\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._adj[v]\n\n    def V(self):\n        \"\"\"Returns the number of vertices in this edge-weighted graph.\n\n        :return: the number of vertices in this edge-weighted graph\n        :rtype: int\n\n        \"\"\"\n        return self._V\n\n    def E(self):\n        \"\"\"Returns the number of edges in this edge-weighted graph.\n\n        :return: the number of edges in this edge-weighted graph\n        :rtype: int\n\n        \"\"\"\n        return self._E\n\n    def degree(self, v):\n        \"\"\"Returns the degree of vertex v.\n\n        :param v: the vertex\n        :return: the degree of vertex v\n        :rtype: int\n        :raises IllegalArgumentException: unless 0 <= v < V\n\n        \"\"\"\n        self._validate_vertex(v)\n        return self._adj[v].size()\n\n    def edges(self):\n        \"\"\"Returns all edges in this edge-weighted graph.\n\n        :return: all edges in this edge-weighted graph\n\n        \"\"\"\n        edges = Bag()\n        for v in range(self._V):\n            self_loops = 0\n            for e in self.adj(v):\n                if e.other(v) > v:\n                    edges.add(e)\n                elif e.other(v) is v:\n                    if self_loops % 2 == 0:\n                        edges.add(e)\n                    self_loops += 1\n        return edges\n\n    def _validate_vertex(self, v):\n        \"\"\"Raises an IllegalArgumentException unless 0 <= v < V.\n\n        :param v: the vertex to be validated\n\n        \"\"\"\n        if v < 0 or v >= self._V:\n            raise IllegalArgumentException(\n                \"vertex {} is not between 0 and {}\".format(v, self._V - 1)\n            )\n\n    def __repr__(self):\n        \"\"\"Returns a string representation of the edge-weighted graph.\n\n        This method takes time proportional to E + V.\n        :return: the number of vertices, followed by the number of edges,\n        followed by the V adjacency lists of edges\n\n        \"\"\"\n        s = [\"{} {} \\n\".format(self._V, self._E)]\n        for v in range(self._V):\n            s.append(\"{}: \".format(v))\n            for e in self._adj[v]:\n                s.append(\"{}: \".format(e))\n            s.append(\"\\n\")\n        return \"\".join(s)\n\n\ndef main():\n    \"\"\"Creates an edge-weighted graph from the given input file and prints\n    it.\"\"\"\n    if len(sys.argv) > 1:\n        stream = InStream(sys.argv[1])\n        G = EdgeWeightedGraph.from_stream(stream)\n        print(G)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/graph.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.bag import Bag\nfrom itu.algs4.fundamentals.stack import Stack\n\n\nclass Graph:\n    \"\"\"The Graph class represents an undirected graph of vertices.\n\n    named 0 through V - 1.\n    It supports the following two primary operations: add an edge to the graph,\n    iterate over all of the vertices adjacent to a vertex. It also provides\n    methods for returning the number of vertices V and the number\n    of edges E. Parallel edges and self-loops are permitted.\n    By convention, a self-loop v-v appears in the\n    adjacency list of v twice and contributes two to the degree\n    of v.\n\n    This implementation uses an adjacency-lists representation, which\n    is a vertex-indexed array of Bag objects.\n    All operations take constant time (in the worst case) except\n    iterating over the vertices adjacent to a given vertex, which takes\n    time proportional to the number of such vertices.\n\n    \"\"\"\n\n    def __init__(self, V):\n        \"\"\"Initializes an empty graph with V vertices and 0 edges. param V the\n        number of vertices.\n\n        :param V: number of vertices\n        :raises: ValueError if V < 0\n\n        \"\"\"\n        if V < 0:\n            raise ValueError(\"Number of vertices must be nonnegative\")\n        self._V = V  # number of vertices\n        self._E = 0  # number of edges\n        self._adj = []  # adjacency lists\n\n        for _ in range(V):\n            self._adj.append(Bag())  # Initialize all lists to empty bags.\n\n    @staticmethod\n    def from_stream(stream):\n        \"\"\"Initializes a graph from the specified input stream. The format is\n        the number of vertices V, followed by the number of edges E, followed\n        by E pairs of vertices, with each entry separated by whitespace.\n\n        :param stream: the input stream\n        :returns: new graph from stream\n        :raises ValueError: if the endpoints of any edge are not in prescribed range\n        :raises ValueError: if the number of vertices or edges is negative\n        :raises ValueError: if the input stream is in the wrong format\n\n        \"\"\"\n        V = stream.readInt()  # read V\n        if V < 0:\n            raise ValueError(\"Number of vertices must be nonnegative\")\n        g = Graph(V)  # construct this graph\n        E = stream.readInt()  # read E\n        if E < 0:\n            raise ValueError(\"Number of edges in a Graph must be nonnegative\")\n        for _ in range(E):\n            # Add an edge\n            v = stream.readInt()  # read a vertex,\n            w = stream.readInt()  # read another vertex,\n            g._validateVertex(v)\n            g._validateVertex(w)\n            g.add_edge(v, w)  # and add edge connecting them.\n        return g\n\n    @staticmethod\n    def from_graph(G):\n        \"\"\"Initializes a new graph that is a deep copy of G.\n\n        :param G: the graph to copy\n        :returns: copy of G\n\n        \"\"\"\n        g = Graph(G.V())\n        g._E = G.E()\n        for v in range(G.V()):\n            # reverse so that adjacency list is in same order as original\n            reverse = Stack()\n            for w in G._adj[v]:\n                reverse.push(w)\n            for w in reverse:\n                g._adj[v].add(w)\n\n    def V(self):\n        \"\"\"Returns the number of vertices in this graph.\n\n        :returns: the number of vertices in this graph.\n\n        \"\"\"\n        return self._V\n\n    def E(self):\n        \"\"\"Returns the number of edges in this graph.\n\n        :returns: the number of edges in this graph.\n\n        \"\"\"\n        return self._E\n\n    def _validateVertex(self, v):\n        # throw a ValueError unless 0 <= v < V\n        if v < 0 or v >= self._V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, self._V))\n\n    def add_edge(self, v, w):\n        \"\"\"Adds the undirected edge v-w to this graph.\n\n        :param v: one vertex in the edge\n        :param w: the other vertex in the edge\n        :raises ValueError: unless both 0 <= v < V and 0 <= w < V\n\n        \"\"\"\n        self._adj[v].add(w)  # add w to v's list\n        self._adj[w].add(v)  # add v to w's list\n        self._E += 1\n\n    def adj(self, v):\n        \"\"\"Returns the vertices adjacent to vertex v.\n\n        :param v: the vertex\n        :returns: the vertices adjacent to vertex v, as an iterable\n        :raises ValueError: unless  0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._adj[v]\n\n    def degree(self, v):\n        \"\"\"Returns the degree of vertex v.\n\n        :param v: the vertex\n        :returns: the degree of vertex v\n        :raises ValueError:  unless 0 <= v < V\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._adj[v].size()\n\n    def __repr__(self):\n        \"\"\"Returns a string representation of this graph.\n\n        :returns: the number of vertices V, followed by the number of edges E,\n                    followed by the V adjacency lists\n\n        \"\"\"\n        s = [\"{} vertices, {} edges\\n\".format(self._V, self._E)]\n        for v in range(self._V):\n            s.append(\"%d : \" % (v))\n            for w in self._adj[v]:\n                s.append(\"%d \" % (w))\n            s.append(\"\\n\")\n\n        return \"\".join(s)\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = Graph.from_stream(In)\n    stdio.writeln(G)\n"
  },
  {
    "path": "itu/algs4/graphs/kosaraju_sharir_scc.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"\n *  Execution:    python kosaraju_sharir_scc.py filename.txt\n *  Dependencies: Digraph TransitiveClosure InStream DepthFirstOrder\n *  Data files:   https:#algs4.cs.princeton.edu/42digraph/tinyDG.txt\n *                https:#algs4.cs.princeton.edu/42digraph/mediumDG.txt\n *                https:#algs4.cs.princeton.edu/42digraph/largeDG.txt\n *\n *  Compute the strongly-connected components of a digraph using the\n *  Kosaraju-Sharir algorithm.\n *\n *  Runs in O(E + V) time.\n *\n *  % python kosaraju_sharir_scc.py tinyDG.txt\n *  5 strong components\n *  1\n *  0 2 3 4 5\n *  9 10 11 12\n *  6 8\n *  7\n *\n\"\"\"\nimport sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.graphs.depth_first_order import DepthFirstOrder\nfrom itu.algs4.graphs.digraph import Digraph\nfrom itu.algs4.graphs.transitive_closure import TransitiveClosure\nfrom itu.algs4.stdlib.instream import InStream\n\n\nclass KosarajuSharirSCC:\n\n    \"\"\"\n    * Computes the strong components of the digraph G.\n    * @param G the digraph\n    \"\"\"\n\n    def __init__(self, G):\n        self._marked = [False] * G.V()  # marked[v] = has vertex v been visited?\n        self._id = [0] * G.V()  # id[v] = id of strong component containing v\n        self._count = 0  # number of strongly-connected components\n\n        # compute reverse postorder of reverse graph\n        dfo = DepthFirstOrder(G.reverse())\n\n        # run DFS on G, using reverse postorder to guide calculation\n        for v in dfo.reverse_post():\n            if not self._marked[v]:\n                self._dfs(G, v)\n                self._count += 1\n\n        # check that id[] gives strong components\n        assert self._check(G)\n\n    # DFS on graph G\n    def _dfs(self, G, v):\n        self._marked[v] = True\n        self._id[v] = self._count\n        for w in G.adj(v):\n            if not self._marked[w]:\n                self._dfs(G, w)\n\n    \"\"\"\n     * Returns the number of strong components.\n     * @return the number of strong components\n     \"\"\"\n\n    def count(self):\n        return self._count\n\n    \"\"\"\n     * Are vertices v and w in the same strong component?\n     * @param  v one vertex\n     * @param  w the other vertex\n     * @return true if vertices v and w are in the same\n     *         strong component, and false otherwise\n     * @throws IllegalArgumentException unless 0 <= v < V\n     * @throws IllegalArgumentException unless 0 <= w < V\n     \"\"\"\n\n    def strongly_connected(self, v, w):\n        self._validate_vertex(v)\n        self._validate_vertex(w)\n        return self._id[v] == self._id[w]\n\n    \"\"\"\n     * Returns the component id of the strong component containing vertex v.\n     * @param  v the vertex\n     * @return the component id of the strong component containing vertex v\n     * @throws IllegalArgumentException unless 0 <= s < V\n     \"\"\"\n\n    def id(self, v):\n        self._validate_vertex(v)\n        return self._id[v]\n\n    # does the id[] array contain the strongly connected components?\n    def _check(self, G):\n        tc = TransitiveClosure(G)\n        for v in range(G.V()):\n            for w in range(G.V()):\n                if self.strongly_connected(v, w) != (\n                    tc.reachable(v, w) and tc.reachable(w, v)\n                ):\n                    return False\n        return True\n\n    # throw an IllegalArgumentException unless 0 <= v < V\n    def _validate_vertex(self, v):\n        V = len(self._marked)\n        if v < 0 or v >= V:\n            raise IllegalArgumentException(\n                \"vertex {} is not between 0 and {}\".format(v, V - 1)\n            )\n\n\ndef main(args):\n    stream = InStream(args[0])\n    G = Digraph.from_stream(stream)\n    scc = KosarajuSharirSCC(G)\n\n    # number of connected components\n    m = scc.count()\n    print(\"{} strong components\".format(m))\n\n    # compute list of vertices in each strong component\n    components = [Queue() for i in range(m)]\n\n    for v in range(G.V()):\n        components[scc.id(v)].enqueue(v)\n\n    # print results\n    for i in range(m):\n        for v in components[i]:\n            print(str(v), end=\" \")\n        print()\n\n\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n"
  },
  {
    "path": "itu/algs4/graphs/kruskal_mst.py",
    "content": "import sys\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.uf import WeightedQuickUnionUF\nfrom itu.algs4.graphs.edge_weighted_graph import EdgeWeightedGraph\nfrom itu.algs4.sorting.min_pq import MinPQ\nfrom itu.algs4.stdlib.instream import InStream\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\nclass KruskalMST:\n    \"\"\"The KruskalMST class represents a data type for computing a minimum\n    spanning tree in an edge-weighted graph.\n\n    The edge weights can be positive, zero, or negative and need not be\n    distinct. If the graph is not connected, it computes a minimum\n    spanning forest, which is the union of minimum spanning trees in\n    each connected component. The weight method returns the weight of a\n    minimum spanning tree and the edges method returns its edges. This\n    implementation uses Kruskal's algorithm and the union-find data\n    type. The constructor takes time proportional to E log E and extra\n    space (not including the graph) proportional to V, where V is the\n    number of vertices and E is the number of edges- Afterwards, the\n    weight method takes constant time and the edges method takes time\n    proportional to V.\n\n    \"\"\"\n\n    def __init__(self, G):\n        \"\"\"Computes a minimum spanning tree (or forest) of an edge-weighted\n        graph.\n\n        :param G: the edge-weighted graph\n\n        \"\"\"\n        self._weight = 0\n        self._mst = Queue()\n        pq = MinPQ()\n\n        for e in G.edges():\n            pq.insert(e)\n\n        uf = WeightedQuickUnionUF(G.V())\n        while not pq.is_empty() and self._mst.size() < G.V() - 1:\n            e = pq.del_min()\n            v = e.either()\n            w = e.other(v)\n            if not uf.connected(v, w):\n                uf.union(v, w)\n                self._mst.enqueue(e)\n                self._weight += e.weight()\n\n    def edges(self):\n        \"\"\"Returns the edges in a minimum spanning tree (or forest).\n\n        :return: the edges in a minimum spanning tree (or forest)\n\n        \"\"\"\n        return self._mst\n\n    def weight(self):\n        \"\"\"Returns the sum of the edge weights in a minimum spanning tree (or\n        forest).\n\n        :return: the sum of the edge weights in a minimum spanning tree (or forest)\n\n        \"\"\"\n        return self._weight\n\n\ndef main():\n    \"\"\"Creates an edge-weighted graph from an input file, runs Kruskal's\n    algorithm on it, and prints the edges of the MST and the sum of the edge\n    weights.\"\"\"\n    if len(sys.argv) > 1:\n        stream = InStream(sys.argv[1])\n        G = EdgeWeightedGraph.from_stream(stream)\n        mst = KruskalMST(G)\n        for e in mst.edges():\n            print(e)\n        print(\"{:.5f}\".format(mst.weight()))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/graphs/lazy_prim_mst.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.uf import UF\nfrom itu.algs4.sorting.min_pq import MinPQ\n\n\nclass LazyPrimMST:\n    \"\"\"The LazyPrimMST class represents a data type for computing a minimum\n    spanning tree in an edge-weighted graph. The edge weights can be positive,\n    zero, or negative and need not be distinct. If the graph is not connected,\n    it computes a minimum spanning forest, which is the union of minimum\n    spanning trees in each connected component. The weight() method returns the\n    weight of a minimum spanning tree and the edges() method returns its edges.\n\n    This implementation uses a lazy version of Prim's algorithm with a\n    binary heap of edges. The constructor takes time proportional to E\n    log E and extra space (not including the graph) proportional to E,\n    where V is the number of vertices and E is the number of edges.\n    Afterwards, the weight() method takes constant time and the edges()\n    method takes time proportional to V.\n\n    \"\"\"\n\n    FLOATING_POINT_EPSILON = 1e-12\n\n    def __init__(self, G):\n        \"\"\"Compute a minimum spanning tree (or forest) of an edge-weighted\n        graph.\n\n        :param G: the edge-weighted graph\n\n        \"\"\"\n        self._weight = 0.0  # total weight of MST\n        self._mst = Queue()  # edges in the MST\n        self._marked = [False] * G.V()  # marked[v] = True if v on tree\n        self._pq = MinPQ()  # edges with one endpoint in tree\n\n        for v in range(G.V()):  # run Prim from all vertices to\n            if not self._marked[v]:\n                self._prim(G, v)  # get a minimum spanning forest\n\n        # check optimality conditions\n        assert self._check(G)\n\n    def _prim(self, G, s):\n        # run Prim's algorithm\n        self._scan(G, s)\n        while not self._pq.is_empty():  # better to stop when mst has V-1 edges\n            e = self._pq.del_min()  # smallest edge on pq\n            v = e.either()  # two endpoints\n            w = e.other(v)\n            assert self._marked[v] or self._marked[w]\n            if (\n                self._marked[v] and self._marked[w]\n            ):  # lazy, both v and w already scanned\n                continue\n            self._mst.enqueue(e)  # add e to MST\n            self._weight += e.weight()\n            if not self._marked[v]:\n                self._scan(G, v)  # v becomes part of tree\n            if not self._marked[w]:\n                self._scan(G, w)  # w becomes part of tree\n\n    def _scan(self, G, v):\n        # add all edges e incident to v onto pq if the other endpoint has not yet been scanned\n        assert not self._marked[v]\n        self._marked[v] = True\n        for e in G.adj(v):\n            if not self._marked[e.other(v)]:\n                self._pq.insert(e)\n\n    def edges(self):\n        \"\"\"Returns the edges in a minimum spanning tree (or forest).\n\n        :returns: the edges in a minimum spanning tree (or forest) as\n            an iterable of edges\n\n        \"\"\"\n        return self._mst\n\n    def weight(self):\n        \"\"\"Returns the sum of the edge weights in a minimum spanning tree (or\n        forest).\n\n        :returns: the sum of the edge weights in a minimum spanning tree (or forest)\n\n        \"\"\"\n        return self._weight\n\n    def _check(self, G):\n        # check optimality conditions (takes time proportional to E V lg* V)\n\n        totalWeight = 0.0  # check weight\n        for e in self.edges():\n            totalWeight += e.weight()\n\n        if abs(totalWeight - self.weight()) > LazyPrimMST.FLOATING_POINT_EPSILON:\n            error = \"Weight of edges does not equal weight(): {} vs. {}\\n\".format(\n                totalWeight, self.weight()\n            )\n            print(error, file=sys.stderr)\n            return False\n\n        # check that it is acyclic\n        uf = UF(G.V())\n        for e in self.edges():\n            v = e.either()\n            w = e.other(v)\n            if uf.connected(v, w):\n                print(\"Not a forest\", file=sys.stderr)\n                return False\n            uf.union(v, w)\n\n        # check that it is a spanning forest\n        for e in G.edges():\n            v = e.either()\n            w = e.other(v)\n            if not uf.connected(v, w):\n                print(\"Not a forest\", file=sys.stderr)\n                return False\n\n        # check that it is a minimal spanning forest (cut optimality conditions)\n        for e in self.edges():\n            # all edges in MST except e\n            uf = UF(G.V())\n            for f in self._mst:\n                x = f.either()\n                y = f.other(x)\n                if f != e:\n                    uf.union(x, y)\n\n            # check that e is min weight edge in crossing cut\n            for f in G.edges():\n                x = f.either()\n                y = f.other(x)\n                if not uf.connected(x, y):\n                    if f.weight() < e.weight():\n                        error = \"Edge {} violates cut optimality conditions\".format(f)\n                        print(error, file=sys.stderr)\n                        return False\n        return True\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.graphs.edge_weighted_graph import EdgeWeightedGraph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = EdgeWeightedGraph.from_stream(In)\n    mst = LazyPrimMST(G)\n    for e in mst.edges():\n        stdio.writeln(e)\n    stdio.writef(\"%.5f\\n\", mst.weight())\n"
  },
  {
    "path": "itu/algs4/graphs/prim_mst.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\nimport math\nimport sys\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.fundamentals.uf import UF\nfrom itu.algs4.sorting.index_min_pq import IndexMinPQ\n\n\nclass PrimMST:\n    \"\"\"The PrimMST class represents a data type for computing a minimum\n    spanning tree in an edge-weighted graph. The edge weights can be positive,\n    zero, or negative and need not be distinct. If the graph is not connected,\n    it computes a minimum spanning forest, which is the union of minimum\n    spanning trees in each connected component. The weight() method returns the\n    weight of a minimum spanning tree and the edges() method returns its edges.\n\n    This implementation uses Prim's algorithm with an indexed binary\n    heap. The constructor takes time proportional to E log V and extra\n    space not including the graph) proportional to V, where V is the\n    number of vertices and E is the number of edges. Afterwards, the\n    weight() method takes constant time and the edges() method takes\n    time proportional to V.\n\n    \"\"\"\n\n    FLOATING_POINT_EPSILON = 1e-12\n\n    def __init__(self, G):\n        \"\"\"Compute a minimum spanning tree (or forest) of an edge-weighted\n        graph.\n\n        :param G: the edge-weighted graph\n\n        \"\"\"\n        self._edge_to = [\n            None\n        ] * G.V()  # self._edge_to[v] = shortest edge from tree vertex to non-tree vertex\n        self._dist_to = [0.0] * G.V()  # self._dist_to[v] = weight of shortest such edge\n        self._marked = [\n            False\n        ] * G.V()  # self._marked[v] = True if v on tree, False otherwise\n        self._pq = IndexMinPQ(G.V())\n\n        for v in range(G.V()):\n            self._dist_to[v] = math.inf\n\n        for v in range(G.V()):  # run from each vertex to find\n            if not self._marked[v]:\n                self._prim(G, v)  # minimum spanning forest\n\n        # check optimality conditions\n        assert self._check(G)\n\n    # run Prim's algorithm in graph G, starting from vertex s\n    def _prim(self, G, s):\n        self._dist_to[s] = 0.0\n        self._pq.insert(s, self._dist_to[s])\n        while not self._pq.is_empty():\n            v = self._pq.del_min()\n            self._scan(G, v)\n\n    def _scan(self, G, v):\n        # scan vertex v\n        self._marked[v] = True\n        for e in G.adj(v):\n            w = e.other(v)\n            if self._marked[w]:\n                continue  # v-w is obsolete edge\n            if e.weight() < self._dist_to[w]:\n                self._dist_to[w] = e.weight()\n                self._edge_to[w] = e\n                if self._pq.contains(w):\n                    self._pq.decrease_key(w, self._dist_to[w])\n                else:\n                    self._pq.insert(w, self._dist_to[w])\n\n    def edges(self):\n        \"\"\"Returns the edges in a minimum spanning tree (or forest).\n\n        :returns: the edges in a minimum spanning tree (or forest) as\n                an iterable of edges\n\n        \"\"\"\n        mst = Queue()\n        for v in range(len(self._edge_to)):\n            e = self._edge_to[v]\n            if e is not None:\n                mst.enqueue(e)\n\n        return mst\n\n    def weight(self):\n        \"\"\"Returns the sum of the edge weights in a minimum spanning tree (or\n        forest).\n\n        :returns: the sum of the edge weights in a minimum spanning tree (or forest)\n\n        \"\"\"\n        weight = 0.0\n        for e in self.edges():\n            weight += e.weight()\n        return weight\n\n    def _check(self, G):\n        # check optimality conditions (takes time proportional to E V lg* V)\n\n        totalWeight = 0.0  # check weight\n        for e in self.edges():\n            totalWeight += e.weight()\n\n        if abs(totalWeight - self.weight()) > PrimMST.FLOATING_POINT_EPSILON:\n            error = \"Weight of edges does not equal weight(): {} vs. {}\\n\".format(\n                totalWeight, self.weight()\n            )\n            print(error, file=sys.stderr)\n            return False\n\n        # check that it is acyclic\n        uf = UF(G.V())\n        for e in self.edges():\n            v = e.either()\n            w = e.other(v)\n            if uf.connected(v, w):\n                print(\"Not a forest\", file=sys.stderr)\n                return False\n            uf.union(v, w)\n\n        # check that it is a spanning forest\n        for e in G.edges():\n            v = e.either()\n            w = e.other(v)\n            if not uf.connected(v, w):\n                print(\"Not a spanning forest\", file=sys.stderr)\n                return False\n\n        # check that it is a minimal spanning forest (cut optimality conditions)\n        for e in self.edges():\n            # all edges in MST except e\n            uf = UF(G.V())\n            for f in self.edges():\n                x = f.either()\n                y = f.other(x)\n                if f != e:\n                    uf.union(x, y)\n\n            # check that e is min weight edge in crossing cut\n            for f in G.edges():\n                x = f.either()\n                y = f.other(x)\n                if not uf.connected(x, y):\n                    if f.weight() < e.weight():\n                        error = \"Edge {} violates cut optimality conditions\".format(f)\n                        print(error, file=sys.stderr)\n                        return False\n        return True\n\n\nif __name__ == \"__main__\":\n    from itu.algs4.graphs.edge_weighted_graph import EdgeWeightedGraph\n    from itu.algs4.stdlib import stdio\n    from itu.algs4.stdlib.instream import InStream\n\n    In = InStream(sys.argv[1])\n    G = EdgeWeightedGraph.from_stream(In)\n    mst = PrimMST(G)\n    for e in mst.edges():\n        stdio.writeln(e)\n    stdio.writef(\"%.5f\\n\", mst.weight())\n"
  },
  {
    "path": "itu/algs4/graphs/symbol_digraph.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.graphs.digraph import Digraph\nfrom itu.algs4.searching.binary_search_st import BinarySearchST\nfrom itu.algs4.stdlib import stdio\nfrom itu.algs4.stdlib.instream import InStream\n\n\nclass SymbolDigraph:\n    \"\"\"The SymbolDigraph class representsclass represents a digraph, where the\n    vertex names are arbitrary strings. By providing mappings between vertex\n    names and integers, it serves as a wrapper around the Digraph data type,\n    which assumes the.\n\n    vertex names are integers between 0 and V - 1.\n    It also supports initializing a symbol digraph from a file.\n\n    This implementation uses an ST to map from strings to integers,\n    an array to map from integers to strings, and a Digraph to store\n    the underlying graph.\n    The index_of and contains operations take time\n    proportional to log V, where V is the number of vertices.\n    The name_of operation takes constant time.\n\n    \"\"\"\n\n    def __init__(self, filename, delimiter):\n        \"\"\"Initializes a digraph from a file using the specified delimiter.\n        Each line in the file contains the name of a vertex, followed by a list\n        of the names of the vertices adjacent to that vertex, separated by the\n        delimiter.\n\n        :param filename: the name of the file\n        :param delimiter: the delimiter between fields\n\n        \"\"\"\n        self._st = BinarySearchST()  # string -> index\n\n        # First pass builds the index by reading strings to associate\n        # distinct strings with an index\n        stream = InStream(filename)\n        while not stream.isEmpty():\n            a = stream.readLine().split(delimiter)\n            for i in range(len(a)):\n                if not self._st.contains(a[i]):\n                    self._st.put(a[i], self._st.size())\n\n        stdio.writef(\"Done reading %s\\n\", filename)\n\n        # inverted index to get keys in an array\n        self._keys = [None] * self._st.size()  # index  -> string\n        for name in self._st.keys():\n            self._keys[self._st.get(name)] = name\n\n        # second pass builds the graph by connecting first vertex on each\n        # line to all others\n        self._graph = Digraph(self._st.size())  # the underlying graph\n        stream = InStream(filename)\n        while stream.hasNextLine():\n            a = stream.readLine().split(delimiter)\n            v = self._st.get(a[0])\n            for i in range(1, len(a)):\n                w = self._st.get(a[i])\n                self._graph.add_edge(v, w)\n\n    def contains(self, s):\n        \"\"\"Does the graph contain the vertex named s?\n\n        :param s: the name of a vertex\n        :return:s true if s is the name of a vertex, and false otherwise\n\n        \"\"\"\n        return self._st.contains(s)\n\n    def index_of(self, s):\n        \"\"\"Returns the integer associated with the vertex named s.\n\n        :param s: the name of a vertex\n        :returns: the integer (between 0 and V - 1) associated with the vertex named s\n\n        \"\"\"\n        return self._st.get(s)\n\n    def name_of(self, v):\n        \"\"\"Returns the name of the vertex associated with the integer v.\n\n        @param  v the integer corresponding to a vertex (between 0 and V - 1)\n        @throws IllegalArgumentException unless 0 <= v < V\n        @return the name of the vertex associated with the integer v\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._keys[v]\n\n    def digraph(self):\n        return self._graph\n\n    def _validateVertex(self, v):\n        # throw an IllegalArgumentException unless 0 <= v < V\n        V = self._graph.V()\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    filename = sys.argv[1]\n    delimiter = sys.argv[2]\n    sg = SymbolDigraph(filename, delimiter)\n    graph = sg.digraph()\n    while stdio.hasNextLine():\n        source = stdio.readLine()\n        if sg.contains(source):\n            s = sg.index_of(source)\n            for v in graph.adj(s):\n                stdio.writef(\"\\t%s\\n\", sg.name_of(v))\n        else:\n            stdio.writef(\"input not contain '%i'\", source)\n"
  },
  {
    "path": "itu/algs4/graphs/symbol_graph.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.graphs.graph import Graph\nfrom itu.algs4.searching.binary_search_st import BinarySearchST\nfrom itu.algs4.stdlib import stdio\nfrom itu.algs4.stdlib.instream import InStream\n\n\nclass SymbolGraph:\n    \"\"\"The SymbolGraph class represents an undirected graph, where the vertex\n    names are arbitrary strings. By providing mappings between vertex names and\n    integers, it serves as a wrapper around the Graph data type, which assumes\n    the vertex names are integers.\n\n    between 0 and V - 1.\n    It also supports initializing a symbol graph from a file.\n\n    This implementation uses an ST to map from strings to integers,\n    an array to map from integers to strings, and a Graph to store\n    the underlying graph.\n    The index_of and contains operations take time\n    proportional to log V, where V is the number of vertices.\n    The name_of operation takes constant time.\n\n    \"\"\"\n\n    def __init__(self, filename, delimiter):\n        \"\"\"Initializes a graph from a file using the specified delimiter. Each\n        line in the file contains the name of a vertex, followed by a list of\n        the names of the vertices adjacent to that vertex, separated by the\n        delimiter.\n\n        :param filename: the name of the file\n        :param delimiter: the delimiter between fields\n\n        \"\"\"\n        self._st = BinarySearchST()  # string -> index\n\n        # First pass builds the index by reading strings to associate\n        # distinct strings with an index\n        stream = InStream(filename)\n        while not stream.isEmpty():\n            a = stream.readLine().split(delimiter)\n            for i in range(len(a)):\n                if not self._st.contains(a[i]):\n                    self._st.put(a[i], self._st.size())\n\n        stdio.writef(\"Done reading %s\\n\", filename)\n\n        # inverted index to get keys in an array\n        self._keys = [None] * self._st.size()  # index  -> string\n        for name in self._st.keys():\n            self._keys[self._st.get(name)] = name\n\n        # second pass builds the graph by connecting first vertex on each\n        # line to all others\n        self._graph = Graph(self._st.size())  # the underlying graph\n        stream = InStream(filename)\n        while stream.hasNextLine():\n            a = stream.readLine().split(delimiter)\n            v = self._st.get(a[0])\n            for i in range(1, len(a)):\n                w = self._st.get(a[i])\n                self._graph.add_edge(v, w)\n\n    def contains(self, s):\n        \"\"\"Does the graph contain the vertex named s?\n\n        :param s: the name of a vertex\n        :return:s true if s is the name of a vertex, and false otherwise\n\n        \"\"\"\n        return self._st.contains(s)\n\n    def index_of(self, s):\n        \"\"\"Returns the integer associated with the vertex named s.\n\n        :param s: the name of a vertex\n        :returns: the integer (between 0 and V - 1) associated with the vertex named s\n\n        \"\"\"\n        return self._st.get(s)\n\n    def name_of(self, v):\n        \"\"\"Returns the name of the vertex associated with the integer v.\n\n        @param  v the integer corresponding to a vertex (between 0 and V - 1)\n        @throws IllegalArgumentException unless 0 <= v < V\n        @return the name of the vertex associated with the integer v\n\n        \"\"\"\n        self._validateVertex(v)\n        return self._keys[v]\n\n    def graph(self):\n        return self._graph\n\n    def _validateVertex(self, v):\n        # throw an IllegalArgumentException unless 0 <= v < V\n        V = self._graph.V()\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\".format(v, V - 1))\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    filename = sys.argv[1]\n    delimiter = sys.argv[2]\n    sg = SymbolGraph(filename, delimiter)\n    graph = sg.graph()\n    while stdio.hasNextLine():\n        source = stdio.readLine()\n        if sg.contains(source):\n            s = sg.index_of(source)\n            for v in graph.adj(s):\n                stdio.writef(\"\\t%s\\n\", sg.name_of(v))\n        else:\n            stdio.writef(\"input not contain '%i'\", source)\n"
  },
  {
    "path": "itu/algs4/graphs/topological.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\"\"\"This module implements the topological order algorithm described in\nAlgorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\nFor more information, see chapter 4.2 of the book.\n\n\"\"\"\n\nfrom itu.algs4.graphs.depth_first_order import DepthFirstOrder\nfrom itu.algs4.graphs.digraph import Digraph\nfrom itu.algs4.graphs.directed_cycle import DirectedCycle\nfrom itu.algs4.graphs.edge_weighted_directed_cycle import EdgeWeightedDirectedCycle\n\n\nclass Topological:\n    \"\"\"The Topological class represents a data type for determining a\n    topological order of a directed acyclic graph (DAG). Recall, a digraph has\n    a topological order if and only if it is a DAG. The hasOrder operation\n    determines whether the digraph has a topological order, and if so, the\n    order operation returns one.\n\n    This implementation uses depth-first search. The constructor takes time\n    proportional to V + E (in the worst case), where V is the number of vertices\n    and E is the number of edges. Afterwards, the hasOrder and rank operations\n    takes constant time the order operation takes time proportional to V.\n\n    See DirectedCycle, DirectedCycleX, and EdgeWeightedDirectedCycle to compute\n    a directed cycle if the digraph is not a DAG. See TopologicalX for a\n    nonrecursive queue-based algorithm to compute a topological order of a DAG.\n\n    For additional documentation, see Section 4.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, digraph):\n        \"\"\"Determines whether the digraph (or edge weighted digraph) has a\n        topological order and, if so, finds such a topological order.\n\n        :param digraph: the Digraph or EdgeWeightedDigraph to check\n\n        \"\"\"\n        self._order = None\n\n        if isinstance(digraph, Digraph):\n            finder = DirectedCycle(digraph)\n        else:\n            finder = EdgeWeightedDirectedCycle(digraph)\n\n        if not finder.has_cycle():\n            dfs = DepthFirstOrder(digraph)\n            self._order = dfs.reverse_post()\n            self._rank = [0] * digraph.V()\n            i = 0\n            for v in self._order:\n                self._rank[v] = i\n                i += 1\n\n    def order(self):\n        \"\"\"Returns a topological order if the digraph has a topologial order,\n        and None otherwise.\n\n        :returns: a topological order of the vertices (as an interable) if the digraph has a\n                 topological order (or equivalently, if the digraph is a DAG), and None otherwise\n\n        \"\"\"\n        return self._order\n\n    def has_order(self):\n        \"\"\"Does the digraph have a topological order?\n\n        :returns: True if the digraph has a topological order (or equivalently, if the digraph\n                 is a DAG), and False otherwise\n\n        \"\"\"\n        return self._order is not None\n\n    def rank(self, v):\n        \"\"\"The the rank of vertex v in the topological order -1 if the digraph\n        is not a DAG.\n\n        :param v: the vertex\n        :returns: the position of vertex v in a topological order of the digraph -1 if the digraph is not a DAG\n\n        \"\"\"\n        self._validate_vertex(v)\n        if self.has_order():\n            return self._rank[v]\n        else:\n            return -1\n\n    def _validate_vertex(self, v):\n        # throw an IllegalArgumentException unless 0 <= v < V\n        V = len(self._rank)\n        if v < 0 or v >= V:\n            raise ValueError(\"vertex {} is not between 0 and {}\", v, (V - 1))\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.graphs.symbol_digraph import SymbolDigraph\n    from itu.algs4.stdlib import stdio\n\n    filename = sys.argv[1]\n    delimiter = sys.argv[2]\n    sg = SymbolDigraph(filename, delimiter)\n    topological = Topological(sg.digraph())\n    for v in topological.order():\n        stdio.writeln(sg.name_of(v))\n"
  },
  {
    "path": "itu/algs4/graphs/transitive_closure.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"\n *  Execution:    python transitive_closure.py filename.txt\n *  Dependencies: Digraph DirectedDFS\n *  Data files:   https:#algs4.cs.princeton.edu/42digraph/tinyDG.txt\n *\n *  Compute transitive closure of a digraph and support\n *  reachability queries.\n *\n *  Preprocessing time: O(V(E + V)) time.\n *  Query time: O(1).\n *  Space: O(V^2).\n *\n *  % python transitive_closure.py tinyDG.txt\n *         0  1  2  3  4  5  6  7  8  9 10 11 12\n *  --------------------------------------------\n *    0:   T  T  T  T  T  T\n *    1:      T\n *    2:   T  T  T  T  T  T\n *    3:   T  T  T  T  T  T\n *    4:   T  T  T  T  T  T\n *    5:   T  T  T  T  T  T\n *    6:   T  T  T  T  T  T  T        T  T  T  T\n *    7:   T  T  T  T  T  T  T  T  T  T  T  T  T\n *    8:   T  T  T  T  T  T  T  T  T  T  T  T  T\n *    9:   T  T  T  T  T  T           T  T  T  T\n *   10:   T  T  T  T  T  T           T  T  T  T\n *   11:   T  T  T  T  T  T           T  T  T  T\n *   12:   T  T  T  T  T  T           T  T  T  T\n *\n\"\"\"\nimport sys\n\nfrom itu.algs4.errors.errors import IllegalArgumentException\nfrom itu.algs4.graphs.digraph import Digraph\nfrom itu.algs4.graphs.directed_dfs import DirectedDFS\nfrom itu.algs4.stdlib.instream import InStream\n\n\nclass TransitiveClosure:\n    \"\"\"\n    * Computes the transitive closure of the digraph G.\n    * @param G the digraph\n    \"\"\"\n\n    def __init__(self, G):\n        self._tc = [None] * G.V()  # tc[v] = reachable from v\n        for v in range(G.V()):\n            self._tc[v] = DirectedDFS(G, v)\n\n    \"\"\"\n     * Is there a directed path from vertex v to vertex w in the digraph?\n     * @param  v the source vertex\n     * @param  w the target vertex\n     * @return true if there is a directed path from v to w,\n     *         false otherwise\n     * @throws IllegalArgumentException unless 0 <= v < V\n     * @throws IllegalArgumentException unless 0 <= w < V\n     \"\"\"\n\n    def reachable(self, v, w):\n        self._validate_vertex(v)\n        self._validate_vertex(w)\n        return self._tc[v].is_marked(w)\n\n    # throw an IllegalArgumentException unless 0 <= v < V\n    def _validate_vertex(self, v):\n        V = len(self._tc)\n        if v < 0 or v >= V:\n            raise IllegalArgumentException(\n                \"vertex {} is not between 0 and {}\".format(v, V - 1)\n            )\n\n\ndef main(args):\n    stream = InStream(args[0])\n    G = Digraph.from_stream(stream)\n\n    tc = TransitiveClosure(G)\n\n    # print header\n    print(\"     \", end=\"\")\n    for v in range(G.V()):\n        print(\"{x:3d}\".format(x=v), end=\"\")\n    print()\n    print(\"--------------------------------------------\")\n\n    # print transitive closure\n    for v in range(G.V()):\n        print(\"{x:3d}: \".format(x=v), end=\"\")\n        for w in range(G.V()):\n            if tc.reachable(v, w):\n                print(\"  T\", end=\"\")\n            else:\n                print(\"   \", end=\"\")\n        print()\n\n\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n"
  },
  {
    "path": "itu/algs4/searching/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/searching/binary_search_st.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\nfrom itu.algs4.fundamentals.queue import Queue\n\n\nclass BinarySearchST:\n    \"\"\"The BST class represents an ordered symbol table of generic key-value\n    pairs. It supports the usual put, get, contains, delete, size, and is-empty\n    methods. It also provides ordered methods for finding the minimum, maximum,\n    floor, select, and ceiling. It also provides a keys method for iterating\n    over all of the keys. A symbol table implements the associative array\n    abstraction: when associating a value with a key that is already in the\n    symbol table, the convention is to replace the old value with the new\n    value. Unlike java.util.Map, this class uses the convention that values\n    cannot be None—setting the value associated with a key to None is\n    equivalent to deleting the key from the symbol table.\n\n    This implementation uses a sorted array. It requires that the key\n    type implements the Comparable interface and calls the compareTo()\n    and method to compare two keys. It does not call either equals() or\n    hashCode(). The put and remove operations each take linear time in\n    the worst case the contains, ceiling, floor, and rank operations\n    take logarithmic time the size, is-empty, minimum, maximum, and\n    select operations take constant time. Construction takes constant\n    time.\n\n    \"\"\"\n\n    _INIT_CAPACITY = 2\n\n    def __init__(self, capacity=_INIT_CAPACITY):\n        \"\"\"Initializes an empty symbol table with the specified initial\n        capacity.\n\n        :param capacity: the maximum capacity\n\n        \"\"\"\n        self._keys = [None] * capacity\n        self._vals = [None] * capacity\n        self._n = 0\n\n    def _resize(self, capacity):\n        # resize the underlying \"arrays\"\n        assert capacity >= self._n\n        tempk = [None] * capacity\n        tempv = [None] * capacity\n        for i in range(self._n):\n            tempk[i] = self._keys[i]\n            tempv[i] = self._vals[i]\n\n        self._vals = tempv\n        self._keys = tempk\n\n    def size(self):\n        \"\"\"Returns the number of key-value pairs in this symbol table.\n\n        :returns: the number of key-value pairs in this symbol table\n\n        \"\"\"\n        return self._n\n\n    def __len__(self):\n        return self.size()\n\n    def is_empty(self):\n        \"\"\"Returns True if this symbol table is empty.\n\n        :returns: True if this symbol table is empty\n                False otherwise\n\n        \"\"\"\n        return self.size() == 0\n\n    def contains(self, key):\n        \"\"\"Does this symbol table contain the given key?\n\n        :param key: the key\n        :returns:  True if this symbol table contains  key and\n                False otherwise\n        :raises ValueError: if  key is  None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to contains() is None\")\n        return self.get(key) is not None\n\n    def get(self, key):\n        \"\"\"Returns the value associated with the given key in this symbol\n        table.\n\n        :param key: the key\n        :returns: the value associated with the given key if the key is in the symbol table\n            and None if the key is not in the symbol table\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to get() is None\")\n        if self.is_empty():\n            return None\n        i = self.rank(key)\n        if i < self._n and self._keys[i] == key:\n            return self._vals[i]\n        return None\n\n    def rank(self, key):\n        \"\"\"Returns the number of keys in this symbol table strictly less than\n        key.\n\n        :param key: the key\n        :returns: the number of keys in the symbol table strictly less than  key\n        :raises ValueError: if  key is  None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to rank() is None\")\n\n        lo = 0\n        hi = self._n - 1\n        while lo <= hi:\n            mid = int(lo + (hi - lo) / 2)\n            if key < self._keys[mid]:\n                hi = mid - 1\n            elif key > self._keys[mid]:\n                lo = mid + 1\n            else:\n                return mid\n        return lo\n\n    def put(self, key, val):\n        \"\"\"Inserts the specified key-value pair into the symbol table,\n        overwriting the old value with the new value if the symbol table\n        already contains the specified key. Deletes the specified key (and its\n        associated value) from this symbol table if the specified value is\n        None.\n\n        :param key: the key\n        :param val: the value\n        :raises ValueError: if  key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"first argument to put() is None\")\n\n        if val is None:\n            self.delete(key)\n            return\n\n        i = self.rank(key)\n\n        # key is already in table\n        if i < self._n and self._keys[i] == key:\n            self._vals[i] = val\n            return\n\n        # insert new key-value pair\n        if self._n == len(self._keys):\n            self._resize(2 * len(self._keys))\n\n        j = self._n\n        while j > i:\n            self._keys[j] = self._keys[j - 1]\n            self._vals[j] = self._vals[j - 1]\n            j -= 1\n\n        self._keys[i] = key\n        self._vals[i] = val\n        self._n += 1\n\n        assert self._check()\n\n    def delete(self, key):\n        \"\"\"Removes the specified key and associated value from this symbol\n        table (if the key is in the symbol table).\n\n        :param key: the key\n        :raises ValueError: if  key is  None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to delete() is None\")\n        if self.is_empty():\n            return\n\n        # compute rank\n        i = self.rank(key)\n        n = self._n\n\n        # key not in table\n        if i == n or self._keys[i] != key:\n            return\n\n        j = i\n        while j < self._n - 1:\n            self._keys[j] = self._keys[j + 1]\n            self._vals[j] = self._vals[j + 1]\n            j += 1\n\n        self._n -= 1\n        n = self._n\n        self._keys[n] = None  # to avoid loitering\n        self._vals[n] = None\n\n        # resize if 1/4 full\n        if n > 0 and n == len(self._keys) // 4:\n            self._resize(len(self._keys) // 2)\n\n        assert self._check()\n\n    def deleteMin(self):\n        \"\"\"Removes the smallest key and associated value from this symbol\n        table.\n\n        :raises ValueError: if the symbol table is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise ValueError(\"Symbol table underflow error\")\n        self.delete(self.min())\n\n    def deleteMax(self):\n        \"\"\"Removes the largest key and associated value from this symbol table.\n\n        :raises ValueError: if the symbol table is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise ValueError(\"Symbol table underflow error\")\n        self.delete(self.max())\n\n    # *************************************************************************\n    #                    Ordered symbol table methods.\n    # *************************************************************************\n\n    def min(self):\n        \"\"\"Returns the smallest key in this symbol table.\n\n        :returns: the smallest key in this symbol table\n        :raises ValueError: if this symbol table is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise ValueError(\"called min() with empty symbol table\")\n        return self._keys[0]\n\n    def max(self):\n        \"\"\"Returns the largest key in this symbol table.\n\n        :returns: the largest key in this symbol table\n        :raises ValueError: if this symbol table is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise ValueError(\"called max() with empty symbol table\")\n        return self._keys[self._n - 1]\n\n    def select(self, k):\n        \"\"\"Return the kth smallest key in this symbol table.\n\n        :param k: the order statistic\n        :returns: the  kth smallest key in this symbol table\n        :raises ValueError: unless k is between 0 and n-1\n\n        \"\"\"\n        if k < 0 or k >= self.size():\n            raise ValueError(\"called select() with invalid argument: {}\".format(k))\n\n        return self._keys[k]\n\n    def floor(self, key):\n        \"\"\"Returns the largest key in this symbol table less than or equal to\n        key.\n\n        :param key: the key\n        :returns: the largest key in this symbol table less than or equal to  key\n        :raises ValueError: if there is no such key\n        :raises ValueError: if  key is  None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to floor() is None\")\n        i = self.rank(key)\n        if i < self._n and key == self._keys[i]:\n            return self._keys[i]\n        if i == 0:\n            return None\n        else:\n            return self._keys[i - 1]\n\n    def ceiling(self, key):\n        \"\"\"Returns the smallest key in this symbol table greater than or equal\n        to key.\n\n        :param key: the key\n        :returns: the smallest key in this symbol table greater than or equal to key\n        :raises ValueError: if there is no such key\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to ceiling() is None\")\n        i = self.rank(key)\n        if i == self._n:\n            return None\n        else:\n            return self._keys[i]\n\n    def size_between(self, lo, hi):\n        \"\"\"Returns the number of keys in this symbol table in the specified\n        range.\n\n        :param lo: minimum endpoint\n        :param hi: maximum endpoint\n        :returns: the number of keys in this symbol table between lo\n            (inclusive) and  hi (inclusive)\n        :raises ValueError: if either lo or hi is None\n\n        \"\"\"\n        if lo is None:\n            raise ValueError(\"first argument to size() is None\")\n        if hi is None:\n            raise ValueError(\"second argument to size() is None\")\n\n        if lo > hi:\n            return 0\n        if self.contains(hi):\n            return self.rank(hi) - self.rank(lo) + 1\n        else:\n            return self.rank(hi) - self.rank(lo)\n\n    def keys(self):\n        \"\"\"\n        Returns all keys in this symbol table as an  Iterable.\n        To iterate over all of the keys in the symbol table named  st,\n        use the foreach notation: for (Key key : st.keys()).\n\n        :returns: all keys in this symbol table\n        \"\"\"\n        return self.keys_between(self.min(), self.max())\n\n    def keys_between(self, lo, hi):\n        \"\"\"Returns all keys in this symbol table in the given range, as an\n        Iterable.\n\n        :param lo: minimum endpoint\n        :param hi: maximum endpoint\n        :returns: all keys in this symbol table between lo\n            (inclusive) and hi (inclusive)\n        :raises ValueError: if either lo or hi are None\n\n        \"\"\"\n        if lo is None:\n            raise ValueError(\"first argument to keys() is None\")\n        if hi is None:\n            raise ValueError(\"second argument to keys() is None\")\n\n        queue = Queue()\n        if lo > hi:\n            return queue\n\n        i = self.rank(lo)\n        end = self.rank(hi)\n        while i < end:\n            queue.enqueue(self._keys[i])\n            i += 1\n\n        if self.contains(hi):\n            queue.enqueue(self._keys[self.rank(hi)])\n        return queue\n\n    # *************************************************************************\n    #                    Check internal invariants.\n    # *************************************************************************\n\n    def _check(self):\n        return self._is_sorted() and self._rank_check()\n\n    def _is_sorted(self):\n        # are the items in the array in ascending order?\n        i = 1\n        while i < self.size():\n            if self._keys[i] < self._keys[i - 1]:\n                return False\n            i += 1\n        return True\n\n    def _rank_check(self):\n        # check that rank(select(i)) = i\n        for i in range(self.size()):\n            if i != self.rank(self.select(i)):\n                return False\n        for i in range(self.size()):\n            if self._keys[i] != self.select(self.rank(self._keys[i])):\n                return False\n        return True\n\n\nif __name__ == \"__main__\":\n    from itu.algs4.stdlib import stdio\n\n    st = BinarySearchST()\n    i = 0\n    while not stdio.isEmpty():\n        key = stdio.readString()\n        st.put(key, i)\n        i += 1\n\n    for s in st.keys():\n        stdio.writef(\"%s %i\\n\", s, st.get(s))\n"
  },
  {
    "path": "itu/algs4/searching/bst.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# Python 3\n\nimport sys\nfrom abc import abstractmethod\nfrom typing import Generic, Optional, TypeVar\n\nfrom typing_extensions import Protocol\n\nfrom ..errors.errors import IllegalArgumentException, NoSuchElementException\nfrom ..fundamentals.queue import Queue\n\nsys.setrecursionlimit(10 ** 5)\n\n\"\"\"\nThe BST class represents an ordered symbol table of generic\nkey-value pairs.\n\nThis implementation uses an unbalanced, binary search tree.\n\nFor additional details and documentation, see Section 3.2 of Algorithms,\n4th Edition by Robert Sedgewick and Kevin Wayne.\n\n:original author: Robert Sedgewick and Kevin Wayne\n:original java code: https://algs4.cs.princeton.edu/32bst/BST.java.html\n\n\"\"\"\n\n\nVal = TypeVar(\"Val\")\nKey = TypeVar(\"Key\", bound=\"Comparable\")\n\n\nclass Comparable(Protocol):\n    @abstractmethod\n    def __lt__(self: Key, other: Key) -> bool:\n        pass\n\n\nclass Node(Generic[Key, Val]):\n    def __init__(self, key: Key, value: Optional[Val], size: int):\n        self.left: Optional[Node[Key, Val]] = None  # root of left subtree\n        self.right: Optional[Node[Key, Val]] = None  # root of right subtree\n        self.key: Key = key  # sorted by key\n        self.value: Optional[Val] = value  # associated data\n        self.size: int = size  # number of nodes in subtree\n\n\nclass BST(Generic[Key, Val]):\n    def __init__(self) -> None:\n        \"\"\"Initialises empty symbol table.\"\"\"\n        self._root: Optional[Node[Key, Val]] = None  # root of BST\n\n    def is_empty(self) -> bool:\n        \"\"\"Returns true if this symbol table is empty.\"\"\"\n        return self.size() == 0\n\n    def contains(self, key: Key) -> bool:\n        \"\"\"Does this symbol table contain the given key?\n\n        :param key: the key to search for\n        :return boolean: true if symbol table contains key, false otherwise\n\n        \"\"\"\n        return self.get(key) is not None\n\n    def size(self) -> int:\n        \"\"\"Returns the number of key-value pairs in this symbol table.\"\"\"\n        return self._size(self._root)\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def _size(self, node: Optional[Node[Key, Val]]) -> int:\n        \"\"\"Returns the number of key-value pairs in BST rooted at node.\n\n        :param node: The node which act as root\n\n        \"\"\"\n        if node is None:\n            return 0\n        else:\n            return node.size\n\n    def get(self, key: Key) -> Optional[Val]:\n        \"\"\"Returns the value associated with the given key.\n\n        :param key: The key whose value is returned\n        :return: the value associated with the given key if the key\n        is in the symbol table, None otherwise\n\n        \"\"\"\n        return self._get(self._root, key)\n\n    def _get(self, node: Optional[Node[Key, Val]], key: Key) -> Optional[Val]:\n        if node is None:\n            return None\n        else:\n            if key < node.key:\n                return self._get(node.left, key)\n            elif key > node.key:\n                return self._get(node.right, key)\n            else:\n                return node.value\n\n    def put(self, key: Key, value: Optional[Val]) -> None:\n        \"\"\"Inserts the specified key-value pair into the symbol table,\n        overwriting the old value with the new value if the symbol table\n        already contains the specified key. Deletes the specified key (and its\n        associated value) from this symbol table if the specified value is\n        None.\n\n        :param key, value: the key-value pair to be inserted\n\n        \"\"\"\n        if value is None:\n            self.delete(key)\n            return\n        self._root = self._put(self._root, key, value)\n\n    def _put(\n        self, node: Optional[Node[Key, Val]], key: Key, value: Optional[Val]\n    ) -> Node[Key, Val]:\n        if node is None:\n            newnode: Node[Key, Val] = Node(key, value, 1)\n            return newnode\n        else:\n            if key < (node.key):\n                node.left = self._put(node.left, key, value)\n            elif key > (node.key):\n                node.right = self._put(node.right, key, value)\n            else:\n                node.value = value\n            node.size = 1 + self._size(node.left) + self._size(node.right)\n            return node\n\n    def delete_min(self) -> None:\n        \"\"\"Removes the smallest key and associated value from the symbol table\n        TODO exception?\"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls min() with empty symbol table\")\n        else:\n            assert self._root is not None\n            self._root = self._delete_min(self._root)\n\n    def _delete_min(self, node: Node[Key, Val]) -> Optional[Node[Key, Val]]:\n        if node.left is None:\n            return node.right\n        else:\n            node.left = self._delete_min(node.left)\n            node.size = self._size(node.left) + self._size(node.right) + 1\n            return node\n\n    def delete_max(self) -> None:\n        \"\"\"Removes the largest key and associated value from the symbol\n        table.\"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls max() with empty symbol table\")\n        else:\n            assert self._root is not None\n            self._root = self._delete_max(self._root)\n\n    def _delete_max(self, node: Node[Key, Val]) -> Optional[Node[Key, Val]]:\n        if node.right is None:\n            return node.left\n        else:\n            node.right = self._delete_max(node.right)\n        node.size = self._size(node.left) + self._size(node.right) + 1\n        return node\n\n    def delete(self, key: Key) -> None:\n        \"\"\"Removes the specified key and its associated value from this symbol\n        table (if the key is in this symbol table)\"\"\"\n        self._root = self._delete(self._root, key)\n\n    def _delete(\n        self, node: Optional[Node[Key, Val]], key: Key\n    ) -> Optional[Node[Key, Val]]:\n        if node is None:\n            return None\n        else:\n            if key.__lt__(node.key):\n                node.left = self._delete(node.left, key)\n            elif node.key < key:\n                node.right = self._delete(node.right, key)\n            else:\n                if node.right is None:\n                    return node.left\n                elif node.left is None:\n                    return node.right\n                else:\n                    temp_node = node\n                    assert temp_node.right is not None\n                    node = self._min(temp_node.right)\n                    node.right = self._delete_min(temp_node.right)\n                    node.left = temp_node.left\n\n            node.size = self._size(node.left) + self._size(node.right) + 1\n            return node\n\n    def min(self) -> Key:\n        \"\"\"Returns the smallest key in the BST.\"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls min() with empty symbol table\")\n        else:\n            assert self._root is not None\n            return self._min(self._root).key\n\n    def _min(self, node: Node[Key, Val]) -> Node[Key, Val]:\n        if node.left is None:\n            return node\n        else:\n            return self._min(node.left)\n\n    def max(self) -> Key:\n        \"\"\"Returns the larget key in the symbol table.\"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls max() with empty symbol table\")\n        else:\n            assert self._root is not None\n            return self._max(self._root).key\n\n    def _max(self, node: Node[Key, Val]) -> Node[Key, Val]:\n        if node.right is None:\n            return node\n        else:\n            return self._max(node.right)\n\n    def floor(self, key: Key) -> Key:\n        \"\"\"Returns the largest key in the symbol table less than or equal to\n        key Raises NoSuchElementException if no such key exists.\"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls floor() with empty symbol table\")\n\n        node = self._floor(self._root, key)\n        if node is None:\n            raise NoSuchElementException(\"calls floor() with key < min\")\n        else:\n            return node.key\n\n    def _floor(\n        self, node: Optional[Node[Key, Val]], key: Key\n    ) -> Optional[Node[Key, Val]]:\n        if node is None:\n            return None\n        elif key == node.key:\n            return node\n        elif key < node.key:\n            return self._floor(node.left, key)\n        temp_node = self._floor(node.right, key)\n        if temp_node is not None:\n            return temp_node\n        return node\n\n    def ceiling(self, key: Key) -> Key:\n        \"\"\"Returns the smallest key in the symbol table greater than or equal\n        to key Raises NoSuchElementException if no such key exists.\"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls ceiling() with empty symbol table\")\n\n        node = self._ceiling(self._root, key)\n        if node is None:\n            raise NoSuchElementException(\"calls ceiling() with key > max\")\n        else:\n            return node.key\n\n    def _ceiling(\n        self, node: Optional[Node[Key, Val]], key: Key\n    ) -> Optional[Node[Key, Val]]:\n        if node is None:\n            return None\n        elif key == node.key:\n            return node\n        elif key > node.key:\n            return self._ceiling(node.right, key)\n        temp_node = self._ceiling(node.left, key)\n        if temp_node is not None:\n            return temp_node\n        return node\n\n    def keys(self) -> Queue[Key]:\n        \"\"\"Returns all keys in the symbol table as a list.\"\"\"\n        if self.is_empty():\n            return Queue()\n        return self.range_keys(self.min(), self.max())\n\n    def range_keys(self, lo: Key, hi: Key) -> Queue[Key]:\n        \"\"\"returns all keys in the symbol table in the given range as a list.\n\n        :param lo: minimum endpoint\n        :param hi: maximum endpoint\n        :return: all keys in symbol table between lo (inclusive) and hi (inclusive)\n\n        \"\"\"\n        queue: Queue[Key] = Queue()\n        self._range_keys(self._root, queue, lo, hi)\n        return queue\n\n    def _range_keys(\n        self, node: Optional[Node[Key, Val]], queue: Queue[Key], lo: Key, hi: Key\n    ) -> None:\n        if node is None:\n            return\n        elif lo < node.key:\n            self._range_keys(node.left, queue, lo, hi)\n        if not lo > node.key and not hi < node.key:\n            queue.enqueue(node.key)\n        if hi > node.key:\n            self._range_keys(node.right, queue, lo, hi)\n\n    def select(self, k: int) -> Key:\n        \"\"\"Return the kth smallest key in the symbol table.\n\n        :param k: the order statistic\n        :return: the kth smallest key in the symbol table\n        :raises IllegalArgumentException: unless k is between 0 and n-1\n\n        \"\"\"\n        if k < 0 or k >= self.size():\n            raise IllegalArgumentException(\n                \"argument to select() is invalid: {}\".format(k)\n            )\n        assert self._root is not None\n        x = self._select(self._root, k)\n        return x.key\n\n    def _select(self, x: Node[Key, Val], k: int) -> Node[Key, Val]:\n        \"\"\"\n        Returns the node with key of rank k in the subtree rooted at x\n        :rtype: Node\n        \"\"\"\n        t = self._size(x.left)\n        if t > k:\n            assert x.left is not None\n            return self._select(x.left, k)\n        elif t < k:\n            assert x.right is not None\n            return self._select(x.right, k - t - 1)\n        else:\n            return x\n\n    def rank(self, key: Key) -> int:\n        \"\"\"Returns the number of keys in the symbol table strictly less than\n        key.\n\n        :param key: the key\n        :return: the number of keys in the symbol table strictly less than key\n        :rtype: int\n        :raises IllegalArgumentException: if key is None\n\n        \"\"\"\n        if key is None:\n            raise IllegalArgumentException(\"argument to rank() is None\")\n        return self._rank(key, self._root)\n\n    def _rank(self, key: Key, x: Optional[Node[Key, Val]]) -> int:\n        \"\"\"Returns the number of keys less than key in the subtree rooted at x.\n\n        :rtype: int\n\n        \"\"\"\n        if x is None:\n            return 0\n        if key < x.key:\n            return self._rank(key, x.left)\n        if key > x.key:\n            return 1 + self._size(x.left) + self._rank(key, x.right)\n        else:\n            return self._size(x.left)\n\n    def size_range(self, lo: Key, hi: Key) -> int:\n        \"\"\"Returns the number of keys in the symbol table in the given range.\n\n        :param lo: minimum endpoint\n        :param hi: maximum endpoint\n        :return: the number of keys in the symbol table between lo\n        (inclusive) and hi (inclusive)\n        :rtype: int\n        :raises IllegalArgumentException: if either lo or hi is None\n\n        \"\"\"\n        if lo is None:\n            return IllegalArgumentException(\"first argument to size() is None\")\n        if hi is None:\n            return IllegalArgumentException(\"second argument to size() is None\")\n        if lo > hi:\n            return 0\n        if self.contains(hi):\n            return self.rank(hi) - self.rank(lo) + 1\n        else:\n            return self.rank(hi) - self.rank(lo)\n\n    def height(self) -> int:\n        \"\"\"Returns the height of the BST (for debugging)\"\"\"\n        return self._height(self._root)\n\n    def _height(self, node: Optional[Node[Key, Val]]) -> int:\n        if node is None:\n            return -1\n        else:\n            return 1 + max(self._height(node.left), self._height(node.right))\n\n    def level_order(self) -> Queue[Key]:\n        \"\"\"Returns the keys in the BST in level order (for debugging)\"\"\"\n        queue: Queue[Optional[Node[Key, Val]]] = Queue()\n        keys: Queue[Key] = Queue()\n        queue.enqueue(self._root)\n        while len(queue) > 0:\n            node = queue.dequeue()\n            if node is None:\n                continue\n            else:\n                keys.enqueue(node.key)\n                queue.enqueue(node.left)\n                queue.enqueue(node.right)\n        return keys\n"
  },
  {
    "path": "itu/algs4/searching/file_index.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.stdlib import stdio\n\n#  Execution:    python file_index.py file1.txt file2.txt file3.txt ...\n#\n#  % python file_index.py ex*.txt\n#  age\n#   ex3.txt\n#   ex4.txt\n# best\n#   ex1.txt\n# was\n#   ex1.txt\n#   ex2.txt\n#   ex3.txt\n#   ex4.txt\n#\n#  % python file_index.py *.txt\n#\n#  % python file_index.py *.py\n\n\n\"\"\"\n *  The {@code FileIndex} class provides a client for indexing a set of files,\n *  specified as command-line arguments. It takes queries from standard input\n *  and prints each file that contains the given query.\n\"\"\"\n\n# key = word, value = set of files containing that word\nif __name__ == \"__main__\":\n    st = {}\n    args = sys.argv[1:]\n\n    # create inverted index of all files\n    print(\"Indexing files\")\n    for filename in args:\n        print(\"  \" + filename)\n        file = open(filename, \"r\")\n        for line in file.readlines():\n            for word in line.split():\n                if word not in st:\n                    st[word] = set()\n                s = st.get(word)\n                s.add(file)\n\n    # read queries from standard input, one per line\n    while not stdio.isEmpty():\n        query = stdio.readString()\n        if query in st:\n            s = st.get(query)\n            for file in s:\n                print(\" \" + file.name)\n"
  },
  {
    "path": "itu/algs4/searching/frequency_counter.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.stdlib import stdio\n\n#  Execution:    python frequency_counter.py L < input.txt\n#\n#  Read in a list of words from standard input and print out\n#  the most frequently occurring word that has length greater than\n#  a given threshold.\n#\n#  % python frequency_counter.py 1 < tinyTale.txt\n#  it 10\n#\n#  % python frequency_counter.py 8 < tale.txt\n#  business 122\n#\n#  % python frequency_counter.py 10 < leipzig1M.txt\n#  government 24763\n\n\n\"\"\"\n  The FrequencyCounter class provides a client for\n  reading in a sequence of words and printing a word (exceeding\n  a given length) that occurs most frequently. It is useful as\n  a test client for various symbol table implementations.\n\n  Reads in a command-line integer and sequence of words from\n  standard input and prints out a word (whose length exceeds\n  the threshold) that occurs most frequently to standard output.\n  It also prints out the number of words whose length exceeds\n  the threshold and the number of distinct such words.\n\"\"\"\n\nif __name__ == \"__main__\":\n    args = sys.argv[1:]\n    distinct = 0\n    words = 0\n    minlen = int(args[0])\n    st = {}\n\n    # compute frequency counts\n    while not stdio.isEmpty():\n        key = stdio.readString()\n        if len(key) < minlen:\n            continue\n        words += 1\n        if key in st:\n            st[key] = st.get(key) + 1\n        else:\n            st[key] = 1\n            distinct += 1\n\n    # find a key with the highest frequency count\n    max = \"\"\n    st[max] = 0\n    for word in st.keys():\n        if st.get(word) > st.get(max):\n            max = word\n\n    print(max + \" \" + str(st.get(max)))\n    print(\"distinct = \" + str(distinct))\n    print(\"words    = \" + str(words))\n"
  },
  {
    "path": "itu/algs4/searching/linear_probing_hst.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\nimport sys\n\n\nclass LinearProbingHashST:\n    \"\"\"The LinearProbingHashST class represents a symbol table of dynamic key-\n    value pairs. It supports the usual put, get, contains, delete, size, and is-\n    empty methods. It also provides a key_list method for iterating over all of\n    the keys. A symbol table implements the associative array abstraction: when\n    associating a value with a key that is already in the symbol table, the\n    convention is to replace the old value with the new value. Unlike the Map-\n    class in Java, this class uses the convention that values cannot be null/None.\n    Setting the value associated with a key to None is equivalent to deleting the\n    key from the symbol table.\n\n    This implementation uses a linear probing hash table. It requires that\n    the key type overrides the __eq__ and __hash__ methods. The expected\n    time per put, contains, or remove operation is constant, subject to the\n    uniform hashing assumption. The size, and is-empty operations take\n    constant time. Construction takes constant time.\n\n    \"\"\"\n\n    def __init__(self, capacity=4):\n        \"\"\"Initializes an empty symbol table with the specified initial capacity. If\n        no capacity is specified, it defaults to 4.\n\n        :param capacity: the initial capacity\n\n        \"\"\"\n        self.m = capacity\n        self.n = 0\n        self.keys = [None for i in range(0, self.m)]\n        self.values = [None for i in range(0, self.m)]\n\n    def size(self):\n        \"\"\"Returns the number of key-value pairs in this symbol table.\n\n        :returns: the number of key-value pairs in this symbol table.\n\n        \"\"\"\n        return self.n\n\n    def __len__(self):\n        return self.size()\n\n    def is_empty(self):\n        \"\"\"Returns True if this symbol table is empty.\n\n        :returns: True if this symbol table is empty;\n                    False otherwise\n\n        \"\"\"\n        return self.n == 0\n\n    def contains(self, key):\n        \"\"\"Returns True if this symbol table contains the specified key.\n\n        :param key: the key\n        :returns: True if this symbol table contains the key;\n                    False otherwize\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to contains() is None\")\n        return self.get(key) is not None\n\n    def _hash(self, key):\n        # Hash value between 0 and M-1\n        return (hash(key) & 0x7FFFFFFF) % self.m\n\n    def _resize(self, capacity):\n        # Resizes the hash table to the given capacity by re-hashing all of the keys\n        temp = LinearProbingHashST(capacity)\n        for i in range(0, self.m):\n            if self.keys[i] is not None:\n                temp.put(self.keys[i], self.values[i])\n        self.keys = temp.keys\n        self.values = temp.values\n        self.m = temp.m\n\n    def put(self, key, value):\n        \"\"\"Inserts the specified key-value paur into the symbol table, overwriting\n        the old value with the new value if the symbol table already contains the\n        specified key. Deletes the specified key (and its associated value) from this\n        symbol table if the specified value is None.\n\n        :param key: the key\n        :param value: the value\n        :raises ValueError: if key is None.\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to put() is None\")\n        if value is None:\n            self.delete(key)\n            return\n        # Double table size if 50% full\n        if self.n >= self.m // 2:\n            self._resize(2 * self.m)\n\n        i = self._hash(key)\n        while self.keys[i] is not None:\n            if self.keys[i] == key:\n                self.values[i] = value\n                return\n            i = (i + 1) % self.m\n        self.keys[i] = key\n        self.values[i] = value\n        self.n += 1\n\n    def get(self, key):\n        \"\"\"Returns the value associated with the specified key.\n\n        :param key: the key\n        :returns: the value associated with the key in the symbol table;\n                    None if no such value\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to get() is None\")\n        i = self._hash(key)\n        while self.keys[i] is not None:\n            if self.keys[i] == key:\n                return self.values[i]\n            i = (i + 1) % self.m\n        return None\n\n    def delete(self, key):\n        \"\"\"Removes the specified key and its associated value from this symbol table\n        (if the key is in this symbol table).\n\n        :param key: the key\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to delete() is None\")\n        if not self.contains(key):\n            return\n        # Find position i of key\n        i = self._hash(key)\n        while not key == self.keys[i]:\n            i = (i + 1) % self.m\n        # Delete key and associated value\n        self.keys[i] = None\n        self.values[i] = None\n        # Rehash all keys in same cluster\n        i = (i + 1) % self.m\n        while self.keys[i] is not None:\n            # Delete keys[i] and values[i] and reinsert\n            keyToRehash = self.keys[i]\n            valueToReash = self.values[i]\n            self.keys[i] = None\n            self.values[i] = None\n            self.n -= 1\n            self.put(keyToRehash, valueToReash)\n            i = (i + 1) % self.m\n        self.n -= 1\n\n        # Halves table size if it's less than 12.5% full\n        if self.n > 0 and self.n <= self.m / 8:\n            self._resize(self.m // 2)\n\n        assert self._check()\n\n    def key_list(self):\n        \"\"\"\n        Returns the keys in the symbol table as an iterable\n        :returns: A list containing all keys\n        \"\"\"\n        keys = []\n        for i in range(0, self.m):\n            if self.keys[i] is not None:\n                keys.append(self.keys[i])\n        return keys\n\n    def _check(self):\n        # Integrity check - don't check after each put() because\n        # integrity is not maintained during delete()\n        if self.m < 2 * self.n:\n            print(\"Hash table size m = {}; List size n = {}\".format(self.m, self.n))\n            return False\n        for i in range(0, self.m):\n            if self.keys[i] is None:\n                continue\n            elif self.get(self.keys[i]) != self.values[i]:\n                print(\n                    \"get[{}] = {}; values[i] = {}\".format(\n                        self.keys[i], self.get(self.keys[i]), self.values[i]\n                    )\n                )\n                return False\n        return True\n\n\ndef main():\n    \"\"\"Unit tests the LinearProbingHashST data type.\"\"\"\n    st = LinearProbingHashST()\n    i = 1\n    for key in sys.argv[1:]:\n        st.put(key, i)\n        i += 1\n    for key in st.key_list():\n        print(\"{} {}\".format(key, st.get(key)))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/searching/lookup_csv.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.stdlib import stdio\n\n# data files:\n# https://algs4.cs.princeton.edu/35applications/amino.csv\n#  Data files:   https://algs4.cs.princeton.edu/35applications/DJIA.csv\n#                https://algs4.cs.princeton.edu/35applications/UPC.csv\n#                https://algs4.cs.princeton.edu/35applications/amino.csv\n#                https://algs4.cs.princeton.edu/35applications/elements.csv\n#                https://algs4.cs.princeton.edu/35applications/ip.csv\n#                https://algs4.cs.princeton.edu/35applications/morse.csv\n\n\n#  Execution:    python lookup_csv.py file.csv keyField valField\n#\n#  Reads in a set of key-value pairs from a two-column CSV file\n#  specified on the command line; then, reads in keys from standard\n#  input and prints out corresponding values.\n#\n#  % python lookup_csv.py amino.csv 0 3     % python lookup_csv.py ip.csv 0 1\n#  TTA                                  www.google.com\n#  Leucine                              216.239.41.99\n#  ABC\n#  Not found                            % python lookup_csv.py ip.csv 1 0\n#  TCT                                  216.239.41.99\n#  Serine                               www.google.com\n#\n#  % python lookup_csv.py amino.csv 3 0     % python lookup_csv.py DJIA.csv 0 1\n#  Glycine                              29-Oct-29\n#  GGG                                  252.38\n#                                       20-Oct-87\n#                                       1738.74\n\n\"\"\"\nThe LookupCSV class provides a data-driven client for reading in a\nkey-value pairs from a file; then, printing the values corresponding to the\nkeys found on standard input. Both keys and values are strings.\nThe fields to serve as the key and value are taken as command-line arguments.\n\"\"\"\n\nif __name__ == \"__main__\":\n    args = sys.argv[1:]\n    keyField = int(args[1])\n    valField = int(args[2])\n\n    # symbol table\n    st = {}\n\n    # read in the data from csv file\n    file = open(args[0], \"r\")\n    line = file.readline()\n    while line:\n        tokens = line.split(\",\")\n        key = tokens[keyField]\n        val = tokens[valField]\n        st[key] = val\n        line = file.readline()\n\n    while not stdio.isEmpty():\n        s = stdio.readString()\n        if s in st:\n            print(st.get(s))\n        else:\n            print(\"Not found\")\n    file.close()\n"
  },
  {
    "path": "itu/algs4/searching/lookup_index.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nimport sys\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.stdlib import stdio\n\n# is this really useful??\ntry:\n    q = Queue()\n    q.enqueue(1)\nexcept AttributeError:\n    print(\"ERROR - Could not import itu.algs4 queue\")\n    sys.exit(1)\n\n# Execution:    python lookup_index.py movies.txt \"/\"\n# Dependencies: queue.py stdio.py\n# % python lookup_index.py aminoI.csv \",\"\n# Serine\n#   TCT\n#   TCA\n#   TCG\n#   AGT\n#   AGC\n# TCG\n#   Serine\n#\n# % python lookup_index.py movies.txt \"/\"\n# Bacon, Kevin\n#   Animal House (1978)\n#   Apollo 13 (1995)\n#   Beauty Shop (2005)\n#   Diner (1982)\n#   Few Good Men, A (1992)\n#   Flatliners (1990)\n#   Footloose (1984)\n#   Friday the 13th (1980)\n#   ...\n# Tin Men (1987)\n#   DeBoy, David\n#   Blumenfeld, Alan\n#   ...\n\n# The LookupIndex class provides a data-driven client for reading in a\n# key-value pairs from a file; then, printing the values corresponding to the\n# keys found on standard input. Keys are strings; values are lists of strings.\n# The separating delimiter is taken as a command-line argument. This client\n# is sometimes known as an inverted index.\nif __name__ == \"__main__\":\n    args = sys.argv[1:]\n    filename = args[0]\n    separator = args[1]\n    file = open(filename, \"r\")\n    st = {}\n    ts = {}\n\n    line = file.readline()\n    while line:\n        fields = line.split(separator)\n        key = fields[0]\n        for i in range(1, len(fields)):\n            val = fields[i]\n            if key not in st:\n                st[key] = Queue()\n            if val not in ts:\n                ts[val] = Queue()\n            st.get(key).enqueue(val)\n            ts.get(val).enqueue(key)\n        line = file.readline()\n    print(\"Done indexing\")\n\n    # read queries from standard input, one per line\n    while not stdio.isEmpty():\n        query = stdio.readLine()\n        if query in st:\n            for vals in st.get(query):\n                print(\"  \" + vals)\n        if query in ts:\n            for keys in ts.get(query):\n                print(\"  \" + keys)\n\n    file.close()\n"
  },
  {
    "path": "itu/algs4/searching/red_black_bst.py",
    "content": "from abc import abstractmethod\nfrom typing import Generic, Optional, TypeVar\n\nfrom typing_extensions import Protocol\n\nfrom ..errors.errors import IllegalArgumentException, NoSuchElementException\nfrom ..fundamentals.queue import Queue\n\n# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n# Typing ---\n\n\nKey = TypeVar(\"Key\", bound=\"Comparable\")\nVal = TypeVar(\"Val\")\n\n\nclass Comparable(Protocol):\n    @abstractmethod\n    def __lt__(self: Key, other: Key) -> bool:\n        pass\n\n    def __le__(self: Key, other: Key) -> bool:\n        return self < other or self == other\n\n\n# ---\nclass Node(Generic[Key, Val]):\n    \"\"\"RedBlackBST helper node data type.\"\"\"\n\n    def __init__(self, key: Key, val: Val, color: bool, size: int):\n        \"\"\"Initializes a new node.\n\n        :param key: the key of the node\n        :param val: the value of the node\n        :param size: the subtree count\n\n        \"\"\"\n        self.key: Key = key\n        self.val: Val = val\n        self.left: Optional[Node[Key, Val]] = None\n        self.right: Optional[Node[Key, Val]] = None\n        self.size: int = size\n        self.color: bool = color\n\n\nclass RedBlackBST(Generic[Key, Val]):\n    \"\"\"The RedBlackBST class represents an ordered symbol table of generic key-\n    value pairs.\n\n    It supports the usual put, get, contains, delete, size, and is-empty\n    methods. It also provides ordered methods for finding the minimum,\n    maximum, floor, and ceiling. It also provides a keys method for\n    iterating over all the keys. A symbol table implements the\n    associative array abstraction: when associating a value with a key\n    that is already in the symbol table, the convention is to replace\n    the old value with the new value. This class uses the convention\n    that values cannot be None-setting the value associated with a key\n    to None is equivalent to deleting the key from the symbol table.\n    This implementation uses a left-leaning red-black BST. It requires\n    that the keys are all of the same type and that they can be\n    compared. The put, contains, remove, minimum, maximum, ceiling, and\n    floor operations each take logarithmic time in the worst case, if\n    the tree becomes unbalanced. The size, and is-empty operations take\n    constant time. Construction takes constant time.\n\n    \"\"\"\n\n    RED = True\n    BLACK = False\n\n    def __init__(self) -> None:\n        \"\"\"Initializes an empty symbol table.\"\"\"\n        self._root: Optional[Node[Key, Val]] = None\n\n    def put(self, key: Key, val: Val) -> None:\n        \"\"\"Inserts the specified key-value pair into the symbol table,\n        overwriting the old value with the new value if the symbol table\n        already contains the specified key. Deletes the specified key (and its\n        associated value) from this symbol table if the specified value is\n        None.\n\n        :param key: the key\n        :param val: the value\n        :raises IllegalArgumentException: if key is None\n\n        \"\"\"\n        # Can never happen if type checked:\n        if key is None:\n            raise IllegalArgumentException(\"first argument to put() is None\")\n        if val is None:\n            self.delete(key)\n            return\n\n        self._root = self._put(self._root, key, val)\n        self._root.color = RedBlackBST.BLACK\n\n    def _put(self, h: Optional[Node[Key, Val]], key: Key, val: Val) -> Node[Key, Val]:\n        \"\"\"Inserts the key-value pair in the subtree rooted at h.\n\n        :param h: root of currently inspected subtree\n        :param key: the key\n        :param val: the value\n\n        \"\"\"\n        if h is None:\n            return Node(key, val, self.RED, 1)\n        if key < h.key:\n            h.left = self._put(h.left, key, val)\n        elif key > h.key:\n            h.right = self._put(h.right, key, val)\n        else:\n            h.val = val\n\n        assert h is not None\n        if self._is_red(h.right) and not self._is_red(h.left):\n            h = self._rotate_left(h)\n        assert h is not None\n        if self._is_red(h.left):\n            assert h.left is not None  # bc h.left is red\n            if self._is_red(h.left.left):\n                h = self._rotate_right(h)\n        assert h is not None\n        if self._is_red(h.left) and self._is_red(h.right):\n            self._flip_colors(h)\n\n        h.size = self._size(h.left) + self._size(h.right) + 1\n\n        return h\n\n    def get(self, key: Key) -> Optional[Val]:\n        \"\"\"Returns the value associated with the given key.\n\n        :param key: the key\n        :return: the value associated with the given key if the key is in the symbol table\n        and None if the key is not in the symbol table\n        :raises IllegalArgumentException: if key is None\n\n        \"\"\"\n        # This can never happen if type checked:\n        if key is None:\n            raise IllegalArgumentException(\"argument to get() is None\")\n\n        return self._get(self._root, key)\n\n    def _get(self, x: Optional[Node[Key, Val]], key: Key) -> Optional[Val]:\n        \"\"\"Returns value with the given key in subtree rooted at x. None if no\n        such key.\n\n        :param x: root of currently inspected subtree.\n        :param key: the key\n        :return: value associated with given key. None if no such key\n\n        \"\"\"\n        while x is not None:\n            if key < x.key:\n                x = x.left\n            elif key > x.key:\n                x = x.right\n            else:\n                return x.val\n        return None\n\n    def delete_min(self) -> None:\n        \"\"\"Removes the smallest key and associated value from the symbol table.\n\n        :raises NoSuchElementException: if the symbol table is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"RedBlackBST underflow\")\n        assert self._root is not None\n        if not self._is_red(self._root.left) and not self._is_red(self._root.right):\n            self._root.color = self.RED\n        self._root = self._delete_min(self._root)\n        if not self.is_empty():\n            assert self._root is not None\n            self._root.color = RedBlackBST.BLACK\n\n    def _delete_min(self, h: Node[Key, Val]) -> Optional[Node[Key, Val]]:\n        \"\"\"Deletes the node with the minimum key rooted at h.\"\"\"\n        if h.left is None:\n            return None\n        if not self._is_red(h.left) and not self._is_red(h.left.left):\n            h = self._move_red_left(h)\n        assert h.left is not None  # because _move_red_left moved something to h.left\n        h.left = self._delete_min(h.left)\n        return self._balance(h)\n\n    def delete_max(self) -> None:\n        \"\"\"Removes the largest key and associated value from the symbol table.\n\n        :raises NoSuchElementException: if the symbol table is empty\n\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"RedBlackBST underflow\")\n        assert self._root is not None\n        if not self._is_red(self._root.left) and not self._is_red(self._root.right):\n            self._root.color = self.RED\n        self._root = self._delete_max(self._root)\n        if not self.is_empty():\n            assert self._root is not None\n            self._root.color = RedBlackBST.BLACK\n\n    def _delete_max(self, h: Node[Key, Val]) -> Optional[Node[Key, Val]]:\n        \"\"\"Deletes the key-value pair with the maximum key rooted at h.\"\"\"\n        if self._is_red(h.left):\n            h = self._rotate_right(h)\n        if h.right is None:\n            return None\n        if not self._is_red(h.right) and not self._is_red(h.right.left):\n            h = self._move_red_right(h)\n        assert h.right is not None  # because _move_red_right moved something to h.right\n        h.right = self._delete_max(h.right)\n        return self._balance(h)\n\n    def delete(self, key: Key) -> None:\n        \"\"\"Removes the specified key and its associated value from this symbol\n        table (if the key is in this symbol table).\n\n        :param key: the key\n        :raises IllegalArgumentException: if key is None\n\n        \"\"\"\n        # Cannot happen if type checked:\n        if key is None:\n            raise IllegalArgumentException(\"argument to delete() is None\")\n        if not self.contains(key):\n            return\n        assert self._root is not None\n        if not self._is_red(self._root.left) and not self._is_red(self._root.right):\n            self._root.color = self.RED\n        self._root = self._delete(self._root, key)\n        if not self.is_empty():\n            assert self._root is not None\n            self._root.color = RedBlackBST.BLACK\n\n    def _delete(self, h: Node[Key, Val], key: Key) -> Optional[Node[Key, Val]]:\n        \"\"\"Deletes the key-value pair with the given key rooted at h.\"\"\"\n        if key < h.key:\n            # we assert (from delete) that key exists in h's subtree, so it must exists\n            # in the left subtree, so h.left is not None\n            assert h.left is not None\n            if not self._is_red(h.left) and not self._is_red(h.left.left):\n                h = self._move_red_left(h)\n            assert h.left is not None  # _move_red_left does what it should\n            h.left = self._delete(h.left, key)\n        else:\n            if self._is_red(h.left):\n                h = self._rotate_right(h)\n            if key == h.key and h.right is None:\n                return None\n            assert h.right is not None  # bc. key must be in the right subtree\n            if not self._is_red(h.right) and not self._is_red(h.right.left):\n                h = self._move_red_right(h)\n            assert h.right is not None\n            if key == h.key:\n                x = self._min(h.right)\n                h.key = x.key\n                h.val = x.val\n                h.right = self._delete_min(h.right)\n            else:\n                h.right = self._delete(h.right, key)\n        return self._balance(h)\n\n    def size(self) -> int:\n        \"\"\"Return the number of key-value pairs in this symbol table.\n\n        :return: the number of key-value pairs in this symbol table\n\n        \"\"\"\n        return self._size(self._root)\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def _size(self, x: Optional[Node[Key, Val]]) -> int:\n        \"\"\"Number of nodes in subtree rooted at x. 0 if x is None.\n\n        :param x: root node of subtree\n        :return: number of nodes in subtree\n\n        \"\"\"\n        if x is None:\n            return 0\n        return x.size\n\n    def contains(self, key: Key) -> bool:\n        \"\"\"Does this symbol table contain the given key?\n\n        :param key: the key\n        :return: True if this symbol table contains key and False otherwise\n\n        \"\"\"\n        return self.get(key) is not None\n\n    def is_empty(self) -> bool:\n        \"\"\"Is this symbol table empty?\n\n        :return: True if this symbol table is empty and False otherwise\n\n        \"\"\"\n        return self._root is None\n\n    @classmethod\n    def _is_red(self, x: Optional[Node[Key, Val]]) -> bool:\n        \"\"\"Is node x red?\n\n        :param x: the node to check\n        :return: True if node is red False otherwise\n\n        \"\"\"\n        if x is None:\n            return False\n        return x.color == RedBlackBST.RED\n\n    def _rotate_left(self, h: Node[Key, Val]) -> Node[Key, Val]:\n        \"\"\"Make a right-leaning link lean to the left.\n\n        :param h:\n        :return: The node that has taken h's position\n\n        \"\"\"\n        x = h.right\n        assert x is not None  # bc h has a right-leaning (red) link\n        h.right = x.left\n        x.left = h\n        x.color = h.color\n        h.color = self.RED\n        x.size = h.size\n        h.size = self._size(h.left) + self._size(h.right) + 1\n        return x\n\n    def _rotate_right(self, h: Node[Key, Val]) -> Node[Key, Val]:\n        \"\"\"Make a left-leaning link lean to the right.\n\n        :param h:\n        :return: The node that has taken h's position\n\n        \"\"\"\n        x = h.left\n        assert x is not None  # bc h has a left-leaning (red) link\n        h.left = x.right\n        x.right = h\n        x.color = h.color\n        h.color = self.RED\n        x.size = h.size\n        h.size = self._size(h.left) + self._size(h.right) + 1\n        return x\n\n    def _flip_colors(self, h: Node[Key, Val]) -> None:\n        \"\"\"Flip the colors of a node and its two children.\n\n        :param h: the node\n\n        \"\"\"\n        assert h.left is not None\n        assert h.right is not None\n        h.color = not h.color\n        h.left.color = not h.left.color\n        h.right.color = not h.right.color\n\n    def _move_red_left(self, h: Node[Key, Val]) -> Node[Key, Val]:\n        \"\"\"Assuming that h is red and both h.left and h.left.left are black,\n        make h.left or one of its children red.\n\n        Assumes h.right exists\n\n        \"\"\"\n        assert h.right is not None\n        self._flip_colors(h)\n        if self._is_red(h.right.left):\n            h.right = self._rotate_right(h.right)\n            h = self._rotate_left(h)\n            self._flip_colors(h)\n        return h\n\n    def _move_red_right(self, h: Node[Key, Val]) -> Node[Key, Val]:\n        \"\"\"Assuming that h is red and both h.right and h.right.left are black,\n        make h.right or one of its children red.\"\"\"\n        assert h.left is not None  # more is true: h.right.left exists and is not red\n        self._flip_colors(h)\n        if self._is_red(h.left.left):\n            h = self._rotate_right(h)\n            self._flip_colors(h)\n        return h\n\n    def _balance(self, h: Node[Key, Val]) -> Node[Key, Val]:\n        \"\"\"Restore red-black tree invariant.\"\"\"\n        if self._is_red(h.right) and not self._is_red(h.left):\n            h = self._rotate_left(h)\n        if self._is_red(h.left):\n            assert h.left is not None\n            if self._is_red(h.left.left):\n                h = self._rotate_right(h)\n        if self._is_red(h.left) and self._is_red(h.right):\n            self._flip_colors(h)\n        h.size = self._size(h.left) + self._size(h.right) + 1\n        return h\n\n    def height(self) -> int:\n        \"\"\"\n        Returns the height of the RedBlackBST\n\n        :return: the height of the RedBlackBST (a 1-node tree has height 0)\n        \"\"\"\n        return self._height(self._root)\n\n    def _height(self, x: Optional[Node[Key, Val]]) -> int:\n        \"\"\"Returns height of subtree rooted at x.\"\"\"\n        if x is None:\n            return -1\n        return 1 + max(self._height(x.left), self._height(x.right))\n\n    def min(self) -> Key:\n        \"\"\"\n        Returns the smallest key in the symbol table.\n\n        :return: the smallest key in the symbol table\n        :raises NoSuchElementException: if the symbol table is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls min() with empty symbol table\")\n        assert self._root is not None\n        return self._min(self._root).key\n\n    def _min(self, x: Node[Key, Val]) -> Node[Key, Val]:\n        \"\"\"Returns the Node with the smallest key in subtree rooted at x.\n\n        None if no such key\n\n        \"\"\"\n        if x.left is None:\n            return x\n        else:\n            return self._min(x.left)\n\n    def max(self) -> Key:\n        \"\"\"\n        Returns the largest key in the symbol table.\n\n        :return: the largest key in the symbol table\n        :raises NoSuchElementException: if the symbol table is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"calls max() with empty symbol table\")\n        assert self._root is not None\n        return self._max(self._root).key\n\n    def _max(self, x: Node[Key, Val]) -> Node[Key, Val]:\n        \"\"\"Returns the node with the largest key in subtree rooted at x.\n\n        None if no such key.\n\n        \"\"\"\n        if x.right is None:\n            return x\n        else:\n            return self._max(x.right)\n\n    def keys(self) -> Queue[Key]:\n        \"\"\"Returns all keys in the symbol table.\n\n        :return: all keys in the symbol table\n\n        \"\"\"\n        if self.is_empty():\n            return Queue()\n        return self.keys_range(self.min(), self.max())\n\n    def keys_range(self, lo: Key, hi: Key) -> Queue[Key]:\n        \"\"\"Returns all keys in the symbol table in the given range.\n\n        :param lo: minimum endpoint\n        :param hi: maximum endpoint\n        :return: all keys in the symbol table between lo (inclusive) and hi (inclusive)\n        :raises IllegalArgumentException: if either lo or hi is None\n\n        \"\"\"\n        if lo is None:\n            raise IllegalArgumentException(\"first argument to keys() is None\")\n        if hi is None:\n            raise IllegalArgumentException(\"second argument to keys() is None\")\n        queue: Queue[Key] = Queue()\n        self._keys(self._root, queue, lo, hi)\n        return queue\n\n    def _keys(\n        self, x: Optional[Node[Key, Val]], queue: Queue[Key], lo: Key, hi: Key\n    ) -> None:\n        \"\"\"Adds the keys between lo and hi in the subtree rooted at x to the\n        queue.\"\"\"\n        if x is None:\n            return\n        if lo < x.key:\n            self._keys(x.left, queue, lo, hi)\n        if not x.key < lo and x.key <= hi:\n            queue.enqueue(x.key)\n        if hi > x.key:\n            self._keys(x.right, queue, lo, hi)\n\n    def select(self, k: int) -> Key:\n        \"\"\"Return the kth smallest key in the symbol table.\n\n        :param k: the order statistic\n        :return: the kth smallest key in the symbol table\n        :raises IllegalArgumentException: unless k is between 0 and n-1\n\n        \"\"\"\n        if k < 0 or k >= self.size():\n            raise IllegalArgumentException(\n                \"argument to select() is invalid: {}\".format(k)\n            )\n        assert self._root is not None  # bc. 0 <= k < self.size()\n        x = self._select(self._root, k)\n        return x.key\n\n    def _select(self, x: Node[Key, Val], k: int) -> Node[Key, Val]:\n        \"\"\"Returns the node with key of rank k in the subtree rooted at x.\"\"\"\n        t = self._size(x.left)\n        if t > k:\n            assert x.left is not None\n            return self._select(x.left, k)\n        elif t < k:\n            assert x.right is not None\n            return self._select(x.right, k - t - 1)\n        else:\n            return x\n\n    def rank(self, key: Key) -> int:\n        \"\"\"Returns the number of keys in the symbol table strictly less than\n        key.\n\n        :param key: the key\n        :return: the number of keys in the symbol table strictly less than key\n        :raises IllegalArgumentException: if key is None\n\n        \"\"\"\n        if key is None:\n            raise IllegalArgumentException(\"argument to rank() is None\")\n        return self._rank(key, self._root)\n\n    def _rank(self, key: Key, x: Optional[Node[Key, Val]]) -> int:\n        \"\"\"Returns the number of keys less than key in the subtree rooted at\n        x.\"\"\"\n        if x is None:\n            return 0\n        if key < x.key:\n            return self._rank(key, x.left)\n        if key > x.key:\n            return 1 + self._size(x.left) + self._rank(key, x.right)\n        else:\n            return self._size(x.left)\n\n    def size_range(self, lo: Key, hi: Key) -> int:\n        \"\"\"Returns the number of keys in the symbol table in the given range.\n\n        :param lo: minimum endpoint\n        :param hi: maximum endpoint\n        :return: the number of keys in the symbol table between lo\n        (inclusive) and hi (inclusive)\n        :raises IllegalArgumentException: if either lo or hi is None\n\n        \"\"\"\n        if lo is None:\n            return IllegalArgumentException(\"first argument to size() is None\")\n        if hi is None:\n            return IllegalArgumentException(\"second argument to size() is None\")\n        if lo > hi:\n            return 0\n        if self.contains(hi):\n            return self.rank(hi) - self.rank(lo) + 1\n        else:\n            return self.rank(hi) - self.rank(lo)\n\n    def floor(self, key: Key) -> Key:\n        \"\"\"Returns the largest key in the symbol table less than or equal to\n        key.\n\n        :param key: the key\n        :return: the largest key in the symbol table less than er equal to key\n        :raises IllegalArgumentException: if key is None\n        :raises NoSuchElementException: if there is no such key\n\n        \"\"\"\n        if key is None:\n            raise IllegalArgumentException(\"argument to floor() is None\")\n        if self.is_empty():\n            raise NoSuchElementException(\"calls floor() with empty symbol table\")\n        x = self._floor(self._root, key)\n        if x is None:\n            raise NoSuchElementException(\"calls floor() with key < min\")\n        return x.key\n\n    def _floor(self, x: Optional[Node[Key, Val]], key: Key) -> Optional[Node[Key, Val]]:\n        \"\"\"Returns the largest key in the subtree rooted at x less than or\n        equal to the given key.\"\"\"\n        if x is None:\n            return None\n        if key == x.key:\n            return x\n        if key < x.key:\n            return self._floor(x.left, key)\n        t = self._floor(x.right, key)\n        if t is not None:\n            return t\n        return x\n\n    def ceiling(self, key: Key) -> Key:\n        \"\"\"Returns the smallest key in the symbol table greater than or equal\n        to key.\n\n        :param key: the key\n        :return: the smallest key in the symbol table greater than or equal to key\n        :raises IllegalArgumentException: if key is None\n        :raises NoSuchElementException: if there is no such key\n\n        \"\"\"\n        if key is None:\n            raise IllegalArgumentException(\"argument to ceiling is None\")\n        if self.is_empty():\n            raise NoSuchElementException(\"calls ceiling() with empty symbol table\")\n        x = self._ceiling(self._root, key)\n        if x is None:\n            raise NoSuchElementException(\"calls ceiling() with key > max\")\n        return x.key\n\n    def _ceiling(\n        self, x: Optional[Node[Key, Val]], key: Key\n    ) -> Optional[Node[Key, Val]]:\n        \"\"\"Returns the node with the smallest key in the subtree rooted at x\n        greater than or equal to the given key.\"\"\"\n        if x is None:\n            return None\n        assert x is not None\n        if key == x.key:\n            return x\n        if key > x.key:\n            return self._ceiling(x.right, key)\n        t = self._ceiling(x.left, key)\n        if t is not None:\n            return t\n        return x\n"
  },
  {
    "path": "itu/algs4/searching/seperate_chaining_hst.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport sys\n\nfrom itu.algs4.searching.sequential_search_st import SequentialSearchST\n\n\nclass SeparateChainingHashST:\n    \"\"\"The SeparateChainingHashST class represents a symbol table of dynamic key-\n    value pairs. It supports the usual put, get, contains, delete, size, and is-\n    empty methods. It also provides a keys method for iterating over all of the\n    keys. A symbol table implements the associative array abstraction: when\n    associating a value with a key that is already in the symbol table, the\n    convention is to replace the old value with the new value. Unlike the Map-\n    class in Java, this class uses the convention that values cannot be null/None.\n    Setting the value associated with a key to None is equivalent to deleting the\n    key from the symbol table.\n\n    This implementation uses a separate chaining hash table. It requires\n    that the key type overrides the __eq__ and __hash__ methods. The\n    expected time per put, contains, or remove operation is constant,\n    subject to the uniform hashing assumption. The size, and is-empty\n    operations take constant time. Construction takes constant time.\n\n    \"\"\"\n\n    def __init__(self, M=997):\n        self.M = M  # Hash table size\n        self.N = 0  # Number of pairs\n        self.st = [SequentialSearchST() for i in range(0, M)]  # Array of ST objects\n\n    def _hash(self, key):\n        # Hash value between 0 and M-1\n        return (hash(key) & 0x7FFFFFFF) % self.M\n\n    def get(self, key):\n        \"\"\"Returns the value associated with the specified key.\n\n        :param key: the key\n        :returns: the value associated with the key in the symbol table;\n                    None if no such value\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to get() is None\")\n        i = self._hash(key)\n        return self.st[i].get(key)\n\n    def put(self, key, value):\n        \"\"\"Inserts the specified key-value paur into the symbol table, overwriting\n        the old value with the new value if the symbol table already contains the\n        specified key. Deletes the specified key (and its associated value) from this\n        symbol table if the specified value is None.\n\n        :param key: the key\n        :param value: the value\n        :raises ValueError: if key is None.\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"first argument to put() is None\")\n        if value is None:\n            self.delete(key)\n            return\n        i = self._hash(key)\n        if not self.st[i].contains(key):\n            self.N += 1\n        self.st[i].put(key, value)\n        self.st[self._hash(key)].put(key, value)\n\n    def size(self):\n        \"\"\"Returns the number of key-value pairs in this symbol table.\n\n        :returns: the number of key-value pairs in this symbol table.\n\n        \"\"\"\n        return self.N\n\n    def is_empty(self):\n        \"\"\"Returns true if the symbol table is empty.\n\n        :returns: True if this symbol table is empty;\n                    False otherwise.\n\n        \"\"\"\n        return self.N == 0\n\n    def contains(self, key):\n        \"\"\"Returns true if this symbol table contains the specified key.\n\n        :param key: the key\n        :returns: True if this symbol table contains the key;\n                    False otherwise.\n        :raises ValueError: if key is None.\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to contains() is None\")\n        return self.get(key) is not None\n\n    def delete(self, key):\n        \"\"\"Removes the specified key and its associated value from this symbol table\n        (if the key is in this symbol table).\n\n        :param key: the key\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to delete() is None\")\n        i = self._hash(key)\n        if self.st[i].contains(key):\n            self.N -= 1\n        self.st[i].delete(key)\n\n    def keys(self):\n        \"\"\"\n        Returns the keys in the symbol table as an iterable\n        :returns: A list containing all keys\n        \"\"\"\n        keys = []\n        for i in range(0, self.M):\n            for key in self.st[i].keys():\n                keys.append(key)\n        return keys\n\n    def __len__(self):\n        return self.size()\n\n\ndef main():\n    \"\"\"Unit tests the SeparateChainingHashST data type.\"\"\"\n    st = SeparateChainingHashST()\n    i = 0\n    for key in sys.argv[1:]:\n        st.put(key, i)\n        i += 1\n    for key in st.keys():\n        print(\"{} {}\".format(key, st.get(key)))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/searching/sequential_search_st.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# This is python3\n\n\nclass SequentialSearchST:\n    \"\"\"The  SequentialSearchST class represents an (unordered) symbol table of\n    generic key-value pairs. It supports the usual put, get, contains, delete,\n    size, and is-empty methods. It also provides a keys method for iterating\n    over all of the keys. A symbol table implements the associative array\n    abstraction: when associating a value with a key that is already in the\n    symbol table, the convention is to replace the old value with the new\n    value. The class also uses the convention that values cannot be  None.\n    Setting the value associated with a key to  None is equivalent to deleting\n    the key from the symbol table.\n\n    This implementation uses a singly-linked list and sequential search.\n    It relies on the  equals() method to test whether two keys are\n    equal. It does not call either the  compareTo() or hashCode()\n    method. The put and delete operations take linear time the get and\n    contains operations takes linear time in the worst case. The size,\n    and is-empty operations take constant time. Construction takes\n    constant time.\n\n    \"\"\"\n\n    class Node:\n        # a helper linked list data type\n        def __init__(self, key, val, next):\n            self.key = key\n            self.val = val\n            self.next = next\n\n    def __init__(self):\n        \"\"\"Initializes an empty symbol table.\"\"\"\n        self._n = 0  # number of key-value pairs\n        self._first = None  # the linked list of key-value pairs\n\n    def size(self):\n        \"\"\"Returns the number of key-value pairs in this symbol table.\n\n        :returns: the number of key-value pairs in this symbol table\n\n        \"\"\"\n        return self._n\n\n    def __len__(self):\n        return self.size()\n\n    def is_empty(self):\n        \"\"\"Returns true if this symbol table is empty.\n\n        :returns:  true if this symbol table is empty\n                 false otherwise\n\n        \"\"\"\n        return self.size() == 0\n\n    def contains(self, key):\n        \"\"\"Returns true if this symbol table contains the specified key.\n\n        :param  key the key\n        :returns: true if this symbol table contains key\n                  false otherwise\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to contains() is None\")\n        return self.get(key) is not None\n\n    def get(self, key):\n        \"\"\"Returns the value associated with the given key in this symbol\n        table.\n\n        :param key: the key\n        :returns: the value associated with the given key if the key is in the symbol table\n                    and None if the key is not in the symbol table\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to get() is None\")\n        x = self._first\n        while x is not None:\n            if key == x.key:\n                return x.val\n            x = x.next\n        return None\n\n    def put(self, key, val):\n        \"\"\"Inserts the specified key-value pair into the symbol table,\n        overwriting the old value with the new value if the symbol table\n        already contains the specified key. Deletes the specified key (and its\n        associated value) from this symbol table if the specified value is\n        None.\n\n        :param key: the key\n        :param val: the value\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to put() is None\")\n        if val is None:\n            self.delete(key)\n            return\n\n        x = self._first\n        while x is not None:\n            if key == x.key:\n                x.val = val\n                return\n            x = x.next\n\n        self._first = self.Node(key, val, self._first)\n        self._n += 1\n\n    def delete(self, key):\n        \"\"\"Removes the specified key and its associated value from this symbol\n        table (if the key is in this symbol table).\n\n        :param  key the key\n        :raises ValueError: if key is None\n\n        \"\"\"\n        if key is None:\n            raise ValueError(\"argument to delete() is None\")\n        self._first = self._delete(self._first, key)\n\n    def _delete(self, x, key):\n        # delete key in linked list beginning at Node x\n        # warning: function call stack too large if table is large\n        if x is None:\n            return None\n        if key == x.key:\n            self._n -= 1\n            return x.next\n\n        x.next = self._delete(x.next, key)\n        return x\n\n    def keys(self):\n        \"\"\"Returns all keys in the symbol table as an  Iterable. To iterate\n        over all of the keys in the symbol table named  st, use the foreach\n        notation: for Key key in st.keys().\n\n        :returns: all keys in the symbol table\n\n        \"\"\"\n        x = self._first\n        while x is not None:\n            yield x.key\n            x = x.next\n\n\nif __name__ == \"__main__\":\n    from itu.algs4.stdlib import stdio\n\n    st = SequentialSearchST()\n    i = 0\n    while not stdio.isEmpty():\n        key = stdio.readString()\n        st.put(key, i)\n        i += 1\n\n    for s in st.keys():\n        stdio.writef(\"%s %i\\n\", s, st.get(s))\n"
  },
  {
    "path": "itu/algs4/searching/set.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom itu.algs4.errors.errors import (\n    IllegalArgumentException,\n    NoSuchElementException,\n    UnsupportedOperationException,\n)\n\n\"\"\"\nSet implementation using Python's set() type.\nDoes not allow duplicates.\n\"\"\"\n\n\nclass SET:\n    # Initializes a new set that is an independent copy of the specified set, or an empty one.\n    def __init__(self, x=None):\n        self._set = set() if x is None else x._set.copy()\n\n    # Adds the key to this set (if it is not already present).\n    def add(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called add() with a None key\")\n        self._set.add(key)\n\n    # Returns true if this set contains the given key.\n    def contains(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called contains() with a None key\")\n        return key in self._set\n\n    # Removes the specified key from this set (if the set contains the specified key).\n    def delete(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called delete() with a None key\")\n        if self.contains(key):\n            self._set.remove(key)\n\n    # Returns the number of keys in this set.\n    def size(self):\n        return len(self._set)\n\n    def __len__(self):\n        return self.size()\n\n    # Returns true if this set is empty.\n    def is_empty(self):\n        return self.size() == 0\n\n    # Returns all of the keys in this set, as an iterator.\n    # To iterate over all of the keys in a set named set, use the\n    # foreach notation: for key in set.\n    def __iter__(self):\n        for k in self._set:\n            yield k\n\n    # Returns the largest key in this set.\n    def max(self):\n        if self.is_empty():\n            raise NoSuchElementException(\"called max() with empty set\")\n        return max(self._set)\n\n    # Returns the smallest key in this set.\n    def min(self):\n        if self.is_empty():\n            raise NoSuchElementException(\"called min() with empty set\")\n        return min(self._set)\n\n    # Returns the smallest key in this set greater than or equal to key.\n    def ceiling(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called ceiling() with None key\")\n        ceiling = None\n        for k in self:\n            if (ceiling is None and k >= key) or (\n                ceiling is not None and k >= key and k < ceiling\n            ):\n                ceiling = k\n        if ceiling is None:\n            raise NoSuchElementException(\"all keys are less than \" + str(key))\n        return ceiling\n\n    # Returns the largest key in this set less than or equal to key.\n    def floor(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called floor() with None key\")\n        floor = None\n        for k in self:\n            if (floor is None and k <= key) or (\n                floor is not None and k <= key and k > floor\n            ):\n                floor = k\n        if floor is None:\n            raise NoSuchElementException(\"all keys are greater than \" + str(key))\n        return floor\n\n    # Returns the union of this set and that set.\n    def union(self, that):\n        if that is None:\n            raise IllegalArgumentException(\"called union() with a None argument\")\n        c = set()\n        for x in self:\n            c.add(x)\n        for x in that:\n            c.add(x)\n        return c\n\n    # Returns the intersection of this set and that set.\n    def intersects(self, that):\n        if that is None:\n            raise IllegalArgumentException(\"called intersects() with a null argument\")\n        c = set()\n        if self.size() < that.size():\n            for x in self:\n                if that.contains(x):\n                    c.add(x)\n        else:\n            for x in that:\n                if self.contains(x):\n                    c.add(x)\n        return c\n\n    # Compares this set to the specified set.\n    def __eq__(self, other):\n        if other is None:\n            return False\n        if type(other) is not type(self):\n            return False\n        return self._set == other._set\n\n    # This operation is not supported because sets are mutable.\n    def hashCode(self):\n        raise UnsupportedOperationException(\n            \"hashCode() is not supported because sets are mutable\"\n        )\n\n    # Returns a string representation of this set.\n    def __repr__(self):\n        s = []\n        for item in self:\n            s.append(\"{}\".format(item))\n        return \"{ \" + \"\".join(s) + \" }\"\n\n\ndef main():\n    set = SET()\n    print(\"set = \" + str(set))\n\n    # insert some keys\n    set.add(\"www.cs.princeton.edu\")\n    set.add(\"www.cs.princeton.edu\")  # overwrite old value\n    set.add(\"www.princeton.edu\")\n    set.add(\"www.math.princeton.edu\")\n    set.add(\"www.yale.edu\")\n    set.add(\"www.amazon.com\")\n    set.add(\"www.simpsons.com\")\n    set.add(\"www.stanford.edu\")\n    set.add(\"www.google.com\")\n    set.add(\"www.ibm.com\")\n    set.add(\"www.apple.com\")\n    set.add(\"www.slashdot.com\")\n    set.add(\"www.whitehouse.gov\")\n    set.add(\"www.espn.com\")\n    set.add(\"www.snopes.com\")\n    set.add(\"www.movies.com\")\n    set.add(\"www.cnn.com\")\n    set.add(\"www.iitb.ac.in\")\n\n    print(set.contains(\"www.cs.princeton.edu\"))\n    print(not set.contains(\"www.harvardsucks.com\"))\n    print(set.contains(\"www.simpsons.com\"))\n    print()\n\n    print(\"ceiling(www.simpsonr.com) = \" + set.ceiling(\"www.simpsonr.com\"))\n    print(\"ceiling(www.simpsons.com) = \" + set.ceiling(\"www.simpsons.com\"))\n    print(\"ceiling(www.simpsont.com) = \" + set.ceiling(\"www.simpsont.com\"))\n    print(\"floor(www.simpsonr.com)   = \" + set.floor(\"www.simpsonr.com\"))\n    print(\"floor(www.simpsons.com)   = \" + set.floor(\"www.simpsons.com\"))\n    print(\"floor(www.simpsont.com)   = \" + set.floor(\"www.simpsont.com\"))\n    print()\n\n    print(\"set = \" + str(set))\n    print()\n\n    # print out all keys in this set in lexicographic order\n    for s in set:\n        print(s)\n\n    print()\n    set2 = SET(set)\n    print(set == set2)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/searching/sparse_vector.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nfrom math import sqrt\n\nfrom itu.algs4.searching.seperate_chaining_hst import SeparateChainingHashST\n\n\nclass SparseVector:\n    \"\"\"The SparseVector class represents a d-dimensional mathematical vector.\n    Vectors are mutable: their values can be changed after they are created. It\n    includes methods for addition, subtraction, dot product, scalar product, unit\n    vector and Euclidean norm.\n\n    The implementation is a symbol table of indices and values for which\n    the vector coordinates are nonzero. This makes it efficient when most\n    of the vector coordinates are zero.\n\n    \"\"\"\n\n    def __init__(self, d):\n        \"\"\"Initializes a d-dimensional zero vector.\n\n        :param d: the dimension of the vector\n\n        \"\"\"\n        self.d = d\n        self.st = SeparateChainingHashST()\n\n    def put(self, i, value):\n        \"\"\"Sets the ith coordinate of this vector to the specified value.\n\n        :param i: the index\n        :param value: the new value\n        :raises ValueError: unless i is between 0 and d-1\n\n        \"\"\"\n        if i < 0 or i >= self.d:\n            raise ValueError(\"Illegal index\")\n        if value == 0.0:\n            self.st.delete(i)\n        else:\n            self.st.put(i, value)\n\n    def get(self, i):\n        \"\"\"Returns the ith coordinate of this vector.\n\n        :param i: the index\n        :returns: the value of the ith coordinate of this vector\n        :raises ValueError: unless i is between 0 and d-1\n\n        \"\"\"\n        if i < 0 or i >= self.d:\n            raise ValueError(\"Illegal index\")\n        if self.st.contains(i):\n            return self.st.get(i)\n        else:\n            return 0.0\n\n    def nnz(self):\n        \"\"\"Returns the number of nonzero entries in this vector.\n\n        :returns: the number of nonzero entries in this vector.\n\n        \"\"\"\n        return self.st.size()\n\n    def dimension(self):\n        \"\"\"Returns the dimension of this vector.\n\n        :returns: the dimension of this vector.\n\n        \"\"\"\n        return self.d\n\n    def dot(self, that):\n        \"\"\"Returns the inner product of this vector with the specified vector.\n\n        :param that: the other vector\n        :returns: the dot product between this vector and that vector\n        :raises ValueError: if the lengths of the two vectors are not equal\n\n        \"\"\"\n        if self.d != that.d:\n            raise ValueError(\"Vector lengths disagree\")\n        sum = 0.0\n\n        # iterate over the vector with the fewest nonzeroes\n        if self.st.size() <= that.st.size():\n            for i in self.st.keys():\n                if that.st.contains(i):\n                    sum += self.get(i) * that.get(i)\n        else:\n            for i in that.st.keys():\n                if self.st.contains(i):\n                    sum += self.get(i) * that.get(i)\n        return sum\n\n    def magnitude(self):\n        \"\"\"Returns the magnitude of this vector. This is also known as the L2 norm or\n        the Euclidean norm.\n\n        :returns: the magnitude of this vector\n\n        \"\"\"\n        return sqrt(self.dot(self))\n\n    def scale(self, alpha):\n        \"\"\"Returns the scalar-vector product of this vector with the specified\n        scalar.\n\n        :param alpha: the scalar\n        :returns: the scalar-vector product of this vector with the specified scalar\n\n        \"\"\"\n        c = SparseVector(self.d)\n        for i in self.st.keys():\n            c.put(i, alpha * self.get(i))\n        return c\n\n    def plus(self, that):\n        \"\"\"Returns the sum of this vector and the specified vector.\n\n        :param that: the vector to add to this vector\n        :returns: the sum of this vector and that vector\n        :raises ValueError: if the dimension of the two vectors are not equal\n\n        \"\"\"\n        if self.d != that.d:\n            raise ValueError(\"Vector lengths disagree\")\n        c = SparseVector(self.d)\n        for i in self.st.keys():\n            c.put(i, self.get(i))\n        for i in that.st.keys():\n            c.put(i, that.get(i) + c.get(i))\n        return c\n\n    def __repr__(self):\n        return \"\".join((\"(%s,%s)\" % (str(i), self.st.get(i))) for i in self.st.keys())\n\n\ndef main():\n    \"\"\"Unit tests the SparseVector data type.\"\"\"\n    a = SparseVector(10)\n    b = SparseVector(10)\n    a.put(3, 0.50)\n    a.put(9, 0.75)\n    a.put(6, 0.11)\n    a.put(6, 0.00)\n    b.put(3, 0.60)\n    b.put(4, 0.90)\n    print(\"a       = {}\".format(a))\n    print(\"b       = {}\".format(b))\n    print(\"a dot b = {}\".format(a.dot(b)))\n    print(\"a + b   = {}\".format(a.plus(b)))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/searching/st.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\nfrom itu.algs4.errors.errors import IllegalArgumentException, NoSuchElementException\n\n\"\"\"\n The ST class represents an ordered symbol table of generic\n key-value pairs.\n\"\"\"\n\n\nclass ST:\n    def __init__(self):\n        self._st = dict()\n\n    # Returns the value associated with the given key in this symbol table.\n    def get(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called get() with None key\")\n        return self._st.get(key)\n\n    # Inserts the specified key-value pair into the symbol table, overwriting the old\n    # value with the new value if the symbol table already contains the specified key.\n    # Deletes the specified key (and its associated value) from this symbol table\n    # if the specified value is None.\n    def put(self, key, val):\n        if key is None:\n            raise IllegalArgumentException(\"called put() with None key\")\n        if val is None:\n            self._st.pop(key, None)\n        else:\n            self._st[key] = val\n\n    # Removes the specified key and its associated value from this symbol table\n    # (if the key is in this symbol table).\n    def delete(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called delete() with None key\")\n        self._st.pop(key, None)\n\n    # Returns true if this symbol table contain the given key.\n    def contains(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called contains() with None key\")\n        return key in self._st\n\n    # Returns the number of key-value pairs in this symbol table.\n    def size(self):\n        return len(self._st)\n\n    def __len__(self):\n        return self.size()\n\n    # Returns true if this symbol table is empty.\n    def is_empty(self):\n        return self.size() == 0\n\n    # Returns all keys in this symbol table.\n    # To iterate over all of the keys in the symbol table named st,\n    # use the foreach notation: for key in st.keys() .\n    def keys(self):\n        return self._st.keys()\n\n    def __iter__(self):\n        for k in self.keys():\n            yield k\n\n    # Returns the smallest key in this symbol table.\n    def min(self):\n        if self.is_empty():\n            raise NoSuchElementException(\"called min() with empty symbol table\")\n        return min(self._st)\n\n    # Returns the largest key in this symbol table.\n    def max(self):\n        if self.is_empty():\n            raise NoSuchElementException(\"called max() with empty symbol table\")\n        return max(self._st)\n\n    # Returns the smallest key in this symbol table greater than or equal to key.\n    def ceiling(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called ceiling() with None key\")\n        keys = self.keys()\n        ceiling = None\n        for k in keys:\n            if (ceiling is None and k >= key) or (\n                ceiling is not None and k >= key and k < ceiling\n            ):\n                ceiling = k\n        if ceiling is None:\n            raise NoSuchElementException(\"all keys are less than \" + str(key))\n        return ceiling\n\n    # Returns the largest key in this symbol table less than or equal to key.\n    def floor(self, key):\n        if key is None:\n            raise IllegalArgumentException(\"called floor() with None key\")\n        keys = self.keys()\n        floor = None\n        for k in keys:\n            if (floor is None and k <= key) or (\n                floor is not None and k <= key and k > floor\n            ):\n                floor = k\n        if floor is None:\n            raise NoSuchElementException(\"all keys are greater than \" + str(key))\n        return floor\n"
  },
  {
    "path": "itu/algs4/sorting/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/sorting/datafiles/tiny.txt",
    "content": "S O R T E X A M P L E\n"
  },
  {
    "path": "itu/algs4/sorting/datafiles/words3.txt",
    "content": "bed bug dad yes zoo\nnow for tip ilk dim \ntag jot sob nob sky\nhut men egg few jay\nowl joy rap gig wee\nwas wad fee tap tar\ndug jam all bad yet\n"
  },
  {
    "path": "itu/algs4/sorting/heap.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom itu.algs4.stdlib import stdio\n\n\"\"\"\nThe heap module provides a function for heapsorting an array.\n\"\"\"\n\n\ndef sort(pq):\n    \"\"\"Rearranges the array in ascending order, using the natural order.\n\n    :param pq: the array to be sorted\n\n    \"\"\"\n    n = len(pq)\n    for k in range(n // 2, 0, -1):\n        _sink(pq, k, n)\n    while n > 1:\n        _exch(pq, 1, n)\n        n -= 1\n        _sink(pq, 1, n)\n\n\ndef _sink(pq, k, n):\n    \"\"\"Moves item at index k down to a legal position on the heap.\n\n    :param k: Index of the item to be moved\n    :param n: Amount of items left on the heap\n\n    \"\"\"\n    while 2 * k <= n:\n        j = 2 * k\n        if j < n and _less(pq, j, j + 1):\n            j += 1\n        if not _less(pq, k, j):\n            break\n        _exch(pq, k, j)\n        k = j\n\n\ndef _less(pq, i, j):\n    \"\"\"Check if item at index i is greater than item at index j on the heap.\n    Indices are \"off-by-one\" to support 1-based indexing.\n\n    :param pq: the heap\n    :param i: index of the first item\n    :param j: index of the second item\n    :return: True if item at index i is smaller than item at index j otherwise False\n\n    \"\"\"\n    return pq[i - 1] < pq[j - 1]\n\n\ndef _exch(pq, i, j):\n    \"\"\"Exchanges the positions of items at index i and j on the heap. Indices\n    are \"off-by-one\" to support 1-based indexing.\n\n    :param pq: the heap\n    :param i: index of the first item\n    :param j: index of the second item\n\n    \"\"\"\n    pq[i - 1], pq[j - 1] = pq[j - 1], pq[i - 1]\n\n\ndef _show(pq):\n    \"\"\"Print the contents of the array.\n\n    :param pq: the array to be printed\n\n    \"\"\"\n    for i in range(len(pq)):\n        print(pq[i])\n\n\ndef main():\n    \"\"\"Reads in a sequence of strings from stdin heapsorts them, and prints the\n    result in ascending order.\"\"\"\n    a = stdio.readAllStrings()\n    sort(a)\n    _show(a)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/sorting/index_min_pq.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom itu.algs4.errors.errors import IllegalArgumentException, NoSuchElementException\n\n\nclass IndexMinPQ:\n    \"\"\"The IndexMinPQ class represents an indexed priority queue of generic\n    keys. It supports the usual insert and delete-the-minimum operations, along\n    with delete and change-the-key methods. In order to let the client refer to\n    the keys on the priority queue,\n\n    an integer between 0 and maxN - 1\n    is associated with each key-the client uses this integer to specify\n    which key to delete or change.\n    It also supports methods for peeking at the minimum key,\n    testing if the priority queue is empty, and iterating through\n    the keys.\n    This implementation uses a binary heap along with an array to associate\n    keys with integers, in the given range.\n    The insert, delete-the-minimum, delete, change-key, decrease-key, and increase-key\n    operations take logarithmic time.\n    The is-empty, size, min-index, min-key, and key-of operations take constant time.\n    Construction takes time proportional to the specified capacity.\n\n    \"\"\"\n\n    def __init__(self, max_n):\n        \"\"\"Initializes an empty indexed priority queue with indices between 0.\n\n        and max_n - 1.\n        :param max_n: the keys on this priority queue are indices from 0 to max_n - 1\n        :raises IllegalArgumentException: if max_n < 0\n\n        \"\"\"\n        self.max_n = max_n\n        self.n = 0\n        self.keys = [None] * (max_n + 1)\n        self.pq = [0] * (max_n + 1)\n        self.qp = [-1] * (max_n + 1)\n\n    def insert(self, i, key):\n        \"\"\"Associates key with index i.\n\n        :param i: an index\n        :param key: the key to associate with index i\n        :raises IllegalArgumentException: unless 0 <= i < max_n\n        :raises IllegalArgumentException: if there already is an item associated with index i\n\n        \"\"\"\n        if i < 0 or i >= self.max_n:\n            raise IllegalArgumentException(\"index is not within range\")\n        if self.contains(i):\n            raise IllegalArgumentException(\"index is already in the priority queue\")\n        self.n += 1\n        self.qp[i] = self.n\n        self.pq[self.n] = i\n        self.keys[i] = key\n        self._swim(self.n)\n\n    def contains(self, i):\n        \"\"\"Is i an index on this priority queue?\n\n        :param i: an index\n        :return: True if i is an index on this priority queue False otherwise\n        :rtype: bool\n        :raises IllegalArgumentException: unless 0 <= i < max_n\n\n        \"\"\"\n        if i < 0 or i >= self.max_n:\n            raise IllegalArgumentException(\"index is not within range\")\n        return self.qp[i] != -1\n\n    def change_key(self, i, key):\n        \"\"\"Change the key associated with index i to the specified value.\n\n        :param i: the index of the key to change\n        :param key: change the key associated with index i to this key\n        :raises IllegalArgumentException: unless 0 <= i < max_n\n        :raises NoSuchElementException: if no key is associated with index i\n\n        \"\"\"\n        if i < 0 or i >= self.max_n:\n            raise IllegalArgumentException(\"index is not within range\")\n        if not self.contains(i):\n            raise NoSuchElementException(\"index is not in the priority queue\")\n        self.keys[i] = key\n        self._swim(self.qp[i])\n        self._sink(self.qp[i])\n\n    def decrease_key(self, i, key):\n        \"\"\"Decrease the key associated with index i to the specified value.\n\n        :param i: the index of the key to decrease\n        :param key: decrease the key associated with index i to this key\n        :raises IllegalArgumentException: unless 0 <= i < max_n\n        :raises IllegalArgumentException: if key >= key_of(i)\n        :raises NoSuchElementException: if no key is associated with index i\n\n        \"\"\"\n        if i < 0 or i >= self.max_n:\n            raise IllegalArgumentException(\"index is not within range\")\n        if not self.contains(i):\n            raise IllegalArgumentException(\"index is not in the priority queue\")\n        if self.keys[i] <= key:\n            raise IllegalArgumentException(\n                \"calling decrease_key() with given argument would not strictly decrease the key\"\n            )\n        self.keys[i] = key\n        self._swim(self.qp[i])\n\n    def increase_key(self, i, key):\n        \"\"\"Increase the key associated with index i to the specified value.\n\n        :param i: the index of the key to increase\n        :param key: increase the key associated with index i to this key\n        :raises IllegalArgumentException: unless 0 <= i < max_n\n        :raises IllegalArgumentException: if key <= key_of(i)\n        :raises NoSuchElementException: if no key is associated with index i\n\n        \"\"\"\n        if i < 0 or i >= self.max_n:\n            raise IllegalArgumentException(\"index is not within range\")\n        if not self.contains(i):\n            raise NoSuchElementException(\"index is not in the priority queue\")\n        if self.keys[i] >= key:\n            raise IllegalArgumentException(\n                \"calling increase_key() with given argument would not strictly increase the key\"\n            )\n        self.keys[i] = key\n        self._sink(self.qp[i])\n\n    def delete(self, i):\n        \"\"\"Remove the key associated with index i.\n\n        :param i: the index of the key to remove\n        :raises IllegalArgumentException: unless 0 <= i < max_n\n        :raises NoSuchElementException: if no key is associated with index i\n\n        \"\"\"\n        if i < 0 or i >= self.max_n:\n            raise IllegalArgumentException(\"index is not in range\")\n        if not self.contains(i):\n            raise NoSuchElementException(\"index is not in the priority queue\")\n        index = self.qp[i]\n        self._exch(index, self.n)\n        self.n -= 1\n        self._sink(index)\n        self.keys[i] = None\n        self.qp[i] = -1\n\n    def min_index(self):\n        \"\"\"\n        Returns an index associated with a minimum key.\n        :return: an index associated with a minimum key\n        :rtype: int\n        :raises NoSuchElementException: if this priority queue is empty\n        \"\"\"\n        if self.n == 0:\n            raise NoSuchElementException(\"Priority queue underflow\")\n        return self.pq[1]\n\n    def min_key(self):\n        \"\"\"\n        Returns a minimum key.\n        :return: a minimum key\n        :raises NoSuchElementException: if this priority queue is empty\n        \"\"\"\n        if self.n == 0:\n            raise NoSuchElementException(\"Priority queue underflow\")\n        return self.keys[self.pq[1]]\n\n    def del_min(self):\n        \"\"\"\n        Removes a minimum key and returns its associated index.\n        :return: an index associated with a minimum key\n        :raises NoSuchElementException: if this priority queue is empty\n        :rtype: int\n        \"\"\"\n        if self.n == 0:\n            raise NoSuchElementException(\"Priority queue underflow\")\n        _min = self.pq[1]\n        self._exch(1, self.n)\n        self.n -= 1\n        self._sink(1)\n        self.qp[_min] = -1\n        self.keys[_min] = None\n        self.pq[self.n + 1] = -1\n        return _min\n\n    def is_empty(self):\n        \"\"\"Returns True if this priority queue is empty.\n\n        :return: True if this priority queue is empty False otherwise\n        :rtype: bool\n\n        \"\"\"\n        return self.n == 0\n\n    def size(self):\n        \"\"\"Returns the number of keys on this priority queue.\n\n        :return: the number of keys on this priority queue\n        :rtype: int\n\n        \"\"\"\n        return self.n\n\n    def __len__(self):\n        return self.size()\n\n    def key_of(self, i):\n        \"\"\"Returns the key associated with index i.\n\n        :param i: the index of the key to return\n        :return: the key associated with index i\n        :raises IllegalArgumentException: unless 0 <= i < max_n\n        :raises NoSuchElementException: if no key is associated with index i\n\n        \"\"\"\n        if i < 0 or i >= self.max_n:\n            raise IllegalArgumentException(\"index is out of range\")\n        if not self.contains(i):\n            raise IllegalArgumentException(\"index is not on the priority queue\")\n        return self.keys[i]\n\n    def _exch(self, i, j):\n        \"\"\"Exchanges the position of items at index i and j on the heap.\n\n        :param i: index of the first item\n        :param j: index of the second item\n\n        \"\"\"\n        self.pq[i], self.pq[j] = self.pq[j], self.pq[i]\n        self.qp[self.pq[i]] = i\n        self.qp[self.pq[j]] = j\n\n    def _greater(self, i, j):\n        \"\"\"Returns True if key at index i on the heap is greater than key at\n        index j.\n\n        :param i: index of the first item\n        :param j: index of the second item\n        :return: True if key at index i on the heap is greater than key at index j\n        :rtype: bool\n\n        \"\"\"\n        return self.keys[self.pq[i]] > self.keys[self.pq[j]]\n\n    def _swim(self, k):\n        \"\"\"Moves item at index k up to a legal position on the heap.\n\n        :param k: Index of the item on the heap to be moved\n\n        \"\"\"\n        while k > 1 and self._greater(k // 2, k):\n            self._exch(k, k // 2)\n            k = k // 2\n\n    def _sink(self, k):\n        \"\"\"Moves item at index k down to a legal position on the heap.\n\n        :param k: Index of the item on the heap to be moved\n\n        \"\"\"\n        while 2 * k <= self.n:\n            j = 2 * k\n            if j < self.n and self._greater(j, j + 1):\n                j += 1\n            if not self._greater(k, j):\n                break\n            self._exch(k, j)\n            k = j\n\n    def __iter__(self):\n        \"\"\"Iterates over all the items in this priority queue in ascending\n        order.\"\"\"\n        copy = IndexMinPQ(len(self.pq) - 1)\n        for i in range(1, self.n + 1):\n            copy.insert(self.pq[i], self.keys[self.pq[i]])\n        while not copy.is_empty():\n            yield copy.del_min()\n\n\ndef main():\n    \"\"\"Inserts a bunch of strings to an indexed priority queue, deletes and\n    prints them, inserts them again, and prints them using an iterator.\"\"\"\n    strings = [\"it\", \"was\", \"the\", \"best\", \"of\", \"times\", \"it\", \"was\", \"the\", \"worst\"]\n    pq = IndexMinPQ(len(strings))\n    for i in range(len(strings)):\n        pq.insert(i, strings[i])\n    while not pq.is_empty():\n        i = pq.del_min()\n        print(\"{} {}\".format(i, strings[i]))\n    print()\n    for i in range(len(strings)):\n        pq.insert(i, strings[i])\n    for i in pq:\n        print(\"{} {}\".format(i, strings[i]))\n    while not pq.is_empty():\n        pq.del_min()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/sorting/insertion_sort.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Insertion module provides static methods for sorting an array using\ninsertion sort.\n\nThis implementation makes ~ 1/2 n^2 compares and exchanges in the worst\ncase, so it is not suitable for sorting large arbitrary arrays. More\nprecisely, the number of exchanges is exactly equal to the number of\ninversions. So, for example, it sorts a partially-sorted array in linear\ntime. The sorting algorithm is stable and uses O(1) extra memory.\n\n\"\"\"\nimport sys\nfrom typing import List, TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef sort(a: List[T]):\n    \"\"\"Rearranges the array in ascending order, using the natural order.\n\n    :param a: the array to be sorted.\n\n    \"\"\"\n    # Sort a[] into increasing order.\n    N = len(a)\n    for i in range(1, N):\n        # Insert a[i] among a[i-1], a[i-2], a[i-3]...\n        for j in range(i, 0, -1):\n            if not _less(a[j], a[j - 1]):\n                break\n            _exch(a, j, j - 1)\n\n\ndef _less(v: T, w: T):\n    return v < w\n\n\ndef _exch(a: List[T], i: int, j: int):\n    t = a[i]\n    a[i] = a[j]\n    a[j] = t\n\n\ndef _show(a: List[T]):\n    # Prints the array on a single line\n    for item in a:\n        print(item, end=\" \")\n    print()\n\n\ndef is_sorted(a: List[T]):\n    \"\"\"Returns true if a is sorted.\n\n    :param a: the array to be checked.\n    :returns: True if a is sorted.\n\n    \"\"\"\n    for i in range(1, len(a)):\n        if _less(a[i], a[i - 1]):\n            return False\n    return True\n\n\ndef main():\n    \"\"\"Reads in a sequence of strings from standard input; Shellsorts them; and\n    prints them to standard output in ascending order.\"\"\"\n    a = sys.argv[1:]\n    sort(a)\n    assert is_sorted(a)\n    _show(a)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/sorting/max_pq.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# Python 3\n\nfrom typing import Generic, Iterator, List, Optional, TypeVar\n\nfrom itu.algs4.errors.errors import NoSuchElementException\nfrom itu.algs4.stdlib import stdio\n\nKey = TypeVar(\"Key\")\n\n\nclass MaxPQ(Generic[Key]):\n    \"\"\"The MaxPQ class represents a priority queue of generic keys.\n\n    It supports the usual insert and delete-the-maximum operations,\n    along with methods for peeking at the maximum key, testing if the\n    priority queue is empty, and iterating through the keys. This\n    implementation uses a binary heap. The insert and delete-the-maximum\n    operations take logarithmic amortized time. The max, size and\n    is_empty operations take constant time. Construction takes time\n    proportional to the specified capacity.\n\n    \"\"\"\n\n    def __init__(self, _max: int = 1):\n        \"\"\"Initializes an empty priority queue with the given initial capacity.\n\n        :param _max: the initial capacity, default value is 1\n\n        \"\"\"\n        self._pq: List[Optional[Key]] = [None] * (_max + 1)\n        self._n = 0\n\n    def insert(self, x: Key) -> None:\n        \"\"\"Adds a new key to this priority queue.\n\n        :param x: the new key to add to this priority queue\n\n        \"\"\"\n        if self._n == len(self._pq) - 1:\n            self._resize(2 * len(self._pq))\n        self._n += 1\n        self._pq[self._n] = x\n        self._swim(self._n)\n\n    def max(self) -> Key:\n        \"\"\"\n        Returns a largest key on this priority queue.\n        :return: a largest key on the priority queue\n        :raises NoSuchElementException: if this priority queue is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"Priority queue underflow\")\n\n        assert self._pq[1] is not None\n        return self._pq[1]\n\n    def del_max(self) -> Key:\n        \"\"\"\n        Removes and returns a largest key on this priority queue.\n        :return: a largest key on this priority queue\n        :raises NoSuchElementException: if this priority queue is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"Priority queue underflow\")\n\n        _max = self._pq[1]\n        assert _max is not None\n        self._exch(1, self._n)\n        self._n -= 1\n        self._sink(1)\n        self._pq[self._n + 1] = None\n        if self._n > 0 and self._n == (len(self._pq) - 1) // 4:\n            self._resize(len(self._pq) // 2)\n        return _max\n\n    def is_empty(self) -> bool:\n        \"\"\"Returns True if this priority queue is empty.\n\n        :return: True if this priority queue is empty otherwise False\n        :rtype: bool\n\n        \"\"\"\n        return self._n == 0\n\n    def size(self) -> int:\n        \"\"\"Returns the number of keys on this priority queue.\n\n        :return: the number of keys on this priority queue\n        :rtype: int\n\n        \"\"\"\n        return self._n\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def _sink(self, k) -> None:\n        \"\"\"Moves item at index k down to a legal position on the heap.\n\n        :param k: Index of the item to be moved\n\n        \"\"\"\n        while 2 * k <= self._n:\n            j = 2 * k\n            if j < self._n and self._less(j, j + 1):\n                j += 1\n            if not self._less(k, j):\n                break\n            self._exch(k, j)\n            k = j\n\n    def _swim(self, k: int) -> None:\n        \"\"\"Moves item at index k up to a legal position on the heap.\n\n        :param k: Index of the item to be moved\n\n        \"\"\"\n        while k > 1 and self._less(k // 2, k):\n            self._exch(k, k // 2)\n            k = k // 2\n\n    def _resize(self, capacity: int):\n        \"\"\"Copies the contents of the heap to a new array of size capacity.\n\n        :param capacity: The capacity of the new array\n\n        \"\"\"\n        temp: List[Optional[Key]] = [None] * capacity\n        for i in range(1, self._n + 1):\n            temp[i] = self._pq[i]\n        self._pq = temp\n\n    def _less(self, i: int, j: int):\n        \"\"\"Check if item at index i is less than item at index j on the heap.\n\n        :param i: index of the first item\n        :param j: index of the second item\n        :return: True if item at index i is smaller than item at index j otherwise False\n\n        \"\"\"\n        return self._pq[i] < self._pq[j]\n\n    def _exch(self, i: int, j: int):\n        \"\"\"Exchanges the position of items at index i and j on the heap.\n\n        :param i: index of the first item\n        :param j: index of the second item\n\n        \"\"\"\n        self._pq[i], self._pq[j] = self._pq[j], self._pq[i]\n\n    def __iter__(self) -> Iterator[Key]:\n        \"\"\"Iterates over all the items in this priority queue in heap order.\"\"\"\n        copy: MaxPQ[Key] = MaxPQ(self.size())\n        for i in range(1, self._n + 1):\n            key = self._pq[i]\n            assert key is not None\n            copy.insert(key)\n        for i in range(1, copy._n + 1):\n            yield copy.del_max()\n\n\ndef main():\n    \"\"\"Reads strings from stdin and adds them to a priority queue.\n\n    When reading a '-' it removes a maximum item on the priority queue\n    and prints it to stdout. Prints the amount of items left on the\n    priority queue\n\n    \"\"\"\n    pq = MaxPQ()\n    while not stdio.isEmpty():\n        item = stdio.readString()\n        if item != \"-\":\n            pq.insert(item)\n        elif not pq.is_empty():\n            print(pq.del_max())\n    print(\"({} left on pq)\".format(pq.size()))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/sorting/merge.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\nfrom typing import List, Optional\n\n\"\"\"\nThis module provides functions for sorting an array using mergesort.\n\nFor additional documentation, see Section 2.2 of Algorithms, 4th Edition\nby Robert Sedgewick and Kevin Wayne.\n\"\"\"\n#  Sorts a sequence of strings from standard input using mergesort\n\n\ndef _is_sorted(a: List, lo: int = 0, hi: Optional[int] = None):\n    # If hi is not specified, use whole array\n    if hi is None:\n        hi = len(a)\n\n    # check if sublist is sorted\n    for i in range(lo + 1, hi):\n        if a[i] < a[i - 1]:\n            return False\n    return True\n\n\n# stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]\ndef _merge(a: List, aux: List, lo: int, mid: int, hi: int):\n    # precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays\n    assert _is_sorted(a, lo, mid)\n    assert _is_sorted(a, mid + 1, hi)\n\n    # copy to aux[]\n    for k in range(lo, hi + 1):\n        aux[k] = a[k]\n\n    # merge back to a[]\n    i, j = lo, mid + 1\n    for k in range(lo, hi + 1):\n        if i > mid:\n            a[k] = aux[j]\n            j += 1\n        elif j > hi:\n            a[k] = aux[i]\n            i += 1\n        elif aux[j] < aux[i]:\n            a[k] = aux[j]\n            j += 1\n        else:\n            a[k] = aux[i]\n            i += 1\n\n    # postcondition: a[lo .. hi] is sorted\n    assert _is_sorted(a, lo, hi)\n\n    # mergesort a[lo..hi] using auxiliary array aux[lo..hi]\n\n\ndef _sort(a: List, aux: List, lo: int, hi: int):\n    if hi <= lo:\n        return\n    mid = lo + (hi - lo) // 2\n    _sort(a, aux, lo, mid)\n    _sort(a, aux, mid + 1, hi)\n    _merge(a, aux, lo, mid, hi)\n\n\ndef sort(a: List):\n    \"\"\"Rearranges the array in ascending order, using the natural order.\n\n    :param a: the array to be sorted\n\n    \"\"\"\n    aux = [None] * len(a)\n    _sort(a, aux, 0, len(a) - 1)\n    assert _is_sorted(a)\n\n\n# Reads in a sequence of strings from standard input or a file\n# supplied as argument to the program; mergesorts them;\n# and prints them to standard output in ascending order.\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.stdlib import stdio\n\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    a = stdio.readAllStrings()\n    sort(a)\n    assert _is_sorted(a)\n    for elem in a:\n        print(elem)\n"
  },
  {
    "path": "itu/algs4/sorting/merge_bu.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module provides functions for sorting an array using bottom-up\nmergesort.\n\nFor additional documentation, see Section 2.1 of Algorithms, 4th Edition\nby Robert Sedgewick and Kevin Wayne.\n\n\"\"\"\n#  Sorts a sequence of strings from standard input using mergesort\n\n\ndef _is_sorted(a, lo=0, hi=None):\n    # If hi is not specified, use whole array\n    if hi is None:\n        hi = len(a)\n\n    # check if sublist is sorted\n    for i in range(lo + 1, hi):\n        if a[i] < a[i - 1]:\n            return False\n    return True\n\n\n# stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]\ndef _merge(a, aux, lo, mid, hi):\n    # copy to aux[]\n    for k in range(lo, hi + 1):\n        aux[k] = a[k]\n\n    # merge back to a[]\n    i, j = lo, mid + 1\n    for k in range(lo, hi + 1):\n        if i > mid:\n            a[k] = aux[j]\n            j += 1\n        elif j > hi:\n            a[k] = aux[i]\n            i += 1\n        elif aux[j] < aux[i]:\n            a[k] = aux[j]\n            j += 1\n        else:\n            a[k] = aux[i]\n            i += 1\n\n\ndef sort(a):\n    \"\"\"Rearranges the array in ascending order, using the natural order.\n\n    :param a: the array to be sorted\n\n    \"\"\"\n    n = len(a)\n    aux = [None] * n\n\n    length = 1\n    while length < n:\n        lo = 0\n        while lo < n - length:\n            mid = lo + length - 1\n            hi = min(mid + length, n - 1)\n            _merge(a, aux, lo, mid, hi)\n            lo += 2 * length\n        length *= 2\n\n    assert _is_sorted(a)\n\n\n# Reads in a sequence of strings from standard input or a file\n# supplied as argument to the program; mergesorts them;\n# and prints them to standard output in ascending order.\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.stdlib import stdio\n\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    a = stdio.readAllStrings()\n    sort(a)\n    for elem in a:\n        print(elem)\n"
  },
  {
    "path": "itu/algs4/sorting/min_pq.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nfrom typing import Generic, List, Optional, TypeVar\n\nfrom itu.algs4.errors.errors import NoSuchElementException\nfrom itu.algs4.stdlib import stdio\n\nKey = TypeVar(\"Key\")\n\n\nclass MinPQ(Generic[Key]):\n    \"\"\"The MinPQ class represents a priority queue of generic keys.\n\n    It supports the usual insert and delete-the-minimum operations,\n    along with methods for peeking at the minimum key, testing if the\n    priority queue is empty, and iterating through the keys. This\n    implementation uses a binary heap. The insert and delete-the-minimum\n    operations take logarithmic amortized time. The min, size and is-\n    empty operations take constant time. Construction takes time\n    proportional to the specified capacity.\n\n    \"\"\"\n\n    def __init__(self, _max: int = 1) -> None:\n        \"\"\"Initializes an empty priority queue with the given initial capacity.\n\n        :param _max: the initial capacity, default value is 1\n\n        \"\"\"\n        self._pq: List[Optional[Key]] = [None] * (_max + 1)\n        self._n = 0\n\n    def insert(self, x: Key) -> None:\n        \"\"\"Adds a new key to this priority queue.\n\n        :param x: the new key to add to this priority queue\n\n        \"\"\"\n        if self._n == len(self._pq) - 1:\n            self._resize(2 * len(self._pq))\n        self._n += 1\n        self._pq[self._n] = x\n        self._swim(self._n)\n\n    def min(self) -> Key:\n        \"\"\"\n        Returns a smallest key on this priority queue.\n        :return: a smallest key on the priority queue\n        :raises NoSuchElementException: if this priority queue is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"Priority queue underflow\")\n\n        assert self._pq[1] is not None\n        return self._pq[1]\n\n    def del_min(self) -> Key:\n        \"\"\"\n        Removes and returns a smallest key on this priority queue.\n        :return: a smallest key on this priority queue\n        :raises NoSuchElementException: if this priority queue is empty\n        \"\"\"\n        if self.is_empty():\n            raise NoSuchElementException(\"Priority queue underflow\")\n\n        _min = self._pq[1]\n        assert _min is not None\n        self._exch(1, self._n)\n        self._n -= 1\n        self._sink(1)\n        self._pq[self._n + 1] = None\n        if self._n > 0 and self._n == (len(self._pq) - 1) // 4:\n            self._resize(len(self._pq) // 2)\n        return _min\n\n    def is_empty(self) -> bool:\n        \"\"\"Returns True if this priority queue is empty.\n\n        :return: True if this priority queue is empty otherwise False\n        :rtype: bool\n\n        \"\"\"\n        return self._n == 0\n\n    def size(self) -> int:\n        \"\"\"Returns the number of keys on this priority queue.\n\n        :return: the number of keys on this priority queue\n        :rtype: int\n\n        \"\"\"\n        return self._n\n\n    def __len__(self) -> int:\n        return self.size()\n\n    def _sink(self, k) -> None:\n        \"\"\"Moves item at index k down to a legal position on the heap.\n\n        :param k: Index of the item to be moved\n\n        \"\"\"\n        while 2 * k <= self._n:\n            j = 2 * k\n            if j < self._n and self._greater(j, j + 1):\n                j += 1\n            if not self._greater(k, j):\n                break\n            self._exch(k, j)\n            k = j\n\n    def _swim(self, k) -> None:\n        \"\"\"Moves item at index k up to a legal position on the heap.\n\n        :param k: Index of the item to be moved\n\n        \"\"\"\n        while k > 1 and self._greater(k // 2, k):\n            self._exch(k, k // 2)\n            k = k // 2\n\n    def _greater(self, i: int, j: int):\n        \"\"\"Check if item at index i is greater than item at index j on the\n        heap.\n\n        :param i: index of the first item\n        :param j: index of the second item\n        :return: True if item at index i is smaller than item at index j otherwise False\n\n        \"\"\"\n        return self._pq[i] > self._pq[j]\n\n    def _resize(self, capacity: int):\n        \"\"\"Copies the contents of the heap to a new array of size capacity.\n\n        :param capacity: The capacity of the new array\n\n        \"\"\"\n        temp: List[Optional[Key]] = [None] * capacity\n        for i in range(1, self._n + 1):\n            temp[i] = self._pq[i]\n        self._pq = temp\n\n    def _exch(self, i: int, j: int):\n        \"\"\"Exchanges the position of items at index i and j on the heap.\n\n        :param i: index of the first item\n        :param j: index of the second item\n\n        \"\"\"\n        self._pq[i], self._pq[j] = self._pq[j], self._pq[i]\n\n    def __iter__(self):\n        \"\"\"Iterates over all the items in this priority queue in ascending\n        order.\"\"\"\n        copy = MinPQ(self.size())\n        for i in range(1, self._n + 1):\n            copy.insert(self._pq[i])\n        for i in range(1, copy._n + 1):\n            yield copy.del_min()\n\n\ndef main():\n    \"\"\"Reads strings from stdin and adds them to a minimum priority queue.\n\n    When reading a '-' it removes the minimum element and prints it to\n    stdout.\n\n    \"\"\"\n    pq = MinPQ()\n    while not stdio.isEmpty():\n        item = stdio.readString()\n        if item != \"-\":\n            pq.insert(item)\n        elif not pq.is_empty():\n            print(pq.del_min())\n    print(\"({} left on pq)\".format(pq.size()))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/sorting/quick3way.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Quick3Way module provides static methods for sorting an array using\nquicksort with 3-way partitioning.\"\"\"\nimport sys\nfrom random import shuffle\n\n\ndef sort(a):\n    \"\"\"Rearranges the array in ascending order using the natural order.\n\n    :param a: the array to be sorted.\n\n    \"\"\"\n    shuffle(a)  # Eliminate dependency on input.\n    _sort(a, 0, len(a) - 1)\n\n\ndef _sort(a, lo, hi):\n    if hi <= lo:\n        return\n    lt = lo\n    i = lo + 1\n    gt = hi\n    v = a[lo]\n    while i <= gt:\n        cmpr = _compare(a[i], v)\n        if cmpr < 0:\n            _exch(a, lt, i)\n            lt += 1\n            i += 1\n        elif cmpr > 0:\n            _exch(a, i, gt)\n            gt -= 1\n        else:\n            i += 1\n    _sort(a, lo, lt - 1)\n    _sort(a, gt + 1, hi)\n    assert is_sorted(a)\n\n\ndef _compare(a, b):\n    return (a > b) - (b > a)\n\n\ndef _less(v, w):\n    return _compare(v, w) < 0\n\n\ndef _exch(a, i, j):\n    t = a[i]\n    a[i] = a[j]\n    a[j] = t\n\n\ndef _show(a):\n    # Prints the array on a single line\n    for item in a:\n        print(item, end=\" \")\n    print()\n\n\ndef is_sorted(a):\n    \"\"\"Returns true if a is sorted.\n\n    :param a: the array to be checked.\n    :returns: True if a is sorted.\n\n    \"\"\"\n    for i in range(1, len(a)):\n        if _less(a[i], a[i - 1]):\n            return False\n    return True\n\n\ndef main():\n    \"\"\"Reads in a sequence of strings from standard input; Shellsorts them; and\n    prints them to standard output in ascending order.\"\"\"\n    a = sys.argv[1:]\n    sort(a)\n    _show(a)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/sorting/quicksort.py",
    "content": "# Created for BADS 2018\n# see README.md for details\n# Python 3\n\n\"\"\"The quicksort module provides methods for sorting an array and selecting the\nith smallest element in an array using quicksort.\n\nFor additional documentation, see Section 2.3 of Algorithms, 4th Edition\nby Robert Sedgewick and Kevin Wayne.\n\n:original author: Robert Sedgewick and Kevin Wayne\n:original java code: https://algs4.cs.princeton.edu/23quicksort/Quick.java.html\n\n\"\"\"\n\nfrom itu.algs4.stdlib import stdio, stdrandom\n\n\ndef sort(array):\n    \"\"\"Rearranges the array in ascending order, using the natural order.\"\"\"\n    stdrandom.shuffle(array)\n    _sort(array, 0, len(array) - 1)\n\n\n# quicksort the subarray from array[lo] to array[hi]\ndef _sort(array, lo, hi):\n    if hi <= lo:\n        return\n    j = _partition(array, lo, hi)\n    _sort(array, lo, j - 1)\n    _sort(array, j + 1, hi)\n\n\n# partition the subarray array[lo..hi] so that\n# array[lo..j-1] <= array[j] <= array[j+1..hi]\n# and return the index j\ndef _partition(array, lo, hi):\n    i = lo\n    j = hi + 1\n    v = array[lo]\n    while True:\n\n        while array[i + 1] < v:\n            i += 1\n            if i == hi:\n                break\n        i += 1\n\n        # find item on hi to swap\n        while v < array[j - 1]:\n            j -= 1\n            if j == lo:\n                break\n        j -= 1\n\n        # check if pointers cross\n        if i >= j:\n            break\n\n        _exch(array, i, j)\n\n    # put partitioning item v at a[j]\n    _exch(array, lo, j)\n\n    # now array[lo .. j-1] <= a[j] <= a[j+1 .. hi]\n    return j\n\n\ndef select(array, k):\n    \"\"\"Rearranges the array so that array[k] contains the kth smalles key;\n    array[0] through array[k-1] are less than (or equal to) array[k]; and\n    array[k+1] through array[n-1] are greather than (or equal to) array[k]\n\n    :param array: the array\n    :param k: the rank of the key\n    :return: the key of rank k\n\n    \"\"\"\n    stdrandom.shuffle(array)\n    lo = 0\n    hi = len(array) - 1\n    while hi > lo:\n        i = _partition(array, lo, hi)\n        if i > k:\n            hi = i - 1\n        elif i < k:\n            lo = i + 1\n        else:\n            return array[i]\n    return array[lo]\n\n\n# exchange array[i] and array[j]\ndef _exch(array, i, j):\n    swap = array[i]\n    array[i] = array[j]\n    array[j] = swap\n\n\n###########################################################\n##### Check if array is sorted - useful for debugging #####\n###########################################################\n\n\ndef is_sorted(array):\n    return _is_sorted(array, 0, len(array) - 1)\n\n\ndef _is_sorted(array, lo, hi):\n    for i in range(lo + 1, hi + 1):\n        if array[i] < array[i - 1]:\n            return False\n    return True\n\n\n# print array to standard output\ndef show(array):\n    stdio.write(\" \".join(array))\n\n\nif __name__ == \"__main__\":\n    array = stdio.readAllStrings()\n    sort(array)\n    assert is_sorted(array)\n    show(array)\n\n    # shuffle\n    stdrandom.shuffle(array)\n\n    # display results again using select\n    print()\n    for i in range(0, len(array)):\n        ith = str(select(array, i))\n        stdio.writeln(ith)\n"
  },
  {
    "path": "itu/algs4/sorting/selection.py",
    "content": "from itu.algs4.stdlib import stdio\n\n# Created for BADS 2018\n# see README.md for details\n# Python 3\n\n\"\"\"\nThe selection module provides a function for sorting an\narray using selection sort.\n\"\"\"\n\n\ndef sort(a):\n    \"\"\"Rearranges the array in ascending order, using the natural order.\n\n    :param a: the array to be sorted\n\n    \"\"\"\n    _n = len(a)\n    for i in range(_n):\n        _min = i\n        for j in range(i + 1, _n):\n            if a[j] < a[_min]:\n                _min = j\n        _exch(a, i, _min)\n\n\ndef _exch(a, i, j):\n    \"\"\"Exchanges the the items at index i and j.\n\n    :param a: the array to be sorted\n    :param i: the index for the first item\n    :param j: the index for the second item\n\n    \"\"\"\n    a[i], a[j] = a[j], a[i]\n\n\ndef _show(a):\n    \"\"\"Prints the content of the array.\n\n    :param a: The array to be shown\n\n    \"\"\"\n    for i in range(len(a)):\n        print(a[i])\n\n\ndef main():\n    \"\"\"Reads strings from stdin, sorts them, and prints the result to\n    stdout.\"\"\"\n    a = stdio.readAllStrings()\n    sort(a)\n    _show(a)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/sorting/shellsort.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Shellsort module provides static methods for sorting an array using\nshellsort with Knuth's increment sequence (1, 4, 13, 40, ...).\"\"\"\nimport sys\n\n\ndef sort(a):\n    \"\"\"Rearranges the array in ascending order using the natural order.\n\n    :param a: the array to be sorted.\n\n    \"\"\"\n    N = len(a)\n    h = 1\n    while h < int(N / 3):\n        h = (3 * h) + 1\n    while h >= 1:\n        # h-sort the array\n        for i in range(h, N):\n            # Insert a[i] among a[i-h], a[i-2*h], a[i-3*h]...\n            for j in range(i, h - 1, -h):\n                if not _less(a[j], a[j - h]):\n                    break\n                _exch(a, j, j - h)\n        h = int(h / 3)\n\n\ndef _less(v, w):\n    return v < w\n\n\ndef _exch(a, i, j):\n    t = a[i]\n    a[i] = a[j]\n    a[j] = t\n\n\ndef _show(a):\n    # Prints the array on a single line\n    for item in a:\n        print(item, end=\" \")\n    print()\n\n\ndef is_sorted(a):\n    \"\"\"Returns true if a is sorted.\n\n    :param a: the array to be checked.\n    :returns: True if a is sorted.\n\n    \"\"\"\n    for i in range(1, len(a)):\n        if _less(a[i], a[i - 1]):\n            return False\n    return True\n\n\ndef main():\n    \"\"\"Reads in a sequence of strings from standard input; Shellsorts them; and\n    prints them to standard output in ascending order.\"\"\"\n    a = sys.argv[1:]\n    sort(a)\n    assert is_sorted(a)\n    _show(a)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/stdlib/__init__.py",
    "content": "\"\"\"This module is based on the code at\nhttps://introcs.cs.princeton.edu/python/code/ written by Robert Sedgewick,\nKevin Wayne, and Robert Dondero.\"\"\"\n"
  },
  {
    "path": "itu/algs4/stdlib/binary_out.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport struct\nimport sys\n\n\"\"\"\nBinary output. This class provides methods for converting\nsome primitive type variables (boolean, byte, char, and int)\nto sequences of bits and writing them\nto an output stream.\nThe output stream can be standard output or another outputstream.\nUses big-endian (most-significant byte first).\n\nThe client must flush() the output stream when finished writing bits.\n\nThe client should not intermix calls to BinaryOut with calls to stdout;\notherwise unexpected behavior will result.\n\"\"\"\n\n\nclass BinaryOut:\n    def __init__(self, os=sys.stdout):\n        \"\"\"Initializes a binary output stream from a specified output stream.\n        Defaults to stdin.\n\n        :param os: the output streamt to write to.\n\n        \"\"\"\n        self.out = os.buffer\n        self.buffer = 0  # 8-bit buffer of bits to write out\n        self.n = 0  # number of bits used in buffer\n\n    def _writeBit(self, x):\n        self.buffer <<= 1\n        if x:\n            self.buffer |= 1\n        self.n += 1\n        if self.n == 8:\n            self._clearBuffer()\n\n    def _writeByte(self, x):\n        assert x >= 0 and x < 256\n        # optimized if byte-alligned\n        if self.n == 0:\n            self.out.write(struct.pack(\"B\", x))\n            return\n        # otherwise write one bit at a time\n        for i in range(0, 8):\n            bit = ((x >> (8 - i - 1)) & 1) == 1\n            self._writeBit(bit)\n\n    def _clearBuffer(self):\n        if self.n == 0:\n            return\n        if self.n > 0:\n            self.buffer <<= 8 - self.n\n        self.out.write(self.buffer.to_bytes(1, \"big\"))\n        self.n = 0\n        self.buffer = 0\n\n    def flush(self):\n        self._clearBuffer()\n        self.out.flush()\n\n    def close(self):\n        self.flush()\n        self.out.close()\n\n    def write_bool(self, x):\n        self._writeBit(x)\n\n    def write_byte(self, x):\n        self._writeByte(x & 0xFF)\n\n    def write_int(self, x):\n        self._writeByte(((x >> 24) & 0xFF))\n        self._writeByte(((x >> 16) & 0xFF))\n        self._writeByte(((x >> 8) & 0xFF))\n        self._writeByte(((x >> 0) & 0xFF))\n\n    def write_char(self, x):\n        if ord(x) < 0 or ord(x) >= 256:\n            raise ValueError(\"Illegal 8-bit char = {}\".format(x))\n        self._writeByte(ord(x))\n\n    def write_string(self, s):\n        for i in s:\n            self.write_char(s[i])\n\n\ndef main():\n    out = BinaryOut()\n    for i in sys.argv[1]:\n        out.write_char(i)\n    out.close()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/stdlib/binary_stdin.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport struct\nimport sys\n\nfrom itu.algs4.stdlib.binary_stdout import BinaryStdOut\n\n\"\"\"\nBinary standard input. This class provides methods for reading\nin bits from standard input, either one bit at a time (as a boolean),\n8 bits at a time (as a char) or 32 bits at a time (as an int)\n\nAll primitive types are assumed to be represented in big-endian order.\n\nThe client should not mix class to BinaryStdIn with calls to stdin,\notherwise unexpected behavior will result.\n\"\"\"\n\n\nclass BinaryStdIn:\n    EOF = -1\n    ins = sys.stdin.buffer\n    n = 0\n    buffer_ = 0\n    is_init = False\n\n    @staticmethod\n    def _initialize():\n        BinaryStdIn.buffer_ = 0\n        BinaryStdIn.n = 0\n        BinaryStdIn._fill_buffer()\n        BinaryStdIn.is_init = True\n\n    @staticmethod\n    def _fill_buffer():\n        x = BinaryStdIn.ins.read(1)\n        if x == b\"\":\n            BinaryStdIn.buffer_ = BinaryStdIn.EOF\n            BinaryStdIn.n = -1\n            return\n        BinaryStdIn.buffer_ = struct.unpack(\"B\", x)[0]\n        BinaryStdIn.n = 8\n\n    @staticmethod\n    def close():\n        \"\"\"Close this input stream and release any associated system resources.\"\"\"\n        if not BinaryStdIn.is_init:\n            BinaryStdIn._initialize()\n        BinaryStdIn.ins.close()\n        BinaryStdIn.is_init = False\n\n    @staticmethod\n    def is_empty():\n        if not BinaryStdIn.is_init:\n            BinaryStdIn._initialize()\n        return BinaryStdIn.buffer_ == BinaryStdIn.EOF\n\n    @staticmethod\n    def read_bool():\n        if BinaryStdIn.is_empty():\n            raise EOFError(\"Reading from empty input stream\")\n        BinaryStdIn.n -= 1\n        bit = ((BinaryStdIn.buffer_ >> BinaryStdIn.n) & 1) == 1\n        if BinaryStdIn.n == 0:\n            BinaryStdIn._fill_buffer()\n        return bit\n\n    @staticmethod\n    def read_char():\n        if BinaryStdIn.is_empty():\n            raise EOFError(\"Reading from empty input stream\")\n        if BinaryStdIn.n == 8:\n            x = BinaryStdIn.buffer_\n            BinaryStdIn._fill_buffer()\n            return chr(x & 0xFF)\n        x = BinaryStdIn.buffer_\n        x <<= 8 - BinaryStdIn.n\n        oldN = BinaryStdIn.n\n        if BinaryStdIn.is_empty():\n            raise EOFError(\"Reading from empty input stream\")\n        BinaryStdIn._fill_buffer()\n        BinaryStdIn.n = oldN\n        x |= BinaryStdIn.buffer_ >> BinaryStdIn.n\n        return chr(x & 0xFF)\n\n    @staticmethod\n    def read_string():\n        if BinaryStdIn.is_empty():\n            raise EOFError(\"Reading from empty input stream\")\n        sb = \"\"\n        while not BinaryStdIn.is_empty():\n            sb += BinaryStdIn.read_char()\n        return sb\n\n    @staticmethod\n    def read_int(r=32):\n        if r == 32:\n            x = 0\n            for _ in range(0, 4):\n                c = BinaryStdIn.read_char()\n                x <<= 8\n                x |= ord(c)\n            return x\n        if r < 1 or r > 32:\n            raise ValueError(\"Illegal value for r = {}\".format(r))\n        x = 0\n        for _ in range(0, r):\n            x <<= 1\n            bit = BinaryStdIn.read_bool()\n            if bit:\n                x |= 1\n        return x\n\n\ndef main():\n    while not BinaryStdIn.is_empty():\n        BinaryStdOut.write_char(BinaryStdIn.read_char())\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/stdlib/binary_stdout.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport struct\nimport sys\n\n\"\"\"\nBinary standard output. This class provides methods for converting\nsome primitive type variables (boolean, byte, char, and int)\nto sequences of bits and writing them\nto an output stream.\nThe output stream can be standard output or another outputstream.\nUses big-endian (most-significant byte first).\n\nThe client must flush() the output stream when finished writing bits.\n\nThe client should not intermix calls to BinaryOut with calls to stdout;\notherwise unexpected behavior will result.\n\"\"\"\n\n\nclass BinaryStdOut:\n    out = sys.stdout.buffer\n    buffer_ = 0\n    n = 0\n    is_init = False\n\n    @staticmethod\n    def _initialize():\n        BinaryStdOut.buffer_ = 0  # 8-bit buffer of bits to write out\n        BinaryStdOut.n = 0  # number of bits used in buffer\n        BinaryStdOut.is_init = True\n\n    @staticmethod\n    def _write_bit(x):\n        if not BinaryStdOut.is_init:\n            BinaryStdOut._initialize()\n        BinaryStdOut.buffer_ <<= 1\n        if x:\n            BinaryStdOut.buffer_ |= 1\n        BinaryStdOut.n += 1\n        if BinaryStdOut.n == 8:\n            BinaryStdOut._clear_buffer()\n\n    @staticmethod\n    def _write_byte(x):\n        if not BinaryStdOut.is_init:\n            BinaryStdOut._initialize()\n        assert x >= 0 and x < 256\n        # optimized if byte-alligned\n        if BinaryStdOut.n == 0:\n            BinaryStdOut.out.write(struct.pack(\"B\", x))\n            return\n        # otherwise write one bit at a time\n        for i in range(0, 8):\n            bit = ((x >> (8 - i - 1)) & 1) == 1\n            BinaryStdOut._write_bit(bit)\n\n    @staticmethod\n    def _clear_buffer():\n        if not BinaryStdOut.is_init:\n            BinaryStdOut._initialize()\n        if BinaryStdOut.n == 0:\n            return\n        if BinaryStdOut.n > 0:\n            BinaryStdOut.buffer_ <<= 8 - BinaryStdOut.n\n        BinaryStdOut.out.write(struct.pack(\"B\", BinaryStdOut.buffer_))\n        BinaryStdOut.n = 0\n        BinaryStdOut.buffer_ = 0\n\n    @staticmethod\n    def flush():\n        BinaryStdOut._clear_buffer()\n        BinaryStdOut.out.flush()\n\n    @staticmethod\n    def close():\n        BinaryStdOut.flush()\n        BinaryStdOut.out.close()\n        BinaryStdOut.is_init = False\n\n    @staticmethod\n    def write_bool(x):\n        BinaryStdOut._write_bit(x)\n\n    @staticmethod\n    def write_byte(x):\n        BinaryStdOut._write_byte(x & 0xFF)\n\n    @staticmethod\n    def write_int(x, r=32):\n        if r == 32:\n            BinaryStdOut._write_byte(((x >> 24) & 0xFF))\n            BinaryStdOut._write_byte(((x >> 16) & 0xFF))\n            BinaryStdOut._write_byte(((x >> 8) & 0xFF))\n            BinaryStdOut._write_byte(((x >> 0) & 0xFF))\n            return\n        if r < 1 or r > 16:\n            raise ValueError(\"Illegal value for r = {}\".format(r))\n        if x < 0 or x >= (1 << r):\n            raise ValueError(\"Illegal {}-bit char = {}\".format(r, x))\n        for i in range(0, r):\n            bit = ((x >> (r - i - 1)) & 1) == 1\n            BinaryStdOut._write_bit(bit)\n\n    @staticmethod\n    def write_char(x, r=8):\n        if r == 8:\n            if ord(x) < 0 or ord(x) >= 256:\n                raise ValueError(\"Illegal 8-bit char = {}\".format(x))\n            BinaryStdOut._write_byte(ord(x))\n            return\n        if r < 1 or r > 16:\n            raise ValueError(\"Illegal value for r = {}\".format(r))\n        if ord(x) >= (1 << r):\n            raise ValueError(\"Illegal {}-bit char = {}\".format(r, x))\n        for i in range(0, r):\n            bit = ((x >> (r - i - 1)) & 1) == 1\n            BinaryStdOut._write_bit(bit)\n\n    def write_string(s, r=8):\n        for i in s:\n            BinaryStdOut.write_char(i, r)\n\n\ndef main():\n    for i in sys.argv[1]:\n        BinaryStdOut.write_char(i)\n    BinaryStdOut.close()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/stdlib/color.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"color.py.\n\nThe color module defines the Color class and some popular Color objects.\n\n\"\"\"\n\n# -----------------------------------------------------------------------\n\n\nclass Color:\n    \"\"\"A Color object models an RGB color.\"\"\"\n\n    # -------------------------------------------------------------------\n\n    def __init__(self, r=0, g=0, b=0):\n        \"\"\"Construct self such that it has the given red (r), green (g), and\n        blue (b) components.\"\"\"\n        self._r = r  # Red component\n        self._g = g  # Green component\n        self._b = b  # Blue component\n\n    # -------------------------------------------------------------------\n\n    def getRed(self):\n        \"\"\"Return the red component of self.\"\"\"\n        return self._r\n\n    # -------------------------------------------------------------------\n\n    def getGreen(self):\n        \"\"\"Return the green component of self.\"\"\"\n        return self._g\n\n    # -------------------------------------------------------------------\n\n    def getBlue(self):\n        \"\"\"Return the blue component of self.\"\"\"\n        return self._b\n\n    # -------------------------------------------------------------------\n\n    def __str__(self):\n        \"\"\"Return the string equivalent of self, that is, a string of the form\n        '(r, g, b)'.\"\"\"\n        # return '#%02x%02x%02x' % (self._r, self._g, self._b)\n        return \"(\" + str(self._r) + \", \" + str(self._g) + \", \" + str(self._b) + \")\"\n\n\n# -----------------------------------------------------------------------\n\n# Some predefined Color objects:\n\nWHITE = Color(255, 255, 255)\nBLACK = Color(0, 0, 0)\n\nRED = Color(255, 0, 0)\nGREEN = Color(0, 255, 0)\nBLUE = Color(0, 0, 255)\n\nCYAN = Color(0, 255, 255)\nMAGENTA = Color(255, 0, 255)\nYELLOW = Color(255, 255, 0)\n\nDARK_RED = Color(128, 0, 0)\nDARK_GREEN = Color(0, 128, 0)\nDARK_BLUE = Color(0, 0, 128)\n\nGRAY = Color(128, 128, 128)\nDARK_GRAY = Color(64, 64, 64)\nLIGHT_GRAY = Color(192, 192, 192)\n\nORANGE = Color(255, 200, 0)\nVIOLET = Color(238, 130, 238)\nPINK = Color(255, 175, 175)\n\n# Shade of blue used in Introduction to Programming in Java.\n# It is Pantone 300U. The RGB values are approximately (9, 90, 166).\nBOOK_BLUE = Color(9, 90, 166)\nBOOK_LIGHT_BLUE = Color(103, 198, 243)\n\n# Shade of red used in Algorithms 4th edition\nBOOK_RED = Color(150, 35, 31)\n\n# -----------------------------------------------------------------------\n\n\ndef _main():\n    \"\"\"For testing:\"\"\"\n    from itu.algs4.stdlib import stdio\n\n    c1 = Color(128, 128, 128)\n    stdio.writeln(c1)\n    stdio.writeln(c1.getRed())\n    stdio.writeln(c1.getGreen())\n    stdio.writeln(c1.getBlue())\n\n\nif __name__ == \"__main__\":\n    _main()\n"
  },
  {
    "path": "itu/algs4/stdlib/instream.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"instream.py.\n\nThe instream module defines the InStream class.\n\n\"\"\"\n\n# -----------------------------------------------------------------------\n\nimport re\nimport sys\n\nif sys.hexversion < 0x03000000:\n    import urllib\nelse:\n    from urllib import request as urllib\n\n# -----------------------------------------------------------------------\n\n\nclass InStream:\n\n    \"\"\"An InStream object wraps around a text file or sys.stdin, and supports\n    reading from that stream.\n\n    Note:  Usually it's a bad idea to mix these three sets of methods:\n\n    -- isEmpty(), readInt(), readFloat(), readBool(), readString()\n\n    -- hasNextLine(), readLine()\n\n    -- readAll(), readAllInts(), readAllFloats(), readAllBools(),\n       readAllStrings(), readAllLines()\n\n    Usually it's better to use one set exclusively.\n\n    \"\"\"\n\n    # -------------------------------------------------------------------\n\n    def __init__(self, fileOrUrl=None):\n        \"\"\"Construct self to wrap around a stream.\n\n        The stream can be a file whose name is given as fileOrUrl, a\n        resource whose URL is given as fileOrUrl, or sys.stdin by\n        default.\n\n        \"\"\"\n        self._buffer = \"\"\n        self._stream = None\n        self._readingWebPage = False\n\n        if fileOrUrl is None:\n            # To change the mode of sys.stdin:\n            from itu.algs4.stdlib import stdio  # noqa: F401\n\n            self._stream = sys.stdin\n            return\n\n        # Try to open a file, then a URL.\n        try:\n            if sys.hexversion < 0x03000000:\n                self._stream = open(fileOrUrl, \"rU\")\n            else:\n                self._stream = open(fileOrUrl, \"r\", encoding=\"utf-8\")\n        except IOError:\n            try:\n                self._stream = urllib.urlopen(fileOrUrl)\n                self._readingWebPage = True\n            except IOError:\n                raise IOError(\"No such file or URL: \" + fileOrUrl)\n\n    # -------------------------------------------------------------------\n\n    def _readRegExp(self, regExp):\n        \"\"\"Discard leading white space characters from the stream wrapped by\n        self.\n\n        Then read from the stream and return a string matching regular\n        expression regExp.  Raise an EOFError if no non-whitespace\n        characters remain in the stream. Raise a ValueError if the next\n        characters to be read from the stream do not match regExp.\n\n        \"\"\"\n        if self.isEmpty():\n            raise EOFError()\n        compiledRegExp = re.compile(r\"^\\s*\" + regExp)\n        match = compiledRegExp.search(self._buffer)\n        if match is None:\n            raise ValueError()\n        s = match.group()\n        self._buffer = self._buffer[match.end() :]\n        return s.lstrip()\n\n    # -------------------------------------------------------------------\n\n    def isEmpty(self):\n        \"\"\"Return True iff no non-whitespace characters remain in the stream\n        wrapped by self.\"\"\"\n        while self._buffer.strip() == \"\":\n            line = self._stream.readline()\n            if sys.hexversion < 0x03000000 or self._readingWebPage:\n                line = line.decode(\"utf-8\")\n            if line == \"\":\n                return True\n            self._buffer += str(line)\n        return False\n\n    # -------------------------------------------------------------------\n\n    def readInt(self):\n        \"\"\"Discard leading white space characters from the stream wrapped by\n        self.\n\n        Then read from the stream a sequence of characters comprising an\n        integer.  Convert the sequence of characters to an integer, and\n        return the integer.  Raise an EOFError if no non-whitespace\n        characters remain in the stream.  Raise a ValueError if the next\n        characters to be read from the stream cannot comprise an\n        integer.\n\n        \"\"\"\n        s = self._readRegExp(r\"[-+]?(0[xX][\\dA-Fa-f]+|0[0-7]*|\\d+)\")\n        radix = 10\n        strLength = len(s)\n        if (strLength >= 1) and (s[0:1] == \"0\"):\n            radix = 8\n        if (strLength >= 2) and (s[0:2] == \"-0\"):\n            radix = 8\n        if (strLength >= 2) and (s[0:2] == \"0x\"):\n            radix = 16\n        if (strLength >= 2) and (s[0:2] == \"0X\"):\n            radix = 16\n        if (strLength >= 3) and (s[0:3] == \"-0x\"):\n            radix = 16\n        if (strLength >= 3) and (s[0:3] == \"-0X\"):\n            radix = 16\n        return int(s, radix)\n\n    # -------------------------------------------------------------------\n\n    def readAllInts(self):\n        \"\"\"Read all remaining strings from the stream wrapped by self, convert\n        each to an int, and return those ints in an array.\n\n        Raise a ValueError if any of the strings cannot be converted to\n        an int.\n\n        \"\"\"\n        strings = self.readAllStrings()\n        ints = []\n        for s in strings:\n            i = int(s)\n            ints.append(i)\n        return ints\n\n    # -------------------------------------------------------------------\n\n    def readFloat(self):\n        \"\"\"Discard leading white space characters from the stream wrapped by\n        self.\n\n        Then read from the stream a sequence of characters comprising a\n        float.  Convert the sequence of characters to an float, and\n        return the float.  Raise an EOFError if no non-whitespace\n        characters remain in the stream.  Raise a ValueError if the next\n        characters to be read from the stream cannot comprise a float.\n\n        \"\"\"\n        s = self._readRegExp(r\"[-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?\")\n        return float(s)\n\n    # -------------------------------------------------------------------\n\n    def readAllFloats(self):\n        \"\"\"Read all remaining strings from the stream wrapped by self, convert\n        each to a float, and return those floats in an array.\n\n        Raise a ValueError if any of the strings cannot be converted to\n        a float.\n\n        \"\"\"\n        strings = self.readAllStrings()\n        floats = []\n        for s in strings:\n            f = float(s)\n            floats.append(f)\n        return floats\n\n    # -------------------------------------------------------------------\n\n    def readBool(self):\n        \"\"\"Discard leading white space characters from the stream wrapped by\n        self.\n\n        Then read from the stream a sequence of characters comprising a\n        bool.  Convert the sequence of characters to an bool, and return\n        the bool.  Raise an EOFError if no non-whitespace characters\n        remain in the stream.  Raise a ValueError if the next characters\n        to be read from the stream cannot comprise an bool.\n\n        \"\"\"\n        s = self._readRegExp(r\"(True)|(False)|1|0\")\n        if (s == \"True\") or (s == \"1\"):\n            return True\n        return False\n\n    # -----------------------------------------------------------------------\n\n    def readAllBools(self):\n        \"\"\"Read all remaining strings from the stream wrapped by self, convert\n        each to a bool, and return those bools in an array.\n\n        Raise a ValueError if any of the strings cannot be converted to\n        a bool.\n\n        \"\"\"\n        strings = self.readAllStrings()\n        bools = []\n        for s in strings:\n            b = bool(s)\n            bools.append(b)\n        return bools\n\n    # -------------------------------------------------------------------\n\n    def readString(self):\n        \"\"\"Discard leading white space characters from the stream wrapped by\n        self.\n\n        Then read from the stream a sequence of characters comprising a\n        string, and return the string. Raise an EOFError if no non-\n        whitespace characters remain in the stream.\n\n        \"\"\"\n        s = self._readRegExp(r\"\\S+\")\n        return s\n\n    # -----------------------------------------------------------------------\n\n    def readAllStrings(self):\n        \"\"\"Read all remaining strings from the stream wrapped by self, and\n        return them in an array.\"\"\"\n        strings = []\n        while not self.isEmpty():\n            s = self.readString()\n            strings.append(s)\n        return strings\n\n    # -------------------------------------------------------------------\n\n    def hasNextLine(self):\n        \"\"\"Return True iff the stream wrapped by self has a next line.\"\"\"\n        if self._buffer != \"\":\n            return True\n        else:\n            self._buffer = self._stream.readline()\n            if sys.hexversion < 0x03000000 or self._readingWebPage:\n                self._buffer = self._buffer.decode(\"utf-8\")\n            if self._buffer == \"\":\n                return False\n            return True\n\n    # -------------------------------------------------------------------\n\n    def readLine(self):\n        \"\"\"Read and return as a string the next line of the stream wrapped by\n        self.\n\n        Raise an EOFError is there is no next line.\n\n        \"\"\"\n        if not self.hasNextLine():\n            raise EOFError()\n        s = self._buffer\n        self._buffer = \"\"\n        return s.rstrip(\"\\n\")\n\n    # -------------------------------------------------------------------\n\n    def readAllLines(self):\n        \"\"\"Read all remaining lines from the stream wrapped by self, and return\n        them as strings in an array.\"\"\"\n        lines = []\n        while self.hasNextLine():\n            line = self.readLine()\n            lines.append(line)\n        return lines\n\n    # -------------------------------------------------------------------\n\n    def readAll(self):\n        \"\"\"Read and return as a string all remaining lines of the stream\n        wrapped by self.\"\"\"\n        s = self._buffer\n        self._buffer = \"\"\n        for line in self._stream:\n            if sys.hexversion < 0x03000000 or self._readingWebPage:\n                line = line.decode(\"utf-8\")\n            s += line\n        return s\n\n    # -------------------------------------------------------------------\n\n    def __del__(self):\n        \"\"\"Close the stream wrapped by self.\"\"\"\n        if self._stream is not None:\n            self._stream.close()\n\n\n# =======================================================================\n# For Testing\n# =======================================================================\n\n\ndef _main():\n    \"\"\"For testing.\n\n    The first command-line argument should be the name of the method\n    that should be called. The optional second command-line argument\n    should be the file or URL to read.\n\n    \"\"\"\n\n    from itu.algs4.stdlib import stdio\n\n    testId = sys.argv[1]\n    if len(sys.argv) > 2:\n        inStream = InStream(sys.argv[2])\n    else:\n        inStream = InStream()\n\n    if testId == \"readInt\":\n        stdio.writeln(inStream.readInt())\n    elif testId == \"readAllInts\":\n        stdio.writeln(inStream.readAllInts())\n    elif testId == \"readFloat\":\n        stdio.writeln(inStream.readFloat())\n    elif testId == \"readAllFloats\":\n        stdio.writeln(inStream.readAllFloats())\n    elif testId == \"readBool\":\n        stdio.writeln(inStream.readBool())\n    elif testId == \"readAllBools\":\n        stdio.writeln(inStream.readAllBools())\n    elif testId == \"readString\":\n        stdio.writeln(inStream.readString())\n    elif testId == \"readAllStrings\":\n        stdio.writeln(inStream.readAllStrings())\n    elif testId == \"readLine\":\n        stdio.writeln(inStream.readLine())\n    elif testId == \"readAllLines\":\n        stdio.writeln(inStream.readAllLines())\n    elif testId == \"readAll\":\n        stdio.writeln(inStream.readAll())\n\n\nif __name__ == \"__main__\":\n    _main()\n"
  },
  {
    "path": "itu/algs4/stdlib/outstream.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"outstream.py.\n\nThe outstream module defines the OutStream class.\n\n\"\"\"\n\nimport sys\n\n# -----------------------------------------------------------------------\n\n\nclass OutStream:\n\n    \"\"\"An OutStream object wraps around a text file or sys.stdout, and supports\n    writing to that stream.\"\"\"\n\n    # -------------------------------------------------------------------\n\n    def __init__(self, f=None):\n        \"\"\"Construct self to wrap around a stream.\n\n        If f is provided, then the stream is a file of that name.\n        Otherwise the stream is standard output.\n\n        \"\"\"\n        if f is None:\n            self._stream = sys.stdout\n        else:\n            if sys.hexversion < 0x03000000:\n                self._stream = open(f, \"w\")\n            else:\n                self._stream = open(f, \"w\", encoding=\"utf-8\")\n\n    # -------------------------------------------------------------------\n\n    def writeln(self, x=\"\"):\n        \"\"\"Write x and an end-of-line mark to the stream wrapped by self.\"\"\"\n        if sys.hexversion < 0x03000000:\n            print(\"Error: Python 3 is required.\", file=sys.stderr)\n            sys.exit(1)\n            # x = unicode(x)\n            # x = x.encode(\"utf-8\")\n        else:\n            x = str(x)\n        self._stream.write(x)\n        self._stream.write(\"\\n\")\n        self._stream.flush()\n\n    # -------------------------------------------------------------------\n\n    def write(self, x=\"\"):\n        \"\"\"Write x to the stream wrapped by self.\"\"\"\n        if sys.hexversion < 0x03000000:\n            print(\"Error: Python 3 is required.\", file=sys.stderr)\n            sys.exit(1)\n            # x = unicode(x)\n            # x = x.encode(\"utf-8\")\n        else:\n            x = str(x)\n        self._stream.write(x)\n        self._stream.flush()\n\n    # -------------------------------------------------------------------\n\n    def writef(self, fmt, *args):\n        \"\"\"Write each element of args to the stream wrapped by self.\n\n        Use the format specified by string fmt.\n\n        \"\"\"\n        x = fmt % args\n        if sys.hexversion < 0x03000000:\n            print(\"Error: Python 3 is required.\", file=sys.stderr)\n            sys.exit(1)\n            # x = unicode(x)\n            # x = x.encode(\"utf-8\")\n        self._stream.write(x)\n        self._stream.flush()\n\n    # -------------------------------------------------------------------\n\n    def __del__(self):\n        \"\"\"Close the stream wrapped by self.\"\"\"\n        self._stream.close()\n"
  },
  {
    "path": "itu/algs4/stdlib/picture.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"picture.py.\n\nThe picture module defines the Picture class.\n\n\"\"\"\n\n# -----------------------------------------------------------------------\n\nimport pygame\n\nfrom itu.algs4.stdlib import color as color\n\n# -----------------------------------------------------------------------\n\n_DEFAULT_WIDTH = 512\n_DEFAULT_HEIGHT = 512\n\n# -----------------------------------------------------------------------\n\n\nclass Picture:\n    \"\"\"A Picture object models an image.\n\n    It is initialized such that it has a given width and height and\n    contains all black pixels. Subsequently you can load an image from a\n    given JPG or PNG file.\n\n    \"\"\"\n\n    def __init__(self, arg1=None, arg2=None):\n        \"\"\"If both arg1 and arg2 are None, then construct self such that it is\n        all black with _DEFAULT_WIDTH and height _DEFAULT_HEIGHT.\n\n        If arg1 is not None and arg2 is None, then construct self by\n        reading from the file whose name is arg1. If neither arg1 nor\n        arg2 is None, then construct self such that it is all black with\n        width arg1 and and height arg2.\n\n        \"\"\"\n        if (arg1 is None) and (arg2 is None):\n            maxW = _DEFAULT_WIDTH\n            maxH = _DEFAULT_HEIGHT\n            self._surface = pygame.Surface((maxW, maxH))\n            self._surface.fill((0, 0, 0))\n        elif (arg1 is not None) and (arg2 is None):\n            fileName = arg1\n            try:\n                self._surface = pygame.image.load(fileName)\n            except pygame.error:\n                raise IOError()\n        elif (arg1 is not None) and (arg2 is not None):\n            maxW = arg1\n            maxH = arg2\n            self._surface = pygame.Surface((maxW, maxH))\n            self._surface.fill((0, 0, 0))\n        else:\n            raise ValueError()\n\n    # -------------------------------------------------------------------\n\n    # def load(self, f):\n    #    \"\"\"\n    #    Change self by reading from the file whose name is f. The\n    #    dimensions of the read image override the dimensions specified\n    #    in the constructor.\n    #    \"\"\"\n    # if sys.hexversion >= 0x03000000:\n    #    # Hack because Pygame without full image support\n    #    # can handle only .bmp files.\n    #    bmpFileName = f + '.bmp'\n    #    os.system('convert ' + f + ' ' + bmpFileName)\n    #    self._surface = pygame.image.load(bmpFileName)\n    #    os.system('rm ' + bmpFileName)\n    # else:\n    #    self._surface = pygame.image.load(f)\n\n    #    self._surface = pygame.image.load(f)\n\n    # -------------------------------------------------------------------\n\n    def save(self, f):\n        \"\"\"Save self to the file whose name is f.\"\"\"\n        # if sys.hexversion >= 0x03000000:\n        #    # Hack because Pygame without full image support\n        #    # can handle only .bmp files.\n        #    bmpFileName = f + '.bmp'\n        #    pygame.image.save(self._surface, bmpFileName)\n        #    os.system('convert ' + bmpFileName + ' ' + f)\n        #    os.system('rm ' + bmpFileName)\n        # else:\n        #    pygame.image.save(self._surface, f)\n\n        pygame.image.save(self._surface, f)\n\n    # -------------------------------------------------------------------\n\n    def width(self):\n        \"\"\"Return the width of self.\"\"\"\n        return self._surface.get_width()\n\n    # -------------------------------------------------------------------\n\n    def height(self):\n        \"\"\"Return the height of self.\"\"\"\n        return self._surface.get_height()\n\n    # -------------------------------------------------------------------\n\n    def get(self, x, y):\n        \"\"\"Return the color of self at location (x, y).\"\"\"\n        pygameColor = self._surface.get_at((x, y))\n        return color.Color(pygameColor.r, pygameColor.g, pygameColor.b)\n\n    # -------------------------------------------------------------------\n\n    def set(self, x, y, c):\n        \"\"\"Set the color of self at location (x, y) to c.\"\"\"\n        pygameColor = pygame.Color(c.getRed(), c.getGreen(), c.getBlue(), 0)\n        self._surface.set_at((x, y), pygameColor)\n"
  },
  {
    "path": "itu/algs4/stdlib/stdarray.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdarray.py.\n\nThe stdarray module defines functions related to creating, reading, and\nwriting one- and two-dimensional arrays.\n\n\"\"\"\n\nfrom itu.algs4.stdlib import stdio\n\n# =======================================================================\n# Array creation functions\n# =======================================================================\n\n\ndef create1D(length, value=None):\n    \"\"\"Create and return a 1D array containing length elements, each\n    initialized to value.\"\"\"\n    return [value] * length\n\n\n# -----------------------------------------------------------------------\n\n\ndef create2D(rowCount, colCount, value=None):\n    \"\"\"Create and return a 2D array having rowCount rows and colCount columns,\n    with each element initialized to value.\"\"\"\n    a = [None] * rowCount\n    for row in range(rowCount):\n        a[row] = [value] * colCount\n    return a\n\n\n# =======================================================================\n# Array writing functions\n# =======================================================================\n\n\ndef write1D(a):\n    \"\"\"Write array a to sys.stdout.\n\n    First write its length. bool objects are written as 0 and 1, not\n    False and True.\n\n    \"\"\"\n    length = len(a)\n    stdio.writeln(length)\n    for i in range(length):\n        # stdio.writef('%9.5f ', a[i])\n        element = a[i]\n        if isinstance(element, bool):\n            if element:\n                stdio.write(1)\n            else:\n                stdio.write(0)\n        else:\n            stdio.write(element)\n        stdio.write(\" \")\n    stdio.writeln()\n\n\n# -----------------------------------------------------------------------\n\n\ndef write2D(a):\n    \"\"\"Write two-dimensional array a to sys.stdout.\n\n    First write its dimensions. bool objects are written as 0 and 1, not\n    False and True.\n\n    \"\"\"\n    rowCount = len(a)\n    colCount = len(a[0])\n    stdio.writeln(str(rowCount) + \" \" + str(colCount))\n    for row in range(rowCount):\n        for col in range(colCount):\n            # stdio.writef('%9.5f ', a[row][col])\n            element = a[row][col]\n            if isinstance(element, bool):\n                if element:\n                    stdio.write(1)\n                else:\n                    stdio.write(0)\n            else:\n                stdio.write(element)\n            stdio.write(\" \")\n        stdio.writeln()\n\n\n# =======================================================================\n# Array reading functions\n# =======================================================================\n\n\ndef readInt1D():\n    \"\"\"Read from sys.stdin and return an array of integers.\n\n    An integer at the beginning of sys.stdin defines the array's length.\n\n    \"\"\"\n    count = stdio.readInt()\n    a = create1D(count, None)\n    for i in range(count):\n        a[i] = stdio.readInt()\n    return a\n\n\n# -----------------------------------------------------------------------\n\n\ndef readInt2D():\n    \"\"\"Read from sys.stdin and return a two-dimensional array of integers.\n\n    Two integers at the beginning of sys.stdin define the array's\n    dimensions.\n\n    \"\"\"\n    rowCount = stdio.readInt()\n    colCount = stdio.readInt()\n    a = create2D(rowCount, colCount, 0)\n    for row in range(rowCount):\n        for col in range(colCount):\n            a[row][col] = stdio.readInt()\n    return a\n\n\n# -----------------------------------------------------------------------\n\n\ndef readFloat1D():\n    \"\"\"Read from sys.stdin and return an array of floats.\n\n    An integer at the beginning of sys.stdin defines the array's length.\n\n    \"\"\"\n    count = stdio.readInt()\n    a = create1D(count, None)\n    for i in range(count):\n        a[i] = stdio.readFloat()\n    return a\n\n\n# -----------------------------------------------------------------------\n\n\ndef readFloat2D():\n    \"\"\"Read from sys.stdin and return a two-dimensional array of floats.\n\n    Two integers at the beginning of sys.stdin define the array's\n    dimensions.\n\n    \"\"\"\n    rowCount = stdio.readInt()\n    colCount = stdio.readInt()\n    a = create2D(rowCount, colCount, 0.0)\n    for row in range(rowCount):\n        for col in range(colCount):\n            a[row][col] = stdio.readFloat()\n    return a\n\n\n# -----------------------------------------------------------------------\n\n\ndef readBool1D():\n    \"\"\"Read from sys.stdin and return an array of booleans.\n\n    An integer at the beginning of sys.stdin defines the array's length.\n\n    \"\"\"\n    count = stdio.readInt()\n    a = create1D(count, None)\n    for i in range(count):\n        a[i] = stdio.readBool()\n    return a\n\n\n# -----------------------------------------------------------------------\n\n\ndef readBool2D():\n    \"\"\"Read from sys.stdin and return a two-dimensional array of booleans.\n\n    Two integers at the beginning of sys.stdin define the array's\n    dimensions.\n\n    \"\"\"\n    rowCount = stdio.readInt()\n    colCount = stdio.readInt()\n    a = create2D(rowCount, colCount, False)\n    for row in range(rowCount):\n        for col in range(colCount):\n            a[row][col] = stdio.readBool()\n    return a\n\n\n# =======================================================================\n\n\ndef _main():\n    \"\"\"For testing.\"\"\"\n    write2D(readFloat2D())\n    write2D(readBool2D())\n\n\nif __name__ == \"__main__\":\n    _main()\n"
  },
  {
    "path": "itu/algs4/stdlib/stdaudio.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdaudio.py.\n\nThe stdaudio module defines functions related to audio.\n\n\"\"\"\n\n# -----------------------------------------------------------------------\n\nimport sys\n\nimport numpy\nimport pygame\n\nfrom itu.algs4.stdlib import stdio as stdio\n\n# -----------------------------------------------------------------------\n\n_SAMPLES_PER_SECOND = 44100\n_SAMPLE_SIZE = -16  # Each sample is a signed 16-bit int\n_CHANNEL_COUNT = 1  # 1 => mono, 2 => stereo\n_AUDIO_BUFFER_SIZE = 1024  # In number of samples\n_CHECK_RATE = 44100  # How often to check the queue\n\n_myBuffer = []\n_MY_BUFFER_MAX_LENGTH = 4096  # Determined experimentally.\n\n\ndef wait():\n    \"\"\"Wait for the sound queue to become empty.\n\n    Informally, wait for the currently playing sound to finish.\n\n    \"\"\"\n\n    # Can have at most one sound in the queue.  So must wait for the\n    # queue to become empty before adding a new sound to the queue.\n\n    clock = pygame.time.Clock()\n    while _channel.get_queue() is not None:\n        # while pygame.mixer.get_busy():\n        clock.tick(_CHECK_RATE)\n\n\ndef playSample(s):\n    \"\"\"Play sound sample s.\"\"\"\n    global _myBuffer\n    _myBuffer.append(s)\n    if len(_myBuffer) > _MY_BUFFER_MAX_LENGTH:\n        temp = []\n        for sample in _myBuffer:\n            temp.append(numpy.int16(sample * float(0x7FFF)))\n        samples = numpy.array(temp, numpy.int16)\n        sound = pygame.sndarray.make_sound(samples)\n        wait()\n        _channel.queue(sound)\n        _myBuffer = []\n\n\ndef playSamples(a):\n    \"\"\"Play all sound samples in array a.\"\"\"\n    for sample in a:\n        playSample(sample)\n\n\ndef playArray(a):\n    \"\"\"This function is deprecated.\n\n    It has the same behavior as stdaudio.playSamples(). Please call\n    stdaudio.playSamples() instead.\n\n    \"\"\"\n    playSamples(a)\n\n\ndef playFile(f):\n    \"\"\"Play all sound samples in the file whose name is f.wav.\"\"\"\n    a = read(f)\n    playSamples(a)\n    # sound = pygame.mixer.Sound(fileName)\n    # samples = pygame.sndarray.samples(sound)\n    # wait()\n    # sound.play()\n\n\ndef save(f, a):\n    \"\"\"Save all samples in array a to the WAVE file whose name is f.wav.\"\"\"\n\n    # Saving to a WAV file isn't handled by PyGame, so use the\n    # standard \"wave\" module instead.\n\n    import wave\n\n    fileName = f + \".wav\"\n    temp = []\n    for sample in a:\n        temp.append(int(sample * float(0x7FFF)))\n    samples = numpy.array(temp, numpy.int16)\n    file = wave.open(fileName, \"w\")\n    file.setnchannels(_CHANNEL_COUNT)\n    file.setsampwidth(2)  # 2 bytes\n    file.setframerate(_SAMPLES_PER_SECOND)\n    file.setnframes(len(samples))\n    file.setcomptype(\"NONE\", \"descrip\")  # No compression\n    file.writeframes(samples.tostring())\n    file.close()\n\n\ndef read(f):\n    \"\"\"Read all samples from the WAVE file whose names is f.wav.\n\n    Store the samples in an array, and return the array.\n\n    \"\"\"\n    fileName = f + \".wav\"\n    sound = pygame.mixer.Sound(fileName)\n    samples = pygame.sndarray.samples(sound)\n    temp = []\n    for i in range(len(samples)):\n        temp.append(float(samples[i]) / float(0x7FFF))\n    return temp\n\n\n# Initialize PyGame to handle audio.\ntry:\n    pygame.mixer.init(\n        _SAMPLES_PER_SECOND, _SAMPLE_SIZE, _CHANNEL_COUNT, _AUDIO_BUFFER_SIZE\n    )\n    _channel = pygame.mixer.Channel(0)\nexcept pygame.error:\n    stdio.writeln(\"Could not initialize PyGame\")\n    sys.exit(1)\n\n# -----------------------------------------------------------------------\n\n\ndef _createTextAudioFile():\n    \"\"\"For testing.\n\n    Create a text audio file.\n\n    \"\"\"\n    notes = [\n        7,\n        0.270,\n        5,\n        0.090,\n        3,\n        0.180,\n        5,\n        0.180,\n        7,\n        0.180,\n        6,\n        0.180,\n        7,\n        0.180,\n        3,\n        0.180,\n        5,\n        0.180,\n        5,\n        0.180,\n        5,\n        0.180,\n        5,\n        0.900,\n        5,\n        0.325,\n        3,\n        0.125,\n        2,\n        0.180,\n        3,\n        0.180,\n        5,\n        0.180,\n        4,\n        0.180,\n        5,\n        0.180,\n        2,\n        0.180,\n        3,\n        0.180,\n        3,\n        0.180,\n        3,\n        0.180,\n        3,\n        0.900,\n    ]\n\n    from itu.algs4.stdlib import outstream\n\n    outStream = outstream.OutStream(\"looney.txt\")\n    for note in notes:\n        outStream.writeln(note)\n\n\ndef _main():\n    \"\"\"For testing.\"\"\"\n    import math\n    import os\n\n    from itu.algs4.stdlib import instream, stdio\n\n    _createTextAudioFile()\n\n    stdio.writeln(\"Creating and playing in small chunks...\")\n    sps = _SAMPLES_PER_SECOND\n    inStream = instream.InStream(\"looney.txt\")\n    while not inStream.isEmpty():\n        pitch = inStream.readInt()\n        duration = inStream.readFloat()\n        hz = 440 * math.pow(2, pitch / 12.0)\n        N = int(sps * duration)\n        notes = []\n        for i in range(N + 1):\n            notes.append(math.sin(2 * math.pi * i * hz / sps))\n        playSamples(notes)\n    wait()\n\n    stdio.writeln(\"Creating and playing in one large chunk...\")\n    sps = _SAMPLES_PER_SECOND\n    notes = []\n    inStream = instream.InStream(\"looney.txt\")\n    while not inStream.isEmpty():\n        pitch = inStream.readInt()\n        duration = inStream.readFloat()\n        hz = 440 * math.pow(2, pitch / 12.0)\n        N = int(sps * duration)\n        for i in range(N + 1):\n            notes.append(math.sin(2 * math.pi * i * hz / sps))\n    playSamples(notes)\n    wait()\n\n    stdio.writeln(\"Saving...\")\n    save(\"looney\", notes)\n\n    stdio.writeln(\"Reading...\")\n    notes = read(\"looney\")\n\n    stdio.writeln(\"Playing an array...\")\n    playSamples(notes)\n    wait()\n\n    stdio.writeln(\"Playing a file...\")\n    playFile(\"looney\")\n    wait()\n\n    os.remove(\"looney.wav\")\n    os.remove(\"looney.txt\")\n\n\nif __name__ == \"__main__\":\n    _main()\n"
  },
  {
    "path": "itu/algs4/stdlib/stddraw.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stddraw.py.\n\nThe stddraw module defines functions that allow the user to create a\ndrawing.  A drawing appears on the canvas.  The canvas appears in the\nwindow.  As a convenience, the module also imports the commonly used\nColor objects defined in the color module.\n\n\"\"\"\n\nimport os\nimport sys\nimport time\n\nimport pygame\nimport pygame.font\nimport pygame.gfxdraw\n\nfrom itu.algs4.stdlib.color import (\n    BLACK,\n    BLUE,\n    CYAN,\n    DARK_BLUE,\n    DARK_GREEN,\n    DARK_RED,\n    GREEN,\n    MAGENTA,\n    ORANGE,\n    PINK,\n    RED,\n    WHITE,\n    YELLOW,\n)\n\nif sys.hexversion < 0x03000000:\n    import tkFileDialog\n    import Tkinter\n    import tkMessageBox\nelse:\n    import tkinter as Tkinter\n    from tkinter import filedialog as tkFileDialog\n    from tkinter import messagebox as tkMessageBox\n\n# -----------------------------------------------------------------------\n\n# Define colors so clients need not import the color module.\n\n\n# -----------------------------------------------------------------------\n\n# Default Sizes and Values\n\n_BORDER = 0.0\n# _BORDER = 0.05\n_DEFAULT_XMIN = 0.0\n_DEFAULT_XMAX = 1.0\n_DEFAULT_YMIN = 0.0\n_DEFAULT_YMAX = 1.0\n_DEFAULT_CANVAS_SIZE = 512\n_DEFAULT_PEN_RADIUS = 0.005  # Maybe change this to 0.0 in the future.\n_DEFAULT_PEN_COLOR = BLACK\n\n_DEFAULT_FONT_FAMILY = \"Helvetica\"\n_DEFAULT_FONT_SIZE = 12\n\n_xmin = None\n_ymin = None\n_xmax = None\n_ymax = None\n\n_fontFamily = _DEFAULT_FONT_FAMILY\n_fontSize = _DEFAULT_FONT_SIZE\n\n_canvasWidth = float(_DEFAULT_CANVAS_SIZE)\n_canvasHeight = float(_DEFAULT_CANVAS_SIZE)\n_penRadius = None\n_penColor = _DEFAULT_PEN_COLOR\n_keysTyped = []\n\n# Has the window been created?\n_windowCreated = False\n\n_surface = None\n_background = None\n\n# -----------------------------------------------------------------------\n# Begin added by Alan J. Broder\n# -----------------------------------------------------------------------\n\n# Keep track of mouse status\n\n# Has the mouse been left-clicked since the last time we checked?\n_mousePressed = False\n\n# The position of the mouse as of the most recent mouse click\n_mousePos = None\n\n# -----------------------------------------------------------------------\n# End added by Alan J. Broder\n# -----------------------------------------------------------------------\n\n# -----------------------------------------------------------------------\n\n\ndef _pygameColor(c):\n    \"\"\"Convert c, an object of type color.Color, to an equivalent object of\n    type pygame.Color.\n\n    Return the result.\n\n    \"\"\"\n    r = c.getRed()\n    g = c.getGreen()\n    b = c.getBlue()\n    return pygame.Color(r, g, b)\n\n\n# -----------------------------------------------------------------------\n\n# Private functions to scale and factor X and Y values.\n\n\ndef _scaleX(x):\n    return _canvasWidth * (x - _xmin) / (_xmax - _xmin)\n\n\ndef _scaleY(y):\n    return _canvasHeight * (_ymax - y) / (_ymax - _ymin)\n\n\ndef _factorX(w):\n    return w * _canvasWidth / abs(_xmax - _xmin)\n\n\ndef _factorY(h):\n    return h * _canvasHeight / abs(_ymax - _ymin)\n\n\n# -----------------------------------------------------------------------\n# Begin added by Alan J. Broder\n# -----------------------------------------------------------------------\n\n\ndef _userX(x):\n    return _xmin + x * (_xmax - _xmin) / _canvasWidth\n\n\ndef _userY(y):\n    return _ymax - y * (_ymax - _ymin) / _canvasHeight\n\n\n# -----------------------------------------------------------------------\n# End added by Alan J. Broder\n# -----------------------------------------------------------------------\n\n# -----------------------------------------------------------------------\n\n\ndef setCanvasSize(w=_DEFAULT_CANVAS_SIZE, h=_DEFAULT_CANVAS_SIZE):\n    \"\"\"Set the size of the canvas to w pixels wide and h pixels high.\n\n    Calling this function is optional. If you call it, you must do so\n    before calling any drawing function.\n\n    \"\"\"\n    global _background\n    global _surface\n    global _canvasWidth\n    global _canvasHeight\n    global _windowCreated\n\n    if _windowCreated:\n        raise Exception(\"The stddraw window already was created\")\n\n    if (w < 1) or (h < 1):\n        raise Exception(\"width and height must be positive\")\n\n    _canvasWidth = w\n    _canvasHeight = h\n    _background = pygame.display.set_mode([w, h])\n    pygame.display.set_caption(\"stddraw window (r-click to save)\")\n    _surface = pygame.Surface((w, h))\n    _surface.fill(_pygameColor(WHITE))\n    _windowCreated = True\n\n\ndef setXscale(min=_DEFAULT_XMIN, max=_DEFAULT_XMAX):\n    \"\"\"Set the x-scale of the canvas such that the minimum x value is min and\n    the maximum x value is max.\"\"\"\n    global _xmin\n    global _xmax\n    min = float(min)\n    max = float(max)\n    if min >= max:\n        raise Exception(\"min must be less than max\")\n    size = max - min\n    _xmin = min - _BORDER * size\n    _xmax = max + _BORDER * size\n\n\ndef setYscale(min=_DEFAULT_YMIN, max=_DEFAULT_YMAX):\n    \"\"\"Set the y-scale of the canvas such that the minimum y value is min and\n    the maximum y value is max.\"\"\"\n    global _ymin\n    global _ymax\n    min = float(min)\n    max = float(max)\n    if min >= max:\n        raise Exception(\"min must be less than max\")\n    size = max - min\n    _ymin = min - _BORDER * size\n    _ymax = max + _BORDER * size\n\n\ndef setPenRadius(r=_DEFAULT_PEN_RADIUS):\n    \"\"\"Set the pen radius to r, thus affecting the subsequent drawing of points\n    and lines.\n\n    If r is 0.0, then points will be drawn with the minimum possible\n    radius and lines with the minimum possible width.\n\n    \"\"\"\n    global _penRadius\n    r = float(r)\n    if r < 0.0:\n        raise Exception(\"Argument to setPenRadius() must be non-neg\")\n    _penRadius = r * float(_DEFAULT_CANVAS_SIZE)\n\n\ndef setPenColor(c=_DEFAULT_PEN_COLOR):\n    \"\"\"Set the pen color to c, where c is an object of class color.Color.\n\n    c defaults to stddraw.BLACK.\n\n    \"\"\"\n    global _penColor\n    _penColor = c\n\n\ndef setFontFamily(f=_DEFAULT_FONT_FAMILY):\n    \"\"\"Set the font family to f (e.g. 'Helvetica' or 'Courier').\"\"\"\n    global _fontFamily\n    _fontFamily = f\n\n\ndef setFontSize(s=_DEFAULT_FONT_SIZE):\n    \"\"\"Set the font size to s (e.g. 12 or 16).\"\"\"\n    global _fontSize\n    _fontSize = s\n\n\n# -----------------------------------------------------------------------\n\n\ndef _makeSureWindowCreated():\n    global _windowCreated\n    if not _windowCreated:\n        setCanvasSize()\n        _windowCreated = True\n\n\n# -----------------------------------------------------------------------\n\n# Functions to draw shapes, text, and images on the background canvas.\n\n\ndef _pixel(x, y):\n    \"\"\"Draw on the background canvas a pixel at (x, y).\"\"\"\n    _makeSureWindowCreated()\n    xs = _scaleX(x)\n    xy = _scaleY(y)\n    pygame.gfxdraw.pixel(\n        _surface, int(round(xs)), int(round(xy)), _pygameColor(_penColor)\n    )\n\n\ndef point(x, y):\n    \"\"\"Draw on the background canvas a point at (x, y).\"\"\"\n    _makeSureWindowCreated()\n    x = float(x)\n    y = float(y)\n    # If the radius is too small, then simply draw a pixel.\n    if _penRadius <= 1.0:\n        _pixel(x, y)\n    else:\n        xs = _scaleX(x)\n        ys = _scaleY(y)\n        pygame.draw.ellipse(\n            _surface,\n            _pygameColor(_penColor),\n            pygame.Rect(\n                xs - _penRadius, ys - _penRadius, _penRadius * 2.0, _penRadius * 2.0\n            ),\n            0,\n        )\n\n\ndef _thickLine(x0, y0, x1, y1, r):\n    \"\"\"Draw on the background canvas a line from (x0, y0) to (x1, y1).\n\n    Draw the line with a pen whose radius is r.\n\n    \"\"\"\n    xs0 = _scaleX(x0)\n    ys0 = _scaleY(y0)\n    xs1 = _scaleX(x1)\n    ys1 = _scaleY(y1)\n    if (abs(xs0 - xs1) < 1.0) and (abs(ys0 - ys1) < 1.0):\n        filledCircle(x0, y0, r)\n        return\n    xMid = (x0 + x1) / 2\n    yMid = (y0 + y1) / 2\n    _thickLine(x0, y0, xMid, yMid, r)\n    _thickLine(xMid, yMid, x1, y1, r)\n\n\ndef line(x0, y0, x1, y1):\n    \"\"\"Draw on the background canvas a line from (x0, y0) to (x1, y1).\"\"\"\n\n    THICK_LINE_CUTOFF = 3  # pixels\n\n    _makeSureWindowCreated()\n\n    x0 = float(x0)\n    y0 = float(y0)\n    x1 = float(x1)\n    y1 = float(y1)\n\n    lineWidth = _penRadius * 2.0\n    if lineWidth == 0.0:\n        lineWidth = 1.0\n    if lineWidth < THICK_LINE_CUTOFF:\n        x0s = _scaleX(x0)\n        y0s = _scaleY(y0)\n        x1s = _scaleX(x1)\n        y1s = _scaleY(y1)\n        pygame.draw.line(\n            _surface,\n            _pygameColor(_penColor),\n            (x0s, y0s),\n            (x1s, y1s),\n            int(round(lineWidth)),\n        )\n    else:\n        _thickLine(x0, y0, x1, y1, _penRadius / _DEFAULT_CANVAS_SIZE)\n\n\ndef circle(x, y, r):\n    \"\"\"Draw on the background canvas a circle of radius r centered on (x,\n    y).\"\"\"\n    _makeSureWindowCreated()\n    x = float(x)\n    y = float(y)\n    r = float(r)\n    ws = _factorX(2.0 * r)\n    hs = _factorY(2.0 * r)\n    # If the radius is too small, then simply draw a pixel.\n    if (ws <= 1.0) and (hs <= 1.0):\n        _pixel(x, y)\n    else:\n        xs = _scaleX(x)\n        ys = _scaleY(y)\n        pygame.draw.ellipse(\n            _surface,\n            _pygameColor(_penColor),\n            pygame.Rect(xs - ws / 2.0, ys - hs / 2.0, ws, hs),\n            int(round(_penRadius)),\n        )\n\n\ndef filledCircle(x, y, r):\n    \"\"\"Draw on the background canvas a filled circle of radius r centered on\n    (x, y).\"\"\"\n    _makeSureWindowCreated()\n    x = float(x)\n    y = float(y)\n    r = float(r)\n    ws = _factorX(2.0 * r)\n    hs = _factorY(2.0 * r)\n    # If the radius is too small, then simply draw a pixel.\n    if (ws <= 1.0) and (hs <= 1.0):\n        _pixel(x, y)\n    else:\n        xs = _scaleX(x)\n        ys = _scaleY(y)\n        pygame.draw.ellipse(\n            _surface,\n            _pygameColor(_penColor),\n            pygame.Rect(xs - ws / 2.0, ys - hs / 2.0, ws, hs),\n            0,\n        )\n\n\ndef rectangle(x, y, w, h):\n    \"\"\"Draw on the background canvas a rectangle of width w and height h whose\n    lower left point is (x, y).\"\"\"\n    _makeSureWindowCreated()\n    x = float(x)\n    y = float(y)\n    w = float(w)\n    h = float(h)\n    ws = _factorX(w)\n    hs = _factorY(h)\n    # If the rectangle is too small, then simply draw a pixel.\n    if (ws <= 1.0) and (hs <= 1.0):\n        _pixel(x, y)\n    else:\n        xs = _scaleX(x)\n        ys = _scaleY(y)\n        pygame.draw.rect(\n            _surface,\n            _pygameColor(_penColor),\n            pygame.Rect(xs, ys - hs, ws, hs),\n            int(round(_penRadius)),\n        )\n\n\ndef filledRectangle(x, y, w, h):\n    \"\"\"Draw on the background canvas a filled rectangle of width w and height h\n    whose lower left point is (x, y).\"\"\"\n    _makeSureWindowCreated()\n    x = float(x)\n    y = float(y)\n    w = float(w)\n    h = float(h)\n    ws = _factorX(w)\n    hs = _factorY(h)\n    # If the rectangle is too small, then simply draw a pixel.\n    if (ws <= 1.0) and (hs <= 1.0):\n        _pixel(x, y)\n    else:\n        xs = _scaleX(x)\n        ys = _scaleY(y)\n        pygame.draw.rect(\n            _surface, _pygameColor(_penColor), pygame.Rect(xs, ys - hs, ws, hs), 0\n        )\n\n\ndef square(x, y, r):\n    \"\"\"Draw on the background canvas a square whose sides are of length 2r,\n    centered on (x, y).\"\"\"\n    _makeSureWindowCreated()\n    rectangle(x - r, y - r, 2.0 * r, 2.0 * r)\n\n\ndef filledSquare(x, y, r):\n    \"\"\"Draw on the background canvas a filled square whose sides are of length\n    2r, centered on (x, y).\"\"\"\n    _makeSureWindowCreated()\n    filledRectangle(x - r, y - r, 2.0 * r, 2.0 * r)\n\n\ndef polygon(x, y):\n    \"\"\"Draw on the background canvas a polygon with coordinates (x[i],\n    y[i]).\"\"\"\n    _makeSureWindowCreated()\n    # Scale X and Y values.\n    xScaled = []\n    for xi in x:\n        xScaled.append(_scaleX(float(xi)))\n    yScaled = []\n    for yi in y:\n        yScaled.append(_scaleY(float(yi)))\n    points = []\n    for i in range(len(x)):\n        points.append((xScaled[i], yScaled[i]))\n    points.append((xScaled[0], yScaled[0]))\n    pygame.draw.polygon(\n        _surface, _pygameColor(_penColor), points, int(round(_penRadius))\n    )\n\n\ndef filledPolygon(x, y):\n    \"\"\"Draw on the background canvas a filled polygon with coordinates (x[i],\n    y[i]).\"\"\"\n    _makeSureWindowCreated()\n    # Scale X and Y values.\n    xScaled = []\n    for xi in x:\n        xScaled.append(_scaleX(float(xi)))\n    yScaled = []\n    for yi in y:\n        yScaled.append(_scaleY(float(yi)))\n    points = []\n    for i in range(len(x)):\n        points.append((xScaled[i], yScaled[i]))\n    points.append((xScaled[0], yScaled[0]))\n    pygame.draw.polygon(_surface, _pygameColor(_penColor), points, 0)\n\n\ndef text(x, y, s):\n    \"\"\"Draw string s on the background canvas centered at (x, y).\"\"\"\n    _makeSureWindowCreated()\n    x = float(x)\n    y = float(y)\n    xs = _scaleX(x)\n    ys = _scaleY(y)\n    font = pygame.font.SysFont(_fontFamily, _fontSize)\n    text = font.render(s, 1, _pygameColor(_penColor))\n    textpos = text.get_rect(center=(xs, ys))\n    _surface.blit(text, textpos)\n\n\ndef picture(pic, x=None, y=None):\n    \"\"\"Draw pic on the background canvas centered at (x, y).\n\n    pic is an object of class picture.Picture. x and y default to the\n    midpoint of the background canvas.\n\n    \"\"\"\n    _makeSureWindowCreated()\n    # By default, draw pic at the middle of the surface.\n    if x is None:\n        x = (_xmax + _xmin) / 2.0\n    if y is None:\n        y = (_ymax + _ymin) / 2.0\n    x = float(x)\n    y = float(y)\n    xs = _scaleX(x)\n    ys = _scaleY(y)\n    ws = pic.width()\n    hs = pic.height()\n    picSurface = pic._surface  # violates encapsulation\n    _surface.blit(picSurface, [xs - ws / 2.0, ys - hs / 2.0, ws, hs])\n\n\ndef clear(c=WHITE):\n    \"\"\"Clear the background canvas to color c, where c is an object of class\n    color.Color.\n\n    c defaults to stddraw.WHITE.\n\n    \"\"\"\n    _makeSureWindowCreated()\n    _surface.fill(_pygameColor(c))\n\n\ndef save(f):\n    \"\"\"Save the window canvas to file f.\"\"\"\n    _makeSureWindowCreated()\n\n    # if sys.hexversion >= 0x03000000:\n    #    # Hack because Pygame without full image support\n    #    # can handle only .bmp files.\n    #    bmpFileName = f + '.bmp'\n    #    pygame.image.save(_surface, bmpFileName)\n    #    os.system('convert ' + bmpFileName + ' ' + f)\n    #    os.system('rm ' + bmpFileName)\n    # else:\n    #    pygame.image.save(_surface, f)\n\n    pygame.image.save(_surface, f)\n\n\n# -----------------------------------------------------------------------\n\n\ndef _show():\n    \"\"\"Copy the background canvas to the window canvas.\"\"\"\n    _background.blit(_surface, (0, 0))\n    pygame.display.flip()\n    _checkForEvents()\n\n\ndef _showAndWaitForever():\n    \"\"\"Copy the background canvas to the window canvas.\n\n    Then wait forever, that is, until the user closes the stddraw\n    window.\n\n    \"\"\"\n    _makeSureWindowCreated()\n    _show()\n    QUANTUM = 0.1\n    while True:\n        time.sleep(QUANTUM)\n        _checkForEvents()\n\n\ndef show(msec=float(\"inf\")):\n    \"\"\"Copy the background canvas to the window canvas, and then wait for msec\n    milliseconds.\n\n    msec defaults to infinity.\n\n    \"\"\"\n    if msec == float(\"inf\"):\n        _showAndWaitForever()\n\n    _makeSureWindowCreated()\n    _show()\n    _checkForEvents()\n\n    # Sleep for the required time, but check for events every\n    # QUANTUM seconds.\n    QUANTUM = 0.1\n    sec = msec / 1000.0\n    if sec < QUANTUM:\n        time.sleep(sec)\n        return\n    secondsWaited = 0.0\n    while secondsWaited < sec:\n        time.sleep(QUANTUM)\n        secondsWaited += QUANTUM\n        _checkForEvents()\n\n\n# -----------------------------------------------------------------------\n\n\ndef _saveToFile():\n    \"\"\"Display a dialog box that asks the user for a file name.\n\n    Save the drawing to the specified file.  Display a confirmation\n    dialog box if successful, and an error dialog box otherwise.  The\n    dialog boxes are displayed using Tkinter, which (on some computers)\n    is incompatible with Pygame. So the dialog boxes must be displayed\n    from child processes.\n\n    \"\"\"\n    import subprocess\n\n    _makeSureWindowCreated()\n\n    stddrawPath = os.path.realpath(__file__)\n\n    childProcess = subprocess.Popen(\n        [sys.executable, stddrawPath, \"getFileName\"], stdout=subprocess.PIPE\n    )\n    so, _ = childProcess.communicate()\n    fileName = so.strip()\n\n    if sys.hexversion >= 0x03000000:\n        fileName = fileName.decode(\"utf-8\")\n\n    if fileName == \"\":\n        return\n\n    if not fileName.endswith((\".jpg\", \".png\")):\n        childProcess = subprocess.Popen(\n            [\n                sys.executable,\n                stddrawPath,\n                \"reportFileSaveError\",\n                'File name must end with \".jpg\" or \".png\".',\n            ]\n        )\n        return\n\n    try:\n        save(fileName)\n        childProcess = subprocess.Popen(\n            [sys.executable, stddrawPath, \"confirmFileSave\"]\n        )\n    except (pygame.error) as e:\n        childProcess = subprocess.Popen(\n            [sys.executable, stddrawPath, \"reportFileSaveError\", str(e)]\n        )\n\n\ndef _checkForEvents():\n    \"\"\"Check if any new event has occured (such as a key typed or button\n    pressed).\n\n    If a key has been typed, then put that key in a queue.\n\n    \"\"\"\n    global _keysTyped\n\n    # -------------------------------------------------------------------\n    # Begin added by Alan J. Broder\n    # -------------------------------------------------------------------\n    global _mousePos\n    global _mousePressed\n    # -------------------------------------------------------------------\n    # End added by Alan J. Broder\n    # -------------------------------------------------------------------\n\n    _makeSureWindowCreated()\n\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            sys.exit()\n        elif event.type == pygame.KEYDOWN:\n            _keysTyped = [event.unicode] + _keysTyped\n        elif (event.type == pygame.MOUSEBUTTONUP) and (event.button == 3):\n            _saveToFile()\n\n        # ---------------------------------------------------------------\n        # Begin added by Alan J. Broder\n        # ---------------------------------------------------------------\n        # Every time the mouse button is pressed, remember\n        # the mouse position as of that press.\n        elif (event.type == pygame.MOUSEBUTTONDOWN) and (event.button == 1):\n            _mousePressed = True\n            _mousePos = event.pos\n        # ---------------------------------------------------------------\n        # End added by Alan J. Broder\n        # ---------------------------------------------------------------\n\n\n# -----------------------------------------------------------------------\n\n# Functions for retrieving keys\n\n\ndef hasNextKeyTyped():\n    \"\"\"Return True if the queue of keys the user typed is not empty.\n\n    Otherwise return False.\n\n    \"\"\"\n    return _keysTyped != []\n\n\ndef nextKeyTyped():\n    \"\"\"Remove the first key from the queue of keys that the the user typed, and\n    return that key.\"\"\"\n    return _keysTyped.pop()\n\n\n# -----------------------------------------------------------------------\n# Begin added by Alan J. Broder\n# -----------------------------------------------------------------------\n\n# Functions for dealing with mouse clicks\n\n\ndef mousePressed():\n    \"\"\"Return True if the mouse has been left-clicked since the last time\n    mousePressed was called, and False otherwise.\"\"\"\n    global _mousePressed\n    if _mousePressed:\n        _mousePressed = False\n        return True\n    return False\n\n\ndef mouseX():\n    \"\"\"Return the x coordinate in user space of the location at which the mouse\n    was most recently left-clicked.\n\n    If a left-click hasn't happened yet, raise an exception, since\n    mouseX() shouldn't be called until mousePressed() returns True.\n\n    \"\"\"\n    if _mousePos:\n        return _userX(_mousePos[0])\n    raise Exception(\"Can't determine mouse position if a click hasn't happened\")\n\n\ndef mouseY():\n    \"\"\"Return the y coordinate in user space of the location at which the mouse\n    was most recently left-clicked.\n\n    If a left-click hasn't happened yet, raise an exception, since\n    mouseY() shouldn't be called until mousePressed() returns True.\n\n    \"\"\"\n    if _mousePos:\n        return _userY(_mousePos[1])\n    raise Exception(\"Can't determine mouse position if a click hasn't happened\")\n\n\n# -----------------------------------------------------------------------\n# End added by Alan J. Broder\n# -----------------------------------------------------------------------\n\n# -----------------------------------------------------------------------\n\n# Initialize the x scale, the y scale, and the pen radius.\n\nsetXscale()\nsetYscale()\nsetPenRadius()\npygame.font.init()\n\n# -----------------------------------------------------------------------\n\n# Functions for displaying Tkinter dialog boxes in child processes.\n\n\ndef _getFileName():\n    \"\"\"Display a dialog box that asks the user for a file name.\"\"\"\n    root = Tkinter.Tk()\n    root.withdraw()\n    reply = tkFileDialog.asksaveasfilename(initialdir=\".\")\n    sys.stdout.write(reply)\n    sys.stdout.flush()\n    sys.exit()\n\n\ndef _confirmFileSave():\n    \"\"\"Display a dialog box that confirms a file save operation.\"\"\"\n    root = Tkinter.Tk()\n    root.withdraw()\n    tkMessageBox.showinfo(\n        title=\"File Save Confirmation\", message=\"The drawing was saved to the file.\"\n    )\n    sys.exit()\n\n\ndef _reportFileSaveError(msg):\n    \"\"\"Display a dialog box that reports a msg.\n\n    msg is a string which describes an error in a file save operation.\n\n    \"\"\"\n    root = Tkinter.Tk()\n    root.withdraw()\n    tkMessageBox.showerror(title=\"File Save Error\", message=msg)\n    sys.exit()\n\n\n# -----------------------------------------------------------------------\n\n\ndef _regressionTest():\n    \"\"\"Perform regression testing.\"\"\"\n\n    clear()\n\n    setPenRadius(0.5)\n    setPenColor(ORANGE)\n    point(0.5, 0.5)\n    show(0.0)\n\n    setPenRadius(0.25)\n    setPenColor(BLUE)\n    point(0.5, 0.5)\n    show(0.0)\n\n    setPenRadius(0.02)\n    setPenColor(RED)\n    point(0.25, 0.25)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(GREEN)\n    point(0.25, 0.25)\n    show(0.0)\n\n    setPenRadius(0)\n    setPenColor(BLACK)\n    point(0.25, 0.25)\n    show(0.0)\n\n    setPenRadius(0.1)\n    setPenColor(RED)\n    point(0.75, 0.75)\n    show(0.0)\n\n    setPenRadius(0)\n    setPenColor(CYAN)\n    for i in range(0, 100):\n        point(i / 512.0, 0.5)\n        point(0.5, i / 512.0)\n    show(0.0)\n\n    setPenRadius(0)\n    setPenColor(MAGENTA)\n    line(0.1, 0.1, 0.3, 0.3)\n    line(0.1, 0.2, 0.3, 0.2)\n    line(0.2, 0.1, 0.2, 0.3)\n    show(0.0)\n\n    setPenRadius(0.05)\n    setPenColor(MAGENTA)\n    line(0.7, 0.5, 0.8, 0.9)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(YELLOW)\n    circle(0.75, 0.25, 0.2)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(YELLOW)\n    filledCircle(0.75, 0.25, 0.1)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(PINK)\n    rectangle(0.25, 0.75, 0.1, 0.2)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(PINK)\n    filledRectangle(0.25, 0.75, 0.05, 0.1)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(DARK_RED)\n    square(0.5, 0.5, 0.1)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(DARK_RED)\n    filledSquare(0.5, 0.5, 0.05)\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(DARK_BLUE)\n    polygon([0.4, 0.5, 0.6], [0.7, 0.8, 0.7])\n    show(0.0)\n\n    setPenRadius(0.01)\n    setPenColor(DARK_GREEN)\n    setFontSize(24)\n    text(0.2, 0.4, \"hello, world\")\n    show(0.0)\n\n    # import picture as p\n    # pic = p.Picture('saveIcon.png')\n    # picture(pic, .5, .85)\n    # show(0.0)\n\n    # Test handling of mouse and keyboard events.\n    setPenColor(BLACK)\n    from itu.algs4.stdlib import stdio\n\n    stdio.writeln(\"Left click with the mouse or type a key\")\n    while True:\n        if mousePressed():\n            filledCircle(mouseX(), mouseY(), 0.02)\n        if hasNextKeyTyped():\n            stdio.write(nextKeyTyped())\n        show(0.0)\n\n    # Never get here.\n    show()\n\n\n# -----------------------------------------------------------------------\n\n\ndef _main():\n    \"\"\"Dispatch to a function that does regression testing, or to a dialog-box-\n    handling function.\"\"\"\n    import sys\n\n    if len(sys.argv) == 1:\n        _regressionTest()\n    elif sys.argv[1] == \"getFileName\":\n        _getFileName()\n    elif sys.argv[1] == \"confirmFileSave\":\n        _confirmFileSave()\n    elif sys.argv[1] == \"reportFileSaveError\":\n        _reportFileSaveError(sys.argv[2])\n\n\nif __name__ == \"__main__\":\n    _main()\n"
  },
  {
    "path": "itu/algs4/stdlib/stdio.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdio.py.\n\nThe stdio module supports reading from standard input and writing to\nsys.stdout.\n\nNote:  Usually it's a bad idea to mix these three sets of reading\nfunctions:\n\n-- isEmpty(), readInt(), readFloat(), readBool(), readString()\n\n-- hasNextLine(), readLine()\n\n-- readAll(), readAllInts(), readAllFloats(), readAllBools(),\n   readAllStrings(), readAllLines()\n\nUsually it's better to use one set exclusively.\n\n\"\"\"\n\nimport re\nimport sys\n\n# -----------------------------------------------------------------------\n\n# Change sys.stdin so it provides universal newline support.\n\nif sys.hexversion < 0x03000000:\n    import os\n\n    sys.stdin = os.fdopen(sys.stdin.fileno(), \"rU\", 0)\nelse:\n    sys.stdin = open(sys.stdin.fileno(), \"r\", newline=None)\n\n# =======================================================================\n# print to stderr\n# from https://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python#14981125\n# =======================================================================\n\n\ndef eprint(*args, **kwargs):\n    print(*args, file=sys.stderr, **kwargs)\n\n\n# =======================================================================\n# Writing functions\n# =======================================================================\n\n\ndef writeln(x=\"\"):\n    \"\"\"Write x and an end-of-line mark to standard output.\"\"\"\n    if sys.hexversion < 0x03000000:\n        print(\"Error: Python 3 is required.\", file=sys.stderr)\n        sys.exit(1)\n        # x = unicode(x)\n        # x = x.encode(\"utf-8\")\n    else:\n        x = str(x)\n    sys.stdout.write(x)\n    sys.stdout.write(\"\\n\")\n    sys.stdout.flush()\n\n\n# -----------------------------------------------------------------------\n\n\ndef write(x=\"\"):\n    \"\"\"Write x to standard output.\"\"\"\n    if sys.hexversion < 0x03000000:\n        print(\"Error: Python 3 is required.\", file=sys.stderr)\n        sys.exit(1)\n        # x = unicode(x)\n        # x = x.encode(\"utf-8\")\n    else:\n        x = str(x)\n    sys.stdout.write(x)\n    sys.stdout.flush()\n\n\n# -----------------------------------------------------------------------\n\n\ndef writef(fmt, *args):\n    \"\"\"Write each element of args to standard output.\n\n    Use the format specified by string fmt.\n\n    \"\"\"\n    x = fmt % args\n    if sys.hexversion < 0x03000000:\n        print(\"Error: Python 3 is required.\", file=sys.stderr)\n        sys.exit(1)\n        # x = unicode(x)\n        # x = x.encode(\"utf-8\")\n    sys.stdout.write(x)\n    sys.stdout.flush()\n\n\n# =======================================================================\n# Reading functions\n# =======================================================================\n\n_buffer = \"\"\n\n# -----------------------------------------------------------------------\n\n\ndef _readRegExp(regExp):\n    \"\"\"Discard leading white space characters from standard input.\n\n    Then read from standard input and return a string matching regular\n    expression regExp.  Raise an EOFError if no non-whitespace\n    characters remain in standard input.  Raise a ValueError if the next\n    characters to be read from standard input do not match 'regExp'.\n\n    \"\"\"\n    global _buffer\n    if isEmpty():\n        raise EOFError()\n    compiledRegExp = re.compile(r\"^\\s*\" + regExp)\n    match = compiledRegExp.search(_buffer)\n    if match is None:\n        raise ValueError()\n    s = match.group()\n    _buffer = _buffer[match.end() :]\n    return s.lstrip()\n\n\n# -----------------------------------------------------------------------\n\n\ndef isEmpty():\n    \"\"\"Return True if no non-whitespace characters remain in standard input.\n\n    Otherwise return False.\n\n    \"\"\"\n    global _buffer\n    while _buffer.strip() == \"\":\n        line = sys.stdin.readline()\n        if sys.hexversion < 0x03000000:\n            line = line.decode(\"utf-8\")\n        if line == \"\":\n            return True\n        _buffer += line\n    return False\n\n\n# -----------------------------------------------------------------------\n\n\ndef readInt():\n    \"\"\"Discard leading white space characters from standard input.\n\n    Then read from standard input a sequence of characters comprising an\n    integer. Convert the sequence of characters to an integer, and\n    return the integer.  Raise an EOFError if no non-whitespace\n    characters remain in standard input. Raise a ValueError if the next\n    characters to be read from standard input cannot comprise an\n    integer.\n\n    \"\"\"\n    s = _readRegExp(r\"[-+]?(0[xX][\\dA-Fa-f]+|0[0-7]*|\\d+)\")\n    radix = 10\n    strLength = len(s)\n    if (strLength >= 1) and (s[0:1] == \"0\"):\n        radix = 8\n    if (strLength >= 2) and (s[0:2] == \"-0\"):\n        radix = 8\n    if (strLength >= 2) and (s[0:2] == \"0x\"):\n        radix = 16\n    if (strLength >= 2) and (s[0:2] == \"0X\"):\n        radix = 16\n    if (strLength >= 3) and (s[0:3] == \"-0x\"):\n        radix = 16\n    if (strLength >= 3) and (s[0:3] == \"-0X\"):\n        radix = 16\n    return int(s, radix)\n\n\n# -----------------------------------------------------------------------\n\n\ndef readAllInts():\n    \"\"\"Read all remaining strings from standard input, convert each to an int,\n    and return those ints in an array.\n\n    Raise a ValueError if any of the strings cannot be converted to an\n    int.\n\n    \"\"\"\n    strings = readAllStrings()\n    ints = []\n    for s in strings:\n        i = int(s)\n        ints.append(i)\n    return ints\n\n\n# -----------------------------------------------------------------------\n\n\ndef readFloat():\n    \"\"\"Discard leading white space characters from standard input.\n\n    Then read from standard input a sequence of characters comprising a\n    float. Convert the sequence of characters to a float, and return the\n    float.  Raise an EOFError if no non-whitespace characters remain in\n    standard input. Raise a ValueError if the next characters to be read\n    from standard input cannot comprise a float.\n\n    \"\"\"\n    s = _readRegExp(r\"[-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?\")\n    return float(s)\n\n\n# -----------------------------------------------------------------------\n\n\ndef readAllFloats():\n    \"\"\"Read all remaining strings from standard input, convert each to a float,\n    and return those floats in an array.\n\n    Raise a ValueError if any of the strings cannot be converted to a\n    float.\n\n    \"\"\"\n    strings = readAllStrings()\n    floats = []\n    for s in strings:\n        f = float(s)\n        floats.append(f)\n    return floats\n\n\n# -----------------------------------------------------------------------\n\n\ndef readBool():\n    \"\"\"Discard leading white space characters from standard input. Then read\n    from standard input a sequence of characters comprising a bool. Convert the\n    sequence of characters to a bool, and return the bool.  Raise an EOFError\n    if no non-whitespace characters remain in standard input. Raise a\n    ValueError if the next characters to be read from standard input cannot\n    comprise a bool.\n\n    These character sequences can comprise a bool:\n    -- True\n    -- False\n    -- 1 (means true)\n    -- 0 (means false)\n\n    \"\"\"\n    s = _readRegExp(r\"(True)|(False)|1|0\")\n    if (s == \"True\") or (s == \"1\"):\n        return True\n    return False\n\n\n# -----------------------------------------------------------------------\n\n\ndef readAllBools():\n    \"\"\"Read all remaining strings from standard input, convert each to a bool,\n    and return those bools in an array.\n\n    Raise a ValueError if any of the strings cannot be converted to a\n    bool.\n\n    \"\"\"\n    strings = readAllStrings()\n    bools = []\n    for s in strings:\n        b = bool(s)\n        bools.append(b)\n    return bools\n\n\n# -----------------------------------------------------------------------\n\n\ndef readString():\n    \"\"\"Discard leading white space characters from standard input.\n\n    Then read from standard input a sequence of characters comprising a\n    string, and return the string. Raise an EOFError if no non-\n    whitespace characters remain in standard input.\n\n    \"\"\"\n    s = _readRegExp(r\"\\S+\")\n    return s\n\n\n# -----------------------------------------------------------------------\n\n\ndef readAllStrings():\n    \"\"\"Read all remaining strings from standard input, and return them in an\n    array.\"\"\"\n    strings = []\n    while not isEmpty():\n        s = readString()\n        strings.append(s)\n    return strings\n\n\n# -----------------------------------------------------------------------\n\n\ndef hasNextLine():\n    \"\"\"Return True if standard input has a next line.\n\n    Otherwise return False.\n\n    \"\"\"\n    global _buffer\n    if _buffer != \"\":\n        return True\n    else:\n        _buffer = sys.stdin.readline()\n        if sys.hexversion < 0x03000000:\n            _buffer = _buffer.decode(\"utf-8\")\n        if _buffer == \"\":\n            return False\n        return True\n\n\n# -----------------------------------------------------------------------\n\n\ndef readLine():\n    \"\"\"Read and return as a string the next line of standard input.\n\n    Raise an EOFError is there is no next line.\n\n    \"\"\"\n    global _buffer\n    if not hasNextLine():\n        raise EOFError()\n    s = _buffer\n    _buffer = \"\"\n    return s.rstrip(\"\\n\")\n\n\n# -----------------------------------------------------------------------\n\n\ndef readAllLines():\n    \"\"\"Read all remaining lines from standard input, and return them as strings\n    in an array.\"\"\"\n    lines = []\n    while hasNextLine():\n        line = readLine()\n        lines.append(line)\n    return lines\n\n\n# -----------------------------------------------------------------------\n\n\ndef readAll():\n    \"\"\"Read and return as a string all remaining lines of standard input.\"\"\"\n    global _buffer\n    s = _buffer\n    _buffer = \"\"\n    for line in sys.stdin:\n        if sys.hexversion < 0x03000000:\n            line = line.decode(\"utf-8\")\n        s += line\n    return s\n\n\n# =======================================================================\n# For Testing\n# =======================================================================\n\n\ndef _testWrite():\n    writeln()\n    writeln(\"string\")\n    writeln(123456)\n    writeln(123.456)\n    writeln(True)\n    write()\n    write(\"string\")\n    write(123456)\n    write(123.456)\n    write(True)\n    writeln()\n    writef(\"<%s> <%8d> <%14.8f>\\n\", \"string\", 123456, 123.456)\n    writef(\"formatstring\\n\")\n\n\n# -----------------------------------------------------------------------\n\n\ndef _main():\n    \"\"\"For testing.\n\n    The command-line argument should be the name of the function that\n    should be called.\n\n    \"\"\"\n\n    map = {\n        \"readInt\": readInt,\n        \"readAllInts\": readAllInts,\n        \"readFloat\": readFloat,\n        \"readAllFloats\": readAllFloats,\n        \"readBool\": readBool,\n        \"readAllBools\": readAllBools,\n        \"readString\": readString,\n        \"readAllStrings\": readAllStrings,\n        \"readLine\": readLine,\n        \"readAllLines\": readAllLines,\n        \"readAll\": readAll,\n    }\n\n    testId = sys.argv[1]\n\n    if testId == \"write\":\n        _testWrite()\n    else:\n        writeln(map[testId]())\n\n\nif __name__ == \"__main__\":\n    _main()\n"
  },
  {
    "path": "itu/algs4/stdlib/stdrandom.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdrandom.py.\n\nThe stdrandom module defines functions related to pseudo-random numbers.\n\n\"\"\"\n\n# -----------------------------------------------------------------------\n\nimport math\nimport random\n\n# -----------------------------------------------------------------------\n\n\ndef seed(i=None):\n    \"\"\"Seed the random number generator as hash(i), where i is an int.\n\n    If i is None, then seed using the current time or, quoting the help\n    page for random.seed(), \"an operating system specific randomness\n    source if available.\"\n\n    \"\"\"\n    random.seed(i)\n\n\n# -----------------------------------------------------------------------\n\n\ndef uniform(hi):\n    \"\"\"Return an integer chosen uniformly from the range [0, hi).\"\"\"\n    return random.randrange(0, hi)\n\n\n# -----------------------------------------------------------------------\ndef uniformInt(lo, hi):\n    \"\"\"Return an integer chosen uniformly from the range [lo, hi).\"\"\"\n    return random.randrange(lo, hi)\n\n\n# -----------------------------------------------------------------------\n\n\ndef uniformFloat(lo, hi):\n    \"\"\"Return a number chosen uniformly from the range [lo, hi).\"\"\"\n    return random.uniform(lo, hi)\n\n\n# -----------------------------------------------------------------------\n\n\ndef bernoulli(p=0.5):\n    \"\"\"Return True with probability p.\"\"\"\n    return random.random() < p\n\n\n# -----------------------------------------------------------------------\n\n\ndef binomial(n, p=0.5):\n    \"\"\"Return the number of heads in n coin flips, each of which is heads with\n    probability p.\"\"\"\n    heads = 0\n    for i in range(n):\n        if bernoulli(p):\n            heads += 1\n    return heads\n\n\n# -----------------------------------------------------------------------\n\n\ndef gaussian(mean=0.0, stddev=1.0):\n    \"\"\"Return a float according to a standard Gaussian distribution with the\n    given mean (mean) and standard deviation (stddev).\"\"\"\n\n    # Approach 1:\n    # return random.gauss(mu, sigma)\n\n    # Approach 2: Use the polar form of the Box-Muller transform.\n    x = uniformFloat(-1.0, 1.0)\n    y = uniformFloat(-1.0, 1.0)\n    r = x * x + y * y\n    while (r >= 1) or (r == 0):\n        x = uniformFloat(-1.0, 1.0)\n        y = uniformFloat(-1.0, 1.0)\n        r = x * x + y * y\n    g = x * math.sqrt(-2 * math.log(r) / r)\n    # Remark:  x * math.sqrt(-2 * math.log(r) / r)\n    # is an independent random gaussian\n    return mean + stddev * g\n\n\n# -----------------------------------------------------------------------\n\n\ndef discrete(a):\n    \"\"\"Return a float from a discrete distribution: i with probability a[i].\n\n    Precondition: the elements of array a sum to 1.\n\n    \"\"\"\n    r = uniformFloat(0.0, sum(a))\n    subtotal = 0.0\n    for i in range(len(a)):\n        subtotal += a[i]\n        if subtotal > r:\n            return i\n    # return len(a) - 1\n\n\n# -----------------------------------------------------------------------\n\n\ndef shuffle(a):\n    \"\"\"Shuffle array a.\"\"\"\n\n    # Approach 1:\n    # for i in range(len(a)):\n    #     j = i + uniformInt(len(a) - i)\n    #     temp = a[i]\n    #     a[i] = a[j]\n    #     a[j] = temp\n\n    # Approach 2:\n    random.shuffle(a)\n\n\n# -----------------------------------------------------------------------\n\n\ndef exp(lambd):\n    \"\"\"Return a float from an exponential distribution with rate lambd.\"\"\"\n\n    # Approach 1:\n    # return random.expovariate(lambd)\n\n    # Approach 2:\n    return -math.log(1 - random.random()) / lambd\n\n\n# -----------------------------------------------------------------------\n\n\ndef _main():\n    \"\"\"For testing.\"\"\"\n    import sys\n\n    from itu.algs4.stdlib import stdio\n\n    seed(1)\n    n = int(sys.argv[1])\n    for i in range(n):\n        stdio.writef(\" %2d \", uniformInt(10, 100))\n        stdio.writef(\"%8.5f \", uniformFloat(10.0, 99.0))\n        stdio.writef(\"%5s \", bernoulli())\n        stdio.writef(\"%5s \", binomial(100, 0.5))\n        stdio.writef(\"%7.5f \", gaussian(9.0, 0.2))\n        stdio.writef(\"%2d \", discrete([0.5, 0.3, 0.1, 0.1]))\n        stdio.writeln()\n\n\nif __name__ == \"__main__\":\n    _main()\n\n# -----------------------------------------------------------------------\n\n# python stdrandom.py 5\n#  27 60.65914 False    41 9.01682  0\n#  55 46.88378  True    48 8.90171  0\n#  58 92.96468  True    52 9.12770  0\n#  79 64.41387 False    47 9.49241  0\n#  29 32.30299  True    45 8.77630  1\n"
  },
  {
    "path": "itu/algs4/stdlib/stdstats.py",
    "content": "# code based on https://introcs.cs.princeton.edu/python/code/stdlib-python.zip as downloaded in dec 2017\n\n\"\"\"stdstats.py.\n\nThe stdstats module defines functions related to statistical analysis\nand graphical data display.\n\n\"\"\"\n\n# -----------------------------------------------------------------------\n\nimport math\n\nfrom itu.algs4.stdlib import stddraw\n\n# -----------------------------------------------------------------------\n\n# def min(a):\n#    \"\"\"\n#    Return the minimum value in array a.  Could call the built-in\n#    min() function instead.\n#    \"\"\"\n#    minumum = float('inf')\n#    for x in a:\n#        if x < minumum:\n#            minumum = x\n#    return minumum\n\n# -----------------------------------------------------------------------\n\n# def max(a):\n#    \"\"\"\n#    Return the maximum value in array a.  Could call the built-in\n#    max() function instead.\n#    \"\"\"\n#    maximum = float('-inf')\n#    for x in a:\n#        if x > maximum:\n#            maximum = x\n#    return maximum\n\n# -----------------------------------------------------------------------\n\n\ndef mean(a):\n    \"\"\"Return the average of the elements of array a.\"\"\"\n    return sum(a) / float(len(a))\n\n\n# -----------------------------------------------------------------------\n\n\ndef var(a):\n    \"\"\"Return the sample variance of the elements of array a.\"\"\"\n    mu = mean(a)\n    total = 0.0\n    for x in a:\n        total += (x - mu) * (x - mu)\n    return total / (float(len(a)) - 1.0)\n\n\n# -----------------------------------------------------------------------\n\n\ndef stddev(a):\n    \"\"\"Return the standard deviation of the elements of array a.\"\"\"\n    return math.sqrt(var(a))\n\n\n# -----------------------------------------------------------------------\n\n\ndef median(a):\n    \"\"\"Return the median of the elements of array a.\"\"\"\n    b = list(a)  # Make a copy of a.\n    b.sort()\n    length = len(b)\n    if length % 2 == 1:\n        return b[length // 2]\n    else:\n        return float(b[length // 2 - 1] + b[length // 2]) / 2.0\n\n\n# -----------------------------------------------------------------------\n\n\ndef plotPoints(a):\n    \"\"\"Plot the elements of array a as points.\"\"\"\n    n = len(a)\n    stddraw.setXscale(-1, n)\n    stddraw.setPenRadius(1.0 / (3.0 * n))\n    for i in range(n):\n        stddraw.point(i, a[i])\n\n\n# -----------------------------------------------------------------------\n\n\ndef plotLines(a):\n    \"\"\"Plot the elements of array a as line end-points.\"\"\"\n    n = len(a)\n    stddraw.setXscale(-1, n)\n    stddraw.setPenRadius(0.0)\n    for i in range(1, n):\n        stddraw.line(i - 1, a[i - 1], i, a[i])\n\n\n# -----------------------------------------------------------------------\n\n\ndef plotBars(a):\n    \"\"\"Plot the elements of array a as bars.\"\"\"\n    n = len(a)\n    stddraw.setXscale(-1, n)\n    for i in range(n):\n        stddraw.filledRectangle(i - 0.25, 0.0, 0.5, a[i])\n\n\n# -----------------------------------------------------------------------\n\n\ndef _main():\n    \"\"\"For testing:\"\"\"\n    import stdarray\n    import stdio\n\n    a = stdarray.readFloat1D()\n    # stdio.writef('       min %7.3f\\n', min(a))\n    # stdio.writef('       max %7.3f\\n', max(a))\n    stdio.writef(\"      mean %7.3f\\n\", mean(a))\n    stdio.writef(\"   std dev %7.3f\\n\", stddev(a))\n    stdio.writef(\"    median %7.3f\\n\", median(a))\n\n\nif __name__ == \"__main__\":\n    _main()\n"
  },
  {
    "path": "itu/algs4/strings/__init__.py",
    "content": ""
  },
  {
    "path": "itu/algs4/strings/boyer_moore.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport sys\n\n\nclass BoyerMoore:\n    \"\"\"The BoyerMoore class finds the first occurence of a pattern string in a\n    text string.\n\n    This implementation uses the Boyer-Moore algorithm (with the bad-\n    character rule, but not the strong good suffix rule).\n\n    \"\"\"\n\n    def __init__(self, pat):\n        \"\"\"Preprocesses the pattern string.\n\n        :param pat: the pattern string\n\n        \"\"\"\n        self.pat = pat\n        M = len(pat)\n        R = 256\n        self.right = [-1 for i in range(0, R)]  # -1 for chars not in pattern\n        for j in range(0, M):\n            self.right[ord(pat[j])] = j\n\n    def search(self, txt):\n        \"\"\"Returns the index of the first occurrrence of the pattern string in\n        the text string.\n\n        :param txt: the text string\n        :return: the index of the first occurrence of the pattern string\n        in the text string; N if no such match\n\n        \"\"\"\n        N = len(txt)\n        M = len(self.pat)\n        skip = 0\n        i = 0\n        # for i in range(0,N-M+1,skip):\n        while i <= N - M:\n            skip = 0\n            for j in range(M - 1, -1, -1):\n                if not (self.pat[j] == txt[i + j]):\n                    skip = j - self.right[ord(txt[i + j])]\n                    if skip < 1:\n                        skip = 1\n                    break\n            if skip == 0:\n                return i\n            i += skip\n        return N\n\n\ndef main():\n    \"\"\"Takes a pattern string and an input string as command-line arguments;\n    searches for the pattern string in the text string; and prints the first\n    occurrence of the pattern string in the text string.\n\n    Will print the pattern after the end of the string if no match is\n    found.\n\n    \"\"\"\n    pat = sys.argv[1]\n    txt = sys.argv[2]\n    bm = BoyerMoore(pat)\n    print(\"text:    {}\".format(txt))\n    offset = bm.search(txt)\n    print(\"pattern:\", end=\" \")\n    for _ in range(0, offset):\n        print(\"\", end=\" \")\n    print(pat)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/strings/huffman_compression.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Huffman compression module provides static methods for compressing and\nexpanding a binary input using Huffman codes over the 8-bit extended ASCII\nalphabet.\n\nFor additional documentation, see Section 5.5 of Algorithms, 4th\nedtition by Robert Sedgewick and Kevin Wayne.\n\n\"\"\"\nimport sys\n\nfrom itu.algs4.sorting.min_pq import MinPQ\nfrom itu.algs4.stdlib.binary_stdin import BinaryStdIn\nfrom itu.algs4.stdlib.binary_stdout import BinaryStdOut\n\n_R = 256\n\n\nclass _Node:\n    def __init__(self, ch, freq, left, right):\n        self.ch = ch\n        self.freq = freq\n        self.left = left\n        self.right = right\n\n    def is_leaf(self):\n        left = self.left\n        right = self.right\n        assert left is None and right is None or left is not None and right is not None\n        return left is None and right is None\n\n    def __gt__(self, that):\n        return self.freq > that.freq\n\n\ndef compress():\n    \"\"\"Reads a sequence of 8-bit bytes from standard input; compresses them using\n    Huffman codes with an 8-bit alphabet; and writes the results to standard\n    input.\"\"\"\n    s = BinaryStdIn.read_string()\n    # Tabulate frequency counts\n    freq = [0 for i in range(0, _R)]\n    for i in range(0, len(s)):\n        freq[ord(s[i])] += 1\n    # Build Huffman trie\n    root = _build_trie(freq)\n    # Build code table\n    st = [None for i in range(0, _R)]\n    _build_code(st, root, \"\")\n    # Print trie for decoder\n    _write_trie(root)\n    # Print number of bytes in original uncompressed message\n    BinaryStdOut.write_int(len(s))\n    # Use Huffman code to encode input\n    for i in range(0, len(s)):\n        code = st[ord(s[i])]\n        for j in range(0, len(code)):\n            if code[j] == \"0\":\n                BinaryStdOut.write_bool(False)\n            elif code[j] == \"1\":\n                BinaryStdOut.write_bool(True)\n            else:\n                raise ValueError(\"Illegal state\")\n    BinaryStdOut.close()\n\n\n# Build the Huffman trie given frequencies\ndef _build_trie(freq):\n    pq = MinPQ()\n    for i in range(0, _R):\n        if freq[i] > 0:\n            pq.insert(_Node(chr(i), freq[i], None, None))\n    if pq.size() == 0:\n        raise ValueError(\"The provided file is empty\")\n    if pq.size() == 1:\n        if freq[ord(\"\\0\")] == 0:\n            pq.insert(_Node(\"\\0\", 0, None, None))\n        else:\n            pq.insert(_Node(\"\\1\", 0, None, None))\n    while pq.size() > 1:\n        left = pq.del_min()\n        right = pq.del_min()\n        parent = _Node(\"\\0\", left.freq + right.freq, left, right)\n        pq.insert(parent)\n    return pq.del_min()\n\n\n# Write bitstring-encoded trie to standard output\ndef _write_trie(x):\n    if x.is_leaf():\n        BinaryStdOut.write_bool(True)\n        BinaryStdOut.write_char(x.ch)\n        return\n    BinaryStdOut.write_bool(False)\n    _write_trie(x.left)\n    _write_trie(x.right)\n\n\n# Make a lookup table from symbols and their encodings\ndef _build_code(st, x, s):\n    if not x.is_leaf():\n        _build_code(st, x.left, s + \"0\")\n        _build_code(st, x.right, s + \"1\")\n    else:\n        st[ord(x.ch)] = s\n\n\ndef expand():\n    \"\"\"Reads a sequence of bits that represents a Huffman-compressed message from\n    standard input; expands them; and writes the results to standard output.\"\"\"\n    BinaryStdIn.is_empty()\n    root = _read_trie()\n    length = BinaryStdIn.read_int()\n    for _ in range(0, length):\n        x = root\n        while not x.is_leaf():\n            bit = BinaryStdIn.read_bool()\n            if bit:\n                x = x.right\n            else:\n                x = x.left\n        BinaryStdOut.write_char(x.ch)\n    BinaryStdOut.close()\n\n\ndef _read_trie():\n    isLeaf = BinaryStdIn.read_bool()\n    if isLeaf:\n        return _Node(BinaryStdIn.read_char(), -1, None, None)\n    else:\n        return _Node(\"\\0\", -1, _read_trie(), _read_trie())\n\n\ndef main():\n    \"\"\"Sample client that calss compress() if the command-line argument is \"-\",\n    and expand() if it is \"+\".\"\"\"\n    if sys.argv[1] == \"-\":\n        compress()\n    elif sys.argv[1] == \"+\":\n        expand()\n    else:\n        raise ValueError(\"Illegal command line argument\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/strings/kmp.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\n\"\"\"\nThe KMP (Knuth-Morris-Pratt) class finds the first occurrence\nof a pattern string in a text string.\nThis implementation uses a version of the Knuth-Morris-Pratt substring search\nalgorithm. The version takes time as space proportional to\nN + M R in the worst case, where N is the length\nof the text string, M is the length of the pattern, and R\nis the alphabet size.\n\"\"\"\n\n\nclass KMP:\n    def __init__(self, pat):\n        \"\"\"Preprocesses the pattern string.\n\n        :param pat: the pattern string\n\n        \"\"\"\n        self.pat = pat\n        M = len(pat)\n        R = 256\n        self.dfa = [[0 for c in range(0, M)] for r in range(0, R)]\n        self.dfa[ord(pat[0])][0] = 1\n        X = 0\n        for j in range(1, M):\n            # Compute dfa[][j]\n            for c in range(0, R):\n                self.dfa[c][j] = self.dfa[c][X]  # Copy mismatch cases\n            self.dfa[ord(pat[j])][j] = j + 1  # Set match case\n            X = self.dfa[ord(pat[j])][X]  # Update restart state\n\n    def search(self, txt):\n        \"\"\"Returns the index of the first occurrrence of the pattern string in the\n        text string.\n\n        :param txt: the text string\n        :return: the index of the first occurrence of the pattern string\n        in the text string; N if no such match\n\n        \"\"\"\n        N = len(txt)\n        M = len(self.pat)\n        j = 0\n        i = 0\n        while i < N and j < M:\n            j = self.dfa[ord(txt[i])][j]\n            i += 1\n        if j == M:  # found (hit end of pattern)\n            return i - M\n        else:  # not found (hit end of text)\n            return N\n\n\ndef main():\n    \"\"\"Takes a pattern string and an input string as command-line arguments;\n    searches for the pattern string in the text string; and prints the first\n    occurrence of the pattern string in the text string.\n\n    Will print the pattern after the end of the string if no match is\n    found.\n\n    \"\"\"\n    pat = sys.argv[1]\n    txt = sys.argv[2]\n    kmp = KMP(pat)\n    print(\"text:    {}\".format(txt))\n    offset = kmp.search(txt)\n    print(\"pattern: \", end=\"\")\n    for _ in range(0, offset):\n        print(\"\", end=\" \")\n    print(pat)\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    main()\n"
  },
  {
    "path": "itu/algs4/strings/lsd.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module provides functions for sorting arrays of strings using lsd sort.\n\nFor additional documentation, see Section 5.1 of Algorithms, 4th Edition\nby Robert Sedgewick and Kevin Wayne.\n\n\"\"\"\n\n\ndef sort(a, w, radix=256):\n    \"\"\"Rearranges the array of w-character strings in ascending order.\n\n    :param a: the array to be sorted\n    :param w: the number of characters per string\n    :param radix: an optional number specifying the size of the alphabet to sort\n\n    \"\"\"\n\n    n = len(a)\n    aux = [None] * n\n\n    for d in range(w - 1, -1, -1):  # from w-i to 0\n        # sort by key-indexed counting on dth character\n\n        # compute frequency counts\n        count = [0] * (radix + 1)\n        for i in range(n):\n            ch = ord(a[i][d])  # get number representation of character\n            count[ch + 1] += 1\n\n        # compute cumulates\n        for r in range(radix):\n            count[r + 1] += count[r]\n\n        # move data\n        for i in range(n):\n            ch = ord(a[i][d])\n            aux[count[ch]] = a[i]\n            count[ch] += 1\n\n        # copy back\n        for i in range(n):\n            a[i] = aux[i]\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.stdlib import stdio\n\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    a = stdio.readAllStrings()\n    sort(a, 3)\n    for elem in a:\n        print(elem)\n"
  },
  {
    "path": "itu/algs4/strings/lzw.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The LSW module provides static methods for compressing and expanding a\nbinary input using LZW over the 8-bit extended ASCII alphabet with 12-bit\ncodewords.\n\nFor additional documentation see Section 5.5 of Algorithms, 4th Edition\nby Robert Sedgewick and Kevin Wayne.\n\n\"\"\"\nimport sys\n\nfrom itu.algs4.stdlib.binary_stdin import BinaryStdIn\nfrom itu.algs4.stdlib.binary_stdout import BinaryStdOut\nfrom itu.algs4.strings.tst import TST\n\n_R = 256\n_L = 4096\n_W = 12\n\n\ndef compress():\n    \"\"\"Reads a sequence of 8-bit bytes from standard input; compresses them using\n    LZW compression with 12-bit codewords; and writes the results to standard\n    output.\"\"\"\n    input_ = BinaryStdIn.read_string()\n    st = TST()\n    for i in range(0, _R):\n        st.put(\"\" + chr(i), i)\n    code = _R + 1\n    while len(input_) > 0:\n        s = st.longest_prefix_of(input_)\n        BinaryStdOut.write_int(st.get(s), _W)\n        t = len(s)\n        if t < len(input_) and code < _L:\n            st.put(input_[0 : t + 1], code)\n            code += 1\n        input_ = input_[t:]\n    BinaryStdOut.write_int(_R, _W)\n    BinaryStdOut.close()\n\n\ndef expand():\n    \"\"\"Reads a sequence of bit encoded using LZW compression with 12-bit codewords\n    from standard input; expands them; and writes the results to standard\n    output.\"\"\"\n    st = [\"\" for i in range(0, _L)]\n    i = 0\n    while i < _R:\n        st[i] = \"\" + chr(i)\n        i += 1\n    st[i] = \"\"\n    i += 1\n\n    codeword = BinaryStdIn.read_int(_W)\n    if codeword == _R:\n        return\n    val = st[codeword]\n    while True:\n        BinaryStdOut.write_string(val)\n        codeword = BinaryStdIn.read_int(_W)\n        if codeword == _R:\n            break\n        s = st[codeword]\n        if i == codeword:\n            s = val + val[0]\n        if i < _L:\n            st[i] = val + s[0]\n            i += 1\n        val = s\n    BinaryStdOut.close()\n\n\ndef main():\n    \"\"\"Sample client that calls compress() if the command-line argument is \"-\",\n    and expand() if it is \"+\".\n\n    Example: echo huhu | python3 algs4/strings/lzw.py - | python3 algs4/strings/lzw.py +\n\n    \"\"\"\n    if sys.argv[1] == \"-\":\n        compress()\n    elif sys.argv[1] == \"+\":\n        expand()\n    else:\n        raise ValueError(\"Illegal command line argument\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/strings/msd.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# Python 3\n\n\"\"\"This module provides functions for sorting arrays of strings using msd sort.\n\nFor additional documentation, see Section 5.1 of Algorithms, 4th Edition\nby Robert Sedgewick and Kevin Wayne.\n\n\"\"\"\n\ncutoff = 15\n\n\n# compare characters at position d\ndef _less(a, b, d):\n    return a[d] < b[d]\n\n\n# insertion sort a[lo..hi], starting at dth character\ndef _insertion(a, lo, hi, d):\n    for i in range(lo, hi + 1):\n        j = i\n        while j > lo and _less(a[j], a[j - 1], d):\n            a[j], a[j - 1] = a[j - 1], a[j]\n            j -= 1\n\n\n# sort from a[lo] to a[hi], starting at the dth character\ndef _sort(a, lo, hi, d, aux, radix):\n    if hi <= lo + cutoff:\n        _insertion(a, lo, hi, d)\n        return\n\n    # compute frequency counts\n    count = [0] * (radix + 2)\n    for i in range(hi + 1):\n        ch = ord(a[i][d])  # get number representation of character\n        count[ch + 2] += 1\n\n    # compute cumulates\n    for r in range(radix + 1):\n        count[r + 1] += count[r]\n\n    # move data\n    for i in range(hi + 1):\n        ch = ord(a[i][d])\n        aux[count[ch + 1]] = a[i]\n        count[ch + 1] += 1\n\n    # copy back\n    for i in range(hi + 1):\n        a[i] = aux[i - lo]\n\n    # recursively sort for each character (excludes sentinel -1)\n    for r in range(radix):\n        _sort(a, lo + count[r], lo + count[r + 1] - 1, d + 1, aux, radix)\n\n\ndef sort(a, radix=256):\n    \"\"\"Rearranges the array of 32-bit integers in ascending order. Currently\n    assumes that the integers are nonnegative.\n\n    :param a: the array to be sorted\n\n    \"\"\"\n    n = len(a)\n    aux = [None] * n\n    _sort(a, 0, n - 1, 0, aux, radix)\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    from itu.algs4.stdlib import stdio\n\n    if len(sys.argv) > 1:\n        try:\n            sys.stdin = open(sys.argv[1])\n        except IOError:\n            print(\"File not found, using standard input instead\")\n\n    a = stdio.readAllStrings()\n    sort(a)\n    for elem in a:\n        print(elem)\n"
  },
  {
    "path": "itu/algs4/strings/nfa.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\nimport sys\n\nfrom itu.algs4.fundamentals.bag import Bag\nfrom itu.algs4.fundamentals.stack import Stack\nfrom itu.algs4.graphs.digraph import Digraph\nfrom itu.algs4.graphs.directed_dfs import DirectedDFS\n\n\nclass NFA:\n    \"\"\"The NFA class provides a data type for creating a nondeterministic finite\n    state automaton (NFA) from a regular expression and testing whether a given\n    string is matched by that regular expression. It supports the following\n    operations: concatenation, closure, binary or, and parentheses, metacharacters\n    (either in the text or pattern), capturing capabilities, greedy or\n    reluctant/lazy modifiers, and other features in industrial-strength\n    implementations such as Java's Pattern and Matcher.\n\n    This implementation builds the NFA using a digraph and a stack\n    and simulates the NFA using digraph search (see the textbook for details).\n    The constructor takes time proportional to m, where m is the\n    number of characters in the regular expression.\n    The recognizes() method takes time proportional to m*n, where n\n    is the number of characters in the text.\n\n    For additional documentation, see section 5.4 of Algorithms, 4th Edition\n    by Robert Sedgewick and Kevin Wayne.\n\n    \"\"\"\n\n    def __init__(self, regex):\n        \"\"\"Initializes the NFA from the specified regular expression.\n\n        :param regex: the regular expression\n\n        \"\"\"\n        self.regex = regex\n        m = len(regex)\n        self.m = m\n        ops = Stack()\n        graph = Digraph(m + 1)\n        for i in range(0, m):\n            lp = i\n            if regex[i] == \"(\" or regex[i] == \"|\":\n                ops.push(i)\n            elif regex[i] == \")\":\n                or_ = ops.pop()\n\n                # 2-way or operator\n                if regex[or_] == \"|\":\n                    lp = ops.pop()\n                    graph.add_edge(lp, or_ + 1)\n                    graph.add_edge(or_, i)\n                elif regex[or_] == \"(\":\n                    lp = or_\n                else:\n                    assert False\n            if i < m - 1 and regex[i + 1] == \"*\":\n                graph.add_edge(lp, i + 1)\n                graph.add_edge(i + 1, lp)\n            if regex[i] == \"(\" or regex[i] == \"*\" or regex[i] == \")\":\n                graph.add_edge(i, i + 1)\n        if ops.size() != 0:\n            raise ValueError(\"Invalid regular expression\")\n        self.graph = graph\n\n    def recognizes(self, txt):\n        \"\"\"Returns True if the text is matched by the regular expression.\n\n        :param txt: the text\n        :returns: True if the text is matched by the regular expression;\n                    False otherwise\n\n        \"\"\"\n        regex = self.regex\n        graph = self.graph\n        m = self.m\n        dfs = DirectedDFS(graph, 0)\n        pc = Bag()\n        for v in range(0, graph.V()):\n            if dfs.is_marked(v):\n                pc.add(v)\n\n        # Compute possible NFA states for txt[i+1]\n        for i in range(0, len(txt)):\n            if txt[i] == \"*\" or txt[i] == \"|\" or txt[i] == \"(\" or txt[i] == \")\":\n                raise ValueError(\"text contains the metacharacter '{}'\".format(txt[i]))\n            match = Bag()\n            for v in pc:\n                if v == m:\n                    continue\n                if regex[v] == txt[i] or regex[i] == \".\":\n                    match.add(v + 1)\n            dfs = DirectedDFS(graph, *match)\n            pc = Bag()\n            for v in range(0, graph.V()):\n                if dfs.is_marked(v):\n                    pc.add(v)\n            # Optimization if no states reachable\n            if pc.size() == 0:\n                return False\n        for v in pc:\n            if v == m:\n                return True\n            return False\n\n\ndef main():\n    \"\"\"Unit tests the NFA data type.\"\"\"\n    regex = \"({})\".format(sys.argv[1])\n    txt = sys.argv[2]\n    nfa = NFA(regex)\n    print(nfa.recognizes(txt))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/strings/quick3string.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\n\"\"\"The Quick3String module provides functions for sorting an array of strings\nusing 3-way radix quicksort.\"\"\"\nimport sys\n\n\ndef sort(a):\n    \"\"\"Rearranges the array of strings in ascending order.\n\n    :param a: the array to be sorted.\n\n    \"\"\"\n    _sort(a, 0, len(a) - 1, 0)\n\n\ndef _sort(a, lo, hi, d):\n    if hi <= lo:\n        return\n    lt = lo\n    gt = hi\n    v = _char_at(a[lo], d)\n    i = lo + 1\n    while i <= gt:\n        t = _char_at(a[i], d)\n        if t < v:\n            _exch(a, lt, i)\n            lt += 1\n            i += 1\n        elif t > v:\n            _exch(a, i, gt)\n            gt -= 1\n        else:\n            i += 1\n    _sort(a, lo, lt - 1, d)\n    if v >= 0:\n        _sort(a, lt, gt, d + 1)\n    _sort(a, gt + 1, hi, d)\n\n\ndef _char_at(s, d):\n    if d < len(s):\n        return ord(s[d])\n    else:\n        return -1\n\n\ndef _show(a):\n    for item in a:\n        print(item)\n\n\ndef is_sorted(a):\n    \"\"\"Returns true if a is sorted.\n\n    :param a: the array to be checked.\n    :returns: True if a is sorted.\n\n    \"\"\"\n    for i in range(1, len(a)):\n        if _less(a[i], a[i - 1]):\n            return False\n    return True\n\n\ndef _less(v, w):\n    return v < w\n\n\ndef _exch(a, i, j):\n    t = a[i]\n    a[i] = a[j]\n    a[j] = t\n\n\ndef main():\n    \"\"\"Reads in a sequence of fixed-length strings from standard input; 3-way\n    radix quicksorts them; and prints them to standard output in ascending\n    order.\"\"\"\n    a = sys.argv[1:]\n    sort(a)\n    assert is_sorted(a)\n    _show(a)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "itu/algs4/strings/rabin_karp.py",
    "content": "# Created for BADS 2018\n# See README.md for details\n# This is python3\nimport math\nimport random\n\n\n# The following part is borrowed from https://langui.sh/2009/03/07/generating-very-large-primes/\n# in an effort to implement the missing long_random_prime() function\ndef _rabin_miller(n):\n    s = n - 1\n    t = 0\n    while s & 1 == 0:\n        s = int(s / 2)\n        t += 1\n    k = 0\n    while k < 128:\n        a = random.randrange(2, n - 1)\n        # a^s is computationally infeasible.  we need a more intelligent approach\n        # v = (a**s)%n\n        # python's core math module can do modular exponentiation\n        v = pow(a, s, n)  # where values are (num,exp,mod)\n        if v != 1:\n            i = 0\n            while v != (n - 1):\n                if i == t - 1:\n                    return False\n                else:\n                    i = i + 1\n                    v = (v ** 2) % n\n        k += 2\n    return True\n\n\ndef _is_prime(n):\n    # lowPrimes is all primes (sans 2, which is covered by the bitwise and operator)\n    # under 1000. taking n modulo each lowPrime allows us to remove a huge chunk\n    # of composite numbers from our potential pool without resorting to Rabin-Miller\n    lowPrimes = [\n        3,\n        5,\n        7,\n        11,\n        13,\n        17,\n        19,\n        23,\n        29,\n        31,\n        37,\n        41,\n        43,\n        47,\n        53,\n        59,\n        61,\n        67,\n        71,\n        73,\n        79,\n        83,\n        89,\n        97,\n        101,\n        103,\n        107,\n        109,\n        113,\n        127,\n        131,\n        137,\n        139,\n        149,\n        151,\n        157,\n        163,\n        167,\n        173,\n        179,\n        181,\n        191,\n        193,\n        197,\n        199,\n        211,\n        223,\n        227,\n        229,\n        233,\n        239,\n        241,\n        251,\n        257,\n        263,\n        269,\n        271,\n        277,\n        281,\n        283,\n        293,\n        307,\n        311,\n        313,\n        317,\n        331,\n        337,\n        347,\n        349,\n        353,\n        359,\n        367,\n        373,\n        379,\n        383,\n        389,\n        397,\n        401,\n        409,\n        419,\n        421,\n        431,\n        433,\n        439,\n        443,\n        449,\n        457,\n        461,\n        463,\n        467,\n        479,\n        487,\n        491,\n        499,\n        503,\n        509,\n        521,\n        523,\n        541,\n        547,\n        557,\n        563,\n        569,\n        571,\n        577,\n        587,\n        593,\n        599,\n        601,\n        607,\n        613,\n        617,\n        619,\n        631,\n        641,\n        643,\n        647,\n        653,\n        659,\n        661,\n        673,\n        677,\n        683,\n        691,\n        701,\n        709,\n        719,\n        727,\n        733,\n        739,\n        743,\n        751,\n        757,\n        761,\n        769,\n        773,\n        787,\n        797,\n        809,\n        811,\n        821,\n        823,\n        827,\n        829,\n        839,\n        853,\n        857,\n        859,\n        863,\n        877,\n        881,\n        883,\n        887,\n        907,\n        911,\n        919,\n        929,\n        937,\n        941,\n        947,\n        953,\n        967,\n        971,\n        977,\n        983,\n        991,\n        997,\n    ]\n    if n >= 3:\n        if n & 1 != 0:\n            for p in lowPrimes:\n                if n == p:\n                    return True\n                if n % p == 0:\n                    return False\n            return _rabin_miller(n)\n    return False\n\n\ndef long_random_prime(k):\n    \"\"\"Generates a random prime.\n\n    :param k: the desired bit length of the prime\n    :returns: a random prime of bit length k\n\n    \"\"\"\n    # k is the desired bit length\n    r = 100 * (math.log(k, 2) + 1)  # number of attempts max\n    r_ = r\n    while r > 0:\n        # randrange is mersenne twister and is completely deterministic\n        # unusable for serious crypto purposes\n        n = random.randrange(2 ** (k - 1), 2 ** (k))\n        r -= 1\n        if _is_prime(n):\n            return n\n    return \"Failure after \" + r_ + \" tries.\"\n\n\nclass RabinKarp:\n    \"\"\"The RabinKarp class finds the first occurence of a pattern string in a\n    text string.\n\n    This implementation uses the Monte Carlo version of the Rabin-Karp\n    algorithm.\n\n    \"\"\"\n\n    def __init__(self, pat):\n        \"\"\"Preprocesses the pattern string.\n\n        :param pat: the pattern string\n\n        \"\"\"\n        self.M = len(pat)\n        self.R = 256\n        self.Q = long_random_prime(32)\n        self.RM = 1\n        for _ in range(1, self.M):\n            self.RM = (self.R * self.RM) % self.Q\n        self.patHash = self._hash(pat, self.M)  # pattern hash value\n\n    def search(self, txt):\n        \"\"\"Returns the index of the first occurrrence of the pattern string in\n        the text string.\n\n        :param txt: the text string\n        :return: the index of the first occurrence of the pattern string\n        in the text string; N if no such match\n\n        \"\"\"\n        N = len(txt)\n        M = self.M\n        RM = self.RM\n        Q = self.Q\n        R = self.R\n        patHash = self.patHash\n        txtHash = self._hash(txt, M)\n        if patHash == txtHash:\n            return 0\n        for i in range(M, N):\n            txtHash = (txtHash + Q - RM * ord(txt[i - M]) % Q) % Q\n            txtHash = (txtHash * R + ord(txt[i])) % Q\n            if patHash == txtHash:\n                if self._check(i - M + 1):\n                    return i - M + 1\n        return N\n\n    def _check(self, i):\n        # Not needed in the Monte Carlo version\n        # For Las Vegas, check pat with txt[i:i-M+1]\n        return True\n\n    def _hash(self, key, M):\n        # Modular hashing using Horner's method\n        h = 0\n        for j in range(0, M):\n            h = self.R * h + ord(key[j]) % self.Q\n        return h\n\n\ndef main():\n    \"\"\"Takes a pattern string and an input string as command-line arguments;\n    searches for the pattern string in the text string; and prints the first\n    occurrence of the pattern string in the text string.\n\n    Will print the pattern after the end of the string if no match is\n    found.\n\n    \"\"\"\n    pat = sys.argv[1]\n    txt = sys.argv[2]\n    rk = RabinKarp(pat)\n    print(\"text:    {}\".format(txt))\n    offset = rk.search(txt)\n    print(\"pattern:\", end=\" \")\n    for _ in range(0, offset):\n        print(\"\", end=\" \")\n    print(pat)\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    main()\n"
  },
  {
    "path": "itu/algs4/strings/trie_st.py",
    "content": "# created for BADS 2018\n# See README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.stdlib import stdio\n\ntry:\n    q = Queue()\n    q.enqueue(1)\nexcept AttributeError:\n    print(\"ERROR - Could not import itu.algs4 queue\")\n    sys.exit(1)\n\n\n\"\"\"\n *  The TrieST class represents an symbol table of key-value\n *  pairs, with string keys and generic values.\n *  It supports the usual put, get, contains,\n *  delete, size, and is-empty methods.\n *  It also provides character-based methods for finding the string\n *  in the symbol table that is the longest prefix of a given prefix,\n *  finding all strings in the symbol table that start with a given prefix,\n *  and finding all strings in the symbol table that match a given pattern.\n *  A symbol table implements the associative array abstraction:\n *  when associating a value with a key that is already in the symbol table,\n *  the convention is to replace the old value with the new value.\n *  This class uses the convention that\n *  values cannot be None, setting the\n *  value associated with a key to None is equivalent to deleting the key\n *  from the symbol table.\n *  This implementation uses a 256-way trie.\n *  The put, contains, delete, and\n *  longest prefix operations take time proportional to the length\n *  of the key (in the worst case). Construction takes constant time.\n *  The size, and is-empty operations take constant time.\n \"\"\"\n\n\nclass TrieST(object):\n    R = 256  # extended ASCII\n\n    # R-way trie node\n    class Node(object):\n        R = 256\n\n        def __init__(self):\n            self.val = None\n            self.next = [None] * self.R  # array of nodes of length R\n\n    def __init__(self):\n        self._root = self.Node()  # root of trie\n        self._n = 0  # number of keys in trie\n\n    # Returns the value associated with the given key.\n    # @param key: the key\n    # @return: the value associated with the given key if the key is in the symbol table\n    #     and None if the key is not in the symbol table\n    # @raises TypeError if key is None\n\n    def get(self, key):\n        x = self._get(self._root, key, 0)\n        return None if x is None else x.val\n\n    # Does this symbol table contain the given key?\n    # @param key: the key\n    # @returns True if this symbol table contains key and\n    #     False otherwise\n    # @raises TypeError if key is None\n\n    def contains(self, key):\n        return self.get(key) is not None\n\n    def _get(self, x, key, d):\n        if x is None:\n            return None\n        if d == len(key):\n            return x\n        c = key[d]\n        return self._get(x.next[ord(c)], key, d + 1)\n\n    # Inserts the key-value pair into the symbol table, overwriting the old value\n    # with the new value if the key is already in the symbol table.\n    # If the value is None, this effectively deletes the key from the symbol table.\n    # @param key: the key\n    # @param val: the value\n    # @raises TypeError if key is None\n\n    def put(self, key, val):\n        if val is None:\n            self.delete(key)\n        else:\n            self._root = self._put(self._root, key, val, 0)\n\n    def _put(self, x, key, val, d):\n        if x is None:\n            x = self.Node()\n        if d == len(key):\n            if x.val is None:\n                self._n += 1\n            x.val = val\n            return x\n        c = key[d]\n        x.next[ord(c)] = self._put(x.next[ord(c)], key, val, d + 1)\n        return x\n\n    # @return the number of key-value pairs in this symbol table\n    def size(self):\n        return self._n\n\n    def __len__(self):\n        return self.size()\n\n    # Is this symbol table empty?\n    # @return True if this symbol table is empty and False otherwise\n    def is_empty(self):\n        return self.size() == 0\n\n    # Returns all keys in the symbol table as an iterable object.\n    # To iterate over all of the keys in the symbol table named st,\n    # use the foreach notation: for key in st.keys().\n    # @return all keys in the symbol table as an iterable object\n\n    def keys(self):\n        return self.keys_with_prefix(\"\")\n\n    # Returns all of the keys in the set that start with prefix.\n    # @param prefix: the prefix\n    # @return all of the keys in the set that start with prefix,\n    #     as an iterable\n\n    def keys_with_prefix(self, prefix):\n        results = Queue()\n        x = self._get(self._root, prefix, 0)\n        self._collect(x, prefix, results)\n        return results\n\n    def _collect(self, x, prefix, results):\n        if x is None:\n            return\n        if x.val is not None:\n            results.enqueue(prefix)\n        for c in range(0, self.R):\n            self._collect(x.next[c], prefix + chr(c), results)\n\n    # Returns all of the keys in the symbol table that match pattern,\n    # where . symbol is treated as a wildcard character.\n    # @param pattern the pattern\n    # @return all of the keys in the symbol table that match pattern,\n    #     as an iterable, where . is treated as a wildcard character.\n\n    def keys_that_match(self, pattern):\n        results = Queue()\n        self._collect_match(self._root, \"\", pattern, results)\n        return results\n\n    def _collect_match(self, x, prefix, pattern, results):\n        if x is None:\n            return None\n        d = len(prefix)\n        if d == len(pattern) and x.val is not None:\n            results.enqueue(prefix)\n        if d >= len(pattern):\n            return\n        c = pattern[d]\n        if c == \".\":\n            for c in range(0, self.R):\n                self._collect_match(x.next[c], prefix + chr(c), pattern, results)\n        else:\n            self._collect_match(x.next[ord(c)], prefix + c, pattern, results)\n\n    # Returns the string in the symbol table that is the longest prefix of query,\n    # or None, if no such string.\n    # @param query the query string\n    # @return the string in the symbol table that is the longest prefix of query,\n    #  or None if no such string\n    # @raises TypeError if query is None\n\n    def longest_prefix_of(self, query):\n        length = self._longest_prefix_of(self._root, query, 0, -1)\n        if length == -1:\n            return None\n        else:\n            return query[:length]\n\n    # returns the length of the longest string key in the subtrie\n    # rooted at x that is a prefix of the query string,\n    # assuming the first d character match and we have already\n    # found a prefix match of given length (-1 if no such match)\n\n    def _longest_prefix_of(self, x, query, d, length):\n        if x is None:\n            return length\n        if x.val is not None:\n            length = d\n        if d == len(query):\n            return length\n        c = query[d]\n        return self._longest_prefix_of(x.next[ord(c)], query, d + 1, length)\n\n    # Removes the key from the set if the key is present.\n    # @param key the key\n    # @raises TypeError if key is None\n\n    def delete(self, key):\n        self._root = self._delete(self._root, key, 0)\n\n    def _delete(self, x, key, d):\n        if x is None:\n            return None\n        if d == len(key):\n            if x.val is not None:\n                self._n += -1\n            x.val = None\n        else:\n            c = key[d]\n            x.next[ord(c)] = self._delete(x.next[ord(c)], key, d + 1)\n\n        # remove subtrie rooted at x if it is completely empty\n        if x.val is not None:\n            return x\n        for c in range(0, self.R):\n            if x.next[c] is not None:\n                return x\n        return None\n\n\ndef test():\n    st = TrieST()\n    st.put(\"abc\", 0)\n    keys = [k for k in st.keys()]\n    assert keys == [\"abc\"]\n    assert st.get(\"abc\") == 0\n    st.put(\"a\", 1)\n    st.put(\"b\", 2)\n    st.put(\"c\", 3)\n    st.delete(\"abc\")\n    assert \"abc\" not in [k for k in st.keys()]\n    assert st.get(\"a\") == 1\n    assert st.get(\"b\") == 2\n    assert st.get(\"c\") == 3\n    st.put(\"hello\", 10)\n    assert st.contains(\"hello\")\n    assert st.contains(\"not there\") is False\n    st.put(\"he\", 20)\n    assert st.longest_prefix_of(\"hell\") == \"he\"\n    st.put(\"jello\", 30)\n    q = st.keys_that_match(\".e.l.\")\n    assert q.size() == 2 and \"jello\" in q and \"hello\" in q\n    print(\"tests passed.\")\n\n\nif __name__ == \"__main__\":\n    test()\n    st = TrieST()\n    i = 0\n    print(\"Insert keys (Ctrl-D to stop):\")\n    while not stdio.isEmpty():\n        key = stdio.readString()\n        st.put(key, i)\n        i += 1\n    # print results\n    if st.size() < 100:\n        print('keys(\"\"):')\n        for key in st.keys():\n            print(\"{} {}\".format(key, st.get(key)))\n        print()\n    print('longest_prefix_of(\"shellsort\"):')\n    print(st.longest_prefix_of(\"shellsort\"))\n    print()\n    print('longest_prefix_of(\"quicksort\")')\n    print(st.longest_prefix_of(\"quicksort\"))\n    print()\n    print('keys_with_prefix(\"shor\")')\n    for s in st.keys_with_prefix(\"shor\"):\n        print(s)\n    print()\n    print('keys_that_match(\"he.l.\")')\n    for s in st.keys_that_match(\"he.l.\"):\n        print()\n"
  },
  {
    "path": "itu/algs4/strings/tst.py",
    "content": "# created for BADS 2018\n# see README.md for details\n# Python 3\n\nimport sys\n\nfrom itu.algs4.fundamentals.queue import Queue\nfrom itu.algs4.stdlib import stdio\n\ntry:\n    q = Queue()\n    q.enqueue(1)\nexcept AttributeError:\n    print(\"ERROR - unable to import python algs4 Queue class\")\n    sys.exit(1)\n\n# Symbol table with string keys, implemented using a ternary search\n# trie (TST).\n\n\"\"\"\n  The TST class represents an symbol table of key-value\n  pairs, with string keys and generic values.\n  It supports the usual put, get, contains,\n  delete, size, and is-empty methods.\n  It also provides character-based methods for finding the string\n  in the symbol table that is the longest prefix of a given prefix,\n  finding all strings in the symbol table that start with a given prefix,\n  and finding all strings in the symbol table that match a given pattern.\n  A symbol table implements the associative array abstraction:\n  when associating a value with a key that is already in the symbol table,\n  the convention is to replace the old value with the new value.\n  This class uses the convention that\n  values cannot be None setting the\n  value associated with a key to None is equivalent to deleting the key\n  from the symbol table.\n  This implementation uses a ternary search trie.\n\"\"\"\n\n\nclass TST(object):\n    class Node:\n        def __init__(self):\n            self.c = None  # character\n            self.left = None  # left, middle and right subtries\n            self.mid = None\n            self.right = None\n            self.val = None  # value associated with string\n\n    def __init__(self):\n        self.n = 0  # size\n        self.root = None  # root of TST\n\n    # @return the number of key-value pairs in this symbol table\n    def size(self):\n        return self.n\n\n    def __len__(self):\n        return self.size()\n\n    # Does this symbol table contain the given key?\n    # @param key the key\n    # @return True if this symbol table contains key and\n    #     False otherwise\n    # @raises ValueError if key is None\n    def contains(self, key):\n        if key is None:\n            raise ValueError(\n                \"argument of contains is None\"\n            )  # TODO maybe get a specific exception, like IllegalArgumentException in Java\n        return self.get(key) is not None\n\n    # Returns the value associated with the given key.\n    # @param key the key\n    # @return the value associated with the given key if the key is in the symbol table\n    #     and null if the key is not in the symbol table\n    # @raises ValueError if key is None\n    def get(self, key):\n        if key is None:\n            raise ValueError(\n                \"calls get() with null argument\"\n            )  # TODO IllegalArgumentException?\n        if len(key) == 0:\n            raise ValueError(\n                \"key must have length >=1\"\n            )  # TODO IllegalArgumentException?\n        x = self._get(self.root, key, 0)\n        if x is None:\n            return None\n        return x.val\n\n    # return subtrie corresponding to given key\n    def _get(self, x, key, d):\n        if x is None:\n            return None\n        if len(key) == 0:\n            raise ValueError(\"key nust have length >= 1\")\n        c = key[d]\n        if c < x.c:\n            return self._get(x.left, key, d)\n        elif c > x.c:\n            return self._get(x.right, key, d)\n        elif d < len(key) - 1:\n            return self._get(x.mid, key, d + 1)\n        else:\n            return x\n\n    # Inserts the key-value pair into the symbol table, overwriting the old value\n    # with the new value if the key is already in the symbol table.\n    # If the value is None, this effectively deletes the key from the symbol table.\n    # @param key the key\n    # @param val the value\n    # @raises ValueError if key is None\n\n    def put(self, key, val):\n        if key is None:\n            raise ValueError(\n                \"calls put() with null key\"\n            )  # TODO IllegalArgumentException\n        if not self.contains(key):\n            self.n += 1\n        self.root = self._put(self.root, key, val, 0)\n\n    def _put(self, x, key, val, d):\n        c = key[d]\n        if x is None:\n            x = self.Node()\n            x.c = c\n        if c < x.c:\n            x.left = self._put(x.left, key, val, d)\n        elif c > x.c:\n            x.right = self._put(x.right, key, val, d)\n        elif d < len(key) - 1:\n            x.mid = self._put(x.mid, key, val, d + 1)\n        else:\n            x.val = val\n\n        return x\n\n    # Returns the string in the symbol table that is the longest prefix of query,\n    # or None, if no such string.\n    # @param query the query string\n    # @return the string in the symbol table that is the longest prefix of query,\n    #     or None if no such string\n    # @raises ValueError if query is None\n\n    def longest_prefix_of(self, query):\n        if query is None:\n            raise ValueError(\"calls longest_path_of() with None argument\")\n        if len(query) == 0:\n            return None\n        length = 0\n        x = self.root\n        i = 0\n        while x is not None and i < len(query):\n            c = query[i]\n            if c < x.c:\n                x = x.left\n            elif c > x.c:\n                x = x.right\n            else:\n                i += 1\n                if x.val is not None:\n                    length = i\n                x = x.mid\n        return query[0:length]\n\n    # Returns all keys in the symbol table as an Iterable.\n    # To iterate over all of the keys in the symbol table named st,\n    # use the foreach notation: for key in st.keys().\n    # @return all keys in the symbol table as an Iterable\n\n    def keys(self):\n        queue = Queue()\n        self._collect(self.root, \"\", queue)\n        return queue\n\n    # Returns all of the keys in the set that start with prefix.\n    # @param prefix the prefix\n    # @return all of the keys in the set that start with prefix,\n    #     as an iterable\n    # @raises ValueError if prefix is None\n\n    def keys_with_prefix(self, prefix):\n        if prefix is None:\n            raise ValueError(\n                \"calls keys_with_prefix with null argument\"\n            )  # TODO IllegalArgumentException\n        queue = Queue()\n        x = self._get(self.root, prefix, 0)\n        if x is None:\n            return queue\n        if x.val is not None:\n            queue.enqueue(prefix)\n        self._collect(x.mid, prefix, queue)\n        return queue\n\n    # all keys in subtrie rooted at x with given prefix\n    def _collect(self, x, prefix, queue):\n        if x is None:\n            return\n        self._collect(x.left, prefix, queue)\n        if x.val is not None:\n            queue.enqueue(prefix + str(x.c))\n        self._collect(x.mid, prefix + str(x.c), queue)\n        self._collect(x.right, prefix, queue)\n\n    # Returns all of the keys in the symbol table that match pattern,\n    # where . symbol is treated as a wildcard character.\n    # @param pattern the pattern\n    # @return all of the keys in the symbol table that match pattern,\n    #     as an iterable, where . is treated as a wildcard character.\n\n    def keys_that_match(self, pattern):\n        queue = Queue()\n        self._collect_match(self.root, \"\", 0, pattern, queue)\n        return queue\n\n    def _collect_match(self, x, prefix, i, pattern, queue):\n        if x is None:\n            return\n        c = pattern[i]\n        if c == \".\" or c < x.c:\n            self._collect_match(x.left, prefix, i, pattern, queue)\n        if c == \".\" or c == x.c:\n            if i == len(pattern) - 1 and x.val is not None:\n                queue.enqueue(prefix + str(x.c))\n            if i < len(pattern) - 1:\n                self._collect_match(x.mid, prefix + x.c, i + 1, pattern, queue)\n        if c == \".\" or c > x.c:\n            self._collect_match(x.right, prefix, i, pattern, queue)\n\n\n# * Unit tests the TST data type.\ndef test():\n    st = TST()\n    st.put(\"abc\", 0)\n    keys = [k for k in st.keys()]\n    assert keys == [\"abc\"]\n    assert st.get(\"abc\") == 0\n    st.put(\"a\", 1)\n    st.put(\"b\", 2)\n    st.put(\"c\", 3)\n    # st.delete(\"abc\")\n    # assert \"abc\" not in [k for k in st.keys()]\n    assert st.get(\"a\") == 1\n    assert st.get(\"b\") == 2\n    assert st.get(\"c\") == 3\n    st.put(\"hello\", 10)\n    assert st.contains(\"hello\")\n    assert st.contains(\"not there\") is False\n    st.put(\"he\", 20)\n    assert st.longest_prefix_of(\"hell\") == \"he\"\n    st.put(\"jello\", 30)\n    q = st.keys_that_match(\".e.l.\")\n    assert q.size() == 2 and \"jello\" in q and \"hello\" in q\n    print(\"tests passed.\")\n\n\nif __name__ == \"__main__\":\n    test()\n    st = TST()\n    i = 0\n    # build symbol table from stdin\n    print(\"Insert keys (Ctrl-D to stop):\")\n    while not stdio.isEmpty():\n        key = stdio.readString()\n        st.put(key, i)\n        i += 1\n    # print results\n    if st.size() < 100:\n        print('keys(\"\"):')\n        for key in st.keys():\n            print(\"{} {}\".format(key, st.get(key)))\n        print()\n\n        print('longestPrefixOf(\"shellsort\"):')\n        print(st.longest_prefix_of(\"shellsort\"))\n        print()\n\n        print('longestPrefixOf(\"shell\"):')\n        print(st.longest_prefix_of(\"shell\"))\n        print()\n\n        print('keysWithPrefix(\"shor\"):')\n        for s in st.keys_with_prefix(\"shor\"):\n            print(s)\n        print()\n\n        print('keysThatMatch(\".he.l.\"):')\n        for s in st.keys_that_match(\".he.l.\"):\n            print(s)\n"
  },
  {
    "path": "setup.cfg",
    "content": "[flake8]\nignore = E203, E266, E501, W503\nmax-line-length = 88\nmax-complexity = 18\nselect = B,C,E,F,W,T4\n\n[isort]\nmulti_line_output=3\ninclude_trailing_comma=True\nforce_grid_wrap=0\nuse_parentheses=True\nline_length = 88\n\n[mypy]\nfiles=.\nexclude=itu\nignore_missing_imports=true\n\n[tool:pytest]\ntestpaths=tests\n\n[coverage:run]\nsource = itu\n\n[coverage:report]\nexclude_lines =\n    # Have to re-enable the standard pragma\n    pragma: no cover\n\n    # Don't complain about missing debug-only code:\n    def __repr__\n    if self\\.debug\n\n    # Don't complain if tests don't hit defensive assertion code:\n    raise AssertionError\n    raise NotImplementedError\n\n    # Don't complain if non-runnable code isn't run:\n    if 0:\n    if __name__ == .__main__.:\n"
  },
  {
    "path": "setup.py",
    "content": "from setuptools import find_packages, setup\n\nsetup(\n    name=\"itu.algs4\",\n    version=\"0.2.5\",\n    description='Python 3 port of the Java code in \"Algorithms, 4th Edition\" by Sedgewick and Wayne',\n    long_description=open(\"README.md\").read(),\n    long_description_content_type=\"text/markdown\",\n    author=\"Algorithms group at ITU Copenhagen\",\n    # author_email='',\n    url=\"https://github.com/itu-algorithms/itu.algs4/\",\n    license=\"GNU General Public License v3 (GPLv3)\",\n    packages=find_packages(exclude=[\"examples\", \"tests\"]),\n    include_package_data=True,\n    extras_require={\n        \"audio\": [\"numpy\"],\n        \"visual\": [\"pygame\"],\n        \"dev\": [\n            \"flake8\",\n            \"black\",\n            \"isort\",\n            \"pytest\",\n            \"pytest-cov\",\n            \"coveralls\",\n            \"mypy\",\n        ],\n    },\n    zip_safe=False,\n    platforms=\"any\",\n    classifiers=[\n        \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n        \"Operating System :: OS Independent\",\n        \"Natural Language :: English\",\n        \"Programming Language :: Python\",\n        \"Programming Language :: Python :: 3\",\n        \"Topic :: Utilities\",\n        \"Intended Audience :: Developers\",\n        \"Intended Audience :: Education\",\n        \"Intended Audience :: Science/Research\",\n        \"Topic :: Software Development :: Libraries :: Python Modules\",\n    ],\n)\n"
  },
  {
    "path": "tests/test_bst.py",
    "content": "import random\nimport unittest\n\nfrom itu.algs4.errors.errors import NoSuchElementException\nfrom itu.algs4.searching.bst import BST\n\n\nclass TestBSTMethods(unittest.TestCase):\n    def setUp(self):\n        self.bst = BST()\n\n    def test_empty(self):\n        self.assertTrue(self.bst.is_empty())\n        self.bst.put(0, 0)\n        self.assertFalse(self.bst.is_empty())\n\n    def test_size(self):\n        for i in range(10):\n            self.assertEqual(i, self.bst.size())\n            self.bst.put(str(i), i)\n\n        for i in range(10):\n            self.assertEqual(10, self.bst.size())\n            self.bst.put(str(i), i + 1)  # key already there: no change in size\n\n        for i in reversed(range(10)):\n            self.assertEqual(i + 1, self.bst.size())\n            self.bst.delete(str(i))\n\n        self.assertEqual(0, self.bst.size())\n\n    def test_floor_and_ceiling(self):\n        self.bst.put(0, 0)\n        self.bst.put(2, 2)\n        self.assertEqual(0, self.bst.floor(0))\n        self.assertEqual(0, self.bst.floor(1))\n        self.assertEqual(2, self.bst.floor(2))\n        self.assertEqual(2, self.bst.floor(3))\n        self.assertEqual(0, self.bst.ceiling(-1))\n        self.assertEqual(0, self.bst.ceiling(0))\n        self.assertEqual(2, self.bst.ceiling(1))\n        self.assertEqual(2, self.bst.ceiling(2))\n\n    def test_rank_select(self):\n        for i in range(0, 2 ** 8 + 2, 2):\n            self.bst.put(i, i)\n            self.assertEqual(0, self.bst.min())\n            self.assertEqual(i, self.bst.max())\n            self.assertEqual(i, self.bst.select(i // 2))\n            self.assertEqual(i // 2, self.bst.rank(i))\n\n    def test_exceptions(self):\n        with self.assertRaises(NoSuchElementException):\n            self.bst.min()\n        with self.assertRaises(NoSuchElementException):\n            self.bst.max()\n        with self.assertRaises(NoSuchElementException):\n            self.bst.floor(0)\n        self.bst.put(0, 0)\n        with self.assertRaises(NoSuchElementException):\n            self.bst.floor(-1)\n\n\nclass LargerBSTMethods(unittest.TestCase):\n    L = [1, 3, 6, 7, 10, 13, 16]\n\n    def setUp(self):\n        self.bst = BST()\n        for x in self.L:\n            self.bst.put(x, x)\n\n    def test_put_and_get(self):\n        st = self.bst\n        for x in st.keys():\n            self.assertEqual(st.get(x), x)\n        for x in st.keys():\n            st.put(x, st.get(x) - 1)\n        for x in st.keys():\n            self.assertEqual(st.get(x), x - 1)\n        self.assertIsNone(st.get(2))\n        st.put(2, 2)\n        self.assertEqual(2, st.get(2))\n\n    def test_keys(self):\n        i = 0\n        for x in self.bst.keys():\n            self.assertEqual(x, self.L[i])\n            i += 1\n\n    def test_min(self):\n        self.assertEqual(self.bst.min(), min(self.L))\n\n    def test_max(self):\n        self.assertEqual(self.bst.max(), max(self.L))\n\n    def test_delete_min(self):\n        self.bst.delete_min()\n        self.assertEqual(self.bst.min(), min(self.L[1:]))\n\n    def test_delete_max(self):\n        self.bst.delete_max()\n        self.assertEqual(self.bst.max(), max(self.L[:-1]))\n\n    def test_range(self):\n        R = [6, 7, 10, 13]\n        i = 0\n        for x in self.bst.range_keys(5, 13):\n            self.assertEqual(x, R[i])\n            i += 1\n\n\nclass HugeBSTMethods(unittest.TestCase):\n    def setUp(self):\n        random.seed(0)\n\n        self.L = random.sample(range(10 ** 6), 10 ** 4)\n        self.S = sorted(self.L)\n        self.bst = BST()\n        for x in self.L:\n            self.bst.put(x, x)\n\n    def test_put_and_get(self):\n        st = self.bst\n        for x in st.keys():\n            self.assertEqual(st.get(x), x)\n        for x in st.keys():\n            st.put(x, st.get(x) - 1)\n        for x in st.keys():\n            self.assertEqual(st.get(x), x - 1)\n\n    def test_keys(self):\n        i = 0\n        for x in self.bst.keys():\n            self.assertEqual(x, self.S[i])\n            i += 1\n\n    def test_min(self):\n        self.assertEqual(self.bst.min(), min(self.L))\n\n    def test_max(self):\n        self.assertEqual(self.bst.max(), max(self.L))\n\n    def test_delete_min(self):\n        self.bst.delete_min()\n        self.assertEqual(self.bst.min(), min(self.S[1:]))\n\n    def test_delete_max(self):\n        self.bst.delete_max()\n        self.assertEqual(self.bst.max(), max(self.S[:-1]))\n\n    def test_min_priority_queue(self):\n        i = 0\n        while not self.bst.is_empty():\n            self.assertEqual(self.S[i], self.bst.min())\n            self.bst.delete_min()\n            i += 1\n\n    def test_max_priority_queue(self):\n        i = len(self.S) - 1\n        while not self.bst.is_empty():\n            self.assertEqual(self.S[i], self.bst.max())\n            self.bst.delete_max()\n            i -= 1\n"
  },
  {
    "path": "tests/test_red_black_bst.py",
    "content": "import random\nimport unittest\n\nfrom itu.algs4.errors.errors import NoSuchElementException\nfrom itu.algs4.searching.red_black_bst import RedBlackBST\n\n\nclass TestRedBlackBSTMethods(unittest.TestCase):\n    def setUp(self):\n        self.st = RedBlackBST()\n\n    def test_empty(self):\n        self.assertTrue(self.st.is_empty())\n        self.st.put(\"spam\", 0)\n        self.assertFalse(self.st.is_empty())\n\n    def test_size(self):\n        for i in range(10):\n            self.assertEqual(i, self.st.size())\n            self.st.put(str(i), i)\n\n        for i in range(10):\n            self.assertEqual(10, self.st.size())\n            self.st.put(str(i), i + 1)  # key already there: no change in size\n\n        for i in reversed(range(10)):\n            self.assertEqual(i + 1, self.st.size())\n            self.st.delete(str(i))\n\n        self.assertEqual(0, self.st.size())\n\n    def test_rank_select(self):\n        for i in range(0, 2 ** 8 + 2, 2):\n            self.st.put(i, i)\n            self.assertEqual(0, self.st.min())\n            self.assertEqual(i, self.st.max())\n            self.assertEqual(i, self.st.select(i // 2))\n            self.assertEqual(i // 2, self.st.rank(i))\n\n    def test_floor_and_ceiling(self):\n        self.st.put(0, 0)\n        self.st.put(2, 2)\n        self.assertEqual(0, self.st.floor(0))\n        self.assertEqual(0, self.st.floor(1))\n        self.assertEqual(2, self.st.floor(2))\n        self.assertEqual(2, self.st.floor(3))\n        self.assertEqual(0, self.st.ceiling(-1))\n        self.assertEqual(0, self.st.ceiling(0))\n        self.assertEqual(2, self.st.ceiling(1))\n        self.assertEqual(2, self.st.ceiling(2))\n\n    def test_exceptions(self):\n        with self.assertRaises(NoSuchElementException):\n            self.st.min()\n        with self.assertRaises(NoSuchElementException):\n            self.st.max()\n        with self.assertRaises(NoSuchElementException):\n            self.st.floor(0)\n        with self.assertRaises(NoSuchElementException):\n            self.st.ceiling(0)\n        self.st.put(0, 0)\n        with self.assertRaises(NoSuchElementException):\n            self.st.floor(-1)\n        with self.assertRaises(NoSuchElementException):\n            self.st.ceiling(1)\n\n\nclass LargerRedBlackBSTMethods(unittest.TestCase):\n    L = [1, 3, 6, 7, 10, 13, 16]\n\n    def setUp(self):\n        self.st = RedBlackBST()\n        for x in self.L:\n            self.st.put(x, x)\n\n    def test_put_and_get(self):\n        st = self.st\n        for x in st.keys():\n            self.assertEqual(st.get(x), x)\n        for x in st.keys():\n            st.put(x, st.get(x) - 1)\n        for x in st.keys():\n            self.assertEqual(st.get(x), x - 1)\n        self.assertIsNone(st.get(2))\n        st.put(2, 2)\n        self.assertEqual(2, st.get(2))\n\n    def test_keys(self):\n        i = 0\n        for k in self.st.keys():\n            self.assertEqual(k, self.L[i])\n            i += 1\n\n    def test_min(self):\n        self.assertEqual(self.st.min(), min(self.L))\n\n    def test_max(self):\n        self.assertEqual(self.st.max(), max(self.L))\n\n    def test_delete_min(self):\n        self.st.delete_min()\n        self.assertEqual(self.st.min(), min(self.L[1:]))\n\n    def test_delete_max(self):\n        self.st.delete_max()\n        self.assertEqual(self.st.max(), max(self.L[:-1]))\n\n    def test_range(self):\n        T = [6, 7, 10, 13]\n        i = 0\n        for k in self.st.keys_range(5, 13):\n            self.assertEqual(k, T[i])\n            i += 1\n\n\nclass HugeRedBlackBSTMethods(unittest.TestCase):\n    def setUp(self):\n        random.seed(0)\n\n        self.L = random.sample(range(10 ** 6), 10 ** 4)\n        self.S = sorted(self.L)\n        self.st = RedBlackBST()\n        for x in self.L:\n            self.st.put(x, x)\n\n    def test_put_and_get(self):\n        st = self.st\n        for x in st.keys():\n            self.assertEqual(st.get(x), x)\n        for x in st.keys():\n            st.put(x, st.get(x) - 1)\n        for x in st.keys():\n            self.assertEqual(st.get(x), x - 1)\n\n    def test_keys(self):\n        i = 0\n        for k in self.st.keys():\n            self.assertEqual(k, self.S[i])\n            i += 1\n\n    def test_min(self):\n        self.assertEqual(self.st.min(), min(self.L))\n\n    def test_max(self):\n        self.assertEqual(self.st.max(), max(self.L))\n\n    def test_delete_min(self):\n        self.st.delete_min()\n        self.assertEqual(self.st.min(), min(self.S[1:]))\n\n    def test_delete_max(self):\n        self.st.delete_max()\n        self.assertEqual(self.st.max(), max(self.S[:-1]))\n\n    def test_min_priority_queue(self):\n        i = 0\n        while not self.st.is_empty():\n            self.assertEqual(self.S[i], self.st.min())\n            self.st.delete_min()\n            i += 1\n\n    def test_max_priority_queue(self):\n        i = len(self.S) - 1\n        while not self.st.is_empty():\n            self.assertEqual(self.S[i], self.st.max())\n            self.st.delete_max()\n            i -= 1\n\n    def test_flights(self):\n        self.st = RedBlackBST()\n        schedule = [\n            [\"09:00:00\", \"Chicago\"],\n            [\"09:00:03\", \"Phoenix\"],\n            [\"09:00:13\", \"Houston\"],\n            [\"09:00:59\", \"Chicago\"],\n            [\"09:01:10\", \"Houston\"],\n            [\"09:03:13\", \"Chicago\"],\n            [\"09:10:11\", \"Seattle\"],\n            [\"09:10:25\", \"Seattle\"],\n            [\"09:14:25\", \"Phoenix\"],\n            [\"09:19:32\", \"Chicago\"],\n            [\"09:19:46\", \"Chicago\"],\n            [\"09:21:05\", \"Chicago\"],\n            [\"09:22:43\", \"Seattle\"],\n            [\"09:22:54\", \"Seattle\"],\n            [\"09:25:52\", \"Chicago\"],\n            [\"09:35:21\", \"Chicago\"],\n            [\"09:36:14\", \"Seattle\"],\n            [\"09:37:44\", \"Phoenix\"],\n        ]\n        for time, city in schedule:\n            self.st.put(time, city)\n        for time, city in schedule:\n            self.assertEqual(city, self.st.get(time))\n        self.assertEqual(len(self.st.keys()), len(schedule))\n"
  },
  {
    "path": "tests/test_stack.py",
    "content": "import random\n\nimport pytest\n\nfrom itu.algs4.fundamentals.stack import FixedCapacityStack, ResizingArrayStack, Stack\n\n\n@pytest.mark.parametrize(\n    \"stack\",\n    [\n        FixedCapacityStack(0),\n        FixedCapacityStack(1),\n        FixedCapacityStack(7),\n        ResizingArrayStack(),\n        Stack(),\n    ],\n)\ndef test_is_empty(stack):\n    assert stack.is_empty()\n\n\n@pytest.mark.parametrize(\n    \"stack\",\n    [FixedCapacityStack(1), FixedCapacityStack(7), ResizingArrayStack(), Stack()],\n)\ndef test_push_pop_once(stack):\n    stack.push(83)\n    assert not stack.is_empty()\n    assert stack.pop() == 83\n    assert stack.is_empty()\n\n\n@pytest.mark.parametrize(\"capacity\", list(range(10)))\ndef test_error_beyond_capacity(capacity):\n    stack = FixedCapacityStack(capacity)\n    for i in range(capacity):\n        stack.push(i)\n    try:\n        stack.push(99)\n        assert False\n    except IndexError:\n        pass\n\n\n@pytest.mark.parametrize(\n    \"stack\", [FixedCapacityStack(100), ResizingArrayStack(), Stack()]\n)\n@pytest.mark.parametrize(\"seed\", [3928, 1928, 39211, 419901])\ndef test_random_pushpop_sequence(stack, seed):\n    random.seed(seed)\n    L = list(range(100))\n    random.shuffle(L)\n    for i in L:\n        stack.push(i)\n    L.reverse()\n    for i in L:\n        assert stack.pop() == i\n    assert stack.is_empty()\n"
  },
  {
    "path": "tests/test_symbol_tables.py",
    "content": "# import random\n#\nimport pytest\n\nfrom itu.algs4.searching.binary_search_st import BinarySearchST\nfrom itu.algs4.searching.bst import BST\nfrom itu.algs4.searching.linear_probing_hst import LinearProbingHashST\nfrom itu.algs4.searching.red_black_bst import RedBlackBST\nfrom itu.algs4.searching.seperate_chaining_hst import SeparateChainingHashST\nfrom itu.algs4.searching.sequential_search_st import SequentialSearchST\nfrom itu.algs4.searching.st import ST\n\nST_IMPLEMENTATIONS = [\n    BinarySearchST,\n    BST,\n    LinearProbingHashST,\n    RedBlackBST,\n    SeparateChainingHashST,\n    SequentialSearchST,\n    ST,\n]\n\n\n@pytest.mark.parametrize(\n    \"st\",\n    [constructor() for constructor in ST_IMPLEMENTATIONS],\n)\ndef test_is_empty(st):\n    assert st.is_empty()\n\n\n@pytest.mark.parametrize(\n    \"st\",\n    [constructor() for constructor in ST_IMPLEMENTATIONS],\n)\ndef test_delete(st):\n    st.put(\"key1\", \"val1\")\n    st.put(\"key2\", \"val2\")\n    st.put(\"key3\", \"val3\")\n    st.delete(\"key3\")\n    st.delete(\"key2\")\n    st.delete(\"key1\")\n    assert st.is_empty()\n\n\n@pytest.mark.parametrize(\n    \"st\",\n    [constructor() for constructor in ST_IMPLEMENTATIONS],\n)\ndef old_tests(st):\n    st.put(\"one\", 1)\n    assert [\"one\"] == list(st.keys())\n    assert st.get(\"one\") == 1\n    assert st.contains(\"one\")\n    st.delete(\"one\")\n    assert st.is_empty()\n    st.put(\"aaa\", 1)\n    st.put(\"bbb\", 2)\n    st.put(\"ccc\", 3)\n    st.put(\"ddd\", 4)\n    st.put(\"eee\", 5)\n    if st.ceiling:\n        assert st.ceiling(\"ccc\") == \"ccc\"\n        assert st.ceiling(\"dad\") == \"ddd\"\n        assert st.floor(\"ccc\") == \"ccc\"\n        assert st.floor(\"dad\") == \"ccc\"\n    for k in st:\n        assert k in st.keys()\n    assert st.min() == \"aaa\"\n    assert st.max() == \"eee\"\n"
  }
]